commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
e019d9c26f2be9d571016a9c606c3635437af323
scripts/init-db.js
scripts/init-db.js
/** * Generate the dbtables * and generate a user with a post * * username = batman * password = robin */ const path = require('path') require('dotenv').load({ path: path.resolve(__dirname, '../../', '.env') }); const bcrypt = require('bcryptjs') const fs = require('fs-promise') const mysql = require('mysql') const redisClient = require('../lib/redis'); /** * DB */ const db = mysql.createPool({ socketPath: process.env.MYSQL_SOCK || null, host: process.env.MYSQL_HOST || 'localhost', user: 'root', password: process.env.MYSQL_ROOT_PASSWORD || 'patrik', database: process.env.MYSQL_DB || 'chamsocial', port: process.env.MYSQL_PORT || 3306, multipleStatements: true, charset: 'utf8mb4' }); function query (sql, prepared = []) { return new Promise(function(resolve, reject) { db.query(sql, prepared, (err, data) => (err ? reject(err) : resolve(data))) }) } function insert (sql, prepared) { return query(sql, prepared).then(data => data.insertId) } /** * Data */ function user () { return { username: 'Batman', email: 'batman@example.com', email_domain: 'example.com', password: bcrypt.hashSync('robin', 8), first_name: 'Bruce', last_name: 'Nanananananana...', company_name: 'Chamsocial', slug: 'batman', interests: '', aboutme: '', lang: 'en', activated: 1 } } function post ({ userId, groupId }) { return { user_id: userId, status: 'published', slug: 'ou-est-alfred', group_id: userId, title: 'Where is Alfred?', content: 'Is he hiding in the batcave?', } } async function createGroup() { const groupId = await insert('INSERT INTO groups SET ?', [{ slug: 'chamshare' }]) const group = { group_id: groupId, title: 'ChamShare', description: 'General mix of content', lang: 'en' } await insert('INSERT INTO groups_content SET ?', [group]) return groupId } /** * The main script */ async function init () { const sql = await fs.readFile('chamsocial-schema.sql', 'utf8') await query(sql) const userId = await insert('INSERT INTO users SET ?', [user()]) const groupId = await createGroup() const postId = await insert('INSERT INTO posts SET ?', [post({userId, groupId})]) return ':)' } init() .then(() => { console.log('yes') redisClient.delWildcard('posts:*', () => {}) redisClient.quit() db.end() }) .catch(e => { console.log(e) db.end() })
Write a script to setup db and a test user & post
Write a script to setup db and a test user & post
JavaScript
mit
chamsocial/Chamsocial,chamsocial/Chamsocial,chamsocial/Chamsocial
--- +++ @@ -0,0 +1,107 @@ +/** + * Generate the dbtables + * and generate a user with a post + * + * username = batman + * password = robin + */ +const path = require('path') +require('dotenv').load({ path: path.resolve(__dirname, '../../', '.env') }); +const bcrypt = require('bcryptjs') +const fs = require('fs-promise') +const mysql = require('mysql') +const redisClient = require('../lib/redis'); + +/** + * DB + */ +const db = mysql.createPool({ + socketPath: process.env.MYSQL_SOCK || null, + host: process.env.MYSQL_HOST || 'localhost', + user: 'root', + password: process.env.MYSQL_ROOT_PASSWORD || 'patrik', + database: process.env.MYSQL_DB || 'chamsocial', + port: process.env.MYSQL_PORT || 3306, + multipleStatements: true, + charset: 'utf8mb4' +}); + +function query (sql, prepared = []) { + return new Promise(function(resolve, reject) { + db.query(sql, prepared, (err, data) => (err ? reject(err) : resolve(data))) + }) +} + +function insert (sql, prepared) { + return query(sql, prepared).then(data => data.insertId) +} + +/** + * Data + */ + +function user () { + return { + username: 'Batman', + email: 'batman@example.com', + email_domain: 'example.com', + password: bcrypt.hashSync('robin', 8), + first_name: 'Bruce', + last_name: 'Nanananananana...', + company_name: 'Chamsocial', + slug: 'batman', + interests: '', + aboutme: '', + lang: 'en', + activated: 1 + } +} + +function post ({ userId, groupId }) { + return { + user_id: userId, + status: 'published', + slug: 'ou-est-alfred', + group_id: userId, + title: 'Where is Alfred?', + content: 'Is he hiding in the batcave?', + } +} + +async function createGroup() { + const groupId = await insert('INSERT INTO groups SET ?', [{ slug: 'chamshare' }]) + const group = { + group_id: groupId, + title: 'ChamShare', + description: 'General mix of content', + lang: 'en' + } + await insert('INSERT INTO groups_content SET ?', [group]) + return groupId +} + +/** + * The main script + */ + +async function init () { + const sql = await fs.readFile('chamsocial-schema.sql', 'utf8') + await query(sql) + + const userId = await insert('INSERT INTO users SET ?', [user()]) + const groupId = await createGroup() + const postId = await insert('INSERT INTO posts SET ?', [post({userId, groupId})]) + return ':)' +} + +init() + .then(() => { + console.log('yes') + redisClient.delWildcard('posts:*', () => {}) + redisClient.quit() + db.end() + }) + .catch(e => { + console.log(e) + db.end() + })
ea8d07da420713a6adc1c3ac50402e9adbc6a88c
test/fitness-scoring.js
test/fitness-scoring.js
const {scoreScenario, boilDownIndividualScore} = require('../app/fitness-scoring.js'); const assert = require('assert'); describe('scoreScenario', () => { it('assigns fitness scores for individuals', () => { const scenario = { id: 1, participants: ['Nick'], initialPositions: { Nick: {x: 0, y: 0} }, expectedPositions: { Nick: [ { frame: 10, x: 100, y: 0 } ] } }; const fitnesses = { Nick: {} }; const individual = [ (entity, api) => api.setVelocity(entity, {x: 10, y: 0}) ]; const individuals = { Nick: [individual] }; scoreScenario(scenario, fitnesses, individuals); assert.equal(fitnesses.Nick[individual][scenario.id].length, 1); assert.equal(typeof fitnesses.Nick[individual][scenario.id].length, 'number'); }); it('has a bug lol', () => { const scenario = { id: 1, participants: ['Nick'], initialPositions: { Nick: {x: 0, y: 0} }, expectedPositions: { Nick: [ { frame: 10, x: 100, y: 0 } ] } }; const fitnesses = { Nick: {} }; function makeVelocityGene (velocity) { return (entity, api) => api.setVelocity(entity, velocity); } const individual = [ makeVelocityGene({x: 10, y: 0}) ]; const individual2 = [ makeVelocityGene({x: -10, y: 0}) ]; const individuals = { Nick: [individual, individual2] }; scoreScenario(scenario, fitnesses, individuals); assert( fitnesses.Nick[individual][scenario.id][0] !== fitnesses.Nick[individual2][scenario.id][0], `Both individuals had a fitness of ${fitnesses.Nick[individual2][scenario.id][0]}` ); }); });
Add tests for fitness behaviour and bug
Add tests for fitness behaviour and bug
JavaScript
mit
helix-pi/helix-pi,Widdershin/helix-pi,helix-pi/helix-pi,Widdershin/helix-pi
--- +++ @@ -0,0 +1,93 @@ +const {scoreScenario, boilDownIndividualScore} = require('../app/fitness-scoring.js'); + +const assert = require('assert'); + +describe('scoreScenario', () => { + it('assigns fitness scores for individuals', () => { + const scenario = { + id: 1, + participants: ['Nick'], + + initialPositions: { + Nick: {x: 0, y: 0} + }, + + expectedPositions: { + Nick: [ + { + frame: 10, + x: 100, + y: 0 + } + ] + } + }; + + const fitnesses = { + Nick: {} + }; + + const individual = [ + (entity, api) => api.setVelocity(entity, {x: 10, y: 0}) + ]; + + const individuals = { + Nick: [individual] + }; + + scoreScenario(scenario, fitnesses, individuals); + + assert.equal(fitnesses.Nick[individual][scenario.id].length, 1); + assert.equal(typeof fitnesses.Nick[individual][scenario.id].length, 'number'); + }); + + it('has a bug lol', () => { + const scenario = { + id: 1, + participants: ['Nick'], + + initialPositions: { + Nick: {x: 0, y: 0} + }, + + expectedPositions: { + Nick: [ + { + frame: 10, + x: 100, + y: 0 + } + ] + } + }; + + const fitnesses = { + Nick: {} + }; + + function makeVelocityGene (velocity) { + return (entity, api) => api.setVelocity(entity, velocity); + } + + const individual = [ + makeVelocityGene({x: 10, y: 0}) + ]; + + const individual2 = [ + makeVelocityGene({x: -10, y: 0}) + ]; + + const individuals = { + Nick: [individual, individual2] + }; + + scoreScenario(scenario, fitnesses, individuals); + + assert( + fitnesses.Nick[individual][scenario.id][0] !== + fitnesses.Nick[individual2][scenario.id][0], + `Both individuals had a fitness of ${fitnesses.Nick[individual2][scenario.id][0]}` + ); + }); +}); +
68f52baec830b28259d5d486b3dcf892e51285d3
server.js
server.js
var dgram = require("dgram"); var socket = dgram.createSocket("udp4"); socket.on("error", function (err) { console.log("server error:\n" + err.stack); socket.close(); }); socket.on("message", function (msg, rinfo) { var jsonObj = { message: msg.toString('utf8').replace(/\r?\n|\r/g, " "), tags: ['sawyer'], sawyer_log_source: rinfo.address }; console.log(JSON.stringify(jsonObj)); }); socket.on("listening", function () { var address = socket.address(); console.log("server listening " + address.address + ":" + address.port); }); socket.bind(6370);
Read syslog data and outputs to console as JSON
Read syslog data and outputs to console as JSON
JavaScript
bsd-3-clause
genebean/sawyer
--- +++ @@ -0,0 +1,21 @@ +var dgram = require("dgram"); + +var socket = dgram.createSocket("udp4"); + +socket.on("error", function (err) { + console.log("server error:\n" + err.stack); + socket.close(); +}); + +socket.on("message", function (msg, rinfo) { + var jsonObj = { message: msg.toString('utf8').replace(/\r?\n|\r/g, " "), tags: ['sawyer'], sawyer_log_source: rinfo.address }; + console.log(JSON.stringify(jsonObj)); +}); + +socket.on("listening", function () { + var address = socket.address(); + console.log("server listening " + + address.address + ":" + address.port); +}); + +socket.bind(6370);
fbe55dba68fb2542fd12e4daf5bd1203d356bb5c
lib/util/hook.js
lib/util/hook.js
/** * This is our "Hook" class that allows a script to hook into the lifecyle of the * "configure", "build" and "clean" commands. It's basically a hack into the * module.js file to allow custom hooks into the module-space, specifically to * make the global scope act as an EventEmitter. */ var fs = require('fs') , path = require('path') , Module = require('module') , EventEmitter = require('events').EventEmitter , functions = Object.keys(EventEmitter.prototype).filter(function (k) { return typeof EventEmitter.prototype[k] == 'function' }) , boilerplate = functions.map(function (k) { return 'var ' + k + ' = module.emitter.' + k + '.bind(module.emitter);' }).join('') module.exports = createHook function createHook (filename, callback) { var emitter = new EventEmitter // first read the file contents fs.readFile(filename, 'utf8', function (err, code) { if (err) { if (err.code == 'ENOENT') { // hook file doesn't exist, oh well callback(null, emitter) } else { callback(err) } return } // got a hook file, now execute it var mod = new Module(filename) mod.filename = filename mod.emitter = emitter try { mod._compile(boilerplate + code, filename) } catch (e) { return callback(e) } callback(null, emitter) }) }
Add the 'createHook()' function. Rather hacky but oh well...
Add the 'createHook()' function. Rather hacky but oh well...
JavaScript
mit
maghoff/node-gyp,spacelis/node-gyp,spacelis/node-gyp,maghoff/node-gyp,tepez/node-gyp,pombredanne/pangyp,saper/node-gyp,yorkie/node-gyp,justinmchase/node-gyp,overra/node-gyp,MiniGod/nw-gyp,implausible/pangyp,CodeJockey/node-ninja,rvagg/pangyp,watonyweng/node-gyp,atiti/pangyp,nodegit/node-gyp,jqk6/node-gyp,fengmk2/node-gyp,svr93/node-gyp,tempbottle/node-gyp,Karnith/node-gyp,iarna/node-gyp,vany-egorov/node-gyp,pombredanne/pangyp,TooTallNate/node-gyp,othiym23/node-gyp,pombredanne/pangyp,ZECTBynmo/notnode-gyp,trentm/node-gyp,kefo/node-gyp,nodegit/node-gyp,Karnith/node-gyp,icosahedron/node-gyp,robertkowalski/node-gyp,TooTallNate/node-gyp,glensc/node-gyp,MiniGod/nw-gyp,svr93/node-gyp,aredridel/node-gyp,jsdevel/node-gyp,adamtegen/node-gyp,ZECTBynmo/notnode-gyp,ebaskoro/node-gyp,aredridel/node-gyp,camsong/node-gyp,Glavin001/node-gyp,atiti/pangyp,jfhenriques/node-gyp,getwe/node-gyp,mcanthony/node-gyp,iam-TJ/node-gyp,prantlf/node-gyp,tempbottle/node-gyp,SonicHedgehog/node-gyp,justinmchase/node-gyp,ebaskoro/node-gyp,abougouffa/node-gyp,overra/node-gyp,watonyweng/node-gyp,glosee/node-gyp,Glavin001/node-gyp,atiti/pangyp,pmq20/node-gyp,JayBeavers/node-gyp,isaacs/node-gyp,getwe/node-gyp,robertkowalski/node-gyp,mmalecki/node-gyp,mcanthony/node-gyp,nodegit/node-gyp,TooTallNate/node-gyp,implausible/pangyp,beatle/node-gyp,CodeJockey/node-ninja,bobrik/node-gyp,nwjs/nw-gyp,ebaskoro/node-gyp,hitsthings/node-gyp,jsdevel/node-gyp,richardcypher/node-gyp,kkragenbrink/node-gyp,caruccio/node-gyp,iam-TJ/node-gyp,mscdex/node-gyp,overra/node-gyp,prantlf/node-gyp,pombredanne/pangyp,justinmchase/node-gyp,mmalecki/node-gyp,svr93/node-gyp,caruccio/node-gyp,tempbottle/node-gyp,CWHopkins/node-gyp,node-migrator-bot/node-gyp,samccone/node-gyp,richardcypher/node-gyp,JacksonTian/node-gyp,justinmchase/node-gyp,yorkie/node-gyp,litmit/node-gyp,kapouer/node-gyp,vany-egorov/node-gyp,kkragenbrink/node-gyp,aredridel/pangyp,iWuzHere/node-gyp,samccone/node-gyp,mmalecki/node-gyp,bnoordhuis/node-gyp,JayBeavers/node-gyp,iam-TJ/node-gyp,camsong/node-gyp,tmpvar/tmpvar-pangyp,othiym23/node-gyp,litmit/node-gyp,fredericosilva/node-gyp,iarna/node-gyp,caruccio/node-gyp,ZECTBynmo/notnode-gyp,malixsys/node-gyp,davidbkemp/node-gyp,jholloman/node-gyp,purplecode/node-gyp,jsdevel/node-gyp,MiniGod/nw-gyp,nishant8BITS/node-gyp,yorkie/node-gyp,svr93/node-gyp,icosahedron/node-gyp,MiniGod/nw-gyp,othiym23/node-gyp,isaacs/node-gyp,camsong/node-gyp,abrkn/node-gyp,spacelis/node-gyp,litmit/node-gyp,samccone/node-gyp,richardcypher/node-gyp,watonyweng/node-gyp,davidbkemp/node-gyp,watonyweng/node-gyp,jholloman/node-gyp,SonicHedgehog/node-gyp,SonicHedgehog/node-gyp,saper/node-gyp,getwe/node-gyp,kkragenbrink/node-gyp,rvagg/pangyp,robertkowalski/node-gyp,refack/node-gyp,kkragenbrink/node-gyp,tepez/node-gyp,Fishrock123/node-gyp,mcanthony/node-gyp,caruccio/node-gyp,pmq20/node-gyp,richardcypher/node-gyp,iWuzHere/node-gyp,glosee/node-gyp,fredericosilva/node-gyp,nishant8BITS/node-gyp,richardcypher/node-gyp,jfhenriques/node-gyp,Glavin001/node-gyp,JacksonTian/node-gyp,zikifer/node-gyp,abrkn/node-gyp,jholloman/node-gyp,iam-TJ/node-gyp,pmq20/node-gyp,getwe/node-gyp,nodejs/node-gyp,isaacs/node-gyp,samccone/node-gyp,hitsthings/node-gyp,implausible/pangyp,prantlf/node-gyp,Karnith/node-gyp,jqk6/node-gyp,msabramo/node-gyp,justinmchase/node-gyp,vany-egorov/node-gyp,SonicHedgehog/node-gyp,prantlf/node-gyp,CWHopkins/node-gyp,CodeJockey/node-ninja,nwjs/nw-gyp,purplecode/node-gyp,jsdevel/node-gyp,fredericosilva/node-gyp,implausible/pangyp,fredericosilva/node-gyp,caruccio/node-gyp,samccone/node-gyp,aredridel/pangyp,nodejs/node-gyp,CWHopkins/node-gyp,aredridel/node-gyp,beatle/node-gyp,refack/node-gyp,kapouer/node-gyp,hitsthings/node-gyp,msabramo/node-gyp,saper/node-gyp,kevinsawicki/node-gyp,abougouffa/node-gyp,refack/node-gyp,isaacs/node-gyp,isaacs/node-gyp,othiym23/node-gyp,bnoordhuis/node-gyp,pombredanne/pangyp,TooTallNate/node-gyp,nishant8BITS/node-gyp,yorkie/node-gyp,nwjs/nw-gyp,prantlf/node-gyp,Karnith/node-gyp,iarna/node-gyp,spacelis/node-gyp,iarna/node-gyp,d3m3vilurr/node-gyp,fengmk2/node-gyp,davidbkemp/node-gyp,trentm/node-gyp,purplecode/node-gyp,icosahedron/node-gyp,bnoordhuis/node-gyp,othiym23/node-gyp,watonyweng/node-gyp,davidbkemp/node-gyp,rvagg/pangyp,msabramo/node-gyp,tepez/node-gyp,iWuzHere/node-gyp,d3m3vilurr/node-gyp,atiti/pangyp,beatle/node-gyp,maghoff/node-gyp,nwjs/nw-gyp,JacksonTian/node-gyp,fredericosilva/node-gyp,Fishrock123/node-gyp,maghoff/node-gyp,ebaskoro/node-gyp,aredridel/node-gyp,kapouer/node-gyp,glensc/node-gyp,node-migrator-bot/node-gyp,iarna/node-gyp,icosahedron/node-gyp,fengmk2/node-gyp,litmit/node-gyp,CodeJockey/node-ninja,implausible/pangyp,bobrik/node-gyp,nodegit/node-gyp,robertkowalski/node-gyp,CWHopkins/node-gyp,nodejs/node-gyp,Karnith/node-gyp,CodeJockey/node-ninja,JacksonTian/node-gyp,kevinsawicki/node-gyp,getwe/node-gyp,kevinsawicki/node-gyp,kapouer/node-gyp,tempbottle/node-gyp,JayBeavers/node-gyp,aredridel/pangyp,kefo/node-gyp,tepez/node-gyp,refack/node-gyp,pmq20/node-gyp,TooTallNate/node-gyp,mscdex/node-gyp,spacelis/node-gyp,zikifer/node-gyp,abougouffa/node-gyp,overra/node-gyp,nodejs/node-gyp,node-migrator-bot/node-gyp,nishant8BITS/node-gyp,CWHopkins/node-gyp,kefo/node-gyp,treygriffith/node-gyp,kevinsawicki/node-gyp,malixsys/node-gyp,JacksonTian/node-gyp,malixsys/node-gyp,glensc/node-gyp,trentm/node-gyp,nwjs/nw-gyp,nishant8BITS/node-gyp,Fishrock123/node-gyp,beatle/node-gyp,atiti/pangyp,iWuzHere/node-gyp,aredridel/pangyp,ZECTBynmo/notnode-gyp,jqk6/node-gyp,mcanthony/node-gyp,d3m3vilurr/node-gyp,bnoordhuis/node-gyp,ZECTBynmo/notnode-gyp,robertkowalski/node-gyp,bobrik/node-gyp,tempbottle/node-gyp,fengmk2/node-gyp,kefo/node-gyp,jfhenriques/node-gyp,jsdevel/node-gyp,fengmk2/node-gyp,glosee/node-gyp,node-migrator-bot/node-gyp,treygriffith/node-gyp,glensc/node-gyp,glosee/node-gyp,jholloman/node-gyp,Glavin001/node-gyp,maghoff/node-gyp,tmpvar/tmpvar-pangyp,kefo/node-gyp,tmpvar/tmpvar-pangyp,overra/node-gyp,litmit/node-gyp,davidbkemp/node-gyp,purplecode/node-gyp,abougouffa/node-gyp,hitsthings/node-gyp,ebaskoro/node-gyp,treygriffith/node-gyp,jqk6/node-gyp,hitsthings/node-gyp,purplecode/node-gyp,yorkie/node-gyp,MiniGod/nw-gyp,jfhenriques/node-gyp,Fishrock123/node-gyp,trentm/node-gyp,beatle/node-gyp,jholloman/node-gyp,msabramo/node-gyp,tmpvar/tmpvar-pangyp,refack/node-gyp,zikifer/node-gyp,camsong/node-gyp,saper/node-gyp,camsong/node-gyp,kapouer/node-gyp,rvagg/pangyp,SonicHedgehog/node-gyp,abrkn/node-gyp,glosee/node-gyp,aredridel/pangyp,abougouffa/node-gyp,malixsys/node-gyp,aredridel/node-gyp,saper/node-gyp,trentm/node-gyp,kkragenbrink/node-gyp,glensc/node-gyp,vany-egorov/node-gyp,mmalecki/node-gyp,kevinsawicki/node-gyp,iam-TJ/node-gyp,icosahedron/node-gyp,iWuzHere/node-gyp,Glavin001/node-gyp,bnoordhuis/node-gyp,nodejs/node-gyp,tepez/node-gyp,rvagg/pangyp,mcanthony/node-gyp,nodegit/node-gyp,JayBeavers/node-gyp,adamtegen/node-gyp,JayBeavers/node-gyp,mmalecki/node-gyp,jfhenriques/node-gyp,treygriffith/node-gyp,bobrik/node-gyp,jqk6/node-gyp,svr93/node-gyp,pmq20/node-gyp,adamtegen/node-gyp,tmpvar/tmpvar-pangyp,mscdex/node-gyp,mscdex/node-gyp
--- +++ @@ -0,0 +1,47 @@ + +/** + * This is our "Hook" class that allows a script to hook into the lifecyle of the + * "configure", "build" and "clean" commands. It's basically a hack into the + * module.js file to allow custom hooks into the module-space, specifically to + * make the global scope act as an EventEmitter. + */ + +var fs = require('fs') + , path = require('path') + , Module = require('module') + , EventEmitter = require('events').EventEmitter + , functions = Object.keys(EventEmitter.prototype).filter(function (k) { + return typeof EventEmitter.prototype[k] == 'function' + }) + , boilerplate = functions.map(function (k) { + return 'var ' + k + ' = module.emitter.' + k + '.bind(module.emitter);' + }).join('') + +module.exports = createHook +function createHook (filename, callback) { + + var emitter = new EventEmitter + + // first read the file contents + fs.readFile(filename, 'utf8', function (err, code) { + if (err) { + if (err.code == 'ENOENT') { + // hook file doesn't exist, oh well + callback(null, emitter) + } else { + callback(err) + } + return + } + // got a hook file, now execute it + var mod = new Module(filename) + mod.filename = filename + mod.emitter = emitter + try { + mod._compile(boilerplate + code, filename) + } catch (e) { + return callback(e) + } + callback(null, emitter) + }) +}
56b7877f251fdd0b9cd53dfa6d0d19f9fd6b7d8f
tests/ids/add_ids.js
tests/ids/add_ids.js
/* bender-tags: editor,unit */ /* bender-ckeditor-plugins: autoid */ 'use strict'; bender.editor = { config: { enterMode: CKEDITOR.ENTER_P } }; bender.test({ setUp: function() { this.editor = this.editorBot.editor; }, 'test it can add a unique id to a heading': function() { var bot = this.editorBot, heading, startHtml = '<h1>This is a heading</h1>'; bot.setHtmlWithSelection(startHtml); heading = this.editor.editable().findOne('h1'); assert.isTrue(heading.hasAttribute('id')); }, 'test it does not change the id of a heading that already has one': function() { var bot = this.editorBot, heading, startHtml = '<h1 id="12345">Heading with id</h1>'; bot.setHtmlWithSelection(startHtml); heading = this.editor.editable().findOne('h1'); assert.isEqual(heading.getId(), '12345'); } });
Add start of tests for checking that plugin adds ids correctly on initial load
Add start of tests for checking that plugin adds ids correctly on initial load
JavaScript
mit
PolicyStat/ckeditor-plugin-autoid-headings,PolicyStat/ckeditor-plugin-autoid-headings
--- +++ @@ -0,0 +1,40 @@ +/* bender-tags: editor,unit */ +/* bender-ckeditor-plugins: autoid */ + +'use strict'; + +bender.editor = { + config: { + enterMode: CKEDITOR.ENTER_P + } +}; + +bender.test({ + setUp: function() { + this.editor = this.editorBot.editor; + }, + + 'test it can add a unique id to a heading': function() { + var bot = this.editorBot, + heading, + startHtml = '<h1>This is a heading</h1>'; + + bot.setHtmlWithSelection(startHtml); + + heading = this.editor.editable().findOne('h1'); + + assert.isTrue(heading.hasAttribute('id')); + }, + + 'test it does not change the id of a heading that already has one': function() { + var bot = this.editorBot, + heading, + startHtml = '<h1 id="12345">Heading with id</h1>'; + + bot.setHtmlWithSelection(startHtml); + + heading = this.editor.editable().findOne('h1'); + + assert.isEqual(heading.getId(), '12345'); + } +});
9b7b663c33e9dea0e21ac778712f4dfa8f507883
sandbox/sangmee.js
sandbox/sangmee.js
function deleteDestination(place) { function placeToDelete(){ return place; }; // delete user's destination // NEED TO REPLACE USERNAME WITH CURRENT USER UID usersRef.child('sangmee/destinations').orderByKey().on('child_added', function(snapshot){ snapshot.forEach(function(destination){ if(destination.key() == placeToDelete()){ var snapshotKey = snapshot.key(); var removeRef = usersRef.child("sangmee/destinations/"+snapshotKey+"/"+placeToDelete()); removeRef.remove(); }; }); }); // delete destination's user // NEED TO REPLACE USERNAME WITH CURRENT USER UID destinationsRef.orderByKey().equalTo(placeToDelete()).on('child_added', function(snapshot){ var removeRef = destinationsRef.child(placeToDelete()+"/users/sangmee") removeRef.remove(); }); };
Add method to delete users destination
Add method to delete users destination
JavaScript
mit
okjill/scout,okjill/scout,okjill/scout,okjill/scout
--- +++ @@ -0,0 +1,29 @@ +function deleteDestination(place) { + function placeToDelete(){ + return place; + }; + +// delete user's destination +// NEED TO REPLACE USERNAME WITH CURRENT USER UID + usersRef.child('sangmee/destinations').orderByKey().on('child_added', function(snapshot){ + + snapshot.forEach(function(destination){ + if(destination.key() == placeToDelete()){ + var snapshotKey = snapshot.key(); + var removeRef = usersRef.child("sangmee/destinations/"+snapshotKey+"/"+placeToDelete()); + removeRef.remove(); + }; + }); + }); + +// delete destination's user +// NEED TO REPLACE USERNAME WITH CURRENT USER UID +destinationsRef.orderByKey().equalTo(placeToDelete()).on('child_added', function(snapshot){ + var removeRef = destinationsRef.child(placeToDelete()+"/users/sangmee") + removeRef.remove(); + }); +}; + + + +
ce34ddf2c1dc99050e669f24f6f35794bbe956a0
lib/datapacktypes/product2.js
lib/datapacktypes/product2.js
var Product2 = module.exports = function(vlocity) { this.vlocity = vlocity; }; Product2.prototype.childrenExport = async function(inputMap) { try { var jobInfo = inputMap.jobInfo; var childrenDataPacks = inputMap.childrenDataPacks; var dataPackType = childrenDataPacks[0].VlocityDataPackType; let queryString = `Select Id from Product2 WHERE `; let whereClause = ''; for (var dataPack of childrenDataPacks) { if (whereClause) { whereClause += ' OR '; } whereClause += `(${this.vlocity.namespacePrefix}GlobalGroupKey__c = '${dataPack.VlocityDataPackData.Id}')`; } let result = await this.vlocity.queryservice.query(queryString + whereClause); VlocityUtils.verbose('Children Query', queryString + whereClause, 'Results', result.records.length); for (var record of result.records) { let recordAdded = this.vlocity.datapacksjob.addRecordToExport(jobInfo, { VlocityDataPackType: dataPackType, manifestOnly: true }, record); if (recordAdded) { VlocityUtils.verbose('Added from Children Query', dataPackType, record.Id); } } for (var dataPack of childrenDataPacks) { jobInfo.currentStatus[dataPack.VlocityDataPackKey] = 'Ignored'; if (jobInfo.alreadyExportedKeys.indexOf(dataPack.VlocityDataPackKey) == -1) { jobInfo.alreadyExportedKeys.push(dataPack.VlocityDataPackKey); } } return true; } catch (e) { VlocityUtils.error('Children Export Error', e); return null; } }
Update to have Children for Product2 run in JavaScript
Update to have Children for Product2 run in JavaScript
JavaScript
mit
vlocityinc/vlocity_build,vlocityinc/vlocity_build,vlocityinc/vlocity_build
--- +++ @@ -0,0 +1,46 @@ +var Product2 = module.exports = function(vlocity) { + this.vlocity = vlocity; +}; + +Product2.prototype.childrenExport = async function(inputMap) { + try { + var jobInfo = inputMap.jobInfo; + var childrenDataPacks = inputMap.childrenDataPacks; + + var dataPackType = childrenDataPacks[0].VlocityDataPackType; + + let queryString = `Select Id from Product2 WHERE `; + let whereClause = ''; + + for (var dataPack of childrenDataPacks) { + + if (whereClause) { + whereClause += ' OR '; + } + + whereClause += `(${this.vlocity.namespacePrefix}GlobalGroupKey__c = '${dataPack.VlocityDataPackData.Id}')`; + } + + let result = await this.vlocity.queryservice.query(queryString + whereClause); + VlocityUtils.verbose('Children Query', queryString + whereClause, 'Results', result.records.length); + for (var record of result.records) { + let recordAdded = this.vlocity.datapacksjob.addRecordToExport(jobInfo, { VlocityDataPackType: dataPackType, manifestOnly: true }, record); + + if (recordAdded) { + VlocityUtils.verbose('Added from Children Query', dataPackType, record.Id); + } + } + + for (var dataPack of childrenDataPacks) { + jobInfo.currentStatus[dataPack.VlocityDataPackKey] = 'Ignored'; + if (jobInfo.alreadyExportedKeys.indexOf(dataPack.VlocityDataPackKey) == -1) { + jobInfo.alreadyExportedKeys.push(dataPack.VlocityDataPackKey); + } + } + + return true; + } catch (e) { + VlocityUtils.error('Children Export Error', e); + return null; + } +}
987f8fb93621526c42b7866af816f01b6d7fced4
lib/mongoskin/gridfs.js
lib/mongoskin/gridfs.js
var GridStore = require('mongodb').GridStore; /** * @param filename: filename or ObjectId */ var SkinGridStore = exports.SkinGridStore = function(skinDb) { this.skinDb = skinDb; } /** * @param filename: filename or ObjectId * callback(err, gridStoreObject) */ SkinGridStore.prototype.open = function(filename, mode, options, callback){ if(!callback){ callback = options; options = undefined; } this.skinDb.open(function(err, db) { new GridStore(db, filename, mode, options).open(callback); }); } /** * @param filename: filename or ObjectId */ SkinGridStore.prototype.unlink = SkinGridStore.prototype.remove = function(filename, callback){ this.skinDb.open(function(err, db) { GridStore.unlink(db, filename, callback); }); } SkinGridStore.prototype.exist = function(filename, rootCollection, callback){ this.skinDb.open(function(err, db) { GridStore.exist(db, filename, rootCollection, callback); }); } exports.SkinGridStore = SkinGridStore;
var GridStore = require('mongodb').GridStore; /** * @param filename: filename or ObjectId */ var SkinGridStore = exports.SkinGridStore = function(skinDb) { this.skinDb = skinDb; } /** * @param filename: filename or ObjectId * callback(err, gridStoreObject) */ SkinGridStore.prototype.open = function(id, filename, mode, options, callback){ if(!callback){ callback = options; options = undefined; } this.skinDb.open(function(err, db) { new GridStore(db, id, filename, mode, options).open(callback); }); } /** * @param filename: filename or ObjectId */ SkinGridStore.prototype.unlink = SkinGridStore.prototype.remove = function(filename, callback){ this.skinDb.open(function(err, db) { GridStore.unlink(db, filename, callback); }); } SkinGridStore.prototype.exist = function(filename, rootCollection, callback){ this.skinDb.open(function(err, db) { GridStore.exist(db, filename, rootCollection, callback); }); } exports.SkinGridStore = SkinGridStore;
Allow opening a file by id and name
Allow opening a file by id and name
JavaScript
mit
kissjs/node-mongoskin,microlv/node-mongoskin,mleanos/node-mongoskin,dropfen/node-mongoskin
--- +++ @@ -11,13 +11,13 @@ * @param filename: filename or ObjectId * callback(err, gridStoreObject) */ -SkinGridStore.prototype.open = function(filename, mode, options, callback){ +SkinGridStore.prototype.open = function(id, filename, mode, options, callback){ if(!callback){ callback = options; options = undefined; } this.skinDb.open(function(err, db) { - new GridStore(db, filename, mode, options).open(callback); + new GridStore(db, id, filename, mode, options).open(callback); }); }
93e2ebe6e77256e9102019350f0969ee3470e813
src/doc_injector.js
src/doc_injector.js
var DocInjector = { init: function() { var that = this; $.each(this.data, function(i, docReference) { that.inject(docReference) }); }, data: [{ "api_url": "http://developer.github.com/v3/meta/#meta", "method_name":"meta" }], inject: function(docReference) { var anchor = docReference.api_url.split("#"); if(window.location.href !== anchor[0]) return; var html = '<div><code>Octokit.rb: <a href="#" target="_blank">Octokit#' + docReference.method_name + '</a></code></div>'; $('#' + anchor[1]).after(html); } }; $().ready(function() { DocInjector.init(); });
Add initial API docs js injector
Add initial API docs js injector
JavaScript
mit
joeyw/octodoctotron,joeyw/octodoctotron,joeyw/octodoctotron
--- +++ @@ -0,0 +1,20 @@ +var DocInjector = { + init: function() { + var that = this; + $.each(this.data, function(i, docReference) { + that.inject(docReference) + }); + }, + data: [{ + "api_url": "http://developer.github.com/v3/meta/#meta", + "method_name":"meta" + }], + inject: function(docReference) { + var anchor = docReference.api_url.split("#"); + if(window.location.href !== anchor[0]) return; + var html = '<div><code>Octokit.rb: <a href="#" target="_blank">Octokit#' + docReference.method_name + '</a></code></div>'; + $('#' + anchor[1]).after(html); + } +}; + +$().ready(function() { DocInjector.init(); });
84c329ce0406b08649bb2c667e5b0e3f4c3e1132
lib/util/TradingPair.js
lib/util/TradingPair.js
/* * * poloniex-unofficial * https://git.io/polonode * * Yet another unofficial Node.js wrapper for the Poloniex cryptocurrency * exchange APIs. * * Copyright (c) 2016 Tyler Filla * * This software may be modified and distributed under the terms of the MIT * license. See the LICENSE file for details. * */ /* * Trading pair utility constructor. */ function TradingPair(baseOrPairString, quote) { this._base = null; this._quote = null; if (typeof quote !== "undefined") { this._base = baseOrPairString; this._quote = quote; } else { this.setPairString(baseOrPairString); } } /* * * function getBase() * * Get the base currency of this trading pair. * */ TradingPair.prototype.getBase = function() { return this._base; }; /* * * function setBase(base) * * Set the base currency of this trading pair. * */ TradingPair.prototype.setBase = function(base) { this._base = base; }; /* * * function getQuote() * * Get the quote currency of this trading pair. * */ TradingPair.prototype.getQuote = function() { return this._quote; }; /* * * function setQuote(quote) * * Set the quote currency of this trading pair. * */ TradingPair.prototype.setQuote = function(quote) { this._quote = quote; }; /* * * function swap() * * Swap the base and quote currencies of this trading pair. * */ TradingPair.prototype.swap = function() { // Localize currencies var base = this._base; var quote = this._quote; // Swap currencies this._base = quote; this._quote = base; }; /* * * function getPairString() * * Get the currencies of this trading pair as a Poloniex pair string (e.g. * "BTC_ETH") * */ TradingPair.prototype.getPairString = function() { return this._base + "_" + this._quote; }; /* * * function setPairString(pairString) * * Set the currencies of this trading pair as a Poloniex pair string (e.g. * "BTC_ETH") * */ TradingPair.prototype.setPairString = function(pairString) { // Validate pair string if (!pairString || pairString.length < 3 || pairString.indexOf("_") == -1) { throw "Invalid Poloniex pair string"; } // Split the pair string var pairStringSplit = pairString.split("_", 1); // Extract components of pair string this._base = pairStringSplit[0]; this._quote = pairStringSplit[1]; };
Implement basic representation of a trading pair
Implement basic representation of a trading pair
JavaScript
mit
tylerfilla/node-poloniex-unofficial
--- +++ @@ -0,0 +1,125 @@ + +/* + * + * poloniex-unofficial + * https://git.io/polonode + * + * Yet another unofficial Node.js wrapper for the Poloniex cryptocurrency + * exchange APIs. + * + * Copyright (c) 2016 Tyler Filla + * + * This software may be modified and distributed under the terms of the MIT + * license. See the LICENSE file for details. + * + */ + +/* + * Trading pair utility constructor. + */ +function TradingPair(baseOrPairString, quote) { + this._base = null; + this._quote = null; + + if (typeof quote !== "undefined") { + this._base = baseOrPairString; + this._quote = quote; + } else { + this.setPairString(baseOrPairString); + } +} + +/* + * + * function getBase() + * + * Get the base currency of this trading pair. + * + */ +TradingPair.prototype.getBase = function() { + return this._base; +}; + +/* + * + * function setBase(base) + * + * Set the base currency of this trading pair. + * + */ +TradingPair.prototype.setBase = function(base) { + this._base = base; +}; + +/* + * + * function getQuote() + * + * Get the quote currency of this trading pair. + * + */ +TradingPair.prototype.getQuote = function() { + return this._quote; +}; + +/* + * + * function setQuote(quote) + * + * Set the quote currency of this trading pair. + * + */ +TradingPair.prototype.setQuote = function(quote) { + this._quote = quote; +}; + +/* + * + * function swap() + * + * Swap the base and quote currencies of this trading pair. + * + */ +TradingPair.prototype.swap = function() { + // Localize currencies + var base = this._base; + var quote = this._quote; + + // Swap currencies + this._base = quote; + this._quote = base; +}; + +/* + * + * function getPairString() + * + * Get the currencies of this trading pair as a Poloniex pair string (e.g. + * "BTC_ETH") + * + */ +TradingPair.prototype.getPairString = function() { + return this._base + "_" + this._quote; +}; + +/* + * + * function setPairString(pairString) + * + * Set the currencies of this trading pair as a Poloniex pair string (e.g. + * "BTC_ETH") + * + */ +TradingPair.prototype.setPairString = function(pairString) { + // Validate pair string + if (!pairString || pairString.length < 3 || pairString.indexOf("_") == -1) { + throw "Invalid Poloniex pair string"; + } + + // Split the pair string + var pairStringSplit = pairString.split("_", 1); + + // Extract components of pair string + this._base = pairStringSplit[0]; + this._quote = pairStringSplit[1]; +};
84157c3942725eaaf928a08ad5ac3ba389dc141a
server/routes/users/index.js
server/routes/users/index.js
import express from 'express'; import * as userController from '../../controllers/users'; const user = express.Router(); // define route controllers for creating sign up, login and sign out user.post('/signup', userController.signUp); user.post('/signin', userController.signIn); user.get('/signout', userController.signOut); export default user;
Set up '/signup' to use User controller
Set up '/signup' to use User controller
JavaScript
apache-2.0
larrystone/BC-26-More-Recipes,larrystone/BC-26-More-Recipes
--- +++ @@ -0,0 +1,13 @@ +import express from 'express'; + +import * as userController from '../../controllers/users'; + +const user = express.Router(); + +// define route controllers for creating sign up, login and sign out +user.post('/signup', userController.signUp); +user.post('/signin', userController.signIn); + +user.get('/signout', userController.signOut); + +export default user;
fae9ab2828b9e5a4c19a65a7e2918b9e33b60558
src/shared/keypaths.js
src/shared/keypaths.js
const refPattern = /\[\s*(\*|[0-9]|[1-9][0-9]+)\s*\]/g; const splitPattern = /([^\\](?:\\\\)*)\./; const escapeKeyPattern = /\\|\./g; const unescapeKeyPattern = /((?:\\)+)\1|\\(\.)/g; export function escapeKey ( key ) { if ( typeof key === 'string' ) { return key.replace( escapeKeyPattern, '\\$&' ); } return key; } export function normalise ( ref ) { return ref ? ref.replace( refPattern, '.$1' ) : ''; } export function splitKeypath ( keypath ) { let parts = normalise( keypath ).split( splitPattern ), result = []; for ( let i = 0; i < parts.length; i += 2 ) { result.push( parts[i] + ( parts[i + 1] || '' ) ); } return result; } export function unescapeKey ( key ) { if ( typeof key === 'string' ) { return key.replace( unescapeKeyPattern, '$1$2' ); } return key; }
const refPattern = /\[\s*(\*|[0-9]|[1-9][0-9]+)\s*\]/g; const splitPattern = /([^\\](?:\\\\)*)\./; const escapeKeyPattern = /\\|\./g; const unescapeKeyPattern = /((?:\\)+)\1|\\(\.)/g; export function escapeKey ( key ) { if ( typeof key === 'string' ) { return key.replace( escapeKeyPattern, '\\$&' ); } return key; } export function normalise ( ref ) { return ref ? ref.replace( refPattern, '.$1' ) : ''; } export function splitKeypath ( keypath ) { let result = [], match; keypath = normalise( keypath ); while ( match = splitPattern.exec( keypath ) ) { let index = match.index + match[1].length; result.push( keypath.substr( 0, index ) ); keypath = keypath.substr( index + 1 ); } result.push(keypath); return result; } export function unescapeKey ( key ) { if ( typeof key === 'string' ) { return key.replace( unescapeKeyPattern, '$1$2' ); } return key; }
Make splitKeypath() work in old IE
Make splitKeypath() work in old IE
JavaScript
mit
marcalexiei/ractive,ISNIT0/ractive,marcalexiei/ractive,marcalexiei/ractive,ISNIT0/ractive,ractivejs/ractive,ractivejs/ractive,ractivejs/ractive,ISNIT0/ractive
--- +++ @@ -16,12 +16,18 @@ } export function splitKeypath ( keypath ) { - let parts = normalise( keypath ).split( splitPattern ), - result = []; + let result = [], + match; - for ( let i = 0; i < parts.length; i += 2 ) { - result.push( parts[i] + ( parts[i + 1] || '' ) ); + keypath = normalise( keypath ); + + while ( match = splitPattern.exec( keypath ) ) { + let index = match.index + match[1].length; + result.push( keypath.substr( 0, index ) ); + keypath = keypath.substr( index + 1 ); } + + result.push(keypath); return result; }
c365f8c33825e67846d40e651f4bb7dd063461c5
lib/extensions.js
lib/extensions.js
var semver = require('semver'), runtimeVersion = semver.parse(process.version); /** * Get Runtime Name * * @api private */ function getRuntimeName() { return process.execPath .split(/[\\/]+/).pop() .split('.').shift(); } /** * Get unique name of binary for current platform * * @api private */ function getBinaryIdentifiableName() { return [process.platform, '-', process.arch, '-', getRuntimeName(), '-', runtimeVersion.major, '.', runtimeVersion.minor].join(''); } process.runtime = getRuntimeName(); process.sassBinaryName = getBinaryIdentifiableName();
var semver = require('semver'), runtimeVersion = semver.parse(process.version); /** * Get Runtime Name * * @api private */ function getRuntimeName() { var runtime = process.execPath .split(/[\\/]+/).pop() .split('.').shift(); return runtime === 'node' || runtime === 'nodejs' ? 'node' : runtime; } /** * Get unique name of binary for current platform * * @api private */ function getBinaryIdentifiableName() { return [process.platform, '-', process.arch, '-', getRuntimeName(), '-', runtimeVersion.major, '.', runtimeVersion.minor].join(''); } process.runtime = getRuntimeName(); process.sassBinaryName = getBinaryIdentifiableName();
Normalize runtime name for binary installation
Normalize runtime name for binary installation
JavaScript
mit
Vitogee/node-sass,littlepoolshark/node-sass,paulcbetts/node-sass,nschonni/node-sass,quentinyang/node-sass,justame/node-sass,Smartbank/node-sass,justame/node-sass,SomeoneWeird/node-sass,pmq20/node-sass,chriseppstein/node-sass,yanickouellet/node-sass,besarthoxhaj/node-sass,am11/node-sass,kylecho/node-sass,nibblebot/node-sass,bigcommerce-labs/node-sass,pmq20/node-sass,bigcommerce-labs/node-sass,gdi2290/node-sass,chriseppstein/node-sass,greyhwndz/node-sass,xzyfer/node-sass,jnbt/node-sass,Smartbank/node-sass,dazld/node-sass,chriseppstein/node-sass,paulcbetts/node-sass,saper/node-sass,cvibhagool/node-sass,Smartbank/node-sass,deanrather/node-sass,glassdimly/node-sass,alanhogan/node-sass,Smartbank/node-sass,cfebs/node-sass,Vitogee/node-sass,xzyfer/node-sass,davejachimiak/node-sass,nfriedly/node-sass,greyhwndz/node-sass,saper/node-sass,ekskimn/node-sass,cvibhagool/node-sass,JTKnox91/node-sass,kylecho/node-sass,sass/node-sass,glassdimly/node-sass,cfebs/node-sass,JTKnox91/node-sass,nschonni/node-sass,nibblebot/node-sass,JTKnox91/node-sass,gdi2290/node-sass,greyhwndz/node-sass,eskygo/node-sass,glassdimly/node-sass,sass/node-sass,gdi2290/node-sass,paulcbetts/node-sass,eskygo/node-sass,lwdgit/node-sass,alanhogan/node-sass,gravityrail/node-sass,quentinyang/node-sass,JohnAlbin/node-sass,gravityrail/node-sass,xzyfer/node-sass,saper/node-sass,ankurp/node-sass,xzyfer/node-sass,dazld/node-sass,jnbt/node-sass,pmq20/node-sass,ankurp/node-sass,Cydrobolt/node-sass,bigcommerce-labs/node-sass,JohnAlbin/node-sass,alanhogan/node-sass,littlepoolshark/node-sass,davejachimiak/node-sass,ankurp/node-sass,Smartbank/node-sass,yanickouellet/node-sass,xzyfer/node-sass,SomeoneWeird/node-sass,FeodorFitsner/node-sass,dazld/node-sass,quentinyang/node-sass,paulcbetts/node-sass,bigcommerce-labs/node-sass,gravityrail/node-sass,Vitogee/node-sass,EdwonLim/node-sass-china,lwdgit/node-sass,nfriedly/node-sass,am11/node-sass,littlepoolshark/node-sass,am11/node-sass,plora/node-sass,sass/node-sass,saper/node-sass,nfriedly/node-sass,glassdimly/node-sass,Smartbank/node-sass,besarthoxhaj/node-sass,deanrather/node-sass,jnbt/node-sass,justame/node-sass,deanrather/node-sass,ekskimn/node-sass,sass/node-sass,deanrather/node-sass,kylecho/node-sass,justame/node-sass,lwdgit/node-sass,saper/node-sass,cvibhagool/node-sass,dazld/node-sass,sass/node-sass,nibblebot/node-sass,xzyfer/node-sass,Smartbank/node-sass,FeodorFitsner/node-sass,Cydrobolt/node-sass,EdwonLim/node-sass-china,sass/node-sass,besarthoxhaj/node-sass,nschonni/node-sass,jnbt/node-sass,Cydrobolt/node-sass,cfebs/node-sass,am11/node-sass,JohnAlbin/node-sass,plora/node-sass,quentinyang/node-sass,saper/node-sass,lwdgit/node-sass,yanickouellet/node-sass,nibblebot/node-sass,sass/node-sass,pmq20/node-sass,davejachimiak/node-sass,eskygo/node-sass,gravityrail/node-sass,greyhwndz/node-sass,gdi2290/node-sass,cfebs/node-sass,xzyfer/node-sass,chriseppstein/node-sass,Cydrobolt/node-sass,FeodorFitsner/node-sass,JTKnox91/node-sass,FeodorFitsner/node-sass,nschonni/node-sass,EdwonLim/node-sass-china,SomeoneWeird/node-sass,ankurp/node-sass,alanhogan/node-sass,saper/node-sass,cvibhagool/node-sass,nschonni/node-sass,ekskimn/node-sass,nschonni/node-sass,ekskimn/node-sass,plora/node-sass,plora/node-sass,Vitogee/node-sass,nschonni/node-sass,kylecho/node-sass
--- +++ @@ -8,9 +8,11 @@ */ function getRuntimeName() { - return process.execPath + var runtime = process.execPath .split(/[\\/]+/).pop() .split('.').shift(); + + return runtime === 'node' || runtime === 'nodejs' ? 'node' : runtime; } /**
394cbfd34ee9439048e266fc824432a5a6edec25
test/player-eats-virus-test.js
test/player-eats-virus-test.js
const chai = require('chai'); const assert = chai.assert; const Player = require('../public/online-player'); const Virus = require('../lib/virus'); describe('Player eating viruses', function(){ context('Player is large enough to consume virus', function() { it('deletes the virus from the viruses array', function() { var player = new Player("id", "Joe", 10, 10); var virus1 = new Virus( { x: 10, y: 10} ); var virus2 = new Virus( { x: 100, y: 100} ); var virusesArray = [virus1, virus2]; player.mass = virus1.mass / 0.89; assert.equal(virusesArray.length, 2); player.eatViruses(virusesArray); assert.equal(virusesArray.length, 1); assert.notInclude(virusesArray, virus1); }); it("cuts the player's mass in half", function() { var player = new Player("id", "Joe", 10, 10); var virus = new Virus( { x: 10, y: 10} ); var virusesArray = [virus]; player.mass = virus.mass / 0.89; var startingMass = player.mass; player.eatViruses(virusesArray); assert.equal(player.mass, startingMass/2); }); }); context("Player is not large enough to consume a virus", function() { it('does not delete the virus from the viruses array', function() { var player = new Player("id", "Joe", 10, 10); var virus1 = new Virus( { x: 10, y: 10} ); var virus2 = new Virus( { x: 100, y: 100} ); var virusesArray = [virus1, virus2]; player.mass = virus1.mass / 0.90; assert.equal(virusesArray.length, 2); player.eatViruses(virusesArray); assert.equal(virusesArray.length, 2); }); it('does not change the player mass', function() { var player = new Player("id", "Joe", 10, 10); var virus = new Virus( { x: 10, y: 10} ); var virusesArray = [virus]; player.mass = virus.mass / 0.90; var startingMass = player.mass; player.eatViruses(virusesArray); assert.equal(virusesArray.length, 1); assert.equal(player.mass, startingMass); }); }); });
Add test for player eats virus
Add test for player eats virus
JavaScript
mit
jecrockett/gametime,jecrockett/gametime
--- +++ @@ -0,0 +1,66 @@ +const chai = require('chai'); +const assert = chai.assert; + +const Player = require('../public/online-player'); +const Virus = require('../lib/virus'); + +describe('Player eating viruses', function(){ + context('Player is large enough to consume virus', function() { + + it('deletes the virus from the viruses array', function() { + var player = new Player("id", "Joe", 10, 10); + var virus1 = new Virus( { x: 10, y: 10} ); + var virus2 = new Virus( { x: 100, y: 100} ); + var virusesArray = [virus1, virus2]; + player.mass = virus1.mass / 0.89; + + assert.equal(virusesArray.length, 2); + + player.eatViruses(virusesArray); + + assert.equal(virusesArray.length, 1); + assert.notInclude(virusesArray, virus1); + }); + + it("cuts the player's mass in half", function() { + var player = new Player("id", "Joe", 10, 10); + var virus = new Virus( { x: 10, y: 10} ); + var virusesArray = [virus]; + player.mass = virus.mass / 0.89; + var startingMass = player.mass; + + player.eatViruses(virusesArray); + + assert.equal(player.mass, startingMass/2); + }); + }); + + context("Player is not large enough to consume a virus", function() { + it('does not delete the virus from the viruses array', function() { + var player = new Player("id", "Joe", 10, 10); + var virus1 = new Virus( { x: 10, y: 10} ); + var virus2 = new Virus( { x: 100, y: 100} ); + var virusesArray = [virus1, virus2]; + player.mass = virus1.mass / 0.90; + + assert.equal(virusesArray.length, 2); + + player.eatViruses(virusesArray); + + assert.equal(virusesArray.length, 2); + }); + + it('does not change the player mass', function() { + var player = new Player("id", "Joe", 10, 10); + var virus = new Virus( { x: 10, y: 10} ); + var virusesArray = [virus]; + player.mass = virus.mass / 0.90; + var startingMass = player.mass; + + player.eatViruses(virusesArray); + + assert.equal(virusesArray.length, 1); + assert.equal(player.mass, startingMass); + }); + }); +});
66cfb46a9a824b185f7ff3b8c74e666fd80436be
lib/number.with.commas.js
lib/number.with.commas.js
"use static"; function numberWithCommas(number) { var parts = number.toString().split("."); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); return parts.join("."); } Handlebars.registerHelper('commas', numberWithCommas);
Format numbers with thousand seperators
Format numbers with thousand seperators
JavaScript
bsd-2-clause
narthollis/eve-skillplan-webapp,narthollis/eve-skillplan-webapp
--- +++ @@ -0,0 +1,10 @@ +"use static"; + +function numberWithCommas(number) { + var parts = number.toString().split("."); + parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); + return parts.join("."); +} + +Handlebars.registerHelper('commas', numberWithCommas); +
5dcc55153ee9f81058f01d22a4db8a215b221966
squanch.js
squanch.js
const squanch = (...patterns) => { return v => { const primitives = ['Number', 'String', 'Boolean', 'Symbol']; const isIdentical = (p, v) => p === v; const isNull = (p, v) => isIdentical(null, p) && isIdentical(p, v); const isUndefined = (p, v) => isIdentical(undefined, p) && isIdentical(p, v); const isPrimitiveWithValue = (primitives, type, value) => { return (value !== null && value !== undefined) && primitives.includes(type.name) && {}.valueOf.call(value) instanceof type; }; const callalbeTruthy = (p, v) => { if (p instanceof Function && ! primitives.includes(p.name)) { return p.call(null, v); } }; for (let sequence of patterns) { let [pattern, fn] = sequence; switch(true) { case (isNull(pattern, v)) : case (isUndefined(pattern, v)) : case (isIdentical(pattern, v)) : case (isPrimitiveWithValue(primitives, pattern, v)) : case (callalbeTruthy(pattern, v)) : return fn.call(null, v); break; } } return 'No patterns matched'; }; }; export default squanch;
Add initial pattern matching logic
Add initial pattern matching logic get schwifty!
JavaScript
mit
magbicaleman/squanch
--- +++ @@ -0,0 +1,36 @@ +const squanch = (...patterns) => { + return v => { + const primitives = ['Number', 'String', 'Boolean', 'Symbol']; + + const isIdentical = (p, v) => p === v; + const isNull = (p, v) => isIdentical(null, p) && isIdentical(p, v); + const isUndefined = (p, v) => isIdentical(undefined, p) && isIdentical(p, v); + const isPrimitiveWithValue = (primitives, type, value) => { + return (value !== null && value !== undefined) + && primitives.includes(type.name) + && {}.valueOf.call(value) instanceof type; + }; + const callalbeTruthy = (p, v) => { + if (p instanceof Function && ! primitives.includes(p.name)) { + return p.call(null, v); + } + }; + + for (let sequence of patterns) { + let [pattern, fn] = sequence; + switch(true) { + case (isNull(pattern, v)) : + case (isUndefined(pattern, v)) : + case (isIdentical(pattern, v)) : + case (isPrimitiveWithValue(primitives, pattern, v)) : + case (callalbeTruthy(pattern, v)) : + return fn.call(null, v); + break; + } + } + + return 'No patterns matched'; + }; +}; + +export default squanch;
e2558b0870f368dcbf7a3defa63167384f521c66
html2md.js
html2md.js
#!/usr/bin/env node var fs = require('fs') toMarkdown = require('to-markdown'); fn = process.argv[2] fs.readFile(fn, 'utf8', function (err,data) { if (err) { return console.log(err); } converter = { filter: ['span', 'title', 'meta', 'style'], replacement: function(content) { if ( content.tagName == 'style' || content.tagName == 'meta' || content.tagName == 'title' ) { return ""; } return content; } }; v = toMarkdown(data, { converters: [converter] }); console.log(v); });
Add html->md script (moved from wkoszek/me/scripts)
Add html->md script (moved from wkoszek/me/scripts)
JavaScript
bsd-2-clause
wkoszek/tools,wkoszek/tools,wkoszek/tools
--- +++ @@ -0,0 +1,30 @@ +#!/usr/bin/env node + +var fs = require('fs') +toMarkdown = require('to-markdown'); + +fn = process.argv[2] + +fs.readFile(fn, 'utf8', function (err,data) { + if (err) { + return console.log(err); + } + converter = { + filter: ['span', 'title', 'meta', 'style'], + replacement: function(content) { + if ( + content.tagName == 'style' || + content.tagName == 'meta' || + content.tagName == 'title' + ) { + return ""; + } + return content; + } + }; + + v = toMarkdown(data, { converters: [converter] }); + + console.log(v); +}); +
cdd10264a128017b80b501e183c2925e30048a43
server/index.js
server/index.js
const express = require('express'); const redis = require("redis"); const session = require('express-session'); const RedisStore = require('connect-redis')(session); const passport = require('passport'); const path = require('path'); const app = express(); const server = require('http').createServer(app); const io = require('socket.io')(server); require('dotenv').config(); const secret = require('./config/secrets'); const routes = require('./routes'); // Config require('./config/passport')(passport); const client = redis.createClient(); client.on("error", err => console.log(`Error: ${err} - Are you running redis?`)); app.use(session({ store: new RedisStore({ client }), secret: secret.sessionSecret, resave: false, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session()); // Use dirs appropriately, with a separation of concerns for the public & dist dirs app.use('/public', express.static(path.join(__dirname, '../public'))); app.use('/dist', express.static(path.join(__dirname, '../dist'))); // Routes routes(app, passport, io); // Server const port = process.env.PORT || 8080; server.listen(port, function() { console.log(`Email service live on port ${port}`); });
const express = require('express'); const redis = require("redis"); const session = require('express-session'); const RedisStore = require('connect-redis')(session); const passport = require('passport'); const path = require('path'); const app = express(); const server = require('http').createServer(app); const io = require('socket.io')(server); const csrf = require('csurf'); require('dotenv').config(); const secret = require('./config/secrets'); const routes = require('./routes'); // Config require('./config/passport')(passport); const client = redis.createClient(); client.on("error", err => console.log(`Error: ${err} - Are you running redis?`)); // eslint-disable-line app.use(session({ store: new RedisStore({ client }), secret: secret.sessionSecret, resave: false, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session()); app.use(csrf()); // Inject CSRF token to req.session // Use dirs appropriately, with a separation of concerns for the public & dist dirs app.use('/public', express.static(path.join(__dirname, '../public'))); app.use('/dist', express.static(path.join(__dirname, '../dist'))); // Routes routes(app, passport, io); // Server const port = process.env.PORT || 8080; server.listen(port, function() { console.log(`Email service live on port ${port}`); // eslint-disable-line });
Add csurf to protect against CSRF attacks
Add csurf to protect against CSRF attacks
JavaScript
bsd-3-clause
zhakkarn/Mail-for-Good,karuppiah7890/Mail-for-Good,karuppiah7890/Mail-for-Good,zhakkarn/Mail-for-Good,zhakkarn/Mail-for-Good,karuppiah7890/Mail-for-Good
--- +++ @@ -7,6 +7,7 @@ const app = express(); const server = require('http').createServer(app); const io = require('socket.io')(server); +const csrf = require('csurf'); require('dotenv').config(); @@ -18,7 +19,7 @@ const client = redis.createClient(); -client.on("error", err => console.log(`Error: ${err} - Are you running redis?`)); +client.on("error", err => console.log(`Error: ${err} - Are you running redis?`)); // eslint-disable-line app.use(session({ store: new RedisStore({ client }), @@ -28,6 +29,7 @@ })); app.use(passport.initialize()); app.use(passport.session()); +app.use(csrf()); // Inject CSRF token to req.session // Use dirs appropriately, with a separation of concerns for the public & dist dirs app.use('/public', express.static(path.join(__dirname, '../public'))); @@ -39,5 +41,5 @@ // Server const port = process.env.PORT || 8080; server.listen(port, function() { - console.log(`Email service live on port ${port}`); + console.log(`Email service live on port ${port}`); // eslint-disable-line });
7022aa26b0ef3a0610b5f80255bc95d8d29027a7
tests/hello.js
tests/hello.js
// Copyright 2015 Samsung Electronics Co., Ltd. // Copyright 2015 University of Szeged. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. print ("Hello JerryScript!");
Add a "Hello JerryScript!" program to the tests
Add a "Hello JerryScript!" program to the tests The current code base does not contain any "first JavaScript program" for those who build JerryScript for Linux console. It does contain a LED-blinking example -- blinky.js -- but that's only useful on an developer board where LEDs-to-be-blinked are available. And the rest of the tests are just that: tests, giving passed/failed information but nothing eye candy. This patch adds a simple JS script that can act as a warm welcome to anyone after the first successful build trying to run something proving that Jerry works. JerryScript-DCO-1.0-Signed-off-by: Akos Kiss akiss@inf.u-szeged.hu
JavaScript
apache-2.0
zherczeg/jerryscript,jack60504/jerryscript,slaff/jerryscript,bzsolt/jerryscript,robertsipka/jerryscript,loki04/jerryscript,LaszloLango/jerryscript,slaff/jerryscript,akosthekiss/jerryscript,bzsolt/jerryscript,jerryscript-project/jerryscript,martijnthe/jerryscript,tilmannOSG/jerryscript,martijnthe/jerryscript,LaszloLango/jerryscript,loki04/jerryscript,jack60504/jerryscript,bzsolt/jerryscript,jerryscript-project/jerryscript,tilmannOSG/jerryscript,glistening/jerryscript,gabrielschulhof/jerryscript,dbatyai/jerryscript,dbatyai/jerryscript,martijnthe/jerryscript,akosthekiss/jerryscript,grgustaf/jerryscript,LaszloLango/jerryscript,tilmannOSG/jerryscript,jack60504/jerryscript,martijnthe/jerryscript,gabrielschulhof/jerryscript,grgustaf/jerryscript,martijnthe/jerryscript,bsdelf/jerryscript,yichoi/jerryscript,jerryscript-project/jerryscript,robertsipka/jerryscript,slaff/jerryscript,gabrielschulhof/jerryscript,robertsipka/jerryscript,tilmannOSG/jerryscript,zherczeg/jerryscript,zherczeg/jerryscript,LeeHayun/jerryscript,robertsipka/jerryscript,glistening/jerryscript,gabrielschulhof/jerryscript,loki04/jerryscript,slaff/jerryscript,dbatyai/jerryscript,jerryscript-project/jerryscript,glistening/jerryscript,jack60504/jerryscript,bsdelf/jerryscript,bsdelf/jerryscript,glistening/jerryscript,bsdelf/jerryscript,bsdelf/jerryscript,LeeHayun/jerryscript,zherczeg/jerryscript,LaszloLango/jerryscript,glistening/jerryscript,jack60504/jerryscript,tilmannOSG/jerryscript,gabrielschulhof/jerryscript,akosthekiss/jerryscript,glistening/jerryscript,akosthekiss/jerryscript,LeeHayun/jerryscript,LeeHayun/jerryscript,zherczeg/jerryscript,LeeHayun/jerryscript,jerryscript-project/jerryscript,bsdelf/jerryscript,dbatyai/jerryscript,akosthekiss/jerryscript,yichoi/jerryscript,grgustaf/jerryscript,loki04/jerryscript,yichoi/jerryscript,grgustaf/jerryscript,martijnthe/jerryscript,slaff/jerryscript,LaszloLango/jerryscript,loki04/jerryscript,grgustaf/jerryscript,robertsipka/jerryscript,grgustaf/jerryscript,bzsolt/jerryscript,loki04/jerryscript,yichoi/jerryscript,dbatyai/jerryscript,bzsolt/jerryscript,jack60504/jerryscript,robertsipka/jerryscript,yichoi/jerryscript
--- +++ @@ -0,0 +1,16 @@ +// Copyright 2015 Samsung Electronics Co., Ltd. +// Copyright 2015 University of Szeged. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +print ("Hello JerryScript!");
944f8f79929e732b6554b7648dac0188213ca540
app/components/api.js
app/components/api.js
export function get(path) { return request('GET', path, '', {}); } export function post(path, body, signature) { return request('POST', path, body, signature); } function request(verb, path, body, signature) { return fetch(path, Object.assign({ method: verb, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', signature }, body })); }
Move API functions into separate file
Move API functions into separate file
JavaScript
apache-2.0
dillonhafer/garage-ios,dillonhafer/garage-ios
--- +++ @@ -0,0 +1,19 @@ +export function get(path) { + return request('GET', path, '', {}); +} + +export function post(path, body, signature) { + return request('POST', path, body, signature); +} + +function request(verb, path, body, signature) { + return fetch(path, Object.assign({ + method: verb, + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + signature + }, + body + })); +}
98c536016b4c8d2364b854b835ad347038dc49dd
tests/utils/time/TimeParserTests.js
tests/utils/time/TimeParserTests.js
/** @ignore */ const TimeParser = requireApp('utils/time/TimeParser'); /** @ignore */ const assert = require('assert'); describe('app/utils/time/TimeParser', () => { describe('#parse()', () => { it('returns format, time array and seconds as an object', () => { let time = TimeParser.parse('2h2s'); assert.equal(true, time.hasOwnProperty('format')); assert.equal(true, time.hasOwnProperty('timeArr')); assert.equal(true, time.hasOwnProperty('seconds')); }); it('returns the correct format of the given string', () => { assert.equal('1 day, 3 hours, 28 minutes, and 42 seconds', TimeParser.parse('1d3h28m42s').format); assert.equal('2 hours, 58 minutes, and 2 seconds', TimeParser.parse('2h58m2s').format); assert.equal('31 minutes and 18 seconds', TimeParser.parse('31m18s').format); assert.equal('42 seconds', TimeParser.parse('42s').format); assert.equal('1 day, 28 minutes, and 42 seconds', TimeParser.parse('1d28m42s').format); assert.equal('2 hours and 2 seconds', TimeParser.parse('2h2s').format); assert.equal('31 days and 18 seconds', TimeParser.parse('31d18s').format); assert.equal('42 seconds and 4 days', TimeParser.parse('42s4d').format); }); it('returns the correct amount of seconds', () => { assert.equal(98922, TimeParser.parse('1d3h28m42s').seconds); assert.equal(10682, TimeParser.parse('2h58m2s').seconds); assert.equal(1878, TimeParser.parse('31m18s').seconds); assert.equal(42, TimeParser.parse('42s').seconds); assert.equal(88122, TimeParser.parse('1d28m42s').seconds); assert.equal(7202, TimeParser.parse('2h2s').seconds); assert.equal(2678418, TimeParser.parse('31d18s').seconds); assert.equal(345642, TimeParser.parse('42s4d').seconds); }); }); });
Add tests for time parser utility
Add tests for time parser utility
JavaScript
mit
Senither/AvaIre
--- +++ @@ -0,0 +1,40 @@ +/** @ignore */ +const TimeParser = requireApp('utils/time/TimeParser'); +/** @ignore */ +const assert = require('assert'); + +describe('app/utils/time/TimeParser', () => { + describe('#parse()', () => { + it('returns format, time array and seconds as an object', () => { + let time = TimeParser.parse('2h2s'); + + assert.equal(true, time.hasOwnProperty('format')); + assert.equal(true, time.hasOwnProperty('timeArr')); + assert.equal(true, time.hasOwnProperty('seconds')); + }); + + it('returns the correct format of the given string', () => { + assert.equal('1 day, 3 hours, 28 minutes, and 42 seconds', TimeParser.parse('1d3h28m42s').format); + assert.equal('2 hours, 58 minutes, and 2 seconds', TimeParser.parse('2h58m2s').format); + assert.equal('31 minutes and 18 seconds', TimeParser.parse('31m18s').format); + assert.equal('42 seconds', TimeParser.parse('42s').format); + + assert.equal('1 day, 28 minutes, and 42 seconds', TimeParser.parse('1d28m42s').format); + assert.equal('2 hours and 2 seconds', TimeParser.parse('2h2s').format); + assert.equal('31 days and 18 seconds', TimeParser.parse('31d18s').format); + assert.equal('42 seconds and 4 days', TimeParser.parse('42s4d').format); + }); + + it('returns the correct amount of seconds', () => { + assert.equal(98922, TimeParser.parse('1d3h28m42s').seconds); + assert.equal(10682, TimeParser.parse('2h58m2s').seconds); + assert.equal(1878, TimeParser.parse('31m18s').seconds); + assert.equal(42, TimeParser.parse('42s').seconds); + + assert.equal(88122, TimeParser.parse('1d28m42s').seconds); + assert.equal(7202, TimeParser.parse('2h2s').seconds); + assert.equal(2678418, TimeParser.parse('31d18s').seconds); + assert.equal(345642, TimeParser.parse('42s4d').seconds); + }); + }); +});
7f61cb688bdd653a05f8d44bb242f63732acdcc2
node-tests/blueprints/mixin-test.js
node-tests/blueprints/mixin-test.js
'use strict'; var blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers'); var setupTestHooks = blueprintHelpers.setupTestHooks; var emberNew = blueprintHelpers.emberNew; var emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy; var expect = require('ember-cli-blueprint-test-helpers/chai').expect; describe('Acceptance: ember generate and destroy mixin', function() { setupTestHooks(this); it('mixin foo-bar', function() { var args = ['mixin', 'foo-bar']; return emberNew() .then(() => emberGenerateDestroy(args, (file) => { expect(file('app/mixins/foo-bar.coffee')) .to.contain("`import Ember from 'ember'`") .to.contain('FooBarMixin = Ember.Mixin.create()') .to.contain("`export default FooBarMixin`"); expect(file('tests/unit/mixins/foo-bar-test.coffee')) .to.contain("`import Ember from 'ember'`") // TODO: Fix this import - it should be absolute .to.contain("`import FooBarMixin from '../../../mixins/foo-bar'`") .to.contain("`import { module, test } from 'qunit'`") .to.contain("module 'Unit | Mixin | foo bar'") .to.contain('FooBarObject = Ember.Object.extend FooBarMixin') .to.contain('subject = FooBarObject.create()'); })); }); it('mixin-test foo-bar', function() { var args = ['mixin-test', 'foo-bar']; return emberNew() .then(() => emberGenerateDestroy(args, (file) => { expect(file('tests/unit/mixins/foo-bar-test.coffee')) .to.contain("`import Ember from 'ember'`") .to.contain("`import FooBarMixin from '../../../mixins/foo-bar'`") .to.contain("`import { module, test } from 'qunit'`") .to.contain("module 'Unit | Mixin | foo bar'") .to.contain('FooBarObject = Ember.Object.extend FooBarMixin') .to.contain('subject = FooBarObject.create()'); })); }); });
Add inital test for mixin blueprint
Add inital test for mixin blueprint
JavaScript
mit
kimroen/ember-cli-coffeescript,kimroen/ember-cli-coffeescript,kimroen/ember-cli-coffeescript
--- +++ @@ -0,0 +1,48 @@ +'use strict'; + +var blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers'); +var setupTestHooks = blueprintHelpers.setupTestHooks; +var emberNew = blueprintHelpers.emberNew; +var emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy; + +var expect = require('ember-cli-blueprint-test-helpers/chai').expect; + +describe('Acceptance: ember generate and destroy mixin', function() { + setupTestHooks(this); + + it('mixin foo-bar', function() { + var args = ['mixin', 'foo-bar']; + + return emberNew() + .then(() => emberGenerateDestroy(args, (file) => { + expect(file('app/mixins/foo-bar.coffee')) + .to.contain("`import Ember from 'ember'`") + .to.contain('FooBarMixin = Ember.Mixin.create()') + .to.contain("`export default FooBarMixin`"); + + expect(file('tests/unit/mixins/foo-bar-test.coffee')) + .to.contain("`import Ember from 'ember'`") + // TODO: Fix this import - it should be absolute + .to.contain("`import FooBarMixin from '../../../mixins/foo-bar'`") + .to.contain("`import { module, test } from 'qunit'`") + .to.contain("module 'Unit | Mixin | foo bar'") + .to.contain('FooBarObject = Ember.Object.extend FooBarMixin') + .to.contain('subject = FooBarObject.create()'); + })); + }); + + it('mixin-test foo-bar', function() { + var args = ['mixin-test', 'foo-bar']; + + return emberNew() + .then(() => emberGenerateDestroy(args, (file) => { + expect(file('tests/unit/mixins/foo-bar-test.coffee')) + .to.contain("`import Ember from 'ember'`") + .to.contain("`import FooBarMixin from '../../../mixins/foo-bar'`") + .to.contain("`import { module, test } from 'qunit'`") + .to.contain("module 'Unit | Mixin | foo bar'") + .to.contain('FooBarObject = Ember.Object.extend FooBarMixin') + .to.contain('subject = FooBarObject.create()'); + })); + }); +});
68235553f0d6fda45339cbf88b4998942ca5037c
i18n/jquery.spectrum-es.js
i18n/jquery.spectrum-es.js
// Spectrum Colorpicker // Spanish (es) localization // https://github.com/bgrins/spectrum (function ( $ ) { var localization = $.spectrum.localization["es"] = { cancelText: "Cancelar", chooseText: "Elegir", clearText: "Borrar color seleccionado", noColorSelectedText: "Ningn color seleccionado", togglePaletteMoreText: "Ms", togglePaletteLessText: "Menos" }; $.extend($.fn.spectrum.defaults, localization); })( jQuery );
// Spectrum Colorpicker // Spanish (es) localization // https://github.com/bgrins/spectrum (function ( $ ) { var localization = $.spectrum.localization["es"] = { cancelText: "Cancelar", chooseText: "Elegir", clearText: "Borrar color seleccionado", noColorSelectedText: "Ningún color seleccionado", togglePaletteMoreText: "Más", togglePaletteLessText: "Menos" }; $.extend($.fn.spectrum.defaults, localization); })( jQuery );
Fix Spanish language file encoding (UTF-8).
Fix Spanish language file encoding (UTF-8).
JavaScript
mit
ginlime/spectrum,GerHobbelt/spectrum,liitii/spectrum,GerHobbelt/spectrum,ajssd/spectrum,maurojs25/spectrum,kotmatpockuh/spectrum,liitii/spectrum,safareli/spectrum,ginlime/spectrum,shawinder/spectrum,armanforghani/spectrum,bgrins/spectrum,ajssd/spectrum,kotmatpockuh/spectrum,safareli/spectrum,c9s/spectrum,shawinder/spectrum,maurojs25/spectrum,bgrins/spectrum,armanforghani/spectrum
--- +++ @@ -8,8 +8,8 @@ cancelText: "Cancelar", chooseText: "Elegir", clearText: "Borrar color seleccionado", - noColorSelectedText: "Ningn color seleccionado", - togglePaletteMoreText: "Ms", + noColorSelectedText: "Ningún color seleccionado", + togglePaletteMoreText: "Más", togglePaletteLessText: "Menos" };
3a0dfb0a715d352ff612059a924a8992006fa6c9
25/passport-facebook.js
25/passport-facebook.js
var passport = require('passport'); var FacebookStrategy = require('passport-facebook').Strategy; var express = require('express'); var cookieSession = require('cookie-session'); var app = express(); app.use(cookieSession({keys: ['asdfghjkl!@#$%ASDFGHJ']})) app.use(passport.initialize()); app.use(passport.session()); var FACEBOOK_APP_ID = '15********'; var FACEBOOK_APP_SECRET = '*********'; passport.serializeUser(function(user, done) { done(null, user); }); passport.deserializeUser(function(obj, done) { done(null, obj); }); passport.use(new FacebookStrategy({ clientID: FACEBOOK_APP_ID, clientSecret: FACEBOOK_APP_SECRET, callbackURL: "http://localhost/auth/facebook/oauth2callback" }, function(accessToken, refreshToken, profile, done) { return done(null, profile); } )); app.get('/auth/Error', function(req, res) { res.send('Login Fail!'); }) app.get('/auth/facebook', passport.authenticate('facebook') ); app.get('/auth/facebook/oauth2callback', passport.authenticate('facebook', { failureRedirect: '/auth/Error' }), function(req, res) { res.send('UserName: ' + req.user.name.givenName + ', eMail: ' + req.user.emails[0].value); } ); app.get('/auth/logout', function(req, res){ req.logOut(); res.send('Logout!'); }); app.all('/*', function(req, res) { res.send('Default Page!'); }); var server = app.listen(80, function() { var host = server.address().address; var port = server.address().port; console.log('Listening at http://%s:%s', host, port); });
Add the example to get the authorization from facebook.
Add the example to get the authorization from facebook.
JavaScript
mit
nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference
--- +++ @@ -0,0 +1,65 @@ +var passport = require('passport'); +var FacebookStrategy = require('passport-facebook').Strategy; +var express = require('express'); + +var cookieSession = require('cookie-session'); +var app = express(); +app.use(cookieSession({keys: ['asdfghjkl!@#$%ASDFGHJ']})) +app.use(passport.initialize()); +app.use(passport.session()); + +var FACEBOOK_APP_ID = '15********'; +var FACEBOOK_APP_SECRET = '*********'; + +passport.serializeUser(function(user, done) { + done(null, user); +}); + +passport.deserializeUser(function(obj, done) { + done(null, obj); +}); + +passport.use(new FacebookStrategy({ + clientID: FACEBOOK_APP_ID, + clientSecret: FACEBOOK_APP_SECRET, + callbackURL: "http://localhost/auth/facebook/oauth2callback" + }, + function(accessToken, refreshToken, profile, done) { + return done(null, profile); + } +)); + +app.get('/auth/Error', function(req, res) { + res.send('Login Fail!'); +}) + +app.get('/auth/facebook', + passport.authenticate('facebook') +); + +app.get('/auth/facebook/oauth2callback', + passport.authenticate('facebook', { + failureRedirect: '/auth/Error' + }), + function(req, res) { + res.send('UserName: ' + req.user.name.givenName + ', eMail: ' + req.user.emails[0].value); + } +); + +app.get('/auth/logout', function(req, res){ + req.logOut(); + res.send('Logout!'); +}); + +app.all('/*', function(req, res) { + res.send('Default Page!'); +}); + +var server = app.listen(80, function() { + + var host = server.address().address; + var port = server.address().port; + + console.log('Listening at http://%s:%s', host, port); +}); +
b85b349730792bfc7721d343467a831a7304e1a8
client/app/data/validator/Email.js
client/app/data/validator/Email.js
Ext.define('Starter.data.validator.Email', { override: 'Ext.data.validator.Email', validate: function(value) { if (value === undefined || value === null || Ext.String.trim(value).length === 0) { return true; } var matcher = this.getMatcher(), result = matcher && matcher.test(value); return result ? result : this.getMessage(); } });
Change the email validator so it also works for optional fields
Change the email validator so it also works for optional fields
JavaScript
apache-2.0
ralscha/eds-starter6-mongodb,ralscha/eds-starter6-mongodb,ralscha/eds-starter6-mongodb
--- +++ @@ -0,0 +1,11 @@ +Ext.define('Starter.data.validator.Email', { + override: 'Ext.data.validator.Email', + + validate: function(value) { + if (value === undefined || value === null || Ext.String.trim(value).length === 0) { + return true; + } + var matcher = this.getMatcher(), result = matcher && matcher.test(value); + return result ? result : this.getMessage(); + } +});
6a6e35d90b2da1265911c1c4ebdf5082b2d1e777
test/reducers/gui_test.js
test/reducers/gui_test.js
/* eslint-disable max-len */ import { UPDATE_LOCATION } from 'react-router-redux' import { expect, // sinon } from '../spec_helper' import * as subject from '../../src/reducers/gui' describe('gui reducer', () => { describe('initial state', () => { it('sets up a default initialState', () => { expect( subject.gui(undefined, {}) ).to.have.keys('modes', 'currentStream') }) }) })
Add basic gui reducer test
Add basic gui reducer test
JavaScript
mit
ello/webapp,ello/webapp,ello/webapp
--- +++ @@ -0,0 +1,15 @@ +/* eslint-disable max-len */ +import { UPDATE_LOCATION } from 'react-router-redux' +import { expect, // sinon + } from '../spec_helper' +import * as subject from '../../src/reducers/gui' + +describe('gui reducer', () => { + describe('initial state', () => { + it('sets up a default initialState', () => { + expect( + subject.gui(undefined, {}) + ).to.have.keys('modes', 'currentStream') + }) + }) +})
57e0abe38feb077cfb1e33414813d5bc704d150e
week-7/variables-objects.js
week-7/variables-objects.js
// JavaScript Variables and Objects // I paired by myself on this challenge. // __________________________________________ // Write your code below. var secretNumber = 7; var password = "just open the door" var allowedIn = false; var members = ["John", "Susan", "Tom", "Mary"] // __________________________________________ // Test Code: Do not alter code below this line. function assert(test, message, test_number) { if (!test) { console.log(test_number + "false"); throw "ERROR: " + message; } console.log(test_number + "true"); return true; } assert( (typeof secretNumber === 'number'), "The value of secretNumber should be a number.", "1. " ) assert( secretNumber === 7, "The value of secretNumber should be 7.", "2. " ) assert( typeof password === 'string', "The value of password should be a string.", "3. " ) assert( password === "just open the door", "The value of password should be 'just open the door'.", "4. " ) assert( typeof allowedIn === 'boolean', "The value of allowedIn should be a boolean.", "5. " ) assert( allowedIn === false, "The value of allowedIn should be false.", "6. " ) assert( members instanceof Array, "The value of members should be an array", "7. " ) assert( members[0] === "John", "The first element in the value of members should be 'John'.", "8. " ) assert( members[3] === "Mary", "The fourth element in the value of members should be 'Mary'.", "9. " )
Add 7.3 variables and objects
Add 7.3 variables and objects
JavaScript
mit
marcus-a-davis/phase-0,marcus-a-davis/phase-0,marcus-a-davis/phase-0
--- +++ @@ -0,0 +1,80 @@ +// JavaScript Variables and Objects + +// I paired by myself on this challenge. + +// __________________________________________ +// Write your code below. + + +var secretNumber = 7; +var password = "just open the door" +var allowedIn = false; +var members = ["John", "Susan", "Tom", "Mary"] + + +// __________________________________________ + +// Test Code: Do not alter code below this line. + +function assert(test, message, test_number) { + if (!test) { + console.log(test_number + "false"); + throw "ERROR: " + message; + } + console.log(test_number + "true"); + return true; +} + +assert( + (typeof secretNumber === 'number'), + "The value of secretNumber should be a number.", + "1. " +) + +assert( + secretNumber === 7, + "The value of secretNumber should be 7.", + "2. " +) + +assert( + typeof password === 'string', + "The value of password should be a string.", + "3. " +) + +assert( + password === "just open the door", + "The value of password should be 'just open the door'.", + "4. " +) + +assert( + typeof allowedIn === 'boolean', + "The value of allowedIn should be a boolean.", + "5. " +) + +assert( + allowedIn === false, + "The value of allowedIn should be false.", + "6. " +) + +assert( + members instanceof Array, + "The value of members should be an array", + "7. " +) + +assert( + members[0] === "John", + "The first element in the value of members should be 'John'.", + "8. " +) + +assert( + members[3] === "Mary", + "The fourth element in the value of members should be 'Mary'.", + "9. " +)
558503a4eb6e696294255161d5d83645c89702d5
migrations/20160728121504-update-chat-channels-to-be-more-flexible.js
migrations/20160728121504-update-chat-channels-to-be-more-flexible.js
exports.up = function(db, cb) { db.runSql(` CREATE TABLE channels ( name citext PRIMARY KEY, private boolean NOT NULL DEFAULT false, high_traffic boolean NOT NULL DEFAULT false, topic text, password text );`, addChannelNameConstraint) function addChannelNameConstraint(err) { if (err) { cb(err) return } const sql = `ALTER TABLE channels ADD CONSTRAINT channel_name_length_check CHECK (length(name) <= 64);` db.runSql(sql, createChannelNameIndex) } function createChannelNameIndex(err) { if (err) { cb(err) return } db.addIndex('channels', 'channels_name_index', ['name'], false /* unique */, insertShieldBatteryChannel) } function insertShieldBatteryChannel(err) { if (err) { cb(err) return } const sql = 'INSERT INTO channels (name) VALUES (\'ShieldBattery\');' db.runSql(sql, addPermissionsToJoinedChannels) } function addPermissionsToJoinedChannels(err) { if (err) { cb(err) return } const sql = `ALTER TABLE joined_channels ADD COLUMN kick boolean NOT NULL DEFAULT false, ADD COLUMN ban boolean NOT NULL DEFAULT false, ADD COLUMN change_topic boolean NOT NULL DEFAULT false, ADD COLUMN toggle_private boolean NOT NULL DEFAULT false, ADD COLUMN edit_permissions boolean NOT NULL DEFAULT false;` db.runSql(sql, addForeignKeysToJoinedChannels) } function addForeignKeysToJoinedChannels(err) { if (err) { cb(err) return } const sql = `ALTER TABLE joined_channels ADD CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES users (id), ADD CONSTRAINT fk_channel_name FOREIGN KEY (channel_name) REFERENCES channels (name);` db.runSql(sql, cb) } } exports.down = function(db, cb) { db.runSql(`ALTER TABLE joined_channels DROP CONSTRAINT fk_user_id, DROP CONSTRAINT fk_channel_name;`, removePermissions) function removePermissions(err) { if (err) { cb(err) return } db.runSql(`ALTER TABLE joined_channels DROP COLUMN kick, DROP COLUMN ban, DROP COLUMN change_topic, DROP COLUMN toggle_private, DROP COLUMN edit_permissions;`, dropChannels) } function dropChannels(err) { if (err) { cb(err) return } db.dropTable('channels', cb) } }
Update the database structure of the chat channels to be more flexible.
Update the database structure of the chat channels to be more flexible.
JavaScript
mit
ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery
--- +++ @@ -0,0 +1,96 @@ +exports.up = function(db, cb) { + db.runSql(` + CREATE TABLE channels ( + name citext PRIMARY KEY, + private boolean NOT NULL DEFAULT false, + high_traffic boolean NOT NULL DEFAULT false, + topic text, + password text + );`, addChannelNameConstraint) + + function addChannelNameConstraint(err) { + if (err) { + cb(err) + return + } + + const sql = `ALTER TABLE channels ADD CONSTRAINT + channel_name_length_check CHECK (length(name) <= 64);` + db.runSql(sql, createChannelNameIndex) + } + + function createChannelNameIndex(err) { + if (err) { + cb(err) + return + } + + db.addIndex('channels', 'channels_name_index', ['name'], + false /* unique */, insertShieldBatteryChannel) + } + + function insertShieldBatteryChannel(err) { + if (err) { + cb(err) + return + } + const sql = 'INSERT INTO channels (name) VALUES (\'ShieldBattery\');' + db.runSql(sql, addPermissionsToJoinedChannels) + } + + function addPermissionsToJoinedChannels(err) { + if (err) { + cb(err) + return + } + + const sql = `ALTER TABLE joined_channels + ADD COLUMN kick boolean NOT NULL DEFAULT false, + ADD COLUMN ban boolean NOT NULL DEFAULT false, + ADD COLUMN change_topic boolean NOT NULL DEFAULT false, + ADD COLUMN toggle_private boolean NOT NULL DEFAULT false, + ADD COLUMN edit_permissions boolean NOT NULL DEFAULT false;` + db.runSql(sql, addForeignKeysToJoinedChannels) + } + + function addForeignKeysToJoinedChannels(err) { + if (err) { + cb(err) + return + } + + const sql = `ALTER TABLE joined_channels + ADD CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES users (id), + ADD CONSTRAINT fk_channel_name FOREIGN KEY (channel_name) REFERENCES channels (name);` + db.runSql(sql, cb) + } +} + +exports.down = function(db, cb) { + db.runSql(`ALTER TABLE joined_channels + DROP CONSTRAINT fk_user_id, + DROP CONSTRAINT fk_channel_name;`, removePermissions) + + function removePermissions(err) { + if (err) { + cb(err) + return + } + + db.runSql(`ALTER TABLE joined_channels + DROP COLUMN kick, + DROP COLUMN ban, + DROP COLUMN change_topic, + DROP COLUMN toggle_private, + DROP COLUMN edit_permissions;`, dropChannels) + } + + function dropChannels(err) { + if (err) { + cb(err) + return + } + + db.dropTable('channels', cb) + } +}
851dc3c21b3b98d60965cda6368623a3750c3c22
client/webpack.common.config.js
client/webpack.common.config.js
// Common webpack configuration used by webpack.hot.config and webpack.rails.config. const path = require('path'); module.exports = { // the project dir context: __dirname, entry: ['jquery', 'jquery-ujs', './assets/javascripts/App'], resolve: { root: [ path.join(__dirname, 'scripts'), path.join(__dirname, 'assets/javascripts'), ], extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx', '.scss', '.css', 'config.js'], }, module: { loaders: [ // React is necessary for the client rendering: {test: require.resolve('react'), loader: 'expose?React'}, {test: require.resolve('jquery'), loader: 'expose?jQuery'}, ], }, };
// Common webpack configuration used by webpack.hot.config and webpack.rails.config. const path = require('path'); module.exports = { // the project dir context: __dirname, entry: ['jquery', 'jquery-ujs', './assets/javascripts/App'], resolve: { root: [ path.join(__dirname, 'scripts'), path.join(__dirname, 'assets/javascripts'), ], extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx', '.scss', '.css', 'config.js'], }, module: { loaders: [ // React is necessary for the client rendering: {test: require.resolve('react'), loader: 'expose?React'}, {test: require.resolve('jquery'), loader: 'expose?jQuery'}, {test: require.resolve('jquery'), loader: 'expose?$'}, ], }, };
Add additional jquery expose-loader to global $
Add additional jquery expose-loader to global $
JavaScript
mit
szyablitsky/react-webpack-rails-tutorial,yakovenkodenis/react-webpack-rails-tutorial,roxolan/react-webpack-rails-tutorial,janklimo/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,jeffthemaximum/jeffline,janklimo/react-webpack-rails-tutorial,suzukaze/react-webpack-rails-tutorial,thiagoc7/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,thiagoc7/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,justin808/react-webpack-rails-tutorial,StanBoyet/react-webpack-rails-tutorial,thiagoc7/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,suzukaze/react-webpack-rails-tutorial,szyablitsky/react-webpack-rails-tutorial,shakacode/react-webpack-rails-tutorial,szyablitsky/react-webpack-rails-tutorial,StanBoyet/react-webpack-rails-tutorial,shakacode/react-webpack-rails-tutorial,csterritt/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,jeffthemaximum/jeffline,szyablitsky/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,bsy/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,suzukaze/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,jeffthemaximum/Teachers-Dont-Pay-Jeff,yakovenkodenis/react-webpack-rails-tutorial,csterritt/react-webpack-rails-tutorial,roxolan/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,shakacode/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,suzukaze/react-webpack-rails-tutorial,thiagoc7/react-webpack-rails-tutorial,justin808/react-webpack-rails-tutorial,jeffthemaximum/jeffline,Johnnycus/react-webpack-rails-tutorial,roxolan/react-webpack-rails-tutorial,yakovenkodenis/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,roxolan/react-webpack-rails-tutorial,justin808/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,janklimo/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,bsy/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,justin808/react-webpack-rails-tutorial,janklimo/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,csterritt/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,shakacode/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,csterritt/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,mscienski/stpauls,yakovenkodenis/react-webpack-rails-tutorial,StanBoyet/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,jeffthemaximum/jeffline,bsy/react-webpack-rails-tutorial,mscienski/stpauls,Rvor/react-webpack-rails-tutorial,jeffthemaximum/jeffline,bsy/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,StanBoyet/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial
--- +++ @@ -21,6 +21,7 @@ // React is necessary for the client rendering: {test: require.resolve('react'), loader: 'expose?React'}, {test: require.resolve('jquery'), loader: 'expose?jQuery'}, + {test: require.resolve('jquery'), loader: 'expose?$'}, ], }, };
1ea2a51a7d944e5e0abf15ff23c959085178adf5
week-7/nums_commas.js
week-7/nums_commas.js
// Separate Numbers with Commas in JavaScript **Pairing Challenge** // I worked on this challenge with: Joseph Scott. // Pseudocode // turn number into string, split it into an array, & reverse it // iterate through array // push each value to new output array // if value's index+1 is divisible by 3, then push a comma // return joined reverse output array // Initial Solution function separateComma(number) { output = []; temp = number.toString().split('').reverse(); for (var i = 1; i <= temp.length; i++) { output.push(temp[i-1]); if (i%3 == 0) { output.push(','); }; }; if (output[output.length-1] === (",")) { output = output.slice(0,output.length-1); }; output = output.reverse().join(""); console.log(output); } // Refactored Solution function separateComma(number) { output = []; temp = number.toString().split('').reverse(); for (var start = 0; start<temp.length; start+=3) { output.push(temp.slice(start, start+3).reverse().join("")); }; output = output.reverse().join(","); console.log(output); }; // Your Own Tests (OPTIONAL) separateComma(1569743); separateComma(1); separateComma(10); separateComma(100); separateComma(1000); separateComma(10000); separateComma(100000); separateComma(1000000); separateComma(10000000); // Reflection // What was it like to approach the problem from the perspective of JavaScript? Did you approach the problem differently? // The original code was actually really similar to the initial Ruby solution, but using JavaScript syntax. The refactored version is not as short as the refactored Ruby version, but I think that it looks a lot more understandable because it uses a for loop, so you can clearly see what the code is doing. // // What did you learn about iterating over arrays in JavaScript? // I learned that you can't iterate through the items in the arrays. Instead, you need to iterate through the indexes. // // What was different about solving this problem in JavaScript? // Ruby has a lovely method called each_slice that takes slices of strings and array and you can use the map method to join each slice with a comma. JavaScript forces you to write your own version of each_slice, which really forces you to think in a different way. // // What built-in methods did you find to incorporate in your refactored solution? // Some of the new methods that we used included toString, split, reverse, slice, and join.
Add code and reflection for challenge.
Add code and reflection for challenge.
JavaScript
mit
svcastaneda/phase-0,svcastaneda/phase-0,svcastaneda/phase-0
--- +++ @@ -0,0 +1,74 @@ +// Separate Numbers with Commas in JavaScript **Pairing Challenge** + + +// I worked on this challenge with: Joseph Scott. + +// Pseudocode +// turn number into string, split it into an array, & reverse it +// iterate through array +// push each value to new output array +// if value's index+1 is divisible by 3, then push a comma +// return joined reverse output array + + +// Initial Solution +function separateComma(number) { + output = []; + temp = number.toString().split('').reverse(); + + for (var i = 1; i <= temp.length; i++) { + output.push(temp[i-1]); + if (i%3 == 0) { + output.push(','); + }; + }; + + if (output[output.length-1] === (",")) { + output = output.slice(0,output.length-1); + }; + + output = output.reverse().join(""); + + console.log(output); +} + + +// Refactored Solution +function separateComma(number) { + output = []; + temp = number.toString().split('').reverse(); + + for (var start = 0; start<temp.length; start+=3) { + output.push(temp.slice(start, start+3).reverse().join("")); + }; + + output = output.reverse().join(","); + console.log(output); +}; + + +// Your Own Tests (OPTIONAL) +separateComma(1569743); +separateComma(1); +separateComma(10); +separateComma(100); +separateComma(1000); +separateComma(10000); +separateComma(100000); +separateComma(1000000); +separateComma(10000000); + + + +// Reflection +// What was it like to approach the problem from the perspective of JavaScript? Did you approach the problem differently? +// The original code was actually really similar to the initial Ruby solution, but using JavaScript syntax. The refactored version is not as short as the refactored Ruby version, but I think that it looks a lot more understandable because it uses a for loop, so you can clearly see what the code is doing. +// +// What did you learn about iterating over arrays in JavaScript? +// I learned that you can't iterate through the items in the arrays. Instead, you need to iterate through the indexes. +// +// What was different about solving this problem in JavaScript? +// Ruby has a lovely method called each_slice that takes slices of strings and array and you can use the map method to join each slice with a comma. JavaScript forces you to write your own version of each_slice, which really forces you to think in a different way. +// +// What built-in methods did you find to incorporate in your refactored solution? +// Some of the new methods that we used included toString, split, reverse, slice, and join.
ee570a8136252524eadf44a52c2e502c1d5e24f1
index.js
index.js
const logger = require('./lib/logging') const make = require('./lib/make') const random = require('./lib/random') const utils = require('./lib/utils') module.exports = { logger, random, make, utils }
Add entry point for node package
Add entry point for node package
JavaScript
mpl-2.0
MozillaSecurity/octo
--- +++ @@ -0,0 +1,11 @@ +const logger = require('./lib/logging') +const make = require('./lib/make') +const random = require('./lib/random') +const utils = require('./lib/utils') + +module.exports = { + logger, + random, + make, + utils +}
d26711169f97188af5600ce48897e6332cb6b024
index.js
index.js
/** * Detect Electron renderer process, which is node, but we should * treat as a browser. */ if ((process || {}).type === 'renderer') { module.exports = require('./browser'); } else { module.exports = require('./node'); }
Add a switch to flip between electron and node
Add a switch to flip between electron and node
JavaScript
mit
visionmedia/debug,jabaz/debug,jabaz/debug
--- +++ @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if ((process || {}).type === 'renderer') { + module.exports = require('./browser'); +} else { + module.exports = require('./node'); +}
28637a6017dd9dd142d795e6600eb31b2f4a48fe
Easy/070_Clibing_Stairs.js
Easy/070_Clibing_Stairs.js
/** * @param {number} n * @return {number} */ var climbStairs = function(n) { var ans = [1,1,2]; for (var i = 3; i <= n; i++) { ans[i] = ans[i - 1] + ans[i - 2]; } return ans[n]; };
Add solution to question 70
Add solution to question 70
JavaScript
mit
Rhadow/leetcode,Rhadow/leetcode,Rhadow/leetcode,Rhadow/leetcode
--- +++ @@ -0,0 +1,13 @@ +/** + * @param {number} n + * @return {number} + */ +var climbStairs = function(n) { + var ans = [1,1,2]; + + for (var i = 3; i <= n; i++) { + ans[i] = ans[i - 1] + ans[i - 2]; + } + + return ans[n]; +};
d14ab90a3d1d459d277beb24d987fc634f7dcaf1
files/transportapi.js/0.0.1/transportapi.min.js
files/transportapi.js/0.0.1/transportapi.min.js
var TransportAPI=function(){var a="",b="",c="http://transportapi.com/v3",d=function(){return"app_id="+a+"&api_key="+b+"&callback=?"},e=function(a,b){return function(){$.ajax({url:a,dataType:"jsonp",timeout:1e4}).done(b).fail(function(){console.log("transportAPIcall FAIL. URL:"+a)})}};return{init:function(c,d){a=c,b=d},busStopsBBOX:function(a,b,f,g,h,i,j){var k=c+"/uk/bus/stops/bbox.json?minlon="+a+"&minlat="+b+"&maxlon="+f+"&maxlat="+g+"&page="+h+"&rpp="+i+"&"+d();return e(k,j)},trainStationsBBOX:function(a,b,f,g,h,i,j){var k=c+"/uk/train/stations/bbox.json?minlon="+a+"&minlat="+b+"&maxlon="+f+"&maxlat="+g+"&page="+h+"&rpp="+i+"&"+d();return e(k,j)},tubeStations:function(a,b){"all"==a&&(a="stations");var f=c+"/uk/tube/"+a+".json?"+d();return e(f,b)},tubePlatforms:function(a,b){var f=c+"/uk/tube/platforms/northern/"+a+".json?"+d();return e(f,b)},tubeStationsPerformance:function(a){var b=c+"/uk/tube/stations/performance.json?"+d();return e(b,a)},trainPerformance:function(a,b){var f=a.join(","),g=c+"/uk/train/stations_live_performance.json?stations="+f+"&station_detail=true&"+d();return console.log("calling trainPerformance:"+g),e(g,b)}}}();
Update project transportapi.js to 0.0.1
Update project transportapi.js to 0.0.1
JavaScript
mit
Swatinem/jsdelivr,walkermatt/jsdelivr,royswastik/jsdelivr,firulais/jsdelivr,bdukes/jsdelivr,ManrajGrover/jsdelivr,ntd/jsdelivr,labsvisual/jsdelivr,justincy/jsdelivr,alexmojaki/jsdelivr,firulais/jsdelivr,Sneezry/jsdelivr,garrypolley/jsdelivr,tomByrer/jsdelivr,dpellier/jsdelivr,yaplas/jsdelivr,bonbon197/jsdelivr,Metrakit/jsdelivr,petkaantonov/jsdelivr,dpellier/jsdelivr,firulais/jsdelivr,spud2451/jsdelivr,evilangelmd/jsdelivr,rtenshi/jsdelivr,stevelacy/jsdelivr,yaplas/jsdelivr,siscia/jsdelivr,ManrajGrover/jsdelivr,ramda/jsdelivr,megawac/jsdelivr,gregorypratt/jsdelivr,Valve/jsdelivr,jtblin/jsdelivr,cognitom/jsdelivr,MenZil/jsdelivr,ajibolam/jsdelivr,cesarmarinhorj/jsdelivr,rtenshi/jsdelivr,cognitom/jsdelivr,vvo/jsdelivr,jtblin/jsdelivr,ajkj/jsdelivr,fchasen/jsdelivr,markcarver/jsdelivr,cesarmarinhorj/jsdelivr,bonbon197/jsdelivr,walkermatt/jsdelivr,moay/jsdelivr,zhuwenxuan/qyerCDN,labsvisual/jsdelivr,Sneezry/jsdelivr,asimihsan/jsdelivr,MenZil/jsdelivr,Heark/jsdelivr,yyx990803/jsdelivr,ramda/jsdelivr,l3dlp/jsdelivr,Third9/jsdelivr,bonbon197/jsdelivr,ajkj/jsdelivr,alexmojaki/jsdelivr,jtblin/jsdelivr,siscia/jsdelivr,AdityaManohar/jsdelivr,cake654326/jsdelivr,Swatinem/jsdelivr,stevelacy/jsdelivr,tunnckoCore/jsdelivr,wallin/jsdelivr,leebyron/jsdelivr,garrypolley/jsdelivr,MenZil/jsdelivr,afghanistanyn/jsdelivr,Third9/jsdelivr,vebin/jsdelivr,evilangelmd/jsdelivr,Valve/jsdelivr,algolia/jsdelivr,Kingside/jsdelivr,Valve/jsdelivr,moay/jsdelivr,leebyron/jsdelivr,cesarmarinhorj/jsdelivr,ndamofli/jsdelivr,ntd/jsdelivr,alexmojaki/jsdelivr,Kingside/jsdelivr,gregorypratt/jsdelivr,firulais/jsdelivr,petkaantonov/jsdelivr,ajibolam/jsdelivr,ManrajGrover/jsdelivr,photonstorm/jsdelivr,fchasen/jsdelivr,oller/jsdelivr,anilanar/jsdelivr,royswastik/jsdelivr,dandv/jsdelivr,megawac/jsdelivr,tomByrer/jsdelivr,CTres/jsdelivr,spud2451/jsdelivr,MaxMillion/jsdelivr,RoberMac/jsdelivr,yyx990803/jsdelivr,ndamofli/jsdelivr,justincy/jsdelivr,ajibolam/jsdelivr,tunnckoCore/jsdelivr,dpellier/jsdelivr,anilanar/jsdelivr,towerz/jsdelivr,cesarmarinhorj/jsdelivr,justincy/jsdelivr,hubdotcom/jsdelivr,labsvisual/jsdelivr,megawac/jsdelivr,bdukes/jsdelivr,ndamofli/jsdelivr,cedricbousmanne/jsdelivr,garrypolley/jsdelivr,ajibolam/jsdelivr,cake654326/jsdelivr,asimihsan/jsdelivr,cognitom/jsdelivr,dnbard/jsdelivr,cedricbousmanne/jsdelivr,dpellier/jsdelivr,yaplas/jsdelivr,MaxMillion/jsdelivr,korusdipl/jsdelivr,dandv/jsdelivr,petkaantonov/jsdelivr,dnbard/jsdelivr,ajkj/jsdelivr,ntd/jsdelivr,dpellier/jsdelivr,ajibolam/jsdelivr,AdityaManohar/jsdelivr,Heark/jsdelivr,cedricbousmanne/jsdelivr,dnbard/jsdelivr,tunnckoCore/jsdelivr,RoberMac/jsdelivr,stevelacy/jsdelivr,siscia/jsdelivr,garrypolley/jsdelivr,evilangelmd/jsdelivr,CTres/jsdelivr,Valve/jsdelivr,vousk/jsdelivr,therob3000/jsdelivr,korusdipl/jsdelivr,anilanar/jsdelivr,Third9/jsdelivr,ndamofli/jsdelivr,wallin/jsdelivr,Swatinem/jsdelivr,fchasen/jsdelivr,moay/jsdelivr,anilanar/jsdelivr,rtenshi/jsdelivr,korusdipl/jsdelivr,labsvisual/jsdelivr,Heark/jsdelivr,markcarver/jsdelivr,rtenshi/jsdelivr,cognitom/jsdelivr,Third9/jsdelivr,wallin/jsdelivr,stevelacy/jsdelivr,Sneezry/jsdelivr,MichaelSL/jsdelivr,dnbard/jsdelivr,photonstorm/jsdelivr,zhuwenxuan/qyerCDN,markcarver/jsdelivr,zhuwenxuan/qyerCDN,hubdotcom/jsdelivr,Sneezry/jsdelivr,RoberMac/jsdelivr,walkermatt/jsdelivr,siscia/jsdelivr,gregorypratt/jsdelivr,ndamofli/jsdelivr,royswastik/jsdelivr,Metrakit/jsdelivr,megawac/jsdelivr,MaxMillion/jsdelivr,therob3000/jsdelivr,CTres/jsdelivr,oller/jsdelivr,cedricbousmanne/jsdelivr,MenZil/jsdelivr,therob3000/jsdelivr,MichaelSL/jsdelivr,ManrajGrover/jsdelivr,ntd/jsdelivr,AdityaManohar/jsdelivr,vousk/jsdelivr,afghanistanyn/jsdelivr,towerz/jsdelivr,oller/jsdelivr,korusdipl/jsdelivr,towerz/jsdelivr,oller/jsdelivr,yaplas/jsdelivr,Metrakit/jsdelivr,spud2451/jsdelivr,CTres/jsdelivr,MichaelSL/jsdelivr,afghanistanyn/jsdelivr,photonstorm/jsdelivr,afghanistanyn/jsdelivr,garrypolley/jsdelivr,towerz/jsdelivr,cake654326/jsdelivr,anilanar/jsdelivr,vebin/jsdelivr,justincy/jsdelivr,tomByrer/jsdelivr,cognitom/jsdelivr,bdukes/jsdelivr,Third9/jsdelivr,hubdotcom/jsdelivr,RoberMac/jsdelivr,asimihsan/jsdelivr,jtblin/jsdelivr,Swatinem/jsdelivr,vousk/jsdelivr,AdityaManohar/jsdelivr,Metrakit/jsdelivr,cake654326/jsdelivr,vebin/jsdelivr,yaplas/jsdelivr,royswastik/jsdelivr,moay/jsdelivr,MichaelSL/jsdelivr,MaxMillion/jsdelivr,stevelacy/jsdelivr,dandv/jsdelivr,l3dlp/jsdelivr,bonbon197/jsdelivr,fchasen/jsdelivr,firulais/jsdelivr,Kingside/jsdelivr,Heark/jsdelivr,RoberMac/jsdelivr,MichaelSL/jsdelivr,moay/jsdelivr,justincy/jsdelivr,ajkj/jsdelivr,ntd/jsdelivr,tunnckoCore/jsdelivr,l3dlp/jsdelivr,evilangelmd/jsdelivr,l3dlp/jsdelivr,cesarmarinhorj/jsdelivr,zhuwenxuan/qyerCDN,Kingside/jsdelivr,vvo/jsdelivr,yyx990803/jsdelivr,spud2451/jsdelivr,royswastik/jsdelivr,leebyron/jsdelivr,vebin/jsdelivr,gregorypratt/jsdelivr,towerz/jsdelivr,vvo/jsdelivr,ramda/jsdelivr,AdityaManohar/jsdelivr,petkaantonov/jsdelivr,alexmojaki/jsdelivr,hubdotcom/jsdelivr,asimihsan/jsdelivr,Valve/jsdelivr,Swatinem/jsdelivr,wallin/jsdelivr,markcarver/jsdelivr,vvo/jsdelivr,jtblin/jsdelivr,markcarver/jsdelivr,labsvisual/jsdelivr,vousk/jsdelivr,ramda/jsdelivr,walkermatt/jsdelivr,asimihsan/jsdelivr,MaxMillion/jsdelivr,algolia/jsdelivr,evilangelmd/jsdelivr,cake654326/jsdelivr,rtenshi/jsdelivr,fchasen/jsdelivr,CTres/jsdelivr,spud2451/jsdelivr,siscia/jsdelivr,gregorypratt/jsdelivr,cedricbousmanne/jsdelivr,tomByrer/jsdelivr,korusdipl/jsdelivr,Heark/jsdelivr,Sneezry/jsdelivr,algolia/jsdelivr,oller/jsdelivr,algolia/jsdelivr,l3dlp/jsdelivr,megawac/jsdelivr,hubdotcom/jsdelivr,bonbon197/jsdelivr,therob3000/jsdelivr,tunnckoCore/jsdelivr,MenZil/jsdelivr,wallin/jsdelivr,therob3000/jsdelivr,vvo/jsdelivr,ManrajGrover/jsdelivr,Kingside/jsdelivr,yyx990803/jsdelivr,dandv/jsdelivr,dandv/jsdelivr,photonstorm/jsdelivr,leebyron/jsdelivr,ajkj/jsdelivr,yyx990803/jsdelivr,walkermatt/jsdelivr,vebin/jsdelivr,Metrakit/jsdelivr,vousk/jsdelivr,alexmojaki/jsdelivr,bdukes/jsdelivr,leebyron/jsdelivr,afghanistanyn/jsdelivr,dnbard/jsdelivr
--- +++ @@ -0,0 +1 @@ +var TransportAPI=function(){var a="",b="",c="http://transportapi.com/v3",d=function(){return"app_id="+a+"&api_key="+b+"&callback=?"},e=function(a,b){return function(){$.ajax({url:a,dataType:"jsonp",timeout:1e4}).done(b).fail(function(){console.log("transportAPIcall FAIL. URL:"+a)})}};return{init:function(c,d){a=c,b=d},busStopsBBOX:function(a,b,f,g,h,i,j){var k=c+"/uk/bus/stops/bbox.json?minlon="+a+"&minlat="+b+"&maxlon="+f+"&maxlat="+g+"&page="+h+"&rpp="+i+"&"+d();return e(k,j)},trainStationsBBOX:function(a,b,f,g,h,i,j){var k=c+"/uk/train/stations/bbox.json?minlon="+a+"&minlat="+b+"&maxlon="+f+"&maxlat="+g+"&page="+h+"&rpp="+i+"&"+d();return e(k,j)},tubeStations:function(a,b){"all"==a&&(a="stations");var f=c+"/uk/tube/"+a+".json?"+d();return e(f,b)},tubePlatforms:function(a,b){var f=c+"/uk/tube/platforms/northern/"+a+".json?"+d();return e(f,b)},tubeStationsPerformance:function(a){var b=c+"/uk/tube/stations/performance.json?"+d();return e(b,a)},trainPerformance:function(a,b){var f=a.join(","),g=c+"/uk/train/stations_live_performance.json?stations="+f+"&station_detail=true&"+d();return console.log("calling trainPerformance:"+g),e(g,b)}}}();
b6ced965ce852c91998b9b9fd08c8120ad5f973c
index.js
index.js
var postcss = require('postcss'), color = require('color'); module.exports = postcss.plugin('postcss-lowvision', function () { return function (css) { css.walkDecls('color', function (decl) { var val = decl.value; var rgb = color(val); rgb = rgb.rgbArray(); decl.value = transparent; decl.cloneAfter({ prop: 'text-shadow', value: '0 0 5px rgba(' + rgb[0] + ', ' + rgb[1] + ', '+ rgb[2] + ', ' + '0.5)' }); }); }; });
var postcss = require('postcss'), color = require('color'); module.exports = postcss.plugin('postcss-lowvision', function () { return function (css) { css.walkDecls('color', function (decl) { var val = decl.value; var rgb = color(val); rgb = rgb.rgbArray(); decl.value = 'transparent'; decl.cloneAfter({ prop: 'text-shadow', value: '0 0 5px rgba(' + rgb[0] + ', ' + rgb[1] + ', '+ rgb[2] + ', ' + '0.5)' }); }); }; });
Fix error - transparent not defined
Fix error - transparent not defined
JavaScript
mit
keukenrolletje/postcss-lowvision
--- +++ @@ -8,7 +8,7 @@ var val = decl.value; var rgb = color(val); rgb = rgb.rgbArray(); - decl.value = transparent; + decl.value = 'transparent'; decl.cloneAfter({ prop: 'text-shadow', value: '0 0 5px rgba(' + rgb[0] + ', ' + rgb[1] + ', '+ rgb[2] + ', ' + '0.5)' }); });
b615be2f238a488b17a394d0b2d0572541164c95
ui/src/kapacitor/components/LogsTable.js
ui/src/kapacitor/components/LogsTable.js
import React, {PropTypes} from 'react' import InfiniteScroll from 'shared/components/InfiniteScroll' import LogsTableRow from 'src/kapacitor/components/LogsTableRow' const LogsTable = ({logs, onToggleExpandLog}) => <div className="logs-table--container"> <div className="logs-table--header"> <h2 className="panel-title">Logs</h2> </div> <div className="logs-table--panel fancy-scroll--kapacitor"> {logs.length ? <InfiniteScroll className="logs-table" itemHeight={87} items={logs.map((log, i) => <LogsTableRow key={log.key} logItem={log} index={i} onToggleExpandLog={onToggleExpandLog} /> )} /> : <div className="page-spinner" />} </div> </div> const {arrayOf, func, shape, string} = PropTypes LogsTable.propTypes = { logs: arrayOf( shape({ key: string.isRequired, ts: string.isRequired, lvl: string.isRequired, msg: string.isRequired, }) ).isRequired, onToggleExpandLog: func.isRequired, } export default LogsTable
import React, {PropTypes} from 'react' import LogsTableRow from 'src/kapacitor/components/LogsTableRow' import FancyScrollbar from 'src/shared/components/FancyScrollbar' const numLogsToRender = 200 const LogsTable = ({logs, onToggleExpandLog}) => <div className="logs-table--container"> <div className="logs-table--header"> <h2 className="panel-title">{`${numLogsToRender} Most Recent Logs`}</h2> </div> <FancyScrollbar autoHide={false} className="logs-table--panel fancy-scroll--kapacitor" > {logs .slice(0, numLogsToRender) .map((log, i) => <LogsTableRow key={log.key} logItem={log} index={i} onToggleExpandLog={onToggleExpandLog} /> )} </FancyScrollbar> </div> const {arrayOf, func, shape, string} = PropTypes LogsTable.propTypes = { logs: arrayOf( shape({ key: string.isRequired, ts: string.isRequired, lvl: string.isRequired, msg: string.isRequired, }) ).isRequired, onToggleExpandLog: func.isRequired, } export default LogsTable
Remove infinite scroll from logs table and render only 200 most recent logs
Remove infinite scroll from logs table and render only 200 most recent logs
JavaScript
mit
li-ang/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdata/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb
--- +++ @@ -1,29 +1,30 @@ import React, {PropTypes} from 'react' -import InfiniteScroll from 'shared/components/InfiniteScroll' import LogsTableRow from 'src/kapacitor/components/LogsTableRow' +import FancyScrollbar from 'src/shared/components/FancyScrollbar' + +const numLogsToRender = 200 const LogsTable = ({logs, onToggleExpandLog}) => <div className="logs-table--container"> <div className="logs-table--header"> - <h2 className="panel-title">Logs</h2> + <h2 className="panel-title">{`${numLogsToRender} Most Recent Logs`}</h2> </div> - <div className="logs-table--panel fancy-scroll--kapacitor"> - {logs.length - ? <InfiniteScroll - className="logs-table" - itemHeight={87} - items={logs.map((log, i) => - <LogsTableRow - key={log.key} - logItem={log} - index={i} - onToggleExpandLog={onToggleExpandLog} - /> - )} + <FancyScrollbar + autoHide={false} + className="logs-table--panel fancy-scroll--kapacitor" + > + {logs + .slice(0, numLogsToRender) + .map((log, i) => + <LogsTableRow + key={log.key} + logItem={log} + index={i} + onToggleExpandLog={onToggleExpandLog} /> - : <div className="page-spinner" />} - </div> + )} + </FancyScrollbar> </div> const {arrayOf, func, shape, string} = PropTypes
37ea3cd02080533bb1fd8f9794f06eef83a6f4eb
example/MultiModule.js
example/MultiModule.js
/** * This is a class/module. * @class class1 * @module module1 */ /** * This is another class/module. * @class class2 * @module module2 */ /** * This is a module that's a private class. * @class class3 * @module module3 */ /** * This is another something. * @class class4 * @module module4 */ /** * This module / class has matching names and stuff. * @class mything * @module mything */
Add more simple modules/classes to test example
Add more simple modules/classes to test example
JavaScript
mit
kevinlacotaco/yuidoc-bootstrap-theme,wyantb/yuidoc-bootstrap-theme,naturalatlas/yuidoc-lucid-theme,kevinlacotaco/yuidoc-bootstrap-theme,wyantb/yuidoc-bootstrap-theme,wyantb/yuidoc-bootstrap-theme,kevinlacotaco/yuidoc-bootstrap-theme,naturalatlas/yuidoc-lucid-theme
--- +++ @@ -0,0 +1,30 @@ + +/** + * This is a class/module. + * @class class1 + * @module module1 + */ + +/** + * This is another class/module. + * @class class2 + * @module module2 + */ + +/** + * This is a module that's a private class. + * @class class3 + * @module module3 + */ + +/** + * This is another something. + * @class class4 + * @module module4 + */ + +/** + * This module / class has matching names and stuff. + * @class mything + * @module mything + */
d3371d4c6eff5c69ff3c904f76541b3c6277355a
src/util/find-element-in-registry.js
src/util/find-element-in-registry.js
import customElements from '../native/custom-elements'; export default function (elem) { const tagName = elem.tagName; if (!tagName) { return; } const tagNameLc = tagName.toLowerCase(); const tagNameDefinition = customElements.get(tagNameLc); if (tagNameDefinition) { return tagNameDefinition; } const isAttribute = elem.getAttribute('is'); const isAttributeDefinition = customElements.get(isAttribute); if (isAttributeDefinition && isAttributeDefinition.extends === tagNameLc) { return isAttributeDefinition; } }
Add a utility for getting an element definition from the registry base on the element itself.
Add a utility for getting an element definition from the registry base on the element itself.
JavaScript
mit
chrisdarroch/skatejs,chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs,skatejs/skatejs
--- +++ @@ -0,0 +1,23 @@ +import customElements from '../native/custom-elements'; + +export default function (elem) { + const tagName = elem.tagName; + + if (!tagName) { + return; + } + + const tagNameLc = tagName.toLowerCase(); + const tagNameDefinition = customElements.get(tagNameLc); + + if (tagNameDefinition) { + return tagNameDefinition; + } + + const isAttribute = elem.getAttribute('is'); + const isAttributeDefinition = customElements.get(isAttribute); + + if (isAttributeDefinition && isAttributeDefinition.extends === tagNameLc) { + return isAttributeDefinition; + } +}
51fab14d010e8187d2691f205439722faac03837
test/addCreateAndModified-test.js
test/addCreateAndModified-test.js
var vows = require('vows') , assert = require('assert') , mongoose = require('mongoose') , timestamp = require('../lib/addCreatedAndModified') , util = require('util') // DB setup mongoose.connect('mongodb://localhost/mongoose_troop') // Setting up test schema var Schema = mongoose.Schema , ObjectId = Schema.ObjectId var BlogPost = new Schema({ author : String , title : String , body : String }) // Registering the timestamp plugin with mongoose // Note: Must be defined before creating schema object mongoose.plugin(timestamp,{debug: true}) var Blog = mongoose.model('BlogPost',BlogPost) vows.describe('Add create and modified').addBatch({ 'when this plugin registered by default':{ topic: function(){ var blog = new Blog() blog.author = "butu5" blog.title = "Mongoose troops!!! timestamp plugin " blog.save(this.callback) }, 'it should create created and modified attribute': function(topic){ assert.equal(util.isDate(topic.created),true) assert.equal(util.isDate(topic.modified),true) } } }).run()
Test case for addCreateAndModified plugin
Test case for addCreateAndModified plugin
JavaScript
mit
tblobaum/mongoose-troop,janez89/mongoose-utilities,iliakan/mongoose-troop
--- +++ @@ -0,0 +1,40 @@ +var vows = require('vows') + , assert = require('assert') + , mongoose = require('mongoose') + , timestamp = require('../lib/addCreatedAndModified') + , util = require('util') + +// DB setup +mongoose.connect('mongodb://localhost/mongoose_troop') + +// Setting up test schema +var Schema = mongoose.Schema + , ObjectId = Schema.ObjectId + +var BlogPost = new Schema({ + author : String + , title : String + , body : String +}) + +// Registering the timestamp plugin with mongoose +// Note: Must be defined before creating schema object +mongoose.plugin(timestamp,{debug: true}) + +var Blog = mongoose.model('BlogPost',BlogPost) + +vows.describe('Add create and modified').addBatch({ + 'when this plugin registered by default':{ + topic: function(){ + var blog = new Blog() + blog.author = "butu5" + blog.title = "Mongoose troops!!! timestamp plugin " + blog.save(this.callback) + }, + + 'it should create created and modified attribute': function(topic){ + assert.equal(util.isDate(topic.created),true) + assert.equal(util.isDate(topic.modified),true) + } + } +}).run()
943e66b8b52cadeb4959378b608cc91ed2d28cb4
lib/natural/util/stopwords_zh.js
lib/natural/util/stopwords_zh.js
/* Copyright (c) 2011, David Przybilla, Chris Umbel 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. */ // a list of commonly used words that have little meaning and can be excluded // from analysis. var words = [ '的','地','得','和','跟', '与','及','向','并','等', '更','已','含','做','我', '你','他','她','们','某', '该','各','每','这','那', '哪','什','么','谁','年', '月','日','时','分','秒', '几','多','来','在','就', '又','很','呢','吧','吗', '了','嘛','哇','儿','哼', '啊','嗯','是','着','都', '不','说','也','看','把', '还','个','有','小','到', '一','为','中','于','对', '会','之','第','此','或', '共','按','请' ]; // tell the world about the noise words. exports.words = words;
Add stopwords which have little meaning and can be excluded from analysis for Chinese.
Add stopwords which have little meaning and can be excluded from analysis for Chinese.
JavaScript
mit
ahmedshuhel/natural,kjhenner/natural,PTaylour/natural,NaturalNode/natural,mamaral/natural,Hugo-ter-Doest/natural,itamayo/natural,mcanthony/natural,walkingdoctors/natural,dpraimeyuu/natural,levy5674/natural,moos/natural,PMSI-AlignAlytics/natural,karimsa/natural,Logicify/natural,polymaths/natural
--- +++ @@ -0,0 +1,45 @@ +/* +Copyright (c) 2011, David Przybilla, Chris Umbel + +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. +*/ + +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = [ + '的','地','得','和','跟', + '与','及','向','并','等', + '更','已','含','做','我', + '你','他','她','们','某', + '该','各','每','这','那', + '哪','什','么','谁','年', + '月','日','时','分','秒', + '几','多','来','在','就', + '又','很','呢','吧','吗', + '了','嘛','哇','儿','哼', + '啊','嗯','是','着','都', + '不','说','也','看','把', + '还','个','有','小','到', + '一','为','中','于','对', + '会','之','第','此','或', + '共','按','请' +]; + +// tell the world about the noise words. +exports.words = words;
846a954d365408a8571c30c22e88beb3c91bd949
context-test.js
context-test.js
var Buffer = require('buffer').Buffer; var readline = require('readline'); var gss = require('./index.js'); var creds = gss.acquireCredential(null, 0, [gss.KRB5_MECHANISM], gss.C_INITIATE); var zsrName = gss.importName('host@zsr.mit.edu', gss.C_NT_HOSTBASED_SERVICE); var context = gss.createInitiator(creds, zsrName, { flags: gss.C_MUTUAL_FLAG | gss.C_CONF_FLAG | gss.C_INTEG_FLAG | gss.C_REPLAY_FLAG | gss.C_SEQUENCE_FLAG, mechanism: gss.KRB5_MECHANISM, }); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); function step(token) { console.log(context.initSecContext(token).toString('base64')); console.log('isEstablished', context.isEstablished()); if (context.isEstablished()) { console.log('flags', context.flags()); rl.close(); } else { rl.question('next token? ', function(answer) { step(new Buffer(answer, 'base64')); }); } }; step(null);
Add a test program for an initiator context
Add a test program for an initiator context
JavaScript
mit
roost-im/node-gss,roost-im/node-gss,roost-im/node-gss
--- +++ @@ -0,0 +1,32 @@ +var Buffer = require('buffer').Buffer; +var readline = require('readline'); + +var gss = require('./index.js'); + +var creds = gss.acquireCredential(null, 0, + [gss.KRB5_MECHANISM], gss.C_INITIATE); +var zsrName = gss.importName('host@zsr.mit.edu', gss.C_NT_HOSTBASED_SERVICE); +var context = gss.createInitiator(creds, zsrName, { + flags: gss.C_MUTUAL_FLAG | gss.C_CONF_FLAG | + gss.C_INTEG_FLAG | gss.C_REPLAY_FLAG | gss.C_SEQUENCE_FLAG, + mechanism: gss.KRB5_MECHANISM, +}); + +var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); + +function step(token) { + console.log(context.initSecContext(token).toString('base64')); + console.log('isEstablished', context.isEstablished()); + if (context.isEstablished()) { + console.log('flags', context.flags()); + rl.close(); + } else { + rl.question('next token? ', function(answer) { + step(new Buffer(answer, 'base64')); + }); + } +}; +step(null);
16e3b3de48b4ee6d391d647ab49dc92e3347204c
eloquent_js/chapter15/ch15_ex03.js
eloquent_js/chapter15/ch15_ex03.js
function asTabs(node) { for (let child of node.children) { let label = child.getAttribute("data-tabname"); let button = document.createElement("button"); button.appendChild(document.createTextNode(label)); button.addEventListener( "click", event => changeTab(event.target.firstChild.nodeValue) ); child.style.display = "none"; tabs.push({ button, label, content: child }); } changeTab(tabs[0].label); // Insert buttons for (let i = tabs.length - 1; i >= 0; --i) { node.prepend(tabs[i].button); } } function changeTab(label) { for (let tab of tabs) { if (tab.label == label) { tab.content.style.display = "block"; tab.button.style.background = "red"; } else { tab.content.style.display = "none"; tab.button.style.background = ""; } } } let tabs = [];
Add chapter 15, exercise 3
Add chapter 15, exercise 3
JavaScript
mit
bewuethr/ctci
--- +++ @@ -0,0 +1,39 @@ +function asTabs(node) { + for (let child of node.children) { + let label = child.getAttribute("data-tabname"); + let button = document.createElement("button"); + button.appendChild(document.createTextNode(label)); + button.addEventListener( + "click", + event => changeTab(event.target.firstChild.nodeValue) + ); + child.style.display = "none"; + tabs.push({ + button, + label, + content: child + }); + } + + changeTab(tabs[0].label); + + // Insert buttons + for (let i = tabs.length - 1; i >= 0; --i) { + node.prepend(tabs[i].button); + } +} + +function changeTab(label) { + for (let tab of tabs) { + if (tab.label == label) { + tab.content.style.display = "block"; + tab.button.style.background = "red"; + } + else { + tab.content.style.display = "none"; + tab.button.style.background = ""; + } + } +} + +let tabs = [];
5b98216ecbcff1bd99ffd8f98630a069d4ad3f2b
test/reporters/console-gjs.js
test/reporters/console-gjs.js
'use strict'; var deferred = require('deferred'); module.exports = function (t, a) { var report = [{ message: 'Lorem ipsum', character: 1, line: 1 }], invoked; report.src = 'Lorem ipsum'; report.options = {}; t(deferred({ 'foo': report }), { log: function (str) { a(typeof str, 'string', "Log string"); invoked = true; } }).end(); a(invoked, true); };
Test for gjs style report
Test for gjs style report
JavaScript
mit
medikoo/xlint,medikoo/xlint
--- +++ @@ -0,0 +1,14 @@ +'use strict'; + +var deferred = require('deferred'); + +module.exports = function (t, a) { + var report = [{ message: 'Lorem ipsum', character: 1, line: 1 }], invoked; + report.src = 'Lorem ipsum'; + report.options = {}; + t(deferred({ 'foo': report }), { log: function (str) { + a(typeof str, 'string', "Log string"); + invoked = true; + } }).end(); + a(invoked, true); +};
54cf7c53c2077520011bbc9f7c6e95e581cea2be
test/components/FactionSwitch.spec.js
test/components/FactionSwitch.spec.js
import { React, sinon, assert, expect, TestUtils } from '../test_exports'; import FactionSwitch from '../../src/js/components/FactionSwitch'; import * as MapActions from '../../src/js/actions/MapActions'; const props = { ontext: 'radiant', offtext: 'dire', isRadiant: true, switchFaction: MapActions.switchFaction } describe('FactionSwitch component', () => { let sandbox, faction, container, elementsContainer, switchHalf, switchHandle; let findDOMWithClass = TestUtils.findRenderedDOMComponentWithClass; let scryDOMWithClass = TestUtils.scryRenderedDOMComponentsWithClass; beforeEach(() => { sandbox = sinon.sandbox.create(); faction = TestUtils.renderIntoDocument(<FactionSwitch {...props}/>); container = findDOMWithClass(faction, 'faction-switch'); elementsContainer = findDOMWithClass(faction, 'faction-switch-elements'); switchHalf = scryDOMWithClass(faction, 'switch-half'); switchHandle = findDOMWithClass(faction, 'switch-handle'); }); afterEach(() => { sandbox.restore(); }); it('should render into the DOM', () => { expect(container).to.not.equal(null); expect(elementsContainer).to.not.equal(null); expect(switchHalf.length).to.equal(2); expect(switchHandle).to.not.equal(null); }); it('should call switchFaction when clicked', () => { let switchActionStub = sandbox.stub(faction.props, "switchFaction"); TestUtils.Simulate.click(container); expect(switchActionStub).to.have.been.called; }); });
Create test with clicking simulation
Create test with clicking simulation
JavaScript
mit
kusera/sentrii,kusera/sentrii
--- +++ @@ -0,0 +1,42 @@ +import { React, sinon, assert, expect, TestUtils } from '../test_exports'; +import FactionSwitch from '../../src/js/components/FactionSwitch'; +import * as MapActions from '../../src/js/actions/MapActions'; + +const props = { + ontext: 'radiant', + offtext: 'dire', + isRadiant: true, + switchFaction: MapActions.switchFaction +} + +describe('FactionSwitch component', () => { + let sandbox, faction, container, elementsContainer, switchHalf, switchHandle; + let findDOMWithClass = TestUtils.findRenderedDOMComponentWithClass; + let scryDOMWithClass = TestUtils.scryRenderedDOMComponentsWithClass; + + beforeEach(() => { + sandbox = sinon.sandbox.create(); + faction = TestUtils.renderIntoDocument(<FactionSwitch {...props}/>); + container = findDOMWithClass(faction, 'faction-switch'); + elementsContainer = findDOMWithClass(faction, 'faction-switch-elements'); + switchHalf = scryDOMWithClass(faction, 'switch-half'); + switchHandle = findDOMWithClass(faction, 'switch-handle'); + }); + + afterEach(() => { + sandbox.restore(); + }); + + it('should render into the DOM', () => { + expect(container).to.not.equal(null); + expect(elementsContainer).to.not.equal(null); + expect(switchHalf.length).to.equal(2); + expect(switchHandle).to.not.equal(null); + }); + + it('should call switchFaction when clicked', () => { + let switchActionStub = sandbox.stub(faction.props, "switchFaction"); + TestUtils.Simulate.click(container); + expect(switchActionStub).to.have.been.called; + }); +});
1c37233c9af23749fea11b52423c64f18fd0be1a
migrations/20171228201331_agenda-tags-image.js
migrations/20171228201331_agenda-tags-image.js
exports.up = function (knex, Promise) { return Promise.all([ knex.schema.table('agenda', function (table) { table.string('image'); }), knex.schema.createTable('tags', function (table) { table.increments('id').notNullable().primary(); table.string('tag').notNullable(); }), knex.schema.createTable('agenda_tags', function (table) { table.integer('agenda').notNullable(); table.integer('tag').notNullable(); }), ]); }; exports.down = function (knex, Promise) { return Promise.all([ knex.schema.dropTable('tags'), knex.schema.dropTable('agenda_tags'), knex.schema.table('agenda', function (table) { table.dropColumn('image'); }), ]); };
Add migration file for agenda tags and image
Add migration file for agenda tags and image
JavaScript
mit
voxpelli/node-one-page,voxpelli/node-one-page
--- +++ @@ -0,0 +1,28 @@ + +exports.up = function (knex, Promise) { + return Promise.all([ + knex.schema.table('agenda', function (table) { + table.string('image'); + }), + + knex.schema.createTable('tags', function (table) { + table.increments('id').notNullable().primary(); + table.string('tag').notNullable(); + }), + + knex.schema.createTable('agenda_tags', function (table) { + table.integer('agenda').notNullable(); + table.integer('tag').notNullable(); + }), + ]); +}; + +exports.down = function (knex, Promise) { + return Promise.all([ + knex.schema.dropTable('tags'), + knex.schema.dropTable('agenda_tags'), + knex.schema.table('agenda', function (table) { + table.dropColumn('image'); + }), + ]); +};
dfa25e23b43c3464b8cd18fc70f5bd69e8e9644d
test-fixtures/migration-data.js
test-fixtures/migration-data.js
export const round1 = { 'Bridge.currentRound': '1', 'Bridge.maker': '0', 'Bridge.players': '[{"bid":null,"win":null,"_buffer":{"lastRound":null,"combo":null,"miss":null,"maxCombo":null,"sum":null},"score":[],"name":"Jonathan"},{"bid":null,"win":null,"_buffer":{"lastRound":null,"combo":null,"miss":null,"maxCombo":null,"sum":null},"score":[],"name":"Helen"},{"bid":null,"win":null,"_buffer":{"lastRound":null,"combo":null,"miss":null,"maxCombo":null,"sum":null},"score":[],"name":"Humphrey"},{"bid":null,"win":null,"_buffer":{"lastRound":null,"combo":null,"miss":null,"maxCombo":null,"sum":null},"score":[],"name":"Margery"}]', 'Bridge.state': '1', 'Bridge.totalRounds': '13' } export const round2 = { 'Bridge.currentRound':'2', 'Bridge.maker':'1', 'Bridge.players':'[{"bid":null,"win":null,"_buffer":{"lastRound":1,"combo":1,"miss":0,"maxCombo":0,"sum":11},"score":[11],"name":"Jonathan"},{"bid":null,"win":null,"_buffer":{"lastRound":1,"combo":0,"miss":1,"maxCombo":0,"sum":-1},"score":[-1],"name":"Helen"},{"bid":null,"win":null,"_buffer":{"lastRound":1,"combo":0,"miss":1,"maxCombo":0,"sum":-1},"score":[-1],"name":"Humphrey"},{"bid":null,"win":null,"_buffer":{"lastRound":1,"combo":0,"miss":1,"maxCombo":0,"sum":-1},"score":[-1],"name":"Margery"}]', 'Bridge.state':'1', 'Bridge.totalRounds':'13' }
Add test fixtures for data in v1.0.0
Add test fixtures for data in v1.0.0
JavaScript
mit
Holi0317/bridge-calc,Holi0317/bridge-calc,Holi0317/bridge-calc
--- +++ @@ -0,0 +1,15 @@ +export const round1 = { + 'Bridge.currentRound': '1', + 'Bridge.maker': '0', + 'Bridge.players': '[{"bid":null,"win":null,"_buffer":{"lastRound":null,"combo":null,"miss":null,"maxCombo":null,"sum":null},"score":[],"name":"Jonathan"},{"bid":null,"win":null,"_buffer":{"lastRound":null,"combo":null,"miss":null,"maxCombo":null,"sum":null},"score":[],"name":"Helen"},{"bid":null,"win":null,"_buffer":{"lastRound":null,"combo":null,"miss":null,"maxCombo":null,"sum":null},"score":[],"name":"Humphrey"},{"bid":null,"win":null,"_buffer":{"lastRound":null,"combo":null,"miss":null,"maxCombo":null,"sum":null},"score":[],"name":"Margery"}]', + 'Bridge.state': '1', + 'Bridge.totalRounds': '13' +} + +export const round2 = { + 'Bridge.currentRound':'2', + 'Bridge.maker':'1', + 'Bridge.players':'[{"bid":null,"win":null,"_buffer":{"lastRound":1,"combo":1,"miss":0,"maxCombo":0,"sum":11},"score":[11],"name":"Jonathan"},{"bid":null,"win":null,"_buffer":{"lastRound":1,"combo":0,"miss":1,"maxCombo":0,"sum":-1},"score":[-1],"name":"Helen"},{"bid":null,"win":null,"_buffer":{"lastRound":1,"combo":0,"miss":1,"maxCombo":0,"sum":-1},"score":[-1],"name":"Humphrey"},{"bid":null,"win":null,"_buffer":{"lastRound":1,"combo":0,"miss":1,"maxCombo":0,"sum":-1},"score":[-1],"name":"Margery"}]', + 'Bridge.state':'1', + 'Bridge.totalRounds':'13' +}
ad31d7b15df5c18f922d026a62ea7cce6056054e
website/app/application/services/prov-template.js
website/app/application/services/prov-template.js
Application.Services.factory("provTemplate", [provTemplate]); function provTemplate() { var service = { _handleProcessStep: function(templates, filesRequired) { if (templates.length !== 0) { return templates[0].template_name; } // templates.length === 0, so check filesRequired if (filesRequired) { return "files"; } // Nothing matches, so... return ""; }, _nextTemplateStep: function(currentStep, templates, filesRequired) { if (currentStep == "files") { // We are on the files step which is the last step for these // templates. return ""; } if (currentStep === "process") { return service._handleProcessStep(templates, filesRequired); } var i = _.indexOf(templates, function(template) { return template.template_name == currentStep; }); console.log("i = " + i); if (i == -1) { // Couldn't find currentStep. This is an error // on the api users part. We could check files, // but better to just say no. return ""; } if (i+1 > templates.length) { // No more templates, check if we should ask for files. if (filesRequired) { return "files"; } return ""; } return templates[i+1].template_name; }, _checkFromOutputs: function(currentStep, template) { next = service._nextTemplateStep(currentStep, template.output_templates, template.required_output_files); if (next !== "") { return { stepType: "output", currentStep: next }; } return { stepType: "done", currentStep: "done" }; }, _checkFromInputs: function(currentStep, template) { next = service._nextTemplateStep(currentStep, template.input_templates, template.required_input_files); if (next !== "") { return { stepType: "input", currentStep: next }; } return service._checkFromOutputs(currentStep, template); }, nextStep: function(currentType, currentStep, template) { console.log("currentType = " + currentType); if (currentType == "process" || currentType == "input") { return service._checkFromInputs(currentStep, template); } else if (currentType == "output") { return service._checkFromOutputs(currentStep, template); } else { return { stepType: "done", currentStep: "done" }; } } }; return service; }
Add service for determining things to do with templates.
Add service for determining things to do with templates.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
--- +++ @@ -0,0 +1,100 @@ +Application.Services.factory("provTemplate", [provTemplate]); + +function provTemplate() { + var service = { + + _handleProcessStep: function(templates, filesRequired) { + if (templates.length !== 0) { + return templates[0].template_name; + } + + // templates.length === 0, so check filesRequired + if (filesRequired) { + return "files"; + } + + // Nothing matches, so... + return ""; + }, + + _nextTemplateStep: function(currentStep, templates, filesRequired) { + if (currentStep == "files") { + // We are on the files step which is the last step for these + // templates. + return ""; + } + + if (currentStep === "process") { + return service._handleProcessStep(templates, filesRequired); + } + + var i = _.indexOf(templates, function(template) { + return template.template_name == currentStep; + }); + + console.log("i = " + i); + if (i == -1) { + // Couldn't find currentStep. This is an error + // on the api users part. We could check files, + // but better to just say no. + return ""; + } + + if (i+1 > templates.length) { + // No more templates, check if we should ask for files. + if (filesRequired) { + return "files"; + } + + return ""; + } + + return templates[i+1].template_name; + }, + + _checkFromOutputs: function(currentStep, template) { + next = service._nextTemplateStep(currentStep, template.output_templates, + template.required_output_files); + if (next !== "") { + return { + stepType: "output", + currentStep: next + }; + } + + return { + stepType: "done", + currentStep: "done" + }; + }, + + _checkFromInputs: function(currentStep, template) { + next = service._nextTemplateStep(currentStep, template.input_templates, + template.required_input_files); + if (next !== "") { + return { + stepType: "input", + currentStep: next + }; + } + + return service._checkFromOutputs(currentStep, template); + + }, + + nextStep: function(currentType, currentStep, template) { + console.log("currentType = " + currentType); + if (currentType == "process" || currentType == "input") { + return service._checkFromInputs(currentStep, template); + } else if (currentType == "output") { + return service._checkFromOutputs(currentStep, template); + } else { + return { + stepType: "done", + currentStep: "done" + }; + } + } + }; + return service; +}
6558cbf9032ad066b42e7e91c33fc4a5a7c63d96
test/js/spec/vent-constructor.js
test/js/spec/vent-constructor.js
define([ 'js-utils/js/vent-constructor', 'underscore' ], function(VentConstructor, _) { describe('Vent constructor', function() { beforeEach(function() { this.clock = sinon.useFakeTimers(); this.router = jasmine.createSpyObj('router', ['navigate']); this.vent = new VentConstructor(this.router); }); afterEach(function() { this.clock.restore(); }); it('should throttle resize events', function() { var trigger = spyOn(this.vent, 'trigger'); _.times(10, function() { this.vent.fireResize(); this.clock.tick(100); }, this); expect(trigger).toHaveCallCount(5); }); it('should call router.navigate with trigger: true', function() { this.vent.navigate('foo/bar'); expect(this.router.navigate.calls[0].args[0]).toEqual('foo/bar'); expect(this.router.navigate.calls[0].args[1].trigger).toBe(true); }); }); });
Add tests for vent constructor. [rev: matthew.gordon2]
Add tests for vent constructor. [rev: matthew.gordon2]
JavaScript
mit
hpautonomy/jsWhatever,hpe-idol/jsWhatever,hpe-idol/jsWhatever,hpautonomy/jsWhatever,hpautonomy/jsWhatever,hpe-idol/jsWhatever
--- +++ @@ -0,0 +1,39 @@ +define([ + 'js-utils/js/vent-constructor', + 'underscore' +], function(VentConstructor, _) { + + describe('Vent constructor', function() { + + beforeEach(function() { + this.clock = sinon.useFakeTimers(); + + this.router = jasmine.createSpyObj('router', ['navigate']); + this.vent = new VentConstructor(this.router); + }); + + afterEach(function() { + this.clock.restore(); + }); + + it('should throttle resize events', function() { + var trigger = spyOn(this.vent, 'trigger'); + + _.times(10, function() { + this.vent.fireResize(); + this.clock.tick(100); + }, this); + + expect(trigger).toHaveCallCount(5); + }); + + it('should call router.navigate with trigger: true', function() { + this.vent.navigate('foo/bar'); + + expect(this.router.navigate.calls[0].args[0]).toEqual('foo/bar'); + expect(this.router.navigate.calls[0].args[1].trigger).toBe(true); + }); + + }); + +});
0703d3d0d20aa9056448af5afd236d3f8d845721
test/validators/boolean.spec.js
test/validators/boolean.spec.js
import { expect } from 'chai'; import validator from '../../lib'; describe('Boolean validator', () => { const rules = { paid: ['boolean'] }; context('when given false', () => { it('should success', () => { const result = validator.validate(rules, {paid: false}); const err = result.messages; expect(result.success).to.equal(true); expect(err).to.not.have.property('paid'); }); }); context('when given true', () => { it('should success', () => { const result = validator.validate(rules, {paid: true}); const err = result.messages; expect(result.success).to.equal(true); expect(err).to.not.have.property('paid'); }); }); context(`when given string 'false'`, () => { it('should fail', () => { const testObj = {paid: 'false'}; const result = validator.validate(rules, testObj); const err = result.messages; expect(result.success).to.equal(false); expect(err).to.have.property('paid'); expect(err.paid.boolean).to.equal('Paid must be a boolean.'); }); }); context(`when given string 'true'`, () => { it('should fail', () => { const testObj = {paid: 'true'}; const result = validator.validate(rules, testObj); const err = result.messages; expect(result.success).to.equal(false); expect(err).to.have.property('paid'); expect(err.paid.boolean).to.equal('Paid must be a boolean.'); }); }); });
Add test cases for boolean validation rule
Add test cases for boolean validation rule
JavaScript
mit
sendyhalim/satpam,cermati/satpam
--- +++ @@ -0,0 +1,53 @@ +import { expect } from 'chai'; +import validator from '../../lib'; + +describe('Boolean validator', () => { + const rules = { + paid: ['boolean'] + }; + + context('when given false', () => { + it('should success', () => { + const result = validator.validate(rules, {paid: false}); + const err = result.messages; + + expect(result.success).to.equal(true); + expect(err).to.not.have.property('paid'); + }); + }); + + context('when given true', () => { + it('should success', () => { + const result = validator.validate(rules, {paid: true}); + const err = result.messages; + + expect(result.success).to.equal(true); + expect(err).to.not.have.property('paid'); + }); + }); + + context(`when given string 'false'`, () => { + it('should fail', () => { + const testObj = {paid: 'false'}; + const result = validator.validate(rules, testObj); + const err = result.messages; + + expect(result.success).to.equal(false); + expect(err).to.have.property('paid'); + expect(err.paid.boolean).to.equal('Paid must be a boolean.'); + }); + }); + + context(`when given string 'true'`, () => { + it('should fail', () => { + const testObj = {paid: 'true'}; + const result = validator.validate(rules, testObj); + const err = result.messages; + + expect(result.success).to.equal(false); + expect(err).to.have.property('paid'); + expect(err.paid.boolean).to.equal('Paid must be a boolean.'); + }); + }); +}); +
9906576240c224e31e5813a7243c503f084e293b
src/utils/hilbert-curve.js
src/utils/hilbert-curve.js
/* eslint-disable no-plusplus,no-bitwise */ // Adapted from Jason Davies: https://www.jasondavies.com/hilbert-curve/ const hilbert = (function () { // From Mike Bostock: http://bl.ocks.org/597287 // Adapted from Nick Johnson: http://bit.ly/biWkkq const pairs = [ [[0, 3], [1, 0], [3, 1], [2, 0]], [[2, 1], [1, 1], [3, 0], [0, 2]], [[2, 2], [3, 3], [1, 2], [0, 1]], [[0, 0], [3, 2], [1, 3], [2, 3]] ]; // d2xy and rot are from: // http://en.wikipedia.org/wiki/Hilbert_curve#Applications_and_mapping_algorithms function rot (n, x, y, rx, ry) { if (ry === 0) { if (rx === 1) { x = n - 1 - x; y = n - 1 - y; } return [y, x]; } return [x, y]; } return { xy2d (x, y, z) { let quad = 0; let pair; let i = 0; while (--z >= 0) { pair = pairs[quad][(x & (1 << z) ? 2 : 0) | (y & (1 << z) ? 1 : 0)]; i = (i << 2) | pair[0]; quad = pair[1]; } return i; }, d2xy (z, t) { let n = 1 << z; let x = 0; let y = 0; for (let s = 1; s < n; s *= 2) { let rx = 1 & (t / 2); let ry = 1 & (t ^ rx); let xy = rot(s, x, y, rx, ry); x = xy[0] + (s * rx); y = xy[1] + (s * ry); t /= 4; } return [x, y]; } }; })(); export default function hilbertCurve (level, index) { return hilbert.d2xy(level, index); }
Add code for Hilbert curve
Add code for Hilbert curve
JavaScript
mit
flekschas/hipiler,flekschas/hipiler,flekschas/hipiler
--- +++ @@ -0,0 +1,60 @@ +/* eslint-disable no-plusplus,no-bitwise */ + +// Adapted from Jason Davies: https://www.jasondavies.com/hilbert-curve/ +const hilbert = (function () { + // From Mike Bostock: http://bl.ocks.org/597287 + // Adapted from Nick Johnson: http://bit.ly/biWkkq + const pairs = [ + [[0, 3], [1, 0], [3, 1], [2, 0]], + [[2, 1], [1, 1], [3, 0], [0, 2]], + [[2, 2], [3, 3], [1, 2], [0, 1]], + [[0, 0], [3, 2], [1, 3], [2, 3]] + ]; + + // d2xy and rot are from: + // http://en.wikipedia.org/wiki/Hilbert_curve#Applications_and_mapping_algorithms + function rot (n, x, y, rx, ry) { + if (ry === 0) { + if (rx === 1) { + x = n - 1 - x; + y = n - 1 - y; + } + return [y, x]; + } + return [x, y]; + } + + return { + xy2d (x, y, z) { + let quad = 0; + let pair; + let i = 0; + + while (--z >= 0) { + pair = pairs[quad][(x & (1 << z) ? 2 : 0) | (y & (1 << z) ? 1 : 0)]; + i = (i << 2) | pair[0]; + quad = pair[1]; + } + + return i; + }, + d2xy (z, t) { + let n = 1 << z; + let x = 0; + let y = 0; + for (let s = 1; s < n; s *= 2) { + let rx = 1 & (t / 2); + let ry = 1 & (t ^ rx); + let xy = rot(s, x, y, rx, ry); + x = xy[0] + (s * rx); + y = xy[1] + (s * ry); + t /= 4; + } + return [x, y]; + } + }; +})(); + +export default function hilbertCurve (level, index) { + return hilbert.d2xy(level, index); +}
5c3bfa6a83689bafe404041987250c455c82a5f9
spec/unit/matrix-client.spec.js
spec/unit/matrix-client.spec.js
"use strict"; var sdk = require("../.."); var MatrixClient = sdk.MatrixClient; var utils = require("../test-utils"); describe("MatrixClient", function() { var userId = "@alice:bar"; var client; beforeEach(function() { utils.beforeEach(this); }); describe("getSyncState", function() { it("should return null if the client isn't started", function() { }); it("should return the same sync state as emitted sync events", function() { }); }); describe("retryImmediately", function() { it("should return false if there is no request waiting", function() { }); it("should return true if there is a request waiting", function() { }); it("should work on /initialSync", function() { }); it("should work on /events", function() { }); it("should work on /pushrules", function() { }); }); describe("emitted sync events", function() { it("should transition null -> PREPARED after /initialSync", function() { }); it("should transition null -> ERROR after a failed /initialSync", function() { }); it("should transition ERROR -> PREPARED after /initialSync if prev failed", function() { }); it("should transition PREPARED -> SYNCING after /initialSync", function() { }); it("should transition SYNCING -> ERROR after a failed /events", function() { }); it("should transition ERROR -> SYNCING after /events if prev failed", function() { }); it("should transition ERROR -> ERROR if multiple /events fails", function() { }); }); });
Add stub unit tests for syncing
Add stub unit tests for syncing
JavaScript
apache-2.0
krombel/matrix-js-sdk,matrix-org/matrix-js-sdk,krombel/matrix-js-sdk,matrix-org/matrix-js-sdk,krombel/matrix-js-sdk,matrix-org/matrix-js-sdk,williamboman/matrix-js-sdk,matrix-org/matrix-js-sdk,williamboman/matrix-js-sdk,williamboman/matrix-js-sdk
--- +++ @@ -0,0 +1,77 @@ +"use strict"; +var sdk = require("../.."); +var MatrixClient = sdk.MatrixClient; +var utils = require("../test-utils"); + +describe("MatrixClient", function() { + var userId = "@alice:bar"; + var client; + + beforeEach(function() { + utils.beforeEach(this); + }); + + describe("getSyncState", function() { + + it("should return null if the client isn't started", function() { + + }); + + it("should return the same sync state as emitted sync events", function() { + + }); + }); + + describe("retryImmediately", function() { + it("should return false if there is no request waiting", function() { + + }); + + it("should return true if there is a request waiting", function() { + + }); + + it("should work on /initialSync", function() { + + }); + + it("should work on /events", function() { + + }); + + it("should work on /pushrules", function() { + + }); + }); + + describe("emitted sync events", function() { + + it("should transition null -> PREPARED after /initialSync", function() { + + }); + + it("should transition null -> ERROR after a failed /initialSync", function() { + + }); + + it("should transition ERROR -> PREPARED after /initialSync if prev failed", function() { + + }); + + it("should transition PREPARED -> SYNCING after /initialSync", function() { + + }); + + it("should transition SYNCING -> ERROR after a failed /events", function() { + + }); + + it("should transition ERROR -> SYNCING after /events if prev failed", function() { + + }); + + it("should transition ERROR -> ERROR if multiple /events fails", function() { + + }); + }); +});
7500fb9b8c55f7468accf6d9a7e0dcb5a5b4d5ef
test/modules.node.test.js
test/modules.node.test.js
var modules = require('../lib/middleware/modules') , fs = require('fs'); function MockRequest() { } function MockResponse(done) { this.headers = {}; this._done = done; } MockResponse.prototype.setHeader = function(name, value) { this.headers[name] = value; } MockResponse.prototype.end = function(data) { this.data = data; this._done(); } describe('modules middleware [Node]', function() { describe('serving increment program', function() { var middleware = modules(__dirname + '/data/node/programs/increment', { resolve: 'node' }); it('should serve increment module', function(done) { var req = new MockRequest(); var res = new MockResponse(check); req.path = '/node_modules/increment/index.js'; middleware(req, res, function(err) { check(err); }); function check(err) { if (err) { return done(err); } res.headers.should.have.property('Content-Type'); res.headers['Content-Type'].should.equal('text/javascript'); var expect = fs.readFileSync('test/expect/node/programs/increment/increment.expect.js', 'utf8') //console.log('data: ' + res.data); //console.log('expect: ' + expect); res.data.should.equal(expect + '\r\n'); done(); } }); }); });
Test case for serving Node program.
Test case for serving Node program.
JavaScript
mit
jaredhanson/jsmt
--- +++ @@ -0,0 +1,53 @@ +var modules = require('../lib/middleware/modules') + , fs = require('fs'); + + +function MockRequest() { +} + +function MockResponse(done) { + this.headers = {}; + this._done = done; +} + +MockResponse.prototype.setHeader = function(name, value) { + this.headers[name] = value; +} + +MockResponse.prototype.end = function(data) { + this.data = data; + this._done(); +} + + +describe('modules middleware [Node]', function() { + + describe('serving increment program', function() { + var middleware = modules(__dirname + '/data/node/programs/increment', { resolve: 'node' }); + + it('should serve increment module', function(done) { + var req = new MockRequest(); + var res = new MockResponse(check); + + req.path = '/node_modules/increment/index.js'; + middleware(req, res, function(err) { + check(err); + }); + + function check(err) { + if (err) { return done(err); } + res.headers.should.have.property('Content-Type'); + res.headers['Content-Type'].should.equal('text/javascript'); + + var expect = fs.readFileSync('test/expect/node/programs/increment/increment.expect.js', 'utf8') + //console.log('data: ' + res.data); + //console.log('expect: ' + expect); + res.data.should.equal(expect + '\r\n'); + + done(); + } + }); + + }); + +});
e1f74e4ca49c6d08b9cf18483acf187b14c47242
test/processtimes.test.js
test/processtimes.test.js
'use strict'; //Load Config File var fs = require('fs'); var processTimes = require('../processtimes'); //Require Module var log4js = require('log4js'); var logger = log4js.getLogger('unit-test'); exports['Test Checking Time Format Function'] ={ 'Test checkTimeFormat sucess(12:00)':function(test){ var time = '12:00'; var result = processTimes.checkTimeFormat(time); test.equal(result,true,'The result should be true!'); test.done(); }, 'Test checkTimeFormat false(24:00)':function(test){ var time = '24:00'; try{ var result = processTimes.checkTimeFormat(time); }catch(ex){ test.ok(ex,'The function must throw error!'); } test.done(); } }
Test the function which will process times
Test the function which will process times
JavaScript
apache-2.0
dollars0427/SQLwatcher
--- +++ @@ -0,0 +1,41 @@ +'use strict'; + +//Load Config File +var fs = require('fs'); +var processTimes = require('../processtimes'); + +//Require Module + +var log4js = require('log4js'); +var logger = log4js.getLogger('unit-test'); + +exports['Test Checking Time Format Function'] ={ + + 'Test checkTimeFormat sucess(12:00)':function(test){ + + var time = '12:00'; + + var result = processTimes.checkTimeFormat(time); + + test.equal(result,true,'The result should be true!'); + + test.done(); + }, + + 'Test checkTimeFormat false(24:00)':function(test){ + + var time = '24:00'; + + try{ + + var result = processTimes.checkTimeFormat(time); + + }catch(ex){ + + test.ok(ex,'The function must throw error!'); + + } + + test.done(); + } +}
323fd8981dd021516d6e8f00930b586bcb900284
Medium/096_Unique_Binary_Search_Trees.js
Medium/096_Unique_Binary_Search_Trees.js
/** * @param {number} n * @return {number} */ var numTrees = function(n) { var dp = [0, 1]; var less = 0; var more = 0; dp[n] = dp[n] || 0; for (var i = 1; i <= n; i++) { less = i - 1; more = n - i; if (!dp[less]) { dp[less] = numTrees(less) } if (!dp[more]) { dp[more] = numTrees(more) } if (dp[less] === 0) { dp[n] += dp[more]; } else if (dp[more] === 0) { dp[n] += dp[less]; } else { dp[n] += (dp[more] * dp[less]); } } return dp[n]; };
Add solution to question 096
Add solution to question 096
JavaScript
mit
Rhadow/leetcode,Rhadow/leetcode,Rhadow/leetcode,Rhadow/leetcode
--- +++ @@ -0,0 +1,30 @@ +/** + * @param {number} n + * @return {number} + */ +var numTrees = function(n) { + var dp = [0, 1]; + var less = 0; + var more = 0; + + dp[n] = dp[n] || 0; + for (var i = 1; i <= n; i++) { + less = i - 1; + more = n - i; + if (!dp[less]) { + dp[less] = numTrees(less) + } + if (!dp[more]) { + dp[more] = numTrees(more) + } + if (dp[less] === 0) { + dp[n] += dp[more]; + } else if (dp[more] === 0) { + dp[n] += dp[less]; + } else { + dp[n] += (dp[more] * dp[less]); + } + } + + return dp[n]; +};
6e8a1628d0468446a4f04306534d9325a93f6f6d
test/composer/lifecycle-os-deps-test.js
test/composer/lifecycle-os-deps-test.js
var assert = require('assert'), path = require('path'), nock = require('nock'), vows = require('vows'), helpers = require('../helpers'), macros = require('../helpers/macros'), mock = require('../helpers/mock'), quill = require('../../lib/quill'), wtfos = require('wtfos'); wtfos.result = { distribution: 'ubuntu' }; var fixturesDir = path.join(__dirname, '..', 'fixtures'), installDir = path.join(fixturesDir, 'installed'), cacheDir = path.join(fixturesDir, 'cache'); vows.describe('quill/composer/lifecycle/os-deps').addBatch( macros.shouldInit(function () { quill.config.set('directories:cache', cacheDir); quill.config.set('directories:install', installDir); }) ).addBatch({ 'When using `quill.composer`': { 'the `run()` method': { topic: function () { quill.argv.force = true; var api = nock('http://api.testquill.com'), self = this; self.data = []; quill.on(['run', '*', 'stdout'], function (system, data) { self.data.push({ name: system.name, data: data.toString() }); }); helpers.cleanInstalled(['ubuntu-dep']); mock.systems.local(api, function () { quill.composer.run('install', 'ubuntu-dep', self.callback); }); }, 'should install the system correctly': function (err, _) { assert.isNull(err); helpers.assertScriptOutput(this.data[0], 'fixture-one'); helpers.assertScriptOutput(this.data[1], 'ubuntu-dep'); } } } }).export(module);
Add missing lifecycle OS deps test
[test] Add missing lifecycle OS deps test
JavaScript
mit
opsmezzo/quill
--- +++ @@ -0,0 +1,53 @@ +var assert = require('assert'), + path = require('path'), + nock = require('nock'), + vows = require('vows'), + helpers = require('../helpers'), + macros = require('../helpers/macros'), + mock = require('../helpers/mock'), + quill = require('../../lib/quill'), + wtfos = require('wtfos'); + +wtfos.result = { + distribution: 'ubuntu' +}; + +var fixturesDir = path.join(__dirname, '..', 'fixtures'), + installDir = path.join(fixturesDir, 'installed'), + cacheDir = path.join(fixturesDir, 'cache'); + +vows.describe('quill/composer/lifecycle/os-deps').addBatch( + macros.shouldInit(function () { + quill.config.set('directories:cache', cacheDir); + quill.config.set('directories:install', installDir); + }) +).addBatch({ + 'When using `quill.composer`': { + 'the `run()` method': { + topic: function () { + quill.argv.force = true; + + var api = nock('http://api.testquill.com'), + self = this; + + self.data = []; + quill.on(['run', '*', 'stdout'], function (system, data) { + self.data.push({ + name: system.name, + data: data.toString() + }); + }); + + helpers.cleanInstalled(['ubuntu-dep']); + mock.systems.local(api, function () { + quill.composer.run('install', 'ubuntu-dep', self.callback); + }); + }, + 'should install the system correctly': function (err, _) { + assert.isNull(err); + helpers.assertScriptOutput(this.data[0], 'fixture-one'); + helpers.assertScriptOutput(this.data[1], 'ubuntu-dep'); + } + } + } +}).export(module);
cd5ceceffef29fcd87b465d9a29ab5975acab6a7
src/js/helpers/qajaxWrapper.js
src/js/helpers/qajaxWrapper.js
var qajax = require("qajax"); var qajaxWrapper = function (options) { var response = { status: null, body: null }; var parseResponse = function (xhr) { response.status = xhr.status; try { response.body = JSON.parse(xhr.responseText); } catch (e) { response.body = xhr.responseText; } }; var api = qajax(options); api.error = function (callback) { var promise = this; // Bind callback also for non 200 status promise.then( // not a 2* response function (xhr) { if (xhr.status.toString()[0] !== "2") { parseResponse(xhr); callback(response); } }, // the promise is only rejected if the server has failed // to reply to the client (network problem or timeout reached). function (xhr) { parseResponse(xhr); callback(response); } ); return promise; }; api.success = function (callback) { var promise = this; promise .then(qajax.filterStatus(function (status) { return status.toString()[0] === "2"; })) .then(function (xhr) { parseResponse(xhr); callback(response); }); return promise; }; return api; }; module.exports = qajaxWrapper;
var qajax = require("qajax"); var uniqueCalls = []; function removeCall(options) { uniqueCalls.splice(uniqueCalls.indexOf(options.url), 1); } var qajaxWrapper = function (options) { if (!options.concurrent) { if (uniqueCalls.indexOf(options.url) > -1) { return { error: () => { return this; }, success: function () { return this; } }; } uniqueCalls.push(options.url); } var response = { status: null, body: null }; var parseResponse = function (xhr) { response.status = xhr.status; try { response.body = JSON.parse(xhr.responseText); } catch (e) { response.body = xhr.responseText; } }; var api = qajax(options); api.error = function (callback) { var promise = this; // Bind callback also for non 200 status promise.then( // not a 2* response function (xhr) { if (xhr.status.toString()[0] !== "2") { parseResponse(xhr); removeCall(options); callback(response); } }, // the promise is only rejected if the server has failed // to reply to the client (network problem or timeout reached). function (xhr) { parseResponse(xhr); removeCall(options); callback(response); } ); return promise; }; api.success = function (callback) { var promise = this; promise .then(qajax.filterStatus(function (status) { return status.toString()[0] === "2"; })) .then(function (xhr) { parseResponse(xhr); removeCall(options); callback(response); }); return promise; }; return api; }; module.exports = qajaxWrapper;
Return stub request object on concurrent request
Return stub request object on concurrent request
JavaScript
apache-2.0
watonyweng/marathon-ui,cribalik/marathon-ui,cribalik/marathon-ui,mesosphere/marathon-ui,yp-engineering/marathon-ui,janisz/marathon-ui,mesosphere/marathon-ui,yp-engineering/marathon-ui,Raffo/marathon-ui,watonyweng/marathon-ui,janisz/marathon-ui,Raffo/marathon-ui
--- +++ @@ -1,6 +1,22 @@ var qajax = require("qajax"); +var uniqueCalls = []; + +function removeCall(options) { + uniqueCalls.splice(uniqueCalls.indexOf(options.url), 1); +} + var qajaxWrapper = function (options) { + if (!options.concurrent) { + if (uniqueCalls.indexOf(options.url) > -1) { + return { + error: () => { return this; }, + success: function () { return this; } + }; + } + uniqueCalls.push(options.url); + } + var response = { status: null, body: null @@ -24,6 +40,7 @@ function (xhr) { if (xhr.status.toString()[0] !== "2") { parseResponse(xhr); + removeCall(options); callback(response); } }, @@ -31,6 +48,7 @@ // to reply to the client (network problem or timeout reached). function (xhr) { parseResponse(xhr); + removeCall(options); callback(response); } ); @@ -45,6 +63,7 @@ })) .then(function (xhr) { parseResponse(xhr); + removeCall(options); callback(response); }); return promise;
b84879cd0ec21e1f7c0dcf8b503560d56e66a6c4
tests/unit/components/LCircleMarker.spec.js
tests/unit/components/LCircleMarker.spec.js
import { getWrapperWithMap } from '@/tests/test-helpers'; import { testCircleFunctionality } from '@/tests/mixin-tests/circle-tests'; import LCircleMarker from '@/components/LCircleMarker.vue'; import L from 'leaflet'; describe('component: LCircleMarker.vue', () => { test('LCircleMarker.vue has a mapObject', () => { const { wrapper } = getWrapperWithMap(LCircleMarker); expect(wrapper.vm.mapObject).toBeDefined(); }); // Circle mixin testCircleFunctionality(LCircleMarker, 'LCircleMarker.vue'); // latLng property test('LCircleMarker.vue accepts and uses latLng prop as an array', () => { const latLng = [3.14, 2.79]; const { wrapper } = getWrapperWithMap(LCircleMarker, { latLng }); expect(wrapper.vm.mapObject.getLatLng()).toEqual(L.latLng(latLng)); }); test('LCircleMarker.vue accepts and uses latLng prop as a Leaflet object', () => { const latLng = L.latLng([3.14, 2.79]); const { wrapper } = getWrapperWithMap(LCircleMarker, { latLng }); expect(wrapper.vm.mapObject.getLatLng()).toEqual(latLng); }); test('LCircleMarker.vue updates the mapObject latLng when prop is changed to an array', async () => { const { wrapper } = getWrapperWithMap(LCircleMarker, { latLng: [11, 22] }); const newLatLng = [1, 1]; wrapper.setProps({ latLng: newLatLng }); await wrapper.vm.$nextTick(); expect(wrapper.vm.mapObject.getLatLng()).toEqual(L.latLng(newLatLng)); }); test('LCircleMarker.vue updates the mapObject latLng when prop is changed to an object', async () => { const { wrapper } = getWrapperWithMap(LCircleMarker, { latLng: [11, 22] }); const newLatLng = L.latLng([1, 1]); wrapper.setProps({ latLng: newLatLng }); await wrapper.vm.$nextTick(); expect(wrapper.vm.mapObject.getLatLng()).toEqual(newLatLng); }); // Pane test('LCircleMarker.vue accepts and uses pane prop', () => { const pane = 'overlayPane'; const { wrapper } = getWrapperWithMap(LCircleMarker, { pane }); expect(wrapper.vm.mapObject.options.pane).toEqual(pane); }); // Slot test('LCircleMarker.vue displays text from its default slot', async () => { const markerText = 'O hai, Marker!'; const { wrapper } = getWrapperWithMap(LCircleMarker, { latLng: [0, 0] }, { slots: { default: markerText } }); await wrapper.vm.$nextTick(); expect(wrapper.text()).toEqual(markerText); }); });
Add tests for LCircleMarker component
Add tests for LCircleMarker component
JavaScript
mit
KoRiGaN/Vue2Leaflet
--- +++ @@ -0,0 +1,77 @@ +import { getWrapperWithMap } from '@/tests/test-helpers'; +import { testCircleFunctionality } from '@/tests/mixin-tests/circle-tests'; +import LCircleMarker from '@/components/LCircleMarker.vue'; +import L from 'leaflet'; + +describe('component: LCircleMarker.vue', () => { + test('LCircleMarker.vue has a mapObject', () => { + const { wrapper } = getWrapperWithMap(LCircleMarker); + + expect(wrapper.vm.mapObject).toBeDefined(); + }); + + // Circle mixin + + testCircleFunctionality(LCircleMarker, 'LCircleMarker.vue'); + + // latLng property + + test('LCircleMarker.vue accepts and uses latLng prop as an array', () => { + const latLng = [3.14, 2.79]; + const { wrapper } = getWrapperWithMap(LCircleMarker, { latLng }); + + expect(wrapper.vm.mapObject.getLatLng()).toEqual(L.latLng(latLng)); + }); + + test('LCircleMarker.vue accepts and uses latLng prop as a Leaflet object', () => { + const latLng = L.latLng([3.14, 2.79]); + const { wrapper } = getWrapperWithMap(LCircleMarker, { latLng }); + + expect(wrapper.vm.mapObject.getLatLng()).toEqual(latLng); + }); + + test('LCircleMarker.vue updates the mapObject latLng when prop is changed to an array', async () => { + const { wrapper } = getWrapperWithMap(LCircleMarker, { latLng: [11, 22] }); + + const newLatLng = [1, 1]; + wrapper.setProps({ latLng: newLatLng }); + await wrapper.vm.$nextTick(); + + expect(wrapper.vm.mapObject.getLatLng()).toEqual(L.latLng(newLatLng)); + }); + + test('LCircleMarker.vue updates the mapObject latLng when prop is changed to an object', async () => { + const { wrapper } = getWrapperWithMap(LCircleMarker, { latLng: [11, 22] }); + + const newLatLng = L.latLng([1, 1]); + wrapper.setProps({ latLng: newLatLng }); + await wrapper.vm.$nextTick(); + + expect(wrapper.vm.mapObject.getLatLng()).toEqual(newLatLng); + }); + + // Pane + + test('LCircleMarker.vue accepts and uses pane prop', () => { + const pane = 'overlayPane'; + const { wrapper } = getWrapperWithMap(LCircleMarker, { pane }); + + expect(wrapper.vm.mapObject.options.pane).toEqual(pane); + }); + + // Slot + + test('LCircleMarker.vue displays text from its default slot', async () => { + const markerText = 'O hai, Marker!'; + const { wrapper } = getWrapperWithMap(LCircleMarker, { + latLng: [0, 0] + }, { + slots: { + default: markerText + } + }); + await wrapper.vm.$nextTick(); + + expect(wrapper.text()).toEqual(markerText); + }); +});
ac82e1dfda63c2140559ae1ec2e452f737be9291
template/js/more-recipe.js
template/js/more-recipe.js
var counter = 0; $("#up-vote").click(function() { counter++; $("#count").text(counter); }); $("#down-vote").click(function() { counter--; $("#count").text(counter); })
Add up-vote & down-vote functionality
Add up-vote & down-vote functionality
JavaScript
mit
iidrees/More-Recipes,iidrees/More-Recipes
--- +++ @@ -0,0 +1,10 @@ + +var counter = 0; +$("#up-vote").click(function() { + counter++; + $("#count").text(counter); +}); +$("#down-vote").click(function() { + counter--; + $("#count").text(counter); +})
b5616985757ade1f8981c1330a605677bf2c3a82
test/components/Header.spec.js
test/components/Header.spec.js
import { React, sinon, assert, expect, TestUtils } from '../test_exports'; import Header from '../../src/js/components/Header'; describe('Header component', () => { let sandbox, header, container, titleGroup, title, subtitle, navbar, navItems; let findDOMWithClass = TestUtils.findRenderedDOMComponentWithClass; let scryDOMWithClass = TestUtils.scryRenderedDOMComponentsWithClass; before(() => { header = TestUtils.renderIntoDocument(<Header/>); container = findDOMWithClass(header, 'header-container'); titleGroup = findDOMWithClass(header, 'title-group'); title = findDOMWithClass(header, 'title'); subtitle = findDOMWithClass(header, 'subtitle'); navbar = findDOMWithClass(header, 'navbar'); navItems = scryDOMWithClass(header, 'nav-item'); }); it('should render into the DOM', () => { expect(container).to.not.equal(null); expect(titleGroup).to.not.equal(null); expect(title).to.not.equal(null); expect(subtitle).to.not.equal(null); expect(navbar).to.not.equal(null); expect(navItems.length).to.equal(3); }); });
Add basic component testing for Header
Add basic component testing for Header
JavaScript
mit
kusera/sentrii,kusera/sentrii
--- +++ @@ -0,0 +1,27 @@ +import { React, sinon, assert, expect, TestUtils } from '../test_exports'; +import Header from '../../src/js/components/Header'; + +describe('Header component', () => { + let sandbox, header, container, titleGroup, title, subtitle, navbar, navItems; + let findDOMWithClass = TestUtils.findRenderedDOMComponentWithClass; + let scryDOMWithClass = TestUtils.scryRenderedDOMComponentsWithClass; + + before(() => { + header = TestUtils.renderIntoDocument(<Header/>); + container = findDOMWithClass(header, 'header-container'); + titleGroup = findDOMWithClass(header, 'title-group'); + title = findDOMWithClass(header, 'title'); + subtitle = findDOMWithClass(header, 'subtitle'); + navbar = findDOMWithClass(header, 'navbar'); + navItems = scryDOMWithClass(header, 'nav-item'); + }); + + it('should render into the DOM', () => { + expect(container).to.not.equal(null); + expect(titleGroup).to.not.equal(null); + expect(title).to.not.equal(null); + expect(subtitle).to.not.equal(null); + expect(navbar).to.not.equal(null); + expect(navItems.length).to.equal(3); + }); +});
3d550711e29ab3be257b65350afe583c39b7f1c7
9/child_process_ls.js
9/child_process_ls.js
var child_process = require('child_process'); var ls = child_process.spawn('ls', [ '-lh', '/usr' ]); ls.stdout.on('data', function (data) { console.log('stdout: ' + data); }); ls.stderr.on('data', function (data) { console.log('stderr: ' + data); }); ls.on('close', function (code) { console.log('child process exited with code ' + code); });
Add the example to list the folder with child process.
Add the example to list the folder with child process.
JavaScript
mit
nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference
--- +++ @@ -0,0 +1,15 @@ +var child_process = require('child_process'); + +var ls = child_process.spawn('ls', [ '-lh', '/usr' ]); + +ls.stdout.on('data', function (data) { + console.log('stdout: ' + data); +}); + +ls.stderr.on('data', function (data) { + console.log('stderr: ' + data); +}); + +ls.on('close', function (code) { + console.log('child process exited with code ' + code); +});
a2bcc2373e3dbb2313878e303612ed8c13807e59
app/resources/v1/users_streets_pg.js
app/resources/v1/users_streets_pg.js
const { User, Street } = require('../../db/models') const { ERRORS } = require('../../../lib/util') const logger = require('../../../lib/logger.js')() exports.get = async function (req, res) { // Flag error if user ID is not provided if (!req.params.user_id) { res.status(400).send('Please provide user ID.') } const findUserStreets = async function (userId) { let streets try { streets = await Street.findAll({ include: [{ model: User, where: { creator_id: userId } }], order: [ ['updated_at', 'DESC'] ] }) } catch (err) { logger.error(err) handleErrors(ERRORS.CANNOT_GET_STREET) } if (!streets) { throw new Error(ERRORS.STREET_NOT_FOUND) } return streets } // END function - handleFindUserstreets const handleFindUserStreets = function (streets) { const json = { streets: streets } res.status(200).send(json) } // END function - handleFindUserStreets function handleErrors (error) { switch (error) { case ERRORS.USER_NOT_FOUND: res.status(404).send('Creator not found.') return case ERRORS.STREET_NOT_FOUND: res.status(404).send('Could not find streets.') return case ERRORS.STREET_DELETED: res.status(410).send('Could not find street.') return case ERRORS.CANNOT_GET_STREET: res.status(500).send('Could not find streets for user.') return case ERRORS.UNAUTHORISED_ACCESS: res.status(401).send('User is not signed-in.') return case ERRORS.FORBIDDEN_REQUEST: res.status(403).send('Signed-in user cannot delete this street.') return default: res.status(500).end() } } // END function - handleErrors let user try { user = await User.findById(req.params.user_id) } catch (err) { logger.error(err) handleErrors(ERRORS.CANNOT_GET_STREET) } if (!user) { res.status(404).send('Could not find user.') return } findUserStreets(user._id) .then(handleFindUserStreets) .catch(handleErrors) }
Add users_streets api with sequelize
Add users_streets api with sequelize
JavaScript
bsd-3-clause
codeforamerica/streetmix,codeforamerica/streetmix,codeforamerica/streetmix
--- +++ @@ -0,0 +1,78 @@ +const { User, Street } = require('../../db/models') +const { ERRORS } = require('../../../lib/util') +const logger = require('../../../lib/logger.js')() + +exports.get = async function (req, res) { + // Flag error if user ID is not provided + if (!req.params.user_id) { + res.status(400).send('Please provide user ID.') + } + + const findUserStreets = async function (userId) { + let streets + try { + streets = await Street.findAll({ + include: [{ + model: User, + where: { creator_id: userId } + }], + order: [ ['updated_at', 'DESC'] ] + }) + } catch (err) { + logger.error(err) + handleErrors(ERRORS.CANNOT_GET_STREET) + } + + if (!streets) { + throw new Error(ERRORS.STREET_NOT_FOUND) + } + return streets + } // END function - handleFindUserstreets + + const handleFindUserStreets = function (streets) { + const json = { streets: streets } + res.status(200).send(json) + } // END function - handleFindUserStreets + + function handleErrors (error) { + switch (error) { + case ERRORS.USER_NOT_FOUND: + res.status(404).send('Creator not found.') + return + case ERRORS.STREET_NOT_FOUND: + res.status(404).send('Could not find streets.') + return + case ERRORS.STREET_DELETED: + res.status(410).send('Could not find street.') + return + case ERRORS.CANNOT_GET_STREET: + res.status(500).send('Could not find streets for user.') + return + case ERRORS.UNAUTHORISED_ACCESS: + res.status(401).send('User is not signed-in.') + return + case ERRORS.FORBIDDEN_REQUEST: + res.status(403).send('Signed-in user cannot delete this street.') + return + default: + res.status(500).end() + } + } // END function - handleErrors + + let user + try { + user = await User.findById(req.params.user_id) + } catch (err) { + logger.error(err) + handleErrors(ERRORS.CANNOT_GET_STREET) + } + + if (!user) { + res.status(404).send('Could not find user.') + return + } + + findUserStreets(user._id) + .then(handleFindUserStreets) + .catch(handleErrors) +}
128ea7db413c3f49832949d8d0f2fff97d2f8701
lib/handlers/providers/index.js
lib/handlers/providers/index.js
"use strict"; var Anyfetch = require('anyfetch'); module.exports.get = function get(req, res, next) { var anyfetchClient = new Anyfetch(req.accessToken.token); anyfetchClient.getDocuments({ fields: 'facets.provider' }, function updated(err, res) { if(!err) { var providers = res.facets.providers; res.send({ 'count': providers.length }); } next(err); }); };
Add new endpoint (to replace start)
Add new endpoint (to replace start)
JavaScript
mit
AnyFetch/companion-server
--- +++ @@ -0,0 +1,17 @@ +"use strict"; +var Anyfetch = require('anyfetch'); + +module.exports.get = function get(req, res, next) { + var anyfetchClient = new Anyfetch(req.accessToken.token); + anyfetchClient.getDocuments({ + fields: 'facets.provider' + }, function updated(err, res) { + if(!err) { + var providers = res.facets.providers; + res.send({ + 'count': providers.length + }); + } + next(err); + }); +};
15825eacb313872cfe6d8afff52a93604127e8dd
src/physics/arcade/inc/tilemap/TileIntersectsBody.js
src/physics/arcade/inc/tilemap/TileIntersectsBody.js
var TileIntersectsBody = function (tileWorldRect, body) { if (body.isCircle) { return false; } else { return !( body.right <= tileWorldRect.left || body.bottom <= tileWorldRect.top || body.position.x >= tileWorldRect.right || body.position.y >= tileWorldRect.bottom ); } }; module.exports = TileIntersectsBody;
var TileIntersectsBody = function (tileWorldRect, body) { // Currently, all bodies are treated as rectangles when colliding with a Tile. Eventually, this // should support circle bodies when those are less buggy in v3. return !( body.right <= tileWorldRect.left || body.bottom <= tileWorldRect.top || body.position.x >= tileWorldRect.right || body.position.y >= tileWorldRect.bottom ); }; module.exports = TileIntersectsBody;
Add note about circle bodies not currently being supported in Arcade tile intersection
Add note about circle bodies not currently being supported in Arcade tile intersection
JavaScript
mit
photonstorm/phaser,TukekeSoft/phaser,TukekeSoft/phaser,BeanSeed/phaser,mahill/phaser,spayton/phaser,photonstorm/phaser,pixelpicosean/phaser,spayton/phaser,TukekeSoft/phaser,rblopes/phaser,BeanSeed/phaser,englercj/phaser,mahill/phaser
--- +++ @@ -1,18 +1,14 @@ var TileIntersectsBody = function (tileWorldRect, body) { - if (body.isCircle) - { - return false; - } - else - { - return !( - body.right <= tileWorldRect.left || - body.bottom <= tileWorldRect.top || - body.position.x >= tileWorldRect.right || - body.position.y >= tileWorldRect.bottom - ); - } + // Currently, all bodies are treated as rectangles when colliding with a Tile. Eventually, this + // should support circle bodies when those are less buggy in v3. + + return !( + body.right <= tileWorldRect.left || + body.bottom <= tileWorldRect.top || + body.position.x >= tileWorldRect.right || + body.position.y >= tileWorldRect.bottom + ); }; module.exports = TileIntersectsBody;
0c5f9eda34a90954a94c2e9aa657d2256fe0208f
flow-typed/npm/react-ui-validations_v0.x.x.js
flow-typed/npm/react-ui-validations_v0.x.x.js
// flow-typed signature: 291855e84801d873d854919a58e86373 // flow-typed version: <<STUB>>/react-ui-validations_v0.0.0/flow_v0.90.0 /** * This is an autogenerated libdef stub for: * * 'react-ui-validations' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module "react-ui-validations" { declare export type ValidationInfo = { message: string | React$Node, level?: "error" | "warning", type?: "submit" | "lostfocus" | "immediate", }; declare type ValidationContainerProps = {| "data-tid"?: string, children?: any, |}; declare export class ValidationContainer extends React$Component<ValidationContainerProps> { validate(): Promise<boolean>; submit(withoutScroll?: boolean): Promise<void>; } declare type ValidationTooltipProps = {| "data-tid"?: string, error: boolean, pos: TooltipPosition, render: () => ?React$Node | ?string, children?: any, |}; declare export class ValidationTooltip extends React$Component<ValidationTooltipProps> {} declare type ValidationTooltipContextProps = {| "data-tid"?: string, children?: any, |}; declare export class ValidationTooltipContext extends React$Component<ValidationTooltipContextProps> { validate(): Promise<boolean>; submit(): Promise<void>; } declare type ValidationMessageRenderer = ( control: React$Node, hasError: boolean, validation: ValidationInfo ) => React$Node; declare type TooltipPosition = | "top left" | "top center" | "top right" | "bottom left" | "bottom center" | "bottom right" | "left top" | "left middle" | "left bottom" | "right top" | "right middle" | "right bottom"; declare export function text(position: "right" | "bottom"): ValidationMessageRenderer; declare export function tooltip(position: TooltipPosition): ValidationMessageRenderer; declare type ValidationWrapperV1Props = {| "data-tid"?: string, validationInfo: ?ValidationInfo, renderMessage?: ValidationMessageRenderer, children?: any, |}; declare export class ValidationWrapperV1 extends React$Component<ValidationWrapperV1Props> {} }
Add types for react-ui-validation package
Add types for react-ui-validation package
JavaScript
mit
moira-alert/web2.0,moira-alert/web2.0,moira-alert/web2.0,moira-alert/web2.0
--- +++ @@ -0,0 +1,84 @@ +// flow-typed signature: 291855e84801d873d854919a58e86373 +// flow-typed version: <<STUB>>/react-ui-validations_v0.0.0/flow_v0.90.0 + +/** + * This is an autogenerated libdef stub for: + * + * 'react-ui-validations' + * + * Fill this stub out by replacing all the `any` types. + * + * Once filled out, we encourage you to share your work with the + * community by sending a pull request to: + * https://github.com/flowtype/flow-typed + */ + +declare module "react-ui-validations" { + declare export type ValidationInfo = { + message: string | React$Node, + level?: "error" | "warning", + type?: "submit" | "lostfocus" | "immediate", + }; + + declare type ValidationContainerProps = {| + "data-tid"?: string, + children?: any, + |}; + + declare export class ValidationContainer extends React$Component<ValidationContainerProps> { + validate(): Promise<boolean>; + submit(withoutScroll?: boolean): Promise<void>; + } + + declare type ValidationTooltipProps = {| + "data-tid"?: string, + error: boolean, + pos: TooltipPosition, + render: () => ?React$Node | ?string, + children?: any, + |}; + + declare export class ValidationTooltip extends React$Component<ValidationTooltipProps> {} + + declare type ValidationTooltipContextProps = {| + "data-tid"?: string, + children?: any, + |}; + + declare export class ValidationTooltipContext extends React$Component<ValidationTooltipContextProps> { + validate(): Promise<boolean>; + submit(): Promise<void>; + } + + declare type ValidationMessageRenderer = ( + control: React$Node, + hasError: boolean, + validation: ValidationInfo + ) => React$Node; + + declare type TooltipPosition = + | "top left" + | "top center" + | "top right" + | "bottom left" + | "bottom center" + | "bottom right" + | "left top" + | "left middle" + | "left bottom" + | "right top" + | "right middle" + | "right bottom"; + + declare export function text(position: "right" | "bottom"): ValidationMessageRenderer; + declare export function tooltip(position: TooltipPosition): ValidationMessageRenderer; + + declare type ValidationWrapperV1Props = {| + "data-tid"?: string, + validationInfo: ?ValidationInfo, + renderMessage?: ValidationMessageRenderer, + children?: any, + |}; + + declare export class ValidationWrapperV1 extends React$Component<ValidationWrapperV1Props> {} +}
72af2a8f45fad46be6f01a52a2ff40507b2a450c
frontend/src/containers/DeleteNotification.js
frontend/src/containers/DeleteNotification.js
import React from 'react'; export default class DeleteNotification extends React.Component { render() { return( <div className='notification'> <p>The victim has been deleted.</p> <div className='btn underline' onClick={ this.props.onUndo }>Undo</div> <button type='button' className='close nooutline' onClick={ this.props.onClose }>&times;</button> </div> ); } }
Add notification once victim deleted
Add notification once victim deleted
JavaScript
mit
dimriou/rupture,dimriou/rupture,dionyziz/rupture,dimkarakostas/rupture,esarafianou/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,dionyziz/rupture,dimriou/rupture,dimkarakostas/rupture,dimriou/rupture,dimkarakostas/rupture,esarafianou/rupture,dimkarakostas/rupture,dionyziz/rupture,esarafianou/rupture
--- +++ @@ -0,0 +1,14 @@ +import React from 'react'; + +export default class DeleteNotification extends React.Component { + render() { + return( + <div className='notification'> + <p>The victim has been deleted.</p> + <div className='btn underline' onClick={ this.props.onUndo }>Undo</div> + <button type='button' className='close nooutline' onClick={ this.props.onClose }>&times;</button> + </div> + ); + } +} +
24e779a15d7a21d0f64ad90402ff8a30e0fc8ea3
js/es6-playground/06-defaut-rest-spread.js
js/es6-playground/06-defaut-rest-spread.js
// 06 - Callee-evaluated default parameter values. // Default params function mul(a, b = 100) { return a * b; } console.log("MUL: ", mul(5)); function sum(a, b = getSum()) { return a + b; } var getSum = () => 100; console.log("SUM: ", sum(5)); // Rest parameters function rest1(x, ...y) { return x + y.length; } console.log(`REST1 = ${rest1(10, 1, 2, 3)}`); function rest2(...[a, b, c]) { return a + b + c; } console.log(`REST2 = ${rest2(1, 2, 3)}`); // Spread let arr1 = [2, 4, 6]; console.log(`SPREAD1 = ${rest1(1, ...arr1)}`); console.log(`SPREAD2 = ${rest2(1, ...arr1)}`); // eof
Add es6 default, rest, spread params examples
Add es6 default, rest, spread params examples
JavaScript
mit
petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox
--- +++ @@ -0,0 +1,34 @@ +// 06 - Callee-evaluated default parameter values. + +// Default params + +function mul(a, b = 100) { + return a * b; +} +console.log("MUL: ", mul(5)); + +function sum(a, b = getSum()) { + return a + b; +} +var getSum = () => 100; +console.log("SUM: ", sum(5)); + +// Rest parameters + +function rest1(x, ...y) { + return x + y.length; +} +console.log(`REST1 = ${rest1(10, 1, 2, 3)}`); + +function rest2(...[a, b, c]) { + return a + b + c; +} +console.log(`REST2 = ${rest2(1, 2, 3)}`); + +// Spread + +let arr1 = [2, 4, 6]; +console.log(`SPREAD1 = ${rest1(1, ...arr1)}`); +console.log(`SPREAD2 = ${rest2(1, ...arr1)}`); + +// eof
69ac01bce7a2c4f657e7fa44d5d51696cb788354
index.js
index.js
var rabbit = require('./rabbit'); var config = require('./rabbit.json'); var commandLineArgs = require('command-line-args'); var args = commandLineArgs([{ name: 'port', alias: 'p' }]).parse(); var socketConfig = require('./socket'); var socketInst = null; var queue = require('./queue'); rabbit.connect().then(function(connection) { queue(connection).then(function(queue) { console.log('- queue is listening for messages -'); queue.subscribe(function(message, headers) { push(headers.channel, message.data.toString()); }); }); }); socketInst = socketConfig.connect(args.port); function push(channel, message) { if (socketInst) { socketInst.send(channel, message); } }
Add an application that gets messages from rabbit and pushes them into a socket.
Add an application that gets messages from rabbit and pushes them into a socket.
JavaScript
mit
RenovoSolutions/socket-server
--- +++ @@ -0,0 +1,27 @@ +var rabbit = require('./rabbit'); +var config = require('./rabbit.json'); +var commandLineArgs = require('command-line-args'); + +var args = commandLineArgs([{ name: 'port', alias: 'p' }]).parse(); + +var socketConfig = require('./socket'); +var socketInst = null; + +var queue = require('./queue'); + +rabbit.connect().then(function(connection) { + queue(connection).then(function(queue) { + console.log('- queue is listening for messages -'); + queue.subscribe(function(message, headers) { + push(headers.channel, message.data.toString()); + }); + }); +}); + +socketInst = socketConfig.connect(args.port); + +function push(channel, message) { + if (socketInst) { + socketInst.send(channel, message); + } +}
1632ae052f0a5061c09c3c00afc236ad7296ef46
feature-detects/pointerlock-api.js
feature-detects/pointerlock-api.js
// https://developer.mozilla.org/en-US/docs/API/Pointer_Lock_API Modernizr.addTest('pointerlock',!!Modernizr.prefixed('pointerLockElement', document));
Add pointerlock api feature detect
Add pointerlock api feature detect
JavaScript
mit
Modernizr/Modernizr,Modernizr/Modernizr
--- +++ @@ -0,0 +1,4 @@ +// https://developer.mozilla.org/en-US/docs/API/Pointer_Lock_API + +Modernizr.addTest('pointerlock',!!Modernizr.prefixed('pointerLockElement', document)); +
8001fd55e826485c10c993184e1a0016f07bb858
src/main/webapp/app/entities/participation/participation-delete-dialog.controller.js
src/main/webapp/app/entities/participation/participation-delete-dialog.controller.js
(function () { 'use strict'; angular .module('exerciseApplicationApp') .controller('ParticipationDeleteController', ParticipationDeleteController); ParticipationDeleteController.$inject = ['$uibModalInstance', 'entity', 'Participation']; function ParticipationDeleteController($uibModalInstance, entity, Participation) { var vm = this; vm.participation = entity; vm.clear = clear; vm.confirmDelete = confirmDelete; function clear() { $uibModalInstance.dismiss('cancel'); } function confirmDelete(id, deleteBuildPlan, deleteRepository) { Participation.delete({ id: id, deleteBuildPlan: deleteBuildPlan, deleteRepository: deleteRepository }, function () { $uibModalInstance.close(true); }); } } })();
(function () { 'use strict'; angular .module('exerciseApplicationApp') .controller('ParticipationDeleteController', ParticipationDeleteController); ParticipationDeleteController.$inject = ['$uibModalInstance', 'entity', 'Participation']; function ParticipationDeleteController($uibModalInstance, entity, Participation) { var vm = this; vm.participation = entity; vm.deleteBuildPlan = true; vm.deleteRepository = true; vm.clear = clear; vm.confirmDelete = confirmDelete; function clear() { $uibModalInstance.dismiss('cancel'); } function confirmDelete(id, deleteBuildPlan, deleteRepository) { Participation.delete({ id: id, deleteBuildPlan: deleteBuildPlan, deleteRepository: deleteRepository }, function () { $uibModalInstance.close(true); }); } } })();
Make deleting build plan and repository default when deleting participation
Make deleting build plan and repository default when deleting participation
JavaScript
mit
ls1intum/ArTEMiS,ls1intum/ArTEMiS,ls1intum/ArTEMiS,ls1intum/ArTEMiS,LisLo/ArTEMiS,LisLo/ArTEMiS,ls1intum/ArTEMiS,LisLo/ArTEMiS,ls1intum/ArTEMiS
--- +++ @@ -11,6 +11,9 @@ var vm = this; vm.participation = entity; + vm.deleteBuildPlan = true; + vm.deleteRepository = true; + vm.clear = clear; vm.confirmDelete = confirmDelete;
25d0b59a3791063c815d7b83748f410c1a58df5b
src/monster-array.js
src/monster-array.js
/*jshint esnext: true*/ /*jshint browser: true*/ 'use strict' function randBetween(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function monsterObject() { return { // context: window.sprite_canvas.getContext('2d'), width: 32, height: 16, leftIndex: 1, rightIndex: 1, // image: goomba_tilemap, numberOfFrames: 2, ticksPerFrame: 16, x: randBetween(20, 500), // y: (window.sprite_canvas.height - 16) - 2*16, velocityX: 0.75, velocityY: 0, gravity: 0.3, onground: true, jumpHeight: -8, motion_direction: randBetween(1, 2) == 1 ? 'L' : 'R' }; } function createMonsters(num) { return [...Array(num)].map((a) => a = monsterObject()); } // var monsterObject = { // // context: window.sprite_canvas.getContext('2d'), // width: 32, // height: 16, // leftIndex: 1, // rightIndex: 1, // image: goomba_tilemap, // numberOfFrames: 2, // ticksPerFrame: 16, // x: randBetween(20, window.sprite_canvas.width-20), // y: (window.sprite_canvas.height - 16) - 2*16, // velocityX: 0.75, // velocityY: 0, // gravity: 0.3, // onground: true, // jumpHeight: -8 // };
Add randbetween- and two monster-functions
Add randbetween- and two monster-functions
JavaScript
mit
Mattiaslndstrm/koopa-paratroopas,Mattiaslndstrm/koopa-paratroopas,Mattiaslndstrm/koopa-paratroopas
--- +++ @@ -0,0 +1,54 @@ +/*jshint esnext: true*/ +/*jshint browser: true*/ +'use strict' + +function randBetween(min, max) { + return Math.floor(Math.random() * (max - min + 1)) + min; +} + +function monsterObject() { + + return { + // context: window.sprite_canvas.getContext('2d'), + width: 32, + height: 16, + leftIndex: 1, + rightIndex: 1, + // image: goomba_tilemap, + numberOfFrames: 2, + ticksPerFrame: 16, + x: randBetween(20, 500), + // y: (window.sprite_canvas.height - 16) - 2*16, + velocityX: 0.75, + velocityY: 0, + gravity: 0.3, + onground: true, + jumpHeight: -8, + motion_direction: randBetween(1, 2) == 1 ? 'L' : 'R' + }; + +} + + +function createMonsters(num) { + return [...Array(num)].map((a) => a = monsterObject()); +} + + +// var monsterObject = { +// // context: window.sprite_canvas.getContext('2d'), +// width: 32, +// height: 16, +// leftIndex: 1, +// rightIndex: 1, +// image: goomba_tilemap, +// numberOfFrames: 2, +// ticksPerFrame: 16, +// x: randBetween(20, window.sprite_canvas.width-20), +// y: (window.sprite_canvas.height - 16) - 2*16, +// velocityX: 0.75, +// velocityY: 0, +// gravity: 0.3, +// onground: true, +// jumpHeight: -8 +// };
59dddf88dc67724a18b38bf1d6b45f4fa3e4aaa3
test/load-test.js
test/load-test.js
var nock = require('nock'); var Loader = require('../lib/load'); var defaultOptions = { urls: ['http://example.com'] }; var should = require('should') describe('Load', function(){ describe('#getLoadedFilename', function(){ it('should return nothing if no filename was set for url before', function(){ var loader = new Loader(defaultOptions); var url = 'http://example.com'; var localFilename = loader.getLoadedFilename(url); should(localFilename).not.be.ok; }); }); describe('#setLoadedFilename, #getLoadedFilename', function(){ it('should set local filename for url and then get local filename by url', function(){ var loader = new Loader(defaultOptions); var url = 'http://example.com'; var localFilename = 'index.html'; loader.setLoadedFilename(url, localFilename); loader.getLoadedFilename(url).should.be.equal(localFilename); }); }); describe('#getAllLoadedFilenames', function(){ it('should return an array with all local filenames set before', function(){ var loader = new Loader(defaultOptions); for (var i = 1; i <= 3; i++) { loader.setLoadedFilename('http://example.com/' + i, 'file-' + i + '.txt'); } var allLoadedFilenames = loader.getAllLoadedFilenames(); allLoadedFilenames.should.be.instanceof(Array).and.have.lengthOf(3); allLoadedFilenames.should.containEql('file-1.txt'); allLoadedFilenames.should.containEql('file-2.txt'); allLoadedFilenames.should.containEql('file-3.txt'); }); }); describe('#getFilename', function(){ it('should return different result for filename if such file was already loaded', function(){ var loader = new Loader(defaultOptions); var url1 = 'http://example.com/index.html' var filename1 = 'index.html'; var localFilename1 = loader.getFilename(filename1); loader.setLoadedFilename(url1, localFilename1); var url2 = 'http://example.com/blog/index.html' var filename2 = 'index.html'; var localFilename2 = loader.getFilename(filename2); loader.setLoadedFilename(url2, localFilename2); var url3 = 'http://example.com/about/index.html' var filename3 = 'index.html'; var localFilename3 = loader.getFilename(filename3); loader.setLoadedFilename(url3, localFilename3); localFilename1.should.not.be.equal(localFilename2); localFilename2.should.not.be.equal(localFilename3); localFilename3.should.not.be.equal(localFilename1); }); }); });
Add tests for getLoadedFilename, setLoadedFilename, getAllLoadedFilenames and getFilename functions of loader object
Add tests for getLoadedFilename, setLoadedFilename, getAllLoadedFilenames and getFilename functions of loader object
JavaScript
mit
s0ph1e/node-website-scraper,Flamenco/node-website-scraper,aivus/node-website-scraper,website-scraper/node-website-scraper,s0ph1e/node-website-scraper,aivus/node-website-scraper,website-scraper/node-website-scraper,Flamenco/node-website-scraper
--- +++ @@ -0,0 +1,71 @@ +var nock = require('nock'); +var Loader = require('../lib/load'); + +var defaultOptions = { + urls: ['http://example.com'] +}; + +var should = require('should') +describe('Load', function(){ + describe('#getLoadedFilename', function(){ + it('should return nothing if no filename was set for url before', function(){ + var loader = new Loader(defaultOptions); + var url = 'http://example.com'; + + var localFilename = loader.getLoadedFilename(url); + should(localFilename).not.be.ok; + }); + }); + + describe('#setLoadedFilename, #getLoadedFilename', function(){ + it('should set local filename for url and then get local filename by url', function(){ + var loader = new Loader(defaultOptions); + var url = 'http://example.com'; + var localFilename = 'index.html'; + + loader.setLoadedFilename(url, localFilename); + loader.getLoadedFilename(url).should.be.equal(localFilename); + }); + }); + + describe('#getAllLoadedFilenames', function(){ + it('should return an array with all local filenames set before', function(){ + var loader = new Loader(defaultOptions); + + for (var i = 1; i <= 3; i++) { + loader.setLoadedFilename('http://example.com/' + i, 'file-' + i + '.txt'); + } + + var allLoadedFilenames = loader.getAllLoadedFilenames(); + allLoadedFilenames.should.be.instanceof(Array).and.have.lengthOf(3); + allLoadedFilenames.should.containEql('file-1.txt'); + allLoadedFilenames.should.containEql('file-2.txt'); + allLoadedFilenames.should.containEql('file-3.txt'); + }); + }); + + describe('#getFilename', function(){ + it('should return different result for filename if such file was already loaded', function(){ + var loader = new Loader(defaultOptions); + + var url1 = 'http://example.com/index.html' + var filename1 = 'index.html'; + var localFilename1 = loader.getFilename(filename1); + loader.setLoadedFilename(url1, localFilename1); + + var url2 = 'http://example.com/blog/index.html' + var filename2 = 'index.html'; + var localFilename2 = loader.getFilename(filename2); + loader.setLoadedFilename(url2, localFilename2); + + var url3 = 'http://example.com/about/index.html' + var filename3 = 'index.html'; + var localFilename3 = loader.getFilename(filename3); + loader.setLoadedFilename(url3, localFilename3); + + localFilename1.should.not.be.equal(localFilename2); + localFilename2.should.not.be.equal(localFilename3); + localFilename3.should.not.be.equal(localFilename1); + }); + }); +});
b2d24110d49b6e2b694237e3fe0d8263ef684e68
src/sandbox.tasker.js
src/sandbox.tasker.js
const vm = require('vm'); const fs = require('fs'); const path = require('path'); function convertVariablesToWhatTaskerWouldSend(taskerLocalVariables) { const convertedTaskerLocalVariables = {}; Object.getOwnPropertyNames(taskerLocalVariables).forEach((propertyName) => { const propertyValue = taskerLocalVariables[propertyName]; if (propertyValue instanceof Array) { convertedTaskerLocalVariables[propertyName] = propertyValue; } else if (propertyValue instanceof Function) { console.info(`Converting function ${propertyName} to String before passing it to JavaScript helper`); convertedTaskerLocalVariables[propertyName] = propertyValue.toString(); } else if (propertyValue instanceof Object) { console.info(`Converting Object ${propertyName} to String before passing it to JavaScript helper`); convertedTaskerLocalVariables[propertyName] = JSON.stringify(propertyValue); } else { convertedTaskerLocalVariables[propertyName] = propertyValue; } }); return convertedTaskerLocalVariables; } /** * Run a JavaScript helper with a set of local Tasker variables * @param {String} fileNameUnderTest - The filename of the helper to test * @param {Object} taskerLocalVariables - key-value pairs of local variable values */ function runScript(fileNameUnderTest, taskerLocalVariables) { const fileUnderTest = path.join(__dirname, fileNameUnderTest); const doesFileUnderTestExist = fs.existsSync(fileUnderTest); if (!doesFileUnderTestExist) { console.error(`File you are testing does not exist: ${fileUnderTest}`); return; } const file = fs.readFileSync(fileUnderTest); const convertedTaskerLocalVariables = convertVariablesToWhatTaskerWouldSend(taskerLocalVariables); const context = { ...convertedTaskerLocalVariables, require: require }; vm.createContext(context); const script = new vm.Script(file, { filename: fileUnderTest }); script.runInContext(context); } exports.default = runScript;
Add sandbox to test Tasker JavaScript helpers
Add sandbox to test Tasker JavaScript helpers
JavaScript
mit
StephenGregory/TaskerJavaScriptHelpers
--- +++ @@ -0,0 +1,54 @@ +const vm = require('vm'); +const fs = require('fs'); +const path = require('path'); + +function convertVariablesToWhatTaskerWouldSend(taskerLocalVariables) { + const convertedTaskerLocalVariables = {}; + Object.getOwnPropertyNames(taskerLocalVariables).forEach((propertyName) => { + const propertyValue = taskerLocalVariables[propertyName]; + if (propertyValue instanceof Array) { + convertedTaskerLocalVariables[propertyName] = propertyValue; + } + else if (propertyValue instanceof Function) { + console.info(`Converting function ${propertyName} to String before passing it to JavaScript helper`); + convertedTaskerLocalVariables[propertyName] = propertyValue.toString(); + } + else if (propertyValue instanceof Object) { + console.info(`Converting Object ${propertyName} to String before passing it to JavaScript helper`); + convertedTaskerLocalVariables[propertyName] = JSON.stringify(propertyValue); + } + else { + convertedTaskerLocalVariables[propertyName] = propertyValue; + } + }); + return convertedTaskerLocalVariables; +} + +/** +* Run a JavaScript helper with a set of local Tasker variables +* @param {String} fileNameUnderTest - The filename of the helper to test +* @param {Object} taskerLocalVariables - key-value pairs of local variable values +*/ +function runScript(fileNameUnderTest, taskerLocalVariables) { + const fileUnderTest = path.join(__dirname, fileNameUnderTest); + const doesFileUnderTestExist = fs.existsSync(fileUnderTest); + + if (!doesFileUnderTestExist) { + console.error(`File you are testing does not exist: ${fileUnderTest}`); + return; + } + + const file = fs.readFileSync(fileUnderTest); + + const convertedTaskerLocalVariables = convertVariablesToWhatTaskerWouldSend(taskerLocalVariables); + + const context = { + ...convertedTaskerLocalVariables, + require: require + }; + vm.createContext(context); + const script = new vm.Script(file, { filename: fileUnderTest }); + script.runInContext(context); +} + +exports.default = runScript;
29af056784a9695da0a1d71587f2f1e1a12e4517
deckglue/static/learning/js/show_answer.js
deckglue/static/learning/js/show_answer.js
function show_answer() { if ($("#answer").is(':visible')) { return; } $("#answer").show() $("#rating").show() $("#preanswer").hide() } if ($.urlParam('showAnswer')=='true'){ $(show_answer); }
Add show answer js function for learning
Add show answer js function for learning
JavaScript
mit
DummyDivision/Tsune,DummyDivision/Tsune,DummyDivision/Tsune
--- +++ @@ -0,0 +1,12 @@ +function show_answer() { + if ($("#answer").is(':visible')) { + return; + } + $("#answer").show() + $("#rating").show() + $("#preanswer").hide() +} + +if ($.urlParam('showAnswer')=='true'){ + $(show_answer); +}
a52738276cda5027862acddfbd9f88d82f757b62
src/app/components/facebook/LoginStatus.js
src/app/components/facebook/LoginStatus.js
import React from 'react'; import THREE from 'three'; export default class LoginStatus extends React.Component { static propTypes = { isConnected: React.PropTypes.bool, position: React.PropTypes.instanceOf(THREE.Vector3), frameNumber: React.PropTypes.number }; static defaultProps = { isConnected: false, frameNumber: 0 }; render() { let size = 10; let rotation = new THREE.Euler(); if (this.props.isConnected) { size = 40; let rotationY = (this.props.frameNumber % (360 * 10)) / 500; rotation = new THREE.Euler(0, rotationY, 0); } return ( <mesh position={this.props.position} rotation={rotation} visible={this.props.isConnected} > <boxGeometry width={size} height={size} depth={size} widthSegments={20} heightSegments={10} /> <materialResource resourceId='facebookMaterial' /> </mesh> ); } }
Create Facebook Login Status 3D component (display rotating fb box when connected)
Create Facebook Login Status 3D component (display rotating fb box when connected)
JavaScript
apache-2.0
Colmea/facebook-webvr,Colmea/facebook-webvr
--- +++ @@ -0,0 +1,46 @@ +import React from 'react'; +import THREE from 'three'; + +export default class LoginStatus extends React.Component +{ + static propTypes = { + isConnected: React.PropTypes.bool, + position: React.PropTypes.instanceOf(THREE.Vector3), + frameNumber: React.PropTypes.number + }; + + static defaultProps = { + isConnected: false, + frameNumber: 0 + }; + + render() { + let size = 10; + let rotation = new THREE.Euler(); + + if (this.props.isConnected) { + size = 40; + + let rotationY = (this.props.frameNumber % (360 * 10)) / 500; + rotation = new THREE.Euler(0, rotationY, 0); + } + + return ( + <mesh + position={this.props.position} + rotation={rotation} + visible={this.props.isConnected} + > + <boxGeometry + width={size} + height={size} + depth={size} + widthSegments={20} + heightSegments={10} + /> + <materialResource resourceId='facebookMaterial' /> + + </mesh> + ); + } +}
780dcdde1a9c6ae437f9aec82de55997b75e2e8c
16/sharp-crop.js
16/sharp-crop.js
var sharp = require('sharp'); var dirpath = 'images/'; var imgname = 'download-logo.png'; var tmppath = 'tmp/' sharp(dirpath + imgname) .resize(50, 100) .crop() .toFile(tmppath + 'New_' + imgname, function (err, info) { if (err) throw err; console.log('done'); });
Add the example to crop image via sharp.
Add the example to crop image via sharp.
JavaScript
mit
nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference
--- +++ @@ -0,0 +1,14 @@ +var sharp = require('sharp'); + +var dirpath = 'images/'; +var imgname = 'download-logo.png'; +var tmppath = 'tmp/' + +sharp(dirpath + imgname) + .resize(50, 100) + .crop() + .toFile(tmppath + 'New_' + imgname, function (err, info) { + if (err) + throw err; + console.log('done'); + });
da4102c5fbf0303f8a394ceb42a28909db8470f5
test/test.extends.js
test/test.extends.js
var Twig = Twig || require("../twig"), twig = twig || Twig.twig; describe("Twig.js Extensions ->", function() { it("should be able to extend a meta-type tag", function() { var flags = {}; Twig.extend(function(Twig) { Twig.exports.extendTag({ type: "flag", regex: /^flag\s+(.+)$/, next: [ ], open: true, compile: function (token) { var expression = token.match[1]; // Compile the expression. token.stack = Twig.expression.compile.apply(this, [{ type: Twig.expression.type.expression, value: expression }]).stack; delete token.match; return token; }, parse: function (token, context, chain) { var name = Twig.expression.parse.apply(this, [token.stack, context]), output = ''; flags[name] = true; return { chain: false, output: output }; } }); }); var template = twig({data:"{% flag 'enabled' %}"}).render(); flags.enabled.should.equal(true); }); it("should be able to extend paired tags", function() { // demo data var App = { user: "john", users: { john: {level: "admin"}, tom: {level: "user"} } }; Twig.extend(function(Twig) { // example of extending a tag type that would // restrict content to the specified "level" Twig.exports.extendTag({ type: "auth", regex: /^auth\s+(.+)$/, next: ["endauth"], // match the type of the end tag open: true, compile: function (token) { var expression = token.match[1]; // turn the string expression into tokens. token.stack = Twig.expression.compile.apply(this, [{ type: Twig.expression.type.expression, value: expression }]).stack; delete token.match; return token; }, parse: function (token, context, chain) { var level = Twig.expression.parse.apply(this, [token.stack, context]), output = ""; if (App.users[App.currentUser].level == level) { output = Twig.parse.apply(this, [token.output, context]); } return { chain: chain, output: output }; } }); Twig.exports.extendTag({ type: "endauth", regex: /^endauth$/, next: [ ], open: false }); }); var template = twig({data:"Welcome{% auth 'admin' %} ADMIN{% endauth %}!"}); App.currentUser = "john"; template.render().should.equal("Welcome ADMIN!"); App.currentUser = "tom"; template.render().should.equal("Welcome!"); }); });
Add test with examples of extending twig.js with new tags
Add test with examples of extending twig.js with new tags
JavaScript
bsd-2-clause
rafaellyra/twig.js,justjohn/twig.js,AndBicScadMedia/twig.js,roelvanduijnhoven/twig.js,felicast/twig.js,moodtraffic/twig.js,PeterDaveHello/twig.js,rafaellyra/twig.js,rafaellyra/twig.js,DethCount/twig.js,sarahjean/twig.js,targos/twig.js,plepe/twig.js,roelvanduijnhoven/twig.js,DethCount/twig.js,PeterDaveHello/twig.js,moodtraffic/twig.js,zimmo-be/twig.js,targos/twig.js,onedal88/twig.js,dave-irvine/twig.js,targos/twig.js,roelvanduijnhoven/twig.js,dave-irvine/twig.js,zimmo-be/twig.js,sarahjean/twig.js,sarahjean/twig.js,justjohn/twig.js,AndBicScadMedia/twig.js,d-simon/twig.js,PeterDaveHello/twig.js,twigjs/twig.js,DethCount/twig.js,AndBicScadMedia/twig.js,FoxyCart/twig.js,onedal88/twig.js,FoxyCart/twig.js,d-simon/twig.js,justjohn/twig.js,onedal88/twig.js,plepe/twig.js,FoxyCart/twig.js,plepe/twig.js,moodtraffic/twig.js,twigjs/twig.js,dave-irvine/twig.js,felicast/twig.js,felicast/twig.js,zimmo-be/twig.js,twigjs/twig.js,d-simon/twig.js
--- +++ @@ -0,0 +1,105 @@ +var Twig = Twig || require("../twig"), + twig = twig || Twig.twig; + +describe("Twig.js Extensions ->", function() { + it("should be able to extend a meta-type tag", function() { + var flags = {}; + + Twig.extend(function(Twig) { + Twig.exports.extendTag({ + type: "flag", + regex: /^flag\s+(.+)$/, + next: [ ], + open: true, + compile: function (token) { + var expression = token.match[1]; + + // Compile the expression. + token.stack = Twig.expression.compile.apply(this, [{ + type: Twig.expression.type.expression, + value: expression + }]).stack; + + delete token.match; + return token; + }, + parse: function (token, context, chain) { + var name = Twig.expression.parse.apply(this, [token.stack, context]), + output = ''; + + flags[name] = true; + + return { + chain: false, + output: output + }; + } + }); + }); + + var template = twig({data:"{% flag 'enabled' %}"}).render(); + flags.enabled.should.equal(true); + }); + + it("should be able to extend paired tags", function() { + // demo data + var App = { + user: "john", + users: { + john: {level: "admin"}, + tom: {level: "user"} + } + }; + + Twig.extend(function(Twig) { + // example of extending a tag type that would + // restrict content to the specified "level" + Twig.exports.extendTag({ + type: "auth", + regex: /^auth\s+(.+)$/, + next: ["endauth"], // match the type of the end tag + open: true, + compile: function (token) { + var expression = token.match[1]; + + // turn the string expression into tokens. + token.stack = Twig.expression.compile.apply(this, [{ + type: Twig.expression.type.expression, + value: expression + }]).stack; + + delete token.match; + return token; + }, + parse: function (token, context, chain) { + var level = Twig.expression.parse.apply(this, [token.stack, context]), + output = ""; + + if (App.users[App.currentUser].level == level) + { + output = Twig.parse.apply(this, [token.output, context]); + } + + return { + chain: chain, + output: output + }; + } + }); + Twig.exports.extendTag({ + type: "endauth", + regex: /^endauth$/, + next: [ ], + open: false + }); + }); + + var template = twig({data:"Welcome{% auth 'admin' %} ADMIN{% endauth %}!"}); + + App.currentUser = "john"; + template.render().should.equal("Welcome ADMIN!"); + + App.currentUser = "tom"; + template.render().should.equal("Welcome!"); + }); +});
1d4c0a9f9d64e34df4947c573272468f31333c9c
src/components/buttonGroup/buttonGroup.stories.spec.js
src/components/buttonGroup/buttonGroup.stories.spec.js
import React from 'react'; import ButtonGroup from './ButtonGroup'; import Button from '../button'; export default { component: ButtonGroup, title: 'ButtonGroup', }; const Wrapper = ({ children }) => <div style={{ minHeight: '60px' }}>{children}</div>; export const Main = () => ( <div> {['primary', 'secondary', 'destructive', 'timer'].map((level) => ['small', 'medium', 'large'].map((size) => ( <React.Fragment key={level + size}> <Wrapper> <ButtonGroup level={level} size={size}> <Button>One</Button> <Button>Two</Button> <Button>Three</Button> </ButtonGroup> </Wrapper> <Wrapper> <ButtonGroup level={level} size={size} segmented> <Button>One</Button> <Button>Two</Button> <Button>Three</Button> </ButtonGroup> </Wrapper> <Wrapper> <ButtonGroup level={level} size={size} value="two"> <Button value="one">One</Button> <Button value="two">Two</Button> <Button value="three">Three</Button> </ButtonGroup> </Wrapper> <Wrapper> <ButtonGroup level={level} size={size} segmented value="two"> <Button value="one">One</Button> <Button value="two">Two</Button> <Button value="three">Three</Button> </ButtonGroup> </Wrapper> </React.Fragment> )), )} </div> );
Add a test story for the ButtonGroup component
Add a test story for the ButtonGroup component
JavaScript
mit
teamleadercrm/teamleader-ui
--- +++ @@ -0,0 +1,50 @@ +import React from 'react'; + +import ButtonGroup from './ButtonGroup'; +import Button from '../button'; + +export default { + component: ButtonGroup, + title: 'ButtonGroup', +}; + +const Wrapper = ({ children }) => <div style={{ minHeight: '60px' }}>{children}</div>; + +export const Main = () => ( + <div> + {['primary', 'secondary', 'destructive', 'timer'].map((level) => + ['small', 'medium', 'large'].map((size) => ( + <React.Fragment key={level + size}> + <Wrapper> + <ButtonGroup level={level} size={size}> + <Button>One</Button> + <Button>Two</Button> + <Button>Three</Button> + </ButtonGroup> + </Wrapper> + <Wrapper> + <ButtonGroup level={level} size={size} segmented> + <Button>One</Button> + <Button>Two</Button> + <Button>Three</Button> + </ButtonGroup> + </Wrapper> + <Wrapper> + <ButtonGroup level={level} size={size} value="two"> + <Button value="one">One</Button> + <Button value="two">Two</Button> + <Button value="three">Three</Button> + </ButtonGroup> + </Wrapper> + <Wrapper> + <ButtonGroup level={level} size={size} segmented value="two"> + <Button value="one">One</Button> + <Button value="two">Two</Button> + <Button value="three">Three</Button> + </ButtonGroup> + </Wrapper> + </React.Fragment> + )), + )} + </div> +);
d91d76016cfc3ee0c65fda07830e858394b2aed6
server/watson.js
server/watson.js
var watson = require('watson-developer-cloud'); var speech_to_text = watson.speech_to_text({ username: '{andrew.p.bresee@gmail.com}', password: '{speechdoctor499}', version: 'v1' }); speech_to_text.getModels({}, function(err, models) { if (err) console.log('error:', err); else console.log(JSON.stringify(models, null, 2)); }); speech_to_text.getModel({model_id: 'WatsonModel'}, function(err, model) { if (err) console.log('error:', err); else console.log(JSON.stringify(model, null, 2)); }); speech_to_text.createSession({}, function(err, session) { if (err) console.log('error:', err); else console.log(JSON.stringify(session, null, 2)); });
Change test to stop after ten words
Change test to stop after ten words
JavaScript
mit
nonchalantkettle/SpeechDoctor,nonchalantkettle/SpeechDoctor,alexxisroxxanne/SpeechDoctor,alexxisroxxanne/SpeechDoctor
--- +++ @@ -0,0 +1,28 @@ +var watson = require('watson-developer-cloud'); + +var speech_to_text = watson.speech_to_text({ + username: '{andrew.p.bresee@gmail.com}', + password: '{speechdoctor499}', + version: 'v1' +}); + +speech_to_text.getModels({}, function(err, models) { + if (err) + console.log('error:', err); + else + console.log(JSON.stringify(models, null, 2)); +}); + +speech_to_text.getModel({model_id: 'WatsonModel'}, function(err, model) { + if (err) + console.log('error:', err); + else + console.log(JSON.stringify(model, null, 2)); +}); + +speech_to_text.createSession({}, function(err, session) { + if (err) + console.log('error:', err); + else + console.log(JSON.stringify(session, null, 2)); +});
5c0a8630512a4a417ef69c6bba917dcaf05b888d
src/Clastic/BackofficeBundle/Resources/public/scripts/form.parsley.js
src/Clastic/BackofficeBundle/Resources/public/scripts/form.parsley.js
(function() { var $form = $('form'); $form.parsley(); $.listen('parsley:form:validated', function() { var $tabpanel = $form.find('.tabpanel'); if ($tabpanel.length) { var $firstError = $tabpanel.find('.parsley-error').first(); if ($firstError) { var $tab = $form.find('[role="tablist"] li').eq($firstError.closest('.tab-pane').index()); $tab.find('a').tab('show'); } } }); }());
(function() { var $form = $('form'); $form.parsley(); $.listen('parsley:form:validated', function() { var $tabpanel = $form.find('.tabpanel'); if ($tabpanel.length) { var $firstError = $tabpanel.find('.parsley-error').first(); if ($firstError.length) { var $tab = $form.find('[role="tablist"] li').eq($firstError.closest('.tab-pane').index()); $tab.find('a').tab('show'); } } }); }());
Fix show of last tab when validating valid form.
[Backoffice] Fix show of last tab when validating valid form. Fixes #50.
JavaScript
mit
Windmolders/Clastic,Clastic/Clastic,Windmolders/Clastic,Clastic/Clastic,NoUseFreak/Clastic,Windmolders/Clastic,NoUseFreak/Clastic,NoUseFreak/Clastic,Clastic/Clastic
--- +++ @@ -5,7 +5,7 @@ var $tabpanel = $form.find('.tabpanel'); if ($tabpanel.length) { var $firstError = $tabpanel.find('.parsley-error').first(); - if ($firstError) { + if ($firstError.length) { var $tab = $form.find('[role="tablist"] li').eq($firstError.closest('.tab-pane').index()); $tab.find('a').tab('show'); }
ecd884fee79194456258c2f6384fb8f0a4109480
app/admin-tab/processes/process/route.js
app/admin-tab/processes/process/route.js
import Ember from 'ember'; export default Ember.Route.extend({ params: null, model: function(params /*, transition*/ ) { this.set('params', params); return this.get('store').find('processinstance', params.process_id).then((processInstance) => { return processInstance.followLink('processExecutions').then((processExecutions) => { var sorted = processExecutions.get('content').reverse(); processExecutions.set('content', sorted); return Ember.Object.create({ processInstance: processInstance, processExecutions: processExecutions }); }, ( /*reject*/ ) => { //do some errors }); }); }, intervalId: null, setupController: function(controller, model) { this._super(controller, model); const intervalCount = 2000; if (!this.get('intervalId')) { this.set('intervalId', setInterval(() => { this.get('store').find('processInstance', this.get('params').process_id).then((processInstance) => { processInstance.followLink('processExecutions').then((processExecutions) => { var sorted = processExecutions.get('content').reverse(); processExecutions.set('content', sorted); this.controller.get('model.processExecutions').replaceWith(processExecutions); }); }); }, intervalCount)); } }, deactivate: function() { clearInterval(this.get('intervalId')); } });
import Ember from 'ember'; export default Ember.Route.extend({ params: null, model: function(params /*, transition*/ ) { this.set('params', params); return this.get('store').find('processinstance', params.process_id).then((processInstance) => { return processInstance.followLink('processExecutions').then((processExecutions) => { var sorted = processExecutions.get('content').reverse(); processExecutions.set('content', sorted); return Ember.Object.create({ processInstance: processInstance, processExecutions: processExecutions }); }, ( /*reject*/ ) => { //do some errors }); }); } });
Remove the interval check for child processes
Remove the interval check for child processes
JavaScript
apache-2.0
lvuch/ui,rancher/ui,rancher/ui,westlywright/ui,westlywright/ui,rancherio/ui,vincent99/ui,westlywright/ui,rancherio/ui,nrvale0/ui,rancher/ui,rancherio/ui,nrvale0/ui,nrvale0/ui,pengjiang80/ui,ubiquityhosting/rancher_ui,lvuch/ui,vincent99/ui,lvuch/ui,pengjiang80/ui,pengjiang80/ui,ubiquityhosting/rancher_ui,ubiquityhosting/rancher_ui,vincent99/ui
--- +++ @@ -16,24 +16,5 @@ //do some errors }); }); - }, - intervalId: null, - setupController: function(controller, model) { - this._super(controller, model); - const intervalCount = 2000; - if (!this.get('intervalId')) { - this.set('intervalId', setInterval(() => { - this.get('store').find('processInstance', this.get('params').process_id).then((processInstance) => { - processInstance.followLink('processExecutions').then((processExecutions) => { - var sorted = processExecutions.get('content').reverse(); - processExecutions.set('content', sorted); - this.controller.get('model.processExecutions').replaceWith(processExecutions); - }); - }); - }, intervalCount)); - } - }, - deactivate: function() { - clearInterval(this.get('intervalId')); } });
61461eba5bcc91a01eb565c52a615e33ccb256d7
bezier-curve/js/point.js
bezier-curve/js/point.js
/*exported Point, Endpoint, ControlPoint*/ var Point = (function() { 'use strict'; function Point( x, y ) { this.x = x; this.y = y; } Point.prototype.add = function( x, y ) { this.x += x; this.y += y; return this; }; Point.prototype.sub = function( x, y ) { this.x -= x; this.y -= y; return this; }; Point.prototype.set = function( x, y ) { this.x = x; this.y = y; return this; }; return Point; }) (); var ControlPoint = (function() { 'use strict'; function ControlPoint( x, y ) { Point.call( this, x, y ); } ControlPoint.prototype = Object.create( Point.prototype ); ControlPoint.prototype.constructor = ControlPoint; return ControlPoint; }) (); var Endpoint = (function() { 'use strict'; function Endpoint( x, y ) { ControlPoint.call( this, x, y ); } Endpoint.prototype = Object.create( ControlPoint.prototype ); Endpoint.prototype.constructor = Endpoint; return Endpoint; }) ();
Add separate Point classes file.
bezier-curve: Add separate Point classes file.
JavaScript
mit
razh/experiments,razh/experiments,razh/experiments
--- +++ @@ -0,0 +1,60 @@ +/*exported Point, Endpoint, ControlPoint*/ +var Point = (function() { + 'use strict'; + + function Point( x, y ) { + this.x = x; + this.y = y; + } + + Point.prototype.add = function( x, y ) { + this.x += x; + this.y += y; + return this; + }; + + Point.prototype.sub = function( x, y ) { + this.x -= x; + this.y -= y; + return this; + }; + + Point.prototype.set = function( x, y ) { + this.x = x; + this.y = y; + return this; + }; + + return Point; + +}) (); + + +var ControlPoint = (function() { + 'use strict'; + + function ControlPoint( x, y ) { + Point.call( this, x, y ); + } + + ControlPoint.prototype = Object.create( Point.prototype ); + ControlPoint.prototype.constructor = ControlPoint; + + return ControlPoint; + +}) (); + + +var Endpoint = (function() { + 'use strict'; + + function Endpoint( x, y ) { + ControlPoint.call( this, x, y ); + } + + Endpoint.prototype = Object.create( ControlPoint.prototype ); + Endpoint.prototype.constructor = Endpoint; + + return Endpoint; + +}) ();
8c6ca6582e54d8911678cac49c8d9e43433fc524
javascript/ql/test/library-tests/TaintTracking/summarize-store-load-in-call.js
javascript/ql/test/library-tests/TaintTracking/summarize-store-load-in-call.js
import * as dummy from 'dummy'; function blah(obj) { obj.prop = obj.prop + "x"; return obj.prop; } function test() { sink(blah(source())); // NOT OK blah(); // ensure more than one call site exists }
Add test showing missing flow
JS: Add test showing missing flow
JavaScript
mit
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
--- +++ @@ -0,0 +1,12 @@ +import * as dummy from 'dummy'; + +function blah(obj) { + obj.prop = obj.prop + "x"; + return obj.prop; +} + +function test() { + sink(blah(source())); // NOT OK + + blah(); // ensure more than one call site exists +}
e7bd02fba22ec513b4c7057ed483edd9c7769e4f
server/seeders/20170731120851-roles.js
server/seeders/20170731120851-roles.js
'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Roles', [{ role: 'admin', createdAt: new Date(), updatedAt: new Date() }, { role: 'user', createdAt: new Date(), updatedAt: new Date() }, { role: 'editor', createdAt: new Date(), updatedAt: new Date() } ], {}); }, down: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Roles', null, {}); } };
Define role types in seeders folder
Define role types in seeders folder
JavaScript
mit
vynessa/dman,vynessa/dman
--- +++ @@ -0,0 +1,29 @@ +'use strict'; + +module.exports = { + up: (queryInterface, Sequelize) => { + return queryInterface.bulkInsert('Roles', + [{ + role: 'admin', + createdAt: new Date(), + updatedAt: new Date() + }, + + { + role: 'user', + createdAt: new Date(), + updatedAt: new Date() + }, + + { + role: 'editor', + createdAt: new Date(), + updatedAt: new Date() + } + ], {}); + }, + + down: (queryInterface, Sequelize) => { + return queryInterface.bulkInsert('Roles', null, {}); + } +};
e38f50526425c23f38e08d3f163a93a5534b6c8b
client/userlist.js
client/userlist.js
var UserList = React.createClass({ componentDidMount: function() { socket.on('join', this._join); socket.on('part', this._part); }, render: function() { return ( <ul id='online-list'> <li> <img src='https://avatars.githubusercontent.com/dionyziz' alt='' class='avatar' /> <span>dionyziz</span> </li> </ul> ); }, _join: function(username) { if (username != myUsername) { addOnlineUserToList(username); } }, _part: function(username) { $('#online-list li span').filter(function() { return $(this).text() == username; }).parent().remove(); } }); React.render(<UserList />, document.getElementsByClassName('nicklist')[0]);
var UserList = React.createClass({ componentDidMount: function() { socket.on('join', this._join); socket.on('part', this._part); }, render: function() { return ( <ul id='online-list'></ul> ); }, _join: function(username) { if (username != myUsername) { addOnlineUserToList(username); } }, _part: function(username) { $('#online-list li span').filter(function() { return $(this).text() == username; }).parent().remove(); } }); React.render(<UserList />, document.getElementsByClassName('nicklist')[0]);
Remove placeholder content from online list
Remove placeholder content from online list
JavaScript
mit
gtklocker/ting,VitSalis/ting,mbalamat/ting,gtklocker/ting,VitSalis/ting,dionyziz/ting,VitSalis/ting,mbalamat/ting,mbalamat/ting,odyvarv/ting-1,sirodoht/ting,odyvarv/ting-1,dionyziz/ting,dionyziz/ting,odyvarv/ting-1,odyvarv/ting-1,sirodoht/ting,sirodoht/ting,mbalamat/ting,VitSalis/ting,gtklocker/ting,gtklocker/ting,sirodoht/ting,dionyziz/ting
--- +++ @@ -5,12 +5,7 @@ }, render: function() { return ( - <ul id='online-list'> - <li> - <img src='https://avatars.githubusercontent.com/dionyziz' alt='' class='avatar' /> - <span>dionyziz</span> - </li> - </ul> + <ul id='online-list'></ul> ); }, _join: function(username) {
2a790870e79764ef76614a3a870b2aba09ff4784
test/api/ripple_transactions.js
test/api/ripple_transactions.js
var assert = require("assert"); describe('APi for Ripple Transactions', function(){ describe('creating a ripple transaction', function(){ it('should require a ripple address id of the recipient user', function(fn){ }); it('should require a ripple address id of the sending user', function(fn){ }); it('should require ripple address id of the recipient be in the database', function(fn) { }); it('should require ripple address id of the sender be in the database', function(fn) { }); }); describe('updating a ripple transaction', function() { it('should be able able to update the transaction hash', function(fn){ }); it('should be able to update the transaction state', function(fn) { }); it('should not be able to update any other attributes', function(fn){ }); }); describe('retrieving ripple transaction records', function(){ it('should be able to get a single ripple transaction using its id', function(fn){ }); it('should be able to get multiple ripple transactions using an array of ids', function(fn){ }); it('should be able to get all ripple transactions', function(fn){ }); }); describe('deleting a ripple transaction record', function(){ it('should be able to delete a single transaction record with the transaction id', function(fn){ }); it('should be able to delete many transactions with an array of transaction ids', function(fn){ }); }); });
Add API level test descriptions. for ripple transactions.
[TEST] Add API level test descriptions. for ripple transactions.
JavaScript
isc
xdv/gatewayd,xdv/gatewayd,crazyquark/gatewayd,crazyquark/gatewayd,Parkjeahwan/awegeeks,whotooktwarden/gatewayd,whotooktwarden/gatewayd,zealord/gatewayd,zealord/gatewayd,Parkjeahwan/awegeeks
--- +++ @@ -0,0 +1,68 @@ +var assert = require("assert"); + +describe('APi for Ripple Transactions', function(){ + + describe('creating a ripple transaction', function(){ + + it('should require a ripple address id of the recipient user', function(fn){ + + }); + + it('should require a ripple address id of the sending user', function(fn){ + + }); + + it('should require ripple address id of the recipient be in the database', function(fn) { + + }); + + it('should require ripple address id of the sender be in the database', function(fn) { + + }); + }); + + describe('updating a ripple transaction', function() { + + it('should be able able to update the transaction hash', function(fn){ + + }); + + it('should be able to update the transaction state', function(fn) { + + }); + + it('should not be able to update any other attributes', function(fn){ + + }); + + }); + + describe('retrieving ripple transaction records', function(){ + + it('should be able to get a single ripple transaction using its id', function(fn){ + + }); + + it('should be able to get multiple ripple transactions using an array of ids', function(fn){ + + }); + + it('should be able to get all ripple transactions', function(fn){ + + }); + + }); + + describe('deleting a ripple transaction record', function(){ + + it('should be able to delete a single transaction record with the transaction id', function(fn){ + + }); + + it('should be able to delete many transactions with an array of transaction ids', function(fn){ + + }); + + }); + +});
6c9d24b533197af8e17406b38850a679a4bd2dab
is.js
is.js
// is.js 0.0.1 // Author Aras Atasaygin ;(function() { // Baseline // -------- // root object is window in the browser var root = this; // define is object, current version and configs var is = {}; is.version = '0.0.1'; is.config = {}; // TODO: Add AMD and CommonJS support // is object set global to the browser window root.is = is; // Type checks // ----------- // Test check is.testCheck = function(a) { console.log('test check ' + a); } // Presence checks // --------------- // Regexp checks // ------------- // Environment checks // ------------------ // Arithmetic checks // ----------------- // Time checks // ----------- // Array checks // ------------ // Object checks // ------------- // DOM checks // ---------- // Syntax checks // ---------- // String checks // ---------- // ES6 checks // ---------- }.call(this));
// is.js 0.0.1 // Author Aras Atasaygin ;(function() { // Baseline // -------- // root object is window in the browser var root = this; // define is object, current version and configs var is = {}; is.version = '0.0.1'; is.config = {}; // TODO: Add AMD and CommonJS support // is object set global to the browser window root.is = is; // Type checks // ----------- // is a given value array is.array = Array.isArray || function(value) { // check native isArray first return Object.prototype.toString.call(value) === '[object Array]'; } // Presence checks // --------------- // Regexp checks // ------------- // Environment checks // ------------------ // Arithmetic checks // ----------------- // Time checks // ----------- // Array checks // ------------ // Object checks // ------------- // DOM checks // ---------- // Syntax checks // ---------- // String checks // ---------- // ES6 checks // ---------- }.call(this));
Add first type(array) check method.
Add first type(array) check method.
JavaScript
mit
dkfiresky/is.js,arasatasaygin/is.js,ekaradon/is.js,arasatasaygin/is.js,ryantemple/is.js,rlugojr/is.js,ironmaniiith/is.js,hi-q/is.js,jaspreet21anand/isjs,fermanakgun/is.js,rlugojr/is.js,dstyle0210/is.js,iLikeKoffee/is.js,dstyle0210/is.js,iLikeKoffee/is.js,dkfiresky/is.js,ironmaniiith/is.js,polymaths/is.js,ErikaLim/is.js,ekaradon/is.js,jaspreet21anand/isjs,polymaths/is.js,ryantemple/is.js,Guru107/is.js,mathiasbynens/is.js
--- +++ @@ -1,62 +1,62 @@ -// is.js 0.0.1 -// Author Aras Atasaygin +// is.js 0.0.1 +// Author Aras Atasaygin ;(function() { - // Baseline - // -------- + // Baseline + // -------- - // root object is window in the browser - var root = this; + // root object is window in the browser + var root = this; - // define is object, current version and configs - var is = {}; - is.version = '0.0.1'; - is.config = {}; + // define is object, current version and configs + var is = {}; + is.version = '0.0.1'; + is.config = {}; - // TODO: Add AMD and CommonJS support - // is object set global to the browser window - root.is = is; + // TODO: Add AMD and CommonJS support + // is object set global to the browser window + root.is = is; - // Type checks - // ----------- + // Type checks + // ----------- - // Test check - is.testCheck = function(a) { - console.log('test check ' + a); - } + // is a given value array + is.array = Array.isArray || function(value) { // check native isArray first + return Object.prototype.toString.call(value) === '[object Array]'; + } - // Presence checks - // --------------- + // Presence checks + // --------------- - // Regexp checks - // ------------- + // Regexp checks + // ------------- - // Environment checks - // ------------------ + // Environment checks + // ------------------ - // Arithmetic checks - // ----------------- + // Arithmetic checks + // ----------------- - // Time checks - // ----------- + // Time checks + // ----------- - // Array checks - // ------------ + // Array checks + // ------------ - // Object checks - // ------------- + // Object checks + // ------------- - // DOM checks - // ---------- + // DOM checks + // ---------- - // Syntax checks - // ---------- + // Syntax checks + // ---------- - // String checks - // ---------- + // String checks + // ---------- - // ES6 checks - // ---------- + // ES6 checks + // ---------- }.call(this));
ac539da7a32fac98c5a6266e0b2d88c336623b83
tests/stack-test.js
tests/stack-test.js
"use strict"; /** * Test cases for eStack data structure */ describe("eStack - isstack query", function () { it("should return type of eStack", function () { var stack = new eStack(); expect(stack.getType()).toBe('eStack'); }); }); describe("eStack - add element to stack", function () { it("should return 1 when an element is added to an empty stack", function () { var stack = new eStack(); expect(stack.put(2)).toBe(1); }); }); describe("eStack - get size of stack", function () { var stack = new eStack(); stack.put(2); stack.put(3); it("should return the number of elements in the stack", function () { expect(stack.size()).toBe(2); }); }); describe("eStack - return the element at the head of the stack without removing it", function () { var stack = new eStack(); stack.put(2); stack.put(3); it("should return 2", function () { expect(stack.peek()).toBe(2); }); it("should return 2", function () { expect(stack.size()).toBe(2); }); }); describe("eStack - return the element at the head of the stack and remove it", function () { var stack = new eStack(); stack.put(2); stack.put(3); it("should return 2", function () { expect(stack.remove()).toBe(2); }); it("should return 1", function () { expect(stack.size()).toBe(1); }); }); describe("eStack - clear contents of stack", function () { var stack = new eStack(); stack.put(2); stack.put(3); stack.clear(); it("stack size should return 0 after calling clear function", function () { expect(stack.size()).toBe(0); }); }); describe("eStack - convert stack to array", function () { it("should be an instance of Array", function () { var stack = new eStack(); expect(stack.toArray() instanceof Array).toBe(true); }); });
Add unit test cases for eStack
Add unit test cases for eStack
JavaScript
mit
toystars/eStructures,toystars/eStructures
--- +++ @@ -0,0 +1,80 @@ + +"use strict"; + +/** + * Test cases for eStack data structure + */ + +describe("eStack - isstack query", function () { + it("should return type of eStack", function () { + var stack = new eStack(); + expect(stack.getType()).toBe('eStack'); + }); +}); + +describe("eStack - add element to stack", function () { + it("should return 1 when an element is added to an empty stack", function () { + var stack = new eStack(); + expect(stack.put(2)).toBe(1); + }); +}); + +describe("eStack - get size of stack", function () { + + var stack = new eStack(); + stack.put(2); + stack.put(3); + + it("should return the number of elements in the stack", function () { + expect(stack.size()).toBe(2); + }); + +}); + +describe("eStack - return the element at the head of the stack without removing it", function () { + + var stack = new eStack(); + stack.put(2); + stack.put(3); + + it("should return 2", function () { + expect(stack.peek()).toBe(2); + }); + + it("should return 2", function () { + expect(stack.size()).toBe(2); + }); + +}); + +describe("eStack - return the element at the head of the stack and remove it", function () { + var stack = new eStack(); + stack.put(2); + stack.put(3); + it("should return 2", function () { + expect(stack.remove()).toBe(2); + }); + it("should return 1", function () { + expect(stack.size()).toBe(1); + }); +}); + +describe("eStack - clear contents of stack", function () { + var stack = new eStack(); + stack.put(2); + stack.put(3); + stack.clear(); + + it("stack size should return 0 after calling clear function", function () { + expect(stack.size()).toBe(0); + }); + +}); + +describe("eStack - convert stack to array", function () { + it("should be an instance of Array", function () { + var stack = new eStack(); + expect(stack.toArray() instanceof Array).toBe(true); + }); + +});
bc24531aeb7dcf75783010d5ea0612bec0110213
test/server/routes.spec.js
test/server/routes.spec.js
/* * Copyright (c) 2015-2017 Steven Soloff * * This is free software: you can redistribute it and/or modify it under the * terms of the MIT License (https://opensource.org/licenses/MIT). * This software comes with ABSOLUTELY NO WARRANTY. */ 'use strict' const express = require('express') const routes = require('../../src/server/routes') const securityTest = require('./test-support/security-test') describe('routes', () => { it('should not throw an exception when provided a valid application', () => { expect(() => { const app = express() routes(app, securityTest.getPrivateKey(), securityTest.getPublicKey()) }).not.toThrow() }) })
Add unit tests for routes module
Add unit tests for routes module
JavaScript
mit
ssoloff/dice-server-js,ssoloff/dice-server-js,ssoloff/dice-server-js,ssoloff/dice-server-js
--- +++ @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2015-2017 Steven Soloff + * + * This is free software: you can redistribute it and/or modify it under the + * terms of the MIT License (https://opensource.org/licenses/MIT). + * This software comes with ABSOLUTELY NO WARRANTY. + */ + +'use strict' + +const express = require('express') +const routes = require('../../src/server/routes') +const securityTest = require('./test-support/security-test') + +describe('routes', () => { + it('should not throw an exception when provided a valid application', () => { + expect(() => { + const app = express() + routes(app, securityTest.getPrivateKey(), securityTest.getPublicKey()) + }).not.toThrow() + }) +})
4430ec180e46f7bb25706b1958d906d7528200da
script/gen-an.js
script/gen-an.js
import Hackpad from 'hackpad' import To_markdown from 'to-markdown' import To_XML from 'xml' // help: CLIENT_ID=xxx SECRET=yyy babel-node script/gen-an.js [pad_id] // ex: CLIENT_ID=xxx SECRET=yyy babel-node script/gen-an.js 3RvGJjHbZ3Z // Get your Client ID and Secret from https://g0v.hackpad.com/ep/account/settings/ const CLIENT_ID = process.env.CLIENT_ID const SECRET = process.env.SECRET const client = new Hackpad(CLIENT_ID, SECRET, { site: 'g0v.hackpad.com' }) client.export(process.argv[2], 'latest', 'html', (err, html) => { var markdown_content = To_markdown(html) var debateSection = [] var speaker_name = '', speech = [] markdown_content.split('\n').forEach(function (line, index, arr) { var matcher if(line.startsWith('#')) { debateSection.push({heading: line.split('#')[1].trim() }) } if( line.startsWith('*') ) { speech = speech.concat([ { p: line.split('*')[1].trim() + '\n' }]) } if( !line.startsWith('*') && (matcher = line.match(/^(.+)(?::|:)$/))) { if(speaker_name !== '' && speech.length > 0) { debateSection.push({ speech: [{_attr: { by: `#${speaker_name}`, }}].concat(speech)}) } speaker_name = matcher[1] speech = [] } if(index === arr.length -1) { debateSection.push({ speech: [{_attr: { by: `#${speaker_name}`, }}].concat(speech)}) } }) var an = {akomaNtoso: [{ debate: [ // {meta: [{references: References}]}, // 替TLCPerson 保留 // {preface: Preface}, // 替文件名稱保留 {debateBody: debateSection } ]}]} console.log(To_XML(an)) })
Add Akoma Ntoso xml format generator
Add Akoma Ntoso xml format generator
JavaScript
cc0-1.0
appleboy/react.vtaiwan.tw,g0v/react.vtaiwan.tw,g0v/react.vtaiwan.tw,appleboy/react.vtaiwan.tw,g0v/react.vtaiwan.tw
--- +++ @@ -0,0 +1,50 @@ +import Hackpad from 'hackpad' +import To_markdown from 'to-markdown' +import To_XML from 'xml' + +// help: CLIENT_ID=xxx SECRET=yyy babel-node script/gen-an.js [pad_id] +// ex: CLIENT_ID=xxx SECRET=yyy babel-node script/gen-an.js 3RvGJjHbZ3Z +// Get your Client ID and Secret from https://g0v.hackpad.com/ep/account/settings/ +const CLIENT_ID = process.env.CLIENT_ID +const SECRET = process.env.SECRET + +const client = new Hackpad(CLIENT_ID, SECRET, { site: 'g0v.hackpad.com' }) + +client.export(process.argv[2], 'latest', 'html', (err, html) => { + var markdown_content = To_markdown(html) + var debateSection = [] + + var speaker_name = '', speech = [] + markdown_content.split('\n').forEach(function (line, index, arr) { + var matcher + if(line.startsWith('#')) { + debateSection.push({heading: line.split('#')[1].trim() }) + } + + if( line.startsWith('*') ) { + speech = speech.concat([ { p: line.split('*')[1].trim() + '\n' }]) + } + + if( !line.startsWith('*') && (matcher = line.match(/^(.+)(?::|:)$/))) { + if(speaker_name !== '' && speech.length > 0) { + debateSection.push({ + speech: [{_attr: { by: `#${speaker_name}`, + }}].concat(speech)}) + } + speaker_name = matcher[1] + speech = [] + } + + if(index === arr.length -1) { + debateSection.push({ + speech: [{_attr: { by: `#${speaker_name}`, + }}].concat(speech)}) + } + }) + var an = {akomaNtoso: [{ debate: [ + // {meta: [{references: References}]}, // 替TLCPerson 保留 + // {preface: Preface}, // 替文件名稱保留 + {debateBody: debateSection } + ]}]} + console.log(To_XML(an)) +})
36f6802efb50a0cccc5d6c2f454bdb800d71871c
stories/box.js
stories/box.js
import React from 'react'; import PropTable from './components/propTable'; import { storiesOf } from '@storybook/react'; import { checkA11y } from 'storybook-addon-a11y'; import { withInfo } from '@storybook/addon-info'; import { withKnobs, number, select } from '@storybook/addon-knobs/react'; import {Box, TextBody} from '../components'; const displayValues = ['inline', 'inline-block', 'block', 'flex', 'inline-flex']; const justifyContentValues = [ 'center', 'flex-start', 'flex-end', 'space-around', 'space-between', 'space-evenly', ]; const spacingOptions = { range: true, min: 1, max: 8, step: 1, }; storiesOf('Box', module) .addDecorator((story, context) => withInfo({ propTablesExclude: [TextBody], TableComponent: PropTable })(story)(context)) .addDecorator(checkA11y) .addDecorator(withKnobs) .add('Basic', () => ( <Box style={{backgroundColor: '#fafafa'}} display={select('display', displayValues, 'block')} justifyContent={select('justifyContent', justifyContentValues, 'flex-start')} margin={number('margin', 0, spacingOptions)} padding={number('padding', 3, spacingOptions)} > <TextBody>I'm body text inside a Box component</TextBody> </Box> ));
Add story for our Box component
Add story for our Box component
JavaScript
mit
teamleadercrm/teamleader-ui
--- +++ @@ -0,0 +1,43 @@ +import React from 'react'; +import PropTable from './components/propTable'; +import { storiesOf } from '@storybook/react'; +import { checkA11y } from 'storybook-addon-a11y'; +import { withInfo } from '@storybook/addon-info'; +import { withKnobs, number, select } from '@storybook/addon-knobs/react'; +import {Box, TextBody} from '../components'; + +const displayValues = ['inline', 'inline-block', 'block', 'flex', 'inline-flex']; +const justifyContentValues = [ + 'center', + 'flex-start', + 'flex-end', + 'space-around', + 'space-between', + 'space-evenly', +]; + +const spacingOptions = { + range: true, + min: 1, + max: 8, + step: 1, +}; + +storiesOf('Box', module) + .addDecorator((story, context) => withInfo({ + propTablesExclude: [TextBody], + TableComponent: PropTable + })(story)(context)) + .addDecorator(checkA11y) + .addDecorator(withKnobs) + .add('Basic', () => ( + <Box + style={{backgroundColor: '#fafafa'}} + display={select('display', displayValues, 'block')} + justifyContent={select('justifyContent', justifyContentValues, 'flex-start')} + margin={number('margin', 0, spacingOptions)} + padding={number('padding', 3, spacingOptions)} + > + <TextBody>I'm body text inside a Box component</TextBody> + </Box> + ));
daa63e10a6f460bddcd7edc7473b3f01ec0687e8
src/gamestate.js
src/gamestate.js
function GameState() { "use strict"; } //The following functions do nothing since they're intended to be overwritten. GameState.prototype.update = function update(deltaTime) { "use strict"; }; GameState.prototype.render = function render(screen) { "use strict"; }; GameState.prototype.willDisappear = function willDisappear() { "use strict"; }; GameState.prototype.willAppear = function willAppear() { "use strict"; }; GameState.prototype.toString = function () { "use strict"; return "GameState"; };
Add a GameState super class.
Add a GameState super class.
JavaScript
mit
zedutchgandalf/OpenJGL,zedutchgandalf/OpenJGL
--- +++ @@ -0,0 +1,26 @@ +function GameState() { + "use strict"; +} + +//The following functions do nothing since they're intended to be overwritten. + +GameState.prototype.update = function update(deltaTime) { + "use strict"; +}; + +GameState.prototype.render = function render(screen) { + "use strict"; +}; + +GameState.prototype.willDisappear = function willDisappear() { + "use strict"; +}; + +GameState.prototype.willAppear = function willAppear() { + "use strict"; +}; + +GameState.prototype.toString = function () { + "use strict"; + return "GameState"; +};
8e03d10e5b2e9836a80de5b385b2be2ec5bcd954
scripts/bundleMiddlewaresForBrowsers.js
scripts/bundleMiddlewaresForBrowsers.js
'use strict'; var browserify = require('browserify'), babelify = require('babelify'), path = require('path'); var babelOptions = { presets: ['es2015', 'stage-1'], plugins: ['transform-runtime'], compact: false }; var browserifyOptions = { standalone: 'rotorjsMiddlewares', debug: true }; browserify(path.join('middlewares.js'), browserifyOptions) .transform(babelify, babelOptions) .bundle() .pipe(process.stdout);
Add script for bundle middlewares
scripts/bundleForBrowsers.js: Add script for bundle middlewares
JavaScript
mit
kuraga/rotorjs,kuraga/rotorjs
--- +++ @@ -0,0 +1,20 @@ +'use strict'; + +var browserify = require('browserify'), + babelify = require('babelify'), + path = require('path'); + +var babelOptions = { + presets: ['es2015', 'stage-1'], + plugins: ['transform-runtime'], + compact: false +}; +var browserifyOptions = { + standalone: 'rotorjsMiddlewares', + debug: true +}; + +browserify(path.join('middlewares.js'), browserifyOptions) + .transform(babelify, babelOptions) + .bundle() + .pipe(process.stdout);
724cacbc65fea63a4ed6a2a1f4b8a1e430ad12ee
src/constants/app_config.js
src/constants/app_config.js
// CARTO table names lookup export const cartoTables = { nyc_borough: 'nyc_borough', nyc_city_council: 'nyc_city_council', nyc_community_board: 'nyc_community_board', nyc_neighborhood: 'nyc_neighborhood', nyc_nypd_precinct: 'nyc_nypd_precinct', nyc_zip_codes: 'nyc_zip_codes', nyc_crashes: 'export2016_07' }; export const basemapURL = 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png';
Create app config file with Carto table name look up & basemap url
Create app config file with Carto table name look up & basemap url
JavaScript
mit
clhenrick/nyc-crash-mapper,clhenrick/nyc-crash-mapper,clhenrick/nyc-crash-mapper
--- +++ @@ -0,0 +1,13 @@ +// CARTO table names lookup +export const cartoTables = { + nyc_borough: 'nyc_borough', + nyc_city_council: 'nyc_city_council', + nyc_community_board: 'nyc_community_board', + nyc_neighborhood: 'nyc_neighborhood', + nyc_nypd_precinct: 'nyc_nypd_precinct', + nyc_zip_codes: 'nyc_zip_codes', + nyc_crashes: 'export2016_07' +}; + +export const basemapURL = + 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png';
fc2362735170afa9929af9ef6cecd1b72d45f307
src/data/types/ContentType.js
src/data/types/ContentType.js
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import { GraphQLObjectType as ObjectType, GraphQLString as StringType, GraphQLNonNull as NonNull, } from 'graphql'; const ContentType = new ObjectType({ name: 'Content', fields: { path: { type: new NonNull(StringType) }, title: { type: new NonNull(StringType) }, content: { type: new NonNull(StringType) }, component: { type: new NonNull(StringType) }, }, }); export default ContentType;
Create a template type (content type).
Create a template type (content type).
JavaScript
mit
happyboy171/Feeding-Fish-View-
--- +++ @@ -0,0 +1,26 @@ +/** + * React Starter Kit (https://www.reactstarterkit.com/) + * + * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE.txt file in the root directory of this source tree. + */ + +import { + GraphQLObjectType as ObjectType, + GraphQLString as StringType, + GraphQLNonNull as NonNull, +} from 'graphql'; + +const ContentType = new ObjectType({ + name: 'Content', + fields: { + path: { type: new NonNull(StringType) }, + title: { type: new NonNull(StringType) }, + content: { type: new NonNull(StringType) }, + component: { type: new NonNull(StringType) }, + }, +}); + +export default ContentType;
08718e760bf9e1dca5d8c515ebe0484b7678909d
lib/index.js
lib/index.js
var net = require('net'); var server = net.createServer(function (socket) { socket.write('Echo server\r\n'); socket.pipe(socket); }); server.listen(1337, '127.0.0.1');
Add the simple socket exmaple
Add the simple socket exmaple
JavaScript
mit
FuriKuri/info-bundling
--- +++ @@ -0,0 +1,8 @@ +var net = require('net'); + +var server = net.createServer(function (socket) { + socket.write('Echo server\r\n'); + socket.pipe(socket); +}); + +server.listen(1337, '127.0.0.1');
202e9ae88bfcdc392f396a9aeb08936bf2f50c0e
spec/frontend/dummy_spec.js
spec/frontend/dummy_spec.js
describe('dummy test', () => { it('waits for a loooooong time', () => { setTimeout(() => { throw new Error('broken'); }, 10000); }); });
Add dummy test with setTimeout()
Add dummy test with setTimeout()
JavaScript
mit
mmkassem/gitlabhq,stoplightio/gitlabhq,iiet/iiet-git,stoplightio/gitlabhq,mmkassem/gitlabhq,iiet/iiet-git,iiet/iiet-git,mmkassem/gitlabhq,mmkassem/gitlabhq,iiet/iiet-git,stoplightio/gitlabhq,stoplightio/gitlabhq
--- +++ @@ -0,0 +1,7 @@ +describe('dummy test', () => { + it('waits for a loooooong time', () => { + setTimeout(() => { + throw new Error('broken'); + }, 10000); + }); +});
c2cdd3270d6914328650bd7b5b9a8343fc3fd53c
connectors/v2/thisismyjam.js
connectors/v2/thisismyjam.js
'use strict'; /* global Connector */ Connector.playerSelector = '#player-inner'; Connector.artistSelector = '#artist-name'; Connector.trackSelector = '#track-title'; Connector.isPlaying = function () { return $('#playPause').hasClass('playing'); };
'use strict'; /* global Connector */ Connector.playerSelector = '.foundaudio-player'; Connector.artistSelector = '.foundaudio-artist'; Connector.trackSelector = '.foundaudio-title'; Connector.trackArtImageSelector = '.foundaudio-cover img'; Connector.playButtonSelector = '#foundAudioPlay';
Fix This Is My Jam connector
Fix This Is My Jam connector The Soundcloud player still is not supported.
JavaScript
mit
david-sabata/web-scrobbler,Paszt/web-scrobbler,david-sabata/web-scrobbler,inverse/web-scrobbler,galeksandrp/web-scrobbler,carpet-berlin/web-scrobbler,Paszt/web-scrobbler,carpet-berlin/web-scrobbler,galeksandrp/web-scrobbler,ex47/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,alexesprit/web-scrobbler,ex47/web-scrobbler,inverse/web-scrobbler,usdivad/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,alexesprit/web-scrobbler,usdivad/web-scrobbler
--- +++ @@ -2,12 +2,12 @@ /* global Connector */ -Connector.playerSelector = '#player-inner'; +Connector.playerSelector = '.foundaudio-player'; -Connector.artistSelector = '#artist-name'; +Connector.artistSelector = '.foundaudio-artist'; -Connector.trackSelector = '#track-title'; +Connector.trackSelector = '.foundaudio-title'; -Connector.isPlaying = function () { - return $('#playPause').hasClass('playing'); -}; +Connector.trackArtImageSelector = '.foundaudio-cover img'; + +Connector.playButtonSelector = '#foundAudioPlay';
3007c98f3a4366e1ae3bb1e50c141e7d938d2782
ko-mappings.js
ko-mappings.js
/** * A SET OF COOL MAPPINGS FOR KNOCKOUT.JS * @author zipang * @copyright 2014 - EIDOLON LABS */ (function() { if (!ko) { if (console) console.log("Knockout.JS not present.") return; } // ============================================================= // Add new custom mappings for usual attributes href, src, etc.. // ============================================================= var bindingHandlers = ko.bindingHandlers; ["href", "src", "alt", "title", "width", "height", "placeholder"].forEach( function def(_attr) { var binding = {}, attr = _attr; bindingHandlers[attr] = { update: function (element, valueAccessor) { bindingHandlers.attr.update(element, function () { binding[attr] = valueAccessor(); return binding; }); } }; } ); // ============================================================= // Custom syntax for the class attribute.. class: status[draft|created|in_process] // ============================================================= bindingHandlers["className"] = { init: function (element) { var dataBinds = $(element).data("bind").split(";"); dataBinds.forEach(function(dataBind) { var definitionParts = dataBind.split(":"), key = definitionParts[0].trim(), bindExpr = definitionParts[1].trim(); if (key === "className") { var bindingParts = bindExpr.match(/([\w-]+)/gi), // extract words in pattern attribute[class1|class2] accessorName = bindingParts.shift(), regex = new RegExp(bindingParts.join("|"), "gi"); bindingParts.forEach(function(className) { $(element).data(className + "-update", regex); }); } }); }, update: function (element, valueAccessor) { var newClass = valueAccessor()(), eltClassName = element.className; if (!eltClassName) { element.className = newClass; } else { element.className = eltClassName.replace($(element).data(newClass + "-update"), "") + " " + newClass; } }, preprocess: function(value, name, addBinding) { var bindingParts = value.match(/([\w-]+)/gi), // extract words in pattern attribute[class1|class2] accessorName = bindingParts.shift(); return accessorName; } }; })();
Add usual attributes mapping: href, src, title, alt, placeholder, and the smart className mapping that bind a property to a list of values for a class name
Add usual attributes mapping: href, src, title, alt, placeholder, and the smart className mapping that bind a property to a list of values for a class name
JavaScript
mit
zipang/ko-dings
--- +++ @@ -0,0 +1,75 @@ +/** + * A SET OF COOL MAPPINGS FOR KNOCKOUT.JS + * @author zipang + * @copyright 2014 - EIDOLON LABS + */ + +(function() { + + if (!ko) { + if (console) console.log("Knockout.JS not present.") + return; + } + + // ============================================================= + // Add new custom mappings for usual attributes href, src, etc.. + // ============================================================= + var bindingHandlers = ko.bindingHandlers; + + ["href", "src", "alt", "title", "width", "height", "placeholder"].forEach( + function def(_attr) { + var binding = {}, attr = _attr; + + bindingHandlers[attr] = { + update: function (element, valueAccessor) { + bindingHandlers.attr.update(element, function () { + binding[attr] = valueAccessor(); + return binding; + }); + } + }; + } + ); + + // ============================================================= + // Custom syntax for the class attribute.. class: status[draft|created|in_process] + // ============================================================= + bindingHandlers["className"] = { + init: function (element) { + var dataBinds = $(element).data("bind").split(";"); + + dataBinds.forEach(function(dataBind) { + var definitionParts = dataBind.split(":"), + key = definitionParts[0].trim(), + bindExpr = definitionParts[1].trim(); + + if (key === "className") { + var bindingParts = bindExpr.match(/([\w-]+)/gi), // extract words in pattern attribute[class1|class2] + accessorName = bindingParts.shift(), + regex = new RegExp(bindingParts.join("|"), "gi"); + + bindingParts.forEach(function(className) { + $(element).data(className + "-update", regex); + }); + } + }); + }, + update: function (element, valueAccessor) { + var newClass = valueAccessor()(), + eltClassName = element.className; + if (!eltClassName) { + element.className = newClass; + } else { + element.className = eltClassName.replace($(element).data(newClass + "-update"), "") + + " " + newClass; + } + }, + preprocess: function(value, name, addBinding) { + var bindingParts = value.match(/([\w-]+)/gi), // extract words in pattern attribute[class1|class2] + accessorName = bindingParts.shift(); + + return accessorName; + } + }; + +})();
d584fdbf135e54ebd6281abdb771cf132a7c88c5
client/api.js
client/api.js
import request from 'superagent'; class API { sidebarItems(callback) { request .get('/all_dates') .end((err, response) => { callback(response); }) } } export default API;
Add class to fetch data from the server backend
Add class to fetch data from the server backend
JavaScript
mit
jaischeema/panorma,jaischeema/panorma,jaischeema/panorma
--- +++ @@ -0,0 +1,13 @@ +import request from 'superagent'; + +class API { + sidebarItems(callback) { + request + .get('/all_dates') + .end((err, response) => { + callback(response); + }) + } +} + +export default API;
c6503a28d95702a4004bc1f66f00bb40c978ad13
lib/index.js
lib/index.js
'use strict'; var traverse = require('./util/traverse'); var deref = require('deref'); module.exports = function(schema, refs) { return traverse(deref()(schema, refs, true)); };
'use strict'; var traverse = require('./util/traverse'); var deref = require('deref'); module.exports = function(schema, refs) { var $ = deref(); if (Array.isArray(refs)) { return traverse($(schema, refs, true)); } else { $.refs = refs || {}; } return traverse($(schema, true)); };
Allow array or object for refs; fix
Allow array or object for refs; fix
JavaScript
mit
json-schema-faker/json-schema-faker,rlugojr/json-schema-faker,Scorpil/json-schema-faker,rlugojr/json-schema-faker,json-schema-faker/json-schema-faker,Gash003/json-schema-faker,whitlockjc/json-schema-faker,presidento/json-schema-faker,pateketrueke/json-schema-faker,rlugojr/json-schema-faker
--- +++ @@ -5,5 +5,13 @@ var deref = require('deref'); module.exports = function(schema, refs) { - return traverse(deref()(schema, refs, true)); + var $ = deref(); + + if (Array.isArray(refs)) { + return traverse($(schema, refs, true)); + } else { + $.refs = refs || {}; + } + + return traverse($(schema, true)); };