code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
"use strict" const path = require('path') class Helpers { static getPageIdFromFilenameOrLink(filename) { var base = path.basename(filename) if (base.substr(-3) === '.md') { base = base.substr(0, base.length - 3) } return base.replace(/([^a-z0-9\-_~]+)/gi, '') } } module.exports = Helpers
limedocs/limedocs-wiki-converter
src/helpers.js
JavaScript
mit
320
import { vec3, mat4, quat } from 'gl-matrix'; import Vector3 from './vector3'; let uuid = 0; let axisAngle = 0; const quaternionAxisAngle = vec3.create(); class Object3 { constructor() { this.uid = uuid++; this.position = new Vector3(); this.rotation = new Vector3(); this.scale = new Vector3(1, 1, 1); this.quaternion = quat.create(); this.target = vec3.create(); this.up = vec3.fromValues(0, 1, 0); this.parent = null; this.children = []; this.parentMatrix = mat4.create(); this.modelMatrix = mat4.create(); this.lookAtMatrix = mat4.create(); // use mat4.targetTo rotation when set to true this.lookToTarget = false; // use lookAt rotation when set to true // enable polygonOffset (z-fighting) this.polygonOffset = false; this.polygonOffsetFactor = 0; this.polygonOffsetUnits = 1; } addModel(model) { model.parent = this; // eslint-disable-line this.children.push(model); } removeModel(model) { const index = this.children.indexOf(model); if (index !== -1) { model.destroy(); this.children.splice(index, 1); } } updateMatrices() { mat4.identity(this.parentMatrix); mat4.identity(this.modelMatrix); mat4.identity(this.lookAtMatrix); quat.identity(this.quaternion); if (this.parent) { mat4.copy(this.parentMatrix, this.parent.modelMatrix); mat4.multiply(this.modelMatrix, this.modelMatrix, this.parentMatrix); } if (this.lookToTarget) { mat4.targetTo(this.lookAtMatrix, this.position.data, this.target, this.up); mat4.multiply(this.modelMatrix, this.modelMatrix, this.lookAtMatrix); } else { mat4.translate(this.modelMatrix, this.modelMatrix, this.position.data); quat.rotateX(this.quaternion, this.quaternion, this.rotation.x); quat.rotateY(this.quaternion, this.quaternion, this.rotation.y); quat.rotateZ(this.quaternion, this.quaternion, this.rotation.z); axisAngle = quat.getAxisAngle(quaternionAxisAngle, this.quaternion); mat4.rotate(this.modelMatrix, this.modelMatrix, axisAngle, quaternionAxisAngle); } mat4.scale(this.modelMatrix, this.modelMatrix, this.scale.data); } } export default Object3;
andrevenancio/engine
src/core/object3.js
JavaScript
mit
2,458
import React from 'react'; import PropTypes from 'prop-types'; import Logo from './Logo'; import SearchBar from './SearchBar'; import { CSSTransitionGroup } from 'react-transition-group'; class Header extends React.Component { render() { let header = window.scrollY > 170 && window.innerWidth > 800 ? <div key={this.props.path} className='app-header'> <Logo/> <SearchBar path={this.props.path} history={this.props.history} setResults={this.props.setResults} toggleFetch={this.props.toggleFetch} isBookMenuActive={this.props.isBookMenuActive} /> </div> : null; return ( <CSSTransitionGroup transitionName="header" transitionEnterTimeout={200} transitionLeaveTimeout={200}> {header} </CSSTransitionGroup> ) } } Header.propTypes = { setResults: PropTypes.func.isRequired, toggleFetch: PropTypes.func.isRequired, history: PropTypes.object.isRequired, path: PropTypes.string.isRequired, isBookMenuActive: PropTypes.bool.isRequired }; export default Header;
pixel-glyph/better-reads
src/components/Header.js
JavaScript
mit
1,137
/** * Grunt Project * https://github.com/sixertoy/generator-grunt-project * * Copyright (c) 2014 Matthieu Lassalvy * Licensed under the MIT license. * * Generate folder and files for a grunt project * with grunt basic tasks, jasmine unit testing, istanbul coverage and travis deployement * * @insatll npm install grunt-cli yo bower -g * @usage yo grunt-project * * */ /*global require, process, module */ (function () { 'use strict'; var eZHTMLGenerator, Q = require('q'), path = require('path'), yosay = require('yosay'), lodash = require('lodash'), slugify = require('slugify'), AppBones = require('appbones'), pkg = require('../../package.json'), generators = require('yeoman-generator'); eZHTMLGenerator = generators.Base.extend({ constructor: function () { generators.Base.apply(this, arguments); this.option('skip-install', { desc: 'Skip the bower and node installations', defaults: false }); }, initializing: function () { // custom templates delimiter this.config.set('rdim', '%>'); this.config.set('ldim', '<%='); this.log(yosay('Hello sir, welcome to the awesome ezhtml generator v' + pkg.version)); }, prompting: function () { var $this = this, prompts = [], done = this.async(); // project name prompts.push({ type: 'input', name: 'projectname', message: 'Project name', default: slugify(this.determineAppname()) }); prompts.push({ type: 'input', name: 'username', message: 'Repository user name', default: this.user.git.name() || process.env.user || process.env.username }); prompts.push({ type: 'input', name: 'useremail', message: 'Repository user email', default: this.user.git.email() || '[email protected]' }); // project name prompts.push({ type: 'input', name: 'projectdescription', message: 'Project description', default: 'Project generated with Yeoman generator-ezhtml v' + pkg.version }); prompts.push({ type: 'input', name: 'projectrepository', message: 'Project repository url', default: function (values) { return 'https://github.com' + '/' + values.username + '/' + values.projectname; } }); this.prompt(prompts, function (values) { this.config.set('author', { name: values.username, email: values.useremail }); this.config.set('project', { name: values.projectname, repository: values.projectrepository, description: values.projectdescription }); done(); }.bind(this)); }, configuring: function () { // this.composeWith('ezhtml:conditionnals', {}); if (!this.options['skip-install']) { this.composeWith('ezhtml:scripts', {}); this.composeWith('ezhtml:styles', {}); } }, writing: function () { var $this = this, done = this.async(), data = this.config.getAll(), bones = path.resolve(this.templatePath(), '../bones.yml'), appbones = new AppBones(this.templatePath(), this.destinationPath()); Q.delay((function () { appbones.build(bones, data); }()), 1500).then((function () { done(); }())); }, install: function () { if (!this.options['skip-install']) { this.npmInstall(); } }, end: function () {} }); module.exports = eZHTMLGenerator; }());
sixertoy/generator-ezhtml
generators/app/index.js
JavaScript
mit
4,305
const debug = require('ghost-ignition').debug('importer:posts'), _ = require('lodash'), uuid = require('uuid'), BaseImporter = require('./base'), converters = require('../../../../lib/mobiledoc/converters'), validation = require('../../../validation'); class PostsImporter extends BaseImporter { constructor(allDataFromFile) { super(allDataFromFile, { modelName: 'Post', dataKeyToImport: 'posts', requiredFromFile: ['posts', 'tags', 'posts_tags', 'posts_authors'], requiredImportedData: ['tags'], requiredExistingData: ['tags'] }); } sanitizeAttributes() { _.each(this.dataToImport, (obj) => { if (!validation.validator.isUUID(obj.uuid || '')) { obj.uuid = uuid.v4(); } }); } /** * Naive function to attach related tags and authors. */ addNestedRelations() { this.requiredFromFile.posts_tags = _.orderBy(this.requiredFromFile.posts_tags, ['post_id', 'sort_order'], ['asc', 'asc']); this.requiredFromFile.posts_authors = _.orderBy(this.requiredFromFile.posts_authors, ['post_id', 'sort_order'], ['asc', 'asc']); /** * from {post_id: 1, tag_id: 2} to post.tags=[{id:id}] * from {post_id: 1, author_id: 2} post.authors=[{id:id}] */ const run = (relations, target, fk) => { _.each(relations, (relation) => { if (!relation.post_id) { return; } let postToImport = _.find(this.dataToImport, {id: relation.post_id}); // CASE: we won't import a relation when the target post does not exist if (!postToImport) { return; } if (!postToImport[target] || !_.isArray(postToImport[target])) { postToImport[target] = []; } // CASE: detect duplicate relations if (!_.find(postToImport[target], {id: relation[fk]})) { postToImport[target].push({ id: relation[fk] }); } }); }; run(this.requiredFromFile.posts_tags, 'tags', 'tag_id'); run(this.requiredFromFile.posts_authors, 'authors', 'author_id'); } /** * Replace all identifier references. */ replaceIdentifiers() { const ownerUserId = _.find(this.requiredExistingData.users, (user) => { if (user.roles[0].name === 'Owner') { return true; } }).id; const run = (postToImport, postIndex, targetProperty, tableName) => { if (!postToImport[targetProperty] || !postToImport[targetProperty].length) { return; } let indexesToRemove = []; _.each(postToImport[targetProperty], (object, index) => { // this is the original relational object (old id) let objectInFile = _.find(this.requiredFromFile[tableName], {id: object.id}); if (!objectInFile) { let existingObject = _.find(this.requiredExistingData[tableName], {id: object.id}); // CASE: is not in file, is not in db if (!existingObject) { indexesToRemove.push(index); return; } else { this.dataToImport[postIndex][targetProperty][index].id = existingObject.id; return; } } // CASE: search through imported data. // EDGE CASE: uppercase tag slug was imported and auto modified let importedObject = _.find(this.requiredImportedData[tableName], {originalSlug: objectInFile.slug}); if (importedObject) { this.dataToImport[postIndex][targetProperty][index].id = importedObject.id; return; } // CASE: search through existing data by unique attribute let existingObject = _.find(this.requiredExistingData[tableName], {slug: objectInFile.slug}); if (existingObject) { this.dataToImport[postIndex][targetProperty][index].id = existingObject.id; } else { indexesToRemove.push(index); } }); this.dataToImport[postIndex][targetProperty] = _.filter(this.dataToImport[postIndex][targetProperty], ((object, index) => { return indexesToRemove.indexOf(index) === -1; })); // CASE: we had to remove all the relations, because we could not match or find the relation reference. // e.g. you import a post with multiple authors. Only the primary author is assigned. // But the primary author won't be imported and we can't find the author in the existing database. // This would end in `post.authors = []`, which is not allowed. There must be always minimum one author. // We fallback to the owner user. if (targetProperty === 'authors' && !this.dataToImport[postIndex][targetProperty].length) { this.dataToImport[postIndex][targetProperty] = [{ id: ownerUserId }]; } }; _.each(this.dataToImport, (postToImport, postIndex) => { run(postToImport, postIndex, 'tags', 'tags'); run(postToImport, postIndex, 'authors', 'users'); }); return super.replaceIdentifiers(); } beforeImport() { debug('beforeImport'); this.sanitizeAttributes(); this.addNestedRelations(); _.each(this.dataToImport, (model) => { // NOTE: we remember the original post id for disqus // (see https://github.com/TryGhost/Ghost/issues/8963) // CASE 1: you import a 1.0 export (amp field contains the correct disqus id) // CASE 2: you import a 2.0 export (we have to ensure we use the original post id as disqus id) if (model.id && model.amp) { model.comment_id = model.amp; delete model.amp; } else { if (!model.comment_id) { model.comment_id = model.id; } } // CASE 1: you are importing old editor posts // CASE 2: you are importing Koenig Beta posts if (model.mobiledoc || (model.mobiledoc && model.html && model.html.match(/^<div class="kg-card-markdown">/))) { let mobiledoc; try { mobiledoc = JSON.parse(model.mobiledoc); if (!mobiledoc.cards || !_.isArray(mobiledoc.cards)) { model.mobiledoc = converters.mobiledocConverter.blankStructure(); mobiledoc = model.mobiledoc; } } catch (err) { mobiledoc = converters.mobiledocConverter.blankStructure(); } mobiledoc.cards.forEach((card) => { if (card[0] === 'image') { card[1].cardWidth = card[1].imageStyle; delete card[1].imageStyle; } }); model.mobiledoc = JSON.stringify(mobiledoc); model.html = converters.mobiledocConverter.render(JSON.parse(model.mobiledoc)); } }); // NOTE: We only support removing duplicate posts within the file to import. // For any further future duplication detection, see https://github.com/TryGhost/Ghost/issues/8717. let slugs = []; this.dataToImport = _.filter(this.dataToImport, (post) => { if (slugs.indexOf(post.slug) !== -1) { this.problems.push({ message: 'Entry was not imported and ignored. Detected duplicated entry.', help: this.modelName, context: JSON.stringify({ post: post }) }); return false; } slugs.push(post.slug); return true; }); // NOTE: do after, because model properties are deleted e.g. post.id return super.beforeImport(); } doImport(options, importOptions) { return super.doImport(options, importOptions); } } module.exports = PostsImporter;
tannermares/ghost
core/server/data/importer/importers/data/posts.js
JavaScript
mit
8,682
var path = require('path'); var expect = require('expect.js'); var _s = require('underscore.string'); var apellaJson = require('../lib/json'); var request = require('request'); describe('.find', function () { it('should find the apella.json file', function (done) { apellaJson.find(__dirname + '/pkg-apella-json', function (err, file) { if (err) { return done(err); } expect(file).to.equal(path.resolve(__dirname + '/pkg-apella-json/apella.json')); done(); }); }); it('should fallback to the component.json file', function (done) { apellaJson.find(__dirname + '/pkg-component-json', function (err, file) { if (err) { return done(err); } expect(file).to.equal(path.resolve(__dirname + '/pkg-component-json/component.json')); done(); }); }); it('should not fallback to the component.json file if it\'s a component(1) file', function (done) { apellaJson.find(__dirname + '/pkg-component(1)-json', function (err) { expect(err).to.be.an(Error); expect(err.code).to.equal('ENOENT'); expect(err.message).to.equal('None of apella.json, component.json, .apella.json were found in ' + __dirname + '/pkg-component(1)-json'); done(); }); }); it('should fallback to the .apella.json file', function (done) { apellaJson.find(__dirname + '/pkg-dot-apella-json', function (err, file) { if (err) { return done(err); } expect(file).to.equal(path.resolve(__dirname + '/pkg-dot-apella-json/.apella.json')); done(); }); }); it('should error if no component.json / apella.json / .apella.json is found', function (done) { apellaJson.find(__dirname, function (err) { expect(err).to.be.an(Error); expect(err.code).to.equal('ENOENT'); expect(err.message).to.equal('None of apella.json, component.json, .apella.json were found in ' + __dirname); done(); }); }); }); describe('.findSync', function () { it('should find the apella.json file', function (done) { var file = apellaJson.findSync(__dirname + '/pkg-apella-json'); expect(file).to.equal(path.resolve(__dirname + '/pkg-apella-json/apella.json')); done(); }); it('should fallback to the component.json file', function (done) { var file = apellaJson.findSync(__dirname + '/pkg-component-json'); expect(file).to.equal(path.resolve(__dirname + '/pkg-component-json/component.json')); done(); }); it('should fallback to the .apella.json file', function (done) { var file = apellaJson.findSync(__dirname + '/pkg-dot-apella-json'); expect(file).to.equal(path.resolve(__dirname + '/pkg-dot-apella-json/.apella.json')); done(); }); it('should error if no component.json / apella.json / .apella.json is found', function (done) { var err = apellaJson.findSync(__dirname); expect(err).to.be.an(Error); expect(err.code).to.equal('ENOENT'); expect(err.message).to.equal('None of apella.json, component.json, .apella.json were found in ' + __dirname); done(); }); }); describe('.read', function () { it('should give error if file does not exists', function (done) { apellaJson.read(__dirname + '/willneverexist', function (err) { expect(err).to.be.an(Error); expect(err.code).to.equal('ENOENT'); done(); }); }); it('should give error if when reading an invalid json', function (done) { apellaJson.read(__dirname + '/pkg-apella-json-malformed/apella.json', function (err) { expect(err).to.be.an(Error); expect(err.code).to.equal('EMALFORMED'); expect(err.file).to.equal(path.resolve(__dirname + '/pkg-apella-json-malformed/apella.json')); done(); }); }); it('should read the file and give an object', function (done) { apellaJson.read(__dirname + '/pkg-apella-json/apella.json', function (err, json) { if (err) { return done(err); } expect(json).to.be.an('object'); expect(json.name).to.equal('some-pkg'); expect(json.version).to.equal('0.0.0'); done(); }); }); it('should give the json file that was read', function (done) { apellaJson.read(__dirname + '/pkg-apella-json', function (err, json, file) { if (err) { return done(err); } expect(file).to.equal(__dirname + '/pkg-apella-json/apella.json'); done(); }); }); it('should find for a json file if a directory is given', function (done) { apellaJson.read(__dirname + '/pkg-component-json', function (err, json, file) { if (err) { return done(err); } expect(json).to.be.an('object'); expect(json.name).to.equal('some-pkg'); expect(json.version).to.equal('0.0.0'); expect(file).to.equal(path.resolve(__dirname + '/pkg-component-json/component.json')); done(); }); }); it('should validate the returned object unless validate is false', function (done) { apellaJson.read(__dirname + '/pkg-apella-json-invalid/apella.json', function (err) { expect(err).to.be.an(Error); expect(err.message).to.contain('name'); expect(err.file).to.equal(path.resolve(__dirname + '/pkg-apella-json-invalid/apella.json')); apellaJson.read(__dirname + '/pkg-apella-json-invalid/apella.json', { validate: false }, function (err) { done(err); }); }); }); it('should normalize the returned object if normalize is true', function (done) { apellaJson.read(__dirname + '/pkg-apella-json/apella.json', function (err, json) { if (err) { return done(err); } expect(json.main).to.equal('foo.js'); apellaJson.read(__dirname + '/pkg-apella-json/apella.json', { normalize: true }, function (err, json) { if (err) { return done(err); } expect(json.main).to.eql(['foo.js']); done(); }); }); }); }); describe('.readSync', function () { it('should give error if file does not exists', function (done) { var err = apellaJson.readSync(__dirname + '/willneverexist'); expect(err).to.be.an(Error); expect(err.code).to.equal('ENOENT'); done(); }); it('should give error if when reading an invalid json', function (done) { var err = apellaJson.readSync(__dirname + '/pkg-apella-json-malformed/apella.json'); expect(err).to.be.an(Error); expect(err.code).to.equal('EMALFORMED'); expect(err.file).to.equal(path.resolve(__dirname + '/pkg-apella-json-malformed/apella.json')); done(); }); it('should read the file and give an object', function (done) { var json = apellaJson.readSync(__dirname + '/pkg-apella-json/apella.json'); expect(json).to.be.an('object'); expect(json.name).to.equal('some-pkg'); expect(json.version).to.equal('0.0.0'); done(); }); it('should find for a json file if a directory is given', function (done) { var json = apellaJson.readSync(__dirname + '/pkg-component-json'); expect(json).to.be.an('object'); expect(json.name).to.equal('some-pkg'); expect(json.version).to.equal('0.0.0'); done(); }); it('should validate the returned object unless validate is false', function (done) { var err = apellaJson.readSync(__dirname + '/pkg-apella-json-invalid/apella.json'); expect(err).to.be.an(Error); expect(err.message).to.contain('name'); expect(err.file).to.equal(path.resolve(__dirname + '/pkg-apella-json-invalid/apella.json')); err = apellaJson.readSync(__dirname + '/pkg-apella-json-invalid/apella.json', { validate: false }); expect(err).to.not.be.an(Error); done(); }); it('should normalize the returned object if normalize is true', function (done) { var json = apellaJson.readSync(__dirname + '/pkg-apella-json/apella.json'); expect(json.main).to.equal('foo.js'); json = apellaJson.readSync(__dirname + '/pkg-apella-json/apella.json', { normalize: true }); expect(json.main).to.eql(['foo.js']); done(); }); }); describe('.parse', function () { it('should return the same object, unless clone is true', function () { var json = { name: 'foo' }; expect(apellaJson.parse(json)).to.equal(json); expect(apellaJson.parse(json, { clone: true })).to.not.equal(json); expect(apellaJson.parse(json, { clone: true })).to.eql(json); }); it('should validate the passed object, unless validate is false', function () { expect(function () { apellaJson.parse({}); }).to.throwException(/name/); expect(function () { apellaJson.parse({}, { validate: false }); }).to.not.throwException(); }); it('should not normalize the passed object unless normalize is true', function () { var json = { name: 'foo', main: 'foo.js' }; apellaJson.parse(json); expect(json.main).to.eql('foo.js'); apellaJson.parse(json, { normalize: true }); expect(json.main).to.eql(['foo.js']); }); }); describe('.getIssues', function () { it('should print no errors even for weird package names', function () { var json = { name: '@gruNt/my dependency' }; expect(apellaJson.getIssues(json).errors).to.be.empty(); }); it('should validate the name length', function () { var json = { name: 'a_123456789_123456789_123456789_123456789_123456789_z' }; expect(apellaJson.getIssues(json).warnings).to.contain( 'The "name" is too long, the limit is 50 characters' ); }); it('should validate the name is lowercase', function () { var json = { name: 'gruNt' }; expect(apellaJson.getIssues(json).warnings).to.contain( 'The "name" is recommended to be lowercase, can contain digits, dots, dashes' ); }); it('should validate the name starts with lowercase', function () { var json = { name: '-runt' }; expect(apellaJson.getIssues(json).warnings).to.contain( 'The "name" cannot start with dot or dash' ); }); it('should validate the name starts with lowercase', function () { var json = { name: '.grunt' }; expect(apellaJson.getIssues(json).warnings).to.contain( 'The "name" cannot start with dot or dash' ); }); it('should validate the name ends with lowercase', function () { var json = { name: 'grun-' }; expect(apellaJson.getIssues(json).warnings).to.contain( 'The "name" cannot end with dot or dash' ); }); it('should validate the name ends with lowercase', function () { var json = { name: 'grun.' }; expect(apellaJson.getIssues(json).warnings).to.contain( 'The "name" cannot end with dot or dash' ); }); it('should validate the name is valid', function () { var json = { name: 'gru.n-t' }; expect(apellaJson.getIssues(json).warnings).to.eql([]); }); it('should validate the description length', function () { var json = { name: 'foo', description: _s.repeat('æ', 141) }; expect(apellaJson.getIssues(json).warnings).to.contain( 'The "description" is too long, the limit is 140 characters' ); }); it('should validate the description is valid', function () { var json = { name: 'foo', description: _s.repeat('æ', 140) }; expect(apellaJson.getIssues(json).warnings).to.eql([]); }); it('should validate that main does not contain globs', function () { var json = { name: 'foo', main: ['js/*.js'] }; expect(apellaJson.getIssues(json).warnings).to.contain( 'The "main" field cannot contain globs (example: "*.js")' ); }); it('should validate that main does not contain minified files', function () { var json = { name: 'foo', main: ['foo.min.css'] }; expect(apellaJson.getIssues(json).warnings).to.contain( 'The "main" field cannot contain minified files' ); }); it('should validate that main does not contain fonts', function () { var json = { name: 'foo', main: ['foo.woff'] }; expect(apellaJson.getIssues(json).warnings).to.contain( 'The "main" field cannot contain font, image, audio, or video files' ); }); it('should validate that main does not contain images', function () { var json = { name: 'foo', main: ['foo.png'] }; expect(apellaJson.getIssues(json).warnings).to.contain( 'The "main" field cannot contain font, image, audio, or video files' ); }); it('should validate that main does not contain multiple files of the same filetype', function () { var json = { name: 'foo', main: ['foo.js', 'bar.js'] }; expect(apellaJson.getIssues(json).warnings).to.contain( 'The "main" field has to contain only 1 file per filetype; found multiple .js files: ["foo.js","bar.js"]' ); }); }); describe('.validate', function () { it('should validate the name property', function () { expect(function () { apellaJson.validate({}); }).to.throwException(/name/); }); it('should validate the type of main', function () { var json = { name: 'foo', main: {} }; expect(function () { apellaJson.validate(json); }).to.throwException(); }); it('should validate the type of items of an Array main', function () { var json = { name: 'foo', main: [{}] }; expect(function () { apellaJson.validate(json); }).to.throwException(); }); }); describe('.normalize', function () { it('should normalize the main property', function () { var json = { name: 'foo', main: 'foo.js' }; apellaJson.normalize(json); expect(json.main).to.eql(['foo.js']); }); }); describe('packages from apella registry', function () { var packageList, packageListUrl = 'http://apella.herokuapp.com/packages'; this.timeout(60000); it('can be downloaded from online source ' + packageListUrl, function(done) { request({ url: packageListUrl, json: true }, function(error, response, body) { if(error) { throw error; } expect(body).to.be.an('array'); expect(body).to.not.be.empty(); packageList = body; done(); }); }); it('should validate each listed package', function (done) { expect(packageList).to.be.an('array'); var invalidPackageCount = 0; packageList.forEach(function(package) { try { apellaJson.validate(package); } catch(e) { invalidPackageCount++; console.error('validation of "' + package.name + '" failed: ' + e.message); } }); if(invalidPackageCount) { throw new Error(invalidPackageCount + '/' + packageList.length + ' package names do not validate'); } done(); }); });
apellajs/apella
packages/bower-json/test/test.js
JavaScript
mit
16,224
'use strict'; angular.module('myApp.contact', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/contact', { templateUrl: 'contact/contact.html', controller: 'ContactCtrl', animation: 'page-fadein' }); }]) .controller('ContactCtrl', ['$scope', 'myService', function($scope, myService) { $scope.pageClass = 'page-contact'; myService.set(); $scope.hoveringHuh = false; $scope.copied = false; $scope.hover = function() { return $scope.hoveringHuh = ! $scope.hoveringHuh; }; $scope.click = function() { return $scope.copied = true; }; // copy e-mail address var clientText = new ZeroClipboard( $("#text-to-copy"), { moviePath: "ZeroClipboard.swf", debug: false } ); clientText.on( "ready", function( readyEvent ) { clientText.on( "aftercopy", function( event ) { // $('#copied').fadeIn(2000).delay(3000).fadeOut(3000); // $scope.copied = true; } ); } ); }]);
ctong1124/portfolio2016
app/contact/contact.js
JavaScript
mit
968
var indexSectionsWithContent = { 0: "acdefhilmnoprtw", 1: "w", 2: "aehilmoprw", 3: "w", 4: "acdefhlnrt", 5: "w", 6: "w", 7: "w" }; var indexSectionNames = { 0: "all", 1: "classes", 2: "files", 3: "functions", 4: "variables", 5: "typedefs", 6: "enums", 7: "defines" }; var indexSectionLabels = { 0: "All", 1: "Data Structures", 2: "Files", 3: "Functions", 4: "Variables", 5: "Typedefs", 6: "Enumerations", 7: "Macros" };
niho/libwave
doc/private/html/search/searchdata.js
JavaScript
mit
471
/** * Homes Configuration */ .config(function ($routeProvider) { $routeProvider.when('/homes', { controller: 'homesRoute', templateUrl: 'views/homes.html', reloadOnSearch: false }); });
TheDarkCode/AngularAzureSearch
src/AngularAzureSearch/liamcaReference/js/app/homesCtrl/config/homesConfig.js
JavaScript
mit
222
import {Glyphicon, Table} from 'react-bootstrap'; let defaultActions = ['Download', 'Bookmark']; const actions = { link : defaultActions, image: defaultActions, text : [...defaultActions, 'Edit'], web : [...defaultActions, 'Preview', 'Edit'] }; export default class ActionView extends React.Component { makeBookmark(activeId) { this.getActiveModel(activeId).toggleBookmark(); } makeAction(action, activeId) { switch (action){ case 'Bookmark': this.makeBookmark(activeId); break; } } getActiveModel(activeId) { return this.props.collection.get(activeId); } fileActions(activeId){ let fileType = this.getActiveModel(activeId).toJSON().format || 'link'; return _.map(actions[fileType], (action, index)=> { return ( <tr key={index}> <td onClick={this.makeAction.bind(this, action, activeId)}> { action === 'Download' ? <Glyphicon glyph="download-alt"/> : action === 'Bookmark' ? <Glyphicon glyph="bookmark"/> : action === 'Preview' ? <Glyphicon glyph="eye-open"/> : action === 'Edit' ? <Glyphicon glyph="pencil"/> : null } <strong> {action} </strong> </td> </tr> ) }); } showActiveFile(activeId){ return ( <tr> <td>File selected: <strong>{this.getActiveModel(activeId).toJSON().name}</strong> </td> </tr> ); } render() { let selectFile = ( <tr> <td>Select file at the left side by clicking on it</td> </tr> ); let activeId = this.props.activeId; return ( <Table responsive hover bordered className="action-view"> <thead> <tr> <th><strong>Action</strong></th> </tr> </thead> <tbody> { !activeId ? selectFile : this.fileActions.bind(this, activeId)()} { !activeId ? null : this.showActiveFile.bind(this, activeId)()} </tbody> </Table> ); } }
andrey-ponamarev/file-manager
app/components/ActionView.js
JavaScript
mit
1,844
(function () { 'use strict'; describe('Inventories Controller Tests', function () { // Initialize global variables var InventoriesController, $scope, $httpBackend, $state, Authentication, InventoriesService, mockInventory; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function () { jasmine.addMatchers({ toEqualData: function (util, customEqualityTesters) { return { compare: function (actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _InventoriesService_) { // Set a new global scope $scope = $rootScope.$new(); // Point global variables to injected services $httpBackend = _$httpBackend_; $state = _$state_; Authentication = _Authentication_; InventoriesService = _InventoriesService_; // create mock Inventory mockInventory = new InventoriesService({ _id: '525a8422f6d0f87f0e407a33', name: 'Inventory Name' }); // Mock logged in user Authentication.user = { roles: ['user'] }; // Initialize the Inventories controller. InventoriesController = $controller('InventoriesController as vm', { $scope: $scope, inventoryResolve: {} }); //Spy on state go spyOn($state, 'go'); })); describe('vm.save() as create', function () { var sampleInventoryPostData; beforeEach(function () { // Create a sample Inventory object sampleInventoryPostData = new InventoriesService({ name: 'Inventory Name' }); $scope.vm.inventory = sampleInventoryPostData; }); it('should send a POST request with the form input values and then locate to new object URL', inject(function (InventoriesService) { // Set POST response $httpBackend.expectPOST('api/inventories', sampleInventoryPostData).respond(mockInventory); // Run controller functionality $scope.vm.save(true); $httpBackend.flush(); // Test URL redirection after the Inventory was created expect($state.go).toHaveBeenCalledWith('inventories.view', { inventoryId: mockInventory._id }); })); it('should set $scope.vm.error if error', function () { var errorMessage = 'this is an error message'; $httpBackend.expectPOST('api/inventories', sampleInventoryPostData).respond(400, { message: errorMessage }); $scope.vm.save(true); $httpBackend.flush(); expect($scope.vm.error).toBe(errorMessage); }); }); describe('vm.save() as update', function () { beforeEach(function () { // Mock Inventory in $scope $scope.vm.inventory = mockInventory; }); it('should update a valid Inventory', inject(function (InventoriesService) { // Set PUT response $httpBackend.expectPUT(/api\/inventories\/([0-9a-fA-F]{24})$/).respond(); // Run controller functionality $scope.vm.save(true); $httpBackend.flush(); // Test URL location to new object expect($state.go).toHaveBeenCalledWith('inventories.view', { inventoryId: mockInventory._id }); })); it('should set $scope.vm.error if error', inject(function (InventoriesService) { var errorMessage = 'error'; $httpBackend.expectPUT(/api\/inventories\/([0-9a-fA-F]{24})$/).respond(400, { message: errorMessage }); $scope.vm.save(true); $httpBackend.flush(); expect($scope.vm.error).toBe(errorMessage); })); }); describe('vm.remove()', function () { beforeEach(function () { //Setup Inventories $scope.vm.inventory = mockInventory; }); it('should delete the Inventory and redirect to Inventories', function () { //Return true on confirm message spyOn(window, 'confirm').and.returnValue(true); $httpBackend.expectDELETE(/api\/inventories\/([0-9a-fA-F]{24})$/).respond(204); $scope.vm.remove(); $httpBackend.flush(); expect($state.go).toHaveBeenCalledWith('inventories.list'); }); it('should should not delete the Inventory and not redirect', function () { //Return false on confirm message spyOn(window, 'confirm').and.returnValue(false); $scope.vm.remove(); expect($state.go).not.toHaveBeenCalled(); }); }); }); })();
ebonertz/mean-blog
modules/inventories/tests/client/inventories.client.controller.tests.js
JavaScript
mit
5,483
version https://git-lfs.github.com/spec/v1 oid sha256:ff952c4ac029ba9d378d24581d9a56937e7dc731986397dc47c3c42c56fd0729 size 132398
yogeshsaroya/new-cdnjs
ajax/libs/soundmanager2/2.97a.20120318/script/soundmanager2.js
JavaScript
mit
131
'use strict'; angular.module('eklabs.angularStarterPack.offer') .directive('removeOffer',function($log, $location, Offers){ return { templateUrl : 'eklabs.angularStarterPack/modules/offers/views/MyRemoveOfferView.html', scope : { offer : '=?', callback : '=?', listOffer : '=' },link : function(scope, attr, $http) { // Initialisation du constructeur var offersCreation = new Offers(); // Supprimer une offre de stage scope.deleteOffer = function(idOfferToDelete) { offersCreation.deleteOffer(idOfferToDelete).then(idOfferToDelete); alert("L\'annonce a bien été supprimer. Vous allez être redirigé sur la page d'accueil. "); }; } } })
julienbnr/InternMe
src/modules/offers/directives/my-offer/MyRemoveOfferDirective.js
JavaScript
mit
883
'use strict'; var angular = require('angular'); module.exports = angular.module('services.notifications', []) .factory('notifications', ['$rootScope', function ($rootScope) { var notifications = { 'STICKY' : [], 'ROUTE_CURRENT' : [], 'ROUTE_NEXT' : [] }; var notificationsService = {}; var addNotification = function (notificationsArray, notificationObj) { if (!angular.isObject(notificationObj)) { throw new Error("Only object can be added to the notification service"); } notificationsArray.push(notificationObj); return notificationObj; }; $rootScope.$on('$routeChangeSuccess', function () { notifications.ROUTE_CURRENT.length = 0; notifications.ROUTE_CURRENT = angular.copy(notifications.ROUTE_NEXT); notifications.ROUTE_NEXT.length = 0; }); notificationsService.getCurrent = function(){ return [].concat(notifications.STICKY, notifications.ROUTE_CURRENT); }; notificationsService.pushSticky = function(notification) { return addNotification(notifications.STICKY, notification); }; notificationsService.pushForCurrentRoute = function(notification) { return addNotification(notifications.ROUTE_CURRENT, notification); }; notificationsService.pushForNextRoute = function(notification) { return addNotification(notifications.ROUTE_NEXT, notification); }; notificationsService.remove = function(notification){ angular.forEach(notifications, function (notificationsByType) { var idx = notificationsByType.indexOf(notification); if (idx>-1){ notificationsByType.splice(idx,1); } }); }; notificationsService.removeAll = function(){ angular.forEach(notifications, function (notificationsByType) { notificationsByType.length = 0; }); }; return notificationsService; }]);
evangalen/webpack-angular-app
client/src/common/services/notifications.js
JavaScript
mit
1,830
import KolibriModule from 'kolibri_module'; import { getCurrentSession } from 'kolibri.coreVue.vuex.actions'; import router from 'kolibri.coreVue.router'; import Vue from 'kolibri.lib.vue'; import store from 'kolibri.coreVue.vuex.store'; import heartbeat from 'kolibri.heartbeat'; /* * A class for single page apps that control routing and vuex state. * Override the routes, mutations, initialState, and RootVue getters. */ export default class KolibriApp extends KolibriModule { /* * @return {Array[Object]} Array of objects that define vue-router route configurations. * These will get passed to our internal router, so the handlers should * be functions that invoke vuex actions. */ get routes() { return []; } /* * @return {Object} An object of vuex mutations, with keys as the mutation name, and * values that are methods that perform the store mutation. */ get mutations() { return {}; } /* * @return {Object} The initial state of the vuex store for this app, this will be merged with * the core app initial state to instantiate the store. */ get initialState() { return {}; } /* * @return {Object} A component definition for the root component of this single page app. */ get RootVue() { return {}; } /* * @return {Store} A convenience getter to return the vuex store. */ get store() { return store; } /* * @return {Array[Function]} Array of vuex actions that will do initial state setting before the * routes are handled. Use this to do initial state setup that needs to * be dynamically determined, and done before every route in the app. * Each function should return a promise that resolves when the state * has been set. These will be invoked after the current session has * been set in the vuex store, in order to allow these actions to * reference getters that return data set by the getCurrentSession * action. As this has always been bootstrapped into the base template * this should not cause any real slow down in page loading. */ get stateSetters() { return []; } ready() { this.store.registerModule({ state: this.initialState, mutations: this.mutations, }); getCurrentSession(store).then(() => { Promise.all([ // Invoke each of the state setters before initializing the app. ...this.stateSetters.map(setter => setter(this.store)), ]).then(() => { heartbeat.start(); this.rootvue = new Vue( Object.assign( { el: 'rootvue', store: store, router: router.init(this.routes), }, this.RootVue ) ); }); }); } }
christianmemije/kolibri
kolibri/core/assets/src/kolibri_app.js
JavaScript
mit
3,037
module.exports = require('./lib/tapioca');
salomaosnff/tapioca-load
index.js
JavaScript
mit
42
module.exports = function(server){ return { login: require('./login')(server), logout: require('./logout')(server) } }
julien-sarazin/learning-nodejs
actions/auth/index.js
JavaScript
mit
135
/* * Copyright (c) 2015 Phoenix Scholars Co. (http://dpq.co.ir) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ 'use strict'; angular.module('pluf') /** * @memberof pluf * @ngdoc service * @name $monitor * @description مدیریت تمام مانیتورها را ایجاد می‌کند * * مانیتورها در واحد زمان باید به روز شوند. این سرویس نه تنها مانیتورها را ایجاد * بلکه آنها را در واحد زمان به روز می‌کند. * * در صورتی که استفاده از یک مانیتور تمام شود،‌این سرویس مانیتورهای ایجاد شده را * حذف می‌کند تا میزان انتقال اطلاعات را کم کند. * * @see PMonitor * */ .service('$collection', function($pluf, PCollection, PObjectFactory) { var _cache = new PObjectFactory(function(data) { return new PCollection(data); }); /** * Creates new collection * * @memberof $collection * @return Promise<PCollection> * createdreceipt * */ this.newCollection = $pluf.createNew({ method : 'POST', url : '/api/collection/new' }, _cache); /** * Gets collection detail. Input could be id or name of collection. * * @memberof $collection * @return Promise<PCollection> * createdreceipt * */ this.collection = $pluf.createGet({ method : 'GET', url : '/api/collection/{id}', }, _cache); /** * Lists all collections * * @memberof $collection * @return Promise<PaginatorPage<PCollection>> * createdreceipt * */ this.collections = $pluf.createFind({ method : 'GET', url : '/api/collection/find', }, _cache); });
phoenix-scholars/angular-pluf
src/collection/services/collection.js
JavaScript
mit
2,721
'use strict' // ensure endpoint starts w/ http:// or https:// module.exports = function normalizeEndpoint (endpoint, version) { if (endpoint == null) throw new Error('endpoint is required') if (typeof endpoint !== 'string') throw new Error('endpoint must be a string') if (endpoint === '') throw new Error('endpoint must not be empty string') if (version == null || version === 1) { version = 'v1' } if (version !== 'v1') { throw new Error('Only v1 of the API is currently supported') } // if doesn't match http:// or https://, use https:// endpoint = endpoint.trim() + '/api/' + version + '/' if (!endpoint.match(/^https?:\/\//)) { endpoint = 'https://' + endpoint } return endpoint }
nodesource/nsolid-statsd
node_modules/nsolid-apiclient/lib/normalize-endpoint.js
JavaScript
mit
726
import React, { Component } from 'react' import cx from 'classnames' import Collapse from 'react-collapse' import { MdAutorenew as IconChecking, MdNote as IconSimple, MdViewDay as IconSeparated, } from 'react-icons/md' import fetchGallery from 'helpers/fetchGallery' import Tabbable from 'components/Tabbable' class TemplateChooser extends Component { state = { // can be basic | gallery source: 'basic', isFetching: false, isError: false, gallery: [], } handleChangeSource = async source => { this.setState({ source }) if (source === 'gallery') { if (this.state.isFetching) { return } this.setState({ isFetching: true }) try { const gallery = await fetchGallery() this.setState({ isFetching: false, isError: false, gallery, }) this.handleSelectGalleryTemplate(0) } catch (err) { this.setState({ isFetching: false, isError: true, }) } } else { this.props.onSelect('singleBasic') } } handleSelectGalleryTemplate = i => { this.props.onSelect(this.state.gallery[i]) } render() { const { template, onSelect } = this.props const { source, isFetching, isError, gallery } = this.state return ( <div className="flow-v-20"> <div className="d-f TemplateChooserTabs"> <Tabbable onClick={() => this.handleChangeSource('basic')} className={cx('TemplateChooserTabs--tab f-1 cu-d', { isActive: source === 'basic', })} > {'Basic'} </Tabbable> <Tabbable onClick={() => this.handleChangeSource('gallery')} className={cx('TemplateChooserTabs--tab f-1 cu-d', { isActive: source === 'gallery', })} > {'Gallery'} </Tabbable> </div> <Collapse isOpened springConfig={{ stiffness: 300, damping: 30 }}> {source === 'basic' ? ( <div className="d-f"> <TabItem onClick={() => onSelect('singleBasic')} isSelected={template === 'singleBasic'} label="Single file, basic layout" > <IconSimple size={80} /> </TabItem> <TabItem onClick={() => onSelect('headerFooter')} isSelected={template === 'headerFooter'} label="Header & Footer" > <IconSeparated size={80} /> </TabItem> </div> ) : source === 'gallery' ? ( <div> {isFetching ? ( <div className="z" style={{ height: 250 }}> <IconChecking className="rotating mb-20" size={30} /> {'Fetching templates...'} </div> ) : isError ? ( <div>{'Error'}</div> ) : ( <div className="r" style={{ height: 450 }}> <div className="sticky o-y-a Gallery"> {gallery.map((tpl, i) => ( <Tabbable key={tpl.name} onClick={() => this.handleSelectGalleryTemplate(i)} className={cx('Gallery-Item-wrapper', { isSelected: template.name === tpl.name, })} > <div className="Gallery-Item" style={{ backgroundImage: `url(${tpl.thumbnail})`, }} > <div className="Gallery-item-label small">{tpl.name}</div> </div> </Tabbable> ))} </div> </div> )} </div> ) : null} </Collapse> </div> ) } } function TabItem({ onClick, isSelected, thumbnail, children, label }) { return ( <Tabbable onClick={onClick} className={cx('Gallery-Item-wrapper', { isSelected, })} > <div className="Gallery-Item" style={{ backgroundImage: thumbnail ? `url(${thumbnail})` : undefined, }} > {children} <div className="Gallery-item-label small">{label}</div> </div> </Tabbable> ) } export default TemplateChooser
mjmlio/mjml-app
src/components/NewProjectModal/TemplateChooser.js
JavaScript
mit
4,575
$(document).ready(function () { $('.eacc-change-photo-btn').bind('click', function () { $('#eacc-change-photo-file').click(); return false; }); $('.icon-menu').on('click', function () { var is_active = $('#main-menu').hasClass('active'); if (is_active) { $('#main-menu').slideUp(); $('#main-menu').removeClass('active'); } else { $('#main-menu').slideDown(); $('#main-menu').addClass('active'); } }); $('#name-field').blur(function () { var value = $('#name-field').val(); if (value) { $('.hello').html('miło Cię poznać!'); } else { $('.hello').empty(); } }); $('.login').on('click', function () { var is_open = $('.auth-form-wrapper').hasClass('open'); if (!is_open) { $('.auth-login-wrapper').addClass('open'); fullscreenlogin('.auth-login-wrapper'); } }); $('.close-login').on('click', function () { $('.auth-login-wrapper').removeClass('open'); }) }); function fullscreenlogin(element) { var windowheight = $(window).height(); $(element).css('height', windowheight); $(element).css('height', "touch"); var loginwrapperheight = $('.login-form-wrapper').outerHeight(); if (windowheight > loginwrapperheight) { $('.login-form-wrapper').css('margin-top', (windowheight - loginwrapperheight) / 2); } }
wzywno/tescopl_ng
js/test.js
JavaScript
mit
1,483
import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; export default class AttributeRoute extends Route { @service cognito; async model({ name }) { if (name) { const attrs = await this.cognito.user.getUserAttributesHash(); const value = attrs[name]; return { name, value }; } return { isNew: true }; } }
paulcwatts/ember-cognito
tests/dummy/app/routes/attribute.js
JavaScript
mit
382
import React from 'react'; import clsx from 'clsx'; import { useSelector } from 'react-redux'; import { makeStyles } from '@material-ui/core/styles'; import NoSsr from '@material-ui/core/NoSsr'; import Divider from '@material-ui/core/Divider'; import Grid from '@material-ui/core/Grid'; import Container from '@material-ui/core/Container'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; const users = [ { logo: 'nasa.svg', logoWidth: 49, logoHeight: 40, caption: 'NASA', }, { logo: 'walmart-labs.svg', logoWidth: 205, logoHeight: 39, caption: 'Walmart Labs', class: 'walmart', }, { logo: 'capgemini.svg', logoWidth: 180, logoHeight: 40, caption: 'Capgemini', }, { logo: 'uniqlo.svg', logoWidth: 40, logoHeight: 40, caption: 'Uniqlo', }, { logo: 'bethesda.svg', logoWidth: 196, logoHeight: 29, caption: 'Bethesda', }, { logo: 'jpmorgan.svg', logoWidth: 198, logoHeight: 40, caption: 'J.P. Morgan', }, { logo: 'shutterstock.svg', caption: 'Shutterstock', logoWidth: 205, logoHeight: 29, }, { logo: 'netflix.svg', logoWidth: 111, logoHeight: 29, caption: 'Netflix', }, { logo: 'amazon.svg', logoWidth: 119, logoHeight: 36, caption: 'Amazon', class: 'amazon', }, { logo: 'unity.svg', logoWidth: 138, logoHeight: 50, caption: 'Unity', class: 'unity', }, { logo: 'spotify.svg', logoWidth: 180, logoHeight: 54, caption: 'Spotify', class: 'spotify', }, ]; const useStyles = makeStyles( (theme) => ({ root: { padding: theme.spacing(2), minHeight: 160, paddingTop: theme.spacing(5), }, container: { marginBottom: theme.spacing(4), }, users: { padding: theme.spacing(10, 6, 0), }, grid: { marginTop: theme.spacing(5), marginBottom: theme.spacing(5), }, img: { margin: theme.spacing(1.5, 3), }, amazon: { margin: theme.spacing(2.4, 3, 1.5), }, unity: { margin: theme.spacing(0.5, 3, 1.5), }, spotify: { margin: theme.spacing(0, 3, 1.5), }, walmart: { margin: '13px 4px 12px', }, button: { margin: theme.spacing(2, 0, 0), }, }), { name: 'Users' }, ); export default function Users() { const classes = useStyles(); const t = useSelector((state) => state.options.t); return ( <div className={classes.root}> <NoSsr defer> <Container maxWidth="md" className={classes.container} disableGutters> <Divider /> <div className={classes.users}> <Typography variant="h4" component="h2" align="center" gutterBottom> {t('whosUsing')} </Typography> <Typography variant="body1" align="center" gutterBottom> {t('joinThese')} </Typography> <Grid container justify="center" className={classes.grid}> {users.map((user) => ( <img key={user.caption} src={`/static/images/users/${user.logo}`} alt={user.caption} className={clsx(classes.img, classes[user.class])} loading="lazy" width={user.logoWidth} height={user.logoHeight} /> ))} </Grid> <Typography variant="body1" align="center" gutterBottom> {t('usingMui')} </Typography> <Grid container justify="center"> <Button variant="outlined" href="https://github.com/mui-org/material-ui/issues/22426" rel="noopener nofollow" target="_blank" className={classes.button} > {t('letUsKnow')} </Button> </Grid> </div> </Container> </NoSsr> </div> ); }
lgollut/material-ui
docs/src/pages/landing/Users.js
JavaScript
mit
4,076
/* Dorm Room Control Server July 28, 2014 notify.js Sends notifications through Pushover's notification API Copyright (c) 2014 by Tristan Honscheid <MIT License> */ var req = require("request"); var app_token = "abwQbZzfMK7v2GvJcnFy8h1bNYHrTj"; /* Send a POST request to the Pushover * msgData object: * { * "title" : string, message title (opt), * "priority" : int, -2 = no alert, -1 = quiet, 1 = high priority, 2 = emergency (opt), * "timestamp" : int, unix timestamp (opt), * "sound" : string, a supported sound name to play (opt), * "url" : string, a URL to bundle with the message (opt), * "url_title" : string, the URL's title (opt) * } */ exports.SendNotification = function(userKey, message, msgData, callback) { if(typeof userKey !== "string" || typeof message !== "string") { return false; } var postData = { "token" : app_token, "user" : userKey, "message" : message, "title" : msgData.title, "url" : msgData.url, "url_title" : msgData.url_title, "priority" : msgData.priority, "timestamp" : msgData.timestamp, "sound" : msgData.sound }; var post_options = { uri : "https://api.pushover.net/1/messages.json", method : "POST", form : postData, headers : { "User-Agent" : "nodejs" } }; req(post_options, function(error, response, body) { if(!error && response.statusCode==200) { var data = JSON.parse(body); if(data.status == 1) { callback({"error" : false, "error_msg" : "", "code" : data.request}); } else { callback({"error" : true, "error_msg" : ("Pushover error, status " + response.statusCode + ", " + body)}); } } else { callback({"error" : true, "error_msg" : ("HTTP error, status " + response.statusCode + ", " + body)}); } }); };
tristantech/Dorm-Room-Automation
NodeServer/lib/notify.js
JavaScript
mit
1,918
var fs = require('fs'); var path = require('path'); var config = require('rc')('easy-workflow', { projectName: process.cwd().split(path.sep).pop() }); module.exports = function (gulp) { fs.readdirSync(__dirname).filter(function (file) { return (file.indexOf(".") !== 0) && (file.indexOf('task_') === 0); }).forEach(function (file) { var registerTask = require(path.join(__dirname, file)); registerTask(gulp, config); }); };
grassmu/easy-workflow
templates/tasks/index.js
JavaScript
mit
465
function readCookie(name) { var nameEQ = encodeURIComponent(name) + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length)); } return null; } $.ajaxPrefilter(function (options, originalOptions, jqXHR) { var token = readCookie("_xsrf") // console.log("ajaxPrefilter: _xsrf = ", token) jqXHR.setRequestHeader('X-Csrftoken', token); }); //auth_signup.html //注册发送验证码 $( "#get-authcode-bt" ).bind("click", function() { // event.preventDefault(); // $(this).attr('disabled', 'true') $(this).unbind("click"); var email = $("#email")[0].value var query_string = `mutation MyMutation { auth { signup_identifier(type:"email", data: "${email}") { id } } }` $.ajax({ url: "/api/graphql", method: "POST", // The key needs to match your method's input parameter (case-sensitive). data: JSON.stringify({"query": query_string }), contentType: "application/json; charset=utf-8", dataType: "json", // dataType:'jsonp', success: function(data){ // console.log("data",data.errors) if (data.errors) { var s = data.errors.map(function(v) { $(".error-append").append('<span class="error-message">'+v.message +'</span>'); }) // alert(s) } else { $("#auth_key")[0].value = data.data.auth.signup_identifier.id // console.log('22222=>',$("#auth_key")[0].value) } }, failure: function(errMsg) { alert(errMsg); } }); }) //忘记密码发送验证码 $( "#forgetpassord-authcode-bt" ).bind("click", function() { // event.preventDefault(); // $(this).attr('disabled', 'true') $(this).unbind("click"); var email = $("#email")[0].value var query_string = `mutation MyMutation { auth { forget_password_identifier(type:"email", data: "${email}") { id } } }` $.ajax({ url: "/api/graphql", method: "POST", // The key needs to match your method's input parameter (case-sensitive). data: JSON.stringify({"query": query_string }), contentType: "application/json; charset=utf-8", dataType: "json", // dataType:'jsonp', success: function(data){ // console.log('1111=>',data) if (data.errors) { var s = data.errors.map(function(v) { $(".error-append").append('<span class="error-message">'+v.message +'</span>'); }) // alert(s) } else { $("#auth_key")[0].value = data.data.auth.forget_password_identifier.id } // console.log('22222=>',$("#auth_key")[0].value) }, failure: function(errMsg) { alert(errMsg); } }); }) $('input').on("keypress", function(e) { /* ENTER PRESSED*/ if (e.keyCode == 13) { /* FOCUS ELEMENT */ var inputs = $(this).parents("form").eq(0).find(":input"); var idx = inputs.index(this); if (idx == inputs.length - 1) { inputs[0].select() } else { inputs[idx + 1].focus(); // handles submit buttons inputs[idx + 1].select(); } return false; } }); window.blog_menu_init = function blog_menu_init() { // var $selector = $(".submenu a[href='" + window.location.pathname + "']") // console.log($selector) if (window.location.pathname.startsWith("/console/blog")) { var p_url = window.location.pathname.split("/").slice(0,4).join('/') var selector = ".submenu a[href='" + p_url + "']" $(selector).parent().addClass("active") } else { var selector = ".submenu a[href='" + window.location.pathname + "']" $(selector).parent().addClass("active") } // $selector.parent().addClass("active") var s=window.location.pathname if (!s.startsWith("/console/account")) { $(selector).closest(".panel-default").find(".panel-title a").first().click() } // var $s = $selector.closest(".panel-default").find(".panel-title a").first() // $s.click() // $s.removeClass("collapsed") // console.log($(selector).closest(".panel-default").find(".panel-title a").text()) // console.log($(selector).closest(".panel-default").find("a.collapsed").first()) } //创建目录 import { success_catalog_change, create_catalog, success_blog_catalog_change } from './catalog' window.create_catalog = create_catalog window.success_catalog_change = success_catalog_change window.success_blog_catalog_change = success_blog_catalog_change // Tag操作 import { success_tag_change, create_tag, blog_add_tag, set_hidden_input, success_blog_tag_change, delete_tag } from './tag' window.create_tag = create_tag window.success_tag_change = success_tag_change window.success_blog_tag_change = success_blog_tag_change window.blog_add_tag = blog_add_tag window.set_hidden_input = set_hidden_input window.delete_tag = delete_tag
nuanri/hiblog
src/js-dev/src/blog-home.js
JavaScript
mit
5,466
/** * @since 15-08-13 11:38 * @author vivaxy */ import Url from './index.js'; let assert = chai.assert; describe('new Url()', function () { it('should return link', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', urlLink = new Url(link); assert.equal(urlLink, link); }); it('should return full link, when link is not complete', function () { let link = '/vivaxy/test/url?name=vivaxy&year=2015#some', urlLink = new Url(link).toString(); assert.equal(urlLink, location.origin + link); }); it('should return full link, when link is not complete', function () { let link = '?name=vivaxy&year=2015#some', urlLink = new Url(link).toString(); assert.equal(urlLink, location.origin + location.pathname + link); }); it('should return full link, when link is not complete', function () { let link = '#some', urlLink = new Url(link).toString(); assert.equal(urlLink, location.origin + location.pathname + link); }); }); describe('.get(\'href\')', function () { it('should return href', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', href = new Url(link).get('href'); assert.equal(href, link); }); it('should return full href, when link is not complete', function () { let link = '/vivaxy/test/url?name=vivaxy&year=2015#some', urlLink = new Url(link).toString(); assert.equal(urlLink, location.origin + link); }); it('should return full href, when link is not complete', function () { let link = '?name=vivaxy&year=2015#some', urlLink = new Url(link).toString(); assert.equal(urlLink, location.origin + location.pathname + link); }); it('should return full href, when link is not complete', function () { let link = '#some', urlLink = new Url(link).toString(); assert.equal(urlLink, location.origin + location.pathname + link); }); }); describe('.get(\'protocol\')', function () { it('should return protocol', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', protocol = new Url(link).get('protocol'); assert.equal(protocol, 'https:'); }); it('should return protocol', function () { let link = 'http://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', protocol = new Url(link).get('protocol'); assert.equal(protocol, 'http:'); }); it('should return current protocol, when protocol is not supplied', function () { let link = '//www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', protocol = new Url(link).get('protocol'); assert.equal(protocol, location.protocol); }); it('should return current protocol, when protocol is not supplied', function () { let link = '/vivaxy/test/url?name=vivaxy&year=2015#some', protocol = new Url(link).get('protocol'); assert.equal(protocol, location.protocol); }); }); describe('.get(\'host\')', function () { it('should return host', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', host = new Url(link).get('host'); assert.equal(host, 'www.test.com:8080'); }); it('should return host', function () { let link = 'https://www.test.com/vivaxy/test/url?name=vivaxy&year=2015#some', host = new Url(link).get('host'); assert.equal(host, 'www.test.com'); }); it('should return current host, when host is not supplied', function () { let link = '/vivaxy/test/url?name=vivaxy&year=2015#some', host = new Url(link).get('host'); assert.equal(host, location.host); }); }); describe('.get(\'hostname\')', function () { it('should return hostname', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', hostname = new Url(link).get('hostname'); assert.equal(hostname, 'www.test.com'); }); it('should return hostname', function () { let link = 'https://www.test.com/vivaxy/test/url?name=vivaxy&year=2015#some', hostname = new Url(link).get('hostname'); assert.equal(hostname, 'www.test.com'); }); it('should return current hostname, when hostname is not supplied', function () { let link = '/vivaxy/test/url?name=vivaxy&year=2015#some', hostname = new Url(link).get('hostname'); assert.equal(hostname, location.hostname); }); }); describe('.get(\'port\')', function () { it('should return port', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', port = new Url(link).get('port'); assert.equal(port, '8080'); }); it('should return port', function () { let link = 'https://www.test.com/vivaxy/test/url?name=vivaxy&year=2015#some', port = new Url(link).get('port'); assert.equal(port, ''); }); it('should return current port, when port is not supplied', function () { let link = '/vivaxy/test/url?name=vivaxy&year=2015#some', port = new Url(link).get('port'); assert.equal(port, location.port); }); }); describe('.get(\'path\')', function () { it('should return path', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', path = new Url(link).get('path'); assert.equal(path, '/vivaxy/test/url?name=vivaxy&year=2015'); }); it('should return path', function () { let link = 'https://www.test.com/vivaxy/test/url#some', path = new Url(link).get('path'); assert.equal(path, '/vivaxy/test/url'); }); it('should return current path, when path is not supplied', function () { let link = '?name=vivaxy&year=2015#some', path = new Url(link).get('path'); assert.equal(path, location.pathname + '?name=vivaxy&year=2015'); }); it('should return current path, when path is not supplied', function () { let link = '#some', path = new Url(link).get('path'); assert.equal(path, location.pathname + location.search); }); }); describe('.get(\'pathname\')', function () { it('should return pathname', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', pathname = new Url(link).get('pathname'); assert.equal(pathname, '/vivaxy/test/url'); }); it('should return pathname', function () { let link = 'https://www.test.com/vivaxy/test/url#some', pathname = new Url(link).get('pathname'); assert.equal(pathname, '/vivaxy/test/url'); }); it('should return current pathname, when pathname is not supplied', function () { let link = '?name=vivaxy&year=2015#some', pathname = new Url(link).get('pathname'); assert.equal(pathname, location.pathname); }); it('should return current pathname, when pathname is not supplied', function () { let link = '#some', pathname = new Url(link).get('pathname'); assert.equal(pathname, location.pathname); }); }); describe('.get(\'search\')', function () { it('should return search', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', search = new Url(link).get('search'); assert.equal(search, '?name=vivaxy&year=2015'); }); it('should return search', function () { let link = 'https://www.test.com/vivaxy/test/url#some', search = new Url(link).get('search'); assert.equal(search, ''); }); it('should return current search, when search is not supplied', function () { let link = '#some', search = new Url(link).get('search'); assert.equal(search, location.search); }); }); describe('.get(\'query\')', function () { it('should return query', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', query = new Url(link).get('query'); assert.equal(query, 'name=vivaxy&year=2015'); }); it('should return query', function () { let link = 'https://www.test.com/vivaxy/test/url#some', query = new Url(link).get('query'); assert.equal(query, ''); }); it('should return current query, when query is not supplied', function () { let link = '#some', query = new Url(link).get('query'); assert.equal(query, location.search.slice(1)); }); }); describe('.get(\'parameters\')', function () { it('should return parameters', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', parameters = new Url(link).get('parameters'); assert.equal(parameters.name, 'vivaxy'); assert.equal(parameters.year, '2015'); }); it('should return parameters', function () { let link = 'https://www.test.com/vivaxy/test/url#some', parameters = new Url(link).get('parameters'), parameterCount = 0; for (let i in parameters) { parameterCount++; } assert.equal(parameterCount, 0); }); }); describe('.get(\'hash\')', function () { it('should return hash', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', hash = new Url(link).get('hash'); assert.equal(hash, '#some'); }); it('should return hash', function () { let link = 'https://www.test.com/vivaxy/test/url', hash = new Url(link).get('hash'); assert.equal(hash, ''); }); }); describe('.parameter()', function () { it('should return all parameters', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', parameters = new Url(link).parameter(); assert.equal(parameters.name, 'vivaxy'); assert.equal(parameters.year, '2015'); }); it('should return all parameters', function () { let link = 'https://www.test.com/vivaxy/test/url', parameters = new Url(link).parameter(), parameterCount = 0; for (let i in parameters) { parameterCount++; } assert.equal(parameterCount, 0); }); }); describe('.parameter(`key`)', function () { it('should return parameter', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', url = new Url(link), name = url.parameter('name'), year = url.parameter('year'), other = url.parameter('other'); assert.equal(name, 'vivaxy'); assert.equal(year, '2015'); assert.equal(other, undefined); }); }); describe('.parameter(`key`, `value`)', function () { it('should set parameter and return `url`', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', url = new Url(link); url.parameter('year', 2016); url.parameter('other', 'test'); let year = url.parameter('year'), other = url.parameter('other'); assert.equal(year, '2016'); assert.equal(other, 'test'); }); }); describe('.parameter(`object`)', function () { it('should set parameter and return `url`', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', url = new Url(link); url.parameter('year', 2016); url.parameter('other', 'test'); let year = url.parameter('year'), other = url.parameter('other'); assert.equal(year, '2016'); assert.equal(other, 'test'); }); }); describe('.removeParameter(`key`)', function () { it('should remove parameter and return `url`', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', url = new Url(link); url.removeParameter('year'); url.removeParameter('other'); let year = url.parameter('year'), other = url.parameter('other'); assert.equal(year, undefined); assert.equal(other, undefined); }); }); describe('.set(`key`, `value`)', function () { it('should set `url` and return `url`', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', url = new Url(link); try { url.set('year', '2015'); } catch (e) { assert(e.message, 'Url: `year` cannot be set to url'); } }); it('should set `url` and return `url`', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', url = new Url(link); try { url.set('parameters', 'test'); } catch (e) { assert(e.message, 'Url: use `parameter` instead'); } }); it('should set `url` and return `url`', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', url = new Url(link); url.set('query', 'test=1'); assert(url.get('query'), 'test=1'); }); it('should set `url` and return `url`', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', url = new Url(link); url.set('search', '?test=1'); assert(url.get('search'), '?test=1'); try { url.set('search', 'test=1'); } catch (e) { assert(e.message, 'Url: `search` must starts with `?`'); } }); it('should set `url` and return `url`', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', url = new Url(link); url.set('pathname', 'foo-bar'); assert(url.get('pathname'), 'foo-bar'); }); it('should set `url` and return `url`', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', url = new Url(link); url.set('port', 'foo-bar'); assert(url.get('port'), 'foo-bar'); }); it('should set `url` and return `url`', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', url = new Url(link); url.set('port', 3000); assert(url.get('port'), '3000'); }); it('should set `url` and return `url`', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', url = new Url(link); url.set('hostname', 'foo-bar.com'); assert(url.get('hostname'), 'foo-bar.com'); }); it('should set `url` and return `url`', function () { let link = 'https://www.test.com:8080/vivaxy/test/url?name=vivaxy&year=2015#some', url = new Url(link); url.set('hash', '#foo-bar'); assert(url.get('hash'), '#foo-bar'); try { url.set('hash', 'other'); } catch (e) { assert(e.message, 'Url: `hash` must starts with `#`'); } }); });
vivaxy/url
src/test.js
JavaScript
mit
15,592
import React from 'react/addons'; import BaseComponent from './BaseComponent'; import Note from './Note'; /* * @class Note * @extends React.Component */ class Board extends BaseComponent { constructor(props) { super(props); this.state = { notes: [] } this._bind( 'update', 'add', 'remove', 'nextId', 'eachNote' ); } nextId () { this.uniqueId = this.uniqueId || 0; return this.uniqueId++; } componentWillMount () { var self = this; if(this.props.count) { $.getJSON("http://baconipsum.com/api/?type=all-meat&sentences=" + this.props.count + "&start-with-lorem=1&callback=?", function(results){ results[0].split('. ').forEach(function(sentence){ self.add(sentence.substring(0,40)); }); }); } } add (text) { var arr = this.state.notes; arr.push({ id: this.nextId(), note: text }); this.setState({notes: arr}); } update (newText, i) { var arr = this.state.notes; arr[i].note = newText; this.setState({notes:arr}); } remove (i) { var arr = this.state.notes; arr.splice(i, 1); this.setState({notes: arr}); } eachNote (note, i) { return ( <Note key={note.id} index={i} onChange={this.update} onRemove={this.remove} >{note.note}</Note> ); } render () { return (<div className="board"> {this.state.notes.map(this.eachNote)} <button className="btn btn-sm btn-success glyphicon glyphicon-plus" onClick={this.add.bind(null, "New Note")}></button> </div> ); } } // Prop types validation Board.propTypes = { //cart: React.PropTypes.object.isRequired, count: function(props, propName) { if (typeof props[propName] !== "number"){ return new Error('The count property must be a number'); } if (props[propName] > 100) { return new Error("Creating " + props[propName] + " notes is ridiculous"); } } }; export default Board;
carmouche/es6-react-stickynotes
src/app/components/Board.js
JavaScript
mit
2,320
var path = require('path'); var md5 = require('./../lib/md5file'); describe('md5file', function() { it('should return md5 of file', function(done) { var testFile = path.join(__dirname, 'data', 'a'); md5(testFile, function(hash) { hash.should.be.eql('9195d0beb2a889e1be05ed6bb1954837'); done(); }); }); });
seandou/koa-assets-minify
test/md5file.test.js
JavaScript
mit
337
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _htmlPdf = require('html-pdf'); var _htmlPdf2 = _interopRequireDefault(_htmlPdf); var _handlebars = require('handlebars'); var _handlebars2 = _interopRequireDefault(_handlebars); var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _constants = require('../lib/constants'); var _constants2 = _interopRequireDefault(_constants); var _moment = require('moment'); var _moment2 = _interopRequireDefault(_moment); var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function generateReport(reportName, data, res) { var filePath = _path2.default.join(__dirname, '../views/' + reportName + '.html'); var html = _fs2.default.readFileSync(filePath, 'utf8'); var compiledTemplate = _handlebars2.default.compile(html); var withData = compiledTemplate(data); var options = { format: 'Letter' }; _htmlPdf2.default.create(withData, options).toBuffer(function (err, buffer) { if (err) return console.log(err); res.contentType("application/pdf"); return res.end(buffer, 'binary'); //console.log(res); // { filename: '/app/businesscard.pdf' } }); } function buildReportDataFromColumns(columns, skillData) { console.log(_constants2.default.dateTypes); return _lodash2.default.map(skillData, function (skillDatum) { var dataObject = { skillData: skillDatum, columns: [] }; _lodash2.default.each(columns, function (column) { var keys = column.key.split('.'); var value = skillDatum; _lodash2.default.each(keys, function (key) { if (value) value = value[key]; }); if (column.isDate) { value = (0, _moment2.default)(value).format(_constants2.default.dateTypes.altDateFormat); } dataObject.columns.push({ value: value }); }); return dataObject; }); } exports.default = { generateReport: generateReport, buildReportDataFromColumns: buildReportDataFromColumns }; //# sourceMappingURL=reportHelper.js.map
manuelnelson/patient-pal
dist/lib/reportHelper.js
JavaScript
mit
2,378
// development configuration // author: Kirk Austin module.exports = { environment: 'development', server: { name: 'Node Scratch', port: 3001 }, log: { name: 'node-scratch', path: 'node-scratch.log' } }
kirkaustin/node-scratch
config/development.js
JavaScript
mit
225
import Users from 'meteor/vulcan:users'; import { Utils, addGraphQLMutation, addGraphQLResolvers } from 'meteor/vulcan:core'; /** * @summary Verify that the un/subscription can be performed * @param {String} action * @param {Collection} collection * @param {String} itemId * @param {Object} user * @returns {Object} collectionName, fields: object, item, hasSubscribedItem: boolean */ const prepareSubscription = (action, collection, itemId, user) => { // get item's collection name const collectionName = collection._name.slice(0,1).toUpperCase() + collection._name.slice(1); // get item data const item = collection.findOne(itemId); // there no user logged in or no item, abort process if (!user || !item) { return false; } // edge case: Users collection if (collectionName === 'Users') { // someone can't subscribe to themself, abort process if (item._id === user._id) { return false; } } else { // the item's owner is the subscriber, abort process if (item.userId && item.userId === user._id) { return false; } } // assign the right fields depending on the collection const fields = { subscribers: 'subscribers', subscriberCount: 'subscriberCount', }; // return true if the item has the subscriber's id in its fields const hasSubscribedItem = !!_.deep(item, fields.subscribers) && _.deep(item, fields.subscribers) && _.deep(item, fields.subscribers).indexOf(user._id) !== -1; // assign the right update operator and count depending on the action type const updateQuery = action === 'subscribe' ? { findOperator: '$ne', // where 'IT' isn't... updateOperator: '$addToSet', // ...add 'IT' to the array... updateCount: 1, // ...and log the addition +1 } : { findOperator: '$eq', // where 'IT' is... updateOperator: '$pull', // ...remove 'IT' from the array... updateCount: -1, // ...and log the subtraction -1 }; // return the utility object to pursue return { collectionName, fields, item, hasSubscribedItem, ...updateQuery, }; }; /** * @summary Perform the un/subscription after verification: update the collection item & the user * @param {String} action * @param {Collection} collection * @param {String} itemId * @param {Object} user: current user (xxx: legacy, to replace with this.userId) * @returns {Boolean} */ const performSubscriptionAction = (action, collection, itemId, user) => { // subscription preparation to verify if can pursue and give shorthand variables const subscription = prepareSubscription(action, collection, itemId, user); // Abort process if the situation matches one of these cases: // - subscription preparation failed (ex: no user, no item, subscriber is author's item, ... see all cases above) // - the action is subscribe but the user has already subscribed to this item // - the action is unsubscribe but the user hasn't subscribed to this item if (!subscription || (action === 'subscribe' && subscription.hasSubscribedItem) || (action === 'unsubscribe' && !subscription.hasSubscribedItem)) { throw Error(Utils.encodeIntlError({id: 'app.mutation_not_allowed', value: 'Already subscribed'})) } // shorthand for useful variables const { collectionName, fields, item, findOperator, updateOperator, updateCount } = subscription; // Perform the action, eg. operate on the item's collection const result = collection.update({ _id: itemId, // if it's a subscription, find where there are not the user (ie. findOperator = $ne), else it will be $in [fields.subscribers]: { [findOperator]: user._id } }, { // if it's a subscription, add a subscriber (ie. updateOperator = $addToSet), else it will be $pull [updateOperator]: { [fields.subscribers]: user._id }, // if it's a subscription, the count is incremented of 1, else decremented of 1 $inc: { [fields.subscriberCount]: updateCount }, }); // log the operation on the subscriber if it has succeeded if (result > 0) { // id of the item subject of the action let loggedItem = { itemId: item._id, }; // in case of subscription, log also the date if (action === 'subscribe') { loggedItem = { ...loggedItem, subscribedAt: new Date() }; } // update the user's list of subscribed items Users.update({ _id: user._id }, { [updateOperator]: { [`subscribedItems.${collectionName}`]: loggedItem } }); const updatedUser = Users.findOne({_id: user._id}, {fields: {_id:1, subscribedItems: 1}}); return updatedUser; } else { throw Error(Utils.encodeIntlError({id: 'app.something_bad_happened'})) } }; /** * @summary Generate mutations 'collection.subscribe' & 'collection.unsubscribe' automatically * @params {Array[Collections]} collections */ const subscribeMutationsGenerator = (collection) => { // generic mutation function calling the performSubscriptionAction const genericMutationFunction = (collectionName, action) => { // return the method code return function(root, { documentId }, context) { // extract the current user & the relevant collection from the graphql server context const { currentUser, [Utils.capitalize(collectionName)]: collection } = context; // permission check if (!Users.canDo(context.currentUser, `${collectionName}.${action}`)) { throw new Error(Utils.encodeIntlError({id: "app.noPermission"})); } // do the actual subscription action return performSubscriptionAction(action, collection, documentId, currentUser); }; }; const collectionName = collection._name; // add mutations to the schema addGraphQLMutation(`${collectionName}Subscribe(documentId: String): User`), addGraphQLMutation(`${collectionName}Unsubscribe(documentId: String): User`); // create an object of the shape expected by mutations resolvers addGraphQLResolvers({ Mutation: { [`${collectionName}Subscribe`]: genericMutationFunction(collectionName, 'subscribe'), [`${collectionName}Unsubscribe`]: genericMutationFunction(collectionName, 'unsubscribe'), }, }); }; // Finally. Add the mutations to the Meteor namespace 🖖 // vulcan:users is a dependency of this package, it is alreay imported subscribeMutationsGenerator(Users); // note: leverage weak dependencies on packages const Posts = Package['vulcan:posts'] ? Package['vulcan:posts'].default : null; // check if vulcan:posts exists, if yes, add the mutations to Posts if (!!Posts) { subscribeMutationsGenerator(Posts); } // check if vulcan:categories exists, if yes, add the mutations to Categories const Categories = Package['vulcan:categories'] ? Package['vulcan:categories'].default : null; if (!!Categories) { subscribeMutationsGenerator(Categories); } export default subscribeMutationsGenerator;
acidsound/Telescope
packages/vulcan-subscribe/lib/mutations.js
JavaScript
mit
6,946
import test from 'ava'; import { defaultColors } from './defaultColors.js'; const tests = [ { name: 'Dark background color defined in theme', theme: { colors: { background: '#333333' } }, expectedResult: { tickText: { secondary: '#9d9d9d', primary: '#d9d9d9' }, series: '#f1f1f1', value: '#d9d9d9', axis: '#f1f1f1', gridline: '#707070', fallbackBaseColor: '#f1f1f1' } }, { name: 'Custom chart element basecolor,background & blend ratios defined in theme', theme: { colors: { background: '#FCB716', chartContentBaseColor: '#ffffff', bgBlendRatios: { gridline: 0.5, tickText: { primary: 0, secondary: 0 } } } }, expectedResult: { tickText: { secondary: '#ffffff', primary: '#ffffff' }, series: '#ffffff', value: '#fef2e4', axis: '#ffffff', gridline: '#fedeb5', fallbackBaseColor: '#ffffff' } }, { name: "No fail when theme doesn't have any data", theme: {}, expectedResult: { tickText: { secondary: '#a6a6a6', primary: '#7b7b7b' }, series: '#333333', value: '#7b7b7b', axis: '#333333', gridline: '#e8e8e8', fallbackBaseColor: '#333333' } } ]; tests.forEach(({ theme, name, expectedResult }) => { test(name, t => { t.deepEqual(defaultColors(theme), expectedResult); }); });
datawrapper/datawrapper
libs/shared/defaultColors.test.js
JavaScript
mit
1,909
// Common test code var chai = require('chai'); exports.chai = chai; exports.expect = chai.expect; exports.should = chai.should(); exports.request = require('request');
Huskie/ScottishPremiershipData
test/common.js
JavaScript
mit
169
// Cloud normal module.exports = function updateRole(params) { /* █████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗ ██╗ █████╗ ██╗ ██╗ █████╗ ██╗ ██╗ ██╔══██╗██╔════╝╚██╗ ██╔╝████╗ ██║██╔════╝ ██╔╝██╔══██╗██║ ██║██╔══██╗╚██╗ ██╔╝ ███████║███████╗ ╚████╔╝ ██╔██╗ ██║██║ ██╔╝ ███████║██║ █╗ ██║███████║ ╚████╔╝ ██╔══██║╚════██║ ╚██╔╝ ██║╚██╗██║██║ ██╔╝ ██╔══██║██║███╗██║██╔══██║ ╚██╔╝ ██║ ██║███████║ ██║ ██║ ╚████║╚██████╗██╔╝ ██║ ██║╚███╔███╔╝██║ ██║ ██║ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═╝ */ Parse.Cloud.define("testAsync", (req, res) => { (async () => { try { let isQueryAll = req.params.all !== undefined ? true : false; let userName = req.params.userName !== undefined ? req.params.userName : req.user.get("username"); let roleName = req.params.roleName || req.params.role || req.params.r; !isQueryAll && roleName === undefined && res.error("Vui lòng nhập tên role"); var userResult = await new Parse.Query(Parse.User) .equalTo("username", userName) .find({ useMasterKey: true }); var roleResult = isQueryAll ? await new Parse.Query(Parse.Role) .equalTo("users", userResult[0]) .find() : await new Parse.Query(Parse.Role) .equalTo("name", roleName) .equalTo("users", userResult[0]) .find(); res.success( isQueryAll ? res.success(roleResult) : res.success(roleResult[0]) ); } catch (error) { res.error(error.message); } })(); //end async }); //end define test Async //NEW Parse.Cloud.define("isInRole", (req, res) => { console.log(req); req.user === undefined && res.error("Vui lòng đăng nhập "); let roleName = req.params.roleName || req.params.role || req.params.r; roleName === undefined && res.error("Vui lòng nhập tên role"); (async () => { var roleResult = await new Parse.Query(Parse.Role) .equalTo("name", roleName) .equalTo("users", req.user) .find(); roleResult.length !== 0 ? res.success(true) : res.success(false); })(); }); //kết thúc isInRole function. }; //end cloud
cuduy197/parse-express
cloud/dev.js
JavaScript
mit
3,221
import composeWithTracker from 'compose-with-tracker' import { Meteor } from 'meteor/meteor' export default composeWithTracker((props, onData) => { onData(null, { isLoggingIn: Meteor.loggingIn(), user: Meteor.user() || {}, }) })
FractalFlows/Emergence
app/imports/client/Pages/User/container.js
JavaScript
mit
242
var ipc = require('ipc_utils') var id = 1; var binding = { getCurrent: function () { var cb, getInfo; if (arguments.length == 1) { cb = arguments[0] } else { getInfo = arguments[0] cb = arguments[1] } var responseId = ++id ipc.once('chrome-windows-get-current-response-' + responseId, function(evt, win) { cb(win) }) ipc.send('chrome-windows-get-current', responseId, getInfo) }, getAll: function (getInfo, cb) { if (arguments.length == 1) { cb = arguments[0] } else { getInfo = arguments[0] cb = arguments[1] } var responseId = ++id ipc.once('chrome-windows-get-all-response-' + responseId, function(evt, win) { cb(win) }) ipc.send('chrome-windows-get-all', responseId, getInfo) }, create: function (createData, cb) { console.warn('chrome.windows.create is not supported yet') }, update: function (windowId, updateInfo, cb) { var responseId = ++id cb && ipc.once('chrome-windows-update-response-' + responseId, function (evt, win) { cb(win) }) ipc.send('chrome-windows-update', responseId, windowId, updateInfo) }, WINDOW_ID_NONE: -1, WINDOW_ID_CURRENT: -2 }; exports.binding = binding;
posix4e/electron
atom/common/api/resources/windows_bindings.js
JavaScript
mit
1,251
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var _this = this; var _1 = require("../../../"); describe("StatefulAccessor", function () { beforeEach(function () { _1.Utils.guidCounter = 0; var SomeAccessor = (function (_super) { __extends(SomeAccessor, _super); function SomeAccessor() { _super.apply(this, arguments); this.state = new _1.ValueState(); } return SomeAccessor; }(_1.StatefulAccessor)); _this.accessor = new SomeAccessor("genres.raw"); _this.searchkit = new _1.SearchkitManager("/"); _this.searchkit.addAccessor(_this.accessor); }); it("constructor()", function () { expect(_this.accessor.uuid).toBe("genres.raw1"); expect(_this.accessor.key).toEqual("genres.raw"); expect(_this.accessor.urlKey).toEqual("genres_raw"); }); it("setSearchkitManager()", function () { expect(_this.accessor.searchkit).toBe(_this.searchkit); expect(_this.accessor.state).toBe(_this.accessor.resultsState); }); it("translate()", function () { _this.searchkit.translate = function (key) { return { a: 'b' }[key]; }; expect(_this.accessor.translate("a")).toBe("b"); }); it("onStateChange()", function () { expect(function () { return _this.accessor.onStateChange({}); }) .not.toThrow(); }); it("fromQueryObject", function () { var queryObject = { genres_raw: [1, 2], authors_raw: [3, 4] }; _this.accessor.fromQueryObject(queryObject); expect(_this.accessor.state.getValue()) .toEqual([1, 2]); }); it("getQueryObject()", function () { _this.accessor.state = new _1.ValueState([1, 2]); expect(_this.accessor.getQueryObject()) .toEqual({ genres_raw: [1, 2] }); }); it("getResults()", function () { _this.accessor.results = [1, 2]; expect(_this.accessor.getResults()).toEqual([1, 2]); }); it("getAggregations()", function () { expect(_this.accessor.getAggregations(["foo"], 10)) .toEqual(10); _this.accessor.results = { aggregations: { some_count: { value: 11 } } }; expect(_this.accessor.getAggregations(["some_count", "value"], 10)) .toEqual(11); }); it("setResultsState()", function () { delete _this.accessor.resultsState; expect(_this.accessor.state) .not.toBe(_this.accessor.resultsState); _this.accessor.setResultsState(); expect(_this.accessor.state) .toBe(_this.accessor.resultsState); }); it("resetState()", function () { _this.accessor.state = _this.accessor.state.setValue("foo"); expect(_this.accessor.state.getValue()).toBe("foo"); _this.accessor.resetState(); expect(_this.accessor.state.getValue()).toBe(null); }); it("buildSharedQuery", function () { var query = new _1.ImmutableQuery(); expect(_this.accessor.buildSharedQuery(query)) .toBe(query); }); it("buildOwnQuery", function () { var query = new _1.ImmutableQuery(); expect(_this.accessor.buildOwnQuery(query)) .toBe(query); }); }); //# sourceMappingURL=StatefulAccessorSpec.js.map
viktorkh/elastickit_express
node_modules/searchkit/lib/src/__test__/core/accessors/StatefulAccessorSpec.js
JavaScript
mit
3,647
import { curry } from 'lodash/fp'; const checkIfClickedOutSideContainer = (containerEle, element) => { if (!element) { return true; } else if (element === containerEle) { return false; } else { return checkIfClickedOutSideContainer(containerEle, element.parentNode); } } const onDocumentClick = curry((containerEle, { getState, setState }, { target }) => { const { options } = getState(); if (options.length && checkIfClickedOutSideContainer(containerEle, target)) { setState({ options: [], dismissed: true }); } }); export default onDocumentClick;
Attrash-Islam/infinite-autocomplete
src/onDocumentClick/index.js
JavaScript
mit
612
/*! * jquery.analytics.js * API Analytics agent for jQuery * https://github.com/Mashape/analytics-jquery-agent * * Copyright (c) 2015, Mashape (https://www.mashape.com) * Released under the @LICENSE license * https://github.com/Mashape/analytics-jquery-agent/blob/master/LICENSE * * @version @VERSION * @date @DATE */ (function (factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory) } else if (typeof exports === 'object') { module.exports = factory(require('jquery')) } else { factory(jQuery) } })(function (jQuery) { 'use strict' // Default Constants var PLUGIN_NAME = 'Analytics' var PLUGIN_VERSION = '@VERSION' var PLUGIN_AGENT_NAME = 'mashape-analytics-agent-jquery' var ANALYTICS_HOST = 'socket.analytics.mashape.com/' var FALLBACK_IP = '127.0.0.1' var HTTP_VERSION = 'HTTP/1.1' var ENVIRONMENT = '' var PROTOCOL = 'http://' var ALF_VERSION = '1.0.0' var CLIENT_IP = FALLBACK_IP var SERVER_IP = FALLBACK_IP var DEBUG = false var READY = false // This is not a service token. var TOKEN = 'SKIjLjUcjBmshb733ZqAGiNYu6Qvp1Ue0XGjsnYZRXaI8y1U4O' // Globals var $document = jQuery(document) var queue = [] /** * Plugin constructor * * @param {String} token * @param {Object} options */ function Plugin (token, options) { // Constants configuration ANALYTICS_HOST = options.analyticsHost || ANALYTICS_HOST HTTP_VERSION = options.httpVersion || HTTP_VERSION FALLBACK_IP = options.fallbackIp || FALLBACK_IP SERVER_IP = options.serverIp || FALLBACK_IP CLIENT_IP = options.clientIp || FALLBACK_IP PROTOCOL = options.ssl ? 'https://' : PROTOCOL DEBUG = options.debug || DEBUG // Service token this.serviceToken = token this.hostname = options.hostname || (window ? (window.location ? window.location.hostname : false) : false) this.fetchClientIp = typeof options.fetchClientIp === 'undefined' ? true : options.fetchClientIp this.fetchServerIp = typeof options.fetchServerIp === 'undefined' ? true : options.fetchServerIp // Initialize this.init() } // Extend jQuery.extend(Plugin.prototype, { init: function () { var self = this this.getClientIp(function () { self.getServerIp(function () { self.onReady() }) }) $document.ajaxSend(this.onSend.bind(this)) $document.ajaxComplete(this.onComplete.bind(this)) }, getServerIp: function (next) { var url = PROTOCOL + 'statdns.p.mashape.com/' + this.hostname + '/a?mashape-key=' + TOKEN if (this.fetchServerIp && typeof this.hostname === 'string' && this.hostname.length !== 0) { return jQuery.ajax({ url: url, type: 'GET', global: false, success: function (data) { SERVER_IP = data.answer[0].rdata }, complete: function () { next() } }) } else { return next() } }, getClientIp: function (next) { if (this.fetchClientIp) { return jQuery.ajax({ url: PROTOCOL + 'httpbin.org/ip', type: 'GET', global: false, success: function (data) { CLIENT_IP = data.origin }, complete: function () { next() } }) } next() }, onReady: function () { if (!queue) { return } var entry // System is ready to send alfs READY = true // Send queued alfs for (var i = 0, length = queue.length; i < length; i++) { // Obtain entry entry = queue[i] // Update addresses entry.alf.output.har.log.entries[0].serverIpAddress = this.serverIp entry.alf.output.har.log.entries[0].clientIpAddress = this.clientIp // Send entry.alf.send(entry.options) } // Clear queue queue = null }, onSend: function (event, xhr, options) { // Save start time options._startTime = +(new Date()) options._sendTime = options._startTime - event.timeStamp }, onComplete: function (event, xhr, options, data) { // Start new alf object var alf = new Plugin.Alf(this.serviceToken, { name: PLUGIN_AGENT_NAME, version: PLUGIN_VERSION }) // Type options.type = options.type.toUpperCase() // Modifiers var start = options._startTime var end = event.timeStamp var difference = end - start var url = options.url var responseHeaders = Plugin.getResponseHeaderObject(xhr) var headers = options.headers var query = options.type === 'GET' ? options.data : {} var responseBodySize var bodySize var body // Obtain body try { body = options.type === 'GET' ? typeof options.data === 'string' ? options.data : JSON.stringify(options.data) : '' } catch (e) { body = '' } // Obtain bytesize of body bodySize = Plugin.getStringByteSize(body || '') responseBodySize = Plugin.getStringByteSize(xhr.responseText || '') // Handle Querystring if (typeof query === 'string') { query = Plugin.parseQueryString(query) } // Get Querystring from URL if (url.indexOf('?') !== -1) { jQuery.extend(query, Plugin.parseQueryString(url)) } // Insert entry alf.entry({ startedDateTime: new Date(start).toISOString(), serverIpAddress: SERVER_IP, time: difference, request: { method: options.type, url: options.url, httpVersion: HTTP_VERSION, queryString: Plugin.marshalObjectToArray(query), headers: Plugin.marshalObjectToArray(headers), cookies: [], headersSize: -1, bodySize: bodySize }, response: { status: xhr.status, statusText: xhr.statusText, httpVersion: HTTP_VERSION, headers: Plugin.marshalObjectToArray(responseHeaders), cookies: [], headersSize: -1, bodySize: responseBodySize, redirectURL: Plugin.getObjectValue(responseHeaders, 'Location') || '', content: { mimeType: Plugin.getObjectValue(responseHeaders, 'Content-Type') || 'application/octet-stream', size: responseBodySize } }, timings: { blocked: 0, dns: 0, connect: 0, send: options._sendTime, wait: difference, receive: 0, ssl: 0 }, cache: {} }) if (DEBUG) { options._alf = alf } if (!READY) { queue.push({ options: DEBUG ? options : undefined, alf: alf }) } else { alf.send(DEBUG ? options : undefined) } } }) /** * Alf Constructor */ Plugin.Alf = function Alf (serviceToken, creator) { this.output = { version: ALF_VERSION, environment: ENVIRONMENT, serviceToken: serviceToken, clientIpAddress: CLIENT_IP, har: { log: { version: '1.2', creator: creator, entries: [] } } } } /** * Push ALF Har-esque entry to entries list * * @param {Object} item */ Plugin.Alf.prototype.entry = function (item) { this.output.har.log.entries.push(item) } /** * Send ALF Object to ANALYTICS_HOST */ Plugin.Alf.prototype.send = function (options) { var request = { url: PROTOCOL + ANALYTICS_HOST + ALF_VERSION + '/single', global: false, type: 'POST', data: JSON.stringify(this.output), dataType: 'json', contentType: 'application/json' } if (!DEBUG) { jQuery.ajax(request) } if (options) { options._alfRequest = request } } /** * Parses XMLHttpRequest getAllResponseHeaders into a key-value map * * @param {Object} xhrObject */ Plugin.getResponseHeaderObject = function getResponseHeaderObject (xhrObject) { var headers = xhrObject.getAllResponseHeaders() var list = {} var pairs if (!headers) { return list } pairs = headers.split('\u000d\u000a') for (var i = 0, length = pairs.length; i < length; i++) { var pair = pairs[i] // Can't use split() here because it does the wrong thing // if the header value has the string ": " in it. var index = pair.indexOf('\u003a\u0020') if (index > 0) { var key = pair.substring(0, index) var val = pair.substring(index + 2) list[key] = val } } return list } /** * Returns the specified string as a key-value object. * Reoccuring keys become array values. * * @param {String} string * @return {Object} */ Plugin.parseQueryString = function parseQueryString (string) { if (!string) { return {} } string = decodeURIComponent(string) var index = string.indexOf('?') var result = {} var pairs string = (index !== -1 ? string.slice(0, index) : string) string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, '') if (!string) { return result } pairs = string.split('&') for (var i = 0, length = pairs.length; i < length; i++) { var pair = pairs[i].split('=') var key = pair[0] var value = pair[1] if (key.length) { if (result[key]) { if (!result[key].push) { result[key] = [result[key]] } result[key].push(value || '') } } else { result[key] = value || '' } } return result } /** * Returns an Array of Objects containing the properties name, and value. * * @param {Object} object Object to be marshalled to an Array * @return {Array} */ Plugin.marshalObjectToArray = function marshalObjectToArray (object) { var output = [] for (var key in object) { if (object.hasOwnProperty(key)) { output.push({ name: key, value: object[key] }) } } return output } /** * Returns the value associated with the specified key on the specified object. * Should the key not exist, or the object not have data, a falsy value is returned. * * @param {Object} object Specified object to check for existance of key value. * @param {String} key Object key to obtain value for on specified object. * @return {Mixed} */ Plugin.getObjectValue = function getObjectValue (object, key) { if (Object.keys(object).length) { return object[key] } return null } /** * Returns the bytesize of the specified UTF-8 string * * @param {String} string UTF-8 string to run bytesize calculations on * @return {Number} Bytesize of the specified string */ Plugin.getStringByteSize = function getStringByteSize (string) { return encodeURI(string).split(/%(?:u[0-9A-F]{2})?[0-9A-F]{2}|./).length - 1 } // Export plugin jQuery[PLUGIN_NAME] = function (token, options) { // Support object style initialization if (typeof token === 'object') { options = token token = options.serviceToken } // Setup options options = options || {} // Check service token if (typeof token !== 'string' || token.length === 0) { throw { name: 'MissingArgument', message: 'Service token is missing' } } // Initialize plugin return new Plugin(token, options) } return Plugin })
Mashape/analytics-agent-jquery
src/jquery.analytics.js
JavaScript
mit
11,673
var moduleName = "ngApp.controllers"; import timeCtrl from './controller/time-controller.js'; // import yourCtrlHere from './controller/your-controller'; var ctrls = Array.from([ //yourCtrlHere, timeCtrl ]); var app = angular.module(moduleName, []); for(var ctrl of ctrls){ app.controller(ctrl.name, ctrl.def); } export default moduleName;
hiramsoft/es6-ng-twbs-gulp-start
src/main/es6/controllers.js
JavaScript
mit
356
import xRay from 'x-ray' const xray = xRay() import { map, slice, compose } from 'ramda' import { writeFile } from 'fs' import routeNames from '../resources/routes.json' import { getNameFromMatchedObject } from '../js/core' import { convertStopData } from '../../server/controllers/helpers' export const addRouteName = (route) => { return { ...route, routeName: getNameFromMatchedObject(route.route)(routeNames) } } const convertDataList = map(compose(addRouteName, convertStopData)) // import mongoose from 'mongoose' // mongoose.Promise = require('bluebird') // import Stop from '../../server/models/stop' // import Route from '../../server/models/route' const routeID = process.argv[2] const direction = process.argv[3] console.log(`Getting StopID data for route: ${routeID}, heading in the ${direction} direction`) // async function saveEachResult (obj) { // const data = convertData(obj) // const routeObject = await Route.findOne({ 'ID': data.route }, 'name').exec() // Stop.findOneAndUpdate( // {'stop': data.stop}, // search by unique London bus stopsID // {...data, routeName: routeObject.name}, // spread data and then add routeName // {upsert: true} // create new doc if non exist // ).exec() // .then(function saveSuccess () { // console.log(`StopID ${data.stop} saved`) // }) // .catch(function errorHandler (error) { // console.log(error) // }) // } xray(`http://www.ltconline.ca/webwatch/MobileAda.aspx?r=${routeID}&d=${direction}`, 'a', [{ name: '@html', link: '@href' }] )(function handleXrayResult (err, result) { if (err) { throw err } // gets rid of the back link, Mobile Live Arrival Times and WebWatch Home result = slice(0, result.length - 3, result) /* MongoDb version */ // map(saveEachResult, result) /** * Write to File version */ const toFile = `app/resources/Stops/${routeID}-${direction}.json` writeFile( toFile, JSON.stringify(convertDataList(result), null, 4), () => { console.log(`Done with ${toFile}`) } ) // setTimeout(() => { // mongoose.connection.close() // }, 5000) }) // require('dotenv').load() // mongoose.connect(process.env.MONGO_URI) // .then(function connectHandler () { // console.log('Connected to mongoDB via mongoose: Local') // }) // .catch(function errorHandler (error) { // throw error // })
natac13/london-ontario-data
app/utils/scrapStops.js
JavaScript
mit
2,405
/*!CK:3966042476!*//*1437364312,*/ if (self.CavalryLogger) { CavalryLogger.start_js(["XWEA5"]); } __d("getElementText",["isElementNode","isTextNode"],function(a,b,c,d,e,f,g,h){b.__markCompiled&&b.__markCompiled();var i=null;function j(k){if(h(k)){return k.data;}else if(g(k)){if(i===null){var l=document.createElement('div');i=l.textContent!=null?'textContent':'innerText';}return k[i];}else return '';}e.exports=j;},null); __d("requestAnimationFramePolyfill",["emptyFunction","nativeRequestAnimationFrame"],function(a,b,c,d,e,f,g,h){b.__markCompiled&&b.__markCompiled();var i=0,j=h||function(k){var l=Date.now(),m=Math.max(0,16-(l-i));i=l+m;return a.setTimeout(function(){k(Date.now());},m);};j(g);e.exports=j;},null); __d("forEachObject",[],function(a,b,c,d,e,f){b.__markCompiled&&b.__markCompiled();'use strict';var g=Object.prototype.hasOwnProperty;function h(i,j,k){for(var l in i)if(g.call(i,l))j.call(k,i[l],l,i);}e.exports=h;},null); __d("TimerStorage",["forEachObject"],function(a,b,c,d,e,f,g){b.__markCompiled&&b.__markCompiled();var h={TIMEOUT:'TIMEOUT',INTERVAL:'INTERVAL',IMMEDIATE:'IMMEDIATE',ANIMATION_FRAME:'ANIMATION_FRAME'},i={};g(h,function(k,l){return i[l]=[];});var j={push:function(k,l){i[k].push(l);},popAll:function(k,l){i[k].forEach(l);i[k].length=0;}};Object.assign(j,h);e.exports=j;},null); __d("requestAnimationFrameAcrossTransitions",["TimeSlice","requestAnimationFramePolyfill"],function(a,b,c,d,e,f,g,h){b.__markCompiled&&b.__markCompiled();e.exports=function(){for(var i=[],j=0,k=arguments.length;j<k;j++)i.push(arguments[j]);i[0]=g.guard(i[0],'requestAnimationFrame');return h.apply(a,i);};},null); __d("requestAnimationFrame",["TimerStorage","requestAnimationFrameAcrossTransitions"],function(a,b,c,d,e,f,g,h){b.__markCompiled&&b.__markCompiled();e.exports=function(){for(var i=[],j=0,k=arguments.length;j<k;j++)i.push(arguments[j]);var l=h.apply(a,i);g.push(g.ANIMATION_FRAME,l);return l;};},null); __d("csx",[],function(a,b,c,d,e,f){b.__markCompiled&&b.__markCompiled();function g(h){throw new Error('csx: Unexpected class selector transformation.');}e.exports=g;},null); __d("cx",[],function(a,b,c,d,e,f){b.__markCompiled&&b.__markCompiled();function g(h){throw new Error('cx: Unexpected class transformation.');}e.exports=g;},null);
gloriakang/vax-sentiment
articles/article_saved_html/No Link Between MMR Vaccine and Autism, Even in High-Risk Kids _ NIH Director's Blog_files/QOBizWXcUJp.js
JavaScript
mit
2,272
'use strict'; const Rx = require('rxjs/Rx'); const counter = Rx.Observable.interval(100); const subscriptionA = counter.subscribe(i => console.log(`A ${i}`)); const subscriptionB = counter.subscribe(i => console.log(`B ${i}`)); setTimeout(() => { console.log(`Cancelling subscriptionB`); subscriptionB.unsubscribe(); }, 500);
miguelmota/rxjs-examples
examples/unsubscribe.js
JavaScript
mit
333
var NexSportsFrScraper, Xray = require('x-ray'), Datastore = require('nedb'), bunyan = require('bunyan'); var NexSportsFrScraper = (function(){ var X = Xray(); X.delay(500, 1000); var log = bunyan.createLogger({name: 'scraperlogger'}); var BASE_URL = "http://www.sports.fr"; var CLUBS_LIGUE_1_URI = "/football/ligue-1/clubs.html"; var CLUBS_LIGUE_1_URL = BASE_URL+CLUBS_LIGUE_1_URI; var db = {}; db.scrapeLog = new Datastore({ filename: __dirname+'/scrape.db' }); db.league = new Datastore({ filename: __dirname+'/league.db' }); db.scrapeLog.loadDatabase(); db.league.loadDatabase(); var SCRAPE_TYPE = { LEAGUE: "LEAGUE", TEAM: "TEAM", PLAYER: "PLAYER", STATS: "STATS" }; return { db: db, registerScrape: function(type, options){ log.info(options, 'Registring a scrape of type '+ type); options = options || {}; db.scrapeLog.insert({ type: type, time: (new Date()).toJSON(), options: options }, function(err, newDoc){ if(!err){ }else{ log.error(err, 'Error while registring scrape'); } }); }, getAndSaveTeams: function(next, errorCallback){ log.info('Starting Team retrieval'); var that = this; this.getListTeamsLigue1(function(teams){ if (!!teams) log.info('Retrieved '+teams.length+' teams'); if (!teams) log.info('No teams retrieved'); teams.forEach(function(team, index, teams){ db.league.findOne({name: team.name}, function(err, foundTeam){ var i = index; var length = teams.length; if(!err && !!foundTeam){ db.league.update({name: foundTeam.name}, {$set: foundTeam}, {}, function(err, numReplaced){ log.info({team: foundTeam}, 'Team updated'); that.registerScrape(SCRAPE_TYPE.LEAGUE); if (next && (i == (length - 1))) next(); }); }else if(!err){ db.league.insert(team, function(err, newTeam){ log.info({team: newTeam}, 'Team created'); that.registerScrape(SCRAPE_TYPE.LEAGUE); if (next && (i == (length - 1))) next(); }); }else{ log.error(err, 'Error while saving team'); if(errorCallback) errorCallback(err); if (next && (i == (length - 1))) next(); } }); }); }, function(err){ log.error('Eror while retrieving teams'); if(errorCallback) errorCallback(err); }); }, getAndSaveTeamPlayers: function(teamUrl, next, errorCallback){ log.info('Retrieving team players'); var that = this; this.getListPlayersForTeam(teamUrl, function(players){ if (!!players) log.info('Retrieved '+players.length+' players'); if (!players) log.info('No players retrieved'); var iterFunc = function(i, length){ if (i<length){ var url = players[i].url; that.getPlayerProfile(url, function(player){ player.teamUrl = teamUrl; db.league.findOne({url: url}, function(err, playerFound){ if (!err && !!playerFound){ db.league.update({url: playerFound.url}, {$set: player}, {}, function(err, numReplaced){ log.info({playerFound: playerFound}, 'Player updated'); that.registerScrape(SCRAPE_TYPE.PLAYER, {url: playerFound.url}); iterFunc(i+1, length); }); }else if(!err){ db.league.insert(player, function(err, newPlayer){ log.info({newPlayer: newPlayer}, 'Player created'); that.registerScrape(SCRAPE_TYPE.PLAYER, {url: newPlayer.url}); iterFunc(i+1, length); }); }else{ log.error(err, 'Error while saving player'); if (errorCallback) errorCallback(err); iterFunc(i+1, length); } }); }, function(err){ log.error(err, 'Error while retrieving player'); if (errorCallback) errorCallback(err); iterFunc(i+1, length); }); }else{ that.registerScrape(SCRAPE_TYPE.TEAM, {url: teamUrl}); if (next) next(); } }; iterFunc(0, players.length); }, function(err){ log.error(err, 'Error while retrieving player list for team'); if (errorCallback) errorCallback(err); }); }, getAndSavePlayerStats: function(statsUrl, next, errorCallback){ log.info('Starting Stats retrieval'); var that = this; that.getPlayerStats(statsUrl, function(stats){ if (!!stats) log.info('Retrieved '+stats.length+' lines of statistics'); if (!stats) log.info('No statistics retrieved'); var iterFunc = function(i, length, stats){ var stat = stats[i]; if (i<length){ db.league.findOne({url: stat.url, fixture: stat.fixture}, function(err, statsFound){ if (!err && !!statsFound){ log.info({fixture: statsFound}, 'Line of Statistics already created'); iterFunc(i+1, length, stats); }else if(!err){ db.league.insert(stat, function(err, newStat){ log.info({newStat: newStat}, 'Line of statistics created'); that.registerScrape(SCRAPE_TYPE.STATS, {url: newStat.url}); iterFunc(i+1, length, stats); }); }else{ log.error(err, 'Error while saving statistics'); if (errorCallback) errorCallback(err); iterFunc(i+1, length, stats); } }); }else{ if (next) next(); } }; iterFunc(0, stats.length, stats); },function(err){ log.error( err, 'Error while retrieving player stats'); if (errorCallback) errorCallback(err); }); }, // HTML -> JSON getListPlayersForTeam: function(teamUrl, successCallback, errorCallback){ X(teamUrl, "#col2 > div.nwTable > table > tbody > tr td:nth-child(2) a", [{ url: "@href" }])(function(err, results){ if(!err){ if(successCallback) successCallback(results); }else{ if(errorCallback) errorCallback(err); } }); }, getPlayerProfile: function(playerUrl, successCallback, errorCallback){ X(playerUrl, "#main-content > div.nwTable.nwFiche.nwJoueur", { image: "img@src", lastName: "div.nwIdentity ul > li:nth-child(1) > span > b", firstName: "div.nwIdentity ul > li:nth-child(2) > span > b", birthday: "div.nwIdentity ul > li:nth-child(3) > span > b", birthplace: "div.nwIdentity ul > li:nth-child(5) > span > b", nationality: "div.nwIdentity ul > li:nth-child(6) > span > b", height: "div.nwIdentity ul > li:nth-child(7) > span > b", weight: "div.nwIdentity ul > li:nth-child(8) > span > b", position: "div.nwIdentity ul > li:nth-child(9) > span > b", number: "div.nwIdentity ul > li:nth-child(10) > span > b", statsUrl: "div.nwStat > table > tfoot > tr > td > a@href", type: SCRAPE_TYPE.PLAYER })(function(err, player){ if(!err){ player.url = playerUrl; player.nationality = player.nationality.match(/\S+/g)[0]; player.height = parseInt(player.height.match(/\d+/g).join("")); player.weight = parseInt(player.weight.match(/\d+/g).join("")); player.number = parseInt(player.number); player.type= SCRAPE_TYPE.PLAYER; if(successCallback) successCallback(player); }else{ if(errorCallback) errorCallback(err); } }); }, getPlayerStats: function(playerStatsUrl, successCallback, errorCallback){ X(playerStatsUrl, "#main-content > div.nwTable.nwDetailSaison > table:nth-child(3) > tbody tr", [{ date: "td:nth-child(1)", homeTeam: "td:nth-child(2) img@alt", awayTeam: "td:nth-child(4) img@alt", fixture: "td:nth-child(5) a", homeTeamScore: "td:nth-child(6) a", awayTeamScore: "td:nth-child(6) a", status: "td:nth-child(7)", timePlayed: "td:nth-child(8)", review:"td:nth-child(9)", goals: "td:nth-child(10)", yellowCards: "td:nth-child(11)", redCards: "td:nth-child(12)", type: SCRAPE_TYPE.STATS }])(function(err, playerStats){ if(!err){ var cleanTimeFromScore = function(inputStr){ if(inputStr == "-") return 0; inputStr = inputStr.split('(')[0]; inputStr = parseInt(inputStr); return inputStr; }; [].forEach.call(playerStats, function(element, index, array){ var score = element.homeTeamScore; element.statsUrl = playerStatsUrl; element.fixture = parseInt(element.fixture.match(/\d+/g)[0]); element.homeTeamScore = parseInt(score.match(/\S+/g)[0].split("-")[0]); element.awayTeamScore = parseInt(score.match(/\S+/g)[0].split("-")[1]); element.timePlayed = parseInt(element.timePlayed); element.review = parseFloat(element.review); if(isNaN(element.review)) element.review = -1; element.yellowCards = cleanTimeFromScore(element.yellowCards); element.redCards = cleanTimeFromScore(element.redCards); element.goals = cleanTimeFromScore(element.goals); element.type= SCRAPE_TYPE.STATS; }); if(successCallback) successCallback(playerStats); }else{ if(errorCallback) errorCallback(err); } }); }, getListTeamsLigue1: function(successCallback, errorCallback){ X(CLUBS_LIGUE_1_URL, '#main-content > div.nwTable.nwClub > ul li', [{ name: 'div > h2 > a', image: 'div > span > img@src', url: 'div > h2 > a@href' }])(function(err, result){ if(!err){ [].forEach.call(result, function(element, index, array){ element.name = element.name.match(/\S+/g)[0]; element.type= SCRAPE_TYPE.TEAM; }); if(successCallback) successCallback(result); }else{ if(errorCallback) errorCallback(err); } }); } }; })(); module.exports = NexSportsFrScraper;
Boussadia/NexFootballStatistics
NexSportsFrScraper.js
JavaScript
mit
9,732
/** * Manages state for the `browse` page */ import R from 'ramda'; import { SORT, SET_SORT, ADD_COMPOSITIONS } from 'src/actions/browse'; const initialState = { loadedCompositions: [], totalCompositions: 100, selectedSort: 'NEWEST', }; export default (state=initialState, action={}) => { switch(action.type) { case SET_SORT: { if(action.sort !== state.selectedSort) { return {...state, loadedCompositions: [], selectedSort: action.sort, }; } else { return state; } } case ADD_COMPOSITIONS: { return {...state, loadedCompositions: R.union(state.loadedCompositions, action.compositions)} } default: { return state; } } };
Ameobea/noise-asmjs
src/reducers/browseReducer.js
JavaScript
mit
707
/** * Created by santhoshkumar on 17/09/15. * * Find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum. Kadane’s Algorithm: Initialize: max_so_far = 0 max_ending_here = 0 Loop for each element of the array (a) max_ending_here = max_ending_here + a[i] (b) if(max_ending_here < 0) max_ending_here = 0 (c) if(max_so_far < max_ending_here) max_so_far = max_ending_here return max_so_far Explanation: Simple idea of the Kadane's algorithm is to look for all positive contiguous segments of the array (max_ending_here is used for this). And keep track of maximum sum contiguous segment among all positive segments (max_so_far is used for this). Each time we get a positive sum compare it with max_so_far and update max_so_far if it is greater than max_so_far Lets take the example: {-2, -3, 4, -1, -2, 1, 5, -3} max_so_far = max_ending_here = 0 for i=0, a[0] = -2 max_ending_here = max_ending_here + (-2) Set max_ending_here = 0 because max_ending_here < 0 for i=1, a[1] = -3 max_ending_here = max_ending_here + (-3) Set max_ending_here = 0 because max_ending_here < 0 for i=2, a[2] = 4 max_ending_here = max_ending_here + (4) max_ending_here = 4 max_so_far is updated to 4 because max_ending_here greater than max_so_far which was 0 till now for i=3, a[3] = -1 max_ending_here = max_ending_here + (-1) max_ending_here = 3 for i=4, a[4] = -2 max_ending_here = max_ending_here + (-2) max_ending_here = 1 for i=5, a[5] = 1 max_ending_here = max_ending_here + (1) max_ending_here = 2 for i=6, a[6] = 5 max_ending_here = max_ending_here + (5) max_ending_here = 7 max_so_far is updated to 7 because max_ending_here is greater than max_so_far for i=7, a[7] = -3 max_ending_here = max_ending_here + (-3) max_ending_here = 4 max_so_far = 7 * */ function maxSumSubArray(arr){ var maxEndingHere = 0; var maxSoFar = 0; for(var i=1; i< arr.length; i++){ maxEndingHere = maxEndingHere+arr[i]; if(maxEndingHere < 0){ maxEndingHere = 0; }else if(maxEndingHere > maxSoFar){ maxSoFar = maxEndingHere; } } return maxSoFar; } var a = [-2, -3, 4, -1, -2, 1, 5, -3]; console.log("Array: "+ a); console.log("Max sum subarray: "+maxSumSubArray(a));
skcodeworks/dp-algo-in-js
js/largestsumcontiguoussubarray.js
JavaScript
mit
2,369
(function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([root], factory); } else { // Browser globals root.slugify = factory(root); } }(this, function (window) { var from = 'àáäãâèéëêìíïîòóöôõùúüûñç·/_,:;', to = 'aaaaaeeeeiiiiooooouuuunc------'; return function slugify(str){ var i = 0, len = from.length; str = str.toLowerCase(); for( ; i < len; i++ ){ str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i)); } return str.replace(/^\s+|\s+$/g, '') //trim .replace(/[^-a-zA-Z0-9\s]+/ig, '') .replace(/\s/gi, "-"); }; }));
LeandroLovisolo/MyDataStructures
website/bower_components/slugify/slugify.js
JavaScript
mit
795
'use strict'; /** * Module dependencies. */ var CP_cache = require('../lib/CP_cache'); var CP_get = require('../lib/CP_get.min'); var CP_regexp = require('../lib/CP_regexp'); /** * Configuration dependencies. */ var config = require('../config/production/config'); var modules = require('../config/production/modules'); /** * Node dependencies. */ var md5 = require('md5'); var express = require('express'); var router = express.Router(); /** * RSS. */ router.get('/?', function(req, res, next) { var url = config.protocol + config.domain + req.originalUrl; var urlHash = md5(url.toLowerCase()); getRender(function (err, render) { renderData(err, render); }); /** * Get render. * * @param {Callback} callback */ function getRender(callback) { return (config.cache.time) ? getCache( function (err, render) { return (err) ? callback(err) : callback(null, render) }) : getSphinx( function (err, render) { return (err) ? callback(err) : callback(null, render) }); } /** * Get cache. * * @param {Callback} callback */ function getCache(callback) { CP_cache.get(urlHash, function (err, render) { if (err) return callback(err); return (render) ? callback(null, render) : getSphinx( function (err, render) { return (err) ? callback(err) : callback(null, render) }); }); } /** * Get sphinx. * * @param {Callback} callback */ function getSphinx(callback) { if (!modules.rss.status) { return callback('RSS is disabled!'); } var render = {}; render.config = config; render.movies = []; var collection = (req.query.collection) ? CP_regexp.str(req.query.collection) : ''; var tag = (req.query.tag) ? {"content_tags": CP_regexp.str(req.query.tag)} : ''; var ids = (req.query.ids) ? req.query.ids : ''; if (modules.content.status && collection) { CP_get.contents( {"content_url": collection}, function (err, contents) { if (err) { return callback(err); } if (contents && contents.length && contents[0].movies) { var query_id = []; contents[0].movies.forEach(function (item, i, arr) { query_id.push(item + '^' + (parseInt(arr.length) - parseInt(i))) }); var query = {"query_id": query_id.join('|')}; CP_get.movies( query, contents[0].movies.length, '', 1, function (err, movies) { if (err) { return callback(err); } render.movies = sortingIds(query_id, movies); callback(null, render); }); } else { return callback('Collection is empty!'); } }); } else if (config.index.ids.keys && ids) { var items = (((ids.replace(/[0-9,\s]/g, '')) ? config.index.ids.keys : ids.replace(/[^0-9,]/g, '')) .split(',')) .map(function (key) {return parseInt(key.trim());}); if (items && items.length) { var query_id = []; items.forEach(function (item, i, arr) { query_id.push(item + '^' + (arr.length - i)) }); var query = {"query_id": query_id.join('|')}; CP_get.movies( query, items.length, '', 1, function (err, movies) { if (err) { return callback(err); } render.movies = sortingIds(query_id, movies); callback(null, render); }); } else { return callback('No data!'); } } else if (modules.content.status && tag) { var options = {}; options.protocol = config.protocol; options.domain = config.domain; options.content_image = config.default.image; CP_get.contents( tag, 100, 1, true, options, function (err, contents) { if (err) return callback(err); if (contents && contents.length) { render.movies = contents; callback(null, render); } else { return callback('Tag does not exist!'); } }); } else { CP_get.publishIds(true, function (err, ids) { if (err) { return callback(err); } else if (!ids) { return callback('Publication is over!'); } render.movies = ids.movies; callback(null, render); }); } } /** * Render data. * * @param {Object} err * @param {Object} render */ function renderData(err, render) { if (err) { console.log('[routes/rss.js] Error:', url, err); return next({ "status": 404, "message": err }); } if (typeof render === 'object') { res.header('Content-Type', 'application/xml'); res.render('desktop/rss', render, function(err, html) { if (err) console.log('[renderData] Render Error:', err); res.send(html); if (config.cache.time && html) { CP_cache.set( urlHash, html, config.cache.time, function (err) { if (err) { if ((err+'').indexOf('1048576') + 1) { console.log('[routes/rss.js:renderData] Cache Length Error'); } else { console.log('[routes/rss.js:renderData] Cache Set Error:', err); } } } ); } }); } else { res.send(render); } } }); /** * Sort films are turned by id list. * * @param {Object} ids * @param {Object} movies * @return {Array} */ function sortingIds(ids, movies) { console.log(ids, movies); var result = []; for (var id = 0; id < ids.length; id++) { for (var i = 0; i < movies.length; i++) { if (parseInt(movies[i].kp_id) === parseInt(('' + ids[id]).trim())) { result.push(movies[i]); } } } console.log(result); return result; } module.exports = router;
CinemaPress/CinemaPress-ACMS
routes/rss.js
JavaScript
mit
8,046
({ "clearFilterDialogTitle": "Εκκαθάριση φίλτρου", "filterDefDialogTitle": "Φίλτρο", "ruleTitleTemplate": "Κανόνας ${0}", "conditionEqual": "ίσο", "conditionNotEqual": "όχι ίσο", "conditionLess": "είναι μικρότερο από", "conditionLessEqual": "μικρότερο ή ίσο", "conditionLarger": "είναι μεγαλύτερο από", "conditionLargerEqual": "μεγαλύτερο ή ίσο", "conditionContains": "περιέχει", "conditionIs": "είναι", "conditionStartsWith": "αρχίζει από", "conditionEndWith": "τελειώνει σε", "conditionNotContain": "δεν περιέχει", "conditionIsNot": "δεν είναι", "conditionNotStartWith": "δεν αρχίζει από", "conditionNotEndWith": "δεν τελειώνει σε", "conditionBefore": "πριν", "conditionAfter": "μετά", "conditionRange": "εύρος", "conditionIsEmpty": "είναι κενό", "all": "όλα", "any": "οποιοδήποτε", "relationAll": "όλοι οι κανόνες", "waiRelAll": "Αντιστοιχία με όλους τους παρακάτω κανόνες:", "relationAny": "οποιοσδήποτε κανόνας", "waiRelAny": "Αντιστοιχία με οποιονδήποτε από τους παρακάτω κανόνες:", "relationMsgFront": "Αντιστοιχία", "relationMsgTail": "", "and": "και", "or": "ή", "addRuleButton": "Προσθήκη κανόνα", "waiAddRuleButton": "Προσθήκη νέου κανόνα", "removeRuleButton": "Αφαίρεση κανόνα", "waiRemoveRuleButtonTemplate": "Αφαίρεση κανόνα ${0}", "cancelButton": "Ακύρωση", "waiCancelButton": "Ακύρωση αυτού του πλαισίου διαλόγου", "clearButton": "Εκκαθάριση", "waiClearButton": "Εκκαθάριση του φίλτρου", "filterButton": "Φίλτρο", "waiFilterButton": "Υποβολή του φίλτρου", "columnSelectLabel": "Στήλη", "waiColumnSelectTemplate": "Στήλη για τον κανόνα ${0}", "conditionSelectLabel": "Συνθήκη", "waiConditionSelectTemplate": "Συνθήκη για τον κανόνα ${0}", "valueBoxLabel": "Τιμή", "waiValueBoxTemplate": "Καταχωρήστε τιμή φίλτρου για τον κανόνα ${0}", "rangeTo": "έως", "rangeTemplate": "από ${0} έως ${1}", "statusTipHeaderColumn": "Στήλη", "statusTipHeaderCondition": "Κανόνες", "statusTipTitle": "Γραμμή φίλτρου", "statusTipMsg": "Πατήστε στη γραμμή φίλτρου για φιλτράρισμα με βάση τις τιμές στο ${0}.", "anycolumn": "οποιαδήποτε στήλη", "statusTipTitleNoFilter": "Γραμμή φίλτρου", "statusTipTitleHasFilter": "Φίλτρο", "statusTipRelPre": "Αντιστοιχία", "statusTipRelPost": "κανόνες.", "defaultItemsName": "στοιχεία", "filterBarMsgHasFilterTemplate": "Εμφανίζονται ${0} από ${1} ${2}.", "filterBarMsgNoFilterTemplate": "Δεν έχει εφαρμοστεί φίλτρο", "filterBarDefButton": "Ορισμός φίλτρου", "waiFilterBarDefButton": "Φιλτράρισμα του πίνακα", "a11yFilterBarDefButton": "Φιλτράρισμα...", "filterBarClearButton": "Εκκαθάριση φίλτρου", "waiFilterBarClearButton": "Εκκαθάριση του φίλτρου", "closeFilterBarBtn": "Κλείσιμο γραμμής φίλτρου", "clearFilterMsg": "Με την επιλογή αυτή θα αφαιρεθεί το φίλτρο και θα εμφανιστούν όλες οι διαθέσιμες εγγραφές.", "anyColumnOption": "Οποιαδήποτε στήλη", "trueLabel": "Αληθές", "falseLabel": "Ψευδές" })
henry-gobiernoabierto/geomoose
htdocs/libs/dojo/dojox/grid/enhanced/nls/el/Filter.js
JavaScript
mit
3,906
(function() { 'use strict'; angular .module('ngRouteApp') .controller('AboutController', AboutController); /** @ngInject */ function AboutController() { } })();
Toilal/showcase-ng-routers
ng-route-app/src/app/about/about.controller.js
JavaScript
mit
182
"use strict"; var $ = require("jquery"); var _ = require("underscore"); /** * Adds relative attribute functions: minimum, maximum, equals. * * @param c The comparator function * @param a The attribute name * @param e1 The first element (the element to act upon) * @param s The selector to evaluate as an element to compare to */ function apply(c, a, e1, s) { var e2 = _.first($(s)); if (!e2) return; if (c(parseInt(e1.css(a)), parseInt(e2.css(a)))) { e1.css(a, e2.css(a)); } } var Relative = _.reduce({ "minimum": function(a, b) { return a < b; }, "maximum": function(a, b) { return a > b; }, "equals": function(a, b) { return a == b; } }, function(h, fn, a) { return h[a] = _.partial(apply, fn); }, {}); // alias equals Relative.equal = Relative.equals; console.log("Loaded Relative module"); module.exports = Relative;
sjohnr/behaviors.js
src/main/js/lib/Relative.js
JavaScript
mit
852
var searchData= [ ['cubbyflow_5fdebug',['CUBBYFLOW_DEBUG',['../_core_2_utils_2_logging_8hpp.html#a9444ed1f5c44b8cfafc48c0b4e1adccb',1,'Logging.hpp']]], ['cubbyflow_5ferror',['CUBBYFLOW_ERROR',['../_core_2_utils_2_logging_8hpp.html#aedc411509ba3159ad14bcfd303f64049',1,'Logging.hpp']]], ['cubbyflow_5fgrid_5ftype_5fname',['CUBBYFLOW_GRID_TYPE_NAME',['../_core_2_grid_2_grid_8hpp.html#aa6ca43386489c33de12d7427ee2d1eb1',1,'Grid.hpp']]], ['cubbyflow_5finfo',['CUBBYFLOW_INFO',['../_core_2_utils_2_logging_8hpp.html#abd4a0afd312cbc8af2194a2eaa2de96e',1,'Logging.hpp']]], ['cubbyflow_5fneighbor_5fsearcher_5ftype_5fname',['CUBBYFLOW_NEIGHBOR_SEARCHER_TYPE_NAME',['../_point_neighbor_searcher_8hpp.html#a6495b3a6d51217a8c2767dfffd2bbfde',1,'PointNeighborSearcher.hpp']]], ['cubbyflow_5fpython_5fmake_5findex_5ffunction2',['CUBBYFLOW_PYTHON_MAKE_INDEX_FUNCTION2',['../pybind11_utils_8hpp.html#ac35fef4ce6410bc2205a826978baa47e',1,'pybind11Utils.hpp']]], ['cubbyflow_5fpython_5fmake_5findex_5ffunction3',['CUBBYFLOW_PYTHON_MAKE_INDEX_FUNCTION3',['../pybind11_utils_8hpp.html#afbcbde1460d0a03c81ef7ad533bd18aa',1,'pybind11Utils.hpp']]], ['cubbyflow_5fwarn',['CUBBYFLOW_WARN',['../_core_2_utils_2_logging_8hpp.html#a6eb2609b48450d5813d130993d2f0902',1,'Logging.hpp']]] ];
utilForever/CubbyFlow
search/defines_0.js
JavaScript
mit
1,278
module.exports = function(grunt) { "use strict"; require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks); grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), bannercss: "/*! =============================================================\n" + " * Maricopa Association of Governments\n" + " * CSS files for MAG Development Review Map Viewer\n" + " * @concat.min.css | @version | <%= pkg.version %>\n" + " * Production | <%= pkg.date %>\n" + " * http://ims.azmag.gov/\n" + " * MAG Development Review Viewer\n" + " * ===============================================================\n" + " * @Copyright <%= pkg.copyright %> MAG\n" + " * @License MIT\n" + " * ===============================================================\n" + " */\n", bannerjs: '/*!\n' + '*@main.min.js\n' + '*@JavaScript document for Development Review Map Viewer @ MAG\n' + '*@For Production\n' + '*@<%= pkg.name %> - v<%= pkg.version %> | <%= grunt.template.today("mm-dd-yyyy") %>\n' + '*@author <%= pkg.author %>\n' + '*/\n', htmlhint: { build: { options: { "tag-pair": true, // Force tags to have a closing pair "tagname-lowercase": true, // Force tags to be lowercase "attr-lowercase": true, // Force attribute names to be lowercase e.g. <div id="header"> is invalid "attr-value-double-quotes": true, // Force attributes to have double quotes rather than single "doctype-first": true, // Force the DOCTYPE declaration to come first in the document "spec-char-escape": true, // Force special characters to be escaped "id-unique": true, // Prevent using the same ID multiple times in a document // "head-script-disabled": false, // Prevent script tags being loaded in the head for performance reasons "style-disabled": true // Prevent style tags. CSS should be loaded through }, src: ["src/index.html", "src/view/*.html"] } }, // CSSLint. Tests CSS code quality // https://github.com/gruntjs/grunt-contrib-csslint csslint: { // define the files to lint files: ["src/css/main.css"], strict: { options: { "import": 0, "empty-rules": 0, "display-property-grouping": 0, "shorthand": 0, "font-sizes": 0, "zero-units": 0, "important": 0, "duplicate-properties": 0, } } }, jshint: { files: ["src/js/main.js", "src/js/config.js", "src/js/plugins.js"], options: { // strict: true, sub: true, quotmark: "double", trailing: true, curly: true, eqeqeq: true, unused: true, scripturl: true, // This option defines globals exposed by the Dojo Toolkit. dojo: true, // This option defines globals exposed by the jQuery JavaScript library. jquery: true, // Set force to true to report JSHint errors but not fail the task. force: true, reporter: require("jshint-stylish-ex") } }, uglify: { options: { // add banner to top of output file banner: '<%= bannerjs %>\n' }, build: { files: { "dist/js/main.min.js": ["src/js/main.js"], "dist/js/vendor/bootstrapmap.min.js": ["src/js/vendor/bootstrapmap.js"] } } }, cssmin: { add_banner: { options: { // add banner to top of output file banner: '/* <%= pkg.name %> - v<%= pkg.version %> | <%= grunt.template.today("mm-dd-yyyy") %> */' }, files: { "dist/css/main.min.css": ["src/css/main.css"], "dist/css/normalize.min.css": ["src/css/normalize.css"], "dist/css/bootstrapmap.min.css": ["src/css/bootstrapmap.css"] } } }, concat: { options: { stripBanners: true, banner: '<%= bannercss %>\n' }, dist: { src: ["dist/css/normalize.min.css", "dist/css/bootstrapmap.min.css", "dist/css/main.min.css"], dest: 'dist/css/concat.min.css' } }, clean: { build: { src: ["dist/"] } }, copy: { build: { cwd: "src/", src: ["**"], dest: "dist/", expand: true } }, watch: { html: { files: ["index.html"], tasks: ["htmlhint"] }, css: { files: ["css/main.css"], tasks: ["csslint"] }, js: { files: ["js/mainmap.js", "Gruntfile.js", "js/config.js"], tasks: ["jshint"] } }, versioncheck: { options: { skip: ["semver", "npm", "lodash"], hideUpToDate: false } }, replace: { update_Meta: { src: ["src/index.html", "src/js/config.js", "src/humans.txt", "README.md"], // source files array // src: ["README.md"], // source files array overwrite: true, // overwrite matched source files replacements: [{ // html pages from: /(<meta name="revision-date" content=")[0-9]{2}\/[0-9]{2}\/[0-9]{4}(">)/g, to: '<meta name="revision-date" content="' + '<%= pkg.date %>' + '">', }, { // html pages from: /(<meta name="version" content=")([0-9]+)(?:\.([0-9]+))(?:\.([0-9]+))(">)/g, to: '<meta name="version" content="' + '<%= pkg.version %>' + '">', }, { // config.js from: /(v)([0-9]+)(?:\.([0-9]+))(?:\.([0-9]+))( \| )[0-9]{2}\/[0-9]{2}\/[0-9]{4}/g, to: 'v' + '<%= pkg.version %>' + ' | ' + '<%= pkg.date %>', }, { // humans.txt from: /(Version\: v)([0-9]+)(?:\.([0-9]+))(?:\.([0-9]+))/g, to: "Version: v" + '<%= pkg.version %>', }, { // humans.txt from: /(Last updated\: )[0-9]{2}\/[0-9]{2}\/[0-9]{4}/g, to: "Last updated: " + '<%= pkg.date %>', }, { // README.md from: /(#### version )([0-9]+)(?:\.([0-9]+))(?:\.([0-9]+))/g, to: "#### version " + '<%= pkg.version %>', }, { // README.md from: /(`Updated: )[0-9]{2}\/[0-9]{2}\/[0-9]{4}/g, to: "`Updated: " + '<%= pkg.date %>', }] } } }); // this would be run by typing "grunt test" on the command line grunt.registerTask("work", ["jshint"]); grunt.registerTask("workHTML", ["htmlhint"]); grunt.registerTask("buildcss", ["cssmin", "concat"]); grunt.registerTask("buildjs", ["uglify"]); grunt.registerTask("build-test", ["clean", "copy"]); grunt.registerTask("build", ["clean", "replace", "copy", "uglify", "cssmin", "concat"]); // the default task can be run just by typing "grunt" on the command line grunt.registerTask("default", []); }; // ref // http://coding.smashingmagazine.com/2013/10/29/get-up-running-grunt/ // http://csslint.net/about.html // http://www.jshint.com/docs/options/ // test test test test test test test
AZMAG/map-Developments
Gruntfile.js
JavaScript
mit
8,849
/** * Created by ndyumin on 29.05.2015. * @exports UIModule */ define(function(require) { require('./styles/field.less'); var Wreqr = require('backbone.wreqr'); var globalBus = Wreqr.radio.channel('global'); var UIController = require('./UIController'); return function(app) { var controller = new UIController(app); globalBus.vent.on('newgame', controller.init, controller); } });
nikitadyumin/tetris
src/app/game_ui/UIModule.js
JavaScript
mit
427
require('../../stylus/components/_dialogs.styl') // Mixins import Dependent from '../../mixins/dependent' import Detachable from '../../mixins/detachable' import Overlayable from '../../mixins/overlayable' import Stackable from '../../mixins/stackable' import Toggleable from '../../mixins/toggleable' // Directives import ClickOutside from '../../directives/click-outside' // Helpers import { getZIndex } from '../../util/helpers' export default { name: 'v-dialog', mixins: [Dependent, Detachable, Overlayable, Stackable, Toggleable], directives: { ClickOutside }, data () { return { isDependent: false, stackClass: 'dialog__content__active', stackMinZIndex: 200 } }, props: { disabled: Boolean, persistent: Boolean, fullscreen: Boolean, fullWidth: Boolean, maxWidth: { type: [String, Number], default: 'none' }, origin: { type: String, default: 'center center' }, width: { type: [String, Number], default: 'auto' }, scrollable: Boolean, transition: { type: [String, Boolean], default: 'dialog-transition' } }, computed: { classes () { return { [(`dialog ${this.contentClass}`).trim()]: true, 'dialog--active': this.isActive, 'dialog--persistent': this.persistent, 'dialog--fullscreen': this.fullscreen, 'dialog--stacked-actions': this.stackedActions && !this.fullscreen, 'dialog--scrollable': this.scrollable } }, contentClasses () { return { 'dialog__content': true, 'dialog__content__active': this.isActive } } }, watch: { isActive (val) { if (val) { this.show() } else { this.removeOverlay() this.unbind() } } }, mounted () { this.isBooted = this.isActive this.isActive && this.show() }, beforeDestroy () { if (typeof window !== 'undefined') this.unbind() }, methods: { closeConditional (e) { // close dialog if !persistent, clicked outside and we're the topmost dialog. // Since this should only be called in a capture event (bottom up), we shouldn't need to stop propagation return !this.persistent && getZIndex(this.$refs.content) >= this.getMaxZIndex() && !this.$refs.content.contains(e.target) }, show () { !this.fullscreen && !this.hideOverlay && this.genOverlay() this.fullscreen && this.hideScroll() this.$refs.content.focus() this.$listeners.keydown && this.bind() }, bind () { window.addEventListener('keydown', this.onKeydown) }, unbind () { window.removeEventListener('keydown', this.onKeydown) }, onKeydown (e) { this.$emit('keydown', e) } }, render (h) { const children = [] const data = { 'class': this.classes, ref: 'dialog', directives: [ { name: 'click-outside', value: { callback: this.closeConditional, include: this.getOpenDependentElements } }, { name: 'show', value: this.isActive } ], on: { click: e => e.stopPropagation() } } if (!this.fullscreen) { data.style = { maxWidth: this.maxWidth === 'none' ? undefined : (isNaN(this.maxWidth) ? this.maxWidth : `${this.maxWidth}px`), width: this.width === 'auto' ? undefined : (isNaN(this.width) ? this.width : `${this.width}px`) } } if (this.$slots.activator) { children.push(h('div', { 'class': 'dialog__activator', on: { click: e => { if (!this.disabled) this.isActive = !this.isActive } } }, [this.$slots.activator])) } const dialog = h('transition', { props: { name: this.transition || '', // If false, show nothing origin: this.origin } }, [h('div', data, this.showLazyContent(this.$slots.default) )]) children.push(h('div', { 'class': this.contentClasses, domProps: { tabIndex: -1 }, style: { zIndex: this.activeZIndex }, ref: 'content' }, [dialog])) return h('div', { 'class': 'dialog__container', style: { display: !this.$slots.activator && 'none' || this.fullWidth ? 'block' : 'inline-block' } }, children) } }
azaars/vuetify
src/components/VDialog/VDialog.js
JavaScript
mit
4,409
module.exports = function() { let heroes = ["leto", "duncan", "goku", "batman", "asterix", "naruto", "totoro"]; for(let index = Math.max(0, heroes.length - 5), __ks_0 = Math.min(heroes.length, 3), hero; index < __ks_0; ++index) { hero = heroes[index]; console.log("The hero at index %d is %s", index, hero); } };
kaoscript/kaoscript
test/fixtures/compile/for/for.block.in.from.asc.wbn.wep.ns.js
JavaScript
mit
319
// Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). // For example: // Given binary tree {3,9,20,#,#,15,7}, // 3 // / \ // 9 20 // / \ // 15 7 // return its level order traversal as: // [ // [3], // [9,20], // [15,7] // ] /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ var levelOrder = function(root) { var lib = {}, result = []; function traverse(cNode, cDepth){ if(cNode === null){ return; } else { if(lib[cDepth] === undefined){ lib[cDepth] = [cNode.val]; } else { lib[cDepth].push(cNode.val); } traverse(cNode.left, cDepth+1); traverse(cNode.right, cDepth+1); } } traverse(root, 1); for(var i = 1; i <= Object.keys(lib).length; i++){ result.push(lib[i]); } return result; };
Vrturo/Algo-Gem
Algorithms/JS/trees/binaryLvlOrderTraverse.js
JavaScript
mit
1,066
// import { CallLogs } from '../index'; import expect from 'expect'; // import { shallow } from 'enzyme'; // import React from 'react'; describe('<CallLogs />', () => { it('Expect to have unit tests specified', () => { expect(true).toEqual(false); }); });
luis-teixeira/react-twilio-webphone
app/containers/CallLogs/tests/index.test.js
JavaScript
mit
266
__history = [{"date":"Fri, 12 Jul 2013 08:56:51 GMT","sloc":253,"lloc":175,"functions":56,"deliveredBugs":2.4294367467276246,"maintainability":77.09782649151177,"lintErrors":22,"difficulty":83.76923076923076}]
Schibsted-Tech-Polska/stp.project_analysis
reports/files/node_modules_findit_node_modules_seq_node_modules_hashish_index_js/report.history.js
JavaScript
mit
209
'use strict'; import axios from 'axios'; export default { search: (criteria) => { return axios.post('/gameSystemRankings/search', criteria) .then(function(response) { return response.data; }); }, createOrUpdate: (data) => { return axios.post('/gameSystemRankings', data) .then(function(response) { return response.data; }); }, remove: (id) => { return axios.delete('/gameSystemRankings/' + id) .then(function(response) { return response.data; }); } };
zdizzle6717/battle-comm
src/services/GameSystemRankingService.js
JavaScript
mit
496
var StatusSelector = React.createClass({ handleChange: function(event) { this.props.updateStatusFilter(event.target.value) }, handleNodeGrep: function(event) { this.props.updateNodeFilter(event.target.value) }, handleKeyGrep: function(event) { this.props.updateKeyFilter(event.target.value) }, render: function() { return ( <div> <nav className="navbar navbar-default"> <div className="container"> <form className="form-inline"> <button type="button" value="" className="btn btn-default navbar-btn" onClick={this.handleChange}>Any</button> <button type="button" value="success" className="btn btn-default navbar-btn alert-success" onClick={this.handleChange}>Success</button> <button type="button" value="warning" className="btn btn-default navbar-btn alert-warning" onClick={this.handleChange}>Warning</button> <button type="button" value="danger" className="btn btn-default navbar-btn alert-danger" onClick={this.handleChange}>Danger</button> <button type="button" value="info" className="btn btn-default navbar-btn alert-info" onClick={this.handleChange}>Info</button> <input type="text" id="nodeFilter" className="form-control" placeholder="node | service" onKeyUp={this.handleNodeGrep}/> <input type="text" id="keyFilter" className="form-control" placeholder="key" onKeyUp={this.handleKeyGrep}/> </form> </div> </nav> </div> ); } }); var Title = React.createClass({ render: function() { return ( <span>: {this.props.category}</span> ); } }); var Category = React.createClass({ render: function() { var active = this.props.currentCategory == this.props.name ? "active" : ""; var href = "/" + this.props.name; return ( <li role="presentation" className={active}><a href={href}>{this.props.name}</a></li> ); } }); var Categories = React.createClass({ render: function() { var currentCategory = this.props.currentCategory var handleChange = this.handleChange var cats = this.props.data.map(function(cat, index) { return ( <Category key={index} name={cat} currentCategory={currentCategory}/> ); }); return ( <ul className="nav nav-tabs"> {cats} </ul> ); } }); var Item = React.createClass({ render: function() { var item = this.props.item; var icon = "glyphicon"; var status = item.status; if (item.status != "success" && item.status != "info") { icon += " glyphicon-alert"; status += " alert-" + item.status; } return ( <tbody> <tr className={status} title={status}> <td><span className={icon} /> {item.node}</td> <td>{item.address}</td> <td>{item.key}</td> <td>{item.timestamp}</td> </tr> <tr className={status}> <td colSpan={4}><ItemBody>{item.data}</ItemBody></td> </tr> </tbody> ); } }); var ItemBody = React.createClass({ handleClick: function() { if ( this.state.expanded && window.getSelection().toString() != "" ) { return; } this.setState({ expanded: !this.state.expanded }) }, getInitialState: function() { return { expanded: false }; }, render: function() { var classString = "item_body" if (this.state.expanded) { classString = "item_body_expanded" } return ( <pre className={classString} onClick={this.handleClick}>{this.props.children}</pre> ); } }); var Dashboard = React.createClass({ loadCategoriesFromServer: function() { $.ajax({ url: "/api/?keys", dataType: 'json', success: function(data, textStatus, request) { if (!this.state.currentCategory) { location.pathname = "/" + data[0] } else { this.setState({categories: data}) } }.bind(this), error: function(xhr, status, err) { console.error("/api/?keys", status, err.toString()); }.bind(this) }); }, loadDashboardFromServer: function() { if (!this.state.currentCategory) { setTimeout(this.loadDashboardFromServer, this.props.pollWait / 5); return; } var statusFilter = this.state.statusFilter; var ajax = $.ajax({ url: "/api/" + this.state.currentCategory + "?recurse&wait=55s&index=" + this.state.index || 0, dataType: 'json', success: function(data, textStatus, request) { var timer = setTimeout(this.loadDashboardFromServer, this.props.pollWait); var index = request.getResponseHeader('X-Consul-Index') this.setState({ items: data, index: index, timer: timer, }); }.bind(this), error: function(xhr, status, err) { console.log("ajax error:" + err) var wait = this.props.pollWait * 5 if (err == "abort") { wait = 0 } var timer = setTimeout(this.loadDashboardFromServer, wait); this.setState({ timer: timer }) }.bind(this) }); this.setState({ajax: ajax}) }, getInitialState: function() { var cat = location.pathname.replace(/^\//,"") if (cat == "") { cat = undefined } return { items: [], categories: [], index: 0, ajax: undefined, timer: undefined, statusFilter: "", nodeFilter: "", keyFilter: "", currentCategory: cat }; }, componentDidMount: function() { this.loadCategoriesFromServer(); this.loadDashboardFromServer(); }, updateStatusFilter: function(filter) { this.setState({ statusFilter: filter }); }, updateNodeFilter: function(filter) { this.setState({ nodeFilter: filter }); }, updateKeyFilter: function(filter) { this.setState({ keyFilter: filter }); }, render: function() { var statusFilter = this.state.statusFilter; var nodeFilter = this.state.nodeFilter; var keyFilter = this.state.keyFilter; var items = this.state.items.map(function(item, index) { if ((statusFilter == "" || item.status == statusFilter) && (nodeFilter == "" || item.node.indexOf(nodeFilter) != -1 ) && (keyFilter == "" || item.key.indexOf(keyFilter) != -1 )) { return ( <Item key={index} item={item} /> ); } else { return; } }); return ( <div> <h1>Dashboard <Title category={this.state.currentCategory} /></h1> <Categories data={this.state.categories} currentCategory={this.state.currentCategory} /> <StatusSelector status={this.state.statusFilter} updateStatusFilter={this.updateStatusFilter} updateNodeFilter={this.updateNodeFilter} updateKeyFilter={this.updateKeyFilter} /> <table className="table table-bordered"> <thead> <tr> <th>node | service</th> <th>address</th> <th>key</th> <th className="item_timestamp_col">timestamp</th> </tr> </thead> {items} </table> </div> ); } }); React.render( <Dashboard pollWait={1000} />, document.getElementById('content') );
fujiwara/consul-kv-dashboard
assets/scripts/dashboard.js
JavaScript
mit
7,248
/* TDD style with BDD statements */ import LoggerWithMetadata from './index'; import clogy from '../../lib/clogy.js'; // Passing arrow functions to Mocha is discouraged. Their lexical binding of the // this value makes them unable to access the Mocha context, and statements like // this.timeout(1000); will not work inside an arrow function. // https://mochajs.org/#arrow-functions describe('loggerWithMetadata', function() { let sandbox; beforeEach(function() { sandbox = sinon.sandbox.create(); }); afterEach(function() { sandbox.restore(); }); it('should call clogs info method with the given metadata', function() { sandbox.stub(clogy, 'info'); const loggerWithMetadata = LoggerWithMetadata({ file: 'somefile.js' }); loggerWithMetadata.info('Hello World', 'Everyone'); expect(clogy.info).to.have.been.calledWith('[INFO] [file:somefile.js]', 'Hello World', 'Everyone'); }); });
pgmanutd/clogy
extensions/logger-with-metadata/index.spec.js
JavaScript
mit
928
'use strict'; const expect = require('chai').use(require('chai-string')).expect; const RSVP = require('rsvp'); const request = RSVP.denodeify(require('request')); const AddonTestApp = require('ember-cli-addon-tests').AddonTestApp; describe('FastBoot config', function () { this.timeout(400000); let app; before(function () { app = new AddonTestApp(); return app .create('fastboot-config', { skipNpm: true, emberVersion: 'latest', emberDataVersion: 'latest', }) .then(function () { app.editPackageJSON((pkg) => { delete pkg.devDependencies['ember-fetch']; delete pkg.devDependencies['ember-welcome-page']; }); return app.run('npm', 'install'); }) .then(function () { return app.startServer({ command: 'serve', }); }); }); after(function () { return app.stopServer(); }); it('provides sandbox globals', function () { return request({ url: 'http://localhost:49741/', headers: { Accept: 'text/html', }, }).then(function (response) { expect(response.statusCode).to.equal(200); expect(response.headers['content-type']).to.equalIgnoreCase( 'text/html; charset=utf-8' ); expect(response.body).to.contain('<h1>My Global</h1>'); }); }); });
ember-fastboot/ember-cli-fastboot
packages/ember-cli-fastboot/test/fastboot-config-test.js
JavaScript
mit
1,367
var Square = UI.component({ components: [Animator, KeyInput], animationMap: { moveLeft: { transform: [-50, 0, 0], time: 200, easing: "linear" }, moveRight: { transform: [50, 0, 0], time: 200, easing: "linear" } }, handleKeyPress: function(e) { if(e.keyCode === 37) { this.Animator.animate(this.animationMap.moveLeft); } else if(e.keyCode === 39) { this.Animator.animate(this.animationMap.moveRight); } }, render: function() { return {}; } }); var BigView = UI.component({ render: function() { var boxes = ["argo", "avatar", "breaking_bad", "brick_mansions", "crazy_stupid_love", "descendants", "gangs_of_new_york", "good_night_and_good_luck", "quantum_of_solace", "slumdog_millionaire", "the_kings_speech"]; var repeats = 2; while(--repeats) { boxes = boxes.concat(boxes); } var x = 0, y = 0; var tex_width = 186; var tex_height = 270; var scale = 0.5; var box_width = tex_width * scale; var box_height = tex_height * scale; var covers = boxes.map(function(box) { var box = UI.new(Square, { top: y, left: x, width: box_width, height: box_height, background: "boxes/box_"+box+".png" }); //console.info(box); x += box_width; if(x > 1000-box_width) { x = 0; y += box_height; } return box; }); //console.info(covers); var args = [Square, { name: "background-colored", top: 0, left: 0, width: 1000, height: 700 }].concat(covers); return UI.new.apply(this, args); } }); UI.render(BigView, document.getElementById("app")); var fps = document.getElementById("fps");
davedx/lustro
examples/auto-atlassing.js
JavaScript
mit
1,618
(function myAppCoreConstants() { 'use strict'; angular .module('myApp.core') .constant('FIREBASE_URL', 'https://blistering-heat-2473.firebaseio.com'); })();
neggro/angularjs_firebase
client/app/core/core.constants.js
JavaScript
mit
183
#!/usr/bin/env node const fs = require('fs'); const yaml = require('js-yaml'); const cli = require('../lib/cli'); // define cli options const optionList = [ { name: 'help', type: Boolean, description: 'show this help' }, { name: 'host', alias: 'h', type: String, description: 'host name' }, { name: 'port', alias: 'p', type: Number, description: 'port number' }, { name: 'watch', alias: 'w', type: Boolean, description: 'start in a watch mode' }, { name: 'docker', alias: 'd', type: Boolean, description: 'parse docker-compose.yml for parameters' }, // { name: 'file', alias: 'f', type: String, description: 'override the default docker-compose.yml file name' }, { name: 'service', alias: 's', type: String, description: 'service to look for when parsing docker-compose file' }, { name: 'flags', alias: 'l', type: String, description: 'custom flags to pass to rsync (default -rtR)' }, { name: 'volume', alias: 'v', type: String, description: 'override the default volume name' }, { name: 'version', type: Boolean, description: 'print version number' }, { name: 'files', type: String, defaultOption: true, multiple: true } ]; // define cli usage const usage = function (options) { return require('command-line-usage')([ { header: 'Synopsis', content: [ '$ drsync [bold]{--help}', ] }, { header: 'Options', optionList } ]) }; let args = require('command-line-args')(optionList, {}, process.argv); // override args with options from drsync.yml if (fs.existsSync('./drsync.yml')) { const overrides = yaml.safeLoad(fs.readFileSync('./drsync.yml', 'utf8')); if (overrides) { args = Object.assign({}, args, overrides.options); } } let options = {}; try { options = cli(args); } catch (err) { console.log(err.message); process.exit(); } // show help if requested if (options.help) { console.log(usage(options)); process.exit(); } // show version and exit if (options.version) { console.log(require('../package.json').version); process.exit(); } require('../lib/drsync')(options).subscribe(console.log);
stefda/drsync
bin/drsync.js
JavaScript
mit
2,107
/** * Created by alykoshin on 20.01.16. */ 'use strict'; var gulp = require('gulp'); module.exports = function(config) { // Define test task gulp.task('task21', function () { console.log('task21 is running, config:', config); }); // Define test task gulp.task('task22', function () { console.log('task22 is running, config:', config); }); };
alykoshin/require-dir-all
demo/21_gulp_advanced/gulp/tasks-enabled/task2.js
JavaScript
mit
371
const { FuseBox, QuantumPlugin, UglifyJSPlugin } = require("fuse-box"); const fuse = FuseBox.init({ target: "browser@es5", homeDir: ".", output: "dist/$name.js", plugins: [ QuantumPlugin({ treeshake: true, target: "browser", }), UglifyJSPlugin({ }) ], }); fuse.bundle("remark-bundle").instructions("> index.js"); fuse.run();
zipang/markdown-bundle
src/remark/bundle/fuse.js
JavaScript
mit
348
import { Controller } from 'marionette'; import Layout from '../commons/layout'; import MainPage from '../pages/mainPage'; import ImportPage from '../pages/importPage'; import ProfileView from '../pages/profileView'; export default Controller.extend({ defaultRoute(){ Layout.main.show( new MainPage() ); }, register(){ //Layout.main.show( new RegisterView() ); }, viewProfile(id){ Layout.main.show( new ProfileView(id) ); }, createAi(){ //Layout.main.show( new CreateAIView(id) ); }, import(){ Layout.main.show( new ImportPage() ); } });
jbsouvestre/challengr
Challengr/public/js/routes/controller.js
JavaScript
mit
619
import{ FETCH_TIMELOGS } from '../actions/TimelogActions'; function ajax(url, callback) { var data; var fetch; fetch = new XMLHttpRequest(); fetch.onreadystatechange = function() { if (fetch.readyState == XMLHttpRequest.DONE ) { if(fetch.status == 200){ var data = JSON.parse(fetch.responseText); console.log('---------------------- ajax response '); console.log(data); if (callback) callback(data); } else if(fetch.status == 404) { data = { error: 'There was an error 404' }; console.log('---------------------- ajax response '); console.log(data); } else { data = { error: 'something else other than 200 was returned' }; console.log('---------------------- ajax response '); console.log(data); } } }; fetch.open("GET", url, true); fetch.send(); return data; } var defaultState = ajax('timelogs.json', function (return_data) { return return_data; }); export default function timelogReducer(state = defaultState, action) { switch (action.type) { case FETCH_TIMELOGS: var new_state = ajax('timelogs.json', function (return_data) { console.log('Fetch timelogs was run'); return return_data; }); return new_state; default: return state; } }
pdx-code/teampro
src/reducers/TimelogReducer.js
JavaScript
mit
1,374
/** * @fileoverview Tests for cli. * @author Ian Christian Myers */ //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var assert = require("chai").assert, CLIEngine = require("../../lib/cli-engine"); require("shelljs/global"); /*global tempdir, mkdir, rm, cp*/ //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ describe("CLIEngine", function() { describe("executeOnFiles()", function() { var engine; it("should report zero messages when given a config file and a valid file", function() { engine = new CLIEngine({ // configFile: path.join(__dirname, "..", "..", ".eslintrc") }); var report = engine.executeOnFiles(["lib/cli.js"]); // console.dir(report.results[0].messages); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); it("should return one error message when given a config with rules with options and severity level set to error", function() { engine = new CLIEngine({ configFile: "tests/fixtures/configurations/quotes-error.json", reset: true }); var report = engine.executeOnFiles(["tests/fixtures/single-quoted.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "quotes"); assert.equal(report.results[0].messages[0].severity, 2); }); it("should return two messages when given a config file and a directory of files", function() { engine = new CLIEngine({ configFile: "tests/fixtures/configurations/semi-error.json", reset: true }); var report = engine.executeOnFiles(["tests/fixtures/formatters"]); assert.equal(report.results.length, 2); assert.equal(report.results[0].messages.length, 0); assert.equal(report.results[1].messages.length, 0); }); it("should return zero messages when given a config with environment set to browser", function() { engine = new CLIEngine({ configFile: "tests/fixtures/configurations/env-browser.json", reset: true }); var report = engine.executeOnFiles(["tests/fixtures/globals-browser.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); it("should return zero messages when given an option to set environment to browser", function() { engine = new CLIEngine({ envs: ["browser"], rules: { "no-undef": 2 }, reset: true }); var report = engine.executeOnFiles(["tests/fixtures/globals-browser.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); it("should return zero messages when given a config with environment set to Node.js", function() { engine = new CLIEngine({ configFile: "tests/fixtures/configurations/env-node.json", reset: true }); var report = engine.executeOnFiles(["tests/fixtures/globals-node.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); it("should not return results from previous call when calling more than once", function() { engine = new CLIEngine({ ignore: false, reset: true, rules: { semi: 2 } }); var report = engine.executeOnFiles(["tests/fixtures/missing-semicolon.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "tests/fixtures/missing-semicolon.js"); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "semi"); assert.equal(report.results[0].messages[0].severity, 2); report = engine.executeOnFiles(["tests/fixtures/passing.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "tests/fixtures/passing.js"); assert.equal(report.results[0].messages.length, 0); }); it("should return zero messages when given a directory with eslint excluded files in the directory", function() { engine = new CLIEngine({ ignorePath: "tests/fixtures/.eslintignore" }); var report = engine.executeOnFiles(["tests/fixtures/"]); assert.equal(report.results.length, 0); }); it("should return zero messages when given a file in excluded files list", function() { engine = new CLIEngine({ ignorePath: "tests/fixtures/.eslintignore" }); var report = engine.executeOnFiles(["tests/fixtures/passing"]); assert.equal(report.results.length, 0); }); it("should return two messages when given a file in excluded files list while ignore is off", function() { engine = new CLIEngine({ ignorePath: "tests/fixtures/.eslintignore", ignore: false, reset: true, rules: { "no-undef": 2 } }); var report = engine.executeOnFiles(["tests/fixtures/undef.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "tests/fixtures/undef.js"); assert.equal(report.results[0].messages[0].ruleId, "no-undef"); assert.equal(report.results[0].messages[0].severity, 2); assert.equal(report.results[0].messages[1].ruleId, "no-undef"); assert.equal(report.results[0].messages[1].severity, 2); }); it("should return zero messages when executing a file with a shebang", function() { engine = new CLIEngine({ ignore: false, reset: true }); var report = engine.executeOnFiles(["tests/fixtures/shebang.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); it("should thrown an error when loading a custom rule that doesn't exist", function() { engine = new CLIEngine({ ignore: false, reset: true, rulesPaths: ["./tests/fixtures/rules/wrong"], configFile: "./tests/fixtures/rules/eslint.json" }); assert.throws(function() { engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]); }, /Definition for rule 'custom-rule' was not found/); }); it("should thrown an error when loading a custom rule that doesn't exist", function() { engine = new CLIEngine({ ignore: false, reset: true, rulePaths: ["./tests/fixtures/rules/wrong"], configFile: "./tests/fixtures/rules/eslint.json" }); assert.throws(function() { engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]); }, /Error while loading rule 'custom-rule'/); }); it("should return one message when a custom rule matches a file", function() { engine = new CLIEngine({ ignore: false, reset: true, useEslintrc: false, rulePaths: ["./tests/fixtures/rules/"], configFile: "./tests/fixtures/rules/eslint.json" }); var report = engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "tests/fixtures/rules/test/test-custom-rule.js"); assert.equal(report.results[0].messages.length, 2); assert.equal(report.results[0].messages[0].ruleId, "custom-rule"); assert.equal(report.results[0].messages[0].severity, 1); }); it("should return messages when multiple custom rules match a file", function() { engine = new CLIEngine({ ignore: false, reset: true, rulePaths: [ "./tests/fixtures/rules/dir1", "./tests/fixtures/rules/dir2" ], configFile: "./tests/fixtures/rules/multi-rulesdirs.json" }); var report = engine.executeOnFiles(["tests/fixtures/rules/test-multi-rulesdirs.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "tests/fixtures/rules/test-multi-rulesdirs.js"); assert.equal(report.results[0].messages.length, 2); assert.equal(report.results[0].messages[0].ruleId, "no-literals"); assert.equal(report.results[0].messages[0].severity, 2); assert.equal(report.results[0].messages[1].ruleId, "no-strings"); assert.equal(report.results[0].messages[1].severity, 2); }); it("should return zero messages when executing with reset flag", function() { engine = new CLIEngine({ ignore: false, reset: true, useEslintrc: false }); var report = engine.executeOnFiles(["./tests/fixtures/missing-semicolon.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "./tests/fixtures/missing-semicolon.js"); assert.equal(report.results[0].messages.length, 0); }); it("should return zero messages when executing with reset flag in Node.js environment", function() { engine = new CLIEngine({ ignore: false, reset: true, useEslintrc: false, envs: ["node"] }); var report = engine.executeOnFiles(["./tests/fixtures/process-exit.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "./tests/fixtures/process-exit.js"); assert.equal(report.results[0].messages.length, 0); }); it("should return zero messages and ignore local config file when executing with no-eslintrc flag", function () { engine = new CLIEngine({ ignore: false, reset: true, useEslintrc: false, envs: ["node"] }); var report = engine.executeOnFiles(["./tests/fixtures/eslintrc/quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "./tests/fixtures/eslintrc/quotes.js"); assert.equal(report.results[0].messages.length, 0); }); it("should return zero messages when executing with local config file", function () { engine = new CLIEngine({ ignore: false, reset: true }); var report = engine.executeOnFiles(["./tests/fixtures/eslintrc/quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "./tests/fixtures/eslintrc/quotes.js"); assert.equal(report.results[0].messages.length, 1); }); // These tests have to do with https://github.com/eslint/eslint/issues/963 describe("configuration hierarchy", function() { var fixtureDir; // copy into clean area so as not to get "infected" by this project's .eslintrc files before(function() { fixtureDir = tempdir() + "/eslint/fixtures"; mkdir("-p", fixtureDir); cp("-r", "./tests/fixtures/config-hierarchy", fixtureDir); }); after(function() { rm("-r", fixtureDir); }); // Default configuration - blank it("should return zero messages when executing with reset and no .eslintrc", function () { engine = new CLIEngine({ reset: true, useEslintrc: false }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); // Default configuration - conf/eslint.json it("should return one message when executing with no .eslintrc", function () { engine = new CLIEngine({ useEslintrc: false }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 3); assert.equal(report.results[0].messages[0].ruleId, "no-undef"); assert.equal(report.results[0].messages[0].severity, 2); assert.equal(report.results[0].messages[1].ruleId, "no-console"); assert.equal(report.results[0].messages[1].severity, 2); assert.equal(report.results[0].messages[2].ruleId, "quotes"); assert.equal(report.results[0].messages[2].severity, 2); }); // Default configuration - conf/environments.json (/*eslint-env node*/) it("should return one message when executing with no .eslintrc in the Node.js environment", function () { engine = new CLIEngine({ useEslintrc: false }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes-node.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "quotes"); assert.equal(report.results[0].messages[0].severity, 2); }); // Project configuration - first level .eslintrc it("should return one message when executing with .eslintrc in the Node.js environment", function () { engine = new CLIEngine(); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/process-exit.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "no-process-exit"); assert.equal(report.results[0].messages[0].severity, 2); }); // Project configuration - first level .eslintrc it("should return zero messages when executing with .eslintrc in the Node.js environment and reset", function () { engine = new CLIEngine({ reset: true }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/process-exit.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); // Project configuration - first level .eslintrc it("should return one message when executing with .eslintrc", function () { engine = new CLIEngine({ reset: true }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "quotes"); assert.equal(report.results[0].messages[0].severity, 2); }); // Project configuration - first level package.json it("should return one message when executing with package.json"); // Project configuration - second level .eslintrc it("should return one message when executing with local .eslintrc that overrides parent .eslintrc", function () { engine = new CLIEngine({ reset: true }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/subbroken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "no-console"); assert.equal(report.results[0].messages[0].severity, 1); }); // Project configuration - third level .eslintrc it("should return one message when executing with local .eslintrc that overrides parent and grandparent .eslintrc", function () { engine = new CLIEngine({ reset: true }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/subbroken/subsubbroken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "quotes"); assert.equal(report.results[0].messages[0].severity, 1); }); // Command line configuration - --config with first level .eslintrc it("should return two messages when executing with config file that adds to local .eslintrc", function () { engine = new CLIEngine({ reset: true, configFile: fixtureDir + "/config-hierarchy/broken/add-conf.yaml" }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 2); assert.equal(report.results[0].messages[0].ruleId, "semi"); assert.equal(report.results[0].messages[0].severity, 1); assert.equal(report.results[0].messages[1].ruleId, "quotes"); assert.equal(report.results[0].messages[1].severity, 2); }); // Command line configuration - --config with first level .eslintrc it("should return no messages when executing with config file that overrides local .eslintrc", function () { engine = new CLIEngine({ reset: true, configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml" }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); // Command line configuration - --config with second level .eslintrc it("should return two messages when executing with config file that adds to local and parent .eslintrc", function () { engine = new CLIEngine({ reset: true, configFile: fixtureDir + "/config-hierarchy/broken/add-conf.yaml" }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/subbroken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 2); assert.equal(report.results[0].messages[0].ruleId, "semi"); assert.equal(report.results[0].messages[0].severity, 1); assert.equal(report.results[0].messages[1].ruleId, "no-console"); assert.equal(report.results[0].messages[1].severity, 1); }); // Command line configuration - --config with second level .eslintrc it("should return one message when executing with config file that overrides local and parent .eslintrc", function () { engine = new CLIEngine({ reset: true, configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml" }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/subbroken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "no-console"); assert.equal(report.results[0].messages[0].severity, 1); }); // Command line configuration - --config with first level .eslintrc it("should return no messages when executing with config file that overrides local .eslintrc", function () { engine = new CLIEngine({ reset: true, configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml" }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); // Command line configuration - --rule with --config and first level .eslintrc it("should return one message when executing with command line rule and config file that overrides local .eslintrc", function () { engine = new CLIEngine({ reset: true, configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml", rules: { quotes: [1, "double"] } }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "quotes"); assert.equal(report.results[0].messages[0].severity, 1); }); // Command line configuration - --rule with --config and first level .eslintrc it("should return one message when executing with command line rule and config file that overrides local .eslintrc", function () { engine = new CLIEngine({ reset: true, configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml", rules: { quotes: [1, "double"] } }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "quotes"); assert.equal(report.results[0].messages[0].severity, 1); }); }); // it("should return zero messages when executing with global node flag", function () { // engine = new CLIEngine({ // ignore: false, // reset: true, // useEslintrc: false, // configFile: "./conf/eslint.json", // envs: ["node"] // }); // var files = [ // "./tests/fixtures/globals-node.js" // ]; // var report = engine.executeOnFiles(files); // console.dir(report.results[0].messages); // assert.equal(report.results.length, 1); // assert.equal(report.results[0].filePath, files[0]); // assert.equal(report.results[0].messages.length, 1); // }); // it("should return zero messages when executing with global env flag", function () { // engine = new CLIEngine({ // ignore: false, // reset: true, // useEslintrc: false, // configFile: "./conf/eslint.json", // envs: ["browser", "node"] // }); // var files = [ // "./tests/fixtures/globals-browser.js", // "./tests/fixtures/globals-node.js" // ]; // var report = engine.executeOnFiles(files); // console.dir(report.results[1].messages); // assert.equal(report.results.length, 2); // assert.equal(report.results[0].filePath, files[0]); // assert.equal(report.results[0].messages.length, 1); // assert.equal(report.results[1].filePath, files[1]); // assert.equal(report.results[1].messages.length, 1); // }); // it("should return zero messages when executing with env flag", function () { // var files = [ // "./tests/fixtures/globals-browser.js", // "./tests/fixtures/globals-node.js" // ]; // it("should allow environment-specific globals", function () { // cli.execute("--reset --no-eslintrc --config ./conf/eslint.json --env browser,node --no-ignore " + files.join(" ")); // assert.equal(console.log.args[0][0].split("\n").length, 9); // }); // it("should allow environment-specific globals, with multiple flags", function () { // cli.execute("--reset --no-eslintrc --config ./conf/eslint.json --env browser --env node --no-ignore " + files.join(" ")); // assert.equal(console.log.args[0][0].split("\n").length, 9); // }); // }); // it("should return zero messages when executing without env flag", function () { // var files = [ // "./tests/fixtures/globals-browser.js", // "./tests/fixtures/globals-node.js" // ]; // it("should not define environment-specific globals", function () { // cli.execute("--reset --no-eslintrc --config ./conf/eslint.json --no-ignore " + files.join(" ")); // assert.equal(console.log.args[0][0].split("\n").length, 12); // }); // }); // it("should return zero messages when executing with global flag", function () { // it("should default defined variables to read-only", function () { // var exit = cli.execute("--global baz,bat --no-ignore ./tests/fixtures/undef.js"); // assert.isTrue(console.log.calledOnce); // assert.equal(exit, 1); // }); // it("should allow defining writable global variables", function () { // var exit = cli.execute("--reset --global baz:false,bat:true --no-ignore ./tests/fixtures/undef.js"); // assert.isTrue(console.log.notCalled); // assert.equal(exit, 0); // }); // it("should allow defining variables with multiple flags", function () { // var exit = cli.execute("--reset --global baz --global bat:true --no-ignore ./tests/fixtures/undef.js"); // assert.isTrue(console.log.notCalled); // assert.equal(exit, 0); // }); // }); }); });
roadhump/eslint
tests/lib/cli-engine.js
JavaScript
mit
28,534
/* global angular, moment */ var app = angular.module('flowList', ['ui.grid']); app.controller('flowListCtrl', function($scope, $http) { 'use strict'; $http.get('/json/rawFlowsForLast/5/minutes') .success(function(data) { var retList = []; data.forEach(function(element) { var flowRecord = { srcAddress: element._source.ipv4_src_addr, dstAddress: element._source.ipv4_dst_addr, Packets: element._source.in_pkts, Bytes: element._source.in_bytes, Time: moment(element._source.timestamp) .format('YYYY-MM-DD HH:mm:ss') }; retList.push(flowRecord); }); $scope.flows = retList; }) .error(function() { console.warn('doh'); }); });
skarfacegc/FlowTrack2
www/js/flowListController.js
JavaScript
mit
836
require('date-utils'); var sendgrid = require('sendgrid')("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"); module.exports = function(app, config, passport, mongoose, fs, path){ var isAuthenticated = function(req, res, next){ if(req.isAuthenticated()){ return next(); } else { res.redirect("/login"); } } app.get("/", isAuthenticated, function(req, res){ res.render("index.html"); }); app.get("/myaccount", isAuthenticated, function(req, res){ res.render("index.html"); }); app.get("/create", isAuthenticated, function(req, res){ res.render("index.html"); }); app.get("/search", isAuthenticated, function(req, res){ res.render("index.html"); }); app.get("/login", passport.authenticate('google', { scope : ['profile', 'email'] }) ); app.get("/auth/google/callback", passport.authenticate('google', { successRedirect : '/', failureRedirect: '/login', failureFlash: true }) ); app.get('/logout', function(req, res) { req.logout(); res.redirect("/"); }); var getPools = function(query, res){ var requests = mongoose.model('request'); requests.find(query, function(err, result){ if (err) { console.log(err); } else { res.setHeader('Cache-Control', 'no-cache'); res.json(result); } }); }; app.get('/api/comments', isAuthenticated, function(req, res) { var query = {$or:[{createdOn: {$eq: Date.today()}}, {everyday: {$eq: true}}]}; getPools(query, res); }); app.get('/api/mycomments', isAuthenticated, function(req, res) { var myEmailId = req.user.email; var query = {email: myEmailId}; getPools(query, res); }); app.delete('/api/comments', function (req, res) { var requests = mongoose.model('request'); var query = {_id: req.body.id}; requests.remove(query, function(err, result){ if (err) { console.log(err); } else { console.log("pool deleted"); } }); }); app.post('/api/comments', isAuthenticated, function(req, res) { var user = req.user; var request = mongoose.model('request'); var newRequest = new request({ email: user.email, name: user.name, originAddress: req.body.originAddress, destinationAddress: req.body.destinationAddress, provider: req.body.provider, time: req.body.time, encodedRoute: req.body.encodedRoute, createdOn: Date.today(), everyday: req.body.everyday }); newRequest.save(function (err, result) { if (err) { console.log(err); } else { console.log('documents into the "request" collection are:', result); res.setHeader('Cache-Control', 'no-cache'); res.json(result); } }); }); app.post('/notify', isAuthenticated, function(req, res) { var notifications = req.body.notifications; console.log("notifications"); console.log(notifications); notifications.forEach(function(notification){ var payload = { to : notification.email, from : notification.from, subject : notification.subject, html : notification.html } sendgrid.send(payload, function(err, json) { if (err) { console.error(err); }else{ res.json(json); } }); }); }); app.get('/user', function (req, res) { res.json(req.user); }); }
prabhuramkumar/ThoughtPool
config/routes.js
JavaScript
mit
3,415
(function () { 'use strict'; angular.module('AngularPanelsApp.theme') .directive('trackWidth', trackWidth); /** @ngInject */ function trackWidth() { return { scope: { trackWidth: '=', minWidth: '=', }, link: function (scope, element) { scope.trackWidth = $(element).width() < scope.minWidth; scope.prevTrackWidth = scope.trackWidth; $(window).resize(function() { var trackWidth = $(element).width() < scope.minWidth; if (trackWidth !== scope.prevTrackWidth) { scope.$apply(function() { scope.trackWidth = trackWidth; }); } scope.prevTrackWidth = trackWidth; }); } }; } })();
mauroBus/angular-panels-app
src/app/theme/directives/trackWidth.js
JavaScript
mit
752
function testRequest(place) { //Pebble.sendAppMessage({"status": "Initiated"}); var req = new XMLHttpRequest(); req.open('GET', 'http://maps.googleapis.com/maps/api/geocode/json?address='+ place + '&sensor=false', true); req.onload = function(e) { if (req.readyState == 4 && req.status == 200) { //readystate 4 is DONE //status 200 is OK if(req.status == 200) { var response = JSON.parse(req.responseText); console.log(req.responseText); var location = response.results[0].formatted_address; //var icon = response.list[0].main.icon; //Pebble.sendAppMessage({'status': stat, 'message':'test completed'}); Pebble.sendAppMessage({"status": "Processed","location":location}); } else { console.log('Error'); Pebble.sendAppMessage({"status": "Error"}); } } }; req.send(null); } function testRequestTime() { Pebble.sendAppMessage({"status": "Initiated"}); var req = new XMLHttpRequest(); req.open('GET', 'https://maps.googleapis.com/maps/api/timezone/json?location=59,10&timestamp=360000000&sensor=false', true); req.onload = function(e) { if (req.readyState == 4 && req.status == 200) { //readystate 4 is DONE //status 200 is OK if(req.status == 200) { var response = JSON.parse(req.responseText); console.log(req.responseText); var rawOffset = response.rawOffset; var dstOffset = response.dstOffset; var totOffset = rawOffset+dstOffset; //var icon = response.list[0].main.icon; //Pebble.sendAppMessage({'status': stat, 'message':'test completed'}); Pebble.sendAppMessage({"status": "Processed","offset":totOffset}); } else { console.log('Error'); Pebble.sendAppMessage({"status": "Error"}); } } }; req.send(null); } function makeRequest(method, url, callback) { var req = new XMLHttpRequest(); req.open(method, url, true); req.onload = function(e) { if(req.readyState == 4) { callback(req); } }; req.send(null); } function getOffset(lat,lon){ var timestamp = new Date() / 1000 | 0; makeRequest('GET', 'https://maps.googleapis.com/maps/api/timezone/json?location='lat+','+lon+'timestamp='+timestamp+'&sensor=false', true,my_callback2); } function getLocation(place){ makeRequest('GET','http://maps.googleapis.com/maps/api/geocode/json?address='+ place +'&sensor=false',my_callback1); } // Function to send a message to the Pebble using AppMessage API function sendMessage() { //Pebble.sendAppMessage({"status": 0}); //testRequest(); //testRequestTime(); // PRO TIP: If you are sending more than one message, or a complex set of messages, // it is important that you setup an ackHandler and a nackHandler and call // Pebble.sendAppMessage({ /* Message here */ }, ackHandler, nackHandler), which // will designate the ackHandler and nackHandler that will be called upon the Pebble // ack-ing or nack-ing the message you just sent. The specified nackHandler will // also be called if your message send attempt times out. } // Called when JS is ready Pebble.addEventListener("ready", function(e) { }); // Called when incoming message from the Pebble is received Pebble.addEventListener("appmessage", function(e) { console.log("Received Status: " + e.payload.status); testRequest(e.payload.place); });
alin256/MultiZoneNew
src/pkjs/js/pebble-js-app.js
JavaScript
mit
3,399
version https://git-lfs.github.com/spec/v1 oid sha256:91f5e00183c2613cc249e316de2c35c08d8068c7e57cf90d3d4ea7b0179ef7cf size 651743
yogeshsaroya/new-cdnjs
ajax/libs/yasgui/0.0.6/yasgui.min.js
JavaScript
mit
131
'use strict'; const inView = require('in-view'); const forEach = require('lodash/forEach'); require('gsap'); class Animations { constructor () { this.root = document; this.h1 = this.root.querySelector('[data-hat-title] h1'); this.curtainH1 = this.root.querySelector('[data-curtain-goRight]'); this.goUps = this.root.querySelectorAll('[data-stagger-goUp]'); this.skillsItems = this.root.querySelectorAll('[data-skills-item]'); this.experienceP = this.root.querySelectorAll('[data-experience-container]'); this.portfolioItems = this.root.querySelectorAll('[data-portfolio-item]'); this.map = this.root.querySelector('[data-map]'); this.travelsDescription = this.root.querySelector('[data-travels-p]'); this.contactContainer = this.root.querySelector('[data-contact-container]'); this.animationStarted = false; this.textSpanned = false; } } Animations.prototype.init = function () { if(this.animationStarted) { return; } this.setup(); window.setTimeout(this.animateH1.bind(this), 1000); this.addListenerDescription(); this.addListenerSkillsH2(); this.addListenerExperienceH2(); this.addListenerTravelsH2(); this.addListenerPortfolioH2(); this.addListenerContactH2(); this.triggerResize(); this.animationStarted = true; }; Animations.prototype.setup = function () { TweenMax.set(this.skillsItems, {opacity: 0, yPercent: 100}); TweenMax.set(this.travelsDescription, {opacity: 0}); TweenMax.set(this.map, {opacity: 0}); TweenMax.set(this.experienceP, {opacity: 0}); TweenMax.set(this.portfolioItems, {opacity: 0, yPercent: 100}); TweenMax.set(this.contactContainer, {opacity: 0, yPercent: 100}); this.h2ToBeSpanned = this.root.querySelectorAll('[data-to-be-spanned]'); forEach(this.h2ToBeSpanned, function (title) { let titleMod = title.innerText.split(''); let tmparray = []; forEach(titleMod, function (letter, index) { tmparray[index] = '<span class="letter-box" data-letter-box>' + letter + '</span>'; }); title.innerHTML = tmparray.join(''); }); this.textSpanned = true; }; Animations.prototype.triggerResize = function () { window.dispatchEvent(new Event('resize')); }; Animations.prototype.animateH1 = function () { const spans = this.h1.querySelectorAll('span'); const tl = new TimelineLite({onComplete: this.afterH1.bind(this)}); tl.to(this.curtainH1, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(this.h1, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.curtainH1, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(spans, 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterH1 = function () { this.curtainH1.remove(); TweenMax.staggerTo(this.goUps, .22, {yPercent: -100, opacity: 1, onComplete: this.animateMenu.bind(this) }, .11); }; Animations.prototype.animateMenu = function () { const links = this.root.querySelectorAll('[data-audio-play]'); TweenMax.staggerTo(links, .21, {opacity: 1, yPercent: 100, delay: .66}, .08); }; Animations.prototype.addListenerDescription = function () { inView('[data-description]') .once('enter', function(el) { el.style.opacity = 1; }.bind(this)); }; //Skills Animations.prototype.addListenerSkillsH2 = function () { inView('[data-skills]') .once('enter', function(el){ this.animateSkillsH2(el); }.bind(this)); }; Animations.prototype.animateSkillsH2 = function (el) { const titleH2 = el.querySelector('[data-skills-title] h2'); this.skillsCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterSkillsH2.bind(this)}); tl.to(this.skillsCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.skillsCurtainH2, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterSkillsH2 = function () { this.skillsCurtainH2.remove(); this.animateSkillsItems(); }; Animations.prototype.animateSkillsItems = function (el) { TweenMax.staggerTo(this.skillsItems, .41, {opacity: 1, yPercent: 0, delay: .55}, .18); }; //Experience Animations.prototype.addListenerExperienceH2 = function () { inView('[data-experience]') .once('enter', function(el){ this.animateExperienceH2(el); }.bind(this)); }; Animations.prototype.animateExperienceH2 = function (el) { const titleH2 = el.querySelector('[data-experience-title] h2'); this.experienceCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterExperienceH2.bind(this)}); tl.to(this.experienceCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.experienceCurtainH2, .66, {xPercent: 203, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterExperienceH2 = function () { this.experienceCurtainH2.remove(); TweenMax.to(this.experienceP, 1, {opacity: 1, ease: Power3.easeIn}); } //Travels Animations.prototype.addListenerTravelsH2 = function () { inView('[data-travels]') .once('enter', function(el) { this.animateTravelsH2(el); }.bind(this)); }; Animations.prototype.animateTravelsH2 = function (el) { const titleH2 = el.querySelector('[data-travels-title] h2'); this.arrows = document.getElementById('freccette'); this.travelsCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterTravelsH2.bind(this)}); tl.to(this.travelsCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.travelsCurtainH2, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterTravelsH2 = function () { this.travelsCurtainH2.remove(); TweenMax.to(this.map, .33, {opacity: 1}); this.arrows.classList.add('visible'); TweenMax.to(this.travelsDescription, .44, {opacity: 1, ease: Power3.easeOut}); }; //Portfolio Animations.prototype.addListenerPortfolioH2 = function () { inView('[data-portfolio]') .once('enter', function(el) { this.animatePortfolioH2(el); }.bind(this)); }; Animations.prototype.animatePortfolioH2 = function (el) { const titleH2 = el.querySelector('[data-portfolio-title] h2'); this.portfolioCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterPortfolioH2.bind(this)}); tl.to(this.portfolioCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.portfolioCurtainH2, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterPortfolioH2 = function () { this.portfolioCurtainH2.remove(); this.animatePortfolioItems(); }; Animations.prototype.animatePortfolioItems = function (el) { TweenMax.staggerTo(this.portfolioItems, .88, {opacity: 1, yPercent: 0, ease: Power3.easeOut}, .28); }; //Contact Animations.prototype.addListenerContactH2 = function () { inView('[data-contact]') .once('enter', function(el) { this.animateContactH2(el); }.bind(this)); }; Animations.prototype.animateContactH2 = function (el) { const titleH2 = el.querySelector('[data-contact-title] h2'); this.contactCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterContactH2.bind(this)}); tl.to(this.contactCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.contactCurtainH2, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterContactH2 = function () { this.contactCurtainH2.remove(); TweenMax.to(this.contactContainer, .33, {opacity: 1, yPercent: 0}); }; Animations.prototype.destroy = function () { TweenMax.set(this.skillsItems, {clearProps: 'all'}); TweenMax.set(this.portfolioItems, {clearProps: 'all'}); TweenMax.set(this.map, {clearProps: 'all'}); TweenMax.set(this.experienceP, {clearProps: 'all'}); if(this.textSpanned) { this.clearTextFromSpan(); } }; Animations.prototype.clearTextFromSpan = function () { forEach(this.h2ToBeSpanned, function (title) { let titleInner = title.querySelectorAll('[data-letter-box]'); let tmparray = []; forEach(titleInner, function(el, index){ tmparray[index] = el.innerText; }); title.innerHTML = tmparray.join(''); }); this.textSpanned = false; }; module.exports = Animations;
dnlml/myvc
src/assets/scripts/parts/animations.js
JavaScript
mit
9,136
"use strict"; var notify = require("gulp-notify"); module.exports = function(error) { if( !global.isProd ) { var args = Array.prototype.slice.call(arguments); // Send error to notification center with gulp-notify notify.onError({ title: "Compile Error", message: "<%= error.message %>" }).apply(this, args); // Keep gulp from hanging on this task this.emit("end"); } else { // Log the error and stop the process // to prevent broken code from building console.log(error); process.exit(1); } };
polygon-city/citygml-visual-debugger
gulp/util/handleErrors.js
JavaScript
mit
560
/* colorstrip.js, a plugin for jQuery Copyright (C) 2011 John Watson <[email protected]> flagrantdisregard.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function($) { var colorstrip = new Object; var settings = { maxInterval: 8000, /* milliseconds */ minInterval: 4000, /* milliseconds */ opacity: 0.5, /* 0..1 */ minWidth: 10, /* percent */ maxWidth: 80, /* percent */ colors: ['#c00', '#0c0', '#00c'] }; var strips = []; var timeouts = []; colorstrip.start = function() { var s = colorstrip.target; for(var i=0; i<settings.colors.length; i++) { var e = $('<div>'); e.css( { height: '100%', width: '30%', position: 'absolute', top: 0, left: Math.random()*$(s).width(), opacity: settings.opacity, 'background-color': settings.colors[i] } ); strips.push(e); colorstrip.target.append(e); colorstrip.animate(e); } } colorstrip.animate = function(e) { if (e == undefined) return; var s = colorstrip.target; var n = strips.length; var left = $(e).position().left; var right = $(e).position().left + $(e).width(); $(e).stop(); if (left > $(s).width()) { $(e).css({left: -$(e).width(), 'z-index': Math.random()*n}); } if (right < 0) { $(e).css({left: $(s).width(), 'z-index': Math.random()*n}); } var range = $(s).width() + $(e).width(); var timeout = Math.random()*(settings.maxInterval-settings.minInterval)+settings.minInterval; $(e).animate( { left: Math.random()*range - $(e).width(), width: (Math.random()*(settings.maxWidth-settings.minWidth)+settings.minWidth) + '%' }, timeout, 'easeInOutSine'); timeouts.push(setTimeout(function(){colorstrip.animate(e)}, timeout)); } colorstrip.stop = function() { for(var i=0;i<timeouts.length;i++) { clearTimeout(timeouts[i]); } for(var i=0;i<strips.length;i++) { strips[i].stop(); } } $.fn.colorstrip = function(method, options) { if (typeof method == 'object') { $.extend(settings, method); } if (typeof options == 'object') { $.extend(settings, options); } if (colorstrip[method]) { colorstrip[method](); } else { colorstrip.target = this; colorstrip.start(); } } })(jQuery);
Overdriven-Labs/Mexicoen140
app_server/public/js/colorstrip.js
JavaScript
mit
3,808
googletag.cmd.push(function () { googletag.defineSlot('/423694368/test_Environment_728x90_3', [728, 90], 'div-gpt-ad-1437711610911-0').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_300x600', [300, 600], 'div-gpt-ad-1437711610911-1').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_728x90_1', [[728, 90], [320, 50]], 'div-gpt-ad-1437711610911-2').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_300x250_1', [300, 250], 'div-gpt-ad-1437711610911-3').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_300x250_2', [300, 250], 'div-gpt-ad-1437711610911-4').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_300x250_3', [300, 250], 'div-gpt-ad-1437711610911-5').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_300x250_4', [300, 250], 'div-gpt-ad-1437711610911-6').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_other_300x250_5', [300, 250], 'div-gpt-ad-1469610501174-0').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_300x40_1', [300, 40], 'div-gpt-ad-1437711610911-7').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_300x40_2', [300, 40], 'div-gpt-ad-1437711610911-8').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_300x40_3', [300, 40], 'div-gpt-ad-1437711610911-9').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_300x40_4', [300, 40], 'div-gpt-ad-1437711610911-10').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_300x40_5', [300, 40], 'div-gpt-ad-1437711610911-11').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_PicAD_mix', [[300, 328], [620, 558]], 'div-gpt-ad-1437711610911-12').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_300x1100_left', [300, 1100], 'div-gpt-ad-1443171775703-12').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_300x1100_right', [300, 1100], 'div-gpt-ad-1443171993398-12').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_Environment_960x200', [960, 200], 'div-gpt-ad-1443172174182-12').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_all_300x40_6', [300, 40], 'div-gpt-ad-1501743689891-0').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_all_300x40_7', [300, 40], 'div-gpt-ad-1501743689891-1').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_all_300x40_8', [300, 40], 'div-gpt-ad-1501743689891-2').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_all_300x40_9', [300, 40], 'div-gpt-ad-1501743689891-3').addService(googletag.pubads()); googletag.defineSlot('/423694368/test_all_300x40_10', [300, 40], 'div-gpt-ad-1501743689891-4').addService(googletag.pubads()); googletag.pubads().enableSingleRequest(); googletag.pubads().collapseEmptyDivs(); googletag.enableServices(); });
jessicaliuCW/assets_new
dfp_js/channel/channel_12_test.js
JavaScript
mit
3,235
asc.component('asc-combobox', function(){ this.afterInit = function (combobox) { var div = eDOM.el('div.dropdown-list'); while (combobox.children.length) { var item = combobox.children[0]; if (item.tagName === "ITEM") { item.innerText += item.getAttribute("text"); div.appendChild(item); } } combobox.appendChild(div); var innerText = eDOM.el('span'); var selectedValue = combobox.getAttribute("data-selected-value"); var previouslySelected; if (selectedValue) { for (var i = 0; i < div.children.length; i++) { var child = div.children[i]; if (child.getAttribute("value") === selectedValue) { child.classList.add('selected'); previouslySelected = child; innerText.innerHTML = child.getAttribute("text"); break; } } } if (innerText.innerHTML.length === 0) { innerText.innerHTML = combobox.getAttribute('data-placeholder'); } combobox.insertBefore(innerText, div); combobox.style.width = combobox.offsetWidth + "px"; div.style.width = (combobox.offsetWidth + 14) + "px"; var closeBackClick = function () { combobox.classList.remove('active'); document.body.removeEventListener('click', closeBackClick); }; combobox.addEventListener('click', function (e) { if (combobox.classList.contains('active')) { if (e.target.tagName === "ITEM") { previouslySelected.classList.remove('selected'); previouslySelected = e.target; e.target.classList.add('selected'); innerText.innerHTML = e.target.getAttribute("text"); combobox.setAttribute("data-selected-value", e.target.getAttribute("value")); } closeBackClick(); } else { combobox.classList.add('active'); setTimeout(function () { document.body.addEventListener('click', closeBackClick); }, 0); } }); } });
vestlirik/apple-style-controls
src/combobox/code.js
JavaScript
mit
2,304
module.exports = function ({ $lookup }) { return { object: function () { return function (object, $step = 0) { let $_, $bite return function $parse ($buffer, $start, $end) { switch ($step) { case 0: object = { nudge: 0, padded: 0, sentry: 0 } case 1: case 2: if ($start == $end) { $step = 2 return { start: $start, object: null, parse: $parse } } object.nudge = $buffer[$start++] case 3: $_ = 3 case 4: $bite = Math.min($end - $start, $_) $_ -= $bite $start += $bite if ($_ != 0) { $step = 4 return { start: $start, object: null, parse: $parse } } case 5: $_ = 0 $bite = 1 case 6: while ($bite != -1) { if ($start == $end) { $step = 6 return { start: $start, object: null, parse: $parse } } $_ += $buffer[$start++] << $bite * 8 >>> 0 $bite-- } object.padded = $_ case 7: $_ = 3 case 8: $bite = Math.min($end - $start, $_) $_ -= $bite $start += $bite if ($_ != 0) { $step = 8 return { start: $start, object: null, parse: $parse } } case 9: case 10: if ($start == $end) { $step = 10 return { start: $start, object: null, parse: $parse } } object.sentry = $buffer[$start++] } return { start: $start, object: object, parse: null } } } } () } }
bigeasy/packet
test/generated/literal/single.parser.inc.js
JavaScript
mit
2,627
var context; var plainCanvas; var log; var pointerDown = {}; var lastPositions = {}; var colors = ["rgb(100, 255, 100)", "rgb(255, 0, 0)", "rgb(0, 255, 0)", "rgb(255, 0, 0)", "rgb(0, 255, 100)", "rgb(10, 255, 255)", "rgb(255, 0, 100)"]; var onPointerMove = function(evt) { if (pointerDown[evt.pointerId]) { var color = colors[evt.pointerId % colors.length]; context.strokeStyle = color; context.beginPath(); context.lineWidth = 2; context.moveTo(lastPositions[evt.pointerId].x, lastPositions[evt.pointerId].y); context.lineTo(evt.clientX, evt.clientY); context.closePath(); context.stroke(); lastPositions[evt.pointerId] = { x: evt.clientX, y: evt.clientY }; } }; var pointerLog = function (evt) { var pre = document.querySelector("pre"); pre.innerHTML = evt.type + "\t\t(" + evt.clientX + ", " + evt.clientY + ")\n" + pre.innerHTML; }; var onPointerUp = function (evt) { pointerDown[evt.pointerId] = false; pointerLog(evt); }; var onPointerDown = function (evt) { pointerDown[evt.pointerId] = true; lastPositions[evt.pointerId] = { x: evt.clientX, y: evt.clientY }; pointerLog(evt); }; var onPointerEnter = function (evt) { pointerLog(evt); }; var onPointerLeave = function (evt) { pointerLog(evt); }; var onPointerOver = function (evt) { pointerLog(evt); }; var onload = function() { plainCanvas = document.getElementById("plainCanvas"); log = document.getElementById("log"); plainCanvas.width = plainCanvas.clientWidth; plainCanvas.height = plainCanvas.clientHeight; context = plainCanvas.getContext("2d"); context.fillStyle = "rgba(50, 50, 50, 1)"; context.fillRect(0, 0, plainCanvas.width, plainCanvas.height); plainCanvas.addEventListener("pointerdown", onPointerDown, false); plainCanvas.addEventListener("pointermove", onPointerMove, false); plainCanvas.addEventListener("pointerup", onPointerUp, false); plainCanvas.addEventListener("pointerout", onPointerUp, false); plainCanvas.addEventListener("pointerenter", onPointerEnter, false); plainCanvas.addEventListener("pointerleave", onPointerLeave, false); plainCanvas.addEventListener("pointerover", onPointerOver, false); }; if (document.addEventListener !== undefined) { document.addEventListener("DOMContentLoaded", onload, false); } ;
rtillery/html5demos
draw/index.js
JavaScript
mit
2,482
import http from 'http'; function upsertState(state) { var postData = JSON.stringify(state); var options = { hostname: 'localhost', port: 3000, path: '/application', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': postData.length } }; var req = http.request(options, (res) => { res.setEncoding('utf8'); }); req.write(postData); req.end(); } let defaultState = { excitement: 0, poc: { name: '', email: '' }, contributors: [], popover: false }; let savedState = JSON.parse(localStorage.getItem('appState')); export default function application(state = savedState || defaultState, action) { let newState switch (action.type) { case 'GET_EXCITED': { newState = Object.assign({}, state, { excitement: state.excitement += 1 }); break; } case 'UPDATE_POC': { newState = Object.assign({}, state, { poc: { name: action.name, email: action.email } }); break; } case 'PERSIST_STATE': { upsertState(state); newState = state; break; } case 'SHOW_POPOVER': { newState = Object.assign({}, state, { popover: true }); break; } case 'UPDATE_ESSAY': { newState = Object.assign({}, state, { [action.prompt]: action.response }); break; } case 'UPDATE_COMPANY_NAME': { newState = Object.assign({}, state, { companyName: action.name }); break; } case 'UPDATE_COMPANY_TYPE': { newState = Object.assign({}, state, { companyType: action.companyType }); break; } case 'REMOVE_CONTRIBUTOR': { const contributors = state.contributors.slice(0, state.contributors.length - 1) newState = Object.assign({}, state, { contributors: contributors }); break; } case 'UPDATE_CONTRIBUTOR': { let updated = false; const contributors = state.contributors.map((contributor) => { if (contributor.id === action.id) { updated = true; return { id: contributor.id, name: action.name, email: action.email } } else { return contributor; } }); if (!updated) { contributors.push({ id: action.id, name: action.name, email: action.email }); } newState = Object.assign({}, state, { contributors: contributors }); break; } default: { newState = state; } } localStorage.setItem('appState', JSON.stringify(newState)) return newState; }
doug-wade/incubator-application
browser/reducers/index.js
JavaScript
mit
2,674
version https://git-lfs.github.com/spec/v1 oid sha256:00be998e9791a319bc3751b20c19ce0fa3cb25a87c8dbf9030a728c92af8d95c size 100787
yogeshsaroya/new-cdnjs
ajax/libs/rxjs/2.3.24/rx.all.compat.min.js
JavaScript
mit
131
import PropTypes from 'prop-types' import React from 'react' const Card = ({title}) => <h3>{title}</h3> Card.propTypes = { title: PropTypes.string.isRequired } export default Card
dustinspecker/the-x-effect
app/components/card/index.js
JavaScript
mit
187
var arr = 'ciao come va'.split(' '); var filtered = arr.filter(function(item) { return item != 'va'; }); Array.prototype.filtroMio = function() { if (arr.length == 2) { return this } return []; }; var ar2 = arr.filtroMio(); console.log(ar2); console.log(filtered);
brugnara/node-lessons
lessons/05-filtered.js
JavaScript
mit
280
'use strict'; const test = require('tape'); const Postman = require('../fixtures/postman'); test('`it` without any args', (t) => { let postman = new Postman(t); describe('my test suite', () => { it(); }); postman.checkTests({ '1. my test suite - test #1 (this.fn is not a function)': false, }); t.end(); }); test('`it` with only a name', (t) => { let postman = new Postman(t); describe('my test suite', () => { it('my test'); }); postman.checkTests({ '1. my test suite - my test (this.fn is not a function)': false, }); t.end(); }); test('`it` with only a function', (t) => { let postman = new Postman(t); describe('my test suite', () => { it(() => { }); }); postman.checkTests({ '1. my test suite - test #1': true }); t.end(); }); test('`it` outside of `describe` block', (t) => { let postman = new Postman(t); let i = 0; it('my first test', () => { assert.equal(++i, 1); }); describe('my test suite', () => { it('my second test', () => { assert.equal(++i, 2); }); }); it('my third test', () => { assert.equal(++i, 3); }); t.equal(i, 3); postman.checkTests({ '1. my first test': true, '2. my test suite - my second test': true, '3. my third test': true, }); t.end(); }); test('Error in `it`', (t) => { let postman = new Postman(t); describe('my test suite', () => { it('my test', () => { throw new Error('BOOM!'); }); }); postman.checkTests({ '1. my test suite - my test (BOOM!)': false, }); t.end(); }); test('Error in unnamed `it`', (t) => { let postman = new Postman(t); describe('my test suite', () => { it(() => { throw new Error('BOOM!'); }); }); postman.checkTests({ '1. my test suite - test #1 (BOOM!)': false, }); t.end(); }); test('`it` with successful assertions', (t) => { let postman = new Postman(t); describe('my test suite', () => { it('my test', () => { assert(true); assert.ok(42); assert.equal('hello', 'hello'); expect(new Date()).not.to.equal(new Date()); new Date().should.be.a('Date'); }); }); postman.checkTests({ '1. my test suite - my test': true }); t.end(); }); test('`it` with failed assertions', (t) => { let postman = new Postman(t); describe('my test suite', () => { it('my test', () => { assert.equal('hello', 'world'); }); }); postman.checkTests({ '1. my test suite - my test (expected \'hello\' to equal \'world\')': false, }); t.end(); }); test('`it` runs in the corret order', (t) => { let postman = new Postman(t); let i = 0; describe('my test suite', () => { it('my first test', () => { assert.equal(++i, 1); }); it('my second test', () => { assert.equal(++i, 2); }); it('my third test', () => { assert.equal(++i, 3); }); }); t.equal(i, 3); postman.checkTests({ '1. my test suite - my first test': true, '2. my test suite - my second test': true, '3. my test suite - my third test': true, }); t.end(); }); test('`it` runs in the corret order even if there are failed assertions', (t) => { let postman = new Postman(t); let i = 0; describe('my test suite', () => { it('my first test', () => { assert.equal(++i, 1); }); it('my second test', () => { assert.equal(++i, 9999); }); it('my third test', () => { assert.equal(++i, 3); }); }); t.equal(i, 3); postman.checkTests({ '1. my test suite - my first test': true, '2. my test suite - my second test (expected 2 to equal 9999)': false, '3. my test suite - my third test': true, }); t.end(); }); test('`it` runs in the corret order even if an error occurs', (t) => { let postman = new Postman(t); let i = 0; describe('my test suite', () => { it('my first test', () => { assert.equal(++i, 1); }); it('my second test', () => { assert.equal(++i, 2); throw new Error('BOOM'); }); it('my third test', () => { assert.equal(++i, 3); }); }); t.equal(i, 3); postman.checkTests({ '1. my test suite - my first test': true, '2. my test suite - my second test (BOOM)': false, '3. my test suite - my third test': true, }); t.end(); }); test('`it` can be nested', (t) => { let postman = new Postman(t); let i = 0; it('my first test', () => { assert.equal(++i, 1); }); describe('my test suite', () => { it('my second test', () => { assert.equal(++i, 2); }); describe(() => { it('my third test', () => { assert.equal(++i, 3); }); describe(() => { it('my fourth test', () => { assert.equal(++i, 4); }); }); it('my fifth test', () => { assert.equal(++i, 5); }); }); it('my sixth test', () => { assert.equal(++i, 6); }); }); it('my seventh test', () => { assert.equal(++i, 7); }); t.equal(i, 7); postman.checkTests({ '1. my first test': true, '2. my test suite - my second test': true, '3. my test suite - describe #2 - my third test': true, '4. my test suite - describe #2 - describe #3 - my fourth test': true, '5. my test suite - describe #2 - my fifth test': true, '6. my test suite - my sixth test': true, '7. my seventh test': true, }); t.end(); });
BigstickCarpet/postman-bdd
test/specs/it.spec.js
JavaScript
mit
5,442
'use strict'; var Promise = require('bluebird'); var util = require('./util'); module.exports = function (bookshelf) { var BaseModel = bookshelf.Model.extend({ initialize: function () { this.on('saving', this.validate); }, validate: function (model, attrs, options) { return Promise.resolve(null) .then(util.collectAndCheckMissingAttributes.bind(this, options)) .then(util.validateAttributes.bind(this)) .then(util.setValidatedAttributes.bind(this)); } }); bookshelf.Model = BaseModel; };
murmur76/bookshelf-validation
index.js
JavaScript
mit
545
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('users', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, name: { type: Sequelize.STRING }, username: { type: Sequelize.STRING, allowNull: false, unique: true }, password: { type: Sequelize.STRING, allowNull: false }, salt: { type: Sequelize.STRING, allowNull: false }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('users'); } };
geanjunior/cracha
migrations/20170127020036-create-user.js
JavaScript
mit
1,093
import 'pixi' import 'p2' import Phaser from 'phaser' import BootState from './states/Boot' import SplashState from './states/Splash' import GameState from './states/Game' import config from './config' class Game extends Phaser.Game { constructor () { const docElement = document.documentElement const width = docElement.clientWidth; const height = docElement.clientHeight; super(width, height, Phaser.Auto, 'content', null) this.state.add('Boot', BootState, false); this.state.add('Splash', SplashState, false); this.state.add('Game', GameState, false); this.state.start('Boot') } } window.game = new Game();
juergensen/a-little-game-2
src/main.js
JavaScript
mit
690
import lazy from "lazy.js"; import { EventEmitter } from "events"; import _ from "lodash"; import AppDispatcher from "../AppDispatcher"; import GameStatus from "../constants/GameStatus"; import CompsEvents from "../events/CompsEvents"; import GamesEvents from "../events/GamesEvents"; class GameStore { constructor() { this.info = { status: GameStatus.NOT_STARTED }; this.player = null; this.lastToken = null; this.states = []; } getInfo() { return this.info; } getPlayer() { return this.player; } getLastToken() { return this.lastToken; } getStatus() { return this.info.status; } getState(i) { return this.states[i]; } getCurrentState() { return this.states[this.states.length - 1]; } getAllStates() { return this.states; } getStateCount() { return this.states.length; } _setInfo(info) { this.info = info; } _setPlayer(player) { this.player = player; } _setLastToken(playerToken) { this.lastToken = playerToken; } _setStatus(status) { this.info.status = status; } _pushState(state) { this.states.push(state); } _setAllStates(states) { this.states = states; } } const GamesStore = lazy(EventEmitter.prototype).extend({ games: {}, getGame: function (gameHref, gameId) { let games = this.games[gameHref] = this.games[gameHref] || {}; return games[gameId] = games[gameId] || new GameStore(); }, getAllGames: function (gameHref) { let forHref = this.games[gameHref] = this.games[gameHref] || {}; return _.values(forHref); } }).value(); AppDispatcher.register(function (action) { const { actionType, gameHref, gameId, data, error } = action; let store = gameId ? GamesStore.getGame(gameHref, gameId) : null; switch (actionType) { case GamesEvents.GAME_INFO: store._setInfo(action.game); GamesStore.emit(actionType, gameHref, gameId); break; case GamesEvents.GAME_INFO_ERROR: GamesStore.emit(actionType, gameHref, gameId, error); break; case GamesEvents.GAMES_LIST: action.games.forEach(info => { GamesStore.getGame(gameHref, info.gameId)._setInfo(info); GamesStore.emit(GamesEvents.GAME_INFO, gameHref, info.gameId); }); GamesStore.emit(actionType, gameHref); break; case GamesEvents.GAMES_LIST_ERROR: GamesStore.emit(actionType, gameHref, error); break; case CompsEvents.COMP_GAMES: action.games.forEach(info => { GamesStore.getGame(gameHref, info.gameId)._setInfo(info); GamesStore.emit(GamesEvents.GAME_INFO, gameHref, info.gameId); }); break; case GamesEvents.REGISTER_SUCCESS: store._setLastToken(data.playerToken); GamesStore.emit(actionType, gameHref, gameId, data.playerToken); break; case GamesEvents.REGISTER_ERROR: GamesStore.emit(actionType, gameHref, gameId, error); break; case GamesEvents.INFO: store._setPlayer(data.player); GamesStore.emit(actionType, gameHref, gameId); break; case GamesEvents.HISTORY: store._setAllStates( lazy(data).filter(e => e.eventType === "state").map(e => e.state).value()); break; case GamesEvents.START: case GamesEvents.STATE: store._setStatus(GameStatus.STARTED); store._pushState(data); GamesStore.emit(GamesEvents.NEW_STATE, gameHref, gameId); break; case GamesEvents.END: store._setStatus(GameStatus.ENDED); store._pushState(data); GamesStore.emit(GamesEvents.NEW_STATE, gameHref, gameId); break; case GamesEvents.CONNECTION_OPENED: store._setLastToken(action.playerToken); store._setAllStates([]); GamesStore.emit(actionType, gameHref, gameId); break; case GamesEvents.CONNECTION_CLOSED: case GamesEvents.CONNECTION_ERROR: GamesStore.emit(actionType, gameHref, gameId); break; } }); export default GamesStore;
ruippeixotog/botwars
client/js/stores/GamesStore.js
JavaScript
mit
3,892
Template.sort.helpers({ activeRouteClass: function(/* route names */) { // Man kann natürlich benannte Argumente an die Funktion übergeben, aber man kann auch eine beliebige Anzahl von anonymen Parametern mitgeben und abrufen indem man innerhalb der Funktion das Objekt arguments aufruft. var args = Array.prototype.slice.call(arguments, 0); args.pop(); // Im letzten Fall sollte man das Objekt arguments in ein herkömmliches JavaScript Array konvertieren und dann pop() darauf anwenden um den Hash loszuwerden, den Spacebars am Ende eingefügt hat. var active = _.any(args, function(name) { return Router.current() && Router.current().route.name === name }); return active && 'active'; // JavaScript Pattern boolean && string, bei dem false && myString false zurückgibt, aber true && myString gibt myString zurück } });
shiftux/discover_meteor
client/templates/includes/sort.js
JavaScript
mit
859
define(function(require) { var _ = require('underscore'), d3 = require('d3'); function isTime(type) { return _.contains(['time', 'timestamp', 'date'], type); } function isNum(type) { return _.contains(['num', 'int4', 'int', 'int8', 'float8', 'float', 'bigint'], type); } function isStr(type) { return _.contains(['varchar', 'text', 'str'], type); } function debugMode() { try { return !$("#fake-type > input[type=checkbox]").get()[0].checked; } catch(e) { return false; } } function negateClause(SQL) { if (!SQL) return null; if ($("#selection-type > input[type=checkbox]").get()[0].checked) return SQL; return "not(" + SQL + ")"; } // points: [ { yalias:,..., xalias: } ] // ycols: [ { col, alias, expr } ] function getYDomain(points, ycols) { var yaliases = _.pluck(ycols, 'alias'), yss = _.map(yaliases, function(yalias) { return _.pluck(points, yalias) }), ydomain = [Infinity, -Infinity]; _.each(yss, function(ys) { ys = _.filter(ys, _.isFinite); if (ys.length) { ydomain[0] = Math.min(ydomain[0], d3.min(ys)); ydomain[1] = Math.max(ydomain[1], d3.max(ys)); } }); return ydomain; } // assume getx(point) and point.range contain x values function getXDomain(points, type, getx) { var xdomain = null; if (isStr(type)) { xdomain = {}; _.each(points, function(d) { if (d.range) { _.each(d.range, function(o) { xdomain[o] = 1; }); } xdomain[getx(d)] = 1 ; }); xdomain = _.keys(xdomain); return xdomain; } var diff = 1; var xvals = []; _.each(points, function(d) { if (d.range) xvals.push.apply(xvals, d.range); xvals.push(getx(d)); }); xvals = _.reject(xvals, _.isNull); if (isNum(type)) { xvals = _.filter(xvals, _.isFinite); xdomain = [ d3.min(xvals), d3.max(xvals) ]; diff = 1; if (xdomain[0] != xdomain[1]) diff = (xdomain[1] - xdomain[0]) * 0.05; xdomain[0] -= diff; xdomain[1] += diff; } else if (isTime(type)) { xvals = _.map(xvals, function(v) { return new Date(v); }); xdomain = [ d3.min(xvals), d3.max(xvals) ]; diff = 1000*60*60*24; // 1 day if (xdomain[0] != xdomain[1]) diff = (xdomain[1] - xdomain[0]) * 0.05; xdomain[0] = new Date(+xdomain[0] - diff); xdomain[1] = new Date(+xdomain[1] + diff); } //console.log([type, 'diff', diff, 'domain', JSON.stringify(xdomain)]); return xdomain; } function mergeDomain(oldd, newd, type) { var defaultd = [Infinity, -Infinity]; if (isStr(type)) defaultd = []; if (oldd == null) return newd; if (isStr(type)) return _.union(oldd, newd); var ret = _.clone(oldd); if (!_.isNull(newd[0]) && (_.isFinite(newd[0]) || isTime(newd[0]))) ret[0] = d3.min([ret[0], newd[0]]); if (!_.isNull(newd[1]) && (_.isFinite(newd[1]) || isTime(newd[1]))) ret[1] = d3.max([ret[1], newd[1]]); return ret; } function estNumXTicks(xaxis, type, w) { var xscales = xaxis.scale(); var ex = 40.0/5; var xticks = 10; while(xticks > 1) { if (isStr(type)) { var nchars = d3.sum(_.times( Math.min(xticks, xscales.domain().length), function(idx){return (""+xscales.domain()[idx]).length+.8}) ) } else { var fmt = xscales.tickFormat(); var fmtlen = function(s) {return fmt(s).length+.8;}; var nchars = d3.sum(xscales.ticks(xticks), fmtlen); } if (ex*nchars < w) break; xticks--; } xticks = Math.max(1, +xticks.toFixed()); return xticks; } function setAxisLabels(axis, type, nticks) { var scales = axis.scale(); axis.ticks(nticks).tickSize(0,0); if (isStr(type)) { var skip = scales.domain().length / nticks; var idx = 0; var previdx = null; var tickvals = []; while (idx < scales.domain().length) { if (previdx == null || Math.floor(idx) > previdx) { tickvals.push(scales.domain()[Math.floor(idx)]) } idx += skip; } axis.tickValues(tickvals); } return axis; } function toWhereClause(col, type, vals) { if (!vals || vals.length == 0) return null; var SQL = null; var re = new RegExp("'", "gi"); if (isStr(type)) { SQL = []; if (_.contains(vals, null)) { SQL.push(col + " is null"); } var nonnulls = _.reject(vals, _.isNull); if (nonnulls.length == 1) { var v = nonnulls[0]; if (_.isString(v)) v = "'" + v.replace(re, "\\'") + "'"; SQL.push(col + " = " + v); } else if (nonnulls.length > 1) { vals = _.map(nonnulls, function(v) { if (_.isString(v)) return "'" + v.replace(re, "\\'") + "'"; return v; }); SQL.push(col + " in ("+vals.join(', ')+")"); } if (SQL.length == 0) SQL = null; else if (SQL.length == 1) SQL = SQL[0]; else SQL = "("+SQL.join(' or ')+")"; } else { if (isTime(type)) { if (type == 'time') { var val2s = function(v) { // the values could have already been string encoded. if (_.isDate(v)) return "'" + (new Date(v)).toLocaleTimeString() + "'"; return v; }; } else { var val2s = function(v) { if(_.isDate(v)) return "'" + (new Date(v)).toISOString() + "'"; return v; }; } //vals = _.map(vals, function(v) { return new Date(v)}); } else { var val2s = function(v) { return +v }; } if (vals.length == 1) { SQL = col + " = " + val2s(vals[0]); } else { SQL = [ val2s(d3.min(vals)) + " <= " + col, col + " <= " + val2s(d3.max(vals)) ].join(' and '); } } return SQL; } return { isTime: isTime, isNum: isNum, isStr: isStr, estNumXTicks: estNumXTicks, setAxisLabels: setAxisLabels, toWhereClause: toWhereClause, negateClause: negateClause, getXDomain: getXDomain, getYDomain: getYDomain, mergeDomain: mergeDomain, debugMode: debugMode } })
sirrice/dbwipes
dbwipes/static/js/summary/util.js
JavaScript
mit
6,474
Package.describe({ name: 'angular-compilers', version: '0.4.0', summary: 'Rollup, AOT, SCSS, HTML and TypeScript compilers for Angular Meteor', git: 'https://github.com/Urigo/angular-meteor/tree/master/atmosphere-packages/angular-compilers', documentation: 'README.md' }); Package.registerBuildPlugin({ name: 'Angular Compilers', sources: [ 'plugin/register.js' ], use: [ // Uses an external packages to get the actual compilers '[email protected]', '[email protected]', '[email protected]', '[email protected]' ] }); Package.onUse(function (api) { api.versionsFrom('1.11'); // Required in order to register plugins api.use('isobuild:[email protected]'); });
Urigo/angular-meteor
atmosphere-packages/angular-compilers/package.js
JavaScript
mit
780
var $ = require('jquery'); var layout = module.exports = { init: function() { $('#toggle-sidebar').click(function(e) { e.preventDefault(); layout.sidebar(); }); $('#toggle-overlay').click(function(e) { e.preventDefault(); layout.overlay(); }); }, restore: function() { return this; }, overlay: function(b) { if( typeof b !== 'boolean' ) b = !$('body > .panel').hasClass('overlay'); if( b ) $('body > .panel').addClass('overlay'), $('#toggle-overlay').html('<i class="fa fa-compress"></i>'); else $('body > .panel').removeClass('overlay'), $('#toggle-overlay').html('<i class="fa fa-expand"></i>'); return this; }, sidebar: function(b) { if( typeof b !== 'boolean' ) b = !$('body > .panel').hasClass('sidebar-open'); if( b ) $('body > .panel').addClass('sidebar-open'); else $('body > .panel').removeClass('sidebar-open'); return this; }, fullsize: function(b) { if( typeof b !== 'boolean' ) b = !$('#page').hasClass('fullsize'); if( b ) $('#page').addClass('fullsize'); else $('#page').removeClass('fullsize'); return this; }, dark: function(b) { if( typeof b !== 'boolean' ) b = !$('#page').hasClass('dark'); if( b ) $('#page, header > .utilities').addClass('dark'); else $('#page, header > .utilities').removeClass('dark'); return this; }, gnb: { select: function(url) { $('.gnb > a').each(function() { var el = $(this); if( el.attr('href') === url ) el.addClass('active'); else el.removeClass('active'); }); return this; } } };
joje6/three-cats
www/js/layout.js
JavaScript
mit
1,624
var a = createElement("a"); attr(a, 'href', ""); function anchor(label, href) { var element = createElement(a); attr(element, "href", label); if (isString(label)) { text(element, label); } else { appendChild(element, label); } onclick(element, function (event) { if (/^\w+\:/.test(href)) return; event.preventDefault(); go(href); }); return element; }
yunxu1019/efront
coms/zimoli/anchor.js
JavaScript
mit
423
'use strict'; /** * Module Dependencies */ var config = require('../config/config'); var _ = require('lodash'); var Twit = require('twit'); var async = require('async'); var debug = require('debug')('skeleton'); // https://github.com/visionmedia/debug var graph = require('fbgraph'); var tumblr = require('tumblr.js'); var Github = require('github-api'); var stripe = require('stripe')(config.stripe.key); var twilio = require('twilio')(config.twilio.sid, config.twilio.token); var paypal = require('paypal-rest-sdk'); var cheerio = require('cheerio'); // https://github.com/cheeriojs/cheerio var request = require('request'); // https://github.com/mikeal/request var passport = require('passport'); var foursquare = require('node-foursquare')({ secrets: config.foursquare }); var LastFmNode = require('lastfm').LastFmNode; var querystring = require('querystring'); var passportConf = require('../config/passport'); /** * API Controller */ module.exports.controller = function (app) { /** * GET /api* * *ALL* api routes must be authenticated first */ app.all('/api*', passportConf.isAuthenticated); /** * GET /api * List of API examples. */ // app.get('/api', function (req, res) { // res.render('api/index', { // url: req.url // }); // }); /** * GET /api/react * React examples */ app.get('/api/react', function (req, res) { res.render('api/react', { url: req.url }); }); /** * GET /creditcard * Credit Card Form Example. */ app.get('/api/creditcard', function (req, res) { res.render('api/creditcard', { url: req.url }); }); /** * GET /api/lastfm * Last.fm API example. */ app.get('/api/lastfm', function (req, res, next) { var lastfm = new LastFmNode(config.lastfm); async.parallel({ artistInfo: function (done) { lastfm.request('artist.getInfo', { artist: 'Morcheeba', handlers: { success: function (data) { done(null, data); }, error: function (err) { done(err); } } }); }, artistTopAlbums: function (done) { lastfm.request('artist.getTopAlbums', { artist: 'Morcheeba', handlers: { success: function (data) { var albums = []; _.forEach(data.topalbums.album, function (album) { albums.push(album.image.slice(-1)[0]['#text']); }); done(null, albums.slice(0, 4)); }, error: function (err) { done(err); } } }); } }, function (err, results) { if (err) { return next(err.message); } var artist = { name: results.artistInfo.artist.name, image: results.artistInfo.artist.image.slice(-1)[0]['#text'], tags: results.artistInfo.artist.tags.tag, bio: results.artistInfo.artist.bio.summary, stats: results.artistInfo.artist.stats, similar: results.artistInfo.artist.similar.artist, topAlbums: results.artistTopAlbums }; res.render('api/lastfm', { artist: artist, url: '/apiopen' }); }); }); /** * GET /api/nyt * New York Times API example. */ app.get('/api/nyt', function (req, res, next) { var query = querystring.stringify({ 'api-key': config.nyt.key, 'list-name': 'young-adult' }); var url = 'http://api.nytimes.com/svc/books/v2/lists?' + query; request.get(url, function (error, request, body) { if (request.statusCode === 403) { return next(error('Missing or Invalid New York Times API Key')); } var bestsellers = {}; // NYT occasionally sends bad data :( try { bestsellers = JSON.parse(body); } catch (err) { bestsellers.results = ''; req.flash('error', { msg: err.message }); } res.render('api/nyt', { url: '/apiopen', books: bestsellers.results }); }); }); /** * GET /api/paypal * PayPal SDK example. */ app.get('/api/paypal', function (req, res, next) { paypal.configure(config.paypal); var payment_details = { intent: 'sale', payer: { payment_method: 'paypal' }, redirect_urls: { return_url: config.paypal.returnUrl, cancel_url: config.paypal.cancelUrl }, transactions: [ { description: 'ITEM: Something Awesome!', amount: { currency: 'USD', total: '2.99' } } ] }; paypal.payment.create(payment_details, function (error, payment) { if (error) { // TODO FIXME console.log(error); } else { req.session.payment_id = payment.id; var links = payment.links; for (var i = 0; i < links.length; i++) { if (links[i].rel === 'approval_url') { res.render('api/paypal', { url: '/apilocked', approval_url: links[i].href }); } } } }); }); /** * GET /api/paypal/success * PayPal SDK example. */ app.get('/api/paypal/success', function (req, res, next) { var payment_id = req.session.payment_id; var payment_details = { payer_id: req.query.PayerID }; paypal.payment.execute(payment_id, payment_details, function (error, payment) { if (error) { res.render('api/paypal', { url: req.url, result: true, success: false }); } else { res.render('api/paypal', { url: '/apilocked', result: true, success: true }); } }); }); /** * GET /api/paypal/cancel * PayPal SDK example. */ app.get('/api/paypal/cancel', function (req, res, next) { req.session.payment_id = null; res.render('api/paypal', { url: '/apilocked', result: true, canceled: true }); }); /** * GET /api/scraping * Web scraping example using Cheerio library. */ app.get('/api/scraping', function (req, res, next) { request.get({ url: 'https://news.ycombinator.com/', timeout: 3000 }, function (err, response, body) { if (!err && response.statusCode === 200) { var $ = cheerio.load(body); // Get Articles var links = []; $('.title a[href^="http"], .title a[href^="https"], .title a[href^="item"]').each(function () { if ($(this).text() !== 'scribd') { if ($(this).text() !== 'Bugs') { links.push($(this)); } } }); // Get Comments var comments = []; $('.subtext a[href^="item"]').each(function () { comments.push('<a href="https://news.ycombinator.com/' + $(this).attr('href') + '">' + $(this).text() + '</a>'); }); // Render Page res.render('api/scraping', { url: '/apiopen', links: links, comments: comments }); } else { req.flash('error', { msg: 'Sorry, something went wrong! MSG: ' + err.message }); return res.redirect('back'); } }); }); /** * GET /api/socrata * Web scraping example using Cheerio library. */ app.get('/api/socrata', function (req, res, next) { // Get the socrata open data as JSON // http://dev.socrata.com/docs/queries.html request.get({ url: 'http://controllerdata.lacity.org/resource/qjfm-3srk.json?$order=q4_earnings DESC&$where=year = 2014&$limit=20', timeout: 5000 }, function (err, response, body) { if (!err && response.statusCode === 200) { // Parse the data var payroll = JSON.parse(body); // Render the page res.render('api/socrata', { url: '/apiopen', data: payroll }); } else { req.flash('error', { msg: 'Sorry, something went wrong! MSG: ' + err.message }); return res.redirect('back'); } }); }); /** * GET /api/stripe * Stripe API example. */ app.get('/api/stripe', function (req, res, next) { res.render('api/stripe', { title: 'Stripe API' }); }); /** * POST /api/stripe * @param stipeToken * @param stripeEmail */ app.post('/api/stripe', function (req, res, next) { var stripeToken = req.body.stripeToken; var stripeEmail = req.body.stripeEmail; stripe.charges.create({ amount: 395, currency: 'usd', card: stripeToken, description: stripeEmail }, function (err, charge) { if (err && err.type === 'StripeCardError') { req.flash('error', { msg: 'Your card has been declined.' }); res.redirect('/api/stripe'); } req.flash('success', { msg: 'Your card has been charged successfully.' }); res.redirect('/api/stripe'); }); }); /** * GET /api/twilio * Twilio API example. */ app.get('/api/twilio', function (req, res, next) { res.render('api/twilio', { url: '/apiopen' }); }); /** * POST /api/twilio * Twilio API example. * @param telephone */ app.post('/api/twilio', function (req, res, next) { var message = { to: req.body.telephone, from: config.twilio.phone, body: 'Hello from ' + app.locals.application + '. We are happy you are testing our code!' }; twilio.sendMessage(message, function (err, responseData) { if (err) { return next(err); } req.flash('success', { msg: 'Text sent to ' + responseData.to + '.' }); res.redirect('/api/twilio'); }); }); /** * GET /api/foursquare * Foursquare API example. */ app.get('/api/foursquare', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res, next) { var token = _.find(req.user.tokens, { kind: 'foursquare' }); async.parallel({ trendingVenues: function (callback) { foursquare.Venues.getTrending('40.7222756', '-74.0022724', { limit: 50 }, token.accessToken, function (err, results) { callback(err, results); }); }, venueDetail: function (callback) { foursquare.Venues.getVenue('49da74aef964a5208b5e1fe3', token.accessToken, function (err, results) { callback(err, results); }); }, userCheckins: function (callback) { foursquare.Users.getCheckins('self', null, token.accessToken, function (err, results) { callback(err, results); }); } }, function (err, results) { if (err) { return next(err); } res.render('api/foursquare', { url: '/apilocked', trendingVenues: results.trendingVenues, venueDetail: results.venueDetail, userCheckins: results.userCheckins }); }); }); /** * GET /api/tumblr * Tumblr API example. */ app.get('/api/tumblr', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res) { var token = _.find(req.user.tokens, { kind: 'tumblr' }); var client = tumblr.createClient({ consumer_key: config.tumblr.key, consumer_secret: config.tumblr.secret, token: token.token, token_secret: token.tokenSecret }); client.posts('danielmoyerdesign.tumblr.com', { type: 'photo' }, function (err, data) { res.render('api/tumblr', { url: '/apilocked', blog: data.blog, photoset: data.posts[0].photos }); }); }); /** * GET /api/facebook * Facebook API example. */ app.get('/api/facebook', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res, next) { var token = _.find(req.user.tokens, { kind: 'facebook' }); graph.setAccessToken(token.accessToken); async.parallel({ getMe: function (done) { graph.get(req.user.facebook, function (err, me) { done(err, me); }); }, getMyFriends: function (done) { graph.get(req.user.facebook + '/friends', function (err, friends) { debug('Friends: ' + JSON.stringify(friends)); done(err, friends); }); } }, function (err, results) { if (err) { return next(err); } res.render('api/facebook', { url: '/apilocked', me: results.getMe, friends: results.getMyFriends }); }); }); /** * GET /api/github * GitHub API Example. */ app.get('/api/github', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res) { var token = _.find(req.user.tokens, { kind: 'github' }); var github = new Github({ token: token.accessToken }); var repo = github.getRepo('dstroot', 'skeleton'); repo.show(function (err, repo) { res.render('api/github', { url: '/apilocked', repo: repo }); }); }); /** * GET /api/twitter * Twitter API example. * https://dev.twitter.com/rest/reference/get/search/tweets */ app.get('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res, next) { var token = _.find(req.user.tokens, { kind: 'twitter' }); var params = { q: 'iPhone 6', since_id: 24012619984051000, count: 10, result_type: 'popular' }; var T = new Twit({ consumer_key: config.twitter.consumerKey, consumer_secret: config.twitter.consumerSecret, access_token: token.token, access_token_secret: token.tokenSecret }); T.get('search/tweets', params, function (err, data, response) { if (err) { return next(err); } res.render('api/twitter', { url: '/apilocked', tweets: data.statuses }); }); }); /** * POST /api/twitter * Post a tweet. */ app.post('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res, next) { req.assert('tweet', 'Tweet cannot be empty.').notEmpty(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/api/twitter'); } var token = _.find(req.user.tokens, { kind: 'twitter' }); var T = new Twit({ consumer_key: config.twitter.consumerKey, consumer_secret: config.twitter.consumerSecret, access_token: token.token, access_token_secret: token.tokenSecret }); T.post('statuses/update', { status: req.body.tweet }, function (err, data, response) { if (err) { return next(err); } req.flash('success', { msg: 'Tweet has been posted.' }); res.redirect('/api/twitter'); }); }); /** * OAuth routes for API examples that require authorization. */ app.get('/auth/foursquare', passport.authorize('foursquare')); app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), function (req, res) { res.redirect('/api/foursquare'); }); app.get('/auth/tumblr', passport.authorize('tumblr')); app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function (req, res) { res.redirect('/api/tumblr'); }); };
justyn-clark/mylockedemo
controllers/api.js
JavaScript
mit
15,388
range.collapse(true); // collapse to the starting point console.log(range.collapsed); // outputs "true"
msfrisbie/pjwd-src
Chapter16DOMLevels2And3/Ranges/CollapsingADOMRange/CollapsingADOMRangeExample01.js
JavaScript
mit
108