code
stringlengths
2
1.05M
/* * grunt-tankipas * https://github.com/Leny/grunt-tankipas * * Copyright (c) 2014 Leny * Licensed under the MIT license. */ "use strict"; var chalk, error, spinner, tankipas; tankipas = require("tankipas"); chalk = require("chalk"); error = chalk.bold.red; (spinner = require("simple-spinner")).change_sequence(["◓", "◑", "◒", "◐"]); module.exports = function(grunt) { var tankipasTask; tankipasTask = function() { var fNext, oOptions; fNext = this.async(); oOptions = this.options({ system: null, gap: 120, user: null, branch: null, commit: null, raw: false }); spinner.start(50); return tankipas(process.cwd(), oOptions, function(oError, iTotal) { var iHours, iMinutes, sUserString; spinner.stop(); if (oError) { grunt.log.error(oError); fNext(false); } if (oOptions.raw) { grunt.log.writeln(iTotal); } else { iTotal /= 1000; iMinutes = (iMinutes = Math.floor(iTotal / 60)) > 60 ? iMinutes % 60 : iMinutes; iHours = Math.floor(iTotal / 3600); sUserString = oOptions.user ? " (for " + (chalk.cyan(oOptions.user)) + ")" : ""; grunt.log.writeln("Time spent on project" + sUserString + ": ±" + (chalk.yellow(iHours)) + " hours & " + (chalk.yellow(iMinutes)) + " minutes."); } return fNext(); }); }; if (grunt.config.data.tankipas) { return grunt.registerMultiTask("tankipas", "Compute approximate development time spent on a project, using logs from version control system.", tankipasTask); } else { return grunt.registerTask("tankipas", "Compute approximate development time spent on a project, using logs from version control system.", tankipasTask); } };
module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '../', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], files: [ 'node_modules/jquery/dist/jquery.js', 'node_modules/angular/angular.js', 'node_modules/angular-sanitize/angular-sanitize.js', 'node_modules/angular-ui-bootstrap/ui-bootstrap-tpls.js', 'node_modules/angular-translate/dist/angular-translate.js', 'node_modules/angular-translate-loader-static-files/angular-translate-loader-static-files.js', 'node_modules/angular-mocks/angular-mocks.js', 'node_modules/openlayers/build/ol-custom.js', 'src/anol/anol.js', 'src/anol/helper.js', 'src/anol/layer.js', 'src/anol/layer/basewms.js', 'src/anol/layer/feature.js', 'src/anol/layer/staticgeojson.js', 'src/anol/**/*.js', 'src/modules/module.js', 'src/modules/**/module.js', 'src/modules/**/*.js', 'test/spec/**/*.js', 'src/modules/**/*.html' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { "src/modules/**/*.html": ["ng-html2js"] }, ngHtml2JsPreprocessor: { // the name of the Angular module to create moduleName: "mocked-templates" }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Start these browsers, currently installed from us: // - Chrome // - Firefox // - Safari (only Mac) // - PhantomJS browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true }); };
// test: indent_only const foo = 1 + 2 ; const foo = [1, 2]; const foo = [ 1, 2]; const foo = {a, b}; const foo = { a, b}; someMethod(foo, [ 0, 1, 2,], bar); someMethod( foo, [0, 1, 2,], bar); someMethod(foo, [ 0, 1, 2, ], bar); someMethod( foo, [ 1, 2],); someMethod( foo, [1, 2], ); someMethod(foo, { a: 1, b: 2,}, bar); someMethod( foo, {a: 1, b: 2,}, bar); someMethod(foo, { a: 1, b: 2 }, bar); someMethod( foo, { a: 1, b: 2},); someMethod( foo, {a: 1, b: 2}, ); someMethod(a => a*2 ); someMethod(a => { a*2} ); foo() .bar(a => a*2); foo().bar(a => a*2); foo = function() { }; foo = function() { }; switch (foo) { case 1: return b;} switch (foo) { case 1: return b;} class Foo { } class Foo { bar( ) {} } class Foo { bar() { } } if (x) { statement; more; }
/* * Snapshot multiple pages using arrays. * * Use an array to snapshot specific urls. * Use per-page selectors. * Use per-page output paths. * Remove all script tags from output. * Use javascript arrays. */ var path = require("path"); var util = require("util"); var assert = require("assert"); var htmlSnapshots = require("html-snapshots"); // a data structure with snapshot input var sites = [ { label: "html5rocks", url: "http://html5rocks.com", selector: ".latest-articles" }, { label: "updates.html5rocks", url: "http://updates.html5rocks.com", selector: ".articles-list" } ]; htmlSnapshots.run({ // input source is the array of urls to snapshot input: "array", source: sites.map(function(site) { return site.url; }), // setup and manage the output outputDir: path.join(__dirname, "./tmp"), outputDirClean: true, // per url output paths, { url: outputpath [, url: outputpath] } outputPath: sites.reduce(function(prev, curr) { prev[curr.url] = curr.label; // use the label to differentiate '/index.html' from both sites return prev; }, {}), // per url selectors, { url: selector [, url: selector] } selector: sites.reduce(function(prev, curr) { prev[curr.url] = curr.selector; return prev; }, {}), // remove all script tags from the output snapshotScript: { script: "removeScripts" } }, function(err, completed) { console.log("completed snapshots:"); console.log(util.inspect(completed)); // throw if there was an error assert.ifError(err); });
/*! * Office for Experience Design v1.0.0 (http://ing-experience-design.com/) * Copyright 2016 ING, Office for Experience Design * Licensed under MIT (https://spdx.org/licenses/MIT) */
var async = require('async'), fs = require('graceful-fs'), path = require('path'), colors = require('colors'), swig = require('swig'), spawn = require('child_process').spawn, util = require('../../util'), file = util.file2, commitMessage = require('./util').commitMessage; // http://git-scm.com/docs/git-clone var rRepo = /(:|\/)([^\/]+)\/([^\/]+)\.git\/?$/; module.exports = function(args, callback){ var baseDir = hexo.base_dir, deployDir = path.join(baseDir, '.deploy'), publicDir = hexo.public_dir; if (!args.repo && !args.repository){ var help = ''; help += 'You should configure deployment settings in _config.yml first!\n\n'; help += 'Example:\n'; help += ' deploy:\n'; help += ' type: github\n'; help += ' repo: <repository url>\n'; help += ' branch: [branch]\n'; help += ' message: [message]\n\n'; help += 'For more help, you can check the docs: ' + 'http://hexo.io/docs/deployment.html'.underline; console.log(help); return callback(); } var url = args.repo || args.repository; if (!rRepo.test(url)){ hexo.log.e(url + ' is not a valid repository URL!'); return callback(); } var branch = args.branch; if (!branch){ var match = url.match(rRepo), username = match[2], repo = match[3], rGh = new RegExp('^' + username + '\\.github\\.[io|com]', 'i'); // https://help.github.com/articles/user-organization-and-project-pages if (repo.match(rGh)){ branch = 'master'; } else { branch = 'gh-pages'; } } var run = function(command, args, callback){ var cp = spawn(command, args, {cwd: deployDir}); cp.stdout.on('data', function(data){ process.stdout.write(data); }); cp.stderr.on('data', function(data){ process.stderr.write(data); }); cp.on('close', callback); }; async.series([ // Set up function(next){ fs.exists(deployDir, function(exist){ if (exist && !args.setup) return next(); hexo.log.i('Setting up GitHub deployment...'); var commands = [ ['init'], ['add', '-A', '.'], ['commit', '-m', 'First commit'] ]; if (branch !== 'master') commands.push(['branch', '-M', branch]); commands.push(['remote', 'add', 'github', url]); file.writeFile(path.join(deployDir, 'placeholder'), '', function(err){ if (err) callback(err); async.eachSeries(commands, function(item, next){ run('git', item, function(code){ if (code === 0) next(); }); }, function(){ if (!args.setup) next(); }); }); }); }, function(next){ hexo.log.i('Clearing .deploy folder...'); file.emptyDir(deployDir, next); }, function(next){ hexo.log.i('Copying files from public folder...'); file.copyDir(publicDir, deployDir, next); }, function(next){ var commands = [ ['add', '-A'], ['commit', '-m', commitMessage(args)], ['push', '-u', 'github', branch, '--force'] ]; async.eachSeries(commands, function(item, next){ run('git', item, function(){ next(); }); }, next); } ], callback); };
// config.pro.spec.js import config from '../../../src/constants/config.pro' describe('Config PRO constants', function () { test('exist', () => { expect(config).toMatchSnapshot() }) })
const DrawCard = require('../../drawcard.js'); class VaesTolorro extends DrawCard { setupCardAbilities(ability) { this.interrupt({ when: { onCharacterKilled: event => event.card.getPower() >= 1 }, cost: ability.costs.kneelSelf(), handler: context => { let pendingCard = context.event.card; let power = pendingCard.getPower() >= 2 && pendingCard.getStrength() === 0 ? 2 : 1; pendingCard.modifyPower(-power); this.modifyPower(power); this.game.addMessage('{0} kneels {1} to move {2} power from {3} to {1}', this.controller, this, power, pendingCard); } }); } } VaesTolorro.code = '04074'; module.exports = VaesTolorro;
ga(function(){var e,t=ga.getAll();t&&t.length&&(e=t[0].get("clientId"),document.getElementById("clid").value=e)});
//~ name a361 alert(a361); //~ component a362.js
const fs = require("fs"); module.exports = function (config) { var mod = require("./mod.js")(config); config[mod.name] = mod; function tryPatchComponent(componentName) { if (config[componentName] && fs.existsSync(`${__dirname}/${componentName}.js`)) { require(`./${componentName}`)(config, mod); } } tryPatchComponent("engine"); tryPatchComponent("backend"); tryPatchComponent("driver"); tryPatchComponent("cli"); tryPatchComponent("cronjobs"); };
/*jshint quotmark: false*/ 'use strict'; var Blueprint = require('../models/blueprint'); var Task = require('../models/task'); var parseOptions = require('../utilities/parse-options'); var merge = require('lodash-node/modern/objects/merge'); module.exports = Task.extend({ run: function(options) { var blueprint = Blueprint.lookup(options.args[0], { paths: this.project.blueprintLookupPaths() }); var entity = { name: options.args[1], options: parseOptions(options.args.slice(2)) }; var installOptions = { target: this.project.root, entity: entity, ui: this.ui, analytics: this.analytics, project: this.project }; installOptions = merge(installOptions, options || {}); return blueprint.install(installOptions); } });
angular.module('app') .controller('ProgressController', ['$scope', function ($scope) { $scope.percent = 45; $scope.setPercent = function(p) { $scope.percent = p; } }])
containerRemoveSchemas = new SimpleSchema({ force: { type: Boolean, optional:true, label: "Force" }, link: { type: Boolean, optional:true, label: "Link" }, v: { type: Boolean, optional:true, label: "Volumes" } ,id: { type: String, autoform: { type: 'hidden', label:false } } ,host: { type: String, autoform: { type: 'hidden', label:false } } }); if (Meteor.isClient){ AutoForm.hooks({ containerRemoveForm: { after: { 'method': formNotifier('rm','containers')} }}); }
'use strict'; var should = require('should'), request = require('supertest'), path = require('path'), mongoose = require('mongoose'), User = mongoose.model('User'), Picture = mongoose.model('Picture'), express = require(path.resolve('./config/lib/express')); /** * Globals */ var app, agent, credentials, user, picture; /** * Picture routes tests */ describe('Picture CRUD tests', function () { before(function (done) { // Get application app = express.init(mongoose); agent = request.agent(app); done(); }); beforeEach(function (done) { // Create user credentials credentials = { username: 'username', password: '[email protected]$Aw3$0m3' }; // Create a new user user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: '[email protected]', username: credentials.username, password: credentials.password, provider: 'local' }); // Save a user to the test db and create new picture user.save(function () { picture = { title: 'Picture Title', content: 'Picture Content' }; done(); }); }); it('should be able to save an picture if logged in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new picture agent.post('/api/pictures') .send(picture) .expect(200) .end(function (pictureSaveErr, pictureSaveRes) { // Handle picture save error if (pictureSaveErr) { return done(pictureSaveErr); } // Get a list of pictures agent.get('/api/pictures') .end(function (picturesGetErr, picturesGetRes) { // Handle picture save error if (picturesGetErr) { return done(picturesGetErr); } // Get pictures list var pictures = picturesGetRes.body; // Set assertions (pictures[0].user._id).should.equal(userId); (pictures[0].title).should.match('Picture Title'); // Call the assertion callback done(); }); }); }); }); it('should not be able to save an picture if not logged in', function (done) { agent.post('/api/pictures') .send(picture) .expect(403) .end(function (pictureSaveErr, pictureSaveRes) { // Call the assertion callback done(pictureSaveErr); }); }); it('should not be able to save an picture if no title is provided', function (done) { // Invalidate title field picture.title = ''; agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new picture agent.post('/api/pictures') .send(picture) .expect(400) .end(function (pictureSaveErr, pictureSaveRes) { // Set message assertion (pictureSaveRes.body.message).should.match('Title cannot be blank'); // Handle picture save error done(pictureSaveErr); }); }); }); it('should be able to update an picture if signed in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new picture agent.post('/api/pictures') .send(picture) .expect(200) .end(function (pictureSaveErr, pictureSaveRes) { // Handle picture save error if (pictureSaveErr) { return done(pictureSaveErr); } // Update picture title picture.title = 'WHY YOU GOTTA BE SO MEAN?'; // Update an existing picture agent.put('/api/pictures/' + pictureSaveRes.body._id) .send(picture) .expect(200) .end(function (pictureUpdateErr, pictureUpdateRes) { // Handle picture update error if (pictureUpdateErr) { return done(pictureUpdateErr); } // Set assertions (pictureUpdateRes.body._id).should.equal(pictureSaveRes.body._id); (pictureUpdateRes.body.title).should.match('WHY YOU GOTTA BE SO MEAN?'); // Call the assertion callback done(); }); }); }); }); it('should be able to get a list of pictures if not signed in', function (done) { // Create new picture model instance var pictureObj = new Picture(picture); // Save the picture pictureObj.save(function () { // Request pictures request(app).get('/api/pictures') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Array).and.have.lengthOf(1); // Call the assertion callback done(); }); }); }); it('should be able to get a single picture if not signed in', function (done) { // Create new picture model instance var pictureObj = new Picture(picture); // Save the picture pictureObj.save(function () { request(app).get('/api/pictures/' + pictureObj._id) .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('title', picture.title); // Call the assertion callback done(); }); }); }); it('should return proper error for single picture with an invalid Id, if not signed in', function (done) { // test is not a valid mongoose Id request(app).get('/api/pictures/test') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('message', 'Picture is invalid'); // Call the assertion callback done(); }); }); it('should return proper error for single picture which doesnt exist, if not signed in', function (done) { // This is a valid mongoose Id but a non-existent picture request(app).get('/api/pictures/559e9cd815f80b4c256a8f41') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('message', 'No picture with that identifier has been found'); // Call the assertion callback done(); }); }); it('should be able to delete an picture if signed in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new picture agent.post('/api/pictures') .send(picture) .expect(200) .end(function (pictureSaveErr, pictureSaveRes) { // Handle picture save error if (pictureSaveErr) { return done(pictureSaveErr); } // Delete an existing picture agent.delete('/api/pictures/' + pictureSaveRes.body._id) .send(picture) .expect(200) .end(function (pictureDeleteErr, pictureDeleteRes) { // Handle picture error error if (pictureDeleteErr) { return done(pictureDeleteErr); } // Set assertions (pictureDeleteRes.body._id).should.equal(pictureSaveRes.body._id); // Call the assertion callback done(); }); }); }); }); it('should not be able to delete an picture if not signed in', function (done) { // Set picture user picture.user = user; // Create new picture model instance var pictureObj = new Picture(picture); // Save the picture pictureObj.save(function () { // Try deleting picture request(app).delete('/api/pictures/' + pictureObj._id) .expect(403) .end(function (pictureDeleteErr, pictureDeleteRes) { // Set message assertion (pictureDeleteRes.body.message).should.match('User is not authorized'); // Handle picture error error done(pictureDeleteErr); }); }); }); it('should be able to get a single picture that has an orphaned user reference', function (done) { // Create orphan user creds var _creds = { username: 'orphan', password: '[email protected]$Aw3$0m3' }; // Create orphan user var _orphan = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: '[email protected]', username: _creds.username, password: _creds.password, provider: 'local' }); _orphan.save(function (err, orphan) { // Handle save error if (err) { return done(err); } agent.post('/api/auth/signin') .send(_creds) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var orphanId = orphan._id; // Save a new picture agent.post('/api/pictures') .send(picture) .expect(200) .end(function (pictureSaveErr, pictureSaveRes) { // Handle picture save error if (pictureSaveErr) { return done(pictureSaveErr); } // Set assertions on new picture (pictureSaveRes.body.title).should.equal(picture.title); should.exist(pictureSaveRes.body.user); should.equal(pictureSaveRes.body.user._id, orphanId); // force the picture to have an orphaned user reference orphan.remove(function () { // now signin with valid user agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (err, res) { // Handle signin error if (err) { return done(err); } // Get the picture agent.get('/api/pictures/' + pictureSaveRes.body._id) .expect(200) .end(function (pictureInfoErr, pictureInfoRes) { // Handle picture error if (pictureInfoErr) { return done(pictureInfoErr); } // Set assertions (pictureInfoRes.body._id).should.equal(pictureSaveRes.body._id); (pictureInfoRes.body.title).should.equal(picture.title); should.equal(pictureInfoRes.body.user, undefined); // Call the assertion callback done(); }); }); }); }); }); }); }); it('should be able to get a single picture if signed in and verify the custom "isCurrentUserOwner" field is set to "true"', function (done) { // Create new picture model instance picture.user = user; var pictureObj = new Picture(picture); // Save the picture pictureObj.save(function () { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new picture agent.post('/api/pictures') .send(picture) .expect(200) .end(function (pictureSaveErr, pictureSaveRes) { // Handle picture save error if (pictureSaveErr) { return done(pictureSaveErr); } // Get the picture agent.get('/api/pictures/' + pictureSaveRes.body._id) .expect(200) .end(function (pictureInfoErr, pictureInfoRes) { // Handle picture error if (pictureInfoErr) { return done(pictureInfoErr); } // Set assertions (pictureInfoRes.body._id).should.equal(pictureSaveRes.body._id); (pictureInfoRes.body.title).should.equal(picture.title); // Assert that the "isCurrentUserOwner" field is set to true since the current User created it (pictureInfoRes.body.isCurrentUserOwner).should.equal(true); // Call the assertion callback done(); }); }); }); }); }); it('should be able to get a single picture if not signed in and verify the custom "isCurrentUserOwner" field is set to "false"', function (done) { // Create new picture model instance var pictureObj = new Picture(picture); // Save the picture pictureObj.save(function () { request(app).get('/api/pictures/' + pictureObj._id) .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('title', picture.title); // Assert the custom field "isCurrentUserOwner" is set to false for the un-authenticated User res.body.should.be.instanceof(Object).and.have.property('isCurrentUserOwner', false); // Call the assertion callback done(); }); }); }); it('should be able to get single picture, that a different user created, if logged in & verify the "isCurrentUserOwner" field is set to "false"', function (done) { // Create temporary user creds var _creds = { username: 'temp', password: '[email protected]$Aw3$0m3' }; // Create temporary user var _user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: '[email protected]', username: _creds.username, password: _creds.password, provider: 'local' }); _user.save(function (err, _user) { // Handle save error if (err) { return done(err); } // Sign in with the user that will create the Picture agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user._id; // Save a new picture agent.post('/api/pictures') .send(picture) .expect(200) .end(function (pictureSaveErr, pictureSaveRes) { // Handle picture save error if (pictureSaveErr) { return done(pictureSaveErr); } // Set assertions on new picture (pictureSaveRes.body.title).should.equal(picture.title); should.exist(pictureSaveRes.body.user); should.equal(pictureSaveRes.body.user._id, userId); // now signin with the temporary user agent.post('/api/auth/signin') .send(_creds) .expect(200) .end(function (err, res) { // Handle signin error if (err) { return done(err); } // Get the picture agent.get('/api/pictures/' + pictureSaveRes.body._id) .expect(200) .end(function (pictureInfoErr, pictureInfoRes) { // Handle picture error if (pictureInfoErr) { return done(pictureInfoErr); } // Set assertions (pictureInfoRes.body._id).should.equal(pictureSaveRes.body._id); (pictureInfoRes.body.title).should.equal(picture.title); // Assert that the custom field "isCurrentUserOwner" is set to false since the current User didn't create it (pictureInfoRes.body.isCurrentUserOwner).should.equal(false); // Call the assertion callback done(); }); }); }); }); }); }); afterEach(function (done) { User.remove().exec(function () { Picture.remove().exec(done); }); }); });
app.controller('DashboardController',function($scope,$http,Article){ //Pagination configuration $scope.maxSize = 5; $scope.numPerPage = 5; $scope.currentPage = '1'; $scope.isEdit = false; $scope.isError= false; $scope.newarticle = {}; // Edit/New panel model $scope.curArticle = {}; // Currently selected article model $scope.errors = []; //Load all articles. Article.query(function(data){ $scope.articles = data; },function(error){ console.log(error); alert('Loading data failed.'); }); //Shows validation errors function errorHandler(error){ $scope.isError=true; //Show validator error angular.forEach(error.data,function(key,value){ $scope.errors.push(value + ': ' + key); }); } //Open New panel $scope.newArticle = function(article){ $scope.isEdit=true; $scope.isError=false; //Initialize with Article resource $scope.newarticle = new Article(); }; //Open Edit panel with data on edit button click $scope.editArticle = function(article){ $scope.isEdit=true; $scope.isError=false; // Store selected data for future use $scope.curArticle = article; //Copy data to panel $scope.newarticle = angular.copy(article); }; //Update and New article $scope.addArticle = function(article){ //TODO error handling on requests //Check if update or new if($scope.curArticle.id){ //Send put resource request article.$update(function(data){ // Update values to selected article angular.extend($scope.curArticle,$scope.curArticle,data); //Hide edit/new panel $scope.isEdit = false; },errorHandler); }else{ //Send post resource request article.$save(function(data){ //Add newly add article to articles json $scope.articles.push(data); //Hide edit/new panel $scope.isEdit = false; },errorHandler); } //Remove old values //$scope.newarticle = new Article(); }; //Delete button $scope.deleteArticle = function(article){ if(confirm('Are you sure ?')){ article.$delete(function(data){ alert(data.msg); //Get selected article index then remove from articles json var curIndex = $scope.articles.indexOf(article); $scope.articles.splice(curIndex,1); },function(error){ alert('Item not deleted'); console.log(error); }); } }; //Cancel panel button $scope.cancelArticle = function(article){ $scope.isEdit=false; $scope.isError=false; //Remove old values $scope.newarticle= new Article(); }; });
/* google-paper.js */ 'use strict'; navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; var RAD_2_DEG = 180/Math.PI; function moving_average(period) { var nums = []; return function(num) { nums.push(num); if (nums.length > period) nums.splice(0,1); var sum = 0; for (var i in nums) sum += nums[i]; var n = period; if (nums.length < period) n = nums.length; return(sum/n); } } var GP = GP || {}; GP.PaperTracker = function(options){ this.options = options || {}; this.video; this.canvas; this.context; this.camDirection = 'front'; // back this.imageData; this.detector; this.posit; this.markers; this.init(options); }; GP.PaperTracker.prototype.init = function(options){ this.video = document.getElementById('video'); this.canvas = document.getElementById('video-canvas'); this.context = this.canvas.getContext('2d'); this.canvas.width = parseInt(this.canvas.style.width); this.canvas.height = parseInt(this.canvas.style.height); this.trackingInfo = { lastTrackTime: 0, haveTracking: false, neverTracked: true, translation: [0,0,0], orientation: [0,0,0], rotation: [0,0,0] }; this.detector = new AR.Detector(); this.posit = new POS.Posit(this.options.modelSize, this.canvas.width); }; GP.PaperTracker.prototype.postInit = function(){ var vid = this.video; navigator.getUserMedia({video:true}, function (stream){ if (window.webkitURL) { vid.src = window.webkitURL.createObjectURL(stream); } else if (vid.mozSrcObject !== undefined) { vid.mozSrcObject = stream; } else { vid.src = stream; } }, function(error){ console.log('stream not found'); } ); }; GP.PaperTracker.prototype.snapshot = function(){ this.context.drawImage(this.video, 0, 0, this.canvas.width, this.canvas.height); this.imageData = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height); }; GP.PaperTracker.prototype.detect = function(){ var markers = this.detector.detect(this.imageData); this.markers = markers; return markers; }; GP.PaperTracker.prototype.process = function(){ if (this.video.readyState === this.video.HAVE_ENOUGH_DATA){ this.snapshot(); this.detect(); this.drawCorners(); return true; } return false; }; GP.PaperTracker.prototype.drawCorners = function(){ var corners, corner, i, j; this.context.lineWidth = 3; for (i = 0; i < this.markers.length; ++ i){ corners = this.markers[i].corners; this.context.strokeStyle = "red"; this.context.beginPath(); for (j = 0; j < corners.length; ++ j){ corner = corners[j]; this.context.moveTo(corner.x, corner.y); corner = corners[(j + 1) % corners.length]; this.context.lineTo(corner.x, corner.y); } this.context.stroke(); this.context.closePath(); this.context.strokeStyle = "blue"; this.context.strokeRect(corners[0].x - 2, corners[0].y - 2, 4, 4); } }; GP.PaperTracker.prototype.updateTracking = function(){ var corners, corner, pose, i; if (this.markers.length == 0) { this.trackingInfo.haveTracking = false; return false; } this.trackingInfo.neverTracked = false; this.trackingInfo.haveTracking = true; corners = this.markers[0].corners; for (i = 0; i < corners.length; ++ i){ corner = corners[i]; corner.x = corner.x - (this.canvas.width / 2); corner.y = (this.canvas.height / 2) - corner.y; } pose = this.posit.pose(corners); var rotation = pose.bestRotation; var translation = pose.bestTranslation; this.trackingInfo.translation = translation; this.trackingInfo.rotation = rotation; return this.trackingInfo; };
'use strict'; /* jasmine specs for services go here */ describe('base', function() { beforeEach(function(){ module('d3-uml-modeler.base'); module('d3-uml-modeler.uml-abstract-factory'); module('d3-uml-modeler.constants'); module('d3-uml-modeler.notifications'); }); describe('BaseModelElement', function() { it('T1: should contain a GUID and an empty children hash', inject(["BaseModelElement", function($BaseModelElement) { var model = new $BaseModelElement(); expect(model.GUID).not.toBe(""); expect(model.count).toBe(0); expect(_.isEmpty(model.children)).toBe(true); }])); it('T2: should contain 2 children after a addElement call', inject(["BaseModelElement", function($BaseModelElement) { var model = new $BaseModelElement(); //add 2 models to it. var child1 = new $BaseModelElement(); var child2 = new $BaseModelElement(); model.addElement(child1); model.addElement(child2); //non empty children expect(_.isEmpty(model.children)).toBe(false); expect(model.count).toBe(2); }])); it("T3: should remove elements by passing them or their GUID to removeElement", inject(["BaseModelElement", function($BaseModelElement) { var model = new $BaseModelElement(); //add 2 models to it. var child1 = new $BaseModelElement(); var child2 = new $BaseModelElement(); var child3 = new $BaseModelElement(); var child4 = new $BaseModelElement(); //add some childs model.addElement(child1); model.addElement(child2); model.addElement(child3); model.addElement(child4); //remove a child by passing it to removeElement model.removeElement(child2); //remove a child by passing its GUID to removeElement model.removeElement(child3.GUID); //children count expect(model.count).toBe(2); //test remaining children. expect(model.children[child1.GUID]).toBe(child1); expect(model.children[child2.GUID]).toBe(undefined); expect(model.children[child3.GUID]).toBe(undefined); expect(model.children[child4.GUID]).toBe(child4); }])); it('T4: should contain 3 children after a removeElement call', inject(["BaseModelElement", function($BaseModelElement) { var model = new $BaseModelElement(); //add 2 models to it. var child1 = new $BaseModelElement(); var child2 = new $BaseModelElement(); var child3 = new $BaseModelElement(); var child4 = new $BaseModelElement(); //add some childs model.addElement(child1); model.addElement(child2); model.addElement(child3); model.addElement(child4); //children count expect(model.count).toBe(4); //remove a child model.removeElement(child2); //children count expect(model.count).toBe(3); }])); }); //EventDispatcher describe('EventDispatcher', function(){ it('T5: should contain an empty listeners hash', inject(["EventDispatcher", function(EventDispatcher) { var eventDispatcher = new EventDispatcher(); expect(_.isEmpty(eventDispatcher._listeners)).toBe(true); }])); it('T6: should add and remove listeners', inject(["EventDispatcher", function(EventDispatcher) { var eventDispatcher = new EventDispatcher(); var anAwesomeFunction = function() { //my brilliant code here. console.log("T6: my brilliant code is being executed"); }; eventDispatcher.addEventListener("an.awesome.event", anAwesomeFunction); expect(eventDispatcher.hasListeners()).toBeTruthy(); //remove a listener eventDispatcher.removeEventListener("an.awesome.event", anAwesomeFunction); //check if th event has been removed expect(eventDispatcher.hasListener("an.awesome.event")).toBeFalsy(); expect(eventDispatcher.hasListeners()).toBe(false); var args = ["lol", "cool", "mdr"]; var params = [].concat(args.splice(1, args.length)); expect(params).toContain("cool"); expect(params).toContain("mdr"); expect(params).not.toContain("lol"); spyOn(console, "warn"); expect(function(){eventDispatcher.dispatchEvent("kool");}).not.toThrow(); expect(console.warn).toHaveBeenCalled(); expect(console.warn).toHaveBeenCalledWith("no such registered event : kool"); }])); }); describe('UmlController', function() { beforeEach(function(){ module('d3-uml-modeler.base'); module('d3-uml-modeler.notifications'); module('d3-uml-modeler.underscore'); }); it('T7: should contain a notifications list', inject([ "$rootScope", "_", "Notifications", "UmlController", function($rootScope, _, Notifications, UmlController) { var $scope = $rootScope.$new(); var ctrlFactory = new UmlController($scope, _, Notifications); expect(ctrlFactory.notifications).toBeDefined(); } ])); }); describe('Lodash Service:', function() { beforeEach(module('d3-uml-modeler.underscore')); it('T8: should get an instance of the underscore factory', inject(function(_) { expect(_).toBeDefined(); })); }); describe('Uml Model Abstract Factory', function() { beforeEach(function(){ module('d3-uml-modeler.underscore'); module('d3-uml-modeler.uml-abstract-factory'); }); it('T9: should contain a notifications list', inject(["UmlModelAbstractFactory", "_", function(UmlModelAbstractFactory, _) { expect(UmlModelAbstractFactory).toBeDefined(); expect(typeof UmlModelAbstractFactory).toBe("object"); expect(typeof UmlModelAbstractFactory.createUmlModelElement).toBe("function"); expect(typeof UmlModelAbstractFactory.registerUmlModelElementClass).toBe("function"); } ])); it('T10: should contain a notifications list', inject(["UmlModelAbstractFactory", "Constants", "_", function(UmlModelAbstractFactory, Constants, _) { Constants.ELEMENT_TYPES_TO_NAMES["car"] = "Car"; Constants.ELEMENT_TYPES_TO_NAMES["bicycle"] = "Bicycle"; var CarClass = Class.extend({ name: "", color: "", brand: "" }); var BicycleClass = Class.extend({ color: "", type: "" }); expect(typeof CarClass).toBe('function'); expect(typeof BicycleClass).toBe('function'); UmlModelAbstractFactory.registerUmlModelElementClass("car", CarClass); UmlModelAbstractFactory.registerUmlModelElementClass("bicycle", BicycleClass); expect(function(){ UmlModelAbstractFactory.registerUmlModelElementClass("truck", {}); }).toThrow(); var modelCar = UmlModelAbstractFactory.createUmlModelElement("car", {name: "peugeot"}); expect(modelCar).toBeDefined(); expect(typeof modelCar).toBe("object"); expect(modelCar.GUID).toBeUndefined(); expect(modelCar.name).toBe("peugeot"); var modelBicycle = UmlModelAbstractFactory.createUmlModelElement("bicycle", {name: "BTwin"}); expect(modelBicycle).toBeDefined(); expect(typeof modelBicycle).toBe("object"); expect(modelBicycle.GUID).toBeUndefined(); expect(modelBicycle.name).toBe("BTwin"); //creating an object without passing arguments //expect to throw expect(UmlModelAbstractFactory.createUmlModelElement).toThrow("type not found : undefined"); //creating an object without passing options //expect to work var newCar = UmlModelAbstractFactory.createUmlModelElement("car"); expect(newCar).toBeDefined(); expect(typeof newCar).toBe("object"); expect(newCar.GUID).toBeUndefined(); expect(newCar.name).toBe(""); UmlModelAbstractFactory.unregisterUmlModelElementClass("bicycle", BicycleClass); expect(_.isEmpty(UmlModelAbstractFactory.types)).toBe(false); UmlModelAbstractFactory.unregisterUmlModelElementClass("car", CarClass); expect(_.isEmpty(UmlModelAbstractFactory.types)).toBe(true); // console.log("types : ", UmlModelAbstractFactory.types); } ])); }); });
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* eslint-disable global-require */ // The top-level (parent) route export default { path: '/', // Keep in mind, routes are evaluated in order children: [ require('./home/index').default, require('./contact/index').default, require('./login/index').default, require('./register/index').default, require('./admin/index').default, // Wildcard routes, e.g. { path: '*', ... } (must go last) require('./content/index').default, require('./notFound/index').default, ], async action({ next }) { // Execute each child route until one of them return the result const route = await next(); // Provide default values for title, description etc. route.title = `${route.title || 'Untitled Page'} - www.reactstarterkit.com`; route.description = route.description || ''; return route; }, };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.utils = exports.default = void 0; var reducers = _interopRequireWildcard(require("./reducers")); var _utils = _interopRequireWildcard(require("./utils")); exports.utils = _utils; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } var _default = reducers; exports.default = _default;
/////////////////////////////////////////////////////////////////////////////// // // Effect // /////////////////////////////////////////////////////////////////////////////// //// IMPORTS ////////////////////////////////////////////////////////////////// import { toJs } from 'mori'; import diff from 'virtual-dom/diff'; import patch from 'virtual-dom/patch'; import stateStream from '../streams/state'; /////////////////////////////////////////////////////////////////////////////// // :: DOMNode node, Function stateToModel, Function modelToVDOM // -> Effectful Eventstream that will mutate the node as state changes, // mapping the state to a model that is rendered to a virtual DOM, and // patched to the DOM. // Note - the Effectful EventStream will need a subscriber to start. export default (node, stateToModel, modelToVDOM) => { return stateStream .map(toJs) .map(stateToModel) .map(modelToVDOM) .diff(node, diff) .scan(node, patch); }; ///////////////////////////////////////////////////////////////////////////////
if (typeof global === 'undefined') { global = window; } else { global.XRegExp = require('../../xregexp-all'); } // Ensure that all opt-in features are disabled when each spec starts global.disableOptInFeatures = function() { XRegExp.uninstall('namespacing astral'); }; // Property name used for extended regex instance data global.REGEX_DATA = 'xregexp'; // Check for ES6 `u` flag support global.hasNativeU = XRegExp._hasNativeFlag('u'); // Check for ES6 `y` flag support global.hasNativeY = XRegExp._hasNativeFlag('y'); // Check for strict mode support global.hasStrictMode = (function() { 'use strict'; return !this; }()); // Naive polyfill of String.prototype.repeat if (!String.prototype.repeat) { String.prototype.repeat = function(count) { return count ? Array(count + 1).join(this) : ''; }; }
'use strict'; let datafire = require('datafire'); let openapi = require('./openapi.json'); let aws = require('aws-sdk'); const INTEGRATION_ID = 'amazonaws_data_jobs_iot'; const SDK_ID = 'IoTJobsDataPlane'; let integ = module.exports = new datafire.Integration({ id: INTEGRATION_ID, title: openapi.info.title, description: openapi.info.description, logo: openapi.info['x-logo'], }); integ.security[INTEGRATION_ID]= { integration: INTEGRATION_ID, fields: { accessKeyId: "", secretAccessKey: "", region: "AWS region (if applicable)", } } function maybeCamelCase(str) { return str.replace(/_(\w)/g, (match, char) => char.toUpperCase()) } // We use this instance to make sure each action is available in the SDK at startup. let dummyInstance = new aws[SDK_ID]({version: openapi.version, endpoint: 'foo'}); for (let path in openapi.paths) { for (let method in openapi.paths[path]) { if (method === 'parameters') continue; let op = openapi.paths[path][method]; let actionID = op.operationId; actionID = actionID.replace(/\d\d\d\d_\d\d_\d\d$/, ''); if (actionID.indexOf('_') !== -1) { actionID = actionID.split('_')[1]; } let functionID = actionID.charAt(0).toLowerCase() + actionID.substring(1); if (!dummyInstance[functionID]) { console.error("AWS SDK " + SDK_ID + ": Function " + functionID + " not found"); console.log(method, path, op.operationId, actionID); continue; } let inputParam = (op.parameters || []).filter(p => p.in === 'body')[0] || {}; let response = (op.responses || {})[200] || {}; let inputSchema = { type: 'object', properties: {}, }; if (inputParam.schema) inputSchema.allOf = [inputParam.schema]; (op.parameters || []).forEach(p => { if (p.name !== 'Action' && p.name !== 'Version' && p.name !== 'body' && !p.name.startsWith('X-')) { inputSchema.properties[maybeCamelCase(p.name)] = {type: p.type}; if (p.required) { inputSchema.required = inputSchema.required || []; inputSchema.required.push(p.name); } } }) function getSchema(schema) { if (!schema) return; return Object.assign({definitions: openapi.definitions}, schema); } integ.addAction(actionID, new datafire.Action({ inputSchema: getSchema(inputSchema), outputSchema: getSchema(response.schema), handler: (input, context) => { let lib = new aws[SDK_ID](Object.assign({ version: openapi.info.version, }, context.accounts[INTEGRATION_ID])); return lib[functionID](input).promise() .then(data => { return JSON.parse(JSON.stringify(data)); }) } })); } }
'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _jquery = require('jquery'); var _jquery2 = _interopRequireDefault(_jquery); require('./loading-mask.css!'); var _locale = require('../locale'); var LoadingMask = (function () { function LoadingMask(resources) { _classCallCheck(this, LoadingMask); this.loadingMask = undefined; this.dimScreen = undefined; this.dialog = undefined; this.loadingTitle = undefined; this.title = undefined; this.locale = _locale.Locale.Repository['default']; this._createLoadingMask(); } LoadingMask.prototype._createLoadingMask = function _createLoadingMask() { this.title = this.locale.translate('loading'); this.dimScreen = '<div id="loadingMask" class="spinner"><div class="loadingTitle">' + this.title + '</div><div class="mask"></div></div>'; (0, _jquery2['default'])('body').append(this.dimScreen); this.loadingMask = (0, _jquery2['default'])('#loadingMask'); this.loadingTitle = (0, _jquery2['default'])('.loadingTitle').css({ color: '#ffffff', opacity: 1, fontSize: '2.5em', fontFamily: 'Roboto' }); }; LoadingMask.prototype.show = function show() { this.loadingMask.show(); }; LoadingMask.prototype.hide = function hide() { this.loadingMask.hide(); }; return LoadingMask; })(); exports.LoadingMask = LoadingMask;
var five = require("johnny-five"), board = new five.Board(); board.on("ready", function() { var led = new five.Led(12); var rgb = new five.Led.RGB([6, 5, 3]); var index = 0; this.loop(10, function() { // led.toggle(); if (index === 16777215) { index = 0; } rgb.color(index.toString(16)); index++; }); }); // var led = new five.Led(13); // led.blink(5);
var mysql = require('mysql'); var bcrypt = require('bcryptjs'); var connection = mysql.createConnection({ host: process.env.FOLIO_HOST, user: process.env.FOLIO_USER, database: process.env.FOLIO_DATABASE, password: process.env.FOLIO_PASSWORD }); console.log("[*] Database connection open") console.log("[*] Resetting username and password"); connection.query("TRUNCATE users;"); console.log("[*] Creating default user, admin (username), password (password)"); var passwordhash = bcrypt.hashSync("password", 10); console.log("\t[>] Password hash: " + passwordhash); connection.query("INSERT INTO users(username, passwordhash) values('admin', '" + passwordhash + "');"); connection.end(); console.log("[*] Finished!");
import React from 'react' import PropTypes from 'prop-types' import { MarkerCanvasProvider } from './MarkerCanvasContext' import TimelineMarkersRenderer from './TimelineMarkersRenderer' import { TimelineStateConsumer } from '../timeline/TimelineStateContext' // expand to fill entire parent container (ScrollElement) const staticStyles = { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0 } /** * Renders registered markers and exposes a mouse over listener for * CursorMarkers to subscribe to */ class MarkerCanvas extends React.Component { static propTypes = { getDateFromLeftOffsetPosition: PropTypes.func.isRequired, children: PropTypes.node } handleMouseMove = evt => { if (this.subscription != null) { const { pageX } = evt // FIXME: dont use getBoundingClientRect. Use passed in scroll amount const { left: containerLeft } = this.containerEl.getBoundingClientRect() // number of pixels from left we are on canvas // we do this calculation as pageX is based on x from viewport whereas // our canvas can be scrolled left and right and is generally outside // of the viewport. This calculation is to get how many pixels the cursor // is from left of this element const canvasX = pageX - containerLeft const date = this.props.getDateFromLeftOffsetPosition(canvasX) this.subscription({ leftOffset: canvasX, date, isCursorOverCanvas: true }) } } handleMouseLeave = () => { if (this.subscription != null) { // tell subscriber that we're not on canvas this.subscription({ leftOffset: 0, date: 0, isCursorOverCanvas: false }) } } handleMouseMoveSubscribe = sub => { this.subscription = sub return () => { this.subscription = null } } state = { subscribeToMouseOver: this.handleMouseMoveSubscribe } render() { return ( <MarkerCanvasProvider value={this.state}> <div style={staticStyles} onMouseMove={this.handleMouseMove} onMouseLeave={this.handleMouseLeave} ref={el => (this.containerEl = el)} > <TimelineMarkersRenderer /> {this.props.children} </div> </MarkerCanvasProvider> ) } } const MarkerCanvasWrapper = props => ( <TimelineStateConsumer> {({ getDateFromLeftOffsetPosition }) => ( <MarkerCanvas getDateFromLeftOffsetPosition={getDateFromLeftOffsetPosition} {...props} /> )} </TimelineStateConsumer> ) export default MarkerCanvasWrapper
const mongoose = require('mongoose') const Schema = mongoose.Schema let AgencySchema = new Schema({ }) module.exports = mongoose.model('Agency', AgencySchema)
const mix = require('laravel-mix'); mix .js('resources/assets/app.js', 'public/js') .extract(['vue', 'lodash']) ;
window.test = 1;
const express = require('express'), handler = require('../handlers/sitemap'), requestHelper = require('../helpers/request-helper'), router = express.Router(); router.get('/', requestHelper.cache(), (req, res, next) => { requestHelper.initRouter({ req: req, res: res, handler: handler, endPointParams: { posts: '?system.type=blog_post&order=elements.date[desc]&elements=url_slug' }, view: 'sitemap' }); }); module.exports = router;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var TooltipDelay; (function (TooltipDelay) { TooltipDelay[TooltipDelay["zero"] = 0] = "zero"; TooltipDelay[TooltipDelay["medium"] = 1] = "medium"; })(TooltipDelay = exports.TooltipDelay || (exports.TooltipDelay = {})); //# sourceMappingURL=Tooltip.Props.js.map
require("./71.js"); require("./143.js"); require("./286.js"); require("./571.js"); module.exports = 572;
var joi = require('joi'); var _ = require('lodash'); module.exports = function(router, db) { // This is our "class" that accesses/modifies notes in the db var NoteService = require('../lib/db-notes') var noteService = new NoteService(db); // Joi is a wonderful library that takes strings and converts them into the proper // type while validating them. Anyone who works with query strings knows this is // usually a painfully dull process, and this makes that 10x easier. var querySchema = joi.object().keys({ limit: joi.number().integer().min(1).max(1000), skip: joi.number().integer().min(0), field: joi.string().valid(["createdBy", "note", "lastModified"]), value: joi.string().trim(), sort: joi.valid(["createdBy", "note"]), order: joi.number().valid([1, -1]) }).and(['sort', 'order']).and('field','value'); // Read list router.get('/api/notes', function(req, res, next) { joi.validate(req.query, querySchema, function(err, queryString) { var query = {}, options = {}; if(err) return next(err); if(_.isEmpty(queryString)) { options.sort = { 'lastModified': -1 }; query = {}; } else { query = setQuery(queryString.field, queryString.value); if(queryString.sort) options.sort[queryString.sort] = queryString.order; options.limit = queryString.limit; options.skip = queryString.skip; } noteService.list(query, options, function(err, users) { if(err) return next(err); res.send(users); }); }); }); /** * Adds a note. The lastModified date is handled automatically. */ router.post('/api/notes', function(req, res, next) { var note; note = { createdBy: req.body.name, note: req.body.note }; noteService.add(note, function(err, result) { if(err) { if(err.message ==='Validation failed') { return res.send(400, err); } return next(err); } if(result === null) { return res.send(400, { error: { message: 'Note does not exist' }}); } // Doesn't belong in the api really, but for quickly getting this working: if(req.accepts(['html', 'json']) === 'html') return res.redirect('/notes'); res.send(200, result); }); }); /** * Updates a note. * TODO: Not yet used and tested */ router.put('/api/notes/:id', function(req, res, next) { var id; try{ id = ObjectID(req.params.id); }catch(err) { return res.send(400, {error: err.message}); } noteService.updateNote(id, req.body, function(err, result) { if(err) return next(err); if(result === 0) { return res.send(400, { error: 'Note `' + req.params.id + '` does not exist' }); } res.json(200, null); }); }); /** * Deletes a note from the db */ router.delete('/api/notes/:id', function(req, res, next) { noteService.remove(req.params.id, function(err, result) { if(err) return next(err); if(result === 0) { return res.send(400, { error: 'Note `' + req.params.id + '` does not exist' }); } res.json(200, null); }); }); };
'use strict'; var twoSum = require('../src/two-sum/naive'); describe('twoSum naive', function () { it('should return undefined when called on an empty array', function () { expect(twoSum([], 1)).toBe(undefined); }); it('should return correct result when it exists in sorted lists', function () { expect(twoSum([1, 2, 4, 8, 16], 3)).toEqual([0, 1]); expect(twoSum([1, 2, 4, 8, 16], 6)).toEqual([1, 2]); expect(twoSum([1, 2, 4, 8, 16], 17)).toEqual([0, 4]); expect(twoSum([1, 2, 4, 8, 16], 20)).toEqual([2, 4]); expect(twoSum([1, 2, 4, 8, 16], 24)).toEqual([3, 4]); }); it('should return correct result when it exists in a jumbled lists', function () { expect(twoSum([16, 1, 4, 2, 8], 3)).toEqual([1, 3]); expect(twoSum([16, 1, 4, 2, 8], 6)).toEqual([2, 3]); expect(twoSum([16, 1, 4, 2, 8], 17)).toEqual([0, 1]); expect(twoSum([16, 1, 4, 2, 8], 20)).toEqual([0, 2]); expect(twoSum([16, 1, 4, 2, 8], 24)).toEqual([0, 4]); }); });
module.exports = { description: "", ns: "react-material-ui", type: "ReactNode", dependencies: { npm: { "material-ui/svg-icons/image/photo-size-select-actual": require('material-ui/svg-icons/image/photo-size-select-actual') } }, name: "ImagePhotoSizeSelectActual", ports: { input: {}, output: { component: { title: "ImagePhotoSizeSelectActual", type: "Component" } } } }
import _ from 'lodash/fp' export const TYPES = { ADDON: 'addon', COLLECTION: 'collection', ELEMENT: 'element', VIEW: 'view', MODULE: 'module', } const TYPE_VALUES = _.values(TYPES) /** * Determine if an object qualifies as a META object. * It must have the required keys and valid values. * @private * @param {Object} _meta A proposed Stardust _meta object. * @returns {Boolean} */ export const isMeta = (_meta) => ( _.includes(_.get('type', _meta), TYPE_VALUES) ) /** * Extract the Stardust _meta object and optional key. * Handles literal _meta objects, classes with _meta, objects with _meta * @private * @param {function|object} metaArg A class, a component instance, or meta object.. * @returns {object|string|undefined} */ const getMeta = (metaArg) => { // literal if (isMeta(metaArg)) return metaArg // from prop else if (isMeta(_.get('_meta', metaArg))) return metaArg._meta // from class else if (isMeta(_.get('constructor._meta', metaArg))) return metaArg.constructor._meta } const metaHasKeyValue = _.curry((key, val, metaArg) => _.flow(getMeta, _.get(key), _.eq(val))(metaArg)) export const isType = metaHasKeyValue('type') // ---------------------------------------- // Export // ---------------------------------------- // type export const isAddon = isType(TYPES.ADDON) export const isCollection = isType(TYPES.COLLECTION) export const isElement = isType(TYPES.ELEMENT) export const isView = isType(TYPES.VIEW) export const isModule = isType(TYPES.MODULE) // parent export const isParent = _.flow(getMeta, _.has('parent'), _.eq(false)) export const isChild = _.flow(getMeta, _.has('parent')) // other export const isPrivate = _.flow(getMeta, _.get('name'), _.startsWith('_'))
/** * DevExtreme (ui/scroll_view/ui.scroll_view.js) * Version: 16.2.6 * Build date: Tue Mar 28 2017 * * Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED * EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml */ "use strict"; var $ = require("jquery"), devices = require("../../core/devices"), messageLocalization = require("../../localization/message"), registerComponent = require("../../core/component_registrator"), PullDownStrategy = require("./ui.scroll_view.native.pull_down"), SwipeDownStrategy = require("./ui.scroll_view.native.swipe_down"), SlideDownStrategy = require("./ui.scroll_view.native.slide_down"), SimulatedStrategy = require("./ui.scroll_view.simulated"), Scrollable = require("./ui.scrollable"), LoadIndicator = require("../load_indicator"), config = require("../../core/config"), LoadPanel = require("../load_panel"); var SCROLLVIEW_CLASS = "dx-scrollview", SCROLLVIEW_CONTENT_CLASS = SCROLLVIEW_CLASS + "-content", SCROLLVIEW_TOP_POCKET_CLASS = SCROLLVIEW_CLASS + "-top-pocket", SCROLLVIEW_BOTTOM_POCKET_CLASS = SCROLLVIEW_CLASS + "-bottom-pocket", SCROLLVIEW_PULLDOWN_CLASS = SCROLLVIEW_CLASS + "-pull-down", SCROLLVIEW_REACHBOTTOM_CLASS = SCROLLVIEW_CLASS + "-scrollbottom", SCROLLVIEW_REACHBOTTOM_INDICATOR_CLASS = SCROLLVIEW_REACHBOTTOM_CLASS + "-indicator", SCROLLVIEW_REACHBOTTOM_TEXT_CLASS = SCROLLVIEW_REACHBOTTOM_CLASS + "-text", SCROLLVIEW_LOADPANEL = SCROLLVIEW_CLASS + "-loadpanel"; var refreshStrategies = { pullDown: PullDownStrategy, swipeDown: SwipeDownStrategy, slideDown: SlideDownStrategy, simulated: SimulatedStrategy }; var ScrollView = Scrollable.inherit({ _getDefaultOptions: function() { return $.extend(this.callBase(), { pullingDownText: messageLocalization.format("dxScrollView-pullingDownText"), pulledDownText: messageLocalization.format("dxScrollView-pulledDownText"), refreshingText: messageLocalization.format("dxScrollView-refreshingText"), reachBottomText: messageLocalization.format("dxScrollView-reachBottomText"), onPullDown: null, onReachBottom: null, refreshStrategy: "pullDown" }) }, _defaultOptionsRules: function() { return this.callBase().concat([{ device: function() { var realDevice = devices.real(); return "android" === realDevice.platform }, options: { refreshStrategy: "swipeDown" } }, { device: function() { return "win" === devices.real().platform }, options: { refreshStrategy: "slideDown" } }]) }, _init: function() { this.callBase(); this._loadingIndicatorEnabled = true }, _initMarkup: function() { this.callBase(); this.element().addClass(SCROLLVIEW_CLASS); this._initContent(); this._initTopPocket(); this._initBottomPocket(); this._initLoadPanel() }, _initContent: function() { var $content = $("<div>").addClass(SCROLLVIEW_CONTENT_CLASS); this._$content.wrapInner($content) }, _initTopPocket: function() { var $topPocket = this._$topPocket = $("<div>").addClass(SCROLLVIEW_TOP_POCKET_CLASS), $pullDown = this._$pullDown = $("<div>").addClass(SCROLLVIEW_PULLDOWN_CLASS); $topPocket.append($pullDown); this._$content.prepend($topPocket) }, _initBottomPocket: function() { var $bottomPocket = this._$bottomPocket = $("<div>").addClass(SCROLLVIEW_BOTTOM_POCKET_CLASS), $reachBottom = this._$reachBottom = $("<div>").addClass(SCROLLVIEW_REACHBOTTOM_CLASS), $loadContainer = $("<div>").addClass(SCROLLVIEW_REACHBOTTOM_INDICATOR_CLASS), $loadIndicator = new LoadIndicator($("<div>")).element(), $text = this._$reachBottomText = $("<div>").addClass(SCROLLVIEW_REACHBOTTOM_TEXT_CLASS); this._updateReachBottomText(); $reachBottom.append($loadContainer.append($loadIndicator)).append($text); $bottomPocket.append($reachBottom); this._$content.append($bottomPocket) }, _initLoadPanel: function() { this._loadPanel = this._createComponent($("<div>").addClass(SCROLLVIEW_LOADPANEL).appendTo(this.element()), LoadPanel, { shading: false, delay: 400, message: this.option("refreshingText"), position: { of: this.element() } }) }, _updateReachBottomText: function() { this._$reachBottomText.text(this.option("reachBottomText")) }, _createStrategy: function() { var strategyName = this.option("useNative") ? this.option("refreshStrategy") : "simulated"; var strategyClass = refreshStrategies[strategyName]; if (!strategyClass) { throw Error("E1030", this.option("refreshStrategy")) } this._strategy = new strategyClass(this); this._strategy.pullDownCallbacks.add($.proxy(this._pullDownHandler, this)); this._strategy.releaseCallbacks.add($.proxy(this._releaseHandler, this)); this._strategy.reachBottomCallbacks.add($.proxy(this._reachBottomHandler, this)) }, _createActions: function() { this.callBase(); this._pullDownAction = this._createActionByOption("onPullDown"); this._reachBottomAction = this._createActionByOption("onReachBottom"); this._refreshPocketState() }, _refreshPocketState: function() { this._pullDownEnable(this.hasActionSubscription("onPullDown") && !config().designMode); this._reachBottomEnable(this.hasActionSubscription("onReachBottom") && !config().designMode) }, on: function(eventName) { var result = this.callBase.apply(this, arguments); if ("pullDown" === eventName || "reachBottom" === eventName) { this._refreshPocketState() } return result }, _pullDownEnable: function(enabled) { if (0 === arguments.length) { return this._pullDownEnabled } this._$pullDown.toggle(enabled); this._strategy.pullDownEnable(enabled); this._pullDownEnabled = enabled }, _reachBottomEnable: function(enabled) { if (0 === arguments.length) { return this._reachBottomEnabled } this._$reachBottom.toggle(enabled); this._strategy.reachBottomEnable(enabled); this._reachBottomEnabled = enabled }, _pullDownHandler: function() { this._loadingIndicator(false); this._pullDownLoading() }, _loadingIndicator: function(value) { if (arguments.length < 1) { return this._loadingIndicatorEnabled } this._loadingIndicatorEnabled = value }, _pullDownLoading: function() { this.startLoading(); this._pullDownAction() }, _reachBottomHandler: function() { this._loadingIndicator(false); this._reachBottomLoading() }, _reachBottomLoading: function() { this.startLoading(); this._reachBottomAction() }, _releaseHandler: function() { this.finishLoading(); this._loadingIndicator(true) }, _optionChanged: function(args) { switch (args.name) { case "onPullDown": case "onReachBottom": this._createActions(); break; case "pullingDownText": case "pulledDownText": case "refreshingText": case "refreshStrategy": this._invalidate(); break; case "reachBottomText": this._updateReachBottomText(); break; default: this.callBase(args) } }, isEmpty: function() { return !this.content().children().length }, content: function() { return this._$content.children().eq(1) }, release: function(preventReachBottom) { if (void 0 !== preventReachBottom) { this.toggleLoading(!preventReachBottom) } return this._strategy.release() }, toggleLoading: function(showOrHide) { this._reachBottomEnable(showOrHide) }, isFull: function() { return this.content().height() > this._$container.height() }, refresh: function() { if (!this.hasActionSubscription("onPullDown")) { return } this._strategy.pendingRelease(); this._pullDownLoading() }, startLoading: function() { if (this._loadingIndicator() && this.element().is(":visible")) { this._loadPanel.show() } this._lock() }, finishLoading: function() { this._loadPanel.hide(); this._unlock() }, _dispose: function() { this._strategy.dispose(); this.callBase(); if (this._loadPanel) { this._loadPanel.element().remove() } } }); registerComponent("dxScrollView", ScrollView); module.exports = ScrollView;
var Backbone = require('backbone'), _ = require('underscore'); global.App = {}; App.Task = Backbone.Model.extend({ url : 'http://localhost:9292/tasks/' + this.get('id'), defaults : { title: 'Untitled Task 1', done : false } }); App.TaskCollection = Backbone.collection.extend({ model : Task, urlRoot : 'http://localhost:9292/tasks' }); App.TaskView = Backbone.View.extend({ tagName : 'li', className : 'task', template : _.template(require('./templates/task.html')), initialize : function() { this.render(); }, render : function() { this.$el.html(this.template(this.model.attributes)); this.delegateEvents(); return this; } }); App.TaskCollectionView = Backbone.View.extend({ tagName : 'ul', className : 'task-list', initialize: function() { this.render(); }, render : function() { this.$el.empty(); _.each(this.collection.models, function(task) { var view = new App.TaskView({model: task}); this.$el.append(view.render().$el); }); this.delegateEvents(); return this; } }); App.Router = Backbone.Router.extend({ routes : { '(/)' : 'showList' }, showList: function() { var tasks = new App.TaskCollection(); var view = new App.TaskCollectionView({collection: tasks}); $('body').html(view.render().el); } }); module.exports = App;
var model = require(__dirname + '/../models/model.js'); var controller = function() {}; //create new user function create(id) { var newUser = new model({ id: id, currentCowntt: 0, apiCallsMade: 0 }); return newUser; } function getUser(id, cb) { model.findOne({ //find by unique id id: id }, function(err, user) { if (err) { console.log(err); throw new Error('could not query db'); } if (!user) {//user already existed in database user = create(id); } cb(user); }); } function saveUser(user, cb) { user.save( function(saveErr) { if (saveErr) { console.log('saveError saving to debugger: ' + saveErr); } cb(user); }); } controller.prototype.incrementCowntt = function(id, parentCB) { getUser(id, function (user) { user.currentCowntt += 1; user.apiCallsMade += 1; saveUser(user, function() { parentCB(user.currentCowntt); }); }); }; controller.prototype.decrementCowntt = function(id, parentCB) { getUser(id, function (user) { user.currentCowntt -= 1; user.apiCallsMade += 1; saveUser(user, function() { parentCB(user.currentCowntt); }); }); }; controller.prototype.setCowntt = function(id, setVal, parentCB) { getUser(id, function (user) { user.currentCowntt = setVal; user.apiCallsMade += 1; saveUser(user, function() { parentCB(user.currentCowntt); }); }); }; controller.prototype.getCowntt = function(id, parentCB) { getUser(id, function (user) { user.apiCallsMade += 1; saveUser(user, function() { }); parentCB(user.currentCowntt); }); }; module.exports = controller;
import React, {PropTypes, Component} from 'react'; import moment from 'moment'; import StyleSheet from 'styles/agenda.styl'; export default class AgendaChart extends Component { static propTypes = { items: PropTypes.array, currentDate: PropTypes.number, roomName: PropTypes.string } render() { const start = moment().hour(8).minutes(0); const {currentDate, items, roomName} = this.props; let currTime; if (moment(currentDate).isSame(moment(), 'day')) { currTime = moment().diff(start, 'hours', true); } return ( <div className={StyleSheet.container}> <div className="room-header biggie"> <span className="room-title"> {roomName} </span> </div> <div className="content-container"> {(currTime > 0) && <div className="current-time" style={{ top: `${currTime * 10}%` }}/> } {items.map(item => { const morning = moment(currentDate).hour(8).minutes(0); const fromTop = moment(item.start.dateTime).diff(morning, 'hours', true); const fromBottom = moment(item.end.dateTime).diff(item.start.dateTime, 'hours', true); return ( <div key={`agenda-${item.id}`} className="agenda-item" style={{ top: `${(fromTop * 10)}%`, height: `${(fromBottom * 10)}%` }}> <p className="content"> {item.summary} <br/> {moment(item.start.dateTime).format('h:mm ')}- {moment(item.end.dateTime).format(' h:mm')} </p> </div> ); })} </div> </div> ); } }
import { tshirtImageVersions, imageVersionProps } from './fragments' export default ` ${imageVersionProps} ${tshirtImageVersions} { categoryNav { id name slug level tileImage { ...tshirtImageVersions } } } `
/** * Created with JetBrains WebStorm. * User: yuzhechang * Date: 13-9-24 * Time: 下午3:47 * To change this template use File | Settings | File Templates. */ (function($) { var ngmod = angular.module("framework.controllers", ["framework.serviceService"]); ngmod.controller("pageCtrl",function($scope,$rootScope,service_clist_FlistRES){ $scope.abc = "test-data"; $scope.flistData = null; $scope.selFlist=null ; //页面数据,回传数据 //modal_onLoad是父controller里的虚方法(面向对象里类的概念)。 // 在这里的实际中是父controller里调用$rootScope.modal_onLoad,在子controller里提供modal_onLoad,并写入到$rootScope中。 $rootScope.modal_onLoad = function(config){ $scope.data = config.data; if(config.data.rowData) { $scope.flistData = config.data.rowData; $scope.selFlist = config.data.rowData.fieldName; console.log( $scope.selFlist); } // $scope.flistData.position = config.data.rowsNum; //添加提交按钮的处理事件 config.onSubmitForModal(function(){ console.log("窗口内的提交事件"); // config.resultData = {id:10000,msg:"回传数据"}; config.resultData = $scope.flistData; return true; }); } //获取属性数据 service_clist_FlistRES.get({ },function(structureFlist){ $scope.structureFlist=structureFlist; console.log(structureFlist); }); //选择属性事件 $scope.flistChange=function(flistId) { var flistjson =eval('('+flistId+')'); $scope.flistData = flistjson; $scope.flistData.fieldName=flistjson.name; $scope.flistData.desc=flistjson.description; $scope.flistData.otherName =flistjson.name; $scope.flistData.required=$(".J_isMust option:checked").text(); $scope.flistData.position= $scope.data.rowsNum; } }); })(jQuery);
/** * This animation class is a mixin. * * Ext.util.Animate provides an API for the creation of animated transitions of properties and styles. * This class is used as a mixin and currently applied to {@link Ext.dom.Element}, {@link Ext.CompositeElement}, * {@link Ext.draw.sprite.Sprite}, {@link Ext.draw.sprite.Composite}, and {@link Ext.Component}. Note that Components * have a limited subset of what attributes can be animated such as top, left, x, y, height, width, and * opacity (color, paddings, and margins can not be animated). * * ## Animation Basics * * All animations require three things - `easing`, `duration`, and `to` (the final end value for each property) * you wish to animate. Easing and duration are defaulted values specified below. * Easing describes how the intermediate values used during a transition will be calculated. * {@link Ext.fx.Anim#easing Easing} allows for a transition to change speed over its duration. * You may use the defaults for easing and duration, but you must always set a * {@link Ext.fx.Anim#to to} property which is the end value for all animations. * * Popular element 'to' configurations are: * * - opacity * - x * - y * - color * - height * - width * * Popular sprite 'to' configurations are: * * - translation * - path * - scale * - stroke * - rotation * * The default duration for animations is 250 (which is a 1/4 of a second). Duration is denoted in * milliseconds. Therefore 1 second is 1000, 1 minute would be 60000, and so on. The default easing curve * used for all animations is 'ease'. Popular easing functions are included and can be found in {@link Ext.fx.Anim#easing Easing}. * * For example, a simple animation to fade out an element with a default easing and duration: * * var p1 = Ext.get('myElementId'); * * p1.animate({ * to: { * opacity: 0 * } * }); * * To make this animation fade out in a tenth of a second: * * var p1 = Ext.get('myElementId'); * * p1.animate({ * duration: 100, * to: { * opacity: 0 * } * }); * * ## Animation Queues * * By default all animations are added to a queue which allows for animation via a chain-style API. * For example, the following code will queue 4 animations which occur sequentially (one right after the other): * * p1.animate({ * to: { * x: 500 * } * }).animate({ * to: { * y: 150 * } * }).animate({ * to: { * backgroundColor: '#f00' //red * } * }).animate({ * to: { * opacity: 0 * } * }); * * You can change this behavior by calling the {@link Ext.util.Animate#syncFx syncFx} method and all * subsequent animations for the specified target will be run concurrently (at the same time). * * p1.syncFx(); //this will make all animations run at the same time * * p1.animate({ * to: { * x: 500 * } * }).animate({ * to: { * y: 150 * } * }).animate({ * to: { * backgroundColor: '#f00' //red * } * }).animate({ * to: { * opacity: 0 * } * }); * * This works the same as: * * p1.animate({ * to: { * x: 500, * y: 150, * backgroundColor: '#f00' //red * opacity: 0 * } * }); * * The {@link Ext.util.Animate#stopAnimation stopAnimation} method can be used to stop any * currently running animations and clear any queued animations. * * ## Animation Keyframes * * You can also set up complex animations with {@link Ext.fx.Anim#keyframes keyframes} which follow the * CSS3 Animation configuration pattern. Note rotation, translation, and scaling can only be done for sprites. * The previous example can be written with the following syntax: * * p1.animate({ * duration: 1000, //one second total * keyframes: { * 25: { //from 0 to 250ms (25%) * x: 0 * }, * 50: { //from 250ms to 500ms (50%) * y: 0 * }, * 75: { //from 500ms to 750ms (75%) * backgroundColor: '#f00' //red * }, * 100: { //from 750ms to 1sec * opacity: 0 * } * } * }); * * ## Animation Events * * Each animation you create has events for {@link Ext.fx.Anim#beforeanimate beforeanimate}, * {@link Ext.fx.Anim#afteranimate afteranimate}, and {@link Ext.fx.Anim#lastframe lastframe}. * Keyframed animations adds an additional {@link Ext.fx.Animator#keyframe keyframe} event which * fires for each keyframe in your animation. * * All animations support the {@link Ext.util.Observable#listeners listeners} configuration to attact functions to these events. * * startAnimate: function() { * var p1 = Ext.get('myElementId'); * p1.animate({ * duration: 100, * to: { * opacity: 0 * }, * listeners: { * beforeanimate: function() { * // Execute my custom method before the animation * this.myBeforeAnimateFn(); * }, * afteranimate: function() { * // Execute my custom method after the animation * this.myAfterAnimateFn(); * }, * scope: this * }); * }, * myBeforeAnimateFn: function() { * // My custom logic * }, * myAfterAnimateFn: function() { * // My custom logic * } * * Due to the fact that animations run asynchronously, you can determine if an animation is currently * running on any target by using the {@link Ext.util.Animate#getActiveAnimation getActiveAnimation} * method. This method will return false if there are no active animations or return the currently * running {@link Ext.fx.Anim} instance. * * In this example, we're going to wait for the current animation to finish, then stop any other * queued animations before we fade our element's opacity to 0: * * var curAnim = p1.getActiveAnimation(); * if (curAnim) { * curAnim.on('afteranimate', function() { * p1.stopAnimation(); * p1.animate({ * to: { * opacity: 0 * } * }); * }); * } */ Ext.define('Ext.util.Animate', { mixinId: 'animate', requires: [ 'Ext.fx.Manager', 'Ext.fx.Anim' ], isAnimate: true, /** * Performs custom animation on this object. * * This method is applicable to both the {@link Ext.Component Component} class and the {@link Ext.draw.sprite.Sprite Sprite} * class. It performs animated transitions of certain properties of this object over a specified timeline. * * ### Animating a {@link Ext.Component Component} * * When animating a Component, the following properties may be specified in `from`, `to`, and `keyframe` objects: * * - `x` - The Component's page X position in pixels. * * - `y` - The Component's page Y position in pixels * * - `left` - The Component's `left` value in pixels. * * - `top` - The Component's `top` value in pixels. * * - `width` - The Component's `width` value in pixels. * * - `height` - The Component's `height` value in pixels. * * The following property may be set on the animation config root: * * - `dynamic` - Specify as true to update the Component's layout (if it is a Container) at every frame of the animation. * *Use sparingly as laying out on every intermediate size change is an expensive operation.* * * For example, to animate a Window to a new size, ensuring that its internal layout and any shadow is correct: * * myWindow = Ext.create('Ext.window.Window', { * title: 'Test Component animation', * width: 500, * height: 300, * layout: { * type: 'hbox', * align: 'stretch' * }, * items: [{ * title: 'Left: 33%', * margin: '5 0 5 5', * flex: 1 * }, { * title: 'Left: 66%', * margin: '5 5 5 5', * flex: 2 * }] * }); * myWindow.show(); * myWindow.header.el.on('click', function() { * myWindow.animate({ * to: { * width: (myWindow.getWidth() == 500) ? 700 : 500, * height: (myWindow.getHeight() == 300) ? 400 : 300 * } * }); * }); * * For performance reasons, by default, the internal layout is only updated when the Window reaches its final `"to"` * size. If dynamic updating of the Window's child Components is required, then configure the animation with * `dynamic: true` and the two child items will maintain their proportions during the animation. * * @param {Object} config Configuration for {@link Ext.fx.Anim}. * Note that the {@link Ext.fx.Anim#to to} config is required. * @return {Object} this */ animate: function(animObj) { var me = this; if (Ext.fx.Manager.hasFxBlock(me.id)) { return me; } Ext.fx.Manager.queueFx(new Ext.fx.Anim(me.anim(animObj))); return this; }, /** * @private * Process the passed fx configuration. */ anim: function(config) { if (!Ext.isObject(config)) { return (config) ? {} : false; } var me = this; if (config.stopAnimation) { me.stopAnimation(); } Ext.applyIf(config, Ext.fx.Manager.getFxDefaults(me.id)); return Ext.apply({ target: me, paused: true }, config); }, /** * @private * Get animation properties */ getAnimationProps: function() { var me = this, layout = me.layout; return layout && layout.animate ? layout.animate : {}; }, /** * Stops any running effects and clears this object's internal effects queue if it contains any additional effects * that haven't started yet. * @deprecated 4.0 Replaced by {@link #stopAnimation} * @return {Ext.dom.Element} The Element * @method */ stopFx: Ext.Function.alias(Ext.util.Animate, 'stopAnimation'), /** * Stops any running effects and clears this object's internal effects queue if it contains any additional effects * that haven't started yet. * @return {Ext.dom.Element} The Element */ stopAnimation: function() { Ext.fx.Manager.stopAnimation(this.id); return this; }, /** * Ensures that all effects queued after syncFx is called on this object are run concurrently. This is the opposite * of {@link #sequenceFx}. * @return {Object} this */ syncFx: function() { Ext.fx.Manager.setFxDefaults(this.id, { concurrent: true }); return this; }, /** * Ensures that all effects queued after sequenceFx is called on this object are run in sequence. This is the * opposite of {@link #syncFx}. * @return {Object} this */ sequenceFx: function() { Ext.fx.Manager.setFxDefaults(this.id, { concurrent: false }); return this; }, /** * @deprecated 4.0 Replaced by {@link #getActiveAnimation} * @inheritdoc Ext.util.Animate#getActiveAnimation * @method */ hasActiveFx: Ext.Function.alias(Ext.util.Animate, 'getActiveAnimation'), /** * Returns the current animation if this object has any effects actively running or queued, else returns false. * @return {Ext.fx.Anim/Boolean} Anim if element has active effects, else false */ getActiveAnimation: function() { return Ext.fx.Manager.getActiveAnimation(this.id); } });
/** * Created by Dennis on 08/11/16. */ /* * action types */ export const KNOWLEDGEBASE_CHANGE = 'KNOWLEDGEBASE_CHANGE' /* * other constants */ /* * action creators */ export function setKnowledgebase(k){ return function (dispatch) { dispatch({type: KNOWLEDGEBASE_CHANGE, knowledgebase: k}); } }
import Component from '@ember/component'; import layout from '../templates/components/slds-dropdown-item'; export default Component.extend({ layout, tagName: '', clicked: null, actions: { clicked(handler, next) { if (handler) { handler(next); } } } });
/** * Internationalization / Localization Settings * (sails.config.i18n) * * If your app will touch people from all over the world, i18n (or internationalization) * may be an important part of your international strategy. * * * For more information, check out: * http://links.sailsjs.org/docs/config/i18n */ module.exports.i18n = { // Which locales are supported? locales: ['en', 'es', 'fr', 'de'], objectNotation: true };
var searchData= [ ['m_5fcontent',['m_content',['../class_message.html#a93ebdb6d1f8da485353a83bf72b6eeb7',1,'Message']]], ['m_5fdisplay_5fsize',['m_display_size',['../class_thread_list.html#a40884e201bc524b54e2f0bea7b867f68',1,'ThreadList']]], ['m_5fhead',['m_head',['../class_message.html#a96e95c41fb7e3ce7b6306737ff7b4c5a',1,'Message']]], ['m_5fid',['m_id',['../class_message.html#ab8306aee687fa159eff881a771399572',1,'Message::m_id()'],['../class_thread.html#aadc6842ff8ad6f73bc6e09f326d51a5f',1,'Thread::m_id()']]], ['m_5fid_5fto_5fthread',['m_id_to_thread',['../class_thread_list.html#aef0577b05198bc63a497b8f911ae027c',1,'ThreadList']]], ['m_5flogger',['m_logger',['../class_message.html#aaee0cd94e6c464030a99102d67f47e34',1,'Message::m_logger()'],['../class_thread.html#aae2a38e770394c7e75c44a1c8ccc9c18',1,'Thread::m_logger()'],['../class_thread_list.html#abf184dece6392417ab7f41bb2db49775',1,'ThreadList::m_logger()']]], ['m_5fmessages',['m_messages',['../class_thread.html#a10c656c0fc31e653551bb36dd91efdc8',1,'Thread']]], ['m_5fthreads',['m_threads',['../class_thread_list.html#ac353501c80de153aaf6beb130052fa35',1,'ThreadList']]] ];
import Setting from '../models/setting'; import KhongDau from 'khong-dau'; export function getSettings(req, res) { Setting.find({ disable: false }).exec((err, settings) => { if(err) { res.json({ settings: [] }); } else { res.json({ settings }); } }) }
/** * @fileOverview first_run.js shows the necessary navigation and * design elements to be integrated into the privly-applications * bundle. */ /** * Initialize the applications by showing and hiding the proper * elements. */ function init() { // Set the nav bar to the proper domain privlyNetworkService.initializeNavigation(); privlyNetworkService.initPrivlyService( privlyNetworkService.contentServerDomain(), privlyNetworkService.showLoggedInNav, privlyNetworkService.showLoggedOutNav ); $("#messages").hide(); $("#form").show(); // Show a preview of the tooltip to the user $("#tooltip").append(Privly.glyph.getGlyphDOM()) .show() .append("<br/><br/><p>This is your Privly Glyph</p>"); } // Initialize the application document.addEventListener('DOMContentLoaded', init);
require("./46.js"); require("./93.js"); require("./186.js"); require("./372.js"); module.exports = 373;
var doc = require('dynamodb-doc'); var dynamodb = new doc.DynamoDB(); exports.handler = function(event, context) { console.log(JSON.stringify(event, null, ' ')); var bname = event.name.replace(/\W/g, ''); bname = bname.charAt(0).toUpperCase() + bname.slice(1); dynamodb.updateItem({ "TableName": "baby-names", "Key" : { name : bname }, "UpdateExpression" : "SET votes = votes + :a", "ExpressionAttributeValues" : { ":a" : 1 } }, function(err, data) { if (err) { context.done('error putting item into dynamodb failed: '+err); } else { console.log('success: '+JSON.stringify(data, null, ' ')); context.done(); } }); };
'use strict'; const autoprefixer = require('autoprefixer'); const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const ManifestPlugin = require('webpack-manifest-plugin'); const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin'); const eslintFormatter = require('react-dev-utils/eslintFormatter'); const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); const paths = require('./paths'); const getClientEnvironment = require('./env'); // Webpack uses `publicPath` to determine where the app is being served from. // It requires a trailing slash, or the file assets will get an incorrect path. const publicPath = paths.servedPath; // Some apps do not use client-side routing with pushState. // For these, "homepage" can be set to "." to enable relative asset paths. const shouldUseRelativeAssetPaths = publicPath === './'; // Source maps are resource heavy and can cause out of memory issue for large source files. const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false'; // `publicUrl` is just like `publicPath`, but we will provide it to our app // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz. const publicUrl = publicPath.slice(0, -1); // Get environment variables to inject into our app. const env = getClientEnvironment(publicUrl); // Assert this just to be safe. // Development builds of React are slow and not intended for production. if (env.stringified['process.env'].NODE_ENV !== '"production"') { throw new Error('Production builds must have NODE_ENV=production.'); } // Note: defined here because it will be used more than once. const cssFilename = 'static/css/[name].[contenthash:8].css'; // ExtractTextPlugin expects the build output to be flat. // (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27) // However, our output is structured with css, js and media folders. // To have this structure working with relative paths, we have to use custom options. const extractTextPluginOptions = shouldUseRelativeAssetPaths ? // Making sure that the publicPath goes back to to build folder. { publicPath: Array(cssFilename.split('/').length).join('../') } : {}; // This is the production configuration. // It compiles slowly and is focused on producing a fast and minimal bundle. // The development configuration is different and lives in a separate file. module.exports = { // Don't attempt to continue if there are any errors. bail: true, // We generate sourcemaps in production. This is slow but gives good results. // You can exclude the *.map files from the build during deployment. devtool: shouldUseSourceMap ? "source-map" : false, // In production, we only want to load the polyfills and the app code. entry: [require.resolve("./polyfills"), paths.appIndexJs], output: { // The build folder. path: paths.appBuild, // Generated JS file names (with nested folders). // There will be one main bundle, and one file per asynchronous chunk. // We don't currently advertise code splitting but Webpack supports it. filename: "static/js/[name].[chunkhash:8].js", chunkFilename: "static/js/[name].[chunkhash:8].chunk.js", // We inferred the "public path" (such as / or /my-project) from homepage. publicPath: publicPath, // Point sourcemap entries to original disk location (format as URL on Windows) devtoolModuleFilenameTemplate: info => path.relative(paths.appSrc, info.absoluteResourcePath).replace(/\\/g, "/") }, resolve: { // This allows you to set a fallback for where Webpack should look for modules. // We placed these paths second because we want `node_modules` to "win" // if there are any conflicts. This matches Node resolution mechanism. // https://github.com/facebookincubator/create-react-app/issues/253 modules: ["node_modules", paths.appNodeModules].concat( // It is guaranteed to exist because we tweak it in `env.js` process.env.NODE_PATH.split(path.delimiter).filter(Boolean) ), // These are the reasonable defaults supported by the Node ecosystem. // We also include JSX as a common component filename extension to support // some tools, although we do not recommend using it, see: // https://github.com/facebookincubator/create-react-app/issues/290 // `web` extension prefixes have been added for better support // for React Native Web. extensions: [".web.js", ".mjs", ".js", ".json", ".web.jsx", ".jsx"], alias: { // Support React Native Web // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ "react-native": "react-native-web" }, plugins: [ // Prevents users from importing files from outside of src/ (or node_modules/). // This often causes confusion because we only process files within src/ with babel. // To fix this, we prevent you from importing files out of src/ -- if you'd like to, // please link the files into your node_modules/ and let module-resolution kick in. // Make sure your source files are compiled, as they will not be processed in any way. new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]) ] }, module: { strictExportPresence: true, rules: [ // TODO: Disable require.ensure as it's not a standard language feature. // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176. // { parser: { requireEnsure: false } }, // First, run the linter. // It's important to do this before Babel processes the JS. { test: /\.(js|jsx|mjs)$/, enforce: "pre", use: [ { options: { formatter: eslintFormatter, eslintPath: require.resolve("eslint") }, loader: require.resolve("eslint-loader") } ], include: paths.appSrc }, { // "oneOf" will traverse all following loaders until one will // match the requirements. When no loader matches it will fall // back to the "file" loader at the end of the loader list. oneOf: [ // "url" loader works just like "file" loader but it also embeds // assets smaller than specified size as data URLs to avoid requests. { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], loader: require.resolve("url-loader"), options: { limit: 10000, name: "static/media/[name].[hash:8].[ext]" } }, // Process JS with Babel. { test: /\.(js|jsx|mjs)$/, include: paths.appSrc, loader: require.resolve("babel-loader"), options: { compact: true } }, // The notation here is somewhat confusing. // "postcss" loader applies autoprefixer to our CSS. // "css" loader resolves paths in CSS and adds assets as dependencies. // "style" loader normally turns CSS into JS modules injecting <style>, // but unlike in development configuration, we do something different. // `ExtractTextPlugin` first applies the "postcss" and "css" loaders // (second argument), then grabs the result CSS and puts it into a // separate file in our build process. This way we actually ship // a single CSS file in production instead of JS code injecting <style> // tags. If you use code splitting, however, any async bundles will still // use the "style" loader inside the async code so CSS from them won't be // in the main CSS file. { test: /\.(css|scss)$/, loader: ExtractTextPlugin.extract( Object.assign( { fallback: { loader: require.resolve("style-loader"), options: { hmr: false } }, use: [ { loader: require.resolve("css-loader"), options: { importLoaders: 1, minimize: true, modules: true, localIdentName: "[path][name]__[local]--[hash:base64:5]", sourceMap: shouldUseSourceMap, camelCase: "dashes" } }, { loader: require.resolve("postcss-loader"), options: { // Necessary for external CSS imports to work // https://github.com/facebookincubator/create-react-app/issues/2677 ident: "postcss", plugins: () => [ require("postcss-flexbugs-fixes"), autoprefixer({ browsers: [ ">1%", "last 4 versions", "Firefox ESR", "not ie < 9" // React doesn't support IE8 anyway ], flexbox: "no-2009" }) ], sourceMap: true } }, { loader: require.resolve("sass-loader"), options: { sourceMap: true, data: `@import "${ paths.appSrc }/config/_variables.scss";` } } ] }, extractTextPluginOptions ) ) // Note: this won't work without `new ExtractTextPlugin()` in `plugins`. }, // "file" loader makes sure assets end up in the `build` folder. // When you `import` an asset, you get its filename. // This loader doesn't use a "test" so it will catch all modules // that fall through the other loaders. { loader: require.resolve("file-loader"), // Exclude `js` files to keep "css" loader working as it injects // it's runtime that would otherwise processed through "file" loader. // Also exclude `html` and `json` extensions so they get processed // by webpacks internal loaders. exclude: [/\.js$/, /\.html$/, /\.json$/], options: { name: "static/media/[name].[hash:8].[ext]" } } // ** STOP ** Are you adding a new loader? // Make sure to add the new loader(s) before the "file" loader. ] } ] }, plugins: [ // Makes some environment variables available in index.html. // The public URL is available as %PUBLIC_URL% in index.html, e.g.: // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> // In production, it will be an empty string unless you specify "homepage" // in `package.json`, in which case it will be the pathname of that URL. new InterpolateHtmlPlugin(env.raw), // Generates an `index.html` file with the <script> injected. new HtmlWebpackPlugin({ inject: true, template: paths.appHtml, minify: { removeComments: true, collapseWhitespace: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeStyleLinkTypeAttributes: true, keepClosingSlash: true, minifyJS: true, minifyCSS: true, minifyURLs: true } }), // Makes some environment variables available to the JS code, for example: // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`. // It is absolutely essential that NODE_ENV was set to production here. // Otherwise React will be compiled in the very slow development mode. new webpack.DefinePlugin(env.stringified), // Minify the code. new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, // Disabled because of an issue with Uglify breaking seemingly valid code: // https://github.com/facebookincubator/create-react-app/issues/2376 // Pending further investigation: // https://github.com/mishoo/UglifyJS2/issues/2011 comparisons: false }, mangle: { safari10: true }, output: { comments: false, // Turned on because emoji and regex is not minified properly using default // https://github.com/facebookincubator/create-react-app/issues/2488 ascii_only: true }, sourceMap: shouldUseSourceMap }), // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`. new ExtractTextPlugin({ filename: cssFilename }), // Generate a manifest file which contains a mapping of all asset filenames // to their corresponding output file so that tools can pick it up without // having to parse `index.html`. new ManifestPlugin({ fileName: "asset-manifest.json" }), // Generate a service worker script that will precache, and keep up to date, // the HTML & assets that are part of the Webpack build. new SWPrecacheWebpackPlugin({ // By default, a cache-busting query parameter is appended to requests // used to populate the caches, to ensure the responses are fresh. // If a URL is already hashed by Webpack, then there is no concern // about it being stale, and the cache-busting can be skipped. dontCacheBustUrlsMatching: /\.\w{8}\./, filename: "service-worker.js", logger(message) { if (message.indexOf("Total precache size is") === 0) { // This message occurs for every build and is a bit too noisy. return; } if (message.indexOf("Skipping static resource") === 0) { // This message obscures real errors so we ignore it. // https://github.com/facebookincubator/create-react-app/issues/2612 return; } console.log(message); }, minify: true, // For unknown URLs, fallback to the index page navigateFallback: publicUrl + "/index.html", // Ignores URLs starting from /__ (useful for Firebase): // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219 navigateFallbackWhitelist: [/^(?!\/__).*/], // Don't precache sourcemaps (they're large) and build asset manifest: staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/] }), // Moment.js is an extremely popular library that bundles large locale files // by default due to how Webpack interprets its code. This is a practical // solution that requires the user to opt into importing specific locales. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack // You can remove this if you don't use Moment.js: new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/) ], // Some libraries import Node modules but don't use them in the browser. // Tell Webpack to provide empty mocks for them so importing them works. node: { dgram: "empty", fs: "empty", net: "empty", tls: "empty", child_process: "empty" } };
'use strict'; // Author: ThemeREX.com // user-interface-buttons.html scripts // (function($) { "use strict"; // Init Theme Core Core.init(); // Init Demo JS Demo.init(); // Init Ladda Plugin Ladda.bind('.ladda-button', { timeout: 2000 }); // Simulate loading progress on buttons with ".ladda-button" class Ladda.bind('.progress-button', { callback: function(instance) { var progress = 0; var interval = setInterval(function() { progress = Math.min(progress + Math.random() * 0.1, 1); instance.setProgress(progress); if (progress === 1) { instance.stop(); clearInterval(interval); } }, 200); } }); })(jQuery);
'use strict'; // Teams controller angular.module('teams').controller('TeamsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Teams', 'Players', '$filter', function($scope, $stateParams, $location, Authentication, Teams, Players, $filter) { $scope.authentication = Authentication; // Create new Team $scope.create = function() { // Create new Team object var team = new Teams ({ name: this.name }); // Redirect after save team.$save(function(response) { $location.path('teams/' + response._id); // Clear form fields $scope.name = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Team $scope.remove = function(team) { if ( team ) { team.$remove(); for (var i in $scope.teams) { if ($scope.teams [i] === team) { $scope.teams.splice(i, 1); } } } else { $scope.team.$remove(function() { $location.path('teams'); }); } }; // Update existing Team $scope.update = function() { var team = $scope.team; team.$update(function() { $location.path('teams/' + team._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Find a list of Teams $scope.find = function() { $scope.teams = Teams.query(); }; // Find existing Team $scope.findOne = function() { $scope.team = Teams.get({ teamId: $stateParams.teamId }); $scope.players = Players.query({ 'team': $stateParams.teamId }); }; } ]);
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ /* eslint no-console: ["error", { allow: ["log"] }] */ const gulp = require('gulp'); const modifyFile = require('gulp-modify-file'); const path = require('path'); const rollup = require('rollup'); const buble = require('rollup-plugin-buble'); const replace = require('rollup-plugin-replace'); const commonjs = require('rollup-plugin-commonjs'); const resolve = require('rollup-plugin-node-resolve'); const vue = require('rollup-plugin-vue'); function buildKs(cb) { const env = process.env.NODE_ENV || 'development'; const target = process.env.TARGET || 'universal'; const buildPath = env === 'development' ? './build' : './packages'; let f7VuePath = path.resolve(__dirname, `../${buildPath}/vue/framework7-vue.esm.js`); let f7Path = path.resolve(__dirname, `../${buildPath}/core/framework7.esm.bundle`); if (process.platform.indexOf('win') === 0) { f7VuePath = f7VuePath.replace(/\\/g, '/'); f7Path = f7Path.replace(/\\/g, '/'); } gulp.src('./kitchen-sink/vue/index.html') .pipe(modifyFile((content) => { if (env === 'development') { return content .replace('../../packages/core/css/framework7.min.css', '../../build/core/css/framework7.css') .replace('../../packages/core/js/framework7.min.js', '../../build/core/js/framework7.js'); } return content .replace('../../build/core/css/framework7.css', '../../packages/core/css/framework7.min.css') .replace('../../build/core/js/framework7.js', '../../packages/core/js/framework7.min.js'); })) .pipe(gulp.dest('./kitchen-sink/vue')); rollup.rollup({ input: './kitchen-sink/vue/src/app.js', plugins: [ replace({ delimiters: ['', ''], 'process.env.NODE_ENV': JSON.stringify(env), 'process.env.TARGET': JSON.stringify(target), "'framework7-vue'": () => `'${f7VuePath}'`, "'framework7/framework7.esm.bundle'": () => `'${f7Path}'`, }), resolve({ jsnext: true }), commonjs(), vue(), buble({ objectAssign: 'Object.assign', }), ], onwarn(warning, warn) { const ignore = ['EVAL']; if (warning.code && ignore.indexOf(warning.code) >= 0) { return; } warn(warning); }, }).then(bundle => bundle.write({ format: 'umd', name: 'app', strict: true, sourcemap: false, file: './kitchen-sink/vue/js/app.js', })).then(() => { if (cb) cb(); }).catch((err) => { console.log(err); if (cb) cb(); }); } module.exports = buildKs;
import {expect} from 'chai'; import {camel_case} from '../src'; describe('CamelCase', () => { it('should be exists.', () => { expect(camel_case).to.be.exists; }); it('should convert helloThere to HelloThere.', () => { expect(camel_case('helloThere')).to.be.equals('HelloThere'); }); it('should convert i_am_a_robot to IAmARobot.', () => { expect(camel_case('i_am_a_robot')).to.be.equals('IAmARobot'); }); });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _base = require('./base'); var _base2 = _interopRequireDefault(_base); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var config = { appEnv: 'test' // don't remove the appEnv property here }; exports.default = Object.freeze(Object.assign(_base2.default, config));
import React from 'react' import ColorWheel from './ColorWheel.jsx' React.render(<ColorWheel title='ColorWheel' />, document.querySelector('#color-wheel'))
const uAPI = require('../../index'); const config = require('../../test/testconfig'); const AirService = uAPI.createAirService( { auth: config, debug: 2, production: false, } ); const AirServiceQuiet = uAPI.createAirService( { auth: config, production: false, } ); const requestPTC = 'ADT'; const shop_params = { legs: [ { from: 'LOS', to: 'IST', departureDate: '2019-06-18', }, { from: 'IST', to: 'LOS', departureDate: '2019-06-21', }, ], passengers: { [requestPTC]: 1, }, cabins: ['Economy'], requestId: 'test', }; AirServiceQuiet.shop(shop_params) .then((results) => { const forwardSegments = results['0'].directions['0']['0'].segments; const backSegments = results['0'].directions['1']['0'].segments; const farerules_params = { segments: forwardSegments.concat(backSegments), passengers: shop_params.passengers, long: true, requestId: 'test', }; return AirService.fareRules(farerules_params); }) .then( (res) => { console.log(JSON.stringify(res)); }, err => console.error(err) ).catch((err) => { console.error(err); });
var objc = require('../') objc.dlopen('/System/Library/Frameworks/AppKit.framework/AppKit'); NSApplication = objc.objc_getClass('NSApplication'); console.log(NSApplication); var sharedApplication = objc.sel_registerName('sharedApplication'); var app = objc.objc_msgSend(NSApplication, sharedApplication); console.log(app);
/* * Elfenben - Javascript using tree syntax! This is the compiler written in javascipt * */ var version = "1.0.16", banner = "// Generated by Elfenben v" + version + "\n", isWhitespace = /\s/, isFunction = /^function\b/, validName = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/, noReturn = /^var\b|^set\b|^throw\b/, isHomoiconicExpr = /^#args-if\b|^#args-shift\b|^#args-second\b/, noSemiColon = false, indentSize = 4, indent = -indentSize, keywords = {}, macros = {}, errors = [], include_dirs = [__dirname + "/../includes", "includes"], fs, path, SourceNode = require('source-map').SourceNode if (typeof window === "undefined") { fs = require('fs') path = require('path') } if (!String.prototype.repeat) { String.prototype.repeat = function(num) { return new Array(num + 1).join(this) } } var parse = function(code, filename) { code = "(" + code + ")" var length = code.length, pos = 1, lineno = 1, colno = 1, token_begin_colno = 1 var parser = function() { var tree = [], token = "", isString = false, isSingleString = false, isJSArray = 0, isJSObject = 0, isListComplete = false, isComment = false, isRegex = false, isEscape = false, handleToken = function() { if (token) { tree.push(new SourceNode(lineno, token_begin_colno - 1, filename, token, token)) token = "" } } tree._line = lineno tree._filename = filename while (pos < length) { var c = code.charAt(pos) pos++ colno++ if (c == "\n") { lineno++ colno = 1 if (isComment) { isComment = false } } if (isComment) { continue } if (isEscape) { isEscape = false token += c continue } // strings if (c == '"' || c == '`') { isString = !isString token += c continue } if (isString) { if (c === "\n") { token += "\\n" } else { if (c === "\\") { isEscape = true } token += c } continue } if (c == "'") { isSingleString = !isSingleString token += c continue } if (isSingleString) { token += c continue } // data types if (c == '[') { isJSArray++ token += c continue } if (c == ']') { if (isJSArray === 0) { handleError(4, tree._line, tree._filename) } isJSArray-- token += c continue } if (isJSArray) { token += c continue } if (c == '{') { isJSObject++ token += c continue } if (c == '}') { if (isJSObject === 0) { handleError(6, tree._line, tree._filename) } isJSObject-- token += c continue } if (isJSObject) { token += c continue } if (c == ";") { isComment = true continue } // regex // regex in function position with first char " " is a prob. Use \s instead. if (c === "/" && !(tree.length === 0 && token.length === 0 && isWhitespace.test(code.charAt(pos)))) { isRegex = !isRegex token += c continue } if (isRegex) { if (c === "\\") { isEscape = true } token += c continue } if (c == "(") { handleToken() // catch e.g. "blah(" token_begin_colno = colno tree.push(parser()) continue } if (c == ")") { isListComplete = true handleToken() token_begin_colno = colno break } if (isWhitespace.test(c)) { if (c == '\n') lineno-- handleToken() if (c == '\n') lineno++ token_begin_colno = colno continue } token += c } if (isString) handleError(3, tree._line, tree._filename) if (isRegex) handleError(14, tree._line, tree._filename) if (isSingleString) handleError(3, tree._line, tree._filename) if (isJSArray > 0) handleError(5, tree._line, tree._filename) if (isJSObject > 0) handleError(7, tree._line, tree._filename) if (!isListComplete) handleError(8, tree._line, tree._filename) return tree } var ret = parser() if (pos < length) { handleError(10) } return ret } var handleExpressions = function(exprs) { indent += indentSize var ret = new SourceNode(), l = exprs.length, indentstr = " ".repeat(indent) exprs.forEach(function(expr, i, exprs) { var exprName, tmp = null, r = "" if (Array.isArray(expr)) { exprName = expr[0].name if (exprName === "include") ret.add(handleExpression(expr)) else tmp = handleExpression(expr) } else { tmp = expr } if (i === l - 1 && indent) { if (!noReturn.test(exprName)) r = "return " } if (tmp) { var endline = noSemiColon ? "\n" : ";\n" noSemiColon = false ret.add([indentstr + r, tmp, endline]) } }) indent -= indentSize return ret } var handleExpression = function(expr) { if (!expr || !expr[0]) { return null } var command = expr[0].name if (macros[command]) { expr = macroExpand(expr) if (Array.isArray(expr)) { return handleExpression(expr) } else { return expr } } if (typeof command === "string") { if (keywords[command]) { return keywords[command](expr) } if (command.charAt(0) === ".") { var ret = new SourceNode() ret.add(Array.isArray(expr[1]) ? handleExpression(expr[1]) : expr[1]) ret.prepend("(") ret.add([")", expr[0]]) return ret } } handleSubExpressions(expr) var fName = expr[0] if (!fName) { handleError(1, expr._line) } if (isFunction.test(fName)) fName = new SourceNode(null, null, null, ['(', fName, ')']) exprNode = new SourceNode (null, null, null, expr.slice(1)).join(",") return new SourceNode (null, null, null, [fName, "(", exprNode, ")"]) } var handleSubExpressions = function(expr) { expr.forEach(function(value, i, t) { if (Array.isArray(value)) t[i] = handleExpression(value) }) } var macroExpand = function(tree) { var command = tree[0].name, template = macros[command]["template"], code = macros[command]["code"], replacements = {} for (var i = 0; i < template.length; i++) { if (template[i].name == "rest...") { replacements["~rest..."] = tree.slice(i + 1) } else { if (tree.length === i + 1) { // we are here if any macro arg is not set handleError(12, tree._line, tree._filename, command) } replacements["~" + template[i].name] = tree[i + 1] } } var replaceCode = function(source) { var ret = [] ret._line = tree._line ret._filename = tree._filename // Handle homoiconic expressions in macro var expr_name = source[0] ? source[0].name : "" if (isHomoiconicExpr.test(expr_name)) { var replarray = replacements["~" + source[1].name] if (expr_name === "#args-shift") { if (!Array.isArray(replarray)) { handleError(13, tree._line, tree._filename, command) } var argshift = replarray.shift() if (typeof argshift === "undefined") { handleError(12, tree._line, tree._filename, command) } return argshift } if (expr_name === "#args-second") { if (!Array.isArray(replarray)) { handleError(13, tree._line, tree._filename, command) } var argsecond = replarray.splice(1, 1)[0] if (typeof argsecond === "undefined") { handleError(12, tree._line, tree._filename, command) } return argsecond } if (expr_name === "#args-if") { if (!Array.isArray(replarray)) { handleError(13, tree._line, tree._filename, command) } if (replarray.length) { return replaceCode(source[2]) } else if (source[3]) { return replaceCode(source[3]) } else { return } } } for (var i = 0; i < source.length; i++) { if (Array.isArray(source[i])) { var replcode = replaceCode(source[i]) if (typeof replcode !== "undefined") { ret.push(replcode) } } else { var token = source[i], tokenbak = token, isATSign = false if (token.name.indexOf("@") >= 0) { isATSign = true tokenbak = new SourceNode(token.line, token.column, token.source, token.name.replace("@", ""), token.name.replace("@", "")) } if (replacements[tokenbak.name]) { var repl = replacements[tokenbak.name] if (isATSign || tokenbak.name == "~rest...") { for (var j = 0; j < repl.length; j++) { ret.push(repl[j]) } } else { ret.push(repl) } } else { ret.push(token) } } } return ret } return replaceCode(code) } var handleCompOperator = function(arr) { if (arr.length < 3) handleError(0, arr._line) handleSubExpressions(arr) if (arr[0] == "=") arr[0] = "===" if (arr[0] == "!=") arr[0] = "!==" var op = arr.shift() var ret = new SourceNode() for (i = 0; i < arr.length - 1; i++) ret.add (new SourceNode (null, null, null, [arr[i], " ", op, " ", arr[i + 1]])) ret.join (' && ') ret.prepend('(') ret.add(')') return ret } var handleArithOperator = function(arr) { if (arr.length < 3) handleError(0, arr._line) handleSubExpressions(arr) var op = new SourceNode() op.add([" ", arr.shift(), " "]) var ret = new SourceNode() ret.add(arr) ret.join (op) ret.prepend("(") ret.add(")") return ret } var handleLogicalOperator = handleArithOperator var handleVariableDeclarations = function(arr, varKeyword){ if (arr.length < 3) handleError(0, arr._line, arr._filename) if (arr.length > 3) { indent += indentSize } handleSubExpressions(arr) var ret = new SourceNode () ret.add(varKeyword + " ") for (var i = 1; i < arr.length; i = i + 2) { if (i > 1) { ret.add(",\n" + " ".repeat(indent)) } if (!validName.test(arr[i])) handleError(9, arr._line, arr._filename) ret.add([arr[i], ' = ', arr[i + 1]]) } if (arr.length > 3) { indent -= indentSize } return ret } keywords["var"] = function(arr) { return handleVariableDeclarations(arr, "var") } keywords["const"] = function(arr) { return handleVariableDeclarations(arr, "const") } keywords["let"] = function(arr) { return handleVariableDeclarations(arr, "let") } keywords["new"] = function(arr) { if (arr.length < 2) handleError(0, arr._line, arr._filename) var ret = new SourceNode() ret.add(handleExpression(arr.slice(1))) ret.prepend ("new ") return ret } keywords["throw"] = function(arr) { if (arr.length != 2) handleError(0, arr._line, arr._filename) var ret = new SourceNode() ret.add(Array.isArray(arr[1]) ? handleExpression(arr[1]) : arr[1]) ret.prepend("(function(){throw ") ret.add(";})()") return ret } keywords["set"] = function(arr) { if (arr.length < 3 || arr.length > 4) handleError(0, arr._line, arr._filename) if (arr.length == 4) { arr[1] = (Array.isArray(arr[2]) ? handleExpression(arr[2]) : arr[2]) + "[" + arr[1] + "]" arr[2] = arr[3] } return new SourceNode(null, null, null, [arr[1], " = ", (Array.isArray(arr[2]) ? handleExpression(arr[2]) : arr[2])]) } keywords["function"] = function(arr) { var ret var fName, fArgs, fBody if (arr.length < 2) handleError(0, arr._line, arr._filename) if(Array.isArray(arr[1])) { // an anonymous function fArgs = arr[1] fBody = arr.slice(2) } else if(!Array.isArray(arr[1]) && Array.isArray(arr[2])) { // a named function fName = arr[1] fArgs = arr[2] fBody = arr.slice(3) } else handleError(0, arr._line) ret = new SourceNode(null, null, null, fArgs) ret.join(",") ret.prepend("function" + (fName ? " " + fName.name : "") + "(") ret.add([") {\n",handleExpressions(fBody), " ".repeat(indent), "}"]) if(fName) noSemiColon = true return ret } keywords["try"] = function(arr) { if (arr.length < 3) handleError(0, arr._line, arr._filename) var c = arr.pop(), ind = " ".repeat(indent), ret = new SourceNode() ret.add(["(function() {\n" + ind + "try {\n", handleExpressions(arr.slice(1)), "\n" + ind + "} catch (e) {\n" + ind + "return (", (Array.isArray(c) ? handleExpression(c) : c), ")(e);\n" + ind + "}\n" + ind + "})()"]) return ret } keywords["if"] = function(arr) { if (arr.length < 3 || arr.length > 4) handleError(0, arr._line, arr._filename) indent += indentSize handleSubExpressions(arr) var ret = new SourceNode() ret.add(["(", arr[1], " ?\n" + " ".repeat(indent), arr[2], " :\n" + " ".repeat(indent), (arr[3] || "undefined"), ")"]) indent -= indentSize return ret } keywords["get"] = function(arr) { if (arr.length != 3) handleError(0, arr._line, arr._filename) handleSubExpressions(arr) return new SourceNode(null, null, null, [arr[2], "[", arr[1], "]"]) } keywords["str"] = function(arr) { if (arr.length < 2) handleError(0, arr._line, arr._filename) handleSubExpressions(arr) var ret = new SourceNode() ret.add(arr.slice(1)) ret.join (",") ret.prepend("[") ret.add("].join('')") return ret } keywords["array"] = function(arr) { var ret = new SourceNode() if (arr.length == 1) { ret.add("[]") return ret } indent += indentSize handleSubExpressions(arr) ret.add("[\n" + " ".repeat(indent)) for (var i = 1; i < arr.length; ++i) { if (i > 1) { ret.add(",\n" + " ".repeat(indent)) } ret.add(arr[i]) } indent -= indentSize ret.add("\n" + " ".repeat(indent) + "]") return ret } keywords["object"] = function(arr) { var ret = new SourceNode() if (arr.length == 1) { ret.add("{}") return ret } indent += indentSize handleSubExpressions(arr) ret.add("{\n" + " ".repeat(indent)) for (var i = 1; i < arr.length; i = i + 2) { if (i > 1) { ret.add(",\n" + " ".repeat(indent)) } ret.add([arr[i], ': ', arr[i + 1]]) } indent -= indentSize ret.add("\n" + " ".repeat(indent) + "}") return ret } var includeFile = (function () { var included = [] return function(filename) { if (included.indexOf(filename) !== -1) return "" included.push(filename) var code = fs.readFileSync(filename) var tree = parse(code, filename) return handleExpressions(tree) } })() keywords["include"] = function(arr) { if (arr.length != 2) handleError(0, arr._line, arr._filename) indent -= indentSize var filename = arr[1].name if (typeof filename === "string") filename = filename.replace(/["']/g, "") var found = false; include_dirs.concat([path.dirname(arr._filename)]) .forEach(function(prefix) { if (found) { return; } try { filename = fs.realpathSync(prefix + '/' +filename) found = true; } catch (err) { } }); if (!found) { handleError(11, arr._line, arr._filename) } var ret = new SourceNode() ret = includeFile(filename) indent += indentSize return ret } keywords["javascript"] = function(arr) { if (arr.length != 2) handleError(0, arr._line, arr._filename) noSemiColon = true arr[1].replaceRight(/"/g, '') return arr[1] } keywords["macro"] = function(arr) { if (arr.length != 4) handleError(0, arr._line, arr._filename) macros[arr[1].name] = {template: arr[2], code: arr[3]} return "" } keywords["+"] = handleArithOperator keywords["-"] = handleArithOperator keywords["*"] = handleArithOperator keywords["/"] = handleArithOperator keywords["%"] = handleArithOperator keywords["="] = handleCompOperator keywords["!="] = handleCompOperator keywords[">"] = handleCompOperator keywords[">="] = handleCompOperator keywords["<"] = handleCompOperator keywords["<="] = handleCompOperator keywords["||"] = handleLogicalOperator keywords["&&"] = handleLogicalOperator keywords["!"] = function(arr) { if (arr.length != 2) handleError(0, arr._line, arr._filename) handleSubExpressions(arr) return "(!" + arr[1] + ")" } var handleError = function(no, line, filename, extra) { throw new Error(errors[no] + ((extra) ? " - " + extra : "") + ((line) ? "\nLine no " + line : "") + ((filename) ? "\nFile " + filename : "")) } errors[0] = "Syntax Error" errors[1] = "Empty statement" errors[2] = "Invalid characters in function name" errors[3] = "End of File encountered, unterminated string" errors[4] = "Closing square bracket, without an opening square bracket" errors[5] = "End of File encountered, unterminated array" errors[6] = "Closing curly brace, without an opening curly brace" errors[7] = "End of File encountered, unterminated javascript object '}'" errors[8] = "End of File encountered, unterminated parenthesis" errors[9] = "Invalid character in var name" errors[10] = "Extra chars at end of file. Maybe an extra ')'." errors[11] = "Cannot Open include File" errors[12] = "Invalid no of arguments to " errors[13] = "Invalid Argument type to " errors[14] = "End of File encountered, unterminated regular expression" var _compile = function(code, filename, withSourceMap, a_include_dirs) { indent = -indentSize if (a_include_dirs) include_dirs = a_include_dirs var tree = parse(code, filename) var outputNode = handleExpressions(tree) outputNode.prepend(banner) if (withSourceMap) { var outputFilename = path.basename(filename, '.elf') + '.js' var sourceMapFile = outputFilename + '.map' var output = outputNode.toStringWithSourceMap({ file: outputFilename }); fs.writeFileSync(sourceMapFile, output.map) return output.code + "\n//# sourceMappingURL=" + path.relative(path.dirname(filename), sourceMapFile); } else return outputNode.toString() } exports.version = version exports._compile = _compile exports.parseWithSourceMap = function(code, filename) { var tree = parse(code, filename) var outputNode = handleExpressions(tree) outputNode.prepend(banner) return outputNode.toStringWithSourceMap(); }
/** * Created by Dennis Schwartz on 16/12/15. */ var THREE = require('three'); var TrackballControls = require('three.trackball'); var OrthographicTrackballControls = require('three.orthographictrackball'); var Layouts = require('./layouts'); var Fixed = Layouts.connectedMultilayer; var ForceDirectedLayered = Layouts.independentMultilayer; var Manual = Layouts.manual; var R = require('ramda'); var Defaults = require('./defaults'); function Graphics ( state ) { var stable = false; var maxWeight = state.elements.maxWeight; // Attach the current three instance to the state state.THREE = THREE; /* Create the three.js canvas/WebGL renderer */ state.renderer = createRenderer( state.visEl ); state.scene = new THREE.Scene(); createCamera( state ); /* Create Layout with elements in state */ var layout = createLayout( state ); /* Layouts specify renderers and UI builders */ var nodeRenderer = layout.nodeRenderer; //var linkRenderer = layout.linkRenderer; /** * This sets the default node rendering function */ //var linkRenderer = function ( link ) { // console.log(link); // console.log(state.elements.elements[link.from]); // // var from = nodeUI[link.from.substring(2)]; // var to = nodeUI[link.to.substring(2)]; // link.geometry.vertices[0].set(from.position.x, // from.position.y, // from.position.z); // link.geometry.vertices[1].set(to.position.x, // to.position.y, // to.position.z); // link.geometry.verticesNeedUpdate = true; //}; var nodeUIBuilder = layout.nodeUIBuilder; var linkUIBuilder = layout.linkUIBuilder; /* Create ui (look) of every element and add it to the element object */ var nodes = state.elements.nodelayers; // TODO: Save only IDs in these lists var edges = state.elements.edges; nodes.forEach(function (n) { createNodeUI(state.elements.elements['nl' + n.data.id]); }); edges.forEach(function (e) { var toID = e.data.target.substring(2); var fromID = e.data.source.substring(2); var link = state.elements.elements[ 'e' + fromID + toID ]; createLinkUI(link); }); console.log(state); /* Create controls if set */ /** * Create the UI for each node-layer in the network and add them to the scene * @param node */ function createNodeUI(node) { if (!node.ui) { node.ui = nodeUIBuilder(node); console.log('hello!'); node.position = layout.getNodePosition(node); var layers = R.map(function (i) { return i.data['id'] }, state.elements.layers); node.position.z = layers.indexOf('l' + node.data['layer']) * state.interLayerDistance; } state.scene.add(node.ui); //console.log("added"); //console.log(node.ui); } /** * Create the UI for each link and add it to the scene * @param link */ function createLinkUI(link) { if (!link.ui) { var from = link.data['source']; var to = link.data['target']; link.ui = linkUIBuilder(link); link.ui.from = from; link.ui.to = to; } state.scene.add(link.ui); } /** * This is the main Animation loop calling requestAnimationFrame on window * which in turn calls back to this function */ function run () { //if ( stop ) return; window.requestAnimationFrame( run ); if (!stable) { stable = layout.step(); } renderFrame (); state.controls.update (); } /** * Create three.js state * @param state * @returns {THREE.PerspectiveCamera} */ function createCamera ( state ) { var container = state.renderer.domElement; var camera; var controls; if ( state.cameraType === 'orthographic' ) { // Create camera camera = new THREE.OrthographicCamera( container.width / 2, container.width / -2, container.height / 2, container.height / -2, 1, 1000 ); camera.position.x = 200; camera.position.y = 100; camera.position.z = 300; camera.lookAt(state.scene.position); // Create corresponding controls if necessary if ( state.zoomingEnabled ) controls = new OrthographicTrackballControls(camera, state.renderer.domElement); } else { // Default case camera = new THREE.PerspectiveCamera(45, container.clientWidth / container.clientHeight, 0.1, 30000); if ( state.zoomingEnabled ) controls = new TrackballControls(camera, state.renderer.domElement); } camera.position.z = 400; state.camera = camera; if (state.zoomingEnabled) { controls.panSpeed = 0.8; controls.staticMoving = true; controls.dynamicDampingFactor = 0.3; controls.addEventListener('change', renderFrame); state.controls = controls; } } /** * This function calculates and sets * the current position of each ui-element each frame. */ function renderFrame() { //Alternative version nodes.forEach(function ( node ) { var n = state.elements.elements[ 'nl' + node.data.id ]; nodeRenderer( n ); }); if ( state.directed ) { var arrowScale = 0.25; edges.forEach(function ( edge ) { var toID = edge.data.target.substring(2); var fromID = edge.data.source.substring(2); var link = state.elements.elements[ 'e' + fromID + toID ]; var from = state.elements.elements[ edge.data.source ]; var to = state.elements.elements[ edge.data.target ]; var newSourcePos = new THREE.Vector3(from.ui.position.x, from.ui.position.y, from.ui.position.z); var newTargetPos = new THREE.Vector3(to.ui.position.x, to.ui.position.y, to.ui.position.z); var arrowVec = newTargetPos.clone().sub(newSourcePos); // targetPos + norm(neg(arrowVec)) * (nodesize / 2) var nodeRadVec = arrowVec.clone().negate().normalize().multiplyScalar(state.nodesize || 6); var cursor = newTargetPos.clone().add(nodeRadVec); // point link.ui.geometry.vertices[0].set(cursor.x, cursor.y, cursor.z); link.ui.geometry.vertices[3].set(cursor.x, cursor.y, cursor.z); cursor.add(nodeRadVec.multiplyScalar(1.5)); //arrowHeadBase var arrowHeadBase = cursor.clone(); var flanker = nodeRadVec.clone().cross(new THREE.Vector3(0,0,1)).multiplyScalar(arrowScale); var w = link.data.weight || 1; var factor = 1; if ( maxWeight === 0 ) { factor = .6 - (.6 / (w + .1)); } else { if ( state.normalisation === 'log' ) { factor = 0.6 * ( Math.log(w) / Math.log(maxWeight) ); } else { factor = 0.6 * ( w / maxWeight ); } } var ribboner = flanker.clone().multiplyScalar(factor); var flank1 = cursor.clone().add(flanker); //flank 1 link.ui.geometry.vertices[1].set(flank1.x, flank1.y, flank1.z); flanker.add(flanker.negate().multiplyScalar(arrowScale * 2)); cursor.add(flanker); //flank 2 link.ui.geometry.vertices[2].set(cursor.x, cursor.y, cursor.z); // Move to Ribbon 1 cursor = arrowHeadBase.clone().add(ribboner); link.ui.geometry.vertices[4].set(cursor.x, cursor.y, cursor.z); // Move to Ribbon 2 cursor = arrowHeadBase.clone().add(ribboner.negate()); link.ui.geometry.vertices[5].set(cursor.x, cursor.y, cursor.z); var temp = newTargetPos.clone().add(newSourcePos).divideScalar(2); // Move to source // RibbonSrc1 cursor = newSourcePos.clone().add(ribboner).add(nodeRadVec.negate().multiplyScalar(1.3)); link.ui.geometry.vertices[6].set(cursor.x, cursor.y, cursor.z); // RibbonSrc2 cursor = newSourcePos.clone().add(ribboner.negate()).add(nodeRadVec); link.ui.geometry.vertices[7].set(cursor.x, cursor.y, cursor.z); link.ui.material.color.set(0x000000); //link.ui.material.transparent = true; //link.ui.material.opacity = 0.4; link.ui.geometry.verticesNeedUpdate = true; //link.ui.geometry.elementsNeedUpdate = true; //var distance = newSourcePos.distanceTo(newTargetPos); //var position = newTargetPos.clone().add(newSourcePos).divideScalar(2); //var orientation = new THREE.Matrix4();//a new orientation matrix to offset pivot //var offsetRotation = new THREE.Matrix4();//a matrix to fix pivot rotation //var offsetPosition = new THREE.Matrix4();//a matrix to fix pivot position //orientation.lookAt(newSourcePos, newTargetPos, new THREE.Vector3(0,1,0)); //offsetRotation.makeRotationX(HALF_PI);//rotate 90 degs on X //orientation.multiply(offsetRotation);//combine orientation with rotation transformations //var cylinder = link.ui.geometry;//new THREE.CylinderGeometry(1.2,1.2,distance,1,1,false); ////cylinder.applyMatrix(orientation); //link.ui.scale.y = distance; //link.ui.geometry = cylinder; //link.ui.position.set(position.x, position.y, position.z); //console.log("After"); //console.log(link.ui); }); } else { edges.forEach(function ( edge ) { var toID = edge.data.target.substring(2); var fromID = edge.data.source.substring(2); var link = state.elements.elements[ 'e' + fromID + toID ]; var from = state.elements.elements[ edge.data.source ]; var to = state.elements.elements[ edge.data.target ]; link.ui.geometry.vertices[0].set(from.ui.position.x, from.ui.position.y, from.ui.position.z); link.ui.geometry.vertices[1].set(to.ui.position.x, to.ui.position.y, to.ui.position.z); link.ui.geometry.verticesNeedUpdate = true; }); } state.renderer.render(state.scene, state.camera); } function rebuildUI () { //Object.keys(nodeUI).forEach(function (nodeId) { // scene.remove(nodeUI[nodeId]); //}); //nodeUI = {}; // //Object.keys(linkUI).forEach(function (linkId) { // scene.remove(linkUI[linkId]); //}); //linkUI = {}; // // //network.get( 'nodes' ).forEach(function (n) { // createNodeUI(n); //}); //network.get( 'edges' ).forEach(function (e) { // createLinkUI(e); //}); // Remove old UI nodes.forEach(function (n) { var node = state.elements.elements['nl' + n.data.id]; state.scene.remove(node.ui); node.ui = undefined; }); edges.forEach(function (e) { var toID = e.data.target.substring(2); var fromID = e.data.source.substring(2); var link = state.elements.elements[ 'e' + fromID + toID ]; state.scene.remove(link.ui); link.ui = undefined; }); // Create new UI nodes.forEach(function (n) { createNodeUI(state.elements.elements['nl' + n.data.id]); }); edges.forEach(function (e) { var toID = e.data.target.substring(2); var fromID = e.data.source.substring(2); var link = state.elements.elements[ 'e' + fromID + toID ]; createLinkUI(link); }); } /** * Check if the given Layout was already instantiated or is only a name. * If a name -> create new Layout * @param state * @returns {*} */ function createLayout ( state ) { var input = state.layout; input = input === undefined ? 'ForceDirectedLayered' : input.name; network = state.elements; console.log(state); if ( typeof input === 'string' ) { var layout; if ( input === 'Fixed' ) { console.log(state.physicsSettings); return new Fixed( network, state ); } if ( input === 'ForceDirectedLayered' ) { return new ForceDirectedLayered( network, state ); } if ( input === 'ForceDirected' ) { return new ForceDirected(network, settings); } if ( input === 'Manual' ) { return new Manual( state.elements ); } } else if ( input ) { return input; } throw new Error ( "The layout " + input + " could not be created!" ); } return { THREE: THREE, run: run, resetStable: function () { stable = false; layout.resetStable(); }, /** * You can set the nodeUIBuilder function yourself * allowing for custom UI settings * @param callback */ setNodeUI: function (callback) { nodeUIBuilder = callback; rebuildUI(); return this; }, /** * You can set the nodeUIBuilder function yourself * allowing for custom UI settings * @param callback */ setLinkUI: function (callback) { linkUIBuilder = callback; rebuildUI(); return this; } }; /** * Create the three.js renderer * @param container * @returns {*} */ function createRenderer ( container ) { var webGlSupport = webgl_detect(); var renderer = webGlSupport ? new THREE.WebGLRenderer( { container: container, antialias: true } ) : new THREE.CanvasRenderer( container ); var width = container.clientWidth || window.innerWidth; var height = container.clientHeight || window.innerHeight; renderer.setSize( width, height ); renderer.setClearColor( 0xffffff, 1 ); console.log(renderer); if ( container ) { container.appendChild( renderer.domElement ); } else { document.body.appendChild( renderer.domElement ); } return renderer; } /** * http://stackoverflow.com/questions/11871077/proper-way-to-detect-webgl-support * @param return_context * @returns {*} */ function webgl_detect(return_context) { if (!!window.WebGLRenderingContext) { var canvas = document.createElement("canvas"), names = ["webgl", "experimental-webgl", "moz-webgl", "webkit-3d"], context = false; for(var i=0;i<4;i++) { try { context = canvas.getContext(names[i]); if (context && typeof context.getParameter == "function") { // WebGL is enabled if (return_context) { // return WebGL object if the function's argument is present return {name:names[i], gl:context}; } // else, return just true return true; } } catch(e) {} } // WebGL is supported, but disabled return false; } // WebGL not supported return false; } } module.exports = Graphics;
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.8/esri/copyright.txt for details. //>>built define({zoom:"P\u0159ibl\u00ed\u017eit na",next:"Dal\u0161\u00ed prvek",previous:"P\u0159edchoz\u00ed prvek",close:"Zav\u0159\u00edt",dock:"Ukotvit",undock:"Zru\u0161it ukotven\u00ed",menu:"Nab\u00eddka",untitled:"Bez n\u00e1zvu",pageText:"{index} z {total}",selectedFeature:"Vybran\u00fd prvek",selectedFeatures:"{total} v\u00fdsledk\u016f",loading:"Na\u010d\u00edt\u00e1n\u00ed",collapse:"Sbalit",expand:"Rozbalit"});
const minimatch = require( "minimatch" ); const webpack = require( "webpack" ); const _ = require( "lodash" ); module.exports = function( options ) { function isMatchingModule( mod ) { return mod.resource && _.some( options.paths, path => minimatch( mod.resource, path ) ); } return new webpack.optimize.CommonsChunkPlugin( { name: options.name, filename: options.filename, minChunks: isMatchingModule } ); };
// Private array of chars to use var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); var ID = {}; ID.uuid = function (len, radix) { var chars = CHARS, uuid = [], i; radix = radix || chars.length; if (len) { // Compact form for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix]; } else { // rfc4122, version 4 form var r; // rfc4122 requires these characters uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'; uuid[14] = '4'; // Fill in random data. At i==19 set the high bits of clock sequence as // per rfc4122, sec. 4.1.5 for (i = 0; i < 36; i++) { if (!uuid[i]) { r = 0 | Math.random()*16; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; } } } return uuid.join(''); }; // A more performant, but slightly bulkier, RFC4122v4 solution. We boost performance // by minimizing calls to random() ID.uuidFast = function() { var chars = CHARS, uuid = new Array(36), rnd=0, r; for (var i = 0; i < 36; i++) { if (i==8 || i==13 || i==18 || i==23) { uuid[i] = '-'; } else if (i==14) { uuid[i] = '4'; } else { if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0; r = rnd & 0xf; rnd = rnd >> 4; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; } } return uuid.join(''); }; // A more compact, but less performant, RFC4122v4 solution: ID.uuidCompact = function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); }; module.exports = ID;
// ==UserScript== // @name mineAI // @namespace minesAI // @include http://minesweeperonline.com/#beginner-night // @version 1 // @required http://localhost:8000/convnetjs.js // @grant none // ==/UserScript== // Load the library. var D = document; var appTarg = D.getElementsByTagName ('head')[0] || D.body || D.documentElement; var jsNode = D.createElement ('script'); jsNode.src = 'http://localhost:8000/convnetjs.js'; jsNode.addEventListener ("load", initConvNetJsOnDelay, false); appTarg.appendChild (jsNode); // Allow some time for the library to initialize after loading. function initConvNetJsOnDelay () { setTimeout (initConvNetJs, 666); } // Call the library's start-up function, if any. Note needed use of unsafeWindow. function initConvNetJs () { // species a 2-layer neural network with one hidden layer of 20 neurons var layer_defs = []; // ConvNetJS works on 3-Dimensional volumes (sx, sy, depth), but if you're not dealing with images // then the first two dimensions (sx, sy) will always be kept at size 1 layer_defs.push({type:'input', out_sx:1, out_sy:1, out_depth:2}); // declare 4 neurons, followed by ReLU (rectified linear unit non-linearity) layer_defs.push({type:'fc', num_neurons:4, activation:'relu'}); // 3 more for good measure layer_defs.push({type:'fc', num_neurons:3, activation:'relu'}); // declare the linear classifier on top of the previous hidden layer layer_defs.push({type:'softmax', num_classes:2}); // defined our net with unsafeWindow for use in GreaseMonkey var net = new unsafeWindow.convnetjs.Net(); // create our net with layers as defined above net.makeLayers(layer_defs); // define trainer var trainer = new convnetjs.SGDTrainer(net, {learning_rate:0.01, l2_decay:0.001}); // define inputs (XOR) var t1 = new convnetjs.Vol([0, 0]); // class 0 var t2 = new convnetjs.Vol([0, 1]); // class 1 var t3 = new convnetjs.Vol([1, 0]); // class 1 var t4 = new convnetjs.Vol([1, 1]); // class 0 // train for 1000 iterations with corresponding classes for (var i = 0; i < 1000; i++) { trainer.train(t1, 0); trainer.train(t2, 1); trainer.train(t3, 1); trainer.train(t4, 0); } // learned probability var prob00 = net.forward(t1); var prob01 = net.forward(t2); var prob10 = net.forward(t3); var prob11 = net.forward(t4); // log probability console.log('p(0 | 00): ' + prob00.w[0] + ", p(1 | 00): " + prob00.w[1]); console.log('p(0 | 01): ' + prob01.w[0] + ", p(1 | 01): " + prob01.w[1]); console.log('p(0 | 10): ' + prob10.w[0] + ", p(1 | 10): " + prob10.w[1]); console.log('p(0 | 11): ' + prob11.w[0] + ", p(1 | 11): " + prob11.w[1]); } alert("Done");
var test = require('tst') var assert = require('assert') var noise = require('..') test('white noise', () => { assert(typeof noise.white() === 'function') }) test('pink noise', () => { assert(typeof noise.pink() === 'function') }) test('brown noise', () => { assert(typeof noise.pink() === 'function') })
define(function () { 'use strict'; ({ get foo () { console.log( 'effect' ); return {}; } }).foo.bar; ({ get foo () { return {}; } }).foo.bar.baz; ({ get foo () { console.log( 'effect' ); return () => {}; } }).foo(); ({ get foo () { return () => console.log( 'effect' ); } }).foo(); ({ get foo () { console.log( 'effect' ); return () => () => {}; } }).foo()(); ({ get foo () { return () => () => console.log( 'effect' ); } }).foo()(); });
import {module, inject, createRootFactory} from '../mocks'; describe('solPopmenu directive', function () { let $compile; let $rootScope; let createRoot; let rootEl; beforeEach(module('karma.templates')); beforeEach(module('ui-kit')); beforeEach(inject((_$compile_, _$rootScope_) => { $compile = _$compile_; $rootScope = _$rootScope_; createRoot = createRootFactory($compile); let html = '<div><sol-popmenu icon="list">tranclusion</sol-popmenu></div>'; rootEl = createRoot(html, $rootScope); })); it('should replace the element', () => { let menu = rootEl.find('.popmenu-popup .popmenu-content'); expect(rootEl).not.toContainElement('sol-popmenu'); }); it('should transclude content inside a ".popmenu-popup .popmenu-content" element', () => { let menu = rootEl.find('.popmenu-popup .popmenu-content'); expect(menu).toHaveText('tranclusion'); }); it('should add "fa fa-<icon>" class on toggler according to icon attribute', () => { let toggler = rootEl.find('.popmenu-toggler'); expect(toggler).toHaveClass('fa fa-list'); }); it('should toggle the "closed" class on .popmenu once the .popmenu-toggler clicked', () => { let menu = rootEl.find('.popmenu'); let toggler = rootEl.find('.popmenu-toggler'); expect(menu).not.toHaveClass('closed'); toggler.click(); toggler.click(); $rootScope.$digest(); expect(menu).toHaveClass('closed'); }); it('contains a .popmenu-toggler element', () => { let html = '<div><sol-popmenu></sol-popmenu></div>'; let rootEl = createRoot(html, $rootScope); expect(rootEl).toContainElement('.popmenu-toggler'); }); it('contains a .popmenu element', () => { let html = '<div><sol-popmenu></sol-popmenu></div>'; let rootEl = createRoot(html, $rootScope); expect(rootEl).toContainElement('.popmenu'); }); });
import React from 'react' import Button from 'components/Button' import Flex from 'components/Flex' import { Explanation, TextStep, Buttons } from '../styles' import explanation from 'images/bearing-explanation.svg' export class Step extends React.Component { render () { return ( <TextStep> <div> <h2>Thanks!</h2> <p> If it’s clear which way the camera is pointing, you can go to the next step and try marking the direction and angle of the view of the image. </p> <p> <Explanation alt='Camera and target' title='Camera and target' src={explanation} /> </p> </div> <Buttons> <Flex justifyContent='flex-end'> <Button onClick={this.props.skip} type='skip'>Skip</Button> <Button onClick={this.props.next} type='submit'>Continue</Button> </Flex> </Buttons> </TextStep> ) } } export default Step
export { default } from './ElectronOriginalWordmark'
'use-strict'; var hours = ['6:00am', '7:00am', '8:00am', '9:00am', '10:00am', '11:00am', '12:00pm', '1:00pm', '2:00pm', '3:00pm', '4:00pm', '5:00pm', '6:00pm', '7:00pm']; var allLocations = []; var theTable = document.getElementById('pike'); var el = document.getElementById('moreStores'); // var hourlyTotals = []; // contructor for the Cookie Stores function CookieStore(locationName, minCustomersPerHour, maxCustomersPerHour, avgCookiesPerCustomer) { this.locationName = locationName; this.minCustomersPerHour = minCustomersPerHour; this.maxCustomersPerHour = maxCustomersPerHour; this.avgCookiesPerCustomer = avgCookiesPerCustomer; this.customersEachHour = []; this.cookiesEachHour = []; this.totalDaily = 0; this.calcCustomersThisHour(); this.calcCookiesThisHour(); allLocations.push(this); } // creates total for customers each hour CookieStore.prototype.calcCustomersThisHour = function() { var reference = []; for (var i = 0; i < hours.length; i++) { var numberCustomersPerHour = Math.floor(Math.random() * (this.maxCustomersPerHour - this.minCustomersPerHour + 1)) + this.minCustomersPerHour; reference.push(numberCustomersPerHour); } this.customersEachHour = reference; return numberCustomersPerHour; }; // Creates total for daily cookie sales CookieStore.prototype.calcCookiesThisHour = function() { for (var j = 0; j < hours.length; j++) { var totalCookieSales = Math.ceil(this.customersEachHour[j] * this.avgCookiesPerCustomer); this.cookiesEachHour.push(totalCookieSales); this.totalDaily += this.cookiesEachHour[j]; } this.cookiesEachHour.push(this.totalDaily); }; // creates table elements function makeElement(type, content, parent){ // create var newEl = document.createElement(type); // content newEl.textContent = content; // append parent.appendChild(newEl); } // Push hours to table header var renderHeader = function() { var trEL = document.createElement('tr'); var thEL = document.createElement('th'); thEL.textContent = 'Locations'; trEL.appendChild(thEL); for (var i = 0; i < hours.length; i++) { var thEL = document.createElement('th'); thEL.textContent = hours[i]; trEL.appendChild(thEL); } thEL = document.createElement('th'); thEL.textContent = 'Daily'; trEL.appendChild(thEL); theTable.appendChild(trEL); }; // Push totals to TD's in DOM CookieStore.prototype.render = function() { var trEL = document.createElement('tr'); var tdEL = document.createElement('td'); tdEL.textContent = this.locationName; trEL.appendChild(tdEL); for (var i = 0; i < hours.length + 1; i++) { var tdEL = document.createElement('td'); tdEL.textContent = this.cookiesEachHour[i]; trEL.appendChild(tdEL); } theTable.appendChild(trEL); }; // Footer TOTALLLLL function renderFooter() { var trEL = document.createElement('tr'); var thEL = document.createElement('th'); thEL.textContent = 'Total'; trEL.appendChild(thEL); var totalOfTotals = 0; var hourlyTotal = 0; for (var i = 0; i < hours.length; i++) { hourlyTotal = 0; for (var j = 0; j < allLocations.length; j++) { hourlyTotal += allLocations[j].cookiesEachHour[i]; totalOfTotals += allLocations[j].cookiesEachHour[i]; } thEL = document.createElement('th'); thEL.textContent = hourlyTotal; trEL.appendChild(thEL); } thEL = document.createElement('th'); thEL.textContent = totalOfTotals; trEL.appendChild(thEL); theTable.appendChild(trEL); }; // passing new stores to the cookie store constructor var pikePlace = new CookieStore('Pike Place Market', 23, 65, 6.3); var seaTac = new CookieStore('Seatac', 3, 24, 1.2); var seattleCenter = new CookieStore('Seattle Center', 11, 38, 3.7); var capitolHill = new CookieStore('Capitol Hill', 20, 38, 2.3); var alki = new CookieStore('Alki', 2, 16, 4.6); // Renders the table function renderTable(){ theTable.innerHTML = ''; renderHeader(); for (i = 0; i < allLocations.length; i++) { allLocations[i].render(); } renderFooter(); } renderTable(); // Handler for listener function handleStoreSubmit(event) { event.preventDefault(); var newStoreLocation = event.target.storeLocation.value; var minCustomers = parseInt(event.target.minCustomers.value); var maxCustomers = parseInt(event.target.maxCustomers.value); var avgCookie = parseFloat(event.target.avgCookiesSold.value); console.log('go here'); // prevent empty if(!newStoreLocation || !minCustomers || !maxCustomers || !avgCookie){ return alert('All fields must have a value'); } //validate by type if (typeof minCustomers !== 'number') { return alert('Min customers must be a number'); } // ignore case on store names for(var i = 0; i < allLocations.length; i++){ if(newStoreLocation === allLocations[i].locationName) { allLocations[i].minCustomersPerHour = minCustomers; allLocations[i].maxCustomersPerHour = maxCustomers; allLocations[i].avgCookiesPerCustomer = avgCookie; clearForm(); allLocations[i].totalDaily = 0; allLocations[i].customersEachHour = []; allLocations[i].cookiesEachHour = []; allLocations[i].calcCustomersThisHour(); allLocations[i].calcCookiesThisHour(); console.log('A match was found at index', allLocations[i]); renderTable(); return; } } new CookieStore(newStoreLocation, minCustomers, maxCustomers, avgCookie); function clearForm(){ event.target.storeLocation.value = null; event.target.minCustomers.value = null; event.target.maxCustomers.value = null; event.target.avgCookiesSold.value = null; } clearForm(); // for(var i = allLocations.length - 1; i < allLocations.length; i++){ // allLocations[i].render(); // } renderTable(); }; // Listener code el.addEventListener('submit', handleStoreSubmit);
var express = require('express'); var router = express.Router(); // Play a game from the DB router.get('/games', function (req, res) { res.render('games', data); }); module.exports = router;
import React from 'react'; import ReactTouchPosition from '../../../dist/ReactTouchPosition'; import TouchPositionLabel from './TouchPositionLabel'; import OnPositionChangedLabel from './OnPositionChangedLabel'; import InstructionsLabel from './InstructionsLabel'; export default class extends React.Component { constructor(props) { super(props); this.state = { isPositionOutside: true, touchPosition: { x: 0, y: 0, } } } render() { return ( <div className="example-container"> <ReactTouchPosition {...{ className: 'example', onPositionChanged: ({ isPositionOutside, touchPosition }) => { this.setState({ isPositionOutside, touchPosition }); }, shouldDecorateChildren: false }}> <TouchPositionLabel /> <InstructionsLabel /> </ReactTouchPosition> <OnPositionChangedLabel {...this.state} /> </div> ); } }
/** * React Starter Kit for Firebase * https://github.com/kriasoft/react-firebase-starter * Copyright (c) 2015-present Kriasoft | MIT License */ import { graphql } from 'graphql'; import { Environment, Network, RecordSource, Store } from 'relay-runtime'; import schema from './schema'; import { Context } from './context'; export function createRelay(req) { function fetchQuery(operation, variables, cacheConfig) { return graphql({ schema, source: operation.text, contextValue: new Context(req), variableValues: variables, operationName: operation.name, }).then(payload => { // Passes the raw payload up to the caller (see src/router.js). // This is needed in order to hydrate/de-hydrate that // data on the client during the initial page load. cacheConfig.payload = payload; return payload; }); } const recordSource = new RecordSource(); const store = new Store(recordSource); const network = Network.create(fetchQuery); return new Environment({ store, network }); }
import { Feature } from 'core/feature'; import * as toolkitHelper from 'helpers/toolkit'; export class TargetBalanceWarning extends Feature { constructor() { super(); } shouldInvoke() { return toolkitHelper.getCurrentRouteName().indexOf('budget') !== -1; } invoke() { $('.budget-table-row.is-sub-category').each((index, element) => { const emberId = element.id; const viewData = toolkitHelper.getEmberView(emberId).data; const { subCategory } = viewData; if (subCategory.get('goalType') === ynab.constants.SubCategoryGoalType.TargetBalance) { const available = viewData.get('available'); const targetBalance = subCategory.get('targetBalance'); const currencyElement = $('.budget-table-cell-available .user-data.currency', element); if (available < targetBalance && !currencyElement.hasClass('cautious')) { if (currencyElement.hasClass('positive')) { currencyElement.removeClass('positive'); } currencyElement.addClass('cautious'); } } }); } observe(changedNodes) { if (!this.shouldInvoke()) return; if (changedNodes.has('budget-table-cell-available-div user-data')) { this.invoke(); } } onRouteChanged() { if (!this.shouldInvoke()) return; this.invoke(); } }
angular.module('kindly.requests').directive('request', function() { return { restrict: 'E', replace: true, scope: { request: '=' }, controller: function($scope) { $scope.is = function(medium) { return $scope.request.medium === medium; }; }, templateUrl: 'requests/_request.html' }; });
/** * @license Copyright (c) 2013, Viet Trinh All Rights Reserved. * Available via MIT license. */ /** * A card entity. */ define([ 'framework/entity/base_entity' ], function(BaseEntity) { /** * Constructor. * @param rawObject (optional) * The raw object to create the entity with. */ var Card = function(rawObject) { this.name = null; this.color = null; BaseEntity.call(this, rawObject); return this; }; Card.prototype = new BaseEntity(); BaseEntity.generateProperties(Card); // The card rarities. Card.RARITY = {}; Card.RARITY.MYTHIC = 'M'; Card.RARITY.RARE = 'R'; Card.RARITY.UNCOMMON = 'U'; Card.RARITY.COMMON = 'C'; Card.RARITY.LAND = 'L'; return Card; });
import Ember from 'ember'; import ObjectProxyMixin from '../mixins/object'; export default Ember.ObjectProxy.extend(ObjectProxyMixin, { _storageType: 'session' });
class Auth { isAuthenticate () { return this.getToken() !== null } setToken (token) { window.localStorage.setItem('access_token', token) } getToken () { return window.localStorage.getItem('access_token') } removeToken () { window.localStorage.removeItem('access_token') } } export default new Auth()
'use strict' // import Device from './Device' let Device = require('./Device').Device module.exports = { Device: Device }
(function (window, $, _, Concrete) { 'use strict'; /** * Area object, used for managing areas * @param {jQuery} elem The area's HTML element * @param {EditMode} edit_mode The EditMode instance */ var Area = Concrete.Area = function Area(elem, edit_mode) { this.init.apply(this, _(arguments).toArray()); }; Area.prototype = { init: function areaInit(elem, edit_mode) { var my = this; elem.data('Concrete.area', my); Concrete.createGetterSetters.call(my, { id: elem.data('area-id'), active: true, blockTemplate: _(elem.children('script[role=area-block-wrapper]').html()).template(), elem: elem, totalBlocks: 0, enableGridContainer: elem.data('area-enable-grid-container'), handle: elem.data('area-handle'), dragAreas: [], blocks: [], editMode: edit_mode, maximumBlocks: parseInt(elem.data('maximumBlocks'), 10), blockTypes: elem.data('accepts-block-types').split(' '), blockContainer: elem.children('.ccm-area-block-list') }); my.id = my.getId(); my.setTotalBlocks(0); // we also need to update the DOM which this does. }, /** * Handle unbinding. */ destroy: function areaDestroy() { var my = this; if (my.getAttr('menu')) { my.getAttr('menu').destroy(); } my.reset(); }, reset: function areaReset() { var my = this; _(my.getDragAreas()).each(function (drag_area) { drag_area.destroy(); }); _(my.getBlocks()).each(function (block) { block.destroy(); }); my.setBlocks([]); my.setDragAreas([]); my.setTotalBlocks(0); }, bindEvent: function areaBindEvent(event, handler) { return Concrete.EditMode.prototype.bindEvent.apply(this, _(arguments).toArray()); }, scanBlocks: function areaScanBlocks() { var my = this, type, block; my.reset(); my.addDragArea(null); $('div.ccm-block-edit[data-area-id=' + my.getId() + ']', this.getElem()).each(function () { var me = $(this), handle = me.data('block-type-handle'); if (handle === 'core_area_layout') { type = Concrete.Layout; } else { type = Concrete.Block; } block = new type(me, my); my.addBlock(block); }); }, getBlockByID: function areaGetBlockByID(bID) { var my = this; return _.findWhere(my.getBlocks(), {id: bID}); }, getMenuElem: function areaGetMenuElem() { var my = this; return $('[data-area-menu=area-menu-a' + my.getId() + ']'); }, bindMenu: function areaBindMenu() { var my = this, elem = my.getElem(), totalBlocks = my.getTotalBlocks(), $menuElem = my.getMenuElem(), menuHandle; if (totalBlocks > 0) { menuHandle = '#area-menu-footer-' + my.getId(); } else { menuHandle = 'div[data-area-menu-handle=' + my.getId() + ']'; } if (my.getAttr('menu')) { my.getAttr('menu').destroy(); } var menu_config = { 'handle': menuHandle, 'highlightClassName': 'ccm-area-highlight', 'menuActiveClass': 'ccm-area-highlight', 'menu': $('[data-area-menu=' + elem.attr('data-launch-area-menu') + ']') }; if (my.getElem().hasClass('ccm-global-area')) { menu_config.menuActiveClass += " ccm-global-area-highlight"; menu_config.highlightClassName += " ccm-global-area-highlight"; } my.setAttr('menu', new ConcreteMenu(elem, menu_config)); $menuElem.find('a[data-menu-action=add-inline]') .off('click.edit-mode') .on('click.edit-mode', function (e) { // we are going to place this at the END of the list. var dragAreaLastBlock = false; _.each(my.getBlocks(), function (block) { dragAreaLastBlock = block; }); Concrete.event.fire('EditModeBlockAddInline', { area: my, cID: CCM_CID, btID: $(this).data('block-type-id'), arGridMaximumColumns: $(this).attr('data-area-grid-maximum-columns'), event: e, dragAreaBlock: dragAreaLastBlock, btHandle: $(this).data('block-type-handle') }); return false; }); $menuElem.find('a[data-menu-action=edit-container-layout]') .off('click.edit-mode') .on('click.edit-mode', function (e) { // we are going to place this at the END of the list. var $link = $(this); var bID = parseInt($(this).attr('data-container-layout-block-id')); var editor = Concrete.getEditMode(); var block = _.findWhere(editor.getBlocks(), {id: bID}); Concrete.event.fire('EditModeBlockEditInline', { block: block, arGridMaximumColumns: $link.attr('data-area-grid-maximum-columns'), event: e }); return false; }); $menuElem.find('a[data-menu-action=edit-area-design]') .off('click.edit-mode') .on('click.edit-mode', function (e) { e.preventDefault(); ConcreteToolbar.disable(); my.getElem().addClass('ccm-area-inline-edit-disabled'); var postData = { 'arHandle': my.getHandle(), 'cID': CCM_CID }; my.bindEvent('EditModeExitInline', function (e) { Concrete.event.unsubscribe(e); my.getEditMode().destroyInlineEditModeToolbars(); }); $.ajax({ type: 'GET', url: CCM_DISPATCHER_FILENAME + '/ccm/system/dialogs/area/design', data: postData, success: function (r) { var $container = my.getElem(); my.getEditMode().loadInlineEditModeToolbars($container, r); $.fn.dialog.hideLoader(); } }); }); }, /** * Add block to area * @param {Block} block block to add * @param {Block} sub_block The block that should be above the added block * @return {Boolean} Success, always true */ addBlock: function areaAddBlock(block, sub_block) { var my = this; if (sub_block) { return this.addBlockToIndex(block, _(my.getBlocks()).indexOf(sub_block) + 1); } return this.addBlockToIndex(block, my.getBlocks().length); }, setTotalBlocks: function (totalBlocks) { this.setAttr('totalBlocks', totalBlocks); this.getElem().attr('data-total-blocks', totalBlocks); }, /** * Add to specific index, pipes to addBlock * @param {Block} block Block to add * @param {int} index Index to add to * @return {Boolean} Success, always true */ addBlockToIndex: function areaAddBlockToIndex(block, index) { var totalBlocks = this.getTotalBlocks(), blocks = this.getBlocks(), totalHigherBlocks = totalBlocks - index; block.setArea(this); this.setTotalBlocks(totalBlocks + 1); // any blocks with indexes higher than this one need to have them incremented if (totalHigherBlocks > 0) { var updateBlocksArray = []; for (var i = 0; i < blocks.length; i++) { if (i >= index) { updateBlocksArray[i + 1] = blocks[i]; } else { updateBlocksArray[i] = blocks[i]; } } updateBlocksArray[index] = block; this.setBlocks(updateBlocksArray); } else { this.getBlocks()[index] = block; } this.addDragArea(block); // ensure that the DOM attributes are correct block.getElem().attr("data-area-id", this.getId()); return true; }, /** * Remove block from area * @param {Block} block The block to remove. * @return {Boolean} Success, always true. */ removeBlock: function areaRemoveBlock(block) { var my = this, totalBlocks = my.getTotalBlocks(); block.getContainer().remove(); my.setBlocks(_(my.getBlocks()).without(block)); my.setTotalBlocks(totalBlocks - 1); var drag_area = _.first(_(my.getDragAreas()).filter(function (drag_area) { return drag_area.getBlock() === block; })); if (drag_area) { drag_area.getElem().remove(); my.setDragAreas(_(my.getDragAreas()).without(drag_area)); } if (!my.getTotalBlocks()) { // we have to destroy the old menu and create it anew my.bindMenu(); } return true; }, /** * Add a drag area * @param {Block} block The block to add this area below. * @return {DragArea} The added DragArea */ addDragArea: function areaAddDragArea(block) { var my = this, elem, drag_area; if (!block) { if (my.getDragAreas().length) { throw new Error('No block supplied'); } elem = $('<div class="ccm-area-drag-area"/>'); drag_area = new Concrete.DragArea(elem, my, block); my.getBlockContainer().prepend(elem); } else { elem = $('<div class="ccm-area-drag-area"/>'); drag_area = new Concrete.DragArea(elem, my, block); block.getContainer().after(elem); } my.getDragAreas().push(drag_area); return drag_area; }, /** * Find the contending DragArea's * @param {Pep} pep The Pep object from the event. * @param {Block|Stack} block The Block object from the event. * @return {Array} Array of all drag areas that are capable of accepting the block. */ contendingDragAreas: function areaContendingDragAreas(pep, block) { var my = this, max_blocks = my.getMaximumBlocks(); if (block instanceof Concrete.Stack || block.getHandle() === 'core_stack_display') { return _(my.getDragAreas()).filter(function (drag_area) { return drag_area.isContender(pep, block); }); } else if ((max_blocks > 0 && my.getBlocks().length >= max_blocks) || !_(my.getBlockTypes()).contains(block.getHandle())) { return []; } return _(my.getDragAreas()).filter(function (drag_area) { return drag_area.isContender(pep, block); }); } }; }(window, jQuery, _, Concrete));
//= require active_admin/base //= require jquery.nested-fields //= require chosen-jquery //= require bootstrap //= require bootstrap-wysihtml5 //= require ./active_tweaker
import '../../../../css/rpt/styles.global.css'; import styles from '../../../css/rpt/styles.css'; import React, { Component, PropTypes } from 'react'; import 'react-widgets/lib/less/react-widgets.less'; import DateTimePicker from 'react-widgets/lib/DateTimePicker'; import Multiselect from 'react-widgets/lib/Multiselect'; import { FormGroup,FormControl,HelpBlock,Checkbox,ControlLabel,Label,Row,Col,ListGroup,ListGroupItem,Panel,Table,Button,Glyphicon,ButtonGroup,ButtonToolbar} from 'react-bootstrap'; import { ButtonInput } from 'react-bootstrap'; import * as STATE from "../../../actions/rpt/production/State.js" var dateFormat = require('dateformat'); var Moment = require('moment'); var momentLocalizer = require('react-widgets/lib/localizers/moment'); var classNames = require('classnames'); momentLocalizer(Moment); export default class POWithReceiversDateRange extends React.Component { static propTypes = { ProdRpt: PropTypes.object.isRequired }; constructor(props) { super(props); this.state = { test:this.test.bind(this) }; if ('development'==process.env.NODE_ENV) { } } test(dt,dateStart,dateEnd){ console.log(`dt: ${dt}`); var dtStart = dateFormat(new Date(dt), "mm-dd-yyyy hh:MM:ss"); if ('development'==process.env.NODE_ENV) { console.log(`dtStart=>${dtStart}`); } var dtStartFmt = dateFormat(new Date(dateStart), "mm-dd-yyyy hh:MM:ss"); if ('development'==process.env.NODE_ENV) { console.log(`dtStartFmt=>${dtStartFmt}`); } var dtEndFmt = dateFormat(new Date(dateEnd), "mm-dd-yyyy hh:MM:ss"); if ('development'==process.env.NODE_ENV) { console.log(`dtEndFmt=>${dtEndFmt}`); } } render() { var runAndBackBtn; if(STATE.POWITHRECEIVERS_DATE_RANGE_NOT_READY==this.props.Rpt.state){ runAndBackBtn = <Row> <Col xs={4} >&nbsp;</Col> <Col xs={1}><Button onClick={()=>this.props.poWithReceivers()} bsSize="large" bsStyle="info" disabled>Run</Button></Col> <Col xs={1} >&nbsp;</Col> <Col xs={2}><Button onClick={()=>this.props.setState(STATE.NOT_STARTED)} bsSize="large" bsStyle="warning">Back</Button></Col> <Col xs={3}>&nbsp;</Col> </Row> }else{ runAndBackBtn = <Row> <Col xs={4} >&nbsp;</Col> <Col xs={2}><Button onClick={()=>this.props.poWithReceivers()} bsSize="large" bsStyle="info" >Run</Button></Col> <Col xs={1}><Button onClick={()=>this.props.setState(STATE.NOT_STARTED)} bsSize="large" bsStyle="warning">Back</Button></Col> <Col xs={3}>&nbsp;</Col> </Row> } var pageNoClass = classNames( 'pagination','hidden-xs', 'pull-left' ); var dateHeader; var dateStyle; if(this.props.ProdRpt.openPOWithReceivers.dateHeader.valid){ dateHeader=<h3 style={{textAlign:'center'}}>{this.props.ProdRpt.poWithReceivers.dateHeader.text}</h3> dateStyle='default'; }else{ dateHeader=<h3 style={{textAlign:'center',color:'red !important'}}>{this.props.ProdRpt.openPOWithReceivers.dateHeader.text}</h3> dateStyle='danger'; } return ( <div> <Panel bsStyle={dateStyle} header={dateHeader}> <Row> <Col xs={1} > <h1 style={{marginTop:0}}><Label bsStyle="primary">Start</Label></h1> </Col> <Col xs={8} xsOffset={1} style={{}}> <DateTimePicker onChange={(name,value)=>{ this.state.test(name,this.props.ProdRpt.poWithReceivers.dateStart,this.props.ProdRpt.openPOWithReceivers.dateEnd); this.props.setPOWithReceiversDateStart(name); this.props.poWithReceiversDateRange(); }} defaultValue={this.props.ProdRpt.openPOWithReceivers.dateStart} /> </Col> </Row> <Row> <Col xs={1}> <h1 style={{marginTop:0}}><Label bsStyle="primary">End</Label></h1> </Col> <Col xs={8} xsOffset={1}> <DateTimePicker onChange={(name,value)=>{ this.props.setPOWithReceiversDateEnd(name); this.props.poWithReceiversDateRange(); }} defaultValue={this.props.ProdRpt.poWithReceivers.dateEnd} /> </Col> </Row> </Panel> {runAndBackBtn} </div> ); } }
/*! Pushy - v0.9.1 - 2013-9-16 * Pushy is a responsive off-canvas navigation menu using CSS transforms & transitions. * https://github.com/christophery/pushy/ * by Christopher Yee */ $(window).load(function () { var e = false; if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) { e = true } if (e == false) { menuBtn = $('.menu-btn-left') //css classes to toggle the menu } else { menuBtn = $('.menu-btn-left, .pushy a') //css classes to toggle the menu } $(function() { var pushy = $('.pushy'), //menu css class body = $('body'), container = $('#wrapper'), //container css class container2 = $('section#home'), //container css class push = $('.push-left'), //css class to add pushy capability siteOverlay = $('.site-overlay'), //site overlay pushyClass = "pushy-left pushy-open-left", //menu position & menu open class pushyActiveClass = "pushy-active", //css class to toggle site overlay containerClass = "container-push-left", //container open class pushClass = "push-push-left", //css class to add pushy capability //menuBtn = $('.menu-btn-left'), //css classes to toggle the menu menuSpeed = 200, //jQuery fallback menu speed menuWidth = pushy.width() + "px"; //jQuery fallback menu width function togglePushy(){ body.toggleClass(pushyActiveClass); //toggle site overlay pushy.toggleClass(pushyClass); container.toggleClass(containerClass); container2.toggleClass(containerClass); push.toggleClass(pushClass); //css class to add pushy capability } function openPushyFallback(){ body.addClass(pushyActiveClass); pushy.animate({left: "0px"}, menuSpeed); container.animate({left: menuWidth}, menuSpeed); push.animate({left: menuWidth}, menuSpeed); //css class to add pushy capability } function closePushyFallback(){ body.removeClass(pushyActiveClass); pushy.animate({left: "-" + menuWidth}, menuSpeed); container.animate({left: "0px"}, menuSpeed); push.animate({left: "0px"}, menuSpeed); //css class to add pushy capability } if(Modernizr.csstransforms3d){ //toggle menu menuBtn.click(function() { togglePushy(); }); //close menu when clicking site overlay siteOverlay.click(function(){ togglePushy(); }); }else{ //jQuery fallback pushy.css({left: "-" + menuWidth}); //hide menu by default container.css({"overflow-x": "hidden"}); //fixes IE scrollbar issue //keep track of menu state (open/close) var state = true; //toggle menu menuBtn.click(function() { if (state) { openPushyFallback(); state = false; } else { closePushyFallback(); state = true; } }); //close menu when clicking site overlay siteOverlay.click(function(){ if (state) { openPushyFallback(); state = false; } else { closePushyFallback(); state = true; } }); } }); });
/* eslint-env mocha */ /* eslint-disable func-names, prefer-arrow-callback */ import mainContent from '../pageobjects/main-content.page'; import sideNav from '../pageobjects/side-nav.page'; describe.skip('emoji', ()=> { it('opens general', ()=> { sideNav.openChannel('general'); }); it('opens emoji menu', ()=> { mainContent.emojiBtn.click(); }); describe('render', ()=> { it('should show the emoji picker menu', ()=> { mainContent.emojiPickerMainScreen.isVisible().should.be.true; }); it('click the emoji picker people tab', ()=> { mainContent.emojiPickerPeopleIcon.click(); }); it('should show the emoji picker people tab', ()=> { mainContent.emojiPickerPeopleIcon.isVisible().should.be.true; }); it('should show the emoji picker nature tab', ()=> { mainContent.emojiPickerNatureIcon.isVisible().should.be.true; }); it('should show the emoji picker food tab', ()=> { mainContent.emojiPickerFoodIcon.isVisible().should.be.true; }); it('should show the emoji picker activity tab', ()=> { mainContent.emojiPickerActivityIcon.isVisible().should.be.true; }); it('should show the emoji picker travel tab', ()=> { mainContent.emojiPickerTravelIcon.isVisible().should.be.true; }); it('should show the emoji picker objects tab', ()=> { mainContent.emojiPickerObjectsIcon.isVisible().should.be.true; }); it('should show the emoji picker symbols tab', ()=> { mainContent.emojiPickerSymbolsIcon.isVisible().should.be.true; }); it('should show the emoji picker flags tab', ()=> { mainContent.emojiPickerFlagsIcon.isVisible().should.be.true; }); it('should show the emoji picker custom tab', ()=> { mainContent.emojiPickerCustomIcon.isVisible().should.be.true; }); it('should show the emoji picker change tone button', ()=> { mainContent.emojiPickerChangeTone.isVisible().should.be.true; }); it('should show the emoji picker search bar', ()=> { mainContent.emojiPickerFilter.isVisible().should.be.true; }); it('send a smile emoji', ()=> { mainContent.emojiSmile.click(); }); it('the value on the message input should be the same as the emoji clicked', ()=> { mainContent.messageInput.getValue().should.equal(':smile:'); }); it('send the emoji', ()=> { mainContent.addTextToInput(' '); mainContent.sendBtn.click(); }); it('the value on the message should be the same as the emoji clicked', ()=> { mainContent.lastMessage.getText().should.equal('😄'); }); it('adds emoji text to the message input', ()=> { mainContent.addTextToInput(':smile'); }); it('should show the emoji popup bar', ()=> { mainContent.messagePopUp.isVisible().should.be.true; }); it('the emoji popup bar title should be emoji', ()=> { mainContent.messagePopUpTitle.getText().should.equal('Emoji'); }); it('should show the emoji popup bar items', ()=> { mainContent.messagePopUpItems.isVisible().should.be.true; }); it('click the first emoji on the popup list', ()=> { mainContent.messagePopUpFirstItem.click(); }); it('the value on the message input should be the same as the emoji clicked', ()=> { mainContent.messageInput.getValue().should.equal(':smile:'); }); it('send the emoji', ()=> { mainContent.sendBtn.click(); }); it('the value on the message should be the same as the emoji clicked', ()=> { mainContent.lastMessage.getText().should.equal('😄'); }); }); });
module.exports = function(config) { config.set({ basePath: './', frameworks: ['systemjs', 'jasmine'], systemjs: { configFile: 'config.js', config: { paths: { "*": null, "src/*": "src/*", "typescript": "node_modules/typescript/lib/typescript.js", "systemjs": "node_modules/systemjs/dist/system.js", 'system-polyfills': 'node_modules/systemjs/dist/system-polyfills.js', 'es6-module-loader': 'node_modules/es6-module-loader/dist/es6-module-loader.js' }, packages: { 'test/unit': { defaultExtension: 'ts' }, 'src': { defaultExtension: 'ts' } }, transpiler: 'typescript' }, serveFiles: [ 'src/**/*.ts', 'jspm_packages/**/*.js' ] }, files: [ 'test/unit/*.spec.ts' ], exclude: [], preprocessors: { }, reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
import React, { useState } from 'react'; import { UncontrolledAlert } from 'reactstrap'; import Alert from '../../../src/Alert'; export const AlertFadelessExample = (props) => { const [visible, setVisible] = useState(true); const onDismiss = () => setVisible(false); return ( <div> <Alert color="primary" isOpen={visible} toggle={onDismiss} fade={false}> I am a primary alert and I can be dismissed without animating! </Alert> </div> ); } export function UncontrolledAlertFadelessExample() { return ( <div> <UncontrolledAlert color="info" fade={false}> I am an alert and I can be dismissed without animating! </UncontrolledAlert> </div> ); }
/*jshint browser: true, strict: true, undef: true */ /*global define: false */ ( function( window ) { 'use strict'; // class helper functions from bonzo https://github.com/ded/bonzo function classReg( className ) { return new RegExp("(^|\\s+)" + className + "(\\s+|$)"); } // classList support for class management // altho to be fair, the api sucks because it won't accept multiple classes at once var hasClass, addClass, removeClass; if ( 'classList' in document.documentElement ) { hasClass = function( elem, c ) { return elem.classList.contains( c ); }; addClass = function( elem, c ) { elem.classList.add( c ); }; removeClass = function( elem, c ) { elem.classList.remove( c ); }; } else { hasClass = function( elem, c ) { return classReg( c ).test( elem.className ); }; addClass = function( elem, c ) { if ( !hasClass( elem, c ) ) { elem.className = elem.className + ' ' + c; } }; removeClass = function( elem, c ) { elem.className = elem.className.replace( classReg( c ), ' ' ); }; } function toggleClass( elem, c ) { var fn = hasClass( elem, c ) ? removeClass : addClass; fn( elem, c ); } var classie = { // full names hasClass: hasClass, addClass: addClass, removeClass: removeClass, toggleClass: toggleClass, // short names has: hasClass, add: addClass, remove: removeClass, toggle: toggleClass }; // transport if ( typeof define === 'function' && define.amd ) { // AMD define( classie ); } else { // browser global window.classie = classie; } Modernizr.addTest('csstransformspreserve3d', function () { var prop = Modernizr.prefixed('transformStyle'); var val = 'preserve-3d'; var computedStyle; if(!prop) return false; prop = prop.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-'); Modernizr.testStyles('#modernizr{' + prop + ':' + val + ';}', function (el, rule) { computedStyle = window.getComputedStyle ? getComputedStyle(el, null).getPropertyValue(prop) : ''; }); return (computedStyle === val); }); var support = { transitions : Modernizr.csstransitions, preserve3d : Modernizr.csstransformspreserve3d }, transEndEventNames = { 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd', 'transition': 'transitionend' }, transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ]; function extend( a, b ) { for( var key in b ) { if( b.hasOwnProperty( key ) ) { a[key] = b[key]; } } return a; } function shuffleMArray( marray ) { var arr = [], marrlen = marray.length, inArrLen = marray[0].length; for(var i = 0; i < marrlen; i++) { arr = arr.concat( marray[i] ); } // shuffle 2 d array arr = shuffleArr( arr ); // to 2d var newmarr = [], pos = 0; for( var j = 0; j < marrlen; j++ ) { var tmparr = []; for( var k = 0; k < inArrLen; k++ ) { tmparr.push( arr[ pos ] ); pos++; } newmarr.push( tmparr ); } return newmarr; } function shuffleArr( array ) { var m = array.length, t, i; // While there remain elements to shuffle… while (m) { // Pick a remaining element… i = Math.floor(Math.random() * m--); // And swap it with the current element. t = array[m]; array[m] = array[i]; array[i] = t; } return array; } function Photostack( el, options ) { this.el = el; this.inner = this.el.querySelector( 'div' ); this.allItems = [].slice.call( this.inner.children ); this.allItemsCount = this.allItems.length; if( !this.allItemsCount ) return; this.items = [].slice.call( this.inner.querySelectorAll( 'figure:not([data-dummy])' ) ); this.itemsCount = this.items.length; // index of the current photo this.current = 0; this.options = extend( {}, this.options ); extend( this.options, options ); this._init(); } Photostack.prototype.options = {}; Photostack.prototype._init = function() { this.currentItem = this.items[ this.current ]; this._addNavigation(); this._getSizes(); this._initEvents(); } Photostack.prototype._addNavigation = function() { // add nav dots this.nav = document.createElement( 'nav' ) var inner = ''; for( var i = 0; i < this.itemsCount; ++i ) { inner += '<span></span>'; } this.nav.innerHTML = inner; this.el.appendChild( this.nav ); this.navDots = [].slice.call( this.nav.children ); } Photostack.prototype._initEvents = function() { var self = this, beforeStep = classie.hasClass( this.el, 'photostack-start' ), open = function() { var setTransition = function() { if( support.transitions ) { classie.addClass( self.el, 'photostack-transition' ); } } if( beforeStep ) { this.removeEventListener( 'click', open ); classie.removeClass( self.el, 'photostack-start' ); setTransition(); } else { self.openDefault = true; setTimeout( setTransition, 25 ); } self.started = true; self._showPhoto( self.current ); }; if( beforeStep ) { this._shuffle(); this.el.addEventListener( 'click', open ); } else { open(); } this.navDots.forEach( function( dot, idx ) { dot.addEventListener( 'click', function() { // rotate the photo if clicking on the current dot if( idx === self.current ) { self._rotateItem(); } else { // if the photo is flipped then rotate it back before shuffling again var callback = function() { self._showPhoto( idx ); } if( self.flipped ) { self._rotateItem( callback ); } else { callback(); } } } ); } ); window.addEventListener( 'resize', function() { self._resizeHandler(); } ); } Photostack.prototype._resizeHandler = function() { var self = this; function delayed() { self._resize(); self._resizeTimeout = null; } if ( this._resizeTimeout ) { clearTimeout( this._resizeTimeout ); } this._resizeTimeout = setTimeout( delayed, 100 ); } Photostack.prototype._resize = function() { var self = this, callback = function() { self._shuffle( true ); } this._getSizes(); if( this.started && this.flipped ) { this._rotateItem( callback ); } else { callback(); } } Photostack.prototype._showPhoto = function( pos ) { if( this.isShuffling ) { return false; } this.isShuffling = true; // if there is something behind.. if( classie.hasClass( this.currentItem, 'photostack-flip' ) ) { this._removeItemPerspective(); classie.removeClass( this.navDots[ this.current ], 'flippable' ); } classie.removeClass( this.navDots[ this.current ], 'current' ); classie.removeClass( this.currentItem, 'photostack-current' ); // change current this.current = pos; this.currentItem = this.items[ this.current ]; classie.addClass( this.navDots[ this.current ], 'current' ); // if there is something behind.. if( this.currentItem.querySelector( '.photostack-back' ) ) { // nav dot gets class flippable classie.addClass( this.navDots[ pos ], 'flippable' ); } // shuffle a bit this._shuffle(); } // display items (randomly) Photostack.prototype._shuffle = function( resize ) { var iter = resize ? 1 : this.currentItem.getAttribute( 'data-shuffle-iteration' ) || 1; if( iter <= 0 || !this.started || this.openDefault ) { iter = 1; } // first item is open by default if( this.openDefault ) { // change transform-origin classie.addClass( this.currentItem, 'photostack-flip' ); this.openDefault = false; this.isShuffling = false; } var overlapFactor = .5, // lines & columns lines = Math.ceil(this.sizes.inner.width / (this.sizes.item.width * overlapFactor) ), columns = Math.ceil(this.sizes.inner.height / (this.sizes.item.height * overlapFactor) ), // since we are rounding up the previous calcs we need to know how much more we are adding to the calcs for both x and y axis addX = lines * this.sizes.item.width * overlapFactor + this.sizes.item.width/2 - this.sizes.inner.width, addY = columns * this.sizes.item.height * overlapFactor + this.sizes.item.height/2 - this.sizes.inner.height, // we will want to center the grid extraX = addX / 2, extraY = addY / 2, // max and min rotation angles maxrot = 35, minrot = -35, self = this, // translate/rotate items moveItems = function() { --iter; // create a "grid" of possible positions var grid = []; // populate the positions grid for( var i = 0; i < columns; ++i ) { var col = grid[ i ] = []; for( var j = 0; j < lines; ++j ) { var xVal = j * (self.sizes.item.width * overlapFactor) - extraX, yVal = i * (self.sizes.item.height * overlapFactor) - extraY, olx = 0, oly = 0; if( self.started && iter === 0 ) { var ol = self._isOverlapping( { x : xVal, y : yVal } ); if( ol.overlapping ) { olx = ol.noOverlap.x; oly = ol.noOverlap.y; var r = Math.floor( Math.random() * 3 ); switch(r) { case 0 : olx = 0; break; case 1 : oly = 0; break; } } } col[ j ] = { x : xVal + olx, y : yVal + oly }; } } // shuffle grid = shuffleMArray(grid); var l = 0, c = 0, cntItemsAnim = 0; self.allItems.forEach( function( item, i ) { // pick a random item from the grid if( l === lines - 1 ) { c = c === columns - 1 ? 0 : c + 1; l = 1; } else { ++l } var randXPos = Math.floor( Math.random() * lines ), randYPos = Math.floor( Math.random() * columns ), gridVal = grid[c][l-1], translation = { x : gridVal.x, y : gridVal.y }, onEndTransitionFn = function() { ++cntItemsAnim; if( support.transitions ) { this.removeEventListener( transEndEventName, onEndTransitionFn ); } if( cntItemsAnim === self.allItemsCount ) { if( iter > 0 ) { moveItems.call(); } else { // change transform-origin classie.addClass( self.currentItem, 'photostack-flip' ); // all done.. self.isShuffling = false; if( typeof self.options.callback === 'function' ) { self.options.callback( self.currentItem ); } } } }; if(self.items.indexOf(item) === self.current && self.started && iter === 0) { self.currentItem.style.WebkitTransform = 'translate(' + self.centerItem.x + 'px,' + self.centerItem.y + 'px) rotate(0deg)'; self.currentItem.style.msTransform = 'translate(' + self.centerItem.x + 'px,' + self.centerItem.y + 'px) rotate(0deg)'; self.currentItem.style.transform = 'translate(' + self.centerItem.x + 'px,' + self.centerItem.y + 'px) rotate(0deg)'; // if there is something behind.. if( self.currentItem.querySelector( '.photostack-back' ) ) { self._addItemPerspective(); } classie.addClass( self.currentItem, 'photostack-current' ); } else { item.style.WebkitTransform = 'translate(' + translation.x + 'px,' + translation.y + 'px) rotate(' + Math.floor( Math.random() * (maxrot - minrot + 1) + minrot ) + 'deg)'; item.style.msTransform = 'translate(' + translation.x + 'px,' + translation.y + 'px) rotate(' + Math.floor( Math.random() * (maxrot - minrot + 1) + minrot ) + 'deg)'; item.style.transform = 'translate(' + translation.x + 'px,' + translation.y + 'px) rotate(' + Math.floor( Math.random() * (maxrot - minrot + 1) + minrot ) + 'deg)'; } if( self.started ) { if( support.transitions ) { item.addEventListener( transEndEventName, onEndTransitionFn ); } else { onEndTransitionFn(); } } } ); }; moveItems.call(); } Photostack.prototype._getSizes = function() { this.sizes = { inner : { width : this.inner.offsetWidth, height : this.inner.offsetHeight }, item : { width : this.currentItem.offsetWidth, height : this.currentItem.offsetHeight } }; // translation values to center an item this.centerItem = { x : this.sizes.inner.width / 2 - this.sizes.item.width / 2, y : this.sizes.inner.height / 2 - this.sizes.item.height / 2 }; } Photostack.prototype._isOverlapping = function( itemVal ) { var dxArea = this.sizes.item.width + this.sizes.item.width / 3, // adding some extra avoids any rotated item to touch the central area dyArea = this.sizes.item.height + this.sizes.item.height / 3, areaVal = { x : this.sizes.inner.width / 2 - dxArea / 2, y : this.sizes.inner.height / 2 - dyArea / 2 }, dxItem = this.sizes.item.width, dyItem = this.sizes.item.height; if( !(( itemVal.x + dxItem ) < areaVal.x || itemVal.x > ( areaVal.x + dxArea ) || ( itemVal.y + dyItem ) < areaVal.y || itemVal.y > ( areaVal.y + dyArea )) ) { // how much to move so it does not overlap? // move left / or move right var left = Math.random() < 0.5, randExtraX = Math.floor( Math.random() * (dxItem/4 + 1) ), randExtraY = Math.floor( Math.random() * (dyItem/4 + 1) ), noOverlapX = left ? (itemVal.x - areaVal.x + dxItem) * -1 - randExtraX : (areaVal.x + dxArea) - (itemVal.x + dxItem) + dxItem + randExtraX, noOverlapY = left ? (itemVal.y - areaVal.y + dyItem) * -1 - randExtraY : (areaVal.y + dyArea) - (itemVal.y + dyItem) + dyItem + randExtraY; return { overlapping : true, noOverlap : { x : noOverlapX, y : noOverlapY } } } return { overlapping : false } } Photostack.prototype._addItemPerspective = function() { classie.addClass( this.el, 'photostack-perspective' ); } Photostack.prototype._removeItemPerspective = function() { classie.removeClass( this.el, 'photostack-perspective' ); classie.removeClass( this.currentItem, 'photostack-flip' ); } Photostack.prototype._rotateItem = function( callback ) { if( classie.hasClass( this.el, 'photostack-perspective' ) && !this.isRotating && !this.isShuffling ) { this.isRotating = true; var self = this, onEndTransitionFn = function() { if( support.transitions && support.preserve3d ) { this.removeEventListener( transEndEventName, onEndTransitionFn ); } self.isRotating = false; if( typeof callback === 'function' ) { callback(); } }; if( this.flipped ) { classie.removeClass( this.navDots[ this.current ], 'flip' ); if( support.preserve3d ) { this.currentItem.style.WebkitTransform = 'translate(' + this.centerItem.x + 'px,' + this.centerItem.y + 'px) rotateY(0deg)'; this.currentItem.style.transform = 'translate(' + this.centerItem.x + 'px,' + this.centerItem.y + 'px) rotateY(0deg)'; } else { classie.removeClass( this.currentItem, 'photostack-showback' ); } } else { classie.addClass( this.navDots[ this.current ], 'flip' ); if( support.preserve3d ) { this.currentItem.style.WebkitTransform = 'translate(' + this.centerItem.x + 'px,' + this.centerItem.y + 'px) translate(' + this.sizes.item.width + 'px) rotateY(-179.9deg)'; this.currentItem.style.transform = 'translate(' + this.centerItem.x + 'px,' + this.centerItem.y + 'px) translate(' + this.sizes.item.width + 'px) rotateY(-179.9deg)'; } else { classie.addClass( this.currentItem, 'photostack-showback' ); } } this.flipped = !this.flipped; if( support.transitions && support.preserve3d ) { this.currentItem.addEventListener( transEndEventName, onEndTransitionFn ); } else { onEndTransitionFn(); } } } // add to global namespace window.Photostack = Photostack; var initPhotoSwipeFromDOM = function (gallerySelector) { // parse slide data (url, title, size ...) from DOM elements // (children of gallerySelector) var parseThumbnailElements = function (el) { var thumbElements = el.childNodes , numNodes = thumbElements.length , items = [] , figureEl , linkEl , size , item; for (var i = 0; i < numNodes; i++) { figureEl = thumbElements[i]; // <figure> element // include only element nodes if (figureEl.nodeType !== 1 || figureEl.nodeName.toUpperCase() !== 'FIGURE') { continue; } linkEl = figureEl.children[0]; // <a> element size = linkEl.getAttribute('data-size').split('x'); // create slide object item = { src: linkEl.getAttribute('href') , w: parseInt(size[0], 10) , h: parseInt(size[1], 10) }; if (figureEl.children.length > 1) { // <figcaption> content item.title = figureEl.children[1].innerHTML; } if (linkEl.children.length > 0) { // <img> thumbnail element, retrieving thumbnail url item.msrc = linkEl.children[0].getAttribute('src'); } item.el = figureEl; // save link to element for getThumbBoundsFn items.push(item); } return items; }; // find nearest parent element var closest = function closest(el, fn) { return el && (fn(el) ? el : closest(el.parentNode, fn)); }; // triggers when user clicks on thumbnail var onThumbnailsClick = function (e) { e = e || window.event; e.preventDefault ? e.preventDefault() : e.returnValue = false; var eTarget = e.target || e.srcElement; // find root element of slide var clickedListItem = closest(eTarget, function (el) { return (el.tagName && el.tagName.toUpperCase() === 'FIGURE' && classie.hasClass( el, 'photostack-current' ) ); }); if (!clickedListItem) { return; } // find index of clicked item by looping through all child nodes // alternatively, you may define index via data- attribute var clickedGallery = clickedListItem.parentNode , childNodes = clickedListItem.parentNode.childNodes , numChildNodes = childNodes.length , nodeIndex = 0 , index; for (var i = 0; i < numChildNodes; i++) { if (childNodes[i].nodeType !== 1) { continue; } if (childNodes[i] === clickedListItem) { index = nodeIndex; break; } nodeIndex++; } if (index >= 0) { // open PhotoSwipe if valid index found openPhotoSwipe(index, clickedGallery); } return false; }; // parse picture index and gallery index from URL (#&pid=1&gid=2) var photoswipeParseHash = function () { var hash = window.location.hash.substring(1) , params = {}; if (hash.length < 5) { return params; } var vars = hash.split('&'); for (var i = 0; i < vars.length; i++) { if (!vars[i]) { continue; } var pair = vars[i].split('='); if (pair.length < 2) { continue; } params[pair[0]] = pair[1]; } if (params.gid) { params.gid = parseInt(params.gid, 10); } return params; }; var openPhotoSwipe = function (index, galleryElement, disableAnimation, fromURL) { var pswpElement = document.querySelectorAll('.pswp')[0] , gallery , options , items; items = parseThumbnailElements(galleryElement); // define options (if needed) options = { // define gallery index (for URL) galleryUID: galleryElement.getAttribute('data-pswp-uid') , getThumbBoundsFn: function (index) { // See Options -> getThumbBoundsFn section of documentation for more info var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail pageYScroll = window.pageYOffset || document.documentElement.scrollTop , rect = thumbnail.getBoundingClientRect(); return { x: rect.left , y: rect.top + pageYScroll , w: rect.width }; } }; // PhotoSwipe opened from URL if (fromURL) { if (options.galleryPIDs) { // parse real index when custom PIDs are used // http://photoswipe.com/documentation/faq.html#custom-pid-in-url for (var j = 0; j < items.length; j++) { if (items[j].pid == index) { options.index = j; break; } } } else { // in URL indexes start from 1 options.index = parseInt(index, 10) - 1; } } else { options.index = parseInt(index, 10); } // exit if index not found if (isNaN(options.index)) { return; } if (disableAnimation) { options.showAnimationDuration = 0; } // Pass data to PhotoSwipe and initialize it gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options); gallery.init(); }; // loop through all gallery elements and bind events var galleryElements = document.querySelectorAll(gallerySelector); for (var i = 0, l = galleryElements.length; i < l; i++) { galleryElements[i].setAttribute('data-pswp-uid', i + 1); galleryElements[i].onclick = onThumbnailsClick; } // Parse URL and open gallery if it contains #&pid=3&gid=1 var hashData = photoswipeParseHash(); if (hashData.pid && hashData.gid) { openPhotoSwipe(hashData.pid, galleryElements[hashData.gid - 1], true, true); } }; // execute above function initPhotoSwipeFromDOM('.photostack-container'); })( window );
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var platform_browser_1 = require('@angular/platform-browser'); var forms_1 = require('@angular/forms'); var app_component_1 = require('./app.component'); var people_service_1 = require('./people.service'); var people_list_component_1 = require('./people-list.component'); var person_details_component_1 = require('./person-details.component'); var person_component_1 = require('./+person/person.component'); var http_1 = require('@angular/http'); var angular_datatables_module_1 = require('./shared/modules/datatables/angular-datatables/angular-datatables.module'); var app_routes_1 = require('./app.routes'); var AppModule = (function () { function AppModule() { } AppModule = __decorate([ core_1.NgModule({ imports: [platform_browser_1.BrowserModule, app_routes_1.routing, forms_1.FormsModule, http_1.HttpModule, angular_datatables_module_1.DataTablesModule], declarations: [app_component_1.AppComponent, people_list_component_1.PeopleListComponent, person_details_component_1.PersonDetailsComponent, person_component_1.PersonComponent], bootstrap: [app_component_1.AppComponent], providers: [people_service_1.PeopleService] }), __metadata('design:paramtypes', []) ], AppModule); return AppModule; }()); exports.AppModule = AppModule; //# sourceMappingURL=app.module.js.map
import { div } from '../core/dom-api'; import { urls } from '../urls'; const commentsSort = (a, b) => { if (a.time < b.time) return -1; if (a.time > b.time) return 1; return 0; }; const commentElement = (data) => { let replies = data && data.comments && data.comments.length && data.comments .sort(commentsSort) .map(item => commentElement(item)); return`<div class="comment"> <div class="details"> <div class="user">${data.user}</div> <div class="time">${data.time_ago}</div> </div> <div class="content"> ${data.content} </div> ${replies ? replies.join('') : ''} </div>`; }; const commentsElement = (comments) => { return `<div class="comments">${comments.length && comments.sort(commentsSort).map(data => commentElement(data)).join('')}</div>`; }; export const CommentsView = (props) => { let template; let data; let timeoutId; const loadData = () => { fetch(urls.item(props.routeParams.id)) .then(res => res.json()) .then(res => { data = res; render(); }); }; function createTemplate() { let hasComments = data.comments.length; let commentsContent = commentsElement(data.comments); let url = data.url; url = url.indexOf('item') === 0 ? '/' + url : url; // Set the title document.querySelector('title').innerText = `${data.title} | Vanilla Hacker News PWA`; // Clear timeout if (timeoutId) clearTimeout(timeoutId); return div({ className: 'item-view' }, ` <a class="title" href="${url}" target="_blank"> <h1>${data.title}<span>&#x2197;</span></h1> </a> <div class="subtitle ${data.type}"> <div class="user">${data.user}</div> <div class="time-ago">${data.time_ago}</div> <div class="stars">${data.points} <span>★</span></div> </div> <div class="content"> ${data.content || 'No content'} </div> <div class="comments"> <div class="subtitle">${hasComments ? 'Comments' : 'No coments'}</div> ${commentsContent} </div> `); } function createFirstTemplate() { const firstTemplate = div({ className: 'item-view' }, '<div class="content-loading">Loading content</div>'); timeoutId = setTimeout(() => { firstTemplate.querySelector('.content-loading').innerHTML += '<br/>...<br/>Looks like it takes longer than expected'; scheduleLongerTimeout(firstTemplate); }, 1e3); return firstTemplate; } function scheduleLongerTimeout(el) { timeoutId = setTimeout(() => { el.querySelector('.content-loading').innerHTML += '</br>...<br/>It\'s been over 2 seconds now, content should be arriving soon'; }, 1500); } function render() { if (!!template.parentElement) { let newTemplate = createTemplate(); template.parentElement.replaceChild(newTemplate, template); template = newTemplate; } } template = createFirstTemplate(); loadData(); return template; };
'use strict'; var assert = require('assert'); var resource = require('../resource'); exports.Person = resource.create('Person', {api: 'person', version: 2}) .extend({ flag: function(options){ return this.constructor.post('/people/' + this.id + '/flag', options); } }, { find: function(options){ options = options || {}; assert(options.email, 'An email must be provided'); return this.get('/people/find', options); } });
var opn = require('opn'); console.log('打开二维码...') // Opens the image in the default image viewer opn('static/img/qr.jpg').then(() => { console.log('关闭二维码!') });
//= require "dep3-1-1.js, dep3.js"
function init_map(field_id) { //console.log(field_id); } /*acf.fields.address = acf.field.extend({ type: 'address', $el: null, $input: null, status: '', // '', 'loading', 'ready' geocoder: false, map: false, maps: {}, pending: $(), actions: { 'ready': 'initialize' }, initialize: function () { console.log('init'); } });*/ (function ($) { function initialize_field($el) { console.log('init hook'); console.log($el); initMap($el); } if (typeof acf.add_action !== 'undefined') { /* * ready append (ACF5) * * These are 2 events which are fired during the page load * ready = on page load similar to $(document).ready() * append = on new DOM elements appended via repeater field * * @type event * @date 20/07/13 * * @param $el (jQuery selection) the jQuery element which contains the ACF fields * @return n/a */ acf.add_action('ready append', function ($el) { // search $el for fields of type 'FIELD_NAME' acf.get_fields({type: 'address'}, $el).each(function () { initialize_field($(this)); }); }); } else { /* * acf/setup_fields (ACF4) * * This event is triggered when ACF adds any new elements to the DOM. * * @type function * @since 1.0.0 * @date 01/01/12 * * @param event e: an event object. This can be ignored * @param Element postbox: An element which contains the new HTML * * @return n/a */ $(document).on('acf/setup_fields', function (e, postbox) { $(postbox).find('.field[data-field_type="address"]').each(function () { initialize_field($(this)); }); }); } function initMap($mapElement) { ymaps.ready(function () { /** * Массив сохраняемых данных * * address - краткий адрес, без города * addressFull - полный адрес, с городом * coordinates - координаты адреса * coordinatesMetro - координаты ближайшей станции метро * metroDist - расстояние до ближайшей станции метро (в метрах) * addressMetro - адрес ближайшей станции метро * addressMetroFull - полный адрес ближайшей станции метро * metroLine - ближайшая линия метро, формат line_{number} * * @type {{}} */ var field = {}; /** * Центр карты и координаты метки по умолчанию * @type {number[]} */ var centerMap = [55.753994, 37.622093]; /** * Карта * @type {undefined} */ var addressMap = undefined; /** * Метка * @type {ymaps.GeoObject} */ var geoPoint = new ymaps.GeoObject({ geometry: { type: "Point", coordinates: centerMap } }, { preset: 'islands#blackStretchyIcon', draggable: true }); geoPoint.events.add('dragend', function () { changeLocation(); }); /** * Кнопка определения местоположения * @type {GeolocationButton} */ var geolocationButton = new GeolocationButton({ data: { image: btn.img, title: 'Определить местоположение' }, geolocationOptions: { enableHighAccuracy: true, noPlacemark: false, point: geoPoint, afterSearch: function () { changeLocation() } } }, { selectOnClick: false }); /** * Строка поиска адреса * @type {ymaps.control.SearchControl} */ var searchControl = new ymaps.control.SearchControl({ noPlacemark: true }); searchControl.events.add('resultselect', function (e) { var index = e.get("resultIndex"); var result = searchControl.getResult(index); result.then(function (res) { var geo = res.geometry.getCoordinates(); geoPoint.geometry.setCoordinates(geo); changeLocation(); }); }); /** * Кнопка для поиска ближайшего метро * @type {Button} */ var button = new ymaps.control.Button({ data: { image: btn.metro, title: 'Найти ближайшее метро' } }, { selectOnClick: false }); button.events.add('click', function () { findMetro(); }); /** * Поиск ближайшего метро */ function findMetro() { ymaps.geocode(field.coordinates, { kind: 'metro', results: 1 }).then(function (res) { if (res.geoObjects.getLength()) { var m0 = res.geoObjects.get(0); var coords = m0.geometry.getCoordinates(); field.coordinatesMetro = coords; var dist = ymaps.coordSystem.geo.getDistance(field.coordinates, coords); field.metroDist = Math.round(dist).toFixed(0); res.geoObjects.options.set('preset', 'twirl#metroMoscowIcon'); addressMap.geoObjects.add(res.geoObjects); var getObject = res.geoObjects.get(0); field.addressMetro = getObject.properties.get('name'); field.addressMetroFull = getObject.properties.get('text').replace('Россия,', '').trim(); $('.metro-row').show(); $('input[name="metro"]').val(field.addressMetro); $('input[name="metro_full"]').val(field.addressMetroFull); $('input[name="metro_dist"]').val(field.metroDist); var metroLine = colorMetro(field.addressMetroFull); if (metroLine != undefined) field.metroLine = metroLine; } }); } /** * Событие при смене координат */ function changeLocation() { var coord = geoPoint.geometry.getCoordinates(); field.coordinates = coord; ymaps.geocode(coord).then(function (res) { var getObject = res.geoObjects.get(0); field.address = getObject.properties.get('name'); field.addressFull = getObject.properties.get('text').replace('Россия,', '').trim(); updateField(); }); } /** * Обновление полей с адресом */ function updateField() { $('input[name="address"]').val(field.address); $('input[name="address_full"]').val(field.addressFull); } /** * Загрузка данных */ function loadField() { //field = JSON.parse($('#acf-address-input').val()); updateField(); var loadCoord = (field.coordinates != undefined) ? field.coordinates : centerMap; var loadZoom = (field.zoom != undefined) ? field.zoom : 10; geoPoint.geometry.setCoordinates(loadCoord); addressMap.setCenter(loadCoord); addressMap.setZoom(loadZoom); if (field.addressMetro != undefined || field.addressMetroFull != undefined) { $('.metro-row').show(); $('input[name="metro"]').val(field.addressMetro); $('input[name="metro_full"]').val(field.addressMetroFull); $('input[name="metro_dist"]').val(field.metroDist); } } /** * Возвращает номер линии метро * * @param metro * @returns {*} */ function colorMetro(metro) { var metroArray = metro.split(','); if (metroArray.length >= 3) { metro = metroArray[2].replace('линия', '').trim(); } else return undefined; var moscowMetro = {}; moscowMetro['Сокольническая'] = 'line_1'; moscowMetro['Замоскворецкая'] = 'line_2'; moscowMetro['Арбатско-Покровская'] = 'line_3'; moscowMetro['Филёвская'] = 'line_4'; moscowMetro['Кольцевая'] = 'line_5'; moscowMetro['Калужско-Рижская'] = 'line_6'; moscowMetro['Таганско-Краснопресненская'] = 'line_7'; moscowMetro['Калининско-Солнцевская'] = 'line_8'; moscowMetro['Калининская'] = 'line_8'; moscowMetro['Серпуховско-Тимирязевская'] = 'line_9'; moscowMetro['Люблинско-Дмитровская'] = 'line_10'; moscowMetro['Каховская'] = 'line_11'; moscowMetro['Бутовская'] = 'line_12'; return moscowMetro[metro]; } $('.address-btn-cancel').click(function () { tb_remove(); }); $('#address-btn-ok').click(function () { $('#acf-address-input').val(JSON.stringify(field)); $('#acf-address-display').val(field.addressFull); tb_remove(); }); $('#acf-address-btn').click(function () { if (addressMap != undefined) addressMap.destroy(); addressMap = new ymaps.Map($mapElement, { center: centerMap, zoom: 9, behaviors: ['default', 'scrollZoom'] }); addressMap.events.add('boundschange', function (e) { var zoom = e.get("newZoom"); field.zoom = zoom; }); addressMap.controls .add(geolocationButton, {top: 5, left: 100}) .add('zoomControl') .add('typeSelector', {top: 5, right: 5}) .add(button, {top: 5, left: 65}) .add(searchControl, {top: 5, left: 200}); addressMap.geoObjects.add(geoPoint); loadField(); }); $('#acf-address-clear').click(function () { field = {}; $('.metro-row').hide(); $('#acf-address-display').val(''); $('#acf-address-display').val(''); $('input[name="metro"]').val(''); $('input[name="metro_full"]').val(''); $('input[name="metro_dist"]').val(''); }); $('#acf-address-display').click(function () { $('#acf-address-btn').trigger('click'); }); field = JSON.parse($('#acf-address-input').val()); $('#acf-address-display').val(field.addressFull); }); } })(jQuery);
// flow-typed signature: 02c97f596f96a486574f8fb0fd727a55 // flow-typed version: <<STUB>>/eslint-config-google_v0.14.0/flow_v0.108.0 /** * This is an autogenerated libdef stub for: * * 'eslint-config-google' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'eslint-config-google' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ // Filename aliases declare module 'eslint-config-google/index' { declare module.exports: $Exports<'eslint-config-google'>; } declare module 'eslint-config-google/index.js' { declare module.exports: $Exports<'eslint-config-google'>; }
import { combineReducers } from 'redux' import userInfo from './userInfo' import userFeed from './userFeed' import popularFeed from './popularFeed' export default combineReducers({ userInfo, userFeed, popularFeed })
/* comment */ var g = 1, i = 2, j = 2/* *//1+g+"\/*"/i, x = 3, a = 2/1/g, b = (i)/i/i/* */, s = 'aaa\ bbb\ ccc'; var z = 1;
const matcher = require('../lib/matcher'); describe('Matcher', () => { describe('path', () => { let mock; let request; beforeEach(() => { mock = { request: { path: '/test' } }; request = { originalUrl: '/test?blah=test', path: '/test' }; }); test('should return true if request path exactly matches mock request path', () => { expect(matcher.path(mock, request)).toBe(true); }); test('should return true if request path matches mock request greedy path', () => { mock.request.path = '/test/*'; request.path = '/test/anything'; expect(matcher.path(mock, request)).toBe(true); }); test('should return true if request path matches mock request named path', () => { mock.request.path = '/test/:named/end'; request.path = '/test/anything/end'; expect(matcher.path(mock, request)).toBe(true); }); test('should return false if request path does not match mock request named path', () => { mock.request.path = '/test/:named/end'; request.path = '/this/will/never/match'; expect(matcher.path(mock, request)).toBe(false); }); }); describe('headers', () => { let mock; let request; beforeEach(() => { mock = { request: { headers: { test: 'this' } } }; request = { headers: { test: 'this' } }; }); test('should return true if request headers exactly match mock request headers', () => { expect(matcher.headers(mock, request)).toBe(true); }); test('should return true if request headers contain the mock request headers', () => { request.headers.another = 'glah'; expect(matcher.headers(mock, request)).toBe(true); }); test('should return false if request headers do not match the mock request header values', () => { request.headers = { test: 'nope' }; expect(matcher.headers(mock, request)).toBe(false); }); test('should return false if request headers do not contain the mock request header values', () => { request.headers = { another: 'header' }; expect(matcher.headers(mock, request)).toBe(false); }); }); describe('query', () => { let mock; let request; beforeEach(() => { mock = { request: { query: { test: 'this' } } }; request = { query: { test: 'this' } }; }); test('should return true if mock has no query specified', () => { delete mock.request.query; expect(matcher.query(mock, request)).toBe(true); }); test('should return true if mock has empty query specified', () => { delete mock.request.query.test; expect(matcher.query(mock, request)).toBe(true); }); test('should return true if request query exactly match mock request query', () => { expect(matcher.query(mock, request)).toBe(true); }); test('should return true if request query contain the mock request query', () => { request.query.another = 'glah'; expect(matcher.query(mock, request)).toBe(true); }); test('should return false if request query does not match the mock request header values', () => { request.query = { test: 'nope' }; expect(matcher.query(mock, request)).toBe(false); }); test('should return false if request query does not contain the mock request header values', () => { request.query = { another: 'header' }; expect(matcher.query(mock, request)).toBe(false); }); test('RegExp - should return true if request query matches', () => { mock.request.query.email = { type: 'regex', value: '.*?@bar\.com' }; request.query = { test: 'this', email: '[email protected]' }; expect(matcher.query(mock, request)).toBe(true); }); }); describe('body', () => { let mock; let request; beforeEach(() => { mock = { request: { body: { test: 'this' } } }; request = { body: { test: 'this' } }; }); test('should return true if request body exactly match mock request body', () => { expect(matcher.body(mock, request)).toBe(true); }); test('should return true if request body contain the mock request body', () => { request.body.another = 'glah'; expect(matcher.body(mock, request)).toBe(true); }); test('should return false if request body does not match the mock request header values', () => { request.body = { test: 'nope' }; expect(matcher.body(mock, request)).toBe(false); }); test('should return false if request body does not contain the mock request header values', () => { request.body = { another: 'field' }; expect(matcher.body(mock, request)).toBe(false); }); }); });