id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
50,000
origin1tech/chek
dist/modules/array.js
push
function push(arr) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } arr = arr.concat(flatten.apply(void 0, args)); return { array: arr, val: arr.length }; }
javascript
function push(arr) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } arr = arr.concat(flatten.apply(void 0, args)); return { array: arr, val: arr.length }; }
[ "function", "push", "(", "arr", ")", "{", "var", "args", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "1", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "args", "[", "_i", "-", "1", "]", "=", "arguments", "[", "_i", "]", ";", "}", "arr", "=", "arr", ".", "concat", "(", "flatten", ".", "apply", "(", "void", "0", ",", "args", ")", ")", ";", "return", "{", "array", ":", "arr", ",", "val", ":", "arr", ".", "length", "}", ";", "}" ]
Push Non mutating way to push to an array. @param arr the array to push items to. @param args the items to be added.
[ "Push", "Non", "mutating", "way", "to", "push", "to", "an", "array", "." ]
6bc3ab0ac36126cc7918a244a606009749897b2e
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/array.js#L249-L259
50,001
origin1tech/chek
dist/modules/array.js
splice
function splice(arr, start, remove) { var items = []; for (var _i = 3; _i < arguments.length; _i++) { items[_i - 3] = arguments[_i]; } start = start || 0; var head = arr.slice(0, start); var tail = arr.slice(start); var removed = []; if (remove) { removed = tail.slice(0, remove); tail = tail.slice(remove); } if (!is_1.isValue(remove)) { arr = head.concat(items); removed = tail; } else { arr = head.concat(items).concat(tail); } return { array: arr, val: removed }; }
javascript
function splice(arr, start, remove) { var items = []; for (var _i = 3; _i < arguments.length; _i++) { items[_i - 3] = arguments[_i]; } start = start || 0; var head = arr.slice(0, start); var tail = arr.slice(start); var removed = []; if (remove) { removed = tail.slice(0, remove); tail = tail.slice(remove); } if (!is_1.isValue(remove)) { arr = head.concat(items); removed = tail; } else { arr = head.concat(items).concat(tail); } return { array: arr, val: removed }; }
[ "function", "splice", "(", "arr", ",", "start", ",", "remove", ")", "{", "var", "items", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "3", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "items", "[", "_i", "-", "3", "]", "=", "arguments", "[", "_i", "]", ";", "}", "start", "=", "start", "||", "0", ";", "var", "head", "=", "arr", ".", "slice", "(", "0", ",", "start", ")", ";", "var", "tail", "=", "arr", ".", "slice", "(", "start", ")", ";", "var", "removed", "=", "[", "]", ";", "if", "(", "remove", ")", "{", "removed", "=", "tail", ".", "slice", "(", "0", ",", "remove", ")", ";", "tail", "=", "tail", ".", "slice", "(", "remove", ")", ";", "}", "if", "(", "!", "is_1", ".", "isValue", "(", "remove", ")", ")", "{", "arr", "=", "head", ".", "concat", "(", "items", ")", ";", "removed", "=", "tail", ";", "}", "else", "{", "arr", "=", "head", ".", "concat", "(", "items", ")", ".", "concat", "(", "tail", ")", ";", "}", "return", "{", "array", ":", "arr", ",", "val", ":", "removed", "}", ";", "}" ]
Splice Non mutating way of splicing an array. @param arr the array to be spliced. @param start the starting index (default: 0) @param remove the count to be spliced (default: 1) @param items additional items to be concatenated.
[ "Splice", "Non", "mutating", "way", "of", "splicing", "an", "array", "." ]
6bc3ab0ac36126cc7918a244a606009749897b2e
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/array.js#L287-L311
50,002
origin1tech/chek
dist/modules/array.js
unshift
function unshift(arr) { var items = []; for (var _i = 1; _i < arguments.length; _i++) { items[_i - 1] = arguments[_i]; } arr = arr.concat(flatten(items)); return { array: arr, val: arr.length }; }
javascript
function unshift(arr) { var items = []; for (var _i = 1; _i < arguments.length; _i++) { items[_i - 1] = arguments[_i]; } arr = arr.concat(flatten(items)); return { array: arr, val: arr.length }; }
[ "function", "unshift", "(", "arr", ")", "{", "var", "items", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "1", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "items", "[", "_i", "-", "1", "]", "=", "arguments", "[", "_i", "]", ";", "}", "arr", "=", "arr", ".", "concat", "(", "flatten", "(", "items", ")", ")", ";", "return", "{", "array", ":", "arr", ",", "val", ":", "arr", ".", "length", "}", ";", "}" ]
Unshift Unshifts a value to an array in a non mutable way. @param arr the array to be unshifted. @param value the value to be unshifted
[ "Unshift", "Unshifts", "a", "value", "to", "an", "array", "in", "a", "non", "mutable", "way", "." ]
6bc3ab0ac36126cc7918a244a606009749897b2e
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/array.js#L320-L330
50,003
hydrojs/karma-hydro
index.js
init
function init(config) { var hydroConfig = config.hydro || {}; var hydroJs = hydroConfig.path || dirname(dirname(require.resolve('hydro'))) + '/dist/hydro.js'; var before = hydroConfig.before || []; config.files.unshift(createPattern(__dirname + '/adapter.js')); config.files.unshift(createPattern(hydroJs)); before.reverse().forEach(function(file) { config.files.unshift(createPattern(path.resolve(file))); }); }
javascript
function init(config) { var hydroConfig = config.hydro || {}; var hydroJs = hydroConfig.path || dirname(dirname(require.resolve('hydro'))) + '/dist/hydro.js'; var before = hydroConfig.before || []; config.files.unshift(createPattern(__dirname + '/adapter.js')); config.files.unshift(createPattern(hydroJs)); before.reverse().forEach(function(file) { config.files.unshift(createPattern(path.resolve(file))); }); }
[ "function", "init", "(", "config", ")", "{", "var", "hydroConfig", "=", "config", ".", "hydro", "||", "{", "}", ";", "var", "hydroJs", "=", "hydroConfig", ".", "path", "||", "dirname", "(", "dirname", "(", "require", ".", "resolve", "(", "'hydro'", ")", ")", ")", "+", "'/dist/hydro.js'", ";", "var", "before", "=", "hydroConfig", ".", "before", "||", "[", "]", ";", "config", ".", "files", ".", "unshift", "(", "createPattern", "(", "__dirname", "+", "'/adapter.js'", ")", ")", ";", "config", ".", "files", ".", "unshift", "(", "createPattern", "(", "hydroJs", ")", ")", ";", "before", ".", "reverse", "(", ")", ".", "forEach", "(", "function", "(", "file", ")", "{", "config", ".", "files", ".", "unshift", "(", "createPattern", "(", "path", ".", "resolve", "(", "file", ")", ")", ")", ";", "}", ")", ";", "}" ]
Insert hydro into the loaded files. @param {Array} files @api public
[ "Insert", "hydro", "into", "the", "loaded", "files", "." ]
a0d5e083b1ddd1c4fbc7d6fa29ed1b0d9d4a5193
https://github.com/hydrojs/karma-hydro/blob/a0d5e083b1ddd1c4fbc7d6fa29ed1b0d9d4a5193/index.js#L32-L43
50,004
2dbibracte/rlog
public/bower_components/ui-bootstrap/misc/demo/assets/smoothscroll-angular-custom.js
function(element) { // return value of html.getBoundingClientRect().top ... IE : 0, other browsers : -pageYOffset if(element.nodeName === 'HTML') return -window.pageYOffset return element.getBoundingClientRect().top + window.pageYOffset; }
javascript
function(element) { // return value of html.getBoundingClientRect().top ... IE : 0, other browsers : -pageYOffset if(element.nodeName === 'HTML') return -window.pageYOffset return element.getBoundingClientRect().top + window.pageYOffset; }
[ "function", "(", "element", ")", "{", "// return value of html.getBoundingClientRect().top ... IE : 0, other browsers : -pageYOffset", "if", "(", "element", ".", "nodeName", "===", "'HTML'", ")", "return", "-", "window", ".", "pageYOffset", "return", "element", ".", "getBoundingClientRect", "(", ")", ".", "top", "+", "window", ".", "pageYOffset", ";", "}" ]
Get the top position of an element in the document
[ "Get", "the", "top", "position", "of", "an", "element", "in", "the", "document" ]
10f63cf81ffcd23b37c70620c77942c885e3ce5e
https://github.com/2dbibracte/rlog/blob/10f63cf81ffcd23b37c70620c77942c885e3ce5e/public/bower_components/ui-bootstrap/misc/demo/assets/smoothscroll-angular-custom.js#L12-L16
50,005
2dbibracte/rlog
public/bower_components/ui-bootstrap/misc/demo/assets/smoothscroll-angular-custom.js
function(el, duration, callback){ duration = duration || 500; var start = window.pageYOffset; if (typeof el === 'number') { var end = parseInt(el); } else { var end = getTop(el); } var clock = Date.now(); var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function(fn){window.setTimeout(fn, 15);}; var step = function(){ var elapsed = Date.now() - clock; window.scroll(0, position(start, end, elapsed, duration)); if (elapsed > duration) { if (typeof callback === 'function') { callback(el); } } else { requestAnimationFrame(step); } } step(); }
javascript
function(el, duration, callback){ duration = duration || 500; var start = window.pageYOffset; if (typeof el === 'number') { var end = parseInt(el); } else { var end = getTop(el); } var clock = Date.now(); var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function(fn){window.setTimeout(fn, 15);}; var step = function(){ var elapsed = Date.now() - clock; window.scroll(0, position(start, end, elapsed, duration)); if (elapsed > duration) { if (typeof callback === 'function') { callback(el); } } else { requestAnimationFrame(step); } } step(); }
[ "function", "(", "el", ",", "duration", ",", "callback", ")", "{", "duration", "=", "duration", "||", "500", ";", "var", "start", "=", "window", ".", "pageYOffset", ";", "if", "(", "typeof", "el", "===", "'number'", ")", "{", "var", "end", "=", "parseInt", "(", "el", ")", ";", "}", "else", "{", "var", "end", "=", "getTop", "(", "el", ")", ";", "}", "var", "clock", "=", "Date", ".", "now", "(", ")", ";", "var", "requestAnimationFrame", "=", "window", ".", "requestAnimationFrame", "||", "window", ".", "mozRequestAnimationFrame", "||", "window", ".", "webkitRequestAnimationFrame", "||", "function", "(", "fn", ")", "{", "window", ".", "setTimeout", "(", "fn", ",", "15", ")", ";", "}", ";", "var", "step", "=", "function", "(", ")", "{", "var", "elapsed", "=", "Date", ".", "now", "(", ")", "-", "clock", ";", "window", ".", "scroll", "(", "0", ",", "position", "(", "start", ",", "end", ",", "elapsed", ",", "duration", ")", ")", ";", "if", "(", "elapsed", ">", "duration", ")", "{", "if", "(", "typeof", "callback", "===", "'function'", ")", "{", "callback", "(", "el", ")", ";", "}", "}", "else", "{", "requestAnimationFrame", "(", "step", ")", ";", "}", "}", "step", "(", ")", ";", "}" ]
we use requestAnimationFrame to be called by the browser before every repaint if the first argument is an element then scroll to the top of this element if the first argument is numeric then scroll to this location if the callback exist, it is called when the scrolling is finished
[ "we", "use", "requestAnimationFrame", "to", "be", "called", "by", "the", "browser", "before", "every", "repaint", "if", "the", "first", "argument", "is", "an", "element", "then", "scroll", "to", "the", "top", "of", "this", "element", "if", "the", "first", "argument", "is", "numeric", "then", "scroll", "to", "this", "location", "if", "the", "callback", "exist", "it", "is", "called", "when", "the", "scrolling", "is", "finished" ]
10f63cf81ffcd23b37c70620c77942c885e3ce5e
https://github.com/2dbibracte/rlog/blob/10f63cf81ffcd23b37c70620c77942c885e3ce5e/public/bower_components/ui-bootstrap/misc/demo/assets/smoothscroll-angular-custom.js#L35-L62
50,006
konfirm/devour-gulp
lib/devour.js
preload
function preload() { var path = config.gulpFiles; if (/^[^\/]/.test(path)) { path = config.basePath + '/' + path; } glob.sync(path + '/*/*.js').map(function(file) { return file.replace(path, '').split('/').filter(function(split) { return !!split; }); }).forEach(function(file) { register( file[0], file[file.length - 1].replace(/\.js$/, ''), require(path + '/' + file.join('/')) ); }); console.log(chalk.cyan('Devour initialized')); if (config.verbose) { ['task', 'pipe'].forEach(function(what) { console.log( ' - available %ss: %s', what, what in definitions ? chalk.green(Object.keys(definitions[what]).join(', ')) : chalk.yellow('none') ); }); console.log(''); } }
javascript
function preload() { var path = config.gulpFiles; if (/^[^\/]/.test(path)) { path = config.basePath + '/' + path; } glob.sync(path + '/*/*.js').map(function(file) { return file.replace(path, '').split('/').filter(function(split) { return !!split; }); }).forEach(function(file) { register( file[0], file[file.length - 1].replace(/\.js$/, ''), require(path + '/' + file.join('/')) ); }); console.log(chalk.cyan('Devour initialized')); if (config.verbose) { ['task', 'pipe'].forEach(function(what) { console.log( ' - available %ss: %s', what, what in definitions ? chalk.green(Object.keys(definitions[what]).join(', ')) : chalk.yellow('none') ); }); console.log(''); } }
[ "function", "preload", "(", ")", "{", "var", "path", "=", "config", ".", "gulpFiles", ";", "if", "(", "/", "^[^\\/]", "/", ".", "test", "(", "path", ")", ")", "{", "path", "=", "config", ".", "basePath", "+", "'/'", "+", "path", ";", "}", "glob", ".", "sync", "(", "path", "+", "'/*/*.js'", ")", ".", "map", "(", "function", "(", "file", ")", "{", "return", "file", ".", "replace", "(", "path", ",", "''", ")", ".", "split", "(", "'/'", ")", ".", "filter", "(", "function", "(", "split", ")", "{", "return", "!", "!", "split", ";", "}", ")", ";", "}", ")", ".", "forEach", "(", "function", "(", "file", ")", "{", "register", "(", "file", "[", "0", "]", ",", "file", "[", "file", ".", "length", "-", "1", "]", ".", "replace", "(", "/", "\\.js$", "/", ",", "''", ")", ",", "require", "(", "path", "+", "'/'", "+", "file", ".", "join", "(", "'/'", ")", ")", ")", ";", "}", ")", ";", "console", ".", "log", "(", "chalk", ".", "cyan", "(", "'Devour initialized'", ")", ")", ";", "if", "(", "config", ".", "verbose", ")", "{", "[", "'task'", ",", "'pipe'", "]", ".", "forEach", "(", "function", "(", "what", ")", "{", "console", ".", "log", "(", "' - available %ss: %s'", ",", "what", ",", "what", "in", "definitions", "?", "chalk", ".", "green", "(", "Object", ".", "keys", "(", "definitions", "[", "what", "]", ")", ".", "join", "(", "', '", ")", ")", ":", "chalk", ".", "yellow", "(", "'none'", ")", ")", ";", "}", ")", ";", "console", ".", "log", "(", "''", ")", ";", "}", "}" ]
Load all available tasks and pipes @name preload @access internal @return void
[ "Load", "all", "available", "tasks", "and", "pipes" ]
eed953ac3c582c653fd63cbbb4b550dd33e88d13
https://github.com/konfirm/devour-gulp/blob/eed953ac3c582c653fd63cbbb4b550dd33e88d13/lib/devour.js#L49-L80
50,007
konfirm/devour-gulp
lib/devour.js
register
function register(type, name, create) { if (!(type in definitions)) { definitions[type] = {}; } if (type === 'pipe') { create = chain(create, devour); } definitions[type][name] = create; }
javascript
function register(type, name, create) { if (!(type in definitions)) { definitions[type] = {}; } if (type === 'pipe') { create = chain(create, devour); } definitions[type][name] = create; }
[ "function", "register", "(", "type", ",", "name", ",", "create", ")", "{", "if", "(", "!", "(", "type", "in", "definitions", ")", ")", "{", "definitions", "[", "type", "]", "=", "{", "}", ";", "}", "if", "(", "type", "===", "'pipe'", ")", "{", "create", "=", "chain", "(", "create", ",", "devour", ")", ";", "}", "definitions", "[", "type", "]", "[", "name", "]", "=", "create", ";", "}" ]
Register a task or pipe @name resgister @access internal @param string type [accepts any value, actual values: 'task' or 'pipe'] @param string name @param function create @return void
[ "Register", "a", "task", "or", "pipe" ]
eed953ac3c582c653fd63cbbb4b550dd33e88d13
https://github.com/konfirm/devour-gulp/blob/eed953ac3c582c653fd63cbbb4b550dd33e88d13/lib/devour.js#L91-L101
50,008
konfirm/devour-gulp
lib/devour.js
plug
function plug(name) { var part, scope; if (!('buffer' in plug.prototype)) { plug.prototype.buffer = {}; } part = name.split('.'); scope = part.shift(); if (!(scope in plug.prototype.buffer)) { plug.prototype.buffer[scope] = wanted.require('gulp-' + scope); } scope = plug.prototype.buffer[scope]; part.forEach(function(p) { scope = scope[p]; }); // this may be an a-typical gulp plugin (e.g. sourcemaps) which provides no stream, the implementer probably // knows what to do with this if (typeof scope !== 'function') { return scope; } // invoke the function in the scope with the arguments after the name // this should create a stream return scope.apply(null, Array.prototype.slice.call(arguments, 1)) // always register an error listener for plugins .on('error', function(error) { console.error('Error from plugin %s: %s', chalk.red(name), error); this.emit('end'); }) ; }
javascript
function plug(name) { var part, scope; if (!('buffer' in plug.prototype)) { plug.prototype.buffer = {}; } part = name.split('.'); scope = part.shift(); if (!(scope in plug.prototype.buffer)) { plug.prototype.buffer[scope] = wanted.require('gulp-' + scope); } scope = plug.prototype.buffer[scope]; part.forEach(function(p) { scope = scope[p]; }); // this may be an a-typical gulp plugin (e.g. sourcemaps) which provides no stream, the implementer probably // knows what to do with this if (typeof scope !== 'function') { return scope; } // invoke the function in the scope with the arguments after the name // this should create a stream return scope.apply(null, Array.prototype.slice.call(arguments, 1)) // always register an error listener for plugins .on('error', function(error) { console.error('Error from plugin %s: %s', chalk.red(name), error); this.emit('end'); }) ; }
[ "function", "plug", "(", "name", ")", "{", "var", "part", ",", "scope", ";", "if", "(", "!", "(", "'buffer'", "in", "plug", ".", "prototype", ")", ")", "{", "plug", ".", "prototype", ".", "buffer", "=", "{", "}", ";", "}", "part", "=", "name", ".", "split", "(", "'.'", ")", ";", "scope", "=", "part", ".", "shift", "(", ")", ";", "if", "(", "!", "(", "scope", "in", "plug", ".", "prototype", ".", "buffer", ")", ")", "{", "plug", ".", "prototype", ".", "buffer", "[", "scope", "]", "=", "wanted", ".", "require", "(", "'gulp-'", "+", "scope", ")", ";", "}", "scope", "=", "plug", ".", "prototype", ".", "buffer", "[", "scope", "]", ";", "part", ".", "forEach", "(", "function", "(", "p", ")", "{", "scope", "=", "scope", "[", "p", "]", ";", "}", ")", ";", "// this may be an a-typical gulp plugin (e.g. sourcemaps) which provides no stream, the implementer probably", "// knows what to do with this", "if", "(", "typeof", "scope", "!==", "'function'", ")", "{", "return", "scope", ";", "}", "// invoke the function in the scope with the arguments after the name", "// this should create a stream", "return", "scope", ".", "apply", "(", "null", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", "// always register an error listener for plugins", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "console", ".", "error", "(", "'Error from plugin %s: %s'", ",", "chalk", ".", "red", "(", "name", ")", ",", "error", ")", ";", "this", ".", "emit", "(", "'end'", ")", ";", "}", ")", ";", "}" ]
Obtain a gulp plugin, initialized with given arguments @name plug @access internal @param string name [automatically prefixed with 'gulp-'] @return stream initialized plugin
[ "Obtain", "a", "gulp", "plugin", "initialized", "with", "given", "arguments" ]
eed953ac3c582c653fd63cbbb4b550dd33e88d13
https://github.com/konfirm/devour-gulp/blob/eed953ac3c582c653fd63cbbb4b550dd33e88d13/lib/devour.js#L110-L145
50,009
konfirm/devour-gulp
lib/devour.js
startRequested
function startRequested() { var start = []; if (run.length) { run.forEach(function(task) { var exists = task.replace(/:.*$/, '') in definitions.task; console.log( 'Task %s %s', exists ? chalk.green(task) : chalk.red(task), exists ? 'running' : 'not found!' ); if (exists) { start.push(task); } }); if (start.length) { gulp.start.apply(gulp, start.concat([function(error) { if (error) { throw new Error(error); } console.log('Complete'); }])); } else { console.log(chalk.red('No tasks are running, exiting!')); process.exit(1); } } return !!start.length; }
javascript
function startRequested() { var start = []; if (run.length) { run.forEach(function(task) { var exists = task.replace(/:.*$/, '') in definitions.task; console.log( 'Task %s %s', exists ? chalk.green(task) : chalk.red(task), exists ? 'running' : 'not found!' ); if (exists) { start.push(task); } }); if (start.length) { gulp.start.apply(gulp, start.concat([function(error) { if (error) { throw new Error(error); } console.log('Complete'); }])); } else { console.log(chalk.red('No tasks are running, exiting!')); process.exit(1); } } return !!start.length; }
[ "function", "startRequested", "(", ")", "{", "var", "start", "=", "[", "]", ";", "if", "(", "run", ".", "length", ")", "{", "run", ".", "forEach", "(", "function", "(", "task", ")", "{", "var", "exists", "=", "task", ".", "replace", "(", "/", ":.*$", "/", ",", "''", ")", "in", "definitions", ".", "task", ";", "console", ".", "log", "(", "'Task %s %s'", ",", "exists", "?", "chalk", ".", "green", "(", "task", ")", ":", "chalk", ".", "red", "(", "task", ")", ",", "exists", "?", "'running'", ":", "'not found!'", ")", ";", "if", "(", "exists", ")", "{", "start", ".", "push", "(", "task", ")", ";", "}", "}", ")", ";", "if", "(", "start", ".", "length", ")", "{", "gulp", ".", "start", ".", "apply", "(", "gulp", ",", "start", ".", "concat", "(", "[", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "throw", "new", "Error", "(", "error", ")", ";", "}", "console", ".", "log", "(", "'Complete'", ")", ";", "}", "]", ")", ")", ";", "}", "else", "{", "console", ".", "log", "(", "chalk", ".", "red", "(", "'No tasks are running, exiting!'", ")", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "}", "return", "!", "!", "start", ".", "length", ";", "}" ]
Start tasks provided from the command line @name startRequested @access internal @return bool started
[ "Start", "tasks", "provided", "from", "the", "command", "line" ]
eed953ac3c582c653fd63cbbb4b550dd33e88d13
https://github.com/konfirm/devour-gulp/blob/eed953ac3c582c653fd63cbbb4b550dd33e88d13/lib/devour.js#L153-L187
50,010
jamespdlynn/microjs
examples/game/lib/client.js
readData
function readData(raw){ var dataObj = micro.toJSON(new Buffer(raw)); var type = dataObj._type; delete dataObj._type; switch (type){ case "Ping": //Grab latency (if exists) and bounce back the exact same data packet latency = dataObj.latency || latency; socket.send(raw); break; case "GameData" : //Initialize the game data and update the each of the zone's player data according to latency gameData.set(dataObj); currentZone = gameData.currentZone.update(latency); break; case "Zone": if (!gameData.get("isRunning")) return; //Use dummy Zone Model to first update the data values according to latency dataObj = new Zone(dataObj).update(latency).toJSON(); //Set easing to true so we don't simply override each existing player's x,y coordinates currentZone.set(dataObj, {easing:true, silent:true}); break; case "Player": if (!gameData.get("isRunning")) return; //Use dummy Player Model to update the data values according to latency dataObj = new Player(dataObj).update(latency).toJSON(); //Set easing to true so we don't simply override this player's x,y coordinates (if they exist) currentZone.players.set(dataObj, {easing:true, remove:false, silent:true}); break; case "PlayerUpdate": if (!gameData.get("isRunning")) return; //A player update contains minimal player information, so we don't need to worry about easing currentZone.players.set(dataObj, {add:false, remove:false, silent:true}); break; default: console.warn("Unknown schema type received: "+type); break; } }
javascript
function readData(raw){ var dataObj = micro.toJSON(new Buffer(raw)); var type = dataObj._type; delete dataObj._type; switch (type){ case "Ping": //Grab latency (if exists) and bounce back the exact same data packet latency = dataObj.latency || latency; socket.send(raw); break; case "GameData" : //Initialize the game data and update the each of the zone's player data according to latency gameData.set(dataObj); currentZone = gameData.currentZone.update(latency); break; case "Zone": if (!gameData.get("isRunning")) return; //Use dummy Zone Model to first update the data values according to latency dataObj = new Zone(dataObj).update(latency).toJSON(); //Set easing to true so we don't simply override each existing player's x,y coordinates currentZone.set(dataObj, {easing:true, silent:true}); break; case "Player": if (!gameData.get("isRunning")) return; //Use dummy Player Model to update the data values according to latency dataObj = new Player(dataObj).update(latency).toJSON(); //Set easing to true so we don't simply override this player's x,y coordinates (if they exist) currentZone.players.set(dataObj, {easing:true, remove:false, silent:true}); break; case "PlayerUpdate": if (!gameData.get("isRunning")) return; //A player update contains minimal player information, so we don't need to worry about easing currentZone.players.set(dataObj, {add:false, remove:false, silent:true}); break; default: console.warn("Unknown schema type received: "+type); break; } }
[ "function", "readData", "(", "raw", ")", "{", "var", "dataObj", "=", "micro", ".", "toJSON", "(", "new", "Buffer", "(", "raw", ")", ")", ";", "var", "type", "=", "dataObj", ".", "_type", ";", "delete", "dataObj", ".", "_type", ";", "switch", "(", "type", ")", "{", "case", "\"Ping\"", ":", "//Grab latency (if exists) and bounce back the exact same data packet", "latency", "=", "dataObj", ".", "latency", "||", "latency", ";", "socket", ".", "send", "(", "raw", ")", ";", "break", ";", "case", "\"GameData\"", ":", "//Initialize the game data and update the each of the zone's player data according to latency", "gameData", ".", "set", "(", "dataObj", ")", ";", "currentZone", "=", "gameData", ".", "currentZone", ".", "update", "(", "latency", ")", ";", "break", ";", "case", "\"Zone\"", ":", "if", "(", "!", "gameData", ".", "get", "(", "\"isRunning\"", ")", ")", "return", ";", "//Use dummy Zone Model to first update the data values according to latency", "dataObj", "=", "new", "Zone", "(", "dataObj", ")", ".", "update", "(", "latency", ")", ".", "toJSON", "(", ")", ";", "//Set easing to true so we don't simply override each existing player's x,y coordinates", "currentZone", ".", "set", "(", "dataObj", ",", "{", "easing", ":", "true", ",", "silent", ":", "true", "}", ")", ";", "break", ";", "case", "\"Player\"", ":", "if", "(", "!", "gameData", ".", "get", "(", "\"isRunning\"", ")", ")", "return", ";", "//Use dummy Player Model to update the data values according to latency", "dataObj", "=", "new", "Player", "(", "dataObj", ")", ".", "update", "(", "latency", ")", ".", "toJSON", "(", ")", ";", "//Set easing to true so we don't simply override this player's x,y coordinates (if they exist)", "currentZone", ".", "players", ".", "set", "(", "dataObj", ",", "{", "easing", ":", "true", ",", "remove", ":", "false", ",", "silent", ":", "true", "}", ")", ";", "break", ";", "case", "\"PlayerUpdate\"", ":", "if", "(", "!", "gameData", ".", "get", "(", "\"isRunning\"", ")", ")", "return", ";", "//A player update contains minimal player information, so we don't need to worry about easing", "currentZone", ".", "players", ".", "set", "(", "dataObj", ",", "{", "add", ":", "false", ",", "remove", ":", "false", ",", "silent", ":", "true", "}", ")", ";", "break", ";", "default", ":", "console", ".", "warn", "(", "\"Unknown schema type received: \"", "+", "type", ")", ";", "break", ";", "}", "}" ]
Handle data received from server
[ "Handle", "data", "received", "from", "server" ]
780a4074de84bcd74e3ae50d0ed64144b4474166
https://github.com/jamespdlynn/microjs/blob/780a4074de84bcd74e3ae50d0ed64144b4474166/examples/game/lib/client.js#L39-L89
50,011
jamespdlynn/microjs
examples/game/lib/client.js
onUserPlayerChange
function onUserPlayerChange(data){ var player = gameData.player; //Check if data contains different values if (player.get("angle") !== data.angle.toPrecision(1) || player.get("isAccelerating") !== data.isAccelerating){ var buffer = micro.toBinary(data, "PlayerUpdate"); socket.send(buffer); //Allow for latency before setting these changes on the player setTimeout(function(){ player.set(data); }, latency); } }
javascript
function onUserPlayerChange(data){ var player = gameData.player; //Check if data contains different values if (player.get("angle") !== data.angle.toPrecision(1) || player.get("isAccelerating") !== data.isAccelerating){ var buffer = micro.toBinary(data, "PlayerUpdate"); socket.send(buffer); //Allow for latency before setting these changes on the player setTimeout(function(){ player.set(data); }, latency); } }
[ "function", "onUserPlayerChange", "(", "data", ")", "{", "var", "player", "=", "gameData", ".", "player", ";", "//Check if data contains different values", "if", "(", "player", ".", "get", "(", "\"angle\"", ")", "!==", "data", ".", "angle", ".", "toPrecision", "(", "1", ")", "||", "player", ".", "get", "(", "\"isAccelerating\"", ")", "!==", "data", ".", "isAccelerating", ")", "{", "var", "buffer", "=", "micro", ".", "toBinary", "(", "data", ",", "\"PlayerUpdate\"", ")", ";", "socket", ".", "send", "(", "buffer", ")", ";", "//Allow for latency before setting these changes on the player", "setTimeout", "(", "function", "(", ")", "{", "player", ".", "set", "(", "data", ")", ";", "}", ",", "latency", ")", ";", "}", "}" ]
When a user player change event is caught, send a "PlayerUpdate" to the server
[ "When", "a", "user", "player", "change", "event", "is", "caught", "send", "a", "PlayerUpdate", "to", "the", "server" ]
780a4074de84bcd74e3ae50d0ed64144b4474166
https://github.com/jamespdlynn/microjs/blob/780a4074de84bcd74e3ae50d0ed64144b4474166/examples/game/lib/client.js#L92-L106
50,012
jonschlinkert/expand-task
index.js
Task
function Task(options) { if (!(this instanceof Task)) { return new Task(options); } utils.is(this, 'task'); use(this); this.options = options || {}; if (utils.isTask(options)) { this.options = {}; this.addTargets(options); return this; } }
javascript
function Task(options) { if (!(this instanceof Task)) { return new Task(options); } utils.is(this, 'task'); use(this); this.options = options || {}; if (utils.isTask(options)) { this.options = {}; this.addTargets(options); return this; } }
[ "function", "Task", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Task", ")", ")", "{", "return", "new", "Task", "(", "options", ")", ";", "}", "utils", ".", "is", "(", "this", ",", "'task'", ")", ";", "use", "(", "this", ")", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "if", "(", "utils", ".", "isTask", "(", "options", ")", ")", "{", "this", ".", "options", "=", "{", "}", ";", "this", ".", "addTargets", "(", "options", ")", ";", "return", "this", ";", "}", "}" ]
Create a new Task with the given `options` ```js var task = new Task({cwd: 'src'}); task.addTargets({ site: {src: ['*.hbs']}, blog: {src: ['*.md']} }); ``` @param {Object} `options` @api public
[ "Create", "a", "new", "Task", "with", "the", "given", "options" ]
b885ce5ec49f93980780a3e31e8ec3a1a892e1de
https://github.com/jonschlinkert/expand-task/blob/b885ce5ec49f93980780a3e31e8ec3a1a892e1de/index.js#L22-L36
50,013
moov2/grunt-orchard-development
tasks/download.js
function (info, cb) { // Default to a binary request var options = info.src; var dest = info.dest; // Request the url var req = request(options); // On error, callback req.on('error', cb); // On response, callback for writing out the stream req.on('response', function handleResponse (res) { // Assert the statusCode was good var statusCode = res.statusCode; if (statusCode < 200 || statusCode >= 300) { return cb(new Error('Fetching ' + JSON.stringify(options) + ' failed with HTTP status code ' + statusCode)); } // Otherwise, write out the content var destdir = path.dirname(dest); grunt.file.mkdir(destdir); var writeStream = fs.createWriteStream(dest); // Use `req` as the source of data https://github.com/request/request/blob/v2.51.1/request.js#L1255-L1267 // DEV: This is to pipe out gunzipped data var dataStream = req; dataStream.pipe(writeStream); // When the stream errors or completes, exit writeStream.on('error', cb); writeStream.on('close', cb); }); }
javascript
function (info, cb) { // Default to a binary request var options = info.src; var dest = info.dest; // Request the url var req = request(options); // On error, callback req.on('error', cb); // On response, callback for writing out the stream req.on('response', function handleResponse (res) { // Assert the statusCode was good var statusCode = res.statusCode; if (statusCode < 200 || statusCode >= 300) { return cb(new Error('Fetching ' + JSON.stringify(options) + ' failed with HTTP status code ' + statusCode)); } // Otherwise, write out the content var destdir = path.dirname(dest); grunt.file.mkdir(destdir); var writeStream = fs.createWriteStream(dest); // Use `req` as the source of data https://github.com/request/request/blob/v2.51.1/request.js#L1255-L1267 // DEV: This is to pipe out gunzipped data var dataStream = req; dataStream.pipe(writeStream); // When the stream errors or completes, exit writeStream.on('error', cb); writeStream.on('close', cb); }); }
[ "function", "(", "info", ",", "cb", ")", "{", "// Default to a binary request", "var", "options", "=", "info", ".", "src", ";", "var", "dest", "=", "info", ".", "dest", ";", "// Request the url", "var", "req", "=", "request", "(", "options", ")", ";", "// On error, callback", "req", ".", "on", "(", "'error'", ",", "cb", ")", ";", "// On response, callback for writing out the stream", "req", ".", "on", "(", "'response'", ",", "function", "handleResponse", "(", "res", ")", "{", "// Assert the statusCode was good", "var", "statusCode", "=", "res", ".", "statusCode", ";", "if", "(", "statusCode", "<", "200", "||", "statusCode", ">=", "300", ")", "{", "return", "cb", "(", "new", "Error", "(", "'Fetching '", "+", "JSON", ".", "stringify", "(", "options", ")", "+", "' failed with HTTP status code '", "+", "statusCode", ")", ")", ";", "}", "// Otherwise, write out the content", "var", "destdir", "=", "path", ".", "dirname", "(", "dest", ")", ";", "grunt", ".", "file", ".", "mkdir", "(", "destdir", ")", ";", "var", "writeStream", "=", "fs", ".", "createWriteStream", "(", "dest", ")", ";", "// Use `req` as the source of data https://github.com/request/request/blob/v2.51.1/request.js#L1255-L1267", "// DEV: This is to pipe out gunzipped data", "var", "dataStream", "=", "req", ";", "dataStream", ".", "pipe", "(", "writeStream", ")", ";", "// When the stream errors or completes, exit", "writeStream", ".", "on", "(", "'error'", ",", "cb", ")", ";", "writeStream", ".", "on", "(", "'close'", ",", "cb", ")", ";", "}", ")", ";", "}" ]
Downloads single file to local computer.
[ "Downloads", "single", "file", "to", "local", "computer", "." ]
658c5bae73f894469d099a7c2d735f9cda08d0cc
https://github.com/moov2/grunt-orchard-development/blob/658c5bae73f894469d099a7c2d735f9cda08d0cc/tasks/download.js#L37-L69
50,014
moov2/grunt-orchard-development
tasks/download.js
function (url, content) { var dirName = path.dirname(url); if (!fs.existsSync(dirName)) { fs.mkdirSync(dirName); } fs.writeFileSync(url, content, { mode: 0777 }); }
javascript
function (url, content) { var dirName = path.dirname(url); if (!fs.existsSync(dirName)) { fs.mkdirSync(dirName); } fs.writeFileSync(url, content, { mode: 0777 }); }
[ "function", "(", "url", ",", "content", ")", "{", "var", "dirName", "=", "path", ".", "dirname", "(", "url", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "dirName", ")", ")", "{", "fs", ".", "mkdirSync", "(", "dirName", ")", ";", "}", "fs", ".", "writeFileSync", "(", "url", ",", "content", ",", "{", "mode", ":", "0777", "}", ")", ";", "}" ]
Writes data to a file, ensuring that the containing directory exists.
[ "Writes", "data", "to", "a", "file", "ensuring", "that", "the", "containing", "directory", "exists", "." ]
658c5bae73f894469d099a7c2d735f9cda08d0cc
https://github.com/moov2/grunt-orchard-development/blob/658c5bae73f894469d099a7c2d735f9cda08d0cc/tasks/download.js#L90-L100
50,015
moov2/grunt-orchard-development
tasks/download.js
function (onComplete) { grunt.file.delete(options.tempDir, { force: true }); fs.exists(options.downloadDestination, function (exists) { if (exists) { fs.unlinkSync(options.downloadDestination); } if (onComplete) { onComplete(); } }); }
javascript
function (onComplete) { grunt.file.delete(options.tempDir, { force: true }); fs.exists(options.downloadDestination, function (exists) { if (exists) { fs.unlinkSync(options.downloadDestination); } if (onComplete) { onComplete(); } }); }
[ "function", "(", "onComplete", ")", "{", "grunt", ".", "file", ".", "delete", "(", "options", ".", "tempDir", ",", "{", "force", ":", "true", "}", ")", ";", "fs", ".", "exists", "(", "options", ".", "downloadDestination", ",", "function", "(", "exists", ")", "{", "if", "(", "exists", ")", "{", "fs", ".", "unlinkSync", "(", "options", ".", "downloadDestination", ")", ";", "}", "if", "(", "onComplete", ")", "{", "onComplete", "(", ")", ";", "}", "}", ")", ";", "}" ]
Deletes the downloaded zip & temporary directory.
[ "Deletes", "the", "downloaded", "zip", "&", "temporary", "directory", "." ]
658c5bae73f894469d099a7c2d735f9cda08d0cc
https://github.com/moov2/grunt-orchard-development/blob/658c5bae73f894469d099a7c2d735f9cda08d0cc/tasks/download.js#L129-L141
50,016
moov2/grunt-orchard-development
tasks/download.js
function (orchardDownload) { grunt.log.writeln('downloading Orchard ' + options.version + ', this may take a while...'); helpers.curl({ src: orchardDownload.url, dest: options.downloadDestination }, function handleCurlComplete (err) { // If there is an error, fail if (err) { grunt.fail.warn(err); return done(); } grunt.log.writeln('download complete.'); extractZip(orchardDownload); }); }
javascript
function (orchardDownload) { grunt.log.writeln('downloading Orchard ' + options.version + ', this may take a while...'); helpers.curl({ src: orchardDownload.url, dest: options.downloadDestination }, function handleCurlComplete (err) { // If there is an error, fail if (err) { grunt.fail.warn(err); return done(); } grunt.log.writeln('download complete.'); extractZip(orchardDownload); }); }
[ "function", "(", "orchardDownload", ")", "{", "grunt", ".", "log", ".", "writeln", "(", "'downloading Orchard '", "+", "options", ".", "version", "+", "', this may take a while...'", ")", ";", "helpers", ".", "curl", "(", "{", "src", ":", "orchardDownload", ".", "url", ",", "dest", ":", "options", ".", "downloadDestination", "}", ",", "function", "handleCurlComplete", "(", "err", ")", "{", "// If there is an error, fail", "if", "(", "err", ")", "{", "grunt", ".", "fail", ".", "warn", "(", "err", ")", ";", "return", "done", "(", ")", ";", "}", "grunt", ".", "log", ".", "writeln", "(", "'download complete.'", ")", ";", "extractZip", "(", "orchardDownload", ")", ";", "}", ")", ";", "}" ]
Downloads a version of Orchard from the Internet.
[ "Downloads", "a", "version", "of", "Orchard", "from", "the", "Internet", "." ]
658c5bae73f894469d099a7c2d735f9cda08d0cc
https://github.com/moov2/grunt-orchard-development/blob/658c5bae73f894469d099a7c2d735f9cda08d0cc/tasks/download.js#L146-L162
50,017
moov2/grunt-orchard-development
tasks/download.js
function (orchardDownload) { var content, dest, zip; grunt.log.writeln('extracting downloaded zip...'); fs.mkdirSync(options.tempDir); fs.readFile(options.downloadDestination, function (err, data) { if (err) { throw err; } zip = new JSZip(data); Object.keys(zip.files).forEach(function(filename) { content = zip.files[filename].asNodeBuffer(); dest = path.join(options.tempDir, filename); if (filename.substr(filename.length - 1, 1) === '/') { if (!fs.existsSync(dest)) { fs.mkdirSync(dest); } } else { helpers.writeFile(dest, content); } }); grunt.log.writeln('extraction complete.'); // introduce a slight delay to prevent a permission error when moving // the Orchard source code from a temp directory to a directory // tied to the version number. setTimeout(moveFiles, 200); }); }
javascript
function (orchardDownload) { var content, dest, zip; grunt.log.writeln('extracting downloaded zip...'); fs.mkdirSync(options.tempDir); fs.readFile(options.downloadDestination, function (err, data) { if (err) { throw err; } zip = new JSZip(data); Object.keys(zip.files).forEach(function(filename) { content = zip.files[filename].asNodeBuffer(); dest = path.join(options.tempDir, filename); if (filename.substr(filename.length - 1, 1) === '/') { if (!fs.existsSync(dest)) { fs.mkdirSync(dest); } } else { helpers.writeFile(dest, content); } }); grunt.log.writeln('extraction complete.'); // introduce a slight delay to prevent a permission error when moving // the Orchard source code from a temp directory to a directory // tied to the version number. setTimeout(moveFiles, 200); }); }
[ "function", "(", "orchardDownload", ")", "{", "var", "content", ",", "dest", ",", "zip", ";", "grunt", ".", "log", ".", "writeln", "(", "'extracting downloaded zip...'", ")", ";", "fs", ".", "mkdirSync", "(", "options", ".", "tempDir", ")", ";", "fs", ".", "readFile", "(", "options", ".", "downloadDestination", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "zip", "=", "new", "JSZip", "(", "data", ")", ";", "Object", ".", "keys", "(", "zip", ".", "files", ")", ".", "forEach", "(", "function", "(", "filename", ")", "{", "content", "=", "zip", ".", "files", "[", "filename", "]", ".", "asNodeBuffer", "(", ")", ";", "dest", "=", "path", ".", "join", "(", "options", ".", "tempDir", ",", "filename", ")", ";", "if", "(", "filename", ".", "substr", "(", "filename", ".", "length", "-", "1", ",", "1", ")", "===", "'/'", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "dest", ")", ")", "{", "fs", ".", "mkdirSync", "(", "dest", ")", ";", "}", "}", "else", "{", "helpers", ".", "writeFile", "(", "dest", ",", "content", ")", ";", "}", "}", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "'extraction complete.'", ")", ";", "// introduce a slight delay to prevent a permission error when moving", "// the Orchard source code from a temp directory to a directory", "// tied to the version number.", "setTimeout", "(", "moveFiles", ",", "200", ")", ";", "}", ")", ";", "}" ]
Unzips the download that contains Orchard and sets up the extracted files in a directory reflecting the version number.
[ "Unzips", "the", "download", "that", "contains", "Orchard", "and", "sets", "up", "the", "extracted", "files", "in", "a", "directory", "reflecting", "the", "version", "number", "." ]
658c5bae73f894469d099a7c2d735f9cda08d0cc
https://github.com/moov2/grunt-orchard-development/blob/658c5bae73f894469d099a7c2d735f9cda08d0cc/tasks/download.js#L168-L202
50,018
moov2/grunt-orchard-development
tasks/download.js
function () { // ensures the uncompressed Orchard code is inside the version directory // inside directory that contains local Orchard install. This is to // ensure a directory structure like `/local/1.8.1/Orchard-1.8.1` // doesn't occur becuase the download zip contents is within it's // own directory. var contents = helpers.getDirectories(options.tempDir), currentDirName = (contents.length === 1) ? path.join(options.tempDir, contents[0]) : options.tempDir; mv(currentDirName, options.localDir, {mkdirp: true}, function() { cleanUp(done); }); }
javascript
function () { // ensures the uncompressed Orchard code is inside the version directory // inside directory that contains local Orchard install. This is to // ensure a directory structure like `/local/1.8.1/Orchard-1.8.1` // doesn't occur becuase the download zip contents is within it's // own directory. var contents = helpers.getDirectories(options.tempDir), currentDirName = (contents.length === 1) ? path.join(options.tempDir, contents[0]) : options.tempDir; mv(currentDirName, options.localDir, {mkdirp: true}, function() { cleanUp(done); }); }
[ "function", "(", ")", "{", "// ensures the uncompressed Orchard code is inside the version directory", "// inside directory that contains local Orchard install. This is to", "// ensure a directory structure like `/local/1.8.1/Orchard-1.8.1`", "// doesn't occur becuase the download zip contents is within it's", "// own directory.", "var", "contents", "=", "helpers", ".", "getDirectories", "(", "options", ".", "tempDir", ")", ",", "currentDirName", "=", "(", "contents", ".", "length", "===", "1", ")", "?", "path", ".", "join", "(", "options", ".", "tempDir", ",", "contents", "[", "0", "]", ")", ":", "options", ".", "tempDir", ";", "mv", "(", "currentDirName", ",", "options", ".", "localDir", ",", "{", "mkdirp", ":", "true", "}", ",", "function", "(", ")", "{", "cleanUp", "(", "done", ")", ";", "}", ")", ";", "}" ]
Moves extract files into directory that reflects the version number.
[ "Moves", "extract", "files", "into", "directory", "that", "reflects", "the", "version", "number", "." ]
658c5bae73f894469d099a7c2d735f9cda08d0cc
https://github.com/moov2/grunt-orchard-development/blob/658c5bae73f894469d099a7c2d735f9cda08d0cc/tasks/download.js#L207-L219
50,019
Psychopoulet/node-promfs
lib/extends/_directoryToString.js
_directoryToString
function _directoryToString (directory, encoding, separator, callback) { if ("undefined" === typeof directory) { throw new ReferenceError("missing \"directory\" argument"); } else if ("string" !== typeof directory) { throw new TypeError("\"directory\" argument is not a string"); } else if ("" === directory.trim()) { throw new Error("\"directory\" argument is empty"); } else if ("undefined" === typeof callback && "undefined" === typeof separator && "undefined" === typeof encoding) { throw new ReferenceError("missing \"callback\" argument"); } else if ("function" !== typeof callback && "function" !== typeof separator && "function" !== typeof encoding) { throw new TypeError("\"callback\" argument is not a function"); } else { let _callback = callback; if ("undefined" === typeof _callback) { if ("undefined" === typeof separator) { _callback = encoding; } else { _callback = separator; } } extractFiles(directory, (err, files) => { return err ? _callback(err) : filesToString(files, encoding, separator, _callback); }); } }
javascript
function _directoryToString (directory, encoding, separator, callback) { if ("undefined" === typeof directory) { throw new ReferenceError("missing \"directory\" argument"); } else if ("string" !== typeof directory) { throw new TypeError("\"directory\" argument is not a string"); } else if ("" === directory.trim()) { throw new Error("\"directory\" argument is empty"); } else if ("undefined" === typeof callback && "undefined" === typeof separator && "undefined" === typeof encoding) { throw new ReferenceError("missing \"callback\" argument"); } else if ("function" !== typeof callback && "function" !== typeof separator && "function" !== typeof encoding) { throw new TypeError("\"callback\" argument is not a function"); } else { let _callback = callback; if ("undefined" === typeof _callback) { if ("undefined" === typeof separator) { _callback = encoding; } else { _callback = separator; } } extractFiles(directory, (err, files) => { return err ? _callback(err) : filesToString(files, encoding, separator, _callback); }); } }
[ "function", "_directoryToString", "(", "directory", ",", "encoding", ",", "separator", ",", "callback", ")", "{", "if", "(", "\"undefined\"", "===", "typeof", "directory", ")", "{", "throw", "new", "ReferenceError", "(", "\"missing \\\"directory\\\" argument\"", ")", ";", "}", "else", "if", "(", "\"string\"", "!==", "typeof", "directory", ")", "{", "throw", "new", "TypeError", "(", "\"\\\"directory\\\" argument is not a string\"", ")", ";", "}", "else", "if", "(", "\"\"", "===", "directory", ".", "trim", "(", ")", ")", "{", "throw", "new", "Error", "(", "\"\\\"directory\\\" argument is empty\"", ")", ";", "}", "else", "if", "(", "\"undefined\"", "===", "typeof", "callback", "&&", "\"undefined\"", "===", "typeof", "separator", "&&", "\"undefined\"", "===", "typeof", "encoding", ")", "{", "throw", "new", "ReferenceError", "(", "\"missing \\\"callback\\\" argument\"", ")", ";", "}", "else", "if", "(", "\"function\"", "!==", "typeof", "callback", "&&", "\"function\"", "!==", "typeof", "separator", "&&", "\"function\"", "!==", "typeof", "encoding", ")", "{", "throw", "new", "TypeError", "(", "\"\\\"callback\\\" argument is not a function\"", ")", ";", "}", "else", "{", "let", "_callback", "=", "callback", ";", "if", "(", "\"undefined\"", "===", "typeof", "_callback", ")", "{", "if", "(", "\"undefined\"", "===", "typeof", "separator", ")", "{", "_callback", "=", "encoding", ";", "}", "else", "{", "_callback", "=", "separator", ";", "}", "}", "extractFiles", "(", "directory", ",", "(", "err", ",", "files", ")", "=>", "{", "return", "err", "?", "_callback", "(", "err", ")", ":", "filesToString", "(", "files", ",", "encoding", ",", "separator", ",", "_callback", ")", ";", "}", ")", ";", "}", "}" ]
methods Async directoryToString @param {string} directory : directory to work with @param {string} encoding : encoding to use @param {string} separator : used to separate content (can be "") @param {function|null} callback : operation's result @returns {void}
[ "methods", "Async", "directoryToString" ]
016e272fc58c6ef6eae5ea551a0e8873f0ac20cc
https://github.com/Psychopoulet/node-promfs/blob/016e272fc58c6ef6eae5ea551a0e8873f0ac20cc/lib/extends/_directoryToString.js#L24-L62
50,020
impromptu/impromptu-git
index.js
function (porcelainStatus) { var PORCELAIN_PROPERTY_REGEXES = { // Leading non-whitespace that is not a question mark staged: /^[^\?\s]/, // Trailing non-whitespace unstaged: /\S$/, // Any "A" or "??" added: /A|\?\?/, // Any "M" modified: /M/, // Any "D" deleted: /D/, // Any "R" renamed: /R/ } return porcelainStatus.replace(/\s+$/, '').split('\0').map(function(line) { var status = line.substring(0, 2) var properties = [] for (var property in PORCELAIN_PROPERTY_REGEXES) { if (PORCELAIN_PROPERTY_REGEXES[property].test(status)) properties.push(property) } return { path: line.slice(3), properties: properties } }) }
javascript
function (porcelainStatus) { var PORCELAIN_PROPERTY_REGEXES = { // Leading non-whitespace that is not a question mark staged: /^[^\?\s]/, // Trailing non-whitespace unstaged: /\S$/, // Any "A" or "??" added: /A|\?\?/, // Any "M" modified: /M/, // Any "D" deleted: /D/, // Any "R" renamed: /R/ } return porcelainStatus.replace(/\s+$/, '').split('\0').map(function(line) { var status = line.substring(0, 2) var properties = [] for (var property in PORCELAIN_PROPERTY_REGEXES) { if (PORCELAIN_PROPERTY_REGEXES[property].test(status)) properties.push(property) } return { path: line.slice(3), properties: properties } }) }
[ "function", "(", "porcelainStatus", ")", "{", "var", "PORCELAIN_PROPERTY_REGEXES", "=", "{", "// Leading non-whitespace that is not a question mark", "staged", ":", "/", "^[^\\?\\s]", "/", ",", "// Trailing non-whitespace", "unstaged", ":", "/", "\\S$", "/", ",", "// Any \"A\" or \"??\"", "added", ":", "/", "A|\\?\\?", "/", ",", "// Any \"M\"", "modified", ":", "/", "M", "/", ",", "// Any \"D\"", "deleted", ":", "/", "D", "/", ",", "// Any \"R\"", "renamed", ":", "/", "R", "/", "}", "return", "porcelainStatus", ".", "replace", "(", "/", "\\s+$", "/", ",", "''", ")", ".", "split", "(", "'\\0'", ")", ".", "map", "(", "function", "(", "line", ")", "{", "var", "status", "=", "line", ".", "substring", "(", "0", ",", "2", ")", "var", "properties", "=", "[", "]", "for", "(", "var", "property", "in", "PORCELAIN_PROPERTY_REGEXES", ")", "{", "if", "(", "PORCELAIN_PROPERTY_REGEXES", "[", "property", "]", ".", "test", "(", "status", ")", ")", "properties", ".", "push", "(", "property", ")", "}", "return", "{", "path", ":", "line", ".", "slice", "(", "3", ")", ",", "properties", ":", "properties", "}", "}", ")", "}" ]
Helper function to format git statuses
[ "Helper", "function", "to", "format", "git", "statuses" ]
ce078c236bec273d52bd8a2a5f780dee423e3595
https://github.com/impromptu/impromptu-git/blob/ce078c236bec273d52bd8a2a5f780dee423e3595/index.js#L6-L34
50,021
cemtopkaya/kuark-db
src/db_kalem.js
f_tahta_kalem_takip_ekle
function f_tahta_kalem_takip_ekle(_tahta_id, _kalem_id) { //kalem takip edilecek olarak belirlendiğinde ihalesi de takip edilecek olarak ayarlamalıyız return result.dbQ.sadd(result.kp.tahta.ssetTakiptekiKalemleri(_tahta_id), _kalem_id) .then(function () { return result.dbQ.hget(result.kp.kalem.hsetIhaleleri, _kalem_id) .then(function (_ihale_id) { return result.dbQ.sadd(result.kp.tahta.ssetTakiptekiIhaleleri(_tahta_id), _ihale_id); }); }); }
javascript
function f_tahta_kalem_takip_ekle(_tahta_id, _kalem_id) { //kalem takip edilecek olarak belirlendiğinde ihalesi de takip edilecek olarak ayarlamalıyız return result.dbQ.sadd(result.kp.tahta.ssetTakiptekiKalemleri(_tahta_id), _kalem_id) .then(function () { return result.dbQ.hget(result.kp.kalem.hsetIhaleleri, _kalem_id) .then(function (_ihale_id) { return result.dbQ.sadd(result.kp.tahta.ssetTakiptekiIhaleleri(_tahta_id), _ihale_id); }); }); }
[ "function", "f_tahta_kalem_takip_ekle", "(", "_tahta_id", ",", "_kalem_id", ")", "{", "//kalem takip edilecek olarak belirlendiğinde ihalesi de takip edilecek olarak ayarlamalıyız\r", "return", "result", ".", "dbQ", ".", "sadd", "(", "result", ".", "kp", ".", "tahta", ".", "ssetTakiptekiKalemleri", "(", "_tahta_id", ")", ",", "_kalem_id", ")", ".", "then", "(", "function", "(", ")", "{", "return", "result", ".", "dbQ", ".", "hget", "(", "result", ".", "kp", ".", "kalem", ".", "hsetIhaleleri", ",", "_kalem_id", ")", ".", "then", "(", "function", "(", "_ihale_id", ")", "{", "return", "result", ".", "dbQ", ".", "sadd", "(", "result", ".", "kp", ".", "tahta", ".", "ssetTakiptekiIhaleleri", "(", "_tahta_id", ")", ",", "_ihale_id", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Takip edilecek kalem setine ekle @param _tahta_id @param _kalem_id @returns {*}
[ "Takip", "edilecek", "kalem", "setine", "ekle" ]
d584aaf51f65a013bec79220a05007bd70767ac2
https://github.com/cemtopkaya/kuark-db/blob/d584aaf51f65a013bec79220a05007bd70767ac2/src/db_kalem.js#L229-L238
50,022
cemtopkaya/kuark-db
src/db_kalem.js
f_kalem_ekle_tahta
function f_kalem_ekle_tahta(_tahta_id, _ihale_id, _es_kalem, _db_kalem, _kul_id) { var onay_durumu = _es_kalem.OnayDurumu; //genel ihaleye tahtada yeni kalem ekleniyor //bu durumda sadece tahtanın (tahta:401:ihale:101:kalem) kalemlerine eklemeliyiz //ihalenin genel kalemlerine değil!! (ihale:101:kalem) return result.dbQ.incr(result.kp.kalem.idx) .then(function (_id) { _es_kalem.Id = _db_kalem.Id = _id; emitter.emit(schema.SABIT.OLAY.KALEM_EKLENDI, _es_kalem, _ihale_id, _tahta_id, _kul_id); //satırı ihale-tahta ile ilişkilendireceğiz return result.dbQ.hset(result.kp.kalem.tablo, _id, JSON.stringify(_db_kalem)) .then(function () { return result.dbQ.Q.all([ result.dbQ.sadd(result.kp.tahta.ssetOzelKalemleri(_tahta_id, _ihale_id, true), _db_kalem.Id), result.dbQ.hset(result.kp.kalem.hsetIhaleleri, _db_kalem.Id, _ihale_id) ]); }) .then(function () { //onay durumu varsa güncelle yoksa satırı döner return f_kalem_onay_durumu_guncelle(_tahta_id, _ihale_id, _db_kalem.Id, onay_durumu); }) .then(function () { return f_kalem_id(_id, _tahta_id); }); }) .fail(function (_err) { l.e(_err); throw new exception.Istisna("kalem eklenemedi", "HATA: " + _err); }); }
javascript
function f_kalem_ekle_tahta(_tahta_id, _ihale_id, _es_kalem, _db_kalem, _kul_id) { var onay_durumu = _es_kalem.OnayDurumu; //genel ihaleye tahtada yeni kalem ekleniyor //bu durumda sadece tahtanın (tahta:401:ihale:101:kalem) kalemlerine eklemeliyiz //ihalenin genel kalemlerine değil!! (ihale:101:kalem) return result.dbQ.incr(result.kp.kalem.idx) .then(function (_id) { _es_kalem.Id = _db_kalem.Id = _id; emitter.emit(schema.SABIT.OLAY.KALEM_EKLENDI, _es_kalem, _ihale_id, _tahta_id, _kul_id); //satırı ihale-tahta ile ilişkilendireceğiz return result.dbQ.hset(result.kp.kalem.tablo, _id, JSON.stringify(_db_kalem)) .then(function () { return result.dbQ.Q.all([ result.dbQ.sadd(result.kp.tahta.ssetOzelKalemleri(_tahta_id, _ihale_id, true), _db_kalem.Id), result.dbQ.hset(result.kp.kalem.hsetIhaleleri, _db_kalem.Id, _ihale_id) ]); }) .then(function () { //onay durumu varsa güncelle yoksa satırı döner return f_kalem_onay_durumu_guncelle(_tahta_id, _ihale_id, _db_kalem.Id, onay_durumu); }) .then(function () { return f_kalem_id(_id, _tahta_id); }); }) .fail(function (_err) { l.e(_err); throw new exception.Istisna("kalem eklenemedi", "HATA: " + _err); }); }
[ "function", "f_kalem_ekle_tahta", "(", "_tahta_id", ",", "_ihale_id", ",", "_es_kalem", ",", "_db_kalem", ",", "_kul_id", ")", "{", "var", "onay_durumu", "=", "_es_kalem", ".", "OnayDurumu", ";", "//genel ihaleye tahtada yeni kalem ekleniyor\r", "//bu durumda sadece tahtanın (tahta:401:ihale:101:kalem) kalemlerine eklemeliyiz\r", "//ihalenin genel kalemlerine değil!! (ihale:101:kalem)\r", "return", "result", ".", "dbQ", ".", "incr", "(", "result", ".", "kp", ".", "kalem", ".", "idx", ")", ".", "then", "(", "function", "(", "_id", ")", "{", "_es_kalem", ".", "Id", "=", "_db_kalem", ".", "Id", "=", "_id", ";", "emitter", ".", "emit", "(", "schema", ".", "SABIT", ".", "OLAY", ".", "KALEM_EKLENDI", ",", "_es_kalem", ",", "_ihale_id", ",", "_tahta_id", ",", "_kul_id", ")", ";", "//satırı ihale-tahta ile ilişkilendireceğiz\r", "return", "result", ".", "dbQ", ".", "hset", "(", "result", ".", "kp", ".", "kalem", ".", "tablo", ",", "_id", ",", "JSON", ".", "stringify", "(", "_db_kalem", ")", ")", ".", "then", "(", "function", "(", ")", "{", "return", "result", ".", "dbQ", ".", "Q", ".", "all", "(", "[", "result", ".", "dbQ", ".", "sadd", "(", "result", ".", "kp", ".", "tahta", ".", "ssetOzelKalemleri", "(", "_tahta_id", ",", "_ihale_id", ",", "true", ")", ",", "_db_kalem", ".", "Id", ")", ",", "result", ".", "dbQ", ".", "hset", "(", "result", ".", "kp", ".", "kalem", ".", "hsetIhaleleri", ",", "_db_kalem", ".", "Id", ",", "_ihale_id", ")", "]", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "//onay durumu varsa güncelle yoksa satırı döner\r", "return", "f_kalem_onay_durumu_guncelle", "(", "_tahta_id", ",", "_ihale_id", ",", "_db_kalem", ".", "Id", ",", "onay_durumu", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "f_kalem_id", "(", "_id", ",", "_tahta_id", ")", ";", "}", ")", ";", "}", ")", ".", "fail", "(", "function", "(", "_err", ")", "{", "l", ".", "e", "(", "_err", ")", ";", "throw", "new", "exception", ".", "Istisna", "(", "\"kalem eklenemedi\"", ",", "\"HATA: \"", "+", "_err", ")", ";", "}", ")", ";", "}" ]
Tahtaya yeni kalem ekle @param _tahta_id @param _ihale_id @param _es_kalem @param _db_kalem @param _kul_id @returns {*}
[ "Tahtaya", "yeni", "kalem", "ekle" ]
d584aaf51f65a013bec79220a05007bd70767ac2
https://github.com/cemtopkaya/kuark-db/blob/d584aaf51f65a013bec79220a05007bd70767ac2/src/db_kalem.js#L809-L843
50,023
iopa-io/iopa-rest
src/iopa-rest/context.js
_setIgnoreCase
function _setIgnoreCase(obj, key, val) { var key_lower = key.toLowerCase(); for (var p in obj) { if (obj.hasOwnProperty(p) && key_lower == p.toLowerCase()) { obj[p] = val; return; } } obj[key] = val; }
javascript
function _setIgnoreCase(obj, key, val) { var key_lower = key.toLowerCase(); for (var p in obj) { if (obj.hasOwnProperty(p) && key_lower == p.toLowerCase()) { obj[p] = val; return; } } obj[key] = val; }
[ "function", "_setIgnoreCase", "(", "obj", ",", "key", ",", "val", ")", "{", "var", "key_lower", "=", "key", ".", "toLowerCase", "(", ")", ";", "for", "(", "var", "p", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "p", ")", "&&", "key_lower", "==", "p", ".", "toLowerCase", "(", ")", ")", "{", "obj", "[", "p", "]", "=", "val", ";", "return", ";", "}", "}", "obj", "[", "key", "]", "=", "val", ";", "}" ]
Adds or updates a javascript object, case insensitive for key property @method private_setIgnoreCase @param obj (object) the object to search @param key (string) the new or existing property name @param val (string) the new property value @private
[ "Adds", "or", "updates", "a", "javascript", "object", "case", "insensitive", "for", "key", "property" ]
14a6b11ecf8859683cd62dc2c853985cfb0555f5
https://github.com/iopa-io/iopa-rest/blob/14a6b11ecf8859683cd62dc2c853985cfb0555f5/src/iopa-rest/context.js#L127-L137
50,024
derdesign/protos
storages/sqlite.js
SQLiteStorage
function SQLiteStorage(config) { /*jshint bitwise: false */ var self = this; this.events = new EventEmitter(); app.debug(util.format('Initializing SQLite Storage on %s', config.filename)); config = config || {}; config.table = config.table || "storage"; config.mode = config.mode || (sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE); if (!config.filename) { // Exit if no filename provided throw new Error("No filename provided for SQLite Storage"); } else if (config.filename != ":memory:" && !fs.existsSync(config.filename)) { // Create file if it doesn't exist fs.writeFileSync(config.filename, '', 'binary'); } this.className = this.constructor.name; this.config = config; // Set client this.client = new sqlite3.Database(config.filename, config.mode); // Set db this.db = config.filename; // Create table if not exists app.addReadyTask(); this.client.run(util.format( "CREATE TABLE IF NOT EXISTS %s (key VARCHAR(255) UNIQUE PRIMARY KEY NOT NULL, value TEXT)", config.table), function(err) { if (err) { throw err; } else { app.flushReadyTask(); self.events.emit('init', self.client, self.db); self.initialized = true; } }); // Only set important properties enumerable protos.util.onlySetEnumerable(this, ['className', 'db']); }
javascript
function SQLiteStorage(config) { /*jshint bitwise: false */ var self = this; this.events = new EventEmitter(); app.debug(util.format('Initializing SQLite Storage on %s', config.filename)); config = config || {}; config.table = config.table || "storage"; config.mode = config.mode || (sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE); if (!config.filename) { // Exit if no filename provided throw new Error("No filename provided for SQLite Storage"); } else if (config.filename != ":memory:" && !fs.existsSync(config.filename)) { // Create file if it doesn't exist fs.writeFileSync(config.filename, '', 'binary'); } this.className = this.constructor.name; this.config = config; // Set client this.client = new sqlite3.Database(config.filename, config.mode); // Set db this.db = config.filename; // Create table if not exists app.addReadyTask(); this.client.run(util.format( "CREATE TABLE IF NOT EXISTS %s (key VARCHAR(255) UNIQUE PRIMARY KEY NOT NULL, value TEXT)", config.table), function(err) { if (err) { throw err; } else { app.flushReadyTask(); self.events.emit('init', self.client, self.db); self.initialized = true; } }); // Only set important properties enumerable protos.util.onlySetEnumerable(this, ['className', 'db']); }
[ "function", "SQLiteStorage", "(", "config", ")", "{", "/*jshint bitwise: false */", "var", "self", "=", "this", ";", "this", ".", "events", "=", "new", "EventEmitter", "(", ")", ";", "app", ".", "debug", "(", "util", ".", "format", "(", "'Initializing SQLite Storage on %s'", ",", "config", ".", "filename", ")", ")", ";", "config", "=", "config", "||", "{", "}", ";", "config", ".", "table", "=", "config", ".", "table", "||", "\"storage\"", ";", "config", ".", "mode", "=", "config", ".", "mode", "||", "(", "sqlite3", ".", "OPEN_READWRITE", "|", "sqlite3", ".", "OPEN_CREATE", ")", ";", "if", "(", "!", "config", ".", "filename", ")", "{", "// Exit if no filename provided", "throw", "new", "Error", "(", "\"No filename provided for SQLite Storage\"", ")", ";", "}", "else", "if", "(", "config", ".", "filename", "!=", "\":memory:\"", "&&", "!", "fs", ".", "existsSync", "(", "config", ".", "filename", ")", ")", "{", "// Create file if it doesn't exist", "fs", ".", "writeFileSync", "(", "config", ".", "filename", ",", "''", ",", "'binary'", ")", ";", "}", "this", ".", "className", "=", "this", ".", "constructor", ".", "name", ";", "this", ".", "config", "=", "config", ";", "// Set client", "this", ".", "client", "=", "new", "sqlite3", ".", "Database", "(", "config", ".", "filename", ",", "config", ".", "mode", ")", ";", "// Set db", "this", ".", "db", "=", "config", ".", "filename", ";", "// Create table if not exists", "app", ".", "addReadyTask", "(", ")", ";", "this", ".", "client", ".", "run", "(", "util", ".", "format", "(", "\"CREATE TABLE IF NOT EXISTS %s (key VARCHAR(255) UNIQUE PRIMARY KEY NOT NULL, value TEXT)\"", ",", "config", ".", "table", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "else", "{", "app", ".", "flushReadyTask", "(", ")", ";", "self", ".", "events", ".", "emit", "(", "'init'", ",", "self", ".", "client", ",", "self", ".", "db", ")", ";", "self", ".", "initialized", "=", "true", ";", "}", "}", ")", ";", "// Only set important properties enumerable", "protos", ".", "util", ".", "onlySetEnumerable", "(", "this", ",", "[", "'className'", ",", "'db'", "]", ")", ";", "}" ]
SQLite Storage class @class SQLiteStorage @extends Storage @constructor @param {object} app Application instance @param {object} config Storage configuration
[ "SQLite", "Storage", "class" ]
0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9
https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/storages/sqlite.js#L23-L78
50,025
ottojs/otto-errors
lib/conflict.error.js
ErrorConflict
function ErrorConflict (message) { Error.call(this); // Add Information this.name = 'ErrorConflict'; this.type = 'client'; this.status = 409; if (message) { this.message = message; } }
javascript
function ErrorConflict (message) { Error.call(this); // Add Information this.name = 'ErrorConflict'; this.type = 'client'; this.status = 409; if (message) { this.message = message; } }
[ "function", "ErrorConflict", "(", "message", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "// Add Information", "this", ".", "name", "=", "'ErrorConflict'", ";", "this", ".", "type", "=", "'client'", ";", "this", ".", "status", "=", "409", ";", "if", "(", "message", ")", "{", "this", ".", "message", "=", "message", ";", "}", "}" ]
Error - ErrorConflict
[ "Error", "-", "ErrorConflict" ]
a3c6d98fd5d35ce3c136ed7e1edd2f800af268d9
https://github.com/ottojs/otto-errors/blob/a3c6d98fd5d35ce3c136ed7e1edd2f800af268d9/lib/conflict.error.js#L8-L20
50,026
xiamidaxia/xiami
meteor/minimongo/minimongo.js
function (f, fieldsIndex, ignoreEmptyFields) { if (!f) return function () {}; return function (/*args*/) { var context = this; var args = arguments; if (self.collection.paused) return; if (fieldsIndex !== undefined && self.projectionFn) { args[fieldsIndex] = self.projectionFn(args[fieldsIndex]); if (ignoreEmptyFields && _.isEmpty(args[fieldsIndex])) return; } self.collection._observeQueue.queueTask(function () { f.apply(context, args); }); }; }
javascript
function (f, fieldsIndex, ignoreEmptyFields) { if (!f) return function () {}; return function (/*args*/) { var context = this; var args = arguments; if (self.collection.paused) return; if (fieldsIndex !== undefined && self.projectionFn) { args[fieldsIndex] = self.projectionFn(args[fieldsIndex]); if (ignoreEmptyFields && _.isEmpty(args[fieldsIndex])) return; } self.collection._observeQueue.queueTask(function () { f.apply(context, args); }); }; }
[ "function", "(", "f", ",", "fieldsIndex", ",", "ignoreEmptyFields", ")", "{", "if", "(", "!", "f", ")", "return", "function", "(", ")", "{", "}", ";", "return", "function", "(", "/*args*/", ")", "{", "var", "context", "=", "this", ";", "var", "args", "=", "arguments", ";", "if", "(", "self", ".", "collection", ".", "paused", ")", "return", ";", "if", "(", "fieldsIndex", "!==", "undefined", "&&", "self", ".", "projectionFn", ")", "{", "args", "[", "fieldsIndex", "]", "=", "self", ".", "projectionFn", "(", "args", "[", "fieldsIndex", "]", ")", ";", "if", "(", "ignoreEmptyFields", "&&", "_", ".", "isEmpty", "(", "args", "[", "fieldsIndex", "]", ")", ")", "return", ";", "}", "self", ".", "collection", ".", "_observeQueue", ".", "queueTask", "(", "function", "(", ")", "{", "f", ".", "apply", "(", "context", ",", "args", ")", ";", "}", ")", ";", "}", ";", "}" ]
furthermore, callbacks enqueue until the operation we're working on is done.
[ "furthermore", "callbacks", "enqueue", "until", "the", "operation", "we", "re", "working", "on", "is", "done", "." ]
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/minimongo/minimongo.js#L321-L341
50,027
valiton/node-various-cluster
lib/worker.js
Worker
function Worker() { this.config = JSON.parse(process.env.WORKER_CONFIG); if (typeof this.config !== 'object') { throw new Error('WORKER_CONFIG is missing'); } process.title = process.variousCluster = this.config.title; }
javascript
function Worker() { this.config = JSON.parse(process.env.WORKER_CONFIG); if (typeof this.config !== 'object') { throw new Error('WORKER_CONFIG is missing'); } process.title = process.variousCluster = this.config.title; }
[ "function", "Worker", "(", ")", "{", "this", ".", "config", "=", "JSON", ".", "parse", "(", "process", ".", "env", ".", "WORKER_CONFIG", ")", ";", "if", "(", "typeof", "this", ".", "config", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "'WORKER_CONFIG is missing'", ")", ";", "}", "process", ".", "title", "=", "process", ".", "variousCluster", "=", "this", ".", "config", ".", "title", ";", "}" ]
create a new Worker instance @memberOf global @constructor @this {Worker}
[ "create", "a", "new", "Worker", "instance" ]
b570ff342ef9138e4ae57a3639f3abc8820217ab
https://github.com/valiton/node-various-cluster/blob/b570ff342ef9138e4ae57a3639f3abc8820217ab/lib/worker.js#L96-L102
50,028
integreat-io/integreat-adapter-couchdb
lib/authstrats/couchdb.js
couchdbAuth
function couchdbAuth ({uri, key, secret} = {}) { return { /** * Check whether we've already ran authentication. * @returns {boolean} `true` if already authenticated, otherwise `false` */ isAuthenticated () { return !!this._cookie }, /** * Authenticate and return true if authentication was successful. * @returns {Promise} Promise of authentication success or failure (true/false) */ async authenticate () { return authenticate.call(this, {uri, key, secret}) }, /** * Return an object with the information needed for authenticated requests * with this strategy. * @returns {Object} Auth object */ getAuthObject () { return getAuthObject.call(this) }, /** * Return a headers object with the headers needed for authenticated requests * with this strategy. * @returns {Object} Headers object */ getAuthHeaders () { return getAuthHeaders.call(this) } } }
javascript
function couchdbAuth ({uri, key, secret} = {}) { return { /** * Check whether we've already ran authentication. * @returns {boolean} `true` if already authenticated, otherwise `false` */ isAuthenticated () { return !!this._cookie }, /** * Authenticate and return true if authentication was successful. * @returns {Promise} Promise of authentication success or failure (true/false) */ async authenticate () { return authenticate.call(this, {uri, key, secret}) }, /** * Return an object with the information needed for authenticated requests * with this strategy. * @returns {Object} Auth object */ getAuthObject () { return getAuthObject.call(this) }, /** * Return a headers object with the headers needed for authenticated requests * with this strategy. * @returns {Object} Headers object */ getAuthHeaders () { return getAuthHeaders.call(this) } } }
[ "function", "couchdbAuth", "(", "{", "uri", ",", "key", ",", "secret", "}", "=", "{", "}", ")", "{", "return", "{", "/**\n * Check whether we've already ran authentication.\n * @returns {boolean} `true` if already authenticated, otherwise `false`\n */", "isAuthenticated", "(", ")", "{", "return", "!", "!", "this", ".", "_cookie", "}", ",", "/**\n * Authenticate and return true if authentication was successful.\n * @returns {Promise} Promise of authentication success or failure (true/false)\n */", "async", "authenticate", "(", ")", "{", "return", "authenticate", ".", "call", "(", "this", ",", "{", "uri", ",", "key", ",", "secret", "}", ")", "}", ",", "/**\n * Return an object with the information needed for authenticated requests\n * with this strategy.\n * @returns {Object} Auth object\n */", "getAuthObject", "(", ")", "{", "return", "getAuthObject", ".", "call", "(", "this", ")", "}", ",", "/**\n * Return a headers object with the headers needed for authenticated requests\n * with this strategy.\n * @returns {Object} Headers object\n */", "getAuthHeaders", "(", ")", "{", "return", "getAuthHeaders", ".", "call", "(", "this", ")", "}", "}", "}" ]
Create an instance of the couchdb strategy. Will retrieve an an authentication cookie and send the cookie with every request. @param {Object} options - Options object @returns {Object} Strategy object
[ "Create", "an", "instance", "of", "the", "couchdb", "strategy", ".", "Will", "retrieve", "an", "an", "authentication", "cookie", "and", "send", "the", "cookie", "with", "every", "request", "." ]
e792aaa3e85c5dae41959bc449ed3b0e149f7ebf
https://github.com/integreat-io/integreat-adapter-couchdb/blob/e792aaa3e85c5dae41959bc449ed3b0e149f7ebf/lib/authstrats/couchdb.js#L11-L47
50,029
gethuman/pancakes-recipe
middleware/mw.caller.js
getDeviceId
function getDeviceId(req) { // NOTE: client_id and client_secret are deprecated so eventually remove var deviceId = req.headers['x-device-id']; var deviceSecret = req.headers['x-device-secret']; // if client ID and secret don't exist, then no device if (!deviceId || !deviceSecret) { return null; } // else we have a device, so check the sha hash var shasum = crypto.createHash('md5').update(deviceId + config.security.device.salt); var digest = shasum.digest('hex'); // if the digest is not the same as the secret, request is unauthorized if (digest !== deviceSecret) { log.error('Invalid device ' + deviceId + ' with secret ' + deviceSecret, null); return null; } // else the device is valid, so set it and move on else { return deviceId; } }
javascript
function getDeviceId(req) { // NOTE: client_id and client_secret are deprecated so eventually remove var deviceId = req.headers['x-device-id']; var deviceSecret = req.headers['x-device-secret']; // if client ID and secret don't exist, then no device if (!deviceId || !deviceSecret) { return null; } // else we have a device, so check the sha hash var shasum = crypto.createHash('md5').update(deviceId + config.security.device.salt); var digest = shasum.digest('hex'); // if the digest is not the same as the secret, request is unauthorized if (digest !== deviceSecret) { log.error('Invalid device ' + deviceId + ' with secret ' + deviceSecret, null); return null; } // else the device is valid, so set it and move on else { return deviceId; } }
[ "function", "getDeviceId", "(", "req", ")", "{", "// NOTE: client_id and client_secret are deprecated so eventually remove", "var", "deviceId", "=", "req", ".", "headers", "[", "'x-device-id'", "]", ";", "var", "deviceSecret", "=", "req", ".", "headers", "[", "'x-device-secret'", "]", ";", "// if client ID and secret don't exist, then no device", "if", "(", "!", "deviceId", "||", "!", "deviceSecret", ")", "{", "return", "null", ";", "}", "// else we have a device, so check the sha hash", "var", "shasum", "=", "crypto", ".", "createHash", "(", "'md5'", ")", ".", "update", "(", "deviceId", "+", "config", ".", "security", ".", "device", ".", "salt", ")", ";", "var", "digest", "=", "shasum", ".", "digest", "(", "'hex'", ")", ";", "// if the digest is not the same as the secret, request is unauthorized", "if", "(", "digest", "!==", "deviceSecret", ")", "{", "log", ".", "error", "(", "'Invalid device '", "+", "deviceId", "+", "' with secret '", "+", "deviceSecret", ",", "null", ")", ";", "return", "null", ";", "}", "// else the device is valid, so set it and move on", "else", "{", "return", "deviceId", ";", "}", "}" ]
Get the device id if it exists and the secret is valid @param req @returns {string}
[ "Get", "the", "device", "id", "if", "it", "exists", "and", "the", "secret", "is", "valid" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/middleware/mw.caller.js#L14-L36
50,030
gethuman/pancakes-recipe
middleware/mw.caller.js
getCaller
function getCaller(req) { var ipAddress = req.headers['x-forwarded-for'] || req.info.remoteAddress || ''; var user = req.user; if (user) { // if user admin and there is an onBehalfOf value then use onBehalfOf if (user.role === 'admin' && req.query.onBehalfOfId) { return { _id: req.query.onBehalfOfId, name: req.query.onBehalfOfName, role: req.query.onBehalfOfRole, type: req.query.onBehalfOfType, ipAddress: ipAddress }; } // else return user data as caller info return { _id: user._id, name: user.username, role: user.role, type: 'user', user: user, ipAddress: ipAddress }; } else if (req.deviceId) { return { _id: req.deviceId, name: req.deviceId, role: 'device', type: 'device', ipAddress: ipAddress }; } // if no other auth, but GET then defer to fakeblock ACL level security //else if (req.method === 'get' || req.method === 'options') { else { return { _id: 'unknown', name: 'unknown', role: 'visitor', type: 'visitor', ipAddress: ipAddress }; } }
javascript
function getCaller(req) { var ipAddress = req.headers['x-forwarded-for'] || req.info.remoteAddress || ''; var user = req.user; if (user) { // if user admin and there is an onBehalfOf value then use onBehalfOf if (user.role === 'admin' && req.query.onBehalfOfId) { return { _id: req.query.onBehalfOfId, name: req.query.onBehalfOfName, role: req.query.onBehalfOfRole, type: req.query.onBehalfOfType, ipAddress: ipAddress }; } // else return user data as caller info return { _id: user._id, name: user.username, role: user.role, type: 'user', user: user, ipAddress: ipAddress }; } else if (req.deviceId) { return { _id: req.deviceId, name: req.deviceId, role: 'device', type: 'device', ipAddress: ipAddress }; } // if no other auth, but GET then defer to fakeblock ACL level security //else if (req.method === 'get' || req.method === 'options') { else { return { _id: 'unknown', name: 'unknown', role: 'visitor', type: 'visitor', ipAddress: ipAddress }; } }
[ "function", "getCaller", "(", "req", ")", "{", "var", "ipAddress", "=", "req", ".", "headers", "[", "'x-forwarded-for'", "]", "||", "req", ".", "info", ".", "remoteAddress", "||", "''", ";", "var", "user", "=", "req", ".", "user", ";", "if", "(", "user", ")", "{", "// if user admin and there is an onBehalfOf value then use onBehalfOf", "if", "(", "user", ".", "role", "===", "'admin'", "&&", "req", ".", "query", ".", "onBehalfOfId", ")", "{", "return", "{", "_id", ":", "req", ".", "query", ".", "onBehalfOfId", ",", "name", ":", "req", ".", "query", ".", "onBehalfOfName", ",", "role", ":", "req", ".", "query", ".", "onBehalfOfRole", ",", "type", ":", "req", ".", "query", ".", "onBehalfOfType", ",", "ipAddress", ":", "ipAddress", "}", ";", "}", "// else return user data as caller info", "return", "{", "_id", ":", "user", ".", "_id", ",", "name", ":", "user", ".", "username", ",", "role", ":", "user", ".", "role", ",", "type", ":", "'user'", ",", "user", ":", "user", ",", "ipAddress", ":", "ipAddress", "}", ";", "}", "else", "if", "(", "req", ".", "deviceId", ")", "{", "return", "{", "_id", ":", "req", ".", "deviceId", ",", "name", ":", "req", ".", "deviceId", ",", "role", ":", "'device'", ",", "type", ":", "'device'", ",", "ipAddress", ":", "ipAddress", "}", ";", "}", "// if no other auth, but GET then defer to fakeblock ACL level security", "//else if (req.method === 'get' || req.method === 'options') {", "else", "{", "return", "{", "_id", ":", "'unknown'", ",", "name", ":", "'unknown'", ",", "role", ":", "'visitor'", ",", "type", ":", "'visitor'", ",", "ipAddress", ":", "ipAddress", "}", ";", "}", "}" ]
Get the caller based on the request @param req @returns {*}
[ "Get", "the", "caller", "based", "on", "the", "request" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/middleware/mw.caller.js#L43-L91
50,031
andreypopp/es6-module-jstransform
visitors.js
visitImportDeclaration
function visitImportDeclaration(traverse, node, path, state) { var specifier, name; utils.catchup(node.range[0], state); switch (node.kind) { // import "module" case undefined: utils.append('require(' + node.source.raw + ');', state); break; // import name from "module" case "default": specifier = node.specifiers[0]; assert(specifier, "default import without specifier: " + node); name = specifier.name ? specifier.name.name : specifier.id.name; utils.append('var ' + name + ' = require(' + node.source.raw + ');', state); break; // import {name, one as other} from "module" case "named": var modID; if (node.specifiers.length === 1) { modID = 'require(' + node.source.raw + ')'; } else { modID = genID('mod'); utils.append('var ' + modID + ' = require(' + node.source.raw + ');', state); } for (var i = 0, len = node.specifiers.length; i < len; i++) { specifier = node.specifiers[i]; utils.catchupNewlines(specifier.range[0], state); name = specifier.name ? specifier.name.name : specifier.id.name; utils.append('var ' + name + ' = ' + modID + '.' + specifier.id.name + ';', state); } break; default: assert(false, "don't know how to transform: " + node.kind); } utils.catchupNewlines(node.range[1], state); utils.move(node.range[1], state); return false; }
javascript
function visitImportDeclaration(traverse, node, path, state) { var specifier, name; utils.catchup(node.range[0], state); switch (node.kind) { // import "module" case undefined: utils.append('require(' + node.source.raw + ');', state); break; // import name from "module" case "default": specifier = node.specifiers[0]; assert(specifier, "default import without specifier: " + node); name = specifier.name ? specifier.name.name : specifier.id.name; utils.append('var ' + name + ' = require(' + node.source.raw + ');', state); break; // import {name, one as other} from "module" case "named": var modID; if (node.specifiers.length === 1) { modID = 'require(' + node.source.raw + ')'; } else { modID = genID('mod'); utils.append('var ' + modID + ' = require(' + node.source.raw + ');', state); } for (var i = 0, len = node.specifiers.length; i < len; i++) { specifier = node.specifiers[i]; utils.catchupNewlines(specifier.range[0], state); name = specifier.name ? specifier.name.name : specifier.id.name; utils.append('var ' + name + ' = ' + modID + '.' + specifier.id.name + ';', state); } break; default: assert(false, "don't know how to transform: " + node.kind); } utils.catchupNewlines(node.range[1], state); utils.move(node.range[1], state); return false; }
[ "function", "visitImportDeclaration", "(", "traverse", ",", "node", ",", "path", ",", "state", ")", "{", "var", "specifier", ",", "name", ";", "utils", ".", "catchup", "(", "node", ".", "range", "[", "0", "]", ",", "state", ")", ";", "switch", "(", "node", ".", "kind", ")", "{", "// import \"module\"", "case", "undefined", ":", "utils", ".", "append", "(", "'require('", "+", "node", ".", "source", ".", "raw", "+", "');'", ",", "state", ")", ";", "break", ";", "// import name from \"module\"", "case", "\"default\"", ":", "specifier", "=", "node", ".", "specifiers", "[", "0", "]", ";", "assert", "(", "specifier", ",", "\"default import without specifier: \"", "+", "node", ")", ";", "name", "=", "specifier", ".", "name", "?", "specifier", ".", "name", ".", "name", ":", "specifier", ".", "id", ".", "name", ";", "utils", ".", "append", "(", "'var '", "+", "name", "+", "' = require('", "+", "node", ".", "source", ".", "raw", "+", "');'", ",", "state", ")", ";", "break", ";", "// import {name, one as other} from \"module\"", "case", "\"named\"", ":", "var", "modID", ";", "if", "(", "node", ".", "specifiers", ".", "length", "===", "1", ")", "{", "modID", "=", "'require('", "+", "node", ".", "source", ".", "raw", "+", "')'", ";", "}", "else", "{", "modID", "=", "genID", "(", "'mod'", ")", ";", "utils", ".", "append", "(", "'var '", "+", "modID", "+", "' = require('", "+", "node", ".", "source", ".", "raw", "+", "');'", ",", "state", ")", ";", "}", "for", "(", "var", "i", "=", "0", ",", "len", "=", "node", ".", "specifiers", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "specifier", "=", "node", ".", "specifiers", "[", "i", "]", ";", "utils", ".", "catchupNewlines", "(", "specifier", ".", "range", "[", "0", "]", ",", "state", ")", ";", "name", "=", "specifier", ".", "name", "?", "specifier", ".", "name", ".", "name", ":", "specifier", ".", "id", ".", "name", ";", "utils", ".", "append", "(", "'var '", "+", "name", "+", "' = '", "+", "modID", "+", "'.'", "+", "specifier", ".", "id", ".", "name", "+", "';'", ",", "state", ")", ";", "}", "break", ";", "default", ":", "assert", "(", "false", ",", "\"don't know how to transform: \"", "+", "node", ".", "kind", ")", ";", "}", "utils", ".", "catchupNewlines", "(", "node", ".", "range", "[", "1", "]", ",", "state", ")", ";", "utils", ".", "move", "(", "node", ".", "range", "[", "1", "]", ",", "state", ")", ";", "return", "false", ";", "}" ]
Visit ImportDeclaration. Examples: import "module" import name from "module" import { name, one as other } from "module"
[ "Visit", "ImportDeclaration", "." ]
639fe364f6a3bc1de87d2d3edf5b0dd682b3289b
https://github.com/andreypopp/es6-module-jstransform/blob/639fe364f6a3bc1de87d2d3edf5b0dd682b3289b/visitors.js#L16-L62
50,032
andreypopp/es6-module-jstransform
visitors.js
visitModuleDeclaration
function visitModuleDeclaration(traverse, node, path, state) { utils.catchup(node.range[0], state); utils.append('var ' + node.id.name + ' = require(' + node.source.raw + ');', state); utils.move(node.range[1], state); return false; }
javascript
function visitModuleDeclaration(traverse, node, path, state) { utils.catchup(node.range[0], state); utils.append('var ' + node.id.name + ' = require(' + node.source.raw + ');', state); utils.move(node.range[1], state); return false; }
[ "function", "visitModuleDeclaration", "(", "traverse", ",", "node", ",", "path", ",", "state", ")", "{", "utils", ".", "catchup", "(", "node", ".", "range", "[", "0", "]", ",", "state", ")", ";", "utils", ".", "append", "(", "'var '", "+", "node", ".", "id", ".", "name", "+", "' = require('", "+", "node", ".", "source", ".", "raw", "+", "');'", ",", "state", ")", ";", "utils", ".", "move", "(", "node", ".", "range", "[", "1", "]", ",", "state", ")", ";", "return", "false", ";", "}" ]
Visit ModuleDeclaration. Example: module name from "module"
[ "Visit", "ModuleDeclaration", "." ]
639fe364f6a3bc1de87d2d3edf5b0dd682b3289b
https://github.com/andreypopp/es6-module-jstransform/blob/639fe364f6a3bc1de87d2d3edf5b0dd682b3289b/visitors.js#L216-L221
50,033
derdesign/protos
lib/protos.js
commonStartupOperations
function commonStartupOperations() { if (options.stayUp) { process.on('uncaughtException', app.log); // prints stack trace } startupMessage.call(this, options); }
javascript
function commonStartupOperations() { if (options.stayUp) { process.on('uncaughtException', app.log); // prints stack trace } startupMessage.call(this, options); }
[ "function", "commonStartupOperations", "(", ")", "{", "if", "(", "options", ".", "stayUp", ")", "{", "process", ".", "on", "(", "'uncaughtException'", ",", "app", ".", "log", ")", ";", "// prints stack trace", "}", "startupMessage", ".", "call", "(", "this", ",", "options", ")", ";", "}" ]
Convenience function, to avoid repetition
[ "Convenience", "function", "to", "avoid", "repetition" ]
0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9
https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/protos.js#L685-L690
50,034
allex-servercore-libs/servicepack
authentication/strategies/ipstrategycreator.js
ip2long
function ip2long( a, b, c, d ) { for ( c = b = 0; d = a.split('.')[b++]; c += d >> 8 | b > 4 ? NaN : d * (1 << -8 * b) ) d = parseInt( +d && d ); return c }
javascript
function ip2long( a, b, c, d ) { for ( c = b = 0; d = a.split('.')[b++]; c += d >> 8 | b > 4 ? NaN : d * (1 << -8 * b) ) d = parseInt( +d && d ); return c }
[ "function", "ip2long", "(", "a", ",", "b", ",", "c", ",", "d", ")", "{", "for", "(", "c", "=", "b", "=", "0", ";", "d", "=", "a", ".", "split", "(", "'.'", ")", "[", "b", "++", "]", ";", "c", "+=", "d", ">>", "8", "|", "b", ">", "4", "?", "NaN", ":", "d", "*", "(", "1", "<<", "-", "8", "*", "b", ")", ")", "d", "=", "parseInt", "(", "+", "d", "&&", "d", ")", ";", "return", "c", "}" ]
Convert an IP to a long integer.
[ "Convert", "an", "IP", "to", "a", "long", "integer", "." ]
1b0ce2fe7b9208ab6c8d60d862ceeaf970797d23
https://github.com/allex-servercore-libs/servicepack/blob/1b0ce2fe7b9208ab6c8d60d862ceeaf970797d23/authentication/strategies/ipstrategycreator.js#L13-L31
50,035
allex-servercore-libs/servicepack
authentication/strategies/ipstrategycreator.js
cidr_match
function cidr_match( ip, range ) { // // If the range doesn't have a slash it will only match if identical to the IP. // if ( range.indexOf( "/" ) < 0 ) { return ( ip == range ); } // // Split the range by the slash // var parsed = range.split( "/" ); if ( parsed.length != 2 ) { console.log( "Failed to match CIDR-range on '/'" ); return false; } // // Pad out the base until it is four-parts long // // e.g. This allows 10.0/16 to be the same as 10.0.0.0/16 // while( parsed[0].split( "." ).length < 4 ) { parsed[0] += ".0"; } // // The number of IPs in the range. // // e.g. /24 == 256 IPs. // var ips = 0; // // Work out how many IPs the /slash-part matches. // // We run 2^(32-slash) // // ips = 32 - parseInt(parsed[1],10); ips = Math.pow( 2, ips) // // Logging // // console.log( "Range: " + range + " became " + parsed[0] + "'/'" + parsed[1] ); // console.log( "Which covers " + ips + " ips"); // // OK so we convert the starting IP to a long, and then calculate an ending-IP // by adding on the number of IPs the slash covers. // var ip_start = ip2long( parsed[0] ); var ip_end = ip_start + ips; // // Now convert the IP we're testing to a long. // var ip_long = ip2long( ip ); // // Is it within the range? If so we've a match. // if ( ( ip_long < ip_end ) && ( ip_long >= ip_start ) ) { return true; } else { return false; } }
javascript
function cidr_match( ip, range ) { // // If the range doesn't have a slash it will only match if identical to the IP. // if ( range.indexOf( "/" ) < 0 ) { return ( ip == range ); } // // Split the range by the slash // var parsed = range.split( "/" ); if ( parsed.length != 2 ) { console.log( "Failed to match CIDR-range on '/'" ); return false; } // // Pad out the base until it is four-parts long // // e.g. This allows 10.0/16 to be the same as 10.0.0.0/16 // while( parsed[0].split( "." ).length < 4 ) { parsed[0] += ".0"; } // // The number of IPs in the range. // // e.g. /24 == 256 IPs. // var ips = 0; // // Work out how many IPs the /slash-part matches. // // We run 2^(32-slash) // // ips = 32 - parseInt(parsed[1],10); ips = Math.pow( 2, ips) // // Logging // // console.log( "Range: " + range + " became " + parsed[0] + "'/'" + parsed[1] ); // console.log( "Which covers " + ips + " ips"); // // OK so we convert the starting IP to a long, and then calculate an ending-IP // by adding on the number of IPs the slash covers. // var ip_start = ip2long( parsed[0] ); var ip_end = ip_start + ips; // // Now convert the IP we're testing to a long. // var ip_long = ip2long( ip ); // // Is it within the range? If so we've a match. // if ( ( ip_long < ip_end ) && ( ip_long >= ip_start ) ) { return true; } else { return false; } }
[ "function", "cidr_match", "(", "ip", ",", "range", ")", "{", "//", "// If the range doesn't have a slash it will only match if identical to the IP.", "//", "if", "(", "range", ".", "indexOf", "(", "\"/\"", ")", "<", "0", ")", "{", "return", "(", "ip", "==", "range", ")", ";", "}", "//", "// Split the range by the slash", "//", "var", "parsed", "=", "range", ".", "split", "(", "\"/\"", ")", ";", "if", "(", "parsed", ".", "length", "!=", "2", ")", "{", "console", ".", "log", "(", "\"Failed to match CIDR-range on '/'\"", ")", ";", "return", "false", ";", "}", "//", "// Pad out the base until it is four-parts long", "//", "// e.g. This allows 10.0/16 to be the same as 10.0.0.0/16", "//", "while", "(", "parsed", "[", "0", "]", ".", "split", "(", "\".\"", ")", ".", "length", "<", "4", ")", "{", "parsed", "[", "0", "]", "+=", "\".0\"", ";", "}", "//", "// The number of IPs in the range.", "//", "// e.g. /24 == 256 IPs.", "//", "var", "ips", "=", "0", ";", "//", "// Work out how many IPs the /slash-part matches.", "//", "// We run 2^(32-slash)", "//", "//", "ips", "=", "32", "-", "parseInt", "(", "parsed", "[", "1", "]", ",", "10", ")", ";", "ips", "=", "Math", ".", "pow", "(", "2", ",", "ips", ")", "//", "// Logging", "//", "// console.log( \"Range: \" + range + \" became \" + parsed[0] + \"'/'\" + parsed[1] );", "// console.log( \"Which covers \" + ips + \" ips\");", "//", "// OK so we convert the starting IP to a long, and then calculate an ending-IP", "// by adding on the number of IPs the slash covers.", "//", "var", "ip_start", "=", "ip2long", "(", "parsed", "[", "0", "]", ")", ";", "var", "ip_end", "=", "ip_start", "+", "ips", ";", "//", "// Now convert the IP we're testing to a long.", "//", "var", "ip_long", "=", "ip2long", "(", "ip", ")", ";", "//", "// Is it within the range? If so we've a match.", "//", "if", "(", "(", "ip_long", "<", "ip_end", ")", "&&", "(", "ip_long", ">=", "ip_start", ")", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Determine whether the given IP falls within the specified CIDR range.
[ "Determine", "whether", "the", "given", "IP", "falls", "within", "the", "specified", "CIDR", "range", "." ]
1b0ce2fe7b9208ab6c8d60d862ceeaf970797d23
https://github.com/allex-servercore-libs/servicepack/blob/1b0ce2fe7b9208ab6c8d60d862ceeaf970797d23/authentication/strategies/ipstrategycreator.js#L56-L132
50,036
Rifdhan/weighted-randomly-select
index.js
selectWithValidation
function selectWithValidation(choices) { // Validate argument is an array if(!choices || !choices.length) { throw new Error("Randomly Select: invalid argument, please provide a non-empty array"); } // Validate that: // - each array entry has a 'chance' and 'result' property // - each 'chance' field is a number // - at least one result has a positive non-zero chance let atLeastOneChoiceHasNonZeroChance = false; for(let i = 0; i < choices.length; i++) { if(!exists(choices[i]) || !exists(choices[i].chance) || !exists(choices[i].result)) { throw new Error("Randomly Select: invalid argument, each array entry " + "must be an object with 'chance' and 'result' properties"); } else if(typeof choices[i].chance !== 'number' || choices[i].chance < 0) { throw new Error("Randomly Select: invalid argument, 'chance' must be a positive number: " + JSON.stringify(choices[i].chance)); } else if(choices[i].chance > 0) { atLeastOneChoiceHasNonZeroChance = true; } } if(!atLeastOneChoiceHasNonZeroChance) { throw new Error("Randomly Select: invalid arguments, all results have zero weight"); } // Do the actual random selection and return the result return selectWithoutValidation(choices); }
javascript
function selectWithValidation(choices) { // Validate argument is an array if(!choices || !choices.length) { throw new Error("Randomly Select: invalid argument, please provide a non-empty array"); } // Validate that: // - each array entry has a 'chance' and 'result' property // - each 'chance' field is a number // - at least one result has a positive non-zero chance let atLeastOneChoiceHasNonZeroChance = false; for(let i = 0; i < choices.length; i++) { if(!exists(choices[i]) || !exists(choices[i].chance) || !exists(choices[i].result)) { throw new Error("Randomly Select: invalid argument, each array entry " + "must be an object with 'chance' and 'result' properties"); } else if(typeof choices[i].chance !== 'number' || choices[i].chance < 0) { throw new Error("Randomly Select: invalid argument, 'chance' must be a positive number: " + JSON.stringify(choices[i].chance)); } else if(choices[i].chance > 0) { atLeastOneChoiceHasNonZeroChance = true; } } if(!atLeastOneChoiceHasNonZeroChance) { throw new Error("Randomly Select: invalid arguments, all results have zero weight"); } // Do the actual random selection and return the result return selectWithoutValidation(choices); }
[ "function", "selectWithValidation", "(", "choices", ")", "{", "// Validate argument is an array", "if", "(", "!", "choices", "||", "!", "choices", ".", "length", ")", "{", "throw", "new", "Error", "(", "\"Randomly Select: invalid argument, please provide a non-empty array\"", ")", ";", "}", "// Validate that:", "// - each array entry has a 'chance' and 'result' property", "// - each 'chance' field is a number", "// - at least one result has a positive non-zero chance", "let", "atLeastOneChoiceHasNonZeroChance", "=", "false", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "choices", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "exists", "(", "choices", "[", "i", "]", ")", "||", "!", "exists", "(", "choices", "[", "i", "]", ".", "chance", ")", "||", "!", "exists", "(", "choices", "[", "i", "]", ".", "result", ")", ")", "{", "throw", "new", "Error", "(", "\"Randomly Select: invalid argument, each array entry \"", "+", "\"must be an object with 'chance' and 'result' properties\"", ")", ";", "}", "else", "if", "(", "typeof", "choices", "[", "i", "]", ".", "chance", "!==", "'number'", "||", "choices", "[", "i", "]", ".", "chance", "<", "0", ")", "{", "throw", "new", "Error", "(", "\"Randomly Select: invalid argument, 'chance' must be a positive number: \"", "+", "JSON", ".", "stringify", "(", "choices", "[", "i", "]", ".", "chance", ")", ")", ";", "}", "else", "if", "(", "choices", "[", "i", "]", ".", "chance", ">", "0", ")", "{", "atLeastOneChoiceHasNonZeroChance", "=", "true", ";", "}", "}", "if", "(", "!", "atLeastOneChoiceHasNonZeroChance", ")", "{", "throw", "new", "Error", "(", "\"Randomly Select: invalid arguments, all results have zero weight\"", ")", ";", "}", "// Do the actual random selection and return the result", "return", "selectWithoutValidation", "(", "choices", ")", ";", "}" ]
Performs validation on input before performing the random selection
[ "Performs", "validation", "on", "input", "before", "performing", "the", "random", "selection" ]
b11f26f70f3a16e130a24b5b9f87631297024e8c
https://github.com/Rifdhan/weighted-randomly-select/blob/b11f26f70f3a16e130a24b5b9f87631297024e8c/index.js#L4-L33
50,037
Rifdhan/weighted-randomly-select
index.js
selectWithoutValidation
function selectWithoutValidation(choices) { // Generate a list of options with positive non-zero chances let choicesWithNonZeroChances = []; let totalWeight = 0.0; for(let i = 0; i < choices.length; i++) { if(choices[i].chance > 0.0) { choicesWithNonZeroChances.push(choices[i]); totalWeight += choices[i].chance; } } // Pick a random value from [0,1) let value = Math.random() * totalWeight; // Iterate over possibilities until we find the selected one let chanceCovered = 0.0; for(let i = 0; i < choicesWithNonZeroChances.length; i++) { chanceCovered += choicesWithNonZeroChances[i].chance; if(value < chanceCovered) { return choicesWithNonZeroChances[i].result; } } }
javascript
function selectWithoutValidation(choices) { // Generate a list of options with positive non-zero chances let choicesWithNonZeroChances = []; let totalWeight = 0.0; for(let i = 0; i < choices.length; i++) { if(choices[i].chance > 0.0) { choicesWithNonZeroChances.push(choices[i]); totalWeight += choices[i].chance; } } // Pick a random value from [0,1) let value = Math.random() * totalWeight; // Iterate over possibilities until we find the selected one let chanceCovered = 0.0; for(let i = 0; i < choicesWithNonZeroChances.length; i++) { chanceCovered += choicesWithNonZeroChances[i].chance; if(value < chanceCovered) { return choicesWithNonZeroChances[i].result; } } }
[ "function", "selectWithoutValidation", "(", "choices", ")", "{", "// Generate a list of options with positive non-zero chances", "let", "choicesWithNonZeroChances", "=", "[", "]", ";", "let", "totalWeight", "=", "0.0", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "choices", ".", "length", ";", "i", "++", ")", "{", "if", "(", "choices", "[", "i", "]", ".", "chance", ">", "0.0", ")", "{", "choicesWithNonZeroChances", ".", "push", "(", "choices", "[", "i", "]", ")", ";", "totalWeight", "+=", "choices", "[", "i", "]", ".", "chance", ";", "}", "}", "// Pick a random value from [0,1)", "let", "value", "=", "Math", ".", "random", "(", ")", "*", "totalWeight", ";", "// Iterate over possibilities until we find the selected one", "let", "chanceCovered", "=", "0.0", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "choicesWithNonZeroChances", ".", "length", ";", "i", "++", ")", "{", "chanceCovered", "+=", "choicesWithNonZeroChances", "[", "i", "]", ".", "chance", ";", "if", "(", "value", "<", "chanceCovered", ")", "{", "return", "choicesWithNonZeroChances", "[", "i", "]", ".", "result", ";", "}", "}", "}" ]
Performs the random selection without validating any input
[ "Performs", "the", "random", "selection", "without", "validating", "any", "input" ]
b11f26f70f3a16e130a24b5b9f87631297024e8c
https://github.com/Rifdhan/weighted-randomly-select/blob/b11f26f70f3a16e130a24b5b9f87631297024e8c/index.js#L36-L58
50,038
emiljohansson/captn
captn.dom.addclass/index.js
addClass
function addClass(element, className) { if (!hasClassNameProperty(element) || hasClass(element, className)) { return; } element.className = (element.className + ' ' + className).replace(/^\s+|\s+$/g, ''); }
javascript
function addClass(element, className) { if (!hasClassNameProperty(element) || hasClass(element, className)) { return; } element.className = (element.className + ' ' + className).replace(/^\s+|\s+$/g, ''); }
[ "function", "addClass", "(", "element", ",", "className", ")", "{", "if", "(", "!", "hasClassNameProperty", "(", "element", ")", "||", "hasClass", "(", "element", ",", "className", ")", ")", "{", "return", ";", "}", "element", ".", "className", "=", "(", "element", ".", "className", "+", "' '", "+", "className", ")", ".", "replace", "(", "/", "^\\s+|\\s+$", "/", "g", ",", "''", ")", ";", "}" ]
Adds a class name to the element's list of class names. @static @param {DOMElement} element The DOM element to modify. @param {string} className The name to append. @example hasClass(el, 'container'); // => false addClass(el, 'container'); hasClass(el, 'container'); // => true
[ "Adds", "a", "class", "name", "to", "the", "element", "s", "list", "of", "class", "names", "." ]
dae7520116dc2148b4de06af7e1d7a47a3a3ac37
https://github.com/emiljohansson/captn/blob/dae7520116dc2148b4de06af7e1d7a47a3a3ac37/captn.dom.addclass/index.js#L22-L27
50,039
ripter/bind
src/bind.dom.js
bind
function bind(element, eventName, callback) { element.addEventListener(eventName, callback); return function unbind() { element.removeEventListener(eventName, callback); }; }
javascript
function bind(element, eventName, callback) { element.addEventListener(eventName, callback); return function unbind() { element.removeEventListener(eventName, callback); }; }
[ "function", "bind", "(", "element", ",", "eventName", ",", "callback", ")", "{", "element", ".", "addEventListener", "(", "eventName", ",", "callback", ")", ";", "return", "function", "unbind", "(", ")", "{", "element", ".", "removeEventListener", "(", "eventName", ",", "callback", ")", ";", "}", ";", "}" ]
bind - listens to event on element, returning a function to stop listening to the event. @param {EventTarget} element - https://developer.mozilla.org/en-US/docs/Web/API/EventTarget @param {String} eventName - Name of the event. Like 'click', or 'did-custom-event' @param {Function} callback - @return unbind - function that unbinds the callback from the event on element.
[ "bind", "-", "listens", "to", "event", "on", "element", "returning", "a", "function", "to", "stop", "listening", "to", "the", "event", "." ]
e41e89fc3dc3ea3eb0e8ccfeb8ba97ba4a29b7a5
https://github.com/ripter/bind/blob/e41e89fc3dc3ea3eb0e8ccfeb8ba97ba4a29b7a5/src/bind.dom.js#L8-L14
50,040
xiamidaxia/xiami
meteor/minimongo/projection.js
function (doc, ruleTree) { // Special case for "sets" if (_.isArray(doc)) return _.map(doc, function (subdoc) { return transform(subdoc, ruleTree); }); var res = details.including ? {} : EJSON.clone(doc); _.each(ruleTree, function (rule, key) { if (!_.has(doc, key)) return; if (_.isObject(rule)) { // For sub-objects/subsets we branch if (_.isObject(doc[key])) res[key] = transform(doc[key], rule); // Otherwise we don't even touch this subfield } else if (details.including) res[key] = EJSON.clone(doc[key]); else delete res[key]; }); return res; }
javascript
function (doc, ruleTree) { // Special case for "sets" if (_.isArray(doc)) return _.map(doc, function (subdoc) { return transform(subdoc, ruleTree); }); var res = details.including ? {} : EJSON.clone(doc); _.each(ruleTree, function (rule, key) { if (!_.has(doc, key)) return; if (_.isObject(rule)) { // For sub-objects/subsets we branch if (_.isObject(doc[key])) res[key] = transform(doc[key], rule); // Otherwise we don't even touch this subfield } else if (details.including) res[key] = EJSON.clone(doc[key]); else delete res[key]; }); return res; }
[ "function", "(", "doc", ",", "ruleTree", ")", "{", "// Special case for \"sets\"", "if", "(", "_", ".", "isArray", "(", "doc", ")", ")", "return", "_", ".", "map", "(", "doc", ",", "function", "(", "subdoc", ")", "{", "return", "transform", "(", "subdoc", ",", "ruleTree", ")", ";", "}", ")", ";", "var", "res", "=", "details", ".", "including", "?", "{", "}", ":", "EJSON", ".", "clone", "(", "doc", ")", ";", "_", ".", "each", "(", "ruleTree", ",", "function", "(", "rule", ",", "key", ")", "{", "if", "(", "!", "_", ".", "has", "(", "doc", ",", "key", ")", ")", "return", ";", "if", "(", "_", ".", "isObject", "(", "rule", ")", ")", "{", "// For sub-objects/subsets we branch", "if", "(", "_", ".", "isObject", "(", "doc", "[", "key", "]", ")", ")", "res", "[", "key", "]", "=", "transform", "(", "doc", "[", "key", "]", ",", "rule", ")", ";", "// Otherwise we don't even touch this subfield", "}", "else", "if", "(", "details", ".", "including", ")", "res", "[", "key", "]", "=", "EJSON", ".", "clone", "(", "doc", "[", "key", "]", ")", ";", "else", "delete", "res", "[", "key", "]", ";", "}", ")", ";", "return", "res", ";", "}" ]
returns transformed doc according to ruleTree
[ "returns", "transformed", "doc", "according", "to", "ruleTree" ]
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/minimongo/projection.js#L24-L45
50,041
bithavoc/node-orch-amqp
lib/amqp_source.js
AmqpQueue
function AmqpQueue(source) { assert.ok(source); TasksSource.Queue.apply(this, []); this.source = source; this._amqpProcessing = false; }
javascript
function AmqpQueue(source) { assert.ok(source); TasksSource.Queue.apply(this, []); this.source = source; this._amqpProcessing = false; }
[ "function", "AmqpQueue", "(", "source", ")", "{", "assert", ".", "ok", "(", "source", ")", ";", "TasksSource", ".", "Queue", ".", "apply", "(", "this", ",", "[", "]", ")", ";", "this", ".", "source", "=", "source", ";", "this", ".", "_amqpProcessing", "=", "false", ";", "}" ]
AMQP Queue Wrapper
[ "AMQP", "Queue", "Wrapper" ]
d61b1035e87e4c41df1c7a7cb1472d91f225d117
https://github.com/bithavoc/node-orch-amqp/blob/d61b1035e87e4c41df1c7a7cb1472d91f225d117/lib/amqp_source.js#L72-L77
50,042
robertontiu/wrapper6
src/promises.js
resolve
function resolve(promiseLike) { // Return if already promised if (promiseLike instanceof Promise) { return promiseLike; } var promises = []; if (promiseLike instanceof Array) { promiseLike.forEach((promiseLikeEntry) => { promises.push(promisify(promiseLikeEntry)); }); } else if (promiseLike && (typeof promiseLike === "object")) { Object.keys(promiseLike).forEach((key) => { promises.push(promisify(promiseLike[key])); }); } else { return promisify(promiseLike); } return Promise.all(promises).then((result) => { if (promiseLike instanceof Array) { return result; } var response = {}; Object.keys(promiseLike).forEach((key, index) => { response[key] = result[index]; }); return response; }); }
javascript
function resolve(promiseLike) { // Return if already promised if (promiseLike instanceof Promise) { return promiseLike; } var promises = []; if (promiseLike instanceof Array) { promiseLike.forEach((promiseLikeEntry) => { promises.push(promisify(promiseLikeEntry)); }); } else if (promiseLike && (typeof promiseLike === "object")) { Object.keys(promiseLike).forEach((key) => { promises.push(promisify(promiseLike[key])); }); } else { return promisify(promiseLike); } return Promise.all(promises).then((result) => { if (promiseLike instanceof Array) { return result; } var response = {}; Object.keys(promiseLike).forEach((key, index) => { response[key] = result[index]; }); return response; }); }
[ "function", "resolve", "(", "promiseLike", ")", "{", "// Return if already promised", "if", "(", "promiseLike", "instanceof", "Promise", ")", "{", "return", "promiseLike", ";", "}", "var", "promises", "=", "[", "]", ";", "if", "(", "promiseLike", "instanceof", "Array", ")", "{", "promiseLike", ".", "forEach", "(", "(", "promiseLikeEntry", ")", "=>", "{", "promises", ".", "push", "(", "promisify", "(", "promiseLikeEntry", ")", ")", ";", "}", ")", ";", "}", "else", "if", "(", "promiseLike", "&&", "(", "typeof", "promiseLike", "===", "\"object\"", ")", ")", "{", "Object", ".", "keys", "(", "promiseLike", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "promises", ".", "push", "(", "promisify", "(", "promiseLike", "[", "key", "]", ")", ")", ";", "}", ")", ";", "}", "else", "{", "return", "promisify", "(", "promiseLike", ")", ";", "}", "return", "Promise", ".", "all", "(", "promises", ")", ".", "then", "(", "(", "result", ")", "=>", "{", "if", "(", "promiseLike", "instanceof", "Array", ")", "{", "return", "result", ";", "}", "var", "response", "=", "{", "}", ";", "Object", ".", "keys", "(", "promiseLike", ")", ".", "forEach", "(", "(", "key", ",", "index", ")", "=>", "{", "response", "[", "key", "]", "=", "result", "[", "index", "]", ";", "}", ")", ";", "return", "response", ";", "}", ")", ";", "}" ]
Resolves one or more promise-likes @param {*} promiseLike @returns {Promise}
[ "Resolves", "one", "or", "more", "promise", "-", "likes" ]
70f99dcda0f2e0926b689be349ab9bb95e84a22d
https://github.com/robertontiu/wrapper6/blob/70f99dcda0f2e0926b689be349ab9bb95e84a22d/src/promises.js#L35-L70
50,043
the-terribles/evergreen
lib/graph-builder.js
GraphBuilder
function GraphBuilder(options){ options = options || {}; // Precedence for resolvers. this.resolvers = options.resolvers || [ require('./resolvers/absolute'), require('./resolvers/relative'), require('./resolvers/environment') ]; this.handlers = options.directives || []; }
javascript
function GraphBuilder(options){ options = options || {}; // Precedence for resolvers. this.resolvers = options.resolvers || [ require('./resolvers/absolute'), require('./resolvers/relative'), require('./resolvers/environment') ]; this.handlers = options.directives || []; }
[ "function", "GraphBuilder", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "// Precedence for resolvers.", "this", ".", "resolvers", "=", "options", ".", "resolvers", "||", "[", "require", "(", "'./resolvers/absolute'", ")", ",", "require", "(", "'./resolvers/relative'", ")", ",", "require", "(", "'./resolvers/environment'", ")", "]", ";", "this", ".", "handlers", "=", "options", ".", "directives", "||", "[", "]", ";", "}" ]
Instantiate the GraphBuilder with the set of Directive Handlers. Directive Handler: { strategy: 'name', handle: function(DirectiveContext, tree, metadata, callback){ return callback(err, DirectiveContext); } @param options {Object} @constructor
[ "Instantiate", "the", "GraphBuilder", "with", "the", "set", "of", "Directive", "Handlers", "." ]
c1adaea1ce825727c5c5ed75d858e2f0d22657e2
https://github.com/the-terribles/evergreen/blob/c1adaea1ce825727c5c5ed75d858e2f0d22657e2/lib/graph-builder.js#L29-L41
50,044
gethuman/pancakes-recipe
middleware/mw.error.handling.js
handleGlobalError
function handleGlobalError() { // make sure Q provides long stack traces (disabled in prod for performance) Q.longStackSupport = config.longStackSupport; // hopefully we handle errors before this point, but this will log anything not caught process.on('uncaughtException', function (err) { log.critical('global uncaught exception : ' + err + '\n' + err.stack); /* eslint no-process-exit: 0 */ process.exit(1); }); }
javascript
function handleGlobalError() { // make sure Q provides long stack traces (disabled in prod for performance) Q.longStackSupport = config.longStackSupport; // hopefully we handle errors before this point, but this will log anything not caught process.on('uncaughtException', function (err) { log.critical('global uncaught exception : ' + err + '\n' + err.stack); /* eslint no-process-exit: 0 */ process.exit(1); }); }
[ "function", "handleGlobalError", "(", ")", "{", "// make sure Q provides long stack traces (disabled in prod for performance)", "Q", ".", "longStackSupport", "=", "config", ".", "longStackSupport", ";", "// hopefully we handle errors before this point, but this will log anything not caught", "process", ".", "on", "(", "'uncaughtException'", ",", "function", "(", "err", ")", "{", "log", ".", "critical", "(", "'global uncaught exception : '", "+", "err", "+", "'\\n'", "+", "err", ".", "stack", ")", ";", "/* eslint no-process-exit: 0 */", "process", ".", "exit", "(", "1", ")", ";", "}", ")", ";", "}" ]
Configure global error handling which includes Q and catching uncaught exceptions
[ "Configure", "global", "error", "handling", "which", "includes", "Q", "and", "catching", "uncaught", "exceptions" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/middleware/mw.error.handling.js#L13-L25
50,045
gethuman/pancakes-recipe
middleware/mw.error.handling.js
handlePreResponseError
function handlePreResponseError(server) { server.ext('onPreResponse', function (request, reply) { var response = request.response; var originalResponse = response; var msg; // No error, keep going with the reply as normal if (!response.isBoom) { reply.continue(); return; } // we need to convert to AppError if it is not already if (!(response instanceof AppError)) { msg = response.message || (response + ''); // if legit 404 be sure to use that code (happens with not found in /dist on local) if (msg.indexOf('404:') >= 0 || (response.output && response.output.payload && response.output.payload.statusCode === 404)) { response = new AppError({ code: 'not_found', msg: 'The resource ' + request.url.path + ' was not found' }); } else { msg = response.message || (response + ''); if (response.data) { msg += ' : ' + response.data; } log.info(msg); response = new AppError({ code: response.code || 'api_error', msg: msg, err: response }); } } var code = response.code || 'unknown_error'; var err = errorDecoder[code] || errorDecoder['unknown_error']; var url = request.path; if (err.httpErrorCode === 404) { trackingService.pageNotFound({ caller: request.caller, url: routeHelper.getBaseUrl(request.app.name) + url }); } else { log.error(request.method + ' ' + url + ' (' + err.friendlyMessage + ')', { err: originalResponse } ); } //TODO: this hack sucks, but needed quick way to display error page; do better! if (pancakes.getContainer() === 'webserver') { // hack fix for issue when error on trust site if (request.app && request.app.name === 'trust') { reply().redirect(routeHelper.getBaseUrl('contact') + '?notify=loginFailure'); } // else show error pages else { var errUrl = err.httpErrorCode === 404 ? '/error404' : '/error500'; pancakes.processRoute({ request: request, reply: reply, urlOverride: errUrl, returnCode: err.httpErrorCode }); } } else { reply(Boom.create(err.httpErrorCode, err.friendlyMessage)); } }); }
javascript
function handlePreResponseError(server) { server.ext('onPreResponse', function (request, reply) { var response = request.response; var originalResponse = response; var msg; // No error, keep going with the reply as normal if (!response.isBoom) { reply.continue(); return; } // we need to convert to AppError if it is not already if (!(response instanceof AppError)) { msg = response.message || (response + ''); // if legit 404 be sure to use that code (happens with not found in /dist on local) if (msg.indexOf('404:') >= 0 || (response.output && response.output.payload && response.output.payload.statusCode === 404)) { response = new AppError({ code: 'not_found', msg: 'The resource ' + request.url.path + ' was not found' }); } else { msg = response.message || (response + ''); if (response.data) { msg += ' : ' + response.data; } log.info(msg); response = new AppError({ code: response.code || 'api_error', msg: msg, err: response }); } } var code = response.code || 'unknown_error'; var err = errorDecoder[code] || errorDecoder['unknown_error']; var url = request.path; if (err.httpErrorCode === 404) { trackingService.pageNotFound({ caller: request.caller, url: routeHelper.getBaseUrl(request.app.name) + url }); } else { log.error(request.method + ' ' + url + ' (' + err.friendlyMessage + ')', { err: originalResponse } ); } //TODO: this hack sucks, but needed quick way to display error page; do better! if (pancakes.getContainer() === 'webserver') { // hack fix for issue when error on trust site if (request.app && request.app.name === 'trust') { reply().redirect(routeHelper.getBaseUrl('contact') + '?notify=loginFailure'); } // else show error pages else { var errUrl = err.httpErrorCode === 404 ? '/error404' : '/error500'; pancakes.processRoute({ request: request, reply: reply, urlOverride: errUrl, returnCode: err.httpErrorCode }); } } else { reply(Boom.create(err.httpErrorCode, err.friendlyMessage)); } }); }
[ "function", "handlePreResponseError", "(", "server", ")", "{", "server", ".", "ext", "(", "'onPreResponse'", ",", "function", "(", "request", ",", "reply", ")", "{", "var", "response", "=", "request", ".", "response", ";", "var", "originalResponse", "=", "response", ";", "var", "msg", ";", "// No error, keep going with the reply as normal", "if", "(", "!", "response", ".", "isBoom", ")", "{", "reply", ".", "continue", "(", ")", ";", "return", ";", "}", "// we need to convert to AppError if it is not already", "if", "(", "!", "(", "response", "instanceof", "AppError", ")", ")", "{", "msg", "=", "response", ".", "message", "||", "(", "response", "+", "''", ")", ";", "// if legit 404 be sure to use that code (happens with not found in /dist on local)", "if", "(", "msg", ".", "indexOf", "(", "'404:'", ")", ">=", "0", "||", "(", "response", ".", "output", "&&", "response", ".", "output", ".", "payload", "&&", "response", ".", "output", ".", "payload", ".", "statusCode", "===", "404", ")", ")", "{", "response", "=", "new", "AppError", "(", "{", "code", ":", "'not_found'", ",", "msg", ":", "'The resource '", "+", "request", ".", "url", ".", "path", "+", "' was not found'", "}", ")", ";", "}", "else", "{", "msg", "=", "response", ".", "message", "||", "(", "response", "+", "''", ")", ";", "if", "(", "response", ".", "data", ")", "{", "msg", "+=", "' : '", "+", "response", ".", "data", ";", "}", "log", ".", "info", "(", "msg", ")", ";", "response", "=", "new", "AppError", "(", "{", "code", ":", "response", ".", "code", "||", "'api_error'", ",", "msg", ":", "msg", ",", "err", ":", "response", "}", ")", ";", "}", "}", "var", "code", "=", "response", ".", "code", "||", "'unknown_error'", ";", "var", "err", "=", "errorDecoder", "[", "code", "]", "||", "errorDecoder", "[", "'unknown_error'", "]", ";", "var", "url", "=", "request", ".", "path", ";", "if", "(", "err", ".", "httpErrorCode", "===", "404", ")", "{", "trackingService", ".", "pageNotFound", "(", "{", "caller", ":", "request", ".", "caller", ",", "url", ":", "routeHelper", ".", "getBaseUrl", "(", "request", ".", "app", ".", "name", ")", "+", "url", "}", ")", ";", "}", "else", "{", "log", ".", "error", "(", "request", ".", "method", "+", "' '", "+", "url", "+", "' ('", "+", "err", ".", "friendlyMessage", "+", "')'", ",", "{", "err", ":", "originalResponse", "}", ")", ";", "}", "//TODO: this hack sucks, but needed quick way to display error page; do better!", "if", "(", "pancakes", ".", "getContainer", "(", ")", "===", "'webserver'", ")", "{", "// hack fix for issue when error on trust site", "if", "(", "request", ".", "app", "&&", "request", ".", "app", ".", "name", "===", "'trust'", ")", "{", "reply", "(", ")", ".", "redirect", "(", "routeHelper", ".", "getBaseUrl", "(", "'contact'", ")", "+", "'?notify=loginFailure'", ")", ";", "}", "// else show error pages", "else", "{", "var", "errUrl", "=", "err", ".", "httpErrorCode", "===", "404", "?", "'/error404'", ":", "'/error500'", ";", "pancakes", ".", "processRoute", "(", "{", "request", ":", "request", ",", "reply", ":", "reply", ",", "urlOverride", ":", "errUrl", ",", "returnCode", ":", "err", ".", "httpErrorCode", "}", ")", ";", "}", "}", "else", "{", "reply", "(", "Boom", ".", "create", "(", "err", ".", "httpErrorCode", ",", "err", ".", "friendlyMessage", ")", ")", ";", "}", "}", ")", ";", "}" ]
Set up the pre-response error handler @param server
[ "Set", "up", "the", "pre", "-", "response", "error", "handler" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/middleware/mw.error.handling.js#L31-L100
50,046
erwan/gulp-gist
index.js
leftAlign
function leftAlign(lines) { if (lines.length == 0) return lines; var distance = lines[0].match(/^\s*/)[0].length; var result = []; lines.forEach(function(line){ result.push(line.slice(Math.min(distance, line.match(/^\s*/)[0].length))); }); return result; }
javascript
function leftAlign(lines) { if (lines.length == 0) return lines; var distance = lines[0].match(/^\s*/)[0].length; var result = []; lines.forEach(function(line){ result.push(line.slice(Math.min(distance, line.match(/^\s*/)[0].length))); }); return result; }
[ "function", "leftAlign", "(", "lines", ")", "{", "if", "(", "lines", ".", "length", "==", "0", ")", "return", "lines", ";", "var", "distance", "=", "lines", "[", "0", "]", ".", "match", "(", "/", "^\\s*", "/", ")", "[", "0", "]", ".", "length", ";", "var", "result", "=", "[", "]", ";", "lines", ".", "forEach", "(", "function", "(", "line", ")", "{", "result", ".", "push", "(", "line", ".", "slice", "(", "Math", ".", "min", "(", "distance", ",", "line", ".", "match", "(", "/", "^\\s*", "/", ")", "[", "0", "]", ".", "length", ")", ")", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
Remove indent from the left, aligning everything with the first line
[ "Remove", "indent", "from", "the", "left", "aligning", "everything", "with", "the", "first", "line" ]
1ea776220d6bd322cec9804e40b2c54e735ed0d8
https://github.com/erwan/gulp-gist/blob/1ea776220d6bd322cec9804e40b2c54e735ed0d8/index.js#L13-L21
50,047
usrz/javascript-esquire
src/esquire.js
inject
function inject() { var args = normalize(arguments); /* Sanity check, need a callback */ if (!args.function) { throw new EsquireError("Callback for injection unspecified"); } /* Create a fake "null" module and return its value */ var module = new Module(null, args.arguments, args.function); try { return create(module, timeout, []); } catch (error) { return Promise.reject(error); } }
javascript
function inject() { var args = normalize(arguments); /* Sanity check, need a callback */ if (!args.function) { throw new EsquireError("Callback for injection unspecified"); } /* Create a fake "null" module and return its value */ var module = new Module(null, args.arguments, args.function); try { return create(module, timeout, []); } catch (error) { return Promise.reject(error); } }
[ "function", "inject", "(", ")", "{", "var", "args", "=", "normalize", "(", "arguments", ")", ";", "/* Sanity check, need a callback */", "if", "(", "!", "args", ".", "function", ")", "{", "throw", "new", "EsquireError", "(", "\"Callback for injection unspecified\"", ")", ";", "}", "/* Create a fake \"null\" module and return its value */", "var", "module", "=", "new", "Module", "(", "null", ",", "args", ".", "arguments", ",", "args", ".", "function", ")", ";", "try", "{", "return", "create", "(", "module", ",", "timeout", ",", "[", "]", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "Promise", ".", "reject", "(", "error", ")", ";", "}", "}" ]
Request injection for the specified modules. @instance @function inject @memberof Esquire @example - var esq = new Esquire(); esq.inject(['modA', 'depB'], function(a, b) { // 'a' will be an instance of 'modA' // 'b' will be an instance of 'depB' return "something"; }).then(function(result) { // The function will be (eventually) injected with its required // modules, and its return value will resolve the promis returned // by the "inject(...) method! }); @example Injection also works without arrays (only arguments) esq.inject('modA', 'depB', function(a, b) { // 'a' will be an instance of 'modA' // 'b' will be an instance of 'depB' }); @example Angular-JS style injection (one big array) is supported, too esq.inject(['modA', 'depB', function(a, b) { // 'a' will be an instance of 'modA' // 'b' will be an instance of 'depB' }]); @param {string[]|string} [dependencies] - An array of required module names whose instances will be passed to the `callback(...)` method. @param {function} callback - A function that will be called once all module dependencies have been instantiated, with each instance as a parameter. @return {@link Promise} Whatever value was returned by the `callback` function.
[ "Request", "injection", "for", "the", "specified", "modules", "." ]
59ed57393d9fc1fedd9ec50a7abb6fa7e59e491b
https://github.com/usrz/javascript-esquire/blob/59ed57393d9fc1fedd9ec50a7abb6fa7e59e491b/src/esquire.js#L1076-L1092
50,048
onecommons/polyform
packages/polyform-config/index.js
tryExtensions
function tryExtensions(p, exts, isMain) { for (var i = 0; i < exts.length; i++) { const filename = tryFile(p + exts[i], isMain); if (filename) { return filename; } } return false; }
javascript
function tryExtensions(p, exts, isMain) { for (var i = 0; i < exts.length; i++) { const filename = tryFile(p + exts[i], isMain); if (filename) { return filename; } } return false; }
[ "function", "tryExtensions", "(", "p", ",", "exts", ",", "isMain", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "exts", ".", "length", ";", "i", "++", ")", "{", "const", "filename", "=", "tryFile", "(", "p", "+", "exts", "[", "i", "]", ",", "isMain", ")", ";", "if", "(", "filename", ")", "{", "return", "filename", ";", "}", "}", "return", "false", ";", "}" ]
given a path check a the file exists with any of the set extensions
[ "given", "a", "path", "check", "a", "the", "file", "exists", "with", "any", "of", "the", "set", "extensions" ]
98cc56f7e8283e9a46a789434400e5d432b1ac80
https://github.com/onecommons/polyform/blob/98cc56f7e8283e9a46a789434400e5d432b1ac80/packages/polyform-config/index.js#L44-L53
50,049
c1rabbit/mers-min
mers.js
generate
function generate (orgID, loanNumber) { //strip non-numeric or letters loanNumber = loanNumber.replace(/\D/g,""); orgID = orgID.replace(/\D/g,""); //string letters var loanNum = loanNumber.replace(/[a-z]/gi,""); orgID = orgID.replace(/[a-z]/gi,""); if (orgID.toString().length != 7 ){ throw new Error("org ID is not 7 digits") //return null; } else if (loanNum.toString().length > 10){ throw new Error("[error]: loan number is longer than 10 digits"); //return null; } else if (loanNum.toString().length < 10){ while (loanNum.toString().length < 10){ loanNum = "0" + loanNum; } //console.log("orgID: " + orgID + "\tloanNum: " + loanNum); } var temp = orgID.toString() + loanNum.toString(); var sum = 0; for(var i = 0; i < temp.length; i++){ if(i % 2 == 0){ var x2 = parseInt(temp[i])*2; if(x2 > 9){ sum += 1 + x2 % 10; //console.log(1 + x2 % 10); }else{ sum += x2; //console.log(x2); } }else{ sum += parseInt(temp[i]); //console.log(temp[i]); } } //console.log("sum" + sum); var digit = Math.ceil(sum/10)*10 - sum //console.log(Math.ceil(sum/10)*10); var output = { "orgID": orgID, "loanNum": loanNumber, "digit": digit, "min": orgID + loanNum + digit } return output; }
javascript
function generate (orgID, loanNumber) { //strip non-numeric or letters loanNumber = loanNumber.replace(/\D/g,""); orgID = orgID.replace(/\D/g,""); //string letters var loanNum = loanNumber.replace(/[a-z]/gi,""); orgID = orgID.replace(/[a-z]/gi,""); if (orgID.toString().length != 7 ){ throw new Error("org ID is not 7 digits") //return null; } else if (loanNum.toString().length > 10){ throw new Error("[error]: loan number is longer than 10 digits"); //return null; } else if (loanNum.toString().length < 10){ while (loanNum.toString().length < 10){ loanNum = "0" + loanNum; } //console.log("orgID: " + orgID + "\tloanNum: " + loanNum); } var temp = orgID.toString() + loanNum.toString(); var sum = 0; for(var i = 0; i < temp.length; i++){ if(i % 2 == 0){ var x2 = parseInt(temp[i])*2; if(x2 > 9){ sum += 1 + x2 % 10; //console.log(1 + x2 % 10); }else{ sum += x2; //console.log(x2); } }else{ sum += parseInt(temp[i]); //console.log(temp[i]); } } //console.log("sum" + sum); var digit = Math.ceil(sum/10)*10 - sum //console.log(Math.ceil(sum/10)*10); var output = { "orgID": orgID, "loanNum": loanNumber, "digit": digit, "min": orgID + loanNum + digit } return output; }
[ "function", "generate", "(", "orgID", ",", "loanNumber", ")", "{", "//strip non-numeric or letters", "loanNumber", "=", "loanNumber", ".", "replace", "(", "/", "\\D", "/", "g", ",", "\"\"", ")", ";", "orgID", "=", "orgID", ".", "replace", "(", "/", "\\D", "/", "g", ",", "\"\"", ")", ";", "//string letters", "var", "loanNum", "=", "loanNumber", ".", "replace", "(", "/", "[a-z]", "/", "gi", ",", "\"\"", ")", ";", "orgID", "=", "orgID", ".", "replace", "(", "/", "[a-z]", "/", "gi", ",", "\"\"", ")", ";", "if", "(", "orgID", ".", "toString", "(", ")", ".", "length", "!=", "7", ")", "{", "throw", "new", "Error", "(", "\"org ID is not 7 digits\"", ")", "//return null;", "}", "else", "if", "(", "loanNum", ".", "toString", "(", ")", ".", "length", ">", "10", ")", "{", "throw", "new", "Error", "(", "\"[error]: loan number is longer than 10 digits\"", ")", ";", "//return null;", "}", "else", "if", "(", "loanNum", ".", "toString", "(", ")", ".", "length", "<", "10", ")", "{", "while", "(", "loanNum", ".", "toString", "(", ")", ".", "length", "<", "10", ")", "{", "loanNum", "=", "\"0\"", "+", "loanNum", ";", "}", "//console.log(\"orgID: \" + orgID + \"\\tloanNum: \" + loanNum);", "}", "var", "temp", "=", "orgID", ".", "toString", "(", ")", "+", "loanNum", ".", "toString", "(", ")", ";", "var", "sum", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "temp", ".", "length", ";", "i", "++", ")", "{", "if", "(", "i", "%", "2", "==", "0", ")", "{", "var", "x2", "=", "parseInt", "(", "temp", "[", "i", "]", ")", "*", "2", ";", "if", "(", "x2", ">", "9", ")", "{", "sum", "+=", "1", "+", "x2", "%", "10", ";", "//console.log(1 + x2 % 10);", "}", "else", "{", "sum", "+=", "x2", ";", "//console.log(x2);", "}", "}", "else", "{", "sum", "+=", "parseInt", "(", "temp", "[", "i", "]", ")", ";", "//console.log(temp[i]);", "}", "}", "//console.log(\"sum\" + sum);", "var", "digit", "=", "Math", ".", "ceil", "(", "sum", "/", "10", ")", "*", "10", "-", "sum", "//console.log(Math.ceil(sum/10)*10);", "var", "output", "=", "{", "\"orgID\"", ":", "orgID", ",", "\"loanNum\"", ":", "loanNumber", ",", "\"digit\"", ":", "digit", ",", "\"min\"", ":", "orgID", "+", "loanNum", "+", "digit", "}", "return", "output", ";", "}" ]
mod 10 weight 2
[ "mod", "10", "weight", "2" ]
426371ccb80ed1e710244166396d21bb3cd0e716
https://github.com/c1rabbit/mers-min/blob/426371ccb80ed1e710244166396d21bb3cd0e716/mers.js#L2-L51
50,050
BeepBoopHQ/botkit-storage-beepboop
src/storage.js
bbTeamToBotkitTeam
function bbTeamToBotkitTeam (team) { return { id: team.slack_team_id, createdBy: team.slack_user_id, url: `https://${team.slack_team_domain}.slack.com/`, name: team.slack_team_name, bot: { name: team.slack_bot_user_name, token: team.slack_bot_access_token, user_id: team.slack_bot_user_id, createdBy: team.slack_user_id, app_token: team.slack_access_token } } }
javascript
function bbTeamToBotkitTeam (team) { return { id: team.slack_team_id, createdBy: team.slack_user_id, url: `https://${team.slack_team_domain}.slack.com/`, name: team.slack_team_name, bot: { name: team.slack_bot_user_name, token: team.slack_bot_access_token, user_id: team.slack_bot_user_id, createdBy: team.slack_user_id, app_token: team.slack_access_token } } }
[ "function", "bbTeamToBotkitTeam", "(", "team", ")", "{", "return", "{", "id", ":", "team", ".", "slack_team_id", ",", "createdBy", ":", "team", ".", "slack_user_id", ",", "url", ":", "`", "${", "team", ".", "slack_team_domain", "}", "`", ",", "name", ":", "team", ".", "slack_team_name", ",", "bot", ":", "{", "name", ":", "team", ".", "slack_bot_user_name", ",", "token", ":", "team", ".", "slack_bot_access_token", ",", "user_id", ":", "team", ".", "slack_bot_user_id", ",", "createdBy", ":", "team", ".", "slack_user_id", ",", "app_token", ":", "team", ".", "slack_access_token", "}", "}", "}" ]
transform beep boop team into what botkit expects
[ "transform", "beep", "boop", "team", "into", "what", "botkit", "expects" ]
4bb2bfda995feb71a8ad77df213f11c6cbb7650d
https://github.com/BeepBoopHQ/botkit-storage-beepboop/blob/4bb2bfda995feb71a8ad77df213f11c6cbb7650d/src/storage.js#L137-L151
50,051
nrn/gen-pasta
gen-pasta.js
genPasta
function genPasta (opts) { // GENERAL Functions // function slice (ar, start, end) { return Array.prototype.slice.call(ar, start, end) } function log () { if (console && console.log) console.log(slice(arguments)) } function combine (returned, added) { Object.keys(added).forEach(function (key) { returned[key] = added[key] }) return returned } function last (item) { var tmp = list(item) if (tmp) return tmp[tmp.length - 1] return item } function first (item) { var tmp = list(item) if (tmp) return tmp[0] return item } function list (item) { if (typeof item === 'number') { return item.toString().split('').map(function (a) { return +a }) } else if (typeof item === 'string') return item.split('') else if (Array.isArray(item)) return item else if (typeof item === 'object') return Object.keys(item) } function flatten (arr) { if (Array.isArray(arr)) return arr.map(flatten).join('') return '' + arr } return { log: log , l: log , last:last , first: first , list: list , flatten: flatten , slice: slice , combine: combine // Depricated names , arrify: slice } }
javascript
function genPasta (opts) { // GENERAL Functions // function slice (ar, start, end) { return Array.prototype.slice.call(ar, start, end) } function log () { if (console && console.log) console.log(slice(arguments)) } function combine (returned, added) { Object.keys(added).forEach(function (key) { returned[key] = added[key] }) return returned } function last (item) { var tmp = list(item) if (tmp) return tmp[tmp.length - 1] return item } function first (item) { var tmp = list(item) if (tmp) return tmp[0] return item } function list (item) { if (typeof item === 'number') { return item.toString().split('').map(function (a) { return +a }) } else if (typeof item === 'string') return item.split('') else if (Array.isArray(item)) return item else if (typeof item === 'object') return Object.keys(item) } function flatten (arr) { if (Array.isArray(arr)) return arr.map(flatten).join('') return '' + arr } return { log: log , l: log , last:last , first: first , list: list , flatten: flatten , slice: slice , combine: combine // Depricated names , arrify: slice } }
[ "function", "genPasta", "(", "opts", ")", "{", "// GENERAL Functions", "//", "function", "slice", "(", "ar", ",", "start", ",", "end", ")", "{", "return", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "ar", ",", "start", ",", "end", ")", "}", "function", "log", "(", ")", "{", "if", "(", "console", "&&", "console", ".", "log", ")", "console", ".", "log", "(", "slice", "(", "arguments", ")", ")", "}", "function", "combine", "(", "returned", ",", "added", ")", "{", "Object", ".", "keys", "(", "added", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "returned", "[", "key", "]", "=", "added", "[", "key", "]", "}", ")", "return", "returned", "}", "function", "last", "(", "item", ")", "{", "var", "tmp", "=", "list", "(", "item", ")", "if", "(", "tmp", ")", "return", "tmp", "[", "tmp", ".", "length", "-", "1", "]", "return", "item", "}", "function", "first", "(", "item", ")", "{", "var", "tmp", "=", "list", "(", "item", ")", "if", "(", "tmp", ")", "return", "tmp", "[", "0", "]", "return", "item", "}", "function", "list", "(", "item", ")", "{", "if", "(", "typeof", "item", "===", "'number'", ")", "{", "return", "item", ".", "toString", "(", ")", ".", "split", "(", "''", ")", ".", "map", "(", "function", "(", "a", ")", "{", "return", "+", "a", "}", ")", "}", "else", "if", "(", "typeof", "item", "===", "'string'", ")", "return", "item", ".", "split", "(", "''", ")", "else", "if", "(", "Array", ".", "isArray", "(", "item", ")", ")", "return", "item", "else", "if", "(", "typeof", "item", "===", "'object'", ")", "return", "Object", ".", "keys", "(", "item", ")", "}", "function", "flatten", "(", "arr", ")", "{", "if", "(", "Array", ".", "isArray", "(", "arr", ")", ")", "return", "arr", ".", "map", "(", "flatten", ")", ".", "join", "(", "''", ")", "return", "''", "+", "arr", "}", "return", "{", "log", ":", "log", ",", "l", ":", "log", ",", "last", ":", "last", ",", "first", ":", "first", ",", "list", ":", "list", ",", "flatten", ":", "flatten", ",", "slice", ":", "slice", ",", "combine", ":", "combine", "// Depricated names", ",", "arrify", ":", "slice", "}", "}" ]
gen-pasta.js
[ "gen", "-", "pasta", ".", "js" ]
7e583cd000a8eab9b15c96440d24240d613a8801
https://github.com/nrn/gen-pasta/blob/7e583cd000a8eab9b15c96440d24240d613a8801/gen-pasta.js#L3-L59
50,052
dalekjs/dalek-driver-sauce
lib/commands/url.js
function (url, hash, uuid) { this.lastCalledUrl = url; this.actionQueue.push(this.webdriverClient.url.bind(this.webdriverClient, url)); this.actionQueue.push(this._openCb.bind(this, url, hash, uuid)); return this; }
javascript
function (url, hash, uuid) { this.lastCalledUrl = url; this.actionQueue.push(this.webdriverClient.url.bind(this.webdriverClient, url)); this.actionQueue.push(this._openCb.bind(this, url, hash, uuid)); return this; }
[ "function", "(", "url", ",", "hash", ",", "uuid", ")", "{", "this", ".", "lastCalledUrl", "=", "url", ";", "this", ".", "actionQueue", ".", "push", "(", "this", ".", "webdriverClient", ".", "url", ".", "bind", "(", "this", ".", "webdriverClient", ",", "url", ")", ")", ";", "this", ".", "actionQueue", ".", "push", "(", "this", ".", "_openCb", ".", "bind", "(", "this", ",", "url", ",", "hash", ",", "uuid", ")", ")", ";", "return", "this", ";", "}" ]
Navigate to a new URL @method open @param {string} url Url to navigate to @param {string} hash Unique hash of that fn call @param {string} uuid Unique hash of that fn call @chainable
[ "Navigate", "to", "a", "new", "URL" ]
4b3ef87a0c35a91db8456d074b0d47a3e0df58f7
https://github.com/dalekjs/dalek-driver-sauce/blob/4b3ef87a0c35a91db8456d074b0d47a3e0df58f7/lib/commands/url.js#L50-L55
50,053
dalekjs/dalek-driver-sauce
lib/commands/url.js
function (expected, hash) { this.actionQueue.push(this.webdriverClient.getUrl.bind(this.webdriverClient)); this.actionQueue.push(this._urlCb.bind(this, expected, hash)); return this; }
javascript
function (expected, hash) { this.actionQueue.push(this.webdriverClient.getUrl.bind(this.webdriverClient)); this.actionQueue.push(this._urlCb.bind(this, expected, hash)); return this; }
[ "function", "(", "expected", ",", "hash", ")", "{", "this", ".", "actionQueue", ".", "push", "(", "this", ".", "webdriverClient", ".", "getUrl", ".", "bind", "(", "this", ".", "webdriverClient", ")", ")", ";", "this", ".", "actionQueue", ".", "push", "(", "this", ".", "_urlCb", ".", "bind", "(", "this", ",", "expected", ",", "hash", ")", ")", ";", "return", "this", ";", "}" ]
Fetches the current url @method url @param {string} expected Expected url @param {string} hash Unique hash of that fn call @chainable
[ "Fetches", "the", "current", "url" ]
4b3ef87a0c35a91db8456d074b0d47a3e0df58f7
https://github.com/dalekjs/dalek-driver-sauce/blob/4b3ef87a0c35a91db8456d074b0d47a3e0df58f7/lib/commands/url.js#L84-L88
50,054
just-paja/pwf.js
lib/pwf.js
function(mods) { for (var i = 0, len = mods.length; i < len; i++) { if (!internal.is_module_ready(mods[i])) { return false; } } return true; }
javascript
function(mods) { for (var i = 0, len = mods.length; i < len; i++) { if (!internal.is_module_ready(mods[i])) { return false; } } return true; }
[ "function", "(", "mods", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "mods", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "!", "internal", ".", "is_module_ready", "(", "mods", "[", "i", "]", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Dear sir, are all modules of this list ready? @param Object modules List (array) of module names @return bool
[ "Dear", "sir", "are", "all", "modules", "of", "this", "list", "ready?" ]
f2ae9607f378b3ba4553d48f4a1bc179029b16ea
https://github.com/just-paja/pwf.js/blob/f2ae9607f378b3ba4553d48f4a1bc179029b16ea/lib/pwf.js#L44-L52
50,055
just-paja/pwf.js
lib/pwf.js
function(mods) { for (var i = 0, len = mods.length; i < len; i++) { if (self.get_module_status(mods[i]) !== internal.states.initialized) { return false; } } return true; }
javascript
function(mods) { for (var i = 0, len = mods.length; i < len; i++) { if (self.get_module_status(mods[i]) !== internal.states.initialized) { return false; } } return true; }
[ "function", "(", "mods", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "mods", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "self", ".", "get_module_status", "(", "mods", "[", "i", "]", ")", "!==", "internal", ".", "states", ".", "initialized", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Dear sir, are all members of this noble name list initialized? @param list modules module name @return bool
[ "Dear", "sir", "are", "all", "members", "of", "this", "noble", "name", "list", "initialized?" ]
f2ae9607f378b3ba4553d48f4a1bc179029b16ea
https://github.com/just-paja/pwf.js/blob/f2ae9607f378b3ba4553d48f4a1bc179029b16ea/lib/pwf.js#L61-L69
50,056
just-paja/pwf.js
lib/pwf.js
function() { if (typeof console !== 'undefined' && ((pwf.has('module', 'config') && pwf.config.get('debug.frontend')) || !pwf.has('module', 'config'))) { var args = pwf.clone_array(arguments); if (args.length > 1) { console.log(args); } else { console.log(args[0]); } } }
javascript
function() { if (typeof console !== 'undefined' && ((pwf.has('module', 'config') && pwf.config.get('debug.frontend')) || !pwf.has('module', 'config'))) { var args = pwf.clone_array(arguments); if (args.length > 1) { console.log(args); } else { console.log(args[0]); } } }
[ "function", "(", ")", "{", "if", "(", "typeof", "console", "!==", "'undefined'", "&&", "(", "(", "pwf", ".", "has", "(", "'module'", ",", "'config'", ")", "&&", "pwf", ".", "config", ".", "get", "(", "'debug.frontend'", ")", ")", "||", "!", "pwf", ".", "has", "(", "'module'", ",", "'config'", ")", ")", ")", "{", "var", "args", "=", "pwf", ".", "clone_array", "(", "arguments", ")", ";", "if", "(", "args", ".", "length", ">", "1", ")", "{", "console", ".", "log", "(", "args", ")", ";", "}", "else", "{", "console", ".", "log", "(", "args", "[", "0", "]", ")", ";", "}", "}", "}" ]
Safe dump data into console. Takes any number of any arguments @param mixed any @return void
[ "Safe", "dump", "data", "into", "console", ".", "Takes", "any", "number", "of", "any", "arguments" ]
f2ae9607f378b3ba4553d48f4a1bc179029b16ea
https://github.com/just-paja/pwf.js/blob/f2ae9607f378b3ba4553d48f4a1bc179029b16ea/lib/pwf.js#L1205-L1216
50,057
just-paja/pwf.js
lib/pwf.js
function(items) { var register = []; /// Export as module if running under nodejs if (typeof global === 'object') { register.push(global); } if (typeof window === 'object') { register.push(window); } // Browse all resolved global objects and bind pwf items for (var i = 0; i < register.length; i++) { var obj = register[i]; // Bind all requested items as global for (var key in items) { if (!items.hasOwnProperty(key)) { continue; } obj[key] = items[key]; } // Check for all callbacks bound to this global object and call them if (typeof obj.on_pwf !== 'undefined') { var calls = obj.on_pwf; // Expecting list/array if (!(calls instanceof Array)) { calls = [calls]; } for (var j = 0; j < calls.length; j++) { if (typeof calls[j] !== 'function') { throw new Error('on_pwf:not-a-method:' + j); } calls[j].apply(obj.pwf); } } } }
javascript
function(items) { var register = []; /// Export as module if running under nodejs if (typeof global === 'object') { register.push(global); } if (typeof window === 'object') { register.push(window); } // Browse all resolved global objects and bind pwf items for (var i = 0; i < register.length; i++) { var obj = register[i]; // Bind all requested items as global for (var key in items) { if (!items.hasOwnProperty(key)) { continue; } obj[key] = items[key]; } // Check for all callbacks bound to this global object and call them if (typeof obj.on_pwf !== 'undefined') { var calls = obj.on_pwf; // Expecting list/array if (!(calls instanceof Array)) { calls = [calls]; } for (var j = 0; j < calls.length; j++) { if (typeof calls[j] !== 'function') { throw new Error('on_pwf:not-a-method:' + j); } calls[j].apply(obj.pwf); } } } }
[ "function", "(", "items", ")", "{", "var", "register", "=", "[", "]", ";", "/// Export as module if running under nodejs", "if", "(", "typeof", "global", "===", "'object'", ")", "{", "register", ".", "push", "(", "global", ")", ";", "}", "if", "(", "typeof", "window", "===", "'object'", ")", "{", "register", ".", "push", "(", "window", ")", ";", "}", "// Browse all resolved global objects and bind pwf items", "for", "(", "var", "i", "=", "0", ";", "i", "<", "register", ".", "length", ";", "i", "++", ")", "{", "var", "obj", "=", "register", "[", "i", "]", ";", "// Bind all requested items as global", "for", "(", "var", "key", "in", "items", ")", "{", "if", "(", "!", "items", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "continue", ";", "}", "obj", "[", "key", "]", "=", "items", "[", "key", "]", ";", "}", "// Check for all callbacks bound to this global object and call them", "if", "(", "typeof", "obj", ".", "on_pwf", "!==", "'undefined'", ")", "{", "var", "calls", "=", "obj", ".", "on_pwf", ";", "// Expecting list/array", "if", "(", "!", "(", "calls", "instanceof", "Array", ")", ")", "{", "calls", "=", "[", "calls", "]", ";", "}", "for", "(", "var", "j", "=", "0", ";", "j", "<", "calls", ".", "length", ";", "j", "++", ")", "{", "if", "(", "typeof", "calls", "[", "j", "]", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'on_pwf:not-a-method:'", "+", "j", ")", ";", "}", "calls", "[", "j", "]", ".", "apply", "(", "obj", ".", "pwf", ")", ";", "}", "}", "}", "}" ]
Register items into global objects @param object items Key-value objects to register @return void
[ "Register", "items", "into", "global", "objects" ]
f2ae9607f378b3ba4553d48f4a1bc179029b16ea
https://github.com/just-paja/pwf.js/blob/f2ae9607f378b3ba4553d48f4a1bc179029b16ea/lib/pwf.js#L1223-L1267
50,058
dvalchanov/luckio
src/luckio.js
luckio
function luckio(chance) { var min = 1; var max = math.maxRange(chance); var luckyNumber = math.randomNumber(min, max); return function() { if (math.randomNumber(min, max) === luckyNumber) return true; return false; } }
javascript
function luckio(chance) { var min = 1; var max = math.maxRange(chance); var luckyNumber = math.randomNumber(min, max); return function() { if (math.randomNumber(min, max) === luckyNumber) return true; return false; } }
[ "function", "luckio", "(", "chance", ")", "{", "var", "min", "=", "1", ";", "var", "max", "=", "math", ".", "maxRange", "(", "chance", ")", ";", "var", "luckyNumber", "=", "math", ".", "randomNumber", "(", "min", ",", "max", ")", ";", "return", "function", "(", ")", "{", "if", "(", "math", ".", "randomNumber", "(", "min", ",", "max", ")", "===", "luckyNumber", ")", "return", "true", ";", "return", "false", ";", "}", "}" ]
Pick a lucky number and return a function that matches its picked lucky number to the initial one. If equal it will return `true`, if not `false`. @param {Number} chance Lucky chance to pick a number @returns {Function}
[ "Pick", "a", "lucky", "number", "and", "return", "a", "function", "that", "matches", "its", "picked", "lucky", "number", "to", "the", "initial", "one", ".", "If", "equal", "it", "will", "return", "true", "if", "not", "false", "." ]
5340b97880f848c2cebc997a1e9a2771572e1762
https://github.com/dvalchanov/luckio/blob/5340b97880f848c2cebc997a1e9a2771572e1762/src/luckio.js#L13-L22
50,059
gethuman/pancakes-recipe
utils/i18n.js
getScopeValue
function getScopeValue(scope, field) { if (!scope || !field) { return null; } var fieldParts = field.split('.'); var pntr = scope; _.each(fieldParts, function (fieldPart) { if (pntr) { pntr = pntr[fieldPart]; } }); return pntr; }
javascript
function getScopeValue(scope, field) { if (!scope || !field) { return null; } var fieldParts = field.split('.'); var pntr = scope; _.each(fieldParts, function (fieldPart) { if (pntr) { pntr = pntr[fieldPart]; } }); return pntr; }
[ "function", "getScopeValue", "(", "scope", ",", "field", ")", "{", "if", "(", "!", "scope", "||", "!", "field", ")", "{", "return", "null", ";", "}", "var", "fieldParts", "=", "field", ".", "split", "(", "'.'", ")", ";", "var", "pntr", "=", "scope", ";", "_", ".", "each", "(", "fieldParts", ",", "function", "(", "fieldPart", ")", "{", "if", "(", "pntr", ")", "{", "pntr", "=", "pntr", "[", "fieldPart", "]", ";", "}", "}", ")", ";", "return", "pntr", ";", "}" ]
Get a value from scope for a given field @param scope @param field @returns {{}}
[ "Get", "a", "value", "from", "scope", "for", "a", "given", "field" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/utils/i18n.js#L18-L31
50,060
gethuman/pancakes-recipe
utils/i18n.js
interpolate
function interpolate(val, scope) { // if no scope or value with {{ then no interpolation and can just return translated if (!scope || !val || !val.match) { return val; } // first, we need to get all values with a {{ }} in the string var i18nVars = val.match(i18nVarExpr); // loop through {{ }} values _.each(i18nVars, function (i18nVar) { var field = i18nVar.substring(2, i18nVar.length - 2).trim(); var scopeVal = getScopeValue(scope, field); val = val.replace(i18nVar, scopeVal); }); return val; }
javascript
function interpolate(val, scope) { // if no scope or value with {{ then no interpolation and can just return translated if (!scope || !val || !val.match) { return val; } // first, we need to get all values with a {{ }} in the string var i18nVars = val.match(i18nVarExpr); // loop through {{ }} values _.each(i18nVars, function (i18nVar) { var field = i18nVar.substring(2, i18nVar.length - 2).trim(); var scopeVal = getScopeValue(scope, field); val = val.replace(i18nVar, scopeVal); }); return val; }
[ "function", "interpolate", "(", "val", ",", "scope", ")", "{", "// if no scope or value with {{ then no interpolation and can just return translated", "if", "(", "!", "scope", "||", "!", "val", "||", "!", "val", ".", "match", ")", "{", "return", "val", ";", "}", "// first, we need to get all values with a {{ }} in the string", "var", "i18nVars", "=", "val", ".", "match", "(", "i18nVarExpr", ")", ";", "// loop through {{ }} values", "_", ".", "each", "(", "i18nVars", ",", "function", "(", "i18nVar", ")", "{", "var", "field", "=", "i18nVar", ".", "substring", "(", "2", ",", "i18nVar", ".", "length", "-", "2", ")", ".", "trim", "(", ")", ";", "var", "scopeVal", "=", "getScopeValue", "(", "scope", ",", "field", ")", ";", "val", "=", "val", ".", "replace", "(", "i18nVar", ",", "scopeVal", ")", ";", "}", ")", ";", "return", "val", ";", "}" ]
Attempt to interpolate the string @param val @param scope @returns {*}
[ "Attempt", "to", "interpolate", "the", "string" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/utils/i18n.js#L39-L55
50,061
gethuman/pancakes-recipe
utils/i18n.js
translate
function translate(val, scope, status) { var app = (scope && scope.appName) || context.get('app') || ''; var lang = (scope && scope.lang) || context.get('lang') || 'en'; var translated; // if just one character or is a number, don't do translation if (!val || val.length < 2 || !isNaN(val)) { return val; } // translations could be either nested (on the server) or at the root (on the client) translated = (translations[app] && translations[app][lang] && translations[app][lang][val]) || (_.isString(translations[val]) && translations[val]); // if no transation AND caller passed in status object AND lang is not default (i.e. not english), // set the status object values which the caller can use to record some info // note: this is kind of hacky, but we want the caller (i.e. jng.directives.js) to handle // it because jng.directives has more info about the translation than we do at this level if (!translated && config.i18nDebug && status && lang !== config.lang.default) { status.app = app; status.lang = lang; status.missing = true; } // attempt to interpolate and return the resulting value (val if no translation found) return interpolate(translated || val, scope); }
javascript
function translate(val, scope, status) { var app = (scope && scope.appName) || context.get('app') || ''; var lang = (scope && scope.lang) || context.get('lang') || 'en'; var translated; // if just one character or is a number, don't do translation if (!val || val.length < 2 || !isNaN(val)) { return val; } // translations could be either nested (on the server) or at the root (on the client) translated = (translations[app] && translations[app][lang] && translations[app][lang][val]) || (_.isString(translations[val]) && translations[val]); // if no transation AND caller passed in status object AND lang is not default (i.e. not english), // set the status object values which the caller can use to record some info // note: this is kind of hacky, but we want the caller (i.e. jng.directives.js) to handle // it because jng.directives has more info about the translation than we do at this level if (!translated && config.i18nDebug && status && lang !== config.lang.default) { status.app = app; status.lang = lang; status.missing = true; } // attempt to interpolate and return the resulting value (val if no translation found) return interpolate(translated || val, scope); }
[ "function", "translate", "(", "val", ",", "scope", ",", "status", ")", "{", "var", "app", "=", "(", "scope", "&&", "scope", ".", "appName", ")", "||", "context", ".", "get", "(", "'app'", ")", "||", "''", ";", "var", "lang", "=", "(", "scope", "&&", "scope", ".", "lang", ")", "||", "context", ".", "get", "(", "'lang'", ")", "||", "'en'", ";", "var", "translated", ";", "// if just one character or is a number, don't do translation", "if", "(", "!", "val", "||", "val", ".", "length", "<", "2", "||", "!", "isNaN", "(", "val", ")", ")", "{", "return", "val", ";", "}", "// translations could be either nested (on the server) or at the root (on the client)", "translated", "=", "(", "translations", "[", "app", "]", "&&", "translations", "[", "app", "]", "[", "lang", "]", "&&", "translations", "[", "app", "]", "[", "lang", "]", "[", "val", "]", ")", "||", "(", "_", ".", "isString", "(", "translations", "[", "val", "]", ")", "&&", "translations", "[", "val", "]", ")", ";", "// if no transation AND caller passed in status object AND lang is not default (i.e. not english),", "// set the status object values which the caller can use to record some info", "// note: this is kind of hacky, but we want the caller (i.e. jng.directives.js) to handle", "// it because jng.directives has more info about the translation than we do at this level", "if", "(", "!", "translated", "&&", "config", ".", "i18nDebug", "&&", "status", "&&", "lang", "!==", "config", ".", "lang", ".", "default", ")", "{", "status", ".", "app", "=", "app", ";", "status", ".", "lang", "=", "lang", ";", "status", ".", "missing", "=", "true", ";", "}", "// attempt to interpolate and return the resulting value (val if no translation found)", "return", "interpolate", "(", "translated", "||", "val", ",", "scope", ")", ";", "}" ]
Translate given text into the target language. If not in the target language, look in english, and then finally just return back the value itself @param val @param scope @param status @returns {string}
[ "Translate", "given", "text", "into", "the", "target", "language", ".", "If", "not", "in", "the", "target", "language", "look", "in", "english", "and", "then", "finally", "just", "return", "back", "the", "value", "itself" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/utils/i18n.js#L66-L92
50,062
skerit/hawkejs
lib/client/dom_spotting.js
initialCheck
function initialCheck(attr_name) { var elements = document.querySelectorAll('[' + attr_name + ']'), element, value, i, l; for (i = 0; i < elements.length; i++) { element = elements[i]; value = element.getAttribute(attr_name); if (initial_seen.get(element)) { continue; } if (attributes[attr_name]) { initial_seen.set(element, true); for (l = 0; l < attributes[attr_name].length; l++) { attributes[attr_name][l](element, value, null, true); } } } }
javascript
function initialCheck(attr_name) { var elements = document.querySelectorAll('[' + attr_name + ']'), element, value, i, l; for (i = 0; i < elements.length; i++) { element = elements[i]; value = element.getAttribute(attr_name); if (initial_seen.get(element)) { continue; } if (attributes[attr_name]) { initial_seen.set(element, true); for (l = 0; l < attributes[attr_name].length; l++) { attributes[attr_name][l](element, value, null, true); } } } }
[ "function", "initialCheck", "(", "attr_name", ")", "{", "var", "elements", "=", "document", ".", "querySelectorAll", "(", "'['", "+", "attr_name", "+", "']'", ")", ",", "element", ",", "value", ",", "i", ",", "l", ";", "for", "(", "i", "=", "0", ";", "i", "<", "elements", ".", "length", ";", "i", "++", ")", "{", "element", "=", "elements", "[", "i", "]", ";", "value", "=", "element", ".", "getAttribute", "(", "attr_name", ")", ";", "if", "(", "initial_seen", ".", "get", "(", "element", ")", ")", "{", "continue", ";", "}", "if", "(", "attributes", "[", "attr_name", "]", ")", "{", "initial_seen", ".", "set", "(", "element", ",", "true", ")", ";", "for", "(", "l", "=", "0", ";", "l", "<", "attributes", "[", "attr_name", "]", ".", "length", ";", "l", "++", ")", "{", "attributes", "[", "attr_name", "]", "[", "l", "]", "(", "element", ",", "value", ",", "null", ",", "true", ")", ";", "}", "}", "}", "}" ]
Do an initial check for the given attribute name @author Jelle De Loecker <[email protected]> @since 1.0.0 @version 1.1.2 @param {String} attr_name
[ "Do", "an", "initial", "check", "for", "the", "given", "attribute", "name" ]
15ed7205183ac2c425362deb8c0796c0d16b898a
https://github.com/skerit/hawkejs/blob/15ed7205183ac2c425362deb8c0796c0d16b898a/lib/client/dom_spotting.js#L74-L97
50,063
skerit/hawkejs
lib/client/dom_spotting.js
checkChildren
function checkChildren(mutation, node, seen) { var attr, k, l; if (seen == null) { seen = initial_seen; } // Ignore text nodes if (node.nodeType === 3 || node.nodeType === 8) { return; } // Only check attributes for nodes that haven't been checked before if (!seen.get(node)) { // Indicate this node has been checked seen.set(node, true); // Go over every attribute if (node.attributes) { for (k = 0; k < node.attributes.length; k++) { attr = node.attributes[k]; if (attributes[attr.name]) { for (l = 0; l < attributes[attr.name].length; l++) { attributes[attr.name][l](node, attr.value, null, true); } } } } } // Now check the children for (k = 0; k < node.childNodes.length; k++) { checkChildren(mutation, node.childNodes[k], seen); } }
javascript
function checkChildren(mutation, node, seen) { var attr, k, l; if (seen == null) { seen = initial_seen; } // Ignore text nodes if (node.nodeType === 3 || node.nodeType === 8) { return; } // Only check attributes for nodes that haven't been checked before if (!seen.get(node)) { // Indicate this node has been checked seen.set(node, true); // Go over every attribute if (node.attributes) { for (k = 0; k < node.attributes.length; k++) { attr = node.attributes[k]; if (attributes[attr.name]) { for (l = 0; l < attributes[attr.name].length; l++) { attributes[attr.name][l](node, attr.value, null, true); } } } } } // Now check the children for (k = 0; k < node.childNodes.length; k++) { checkChildren(mutation, node.childNodes[k], seen); } }
[ "function", "checkChildren", "(", "mutation", ",", "node", ",", "seen", ")", "{", "var", "attr", ",", "k", ",", "l", ";", "if", "(", "seen", "==", "null", ")", "{", "seen", "=", "initial_seen", ";", "}", "// Ignore text nodes", "if", "(", "node", ".", "nodeType", "===", "3", "||", "node", ".", "nodeType", "===", "8", ")", "{", "return", ";", "}", "// Only check attributes for nodes that haven't been checked before", "if", "(", "!", "seen", ".", "get", "(", "node", ")", ")", "{", "// Indicate this node has been checked", "seen", ".", "set", "(", "node", ",", "true", ")", ";", "// Go over every attribute", "if", "(", "node", ".", "attributes", ")", "{", "for", "(", "k", "=", "0", ";", "k", "<", "node", ".", "attributes", ".", "length", ";", "k", "++", ")", "{", "attr", "=", "node", ".", "attributes", "[", "k", "]", ";", "if", "(", "attributes", "[", "attr", ".", "name", "]", ")", "{", "for", "(", "l", "=", "0", ";", "l", "<", "attributes", "[", "attr", ".", "name", "]", ".", "length", ";", "l", "++", ")", "{", "attributes", "[", "attr", ".", "name", "]", "[", "l", "]", "(", "node", ",", "attr", ".", "value", ",", "null", ",", "true", ")", ";", "}", "}", "}", "}", "}", "// Now check the children", "for", "(", "k", "=", "0", ";", "k", "<", "node", ".", "childNodes", ".", "length", ";", "k", "++", ")", "{", "checkChildren", "(", "mutation", ",", "node", ".", "childNodes", "[", "k", "]", ",", "seen", ")", ";", "}", "}" ]
Check this added node and all its children @author Jelle De Loecker <[email protected]> @since 1.0.0 @version 1.0.0 @param {Object} mutation @param {Node} node @param {WeakMap} seen
[ "Check", "this", "added", "node", "and", "all", "its", "children" ]
15ed7205183ac2c425362deb8c0796c0d16b898a
https://github.com/skerit/hawkejs/blob/15ed7205183ac2c425362deb8c0796c0d16b898a/lib/client/dom_spotting.js#L110-L149
50,064
valiton/node-simple-pool
lib/simplepool.js
SimplePool
function SimplePool() { var args; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; this.current = 0; this.pool = args.length === 1 && Array.isArray(args[0]) ? args[0] : args; }
javascript
function SimplePool() { var args; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; this.current = 0; this.pool = args.length === 1 && Array.isArray(args[0]) ? args[0] : args; }
[ "function", "SimplePool", "(", ")", "{", "var", "args", ";", "args", "=", "1", "<=", "arguments", ".", "length", "?", "__slice", ".", "call", "(", "arguments", ",", "0", ")", ":", "[", "]", ";", "this", ".", "current", "=", "0", ";", "this", ".", "pool", "=", "args", ".", "length", "===", "1", "&&", "Array", ".", "isArray", "(", "args", "[", "0", "]", ")", "?", "args", "[", "0", "]", ":", "args", ";", "}" ]
create a new SimplePool instance @memberOf global @constructor @this {SimplePool}
[ "create", "a", "new", "SimplePool", "instance" ]
5b6220a7f3b9d000dc66483280509b85e4b70d5d
https://github.com/valiton/node-simple-pool/blob/5b6220a7f3b9d000dc66483280509b85e4b70d5d/lib/simplepool.js#L26-L31
50,065
vibe-project/vibe-protocol
lib/transport-http-server.js
createBaseTransport
function createBaseTransport(req, res) { // A transport object. var self = new events.EventEmitter(); // Because HTTP transport consists of multiple exchanges, an universally // unique identifier is required. self.id = uuid.v4(); // A flag to check the transport is opened. var opened = true; self.on("close", function() { opened = false; }); self.send = function(data) { // Allows to send data only it is opened. If not, fires an error. if (opened) { self.write(data); } else { self.emit("error", new Error("notopened")); } return this; }; return self; }
javascript
function createBaseTransport(req, res) { // A transport object. var self = new events.EventEmitter(); // Because HTTP transport consists of multiple exchanges, an universally // unique identifier is required. self.id = uuid.v4(); // A flag to check the transport is opened. var opened = true; self.on("close", function() { opened = false; }); self.send = function(data) { // Allows to send data only it is opened. If not, fires an error. if (opened) { self.write(data); } else { self.emit("error", new Error("notopened")); } return this; }; return self; }
[ "function", "createBaseTransport", "(", "req", ",", "res", ")", "{", "// A transport object.", "var", "self", "=", "new", "events", ".", "EventEmitter", "(", ")", ";", "// Because HTTP transport consists of multiple exchanges, an universally", "// unique identifier is required.", "self", ".", "id", "=", "uuid", ".", "v4", "(", ")", ";", "// A flag to check the transport is opened.", "var", "opened", "=", "true", ";", "self", ".", "on", "(", "\"close\"", ",", "function", "(", ")", "{", "opened", "=", "false", ";", "}", ")", ";", "self", ".", "send", "=", "function", "(", "data", ")", "{", "// Allows to send data only it is opened. If not, fires an error.", "if", "(", "opened", ")", "{", "self", ".", "write", "(", "data", ")", ";", "}", "else", "{", "self", ".", "emit", "(", "\"error\"", ",", "new", "Error", "(", "\"notopened\"", ")", ")", ";", "}", "return", "this", ";", "}", ";", "return", "self", ";", "}" ]
A base transport.
[ "A", "base", "transport", "." ]
4a350acade3760ea13e75d7b9ce0815cf8b1d688
https://github.com/vibe-project/vibe-protocol/blob/4a350acade3760ea13e75d7b9ce0815cf8b1d688/lib/transport-http-server.js#L181-L202
50,066
vibe-project/vibe-protocol
lib/transport-http-server.js
createStreamTransport
function createStreamTransport(req, res) { // A transport object. var self = createBaseTransport(req, res); // Any error on request-response should propagate to transport. req.on("error", function(error) { self.emit("error", error); }); res.on("error", function(error) { self.emit("error", error); }); // When the underlying connection was terminated abnormally. res.on("close", function() { self.emit("close"); }); // When the complete response has been sent. res.on("finish", function() { self.emit("close"); }); // The response body should be formatted in the [event stream // format](http://www.w3.org/TR/eventsource/#parsing-an-event-stream). self.write = function(data) { // `data` should be either a `Buffer` or a string. if (typeof data === "string") { // A text message should be prefixed with `1`. data = "1" + data; } else { // A binary message should be encoded in Base64 and prefixed with // `2`. data = "2" + data.toString("base64"); } // According to the format, data should be broken up by `\r`, `\n`, or // `\r\n`. var payload = data.split(/\r\n|[\r\n]/).map(function(line) { // Each line should be prefixed with 'data: ' and postfixed with // `\n`. return "data: " + line + "\n"; }) // Prints `\n` as the last character of a message. .join("") + "\n"; // Writes it to response with `utf-8` encoding. res.write(payload, "utf-8"); }; // Ends the response. Accordingly, `res`'s `finish` event will be fired. self.close = function() { res.end(); return this; }; // The content-type headers should be `text/event-stream` for Server-Sent // Events and `text/plain` for others. Also the response should be encoded in `utf-8`. res.setHeader("content-type", "text/" + // If it's Server-Sent Events, `sse` param is `true`. (req.params.sse === "true" ? "event-stream" : "plain") + "; charset=utf-8"); // The padding is required, which makes the client-side transport on old // browsers be aware of change of the response. It should be greater // than 1KB, be composed of white space character and end with `\n`. var text2KB = Array(2048).join(" "); // Some host objects which are used to perform streaming transport can't or // don't allow to read response headers as well as write request headers. // That's why we uses the first message as a handshake output. The handshake // result should be formatted in URI. And transport id should be added as // `id` param. var uri = url.format({query: {id: self.id}}); // Likewise some host objects in old browsers, junk data is needed to make // themselves be aware of change of response. Prints the padding and the // first message following `text/event-stream` with `utf-8` encoding. res.write(text2KB + "\ndata: " + uri + "\n\n", "utf-8"); return self; }
javascript
function createStreamTransport(req, res) { // A transport object. var self = createBaseTransport(req, res); // Any error on request-response should propagate to transport. req.on("error", function(error) { self.emit("error", error); }); res.on("error", function(error) { self.emit("error", error); }); // When the underlying connection was terminated abnormally. res.on("close", function() { self.emit("close"); }); // When the complete response has been sent. res.on("finish", function() { self.emit("close"); }); // The response body should be formatted in the [event stream // format](http://www.w3.org/TR/eventsource/#parsing-an-event-stream). self.write = function(data) { // `data` should be either a `Buffer` or a string. if (typeof data === "string") { // A text message should be prefixed with `1`. data = "1" + data; } else { // A binary message should be encoded in Base64 and prefixed with // `2`. data = "2" + data.toString("base64"); } // According to the format, data should be broken up by `\r`, `\n`, or // `\r\n`. var payload = data.split(/\r\n|[\r\n]/).map(function(line) { // Each line should be prefixed with 'data: ' and postfixed with // `\n`. return "data: " + line + "\n"; }) // Prints `\n` as the last character of a message. .join("") + "\n"; // Writes it to response with `utf-8` encoding. res.write(payload, "utf-8"); }; // Ends the response. Accordingly, `res`'s `finish` event will be fired. self.close = function() { res.end(); return this; }; // The content-type headers should be `text/event-stream` for Server-Sent // Events and `text/plain` for others. Also the response should be encoded in `utf-8`. res.setHeader("content-type", "text/" + // If it's Server-Sent Events, `sse` param is `true`. (req.params.sse === "true" ? "event-stream" : "plain") + "; charset=utf-8"); // The padding is required, which makes the client-side transport on old // browsers be aware of change of the response. It should be greater // than 1KB, be composed of white space character and end with `\n`. var text2KB = Array(2048).join(" "); // Some host objects which are used to perform streaming transport can't or // don't allow to read response headers as well as write request headers. // That's why we uses the first message as a handshake output. The handshake // result should be formatted in URI. And transport id should be added as // `id` param. var uri = url.format({query: {id: self.id}}); // Likewise some host objects in old browsers, junk data is needed to make // themselves be aware of change of response. Prints the padding and the // first message following `text/event-stream` with `utf-8` encoding. res.write(text2KB + "\ndata: " + uri + "\n\n", "utf-8"); return self; }
[ "function", "createStreamTransport", "(", "req", ",", "res", ")", "{", "// A transport object.", "var", "self", "=", "createBaseTransport", "(", "req", ",", "res", ")", ";", "// Any error on request-response should propagate to transport.", "req", ".", "on", "(", "\"error\"", ",", "function", "(", "error", ")", "{", "self", ".", "emit", "(", "\"error\"", ",", "error", ")", ";", "}", ")", ";", "res", ".", "on", "(", "\"error\"", ",", "function", "(", "error", ")", "{", "self", ".", "emit", "(", "\"error\"", ",", "error", ")", ";", "}", ")", ";", "// When the underlying connection was terminated abnormally.", "res", ".", "on", "(", "\"close\"", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "\"close\"", ")", ";", "}", ")", ";", "// When the complete response has been sent.", "res", ".", "on", "(", "\"finish\"", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "\"close\"", ")", ";", "}", ")", ";", "// The response body should be formatted in the [event stream", "// format](http://www.w3.org/TR/eventsource/#parsing-an-event-stream).", "self", ".", "write", "=", "function", "(", "data", ")", "{", "// `data` should be either a `Buffer` or a string.", "if", "(", "typeof", "data", "===", "\"string\"", ")", "{", "// A text message should be prefixed with `1`.", "data", "=", "\"1\"", "+", "data", ";", "}", "else", "{", "// A binary message should be encoded in Base64 and prefixed with", "// `2`.", "data", "=", "\"2\"", "+", "data", ".", "toString", "(", "\"base64\"", ")", ";", "}", "// According to the format, data should be broken up by `\\r`, `\\n`, or", "// `\\r\\n`.", "var", "payload", "=", "data", ".", "split", "(", "/", "\\r\\n|[\\r\\n]", "/", ")", ".", "map", "(", "function", "(", "line", ")", "{", "// Each line should be prefixed with 'data: ' and postfixed with", "// `\\n`.", "return", "\"data: \"", "+", "line", "+", "\"\\n\"", ";", "}", ")", "// Prints `\\n` as the last character of a message.", ".", "join", "(", "\"\"", ")", "+", "\"\\n\"", ";", "// Writes it to response with `utf-8` encoding.", "res", ".", "write", "(", "payload", ",", "\"utf-8\"", ")", ";", "}", ";", "// Ends the response. Accordingly, `res`'s `finish` event will be fired.", "self", ".", "close", "=", "function", "(", ")", "{", "res", ".", "end", "(", ")", ";", "return", "this", ";", "}", ";", "// The content-type headers should be `text/event-stream` for Server-Sent", "// Events and `text/plain` for others. Also the response should be encoded in `utf-8`.", "res", ".", "setHeader", "(", "\"content-type\"", ",", "\"text/\"", "+", "// If it's Server-Sent Events, `sse` param is `true`.", "(", "req", ".", "params", ".", "sse", "===", "\"true\"", "?", "\"event-stream\"", ":", "\"plain\"", ")", "+", "\"; charset=utf-8\"", ")", ";", "// The padding is required, which makes the client-side transport on old", "// browsers be aware of change of the response. It should be greater", "// than 1KB, be composed of white space character and end with `\\n`.", "var", "text2KB", "=", "Array", "(", "2048", ")", ".", "join", "(", "\" \"", ")", ";", "// Some host objects which are used to perform streaming transport can't or", "// don't allow to read response headers as well as write request headers.", "// That's why we uses the first message as a handshake output. The handshake", "// result should be formatted in URI. And transport id should be added as", "// `id` param.", "var", "uri", "=", "url", ".", "format", "(", "{", "query", ":", "{", "id", ":", "self", ".", "id", "}", "}", ")", ";", "// Likewise some host objects in old browsers, junk data is needed to make", "// themselves be aware of change of response. Prints the padding and the", "// first message following `text/event-stream` with `utf-8` encoding.", "res", ".", "write", "(", "text2KB", "+", "\"\\ndata: \"", "+", "uri", "+", "\"\\n\\n\"", ",", "\"utf-8\"", ")", ";", "return", "self", ";", "}" ]
The client performs a HTTP persistent connection and watches changes in response and the server prints chunk as data to response.
[ "The", "client", "performs", "a", "HTTP", "persistent", "connection", "and", "watches", "changes", "in", "response", "and", "the", "server", "prints", "chunk", "as", "data", "to", "response", "." ]
4a350acade3760ea13e75d7b9ce0815cf8b1d688
https://github.com/vibe-project/vibe-protocol/blob/4a350acade3760ea13e75d7b9ce0815cf8b1d688/lib/transport-http-server.js#L206-L275
50,067
unshiftio/failure
index.js
toJSON
function toJSON() { var obj = { message: this.message, stack: this.stack }, key; for (key in this) { if ( has.call(this, key) && 'function' !== typeof this[key] ) { obj[key] = this[key]; } } return obj; }
javascript
function toJSON() { var obj = { message: this.message, stack: this.stack }, key; for (key in this) { if ( has.call(this, key) && 'function' !== typeof this[key] ) { obj[key] = this[key]; } } return obj; }
[ "function", "toJSON", "(", ")", "{", "var", "obj", "=", "{", "message", ":", "this", ".", "message", ",", "stack", ":", "this", ".", "stack", "}", ",", "key", ";", "for", "(", "key", "in", "this", ")", "{", "if", "(", "has", ".", "call", "(", "this", ",", "key", ")", "&&", "'function'", "!==", "typeof", "this", "[", "key", "]", ")", "{", "obj", "[", "key", "]", "=", "this", "[", "key", "]", ";", "}", "}", "return", "obj", ";", "}" ]
Return an object with all the information that should be in the JSON output. It doesn't matter if we list keys that might not be in the err as the JSON.stringify will remove properties who's values are set to `undefined`. So we want to make sure that we include some common properties. @returns {Object} @api public
[ "Return", "an", "object", "with", "all", "the", "information", "that", "should", "be", "in", "the", "JSON", "output", ".", "It", "doesn", "t", "matter", "if", "we", "list", "keys", "that", "might", "not", "be", "in", "the", "err", "as", "the", "JSON", ".", "stringify", "will", "remove", "properties", "who", "s", "values", "are", "set", "to", "undefined", ".", "So", "we", "want", "to", "make", "sure", "that", "we", "include", "some", "common", "properties", "." ]
085e848942f68d8169985799979fb69af553e196
https://github.com/unshiftio/failure/blob/085e848942f68d8169985799979fb69af553e196/index.js#L14-L27
50,068
deepjs/autobahn
lib/app-init.js
function(session) { if (session && session.user) { if (session.user.roles) return { roles: session.user.roles }; return { roles: "user" }; } return { roles: "public" }; }
javascript
function(session) { if (session && session.user) { if (session.user.roles) return { roles: session.user.roles }; return { roles: "user" }; } return { roles: "public" }; }
[ "function", "(", "session", ")", "{", "if", "(", "session", "&&", "session", ".", "user", ")", "{", "if", "(", "session", ".", "user", ".", "roles", ")", "return", "{", "roles", ":", "session", ".", "user", ".", "roles", "}", ";", "return", "{", "roles", ":", "\"user\"", "}", ";", "}", "return", "{", "roles", ":", "\"public\"", "}", ";", "}" ]
default session modes handler
[ "default", "session", "modes", "handler" ]
fe2dfa15c84a4a79bfde86abc1c63fc9f03e6cef
https://github.com/deepjs/autobahn/blob/fe2dfa15c84a4a79bfde86abc1c63fc9f03e6cef/lib/app-init.js#L179-L186
50,069
vidi-insights/vidi-influx-sink
influx-sink.js
on_write
function on_write (metric, enc, done) { var name = metric.name var values = metric.values var tags = metric.tags locals.batch.list[name] = locals.batch.list[name] || [] locals.batch.list[name].push([values, tags]) locals.batch.count = locals.batch.count + 1 var exceeded = locals.batch.count >= locals.batch.max var expired = Date.now() > locals.batch.next if (exceeded || expired) { write_batch() } done() }
javascript
function on_write (metric, enc, done) { var name = metric.name var values = metric.values var tags = metric.tags locals.batch.list[name] = locals.batch.list[name] || [] locals.batch.list[name].push([values, tags]) locals.batch.count = locals.batch.count + 1 var exceeded = locals.batch.count >= locals.batch.max var expired = Date.now() > locals.batch.next if (exceeded || expired) { write_batch() } done() }
[ "function", "on_write", "(", "metric", ",", "enc", ",", "done", ")", "{", "var", "name", "=", "metric", ".", "name", "var", "values", "=", "metric", ".", "values", "var", "tags", "=", "metric", ".", "tags", "locals", ".", "batch", ".", "list", "[", "name", "]", "=", "locals", ".", "batch", ".", "list", "[", "name", "]", "||", "[", "]", "locals", ".", "batch", ".", "list", "[", "name", "]", ".", "push", "(", "[", "values", ",", "tags", "]", ")", "locals", ".", "batch", ".", "count", "=", "locals", ".", "batch", ".", "count", "+", "1", "var", "exceeded", "=", "locals", ".", "batch", ".", "count", ">=", "locals", ".", "batch", ".", "max", "var", "expired", "=", "Date", ".", "now", "(", ")", ">", "locals", ".", "batch", ".", "next", "if", "(", "exceeded", "||", "expired", ")", "{", "write_batch", "(", ")", "}", "done", "(", ")", "}" ]
Called each time the stream is written to
[ "Called", "each", "time", "the", "stream", "is", "written", "to" ]
613851b6f7372415e62384a8a09624d362887f0d
https://github.com/vidi-insights/vidi-influx-sink/blob/613851b6f7372415e62384a8a09624d362887f0d/influx-sink.js#L72-L89
50,070
therne/importer
lib/importer.js
importerSync
function importerSync(options, handler) { var modulePath, recursive = false, parent = ''; if (typeof options === 'string') { modulePath = options; } else { modulePath = options.path; recursive = options.recursive || recursive; parent = options.parent || parent; if (!modulePath) throw new Error("module directory path must be given."); } // absolute path? or relevant path? if (modulePath.indexOf('/') != 0) { // relevant. join with parent module's path modulePath = path.join(path.dirname(module.parent.parent.filename), modulePath); } var files = fs.readdirSync(modulePath); for (var i in files) { var name = files[i]; if (recursive && fs.lstatSync(path.join(modulePath, name)).isDirectory()) { importerSync({ path: path.join(modulePath, name), recursive: true, parent: path.join(parent, name) }, handler); continue; } if (name.lastIndexOf('.js') != name.length - 3) continue; name = name.substring(0, name.lastIndexOf('.')); // remove ext var moduleObj = require(path.join(modulePath, name)); if (handler) handler(moduleObj, path.join(parent, name)); } }
javascript
function importerSync(options, handler) { var modulePath, recursive = false, parent = ''; if (typeof options === 'string') { modulePath = options; } else { modulePath = options.path; recursive = options.recursive || recursive; parent = options.parent || parent; if (!modulePath) throw new Error("module directory path must be given."); } // absolute path? or relevant path? if (modulePath.indexOf('/') != 0) { // relevant. join with parent module's path modulePath = path.join(path.dirname(module.parent.parent.filename), modulePath); } var files = fs.readdirSync(modulePath); for (var i in files) { var name = files[i]; if (recursive && fs.lstatSync(path.join(modulePath, name)).isDirectory()) { importerSync({ path: path.join(modulePath, name), recursive: true, parent: path.join(parent, name) }, handler); continue; } if (name.lastIndexOf('.js') != name.length - 3) continue; name = name.substring(0, name.lastIndexOf('.')); // remove ext var moduleObj = require(path.join(modulePath, name)); if (handler) handler(moduleObj, path.join(parent, name)); } }
[ "function", "importerSync", "(", "options", ",", "handler", ")", "{", "var", "modulePath", ",", "recursive", "=", "false", ",", "parent", "=", "''", ";", "if", "(", "typeof", "options", "===", "'string'", ")", "{", "modulePath", "=", "options", ";", "}", "else", "{", "modulePath", "=", "options", ".", "path", ";", "recursive", "=", "options", ".", "recursive", "||", "recursive", ";", "parent", "=", "options", ".", "parent", "||", "parent", ";", "if", "(", "!", "modulePath", ")", "throw", "new", "Error", "(", "\"module directory path must be given.\"", ")", ";", "}", "// absolute path? or relevant path?", "if", "(", "modulePath", ".", "indexOf", "(", "'/'", ")", "!=", "0", ")", "{", "// relevant. join with parent module's path", "modulePath", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "module", ".", "parent", ".", "parent", ".", "filename", ")", ",", "modulePath", ")", ";", "}", "var", "files", "=", "fs", ".", "readdirSync", "(", "modulePath", ")", ";", "for", "(", "var", "i", "in", "files", ")", "{", "var", "name", "=", "files", "[", "i", "]", ";", "if", "(", "recursive", "&&", "fs", ".", "lstatSync", "(", "path", ".", "join", "(", "modulePath", ",", "name", ")", ")", ".", "isDirectory", "(", ")", ")", "{", "importerSync", "(", "{", "path", ":", "path", ".", "join", "(", "modulePath", ",", "name", ")", ",", "recursive", ":", "true", ",", "parent", ":", "path", ".", "join", "(", "parent", ",", "name", ")", "}", ",", "handler", ")", ";", "continue", ";", "}", "if", "(", "name", ".", "lastIndexOf", "(", "'.js'", ")", "!=", "name", ".", "length", "-", "3", ")", "continue", ";", "name", "=", "name", ".", "substring", "(", "0", ",", "name", ".", "lastIndexOf", "(", "'.'", ")", ")", ";", "// remove ext", "var", "moduleObj", "=", "require", "(", "path", ".", "join", "(", "modulePath", ",", "name", ")", ")", ";", "if", "(", "handler", ")", "handler", "(", "moduleObj", ",", "path", ".", "join", "(", "parent", ",", "name", ")", ")", ";", "}", "}" ]
Retrieves all sources in a given directory and calls handler. @param options Import options. (or module directory path) @param {eachModule} [handler] Called when import each module.
[ "Retrieves", "all", "sources", "in", "a", "given", "directory", "and", "calls", "handler", "." ]
2c39ee45e434e7974139b96484dda11db72da467
https://github.com/therne/importer/blob/2c39ee45e434e7974139b96484dda11db72da467/lib/importer.js#L22-L59
50,071
itsa-server/itsa-classes
classes.js
function (prototypes, force) { var instance, proto, names, l, i, replaceMap, protectedMap, name, nameInProto, finalName, propDescriptor, extraInfo; if (!prototypes) { return; } instance = this; // the Class proto = instance.prototype; names = Object.getOwnPropertyNames(prototypes); l = names.length; i = -1; replaceMap = arguments[2] || REPLACE_CLASS_METHODS; // hidden feature, used by itags protectedMap = arguments[3] || PROTECTED_CLASS_METHODS; // hidden feature, used by itags while (++i < l) { name = names[i]; finalName = replaceMap[name] || name; nameInProto = (finalName in proto); if (!PROTO_RESERVED_NAMES[finalName] && !protectedMap[finalName] && (!nameInProto || force)) { // if nameInProto: set the property, but also backup for chaining using $$orig propDescriptor = Object.getOwnPropertyDescriptor(prototypes, name); if (!propDescriptor.writable) { console.info(NAME+'mergePrototypes will set property of '+name+' without its property-descriptor: for it is an unwritable property.'); proto[finalName] = prototypes[name]; } else { // adding prototypes[name] into $$orig: instance.$$orig[finalName] || (instance.$$orig[finalName]=[]); instance.$$orig[finalName][instance.$$orig[finalName].length] = prototypes[name]; if (typeof prototypes[name] === 'function') { /*jshint -W083 */ propDescriptor.value = (function (originalMethodName, finalMethodName) { return function () { /*jshint +W083 */ // this.$own = prot; // this.$origMethods = instance.$$orig[finalMethodName]; var context, classCarierBkp, methodClassCarierBkp, origPropBkp, returnValue; // in some specific situations, this method is called without context. // can't figure out why (it happens when itable changes some of its its item-values) // probably reasson is that itable.model.items is not the same as itable.getData('_items') // anyway: to prevent errors here, we must return when there is no context: context = this; if (!context) { return; } classCarierBkp = context.__classCarier__; methodClassCarierBkp = context.__methodClassCarier__; origPropBkp = context.__origProp__; context.__methodClassCarier__ = instance; context.__classCarier__ = null; context.__origProp__ = finalMethodName; returnValue = prototypes[originalMethodName].apply(context, arguments); context.__origProp__ = origPropBkp; context.__classCarier__ = classCarierBkp; context.__methodClassCarier__ = methodClassCarierBkp; return returnValue; }; })(name, finalName); } Object.defineProperty(proto, finalName, propDescriptor); } } else { extraInfo = ''; nameInProto && (extraInfo = 'property is already available (you might force it to be set)'); PROTO_RESERVED_NAMES[finalName] && (extraInfo = 'property is a protected property'); protectedMap[finalName] && (extraInfo = 'property is a private property'); console.warn(NAME+'mergePrototypes is not allowed to set the property: '+name+' --> '+extraInfo); } } return instance; }
javascript
function (prototypes, force) { var instance, proto, names, l, i, replaceMap, protectedMap, name, nameInProto, finalName, propDescriptor, extraInfo; if (!prototypes) { return; } instance = this; // the Class proto = instance.prototype; names = Object.getOwnPropertyNames(prototypes); l = names.length; i = -1; replaceMap = arguments[2] || REPLACE_CLASS_METHODS; // hidden feature, used by itags protectedMap = arguments[3] || PROTECTED_CLASS_METHODS; // hidden feature, used by itags while (++i < l) { name = names[i]; finalName = replaceMap[name] || name; nameInProto = (finalName in proto); if (!PROTO_RESERVED_NAMES[finalName] && !protectedMap[finalName] && (!nameInProto || force)) { // if nameInProto: set the property, but also backup for chaining using $$orig propDescriptor = Object.getOwnPropertyDescriptor(prototypes, name); if (!propDescriptor.writable) { console.info(NAME+'mergePrototypes will set property of '+name+' without its property-descriptor: for it is an unwritable property.'); proto[finalName] = prototypes[name]; } else { // adding prototypes[name] into $$orig: instance.$$orig[finalName] || (instance.$$orig[finalName]=[]); instance.$$orig[finalName][instance.$$orig[finalName].length] = prototypes[name]; if (typeof prototypes[name] === 'function') { /*jshint -W083 */ propDescriptor.value = (function (originalMethodName, finalMethodName) { return function () { /*jshint +W083 */ // this.$own = prot; // this.$origMethods = instance.$$orig[finalMethodName]; var context, classCarierBkp, methodClassCarierBkp, origPropBkp, returnValue; // in some specific situations, this method is called without context. // can't figure out why (it happens when itable changes some of its its item-values) // probably reasson is that itable.model.items is not the same as itable.getData('_items') // anyway: to prevent errors here, we must return when there is no context: context = this; if (!context) { return; } classCarierBkp = context.__classCarier__; methodClassCarierBkp = context.__methodClassCarier__; origPropBkp = context.__origProp__; context.__methodClassCarier__ = instance; context.__classCarier__ = null; context.__origProp__ = finalMethodName; returnValue = prototypes[originalMethodName].apply(context, arguments); context.__origProp__ = origPropBkp; context.__classCarier__ = classCarierBkp; context.__methodClassCarier__ = methodClassCarierBkp; return returnValue; }; })(name, finalName); } Object.defineProperty(proto, finalName, propDescriptor); } } else { extraInfo = ''; nameInProto && (extraInfo = 'property is already available (you might force it to be set)'); PROTO_RESERVED_NAMES[finalName] && (extraInfo = 'property is a protected property'); protectedMap[finalName] && (extraInfo = 'property is a private property'); console.warn(NAME+'mergePrototypes is not allowed to set the property: '+name+' --> '+extraInfo); } } return instance; }
[ "function", "(", "prototypes", ",", "force", ")", "{", "var", "instance", ",", "proto", ",", "names", ",", "l", ",", "i", ",", "replaceMap", ",", "protectedMap", ",", "name", ",", "nameInProto", ",", "finalName", ",", "propDescriptor", ",", "extraInfo", ";", "if", "(", "!", "prototypes", ")", "{", "return", ";", "}", "instance", "=", "this", ";", "// the Class", "proto", "=", "instance", ".", "prototype", ";", "names", "=", "Object", ".", "getOwnPropertyNames", "(", "prototypes", ")", ";", "l", "=", "names", ".", "length", ";", "i", "=", "-", "1", ";", "replaceMap", "=", "arguments", "[", "2", "]", "||", "REPLACE_CLASS_METHODS", ";", "// hidden feature, used by itags", "protectedMap", "=", "arguments", "[", "3", "]", "||", "PROTECTED_CLASS_METHODS", ";", "// hidden feature, used by itags", "while", "(", "++", "i", "<", "l", ")", "{", "name", "=", "names", "[", "i", "]", ";", "finalName", "=", "replaceMap", "[", "name", "]", "||", "name", ";", "nameInProto", "=", "(", "finalName", "in", "proto", ")", ";", "if", "(", "!", "PROTO_RESERVED_NAMES", "[", "finalName", "]", "&&", "!", "protectedMap", "[", "finalName", "]", "&&", "(", "!", "nameInProto", "||", "force", ")", ")", "{", "// if nameInProto: set the property, but also backup for chaining using $$orig", "propDescriptor", "=", "Object", ".", "getOwnPropertyDescriptor", "(", "prototypes", ",", "name", ")", ";", "if", "(", "!", "propDescriptor", ".", "writable", ")", "{", "console", ".", "info", "(", "NAME", "+", "'mergePrototypes will set property of '", "+", "name", "+", "' without its property-descriptor: for it is an unwritable property.'", ")", ";", "proto", "[", "finalName", "]", "=", "prototypes", "[", "name", "]", ";", "}", "else", "{", "// adding prototypes[name] into $$orig:", "instance", ".", "$$orig", "[", "finalName", "]", "||", "(", "instance", ".", "$$orig", "[", "finalName", "]", "=", "[", "]", ")", ";", "instance", ".", "$$orig", "[", "finalName", "]", "[", "instance", ".", "$$orig", "[", "finalName", "]", ".", "length", "]", "=", "prototypes", "[", "name", "]", ";", "if", "(", "typeof", "prototypes", "[", "name", "]", "===", "'function'", ")", "{", "/*jshint -W083 */", "propDescriptor", ".", "value", "=", "(", "function", "(", "originalMethodName", ",", "finalMethodName", ")", "{", "return", "function", "(", ")", "{", "/*jshint +W083 */", "// this.$own = prot;", "// this.$origMethods = instance.$$orig[finalMethodName];", "var", "context", ",", "classCarierBkp", ",", "methodClassCarierBkp", ",", "origPropBkp", ",", "returnValue", ";", "// in some specific situations, this method is called without context.", "// can't figure out why (it happens when itable changes some of its its item-values)", "// probably reasson is that itable.model.items is not the same as itable.getData('_items')", "// anyway: to prevent errors here, we must return when there is no context:", "context", "=", "this", ";", "if", "(", "!", "context", ")", "{", "return", ";", "}", "classCarierBkp", "=", "context", ".", "__classCarier__", ";", "methodClassCarierBkp", "=", "context", ".", "__methodClassCarier__", ";", "origPropBkp", "=", "context", ".", "__origProp__", ";", "context", ".", "__methodClassCarier__", "=", "instance", ";", "context", ".", "__classCarier__", "=", "null", ";", "context", ".", "__origProp__", "=", "finalMethodName", ";", "returnValue", "=", "prototypes", "[", "originalMethodName", "]", ".", "apply", "(", "context", ",", "arguments", ")", ";", "context", ".", "__origProp__", "=", "origPropBkp", ";", "context", ".", "__classCarier__", "=", "classCarierBkp", ";", "context", ".", "__methodClassCarier__", "=", "methodClassCarierBkp", ";", "return", "returnValue", ";", "}", ";", "}", ")", "(", "name", ",", "finalName", ")", ";", "}", "Object", ".", "defineProperty", "(", "proto", ",", "finalName", ",", "propDescriptor", ")", ";", "}", "}", "else", "{", "extraInfo", "=", "''", ";", "nameInProto", "&&", "(", "extraInfo", "=", "'property is already available (you might force it to be set)'", ")", ";", "PROTO_RESERVED_NAMES", "[", "finalName", "]", "&&", "(", "extraInfo", "=", "'property is a protected property'", ")", ";", "protectedMap", "[", "finalName", "]", "&&", "(", "extraInfo", "=", "'property is a private property'", ")", ";", "console", ".", "warn", "(", "NAME", "+", "'mergePrototypes is not allowed to set the property: '", "+", "name", "+", "' --> '", "+", "extraInfo", ")", ";", "}", "}", "return", "instance", ";", "}" ]
Merges the given prototypes of properties into the `prototype` of the Class. **Note1 ** to be used on instances --> ONLY on Classes **Note2 ** properties with getters and/or unwritable will NOT be merged The members in the hash prototypes will become members with instances of the merged class. By default, this method will not override existing prototype members, unless the second argument `force` is true. @method mergePrototypes @param prototypes {Object} Hash prototypes of properties to add to the prototype of this object @param force {Boolean} If true, existing members will be overwritten @chainable
[ "Merges", "the", "given", "prototypes", "of", "properties", "into", "the", "prototype", "of", "the", "Class", "." ]
58f3355a5d68d528194d362fb99dd32ea31ec7cf
https://github.com/itsa-server/itsa-classes/blob/58f3355a5d68d528194d362fb99dd32ea31ec7cf/classes.js#L177-L254
50,072
itsa-server/itsa-classes
classes.js
function (properties) { var proto = this.prototype, replaceMap = arguments[1] || REPLACE_CLASS_METHODS; // hidden feature, used by itags Array.isArray(properties) || (properties=[properties]); properties.forEach(function(prop) { prop = replaceMap[prop] || prop; delete proto[prop]; }); return this; }
javascript
function (properties) { var proto = this.prototype, replaceMap = arguments[1] || REPLACE_CLASS_METHODS; // hidden feature, used by itags Array.isArray(properties) || (properties=[properties]); properties.forEach(function(prop) { prop = replaceMap[prop] || prop; delete proto[prop]; }); return this; }
[ "function", "(", "properties", ")", "{", "var", "proto", "=", "this", ".", "prototype", ",", "replaceMap", "=", "arguments", "[", "1", "]", "||", "REPLACE_CLASS_METHODS", ";", "// hidden feature, used by itags", "Array", ".", "isArray", "(", "properties", ")", "||", "(", "properties", "=", "[", "properties", "]", ")", ";", "properties", ".", "forEach", "(", "function", "(", "prop", ")", "{", "prop", "=", "replaceMap", "[", "prop", "]", "||", "prop", ";", "delete", "proto", "[", "prop", "]", ";", "}", ")", ";", "return", "this", ";", "}" ]
Removes the specified prototypes from the Class. @method removePrototypes @param properties {String|Array} Hash of properties to be removed from the Class @chainable
[ "Removes", "the", "specified", "prototypes", "from", "the", "Class", "." ]
58f3355a5d68d528194d362fb99dd32ea31ec7cf
https://github.com/itsa-server/itsa-classes/blob/58f3355a5d68d528194d362fb99dd32ea31ec7cf/classes.js#L264-L273
50,073
itsa-server/itsa-classes
classes.js
function(constructorFn, chainConstruct) { var instance = this; if (typeof constructorFn==='boolean') { chainConstruct = constructorFn; constructorFn = null; } (typeof chainConstruct === 'boolean') || (chainConstruct=DEFAULT_CHAIN_CONSTRUCT); instance.$$constrFn = constructorFn || NOOP; instance.$$chainConstructed = chainConstruct ? true : false; return instance; }
javascript
function(constructorFn, chainConstruct) { var instance = this; if (typeof constructorFn==='boolean') { chainConstruct = constructorFn; constructorFn = null; } (typeof chainConstruct === 'boolean') || (chainConstruct=DEFAULT_CHAIN_CONSTRUCT); instance.$$constrFn = constructorFn || NOOP; instance.$$chainConstructed = chainConstruct ? true : false; return instance; }
[ "function", "(", "constructorFn", ",", "chainConstruct", ")", "{", "var", "instance", "=", "this", ";", "if", "(", "typeof", "constructorFn", "===", "'boolean'", ")", "{", "chainConstruct", "=", "constructorFn", ";", "constructorFn", "=", "null", ";", "}", "(", "typeof", "chainConstruct", "===", "'boolean'", ")", "||", "(", "chainConstruct", "=", "DEFAULT_CHAIN_CONSTRUCT", ")", ";", "instance", ".", "$$constrFn", "=", "constructorFn", "||", "NOOP", ";", "instance", ".", "$$chainConstructed", "=", "chainConstruct", "?", "true", ":", "false", ";", "return", "instance", ";", "}" ]
Redefines the constructor fo the Class @method setConstructor @param [constructorFn] {Function} The function that will serve as the new constructor for the class. If `undefined` defaults to `NOOP` @param [prototypes] {Object} Hash map of properties to be added to the prototype of the new class. @param [chainConstruct=true] {Boolean} Whether -during instance creation- to automaticly construct in the complete hierarchy with the given constructor arguments. @chainable
[ "Redefines", "the", "constructor", "fo", "the", "Class" ]
58f3355a5d68d528194d362fb99dd32ea31ec7cf
https://github.com/itsa-server/itsa-classes/blob/58f3355a5d68d528194d362fb99dd32ea31ec7cf/classes.js#L285-L295
50,074
itsa-server/itsa-classes
classes.js
function (constructor, prototypes, chainConstruct) { var instance = this, constructorClosure = {}, baseProt, proto, constrFn; if (typeof constructor === 'boolean') { constructor = null; prototypes = null; chainConstruct = constructor; } else { if ((typeof constructor === 'object') && (constructor!==null)) { chainConstruct = prototypes; prototypes = constructor; constructor = null; } if (typeof prototypes === 'boolean') { chainConstruct = prototypes; prototypes = null; } } (typeof chainConstruct === 'boolean') || (chainConstruct=DEFAULT_CHAIN_CONSTRUCT); constrFn = constructor || NOOP; constructor = function() { constructorClosure.constructor.$$constrFn.apply(this, arguments); }; constructor = (function(originalConstructor) { return function() { var context = this; if (constructorClosure.constructor.$$chainConstructed) { context.__classCarier__ = constructorClosure.constructor.$$super.constructor; context.__origProp__ = 'constructor'; context.__classCarier__.apply(context, arguments); context.$origMethods = constructorClosure.constructor.$$orig.constructor; } context.__classCarier__ = constructorClosure.constructor; context.__origProp__ = 'constructor'; originalConstructor.apply(context, arguments); // only call aferInit on the last constructor of the chain: (constructorClosure.constructor===context.constructor) && context.afterInit(); }; })(constructor); baseProt = instance.prototype; proto = Object.create(baseProt); constructor.prototype = proto; // webkit doesn't let all objects to have their constructor redefined // when directly assigned. Using `defineProperty will work: Object.defineProperty(proto, 'constructor', {value: constructor}); constructor.$$chainConstructed = chainConstruct ? true : false; constructor.$$super = baseProt; constructor.$$orig = { constructor: constructor }; constructor.$$constrFn = constrFn; constructorClosure.constructor = constructor; prototypes && constructor.mergePrototypes(prototypes, true); return constructor; }
javascript
function (constructor, prototypes, chainConstruct) { var instance = this, constructorClosure = {}, baseProt, proto, constrFn; if (typeof constructor === 'boolean') { constructor = null; prototypes = null; chainConstruct = constructor; } else { if ((typeof constructor === 'object') && (constructor!==null)) { chainConstruct = prototypes; prototypes = constructor; constructor = null; } if (typeof prototypes === 'boolean') { chainConstruct = prototypes; prototypes = null; } } (typeof chainConstruct === 'boolean') || (chainConstruct=DEFAULT_CHAIN_CONSTRUCT); constrFn = constructor || NOOP; constructor = function() { constructorClosure.constructor.$$constrFn.apply(this, arguments); }; constructor = (function(originalConstructor) { return function() { var context = this; if (constructorClosure.constructor.$$chainConstructed) { context.__classCarier__ = constructorClosure.constructor.$$super.constructor; context.__origProp__ = 'constructor'; context.__classCarier__.apply(context, arguments); context.$origMethods = constructorClosure.constructor.$$orig.constructor; } context.__classCarier__ = constructorClosure.constructor; context.__origProp__ = 'constructor'; originalConstructor.apply(context, arguments); // only call aferInit on the last constructor of the chain: (constructorClosure.constructor===context.constructor) && context.afterInit(); }; })(constructor); baseProt = instance.prototype; proto = Object.create(baseProt); constructor.prototype = proto; // webkit doesn't let all objects to have their constructor redefined // when directly assigned. Using `defineProperty will work: Object.defineProperty(proto, 'constructor', {value: constructor}); constructor.$$chainConstructed = chainConstruct ? true : false; constructor.$$super = baseProt; constructor.$$orig = { constructor: constructor }; constructor.$$constrFn = constrFn; constructorClosure.constructor = constructor; prototypes && constructor.mergePrototypes(prototypes, true); return constructor; }
[ "function", "(", "constructor", ",", "prototypes", ",", "chainConstruct", ")", "{", "var", "instance", "=", "this", ",", "constructorClosure", "=", "{", "}", ",", "baseProt", ",", "proto", ",", "constrFn", ";", "if", "(", "typeof", "constructor", "===", "'boolean'", ")", "{", "constructor", "=", "null", ";", "prototypes", "=", "null", ";", "chainConstruct", "=", "constructor", ";", "}", "else", "{", "if", "(", "(", "typeof", "constructor", "===", "'object'", ")", "&&", "(", "constructor", "!==", "null", ")", ")", "{", "chainConstruct", "=", "prototypes", ";", "prototypes", "=", "constructor", ";", "constructor", "=", "null", ";", "}", "if", "(", "typeof", "prototypes", "===", "'boolean'", ")", "{", "chainConstruct", "=", "prototypes", ";", "prototypes", "=", "null", ";", "}", "}", "(", "typeof", "chainConstruct", "===", "'boolean'", ")", "||", "(", "chainConstruct", "=", "DEFAULT_CHAIN_CONSTRUCT", ")", ";", "constrFn", "=", "constructor", "||", "NOOP", ";", "constructor", "=", "function", "(", ")", "{", "constructorClosure", ".", "constructor", ".", "$$constrFn", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "constructor", "=", "(", "function", "(", "originalConstructor", ")", "{", "return", "function", "(", ")", "{", "var", "context", "=", "this", ";", "if", "(", "constructorClosure", ".", "constructor", ".", "$$chainConstructed", ")", "{", "context", ".", "__classCarier__", "=", "constructorClosure", ".", "constructor", ".", "$$super", ".", "constructor", ";", "context", ".", "__origProp__", "=", "'constructor'", ";", "context", ".", "__classCarier__", ".", "apply", "(", "context", ",", "arguments", ")", ";", "context", ".", "$origMethods", "=", "constructorClosure", ".", "constructor", ".", "$$orig", ".", "constructor", ";", "}", "context", ".", "__classCarier__", "=", "constructorClosure", ".", "constructor", ";", "context", ".", "__origProp__", "=", "'constructor'", ";", "originalConstructor", ".", "apply", "(", "context", ",", "arguments", ")", ";", "// only call aferInit on the last constructor of the chain:", "(", "constructorClosure", ".", "constructor", "===", "context", ".", "constructor", ")", "&&", "context", ".", "afterInit", "(", ")", ";", "}", ";", "}", ")", "(", "constructor", ")", ";", "baseProt", "=", "instance", ".", "prototype", ";", "proto", "=", "Object", ".", "create", "(", "baseProt", ")", ";", "constructor", ".", "prototype", "=", "proto", ";", "// webkit doesn't let all objects to have their constructor redefined", "// when directly assigned. Using `defineProperty will work:", "Object", ".", "defineProperty", "(", "proto", ",", "'constructor'", ",", "{", "value", ":", "constructor", "}", ")", ";", "constructor", ".", "$$chainConstructed", "=", "chainConstruct", "?", "true", ":", "false", ";", "constructor", ".", "$$super", "=", "baseProt", ";", "constructor", ".", "$$orig", "=", "{", "constructor", ":", "constructor", "}", ";", "constructor", ".", "$$constrFn", "=", "constrFn", ";", "constructorClosure", ".", "constructor", "=", "constructor", ";", "prototypes", "&&", "constructor", ".", "mergePrototypes", "(", "prototypes", ",", "true", ")", ";", "return", "constructor", ";", "}" ]
Returns a newly created class inheriting from this class using the given `constructor` with the prototypes listed in `prototypes` merged in. The newly created class has the `$$super` static property available to access all of is ancestor's instance methods. Further methods can be added via the [mergePrototypes](#method_mergePrototypes). @example var Circle = Shape.subClass( function (x, y, r) { // arguments will automaticly be passed through to Shape's constructor this.r = r; }, { area: function () { return this.r * this.r * Math.PI; } } ); @method subClass @param [constructor] {Function} The function that will serve as constructor for the new class. If `undefined` defaults to `NOOP` @param [prototypes] {Object} Hash map of properties to be added to the prototype of the new class. @param [chainConstruct=true] {Boolean} Whether -during instance creation- to automaticly construct in the complete hierarchy with the given constructor arguments. @return the new class.
[ "Returns", "a", "newly", "created", "class", "inheriting", "from", "this", "class", "using", "the", "given", "constructor", "with", "the", "prototypes", "listed", "in", "prototypes", "merged", "in", "." ]
58f3355a5d68d528194d362fb99dd32ea31ec7cf
https://github.com/itsa-server/itsa-classes/blob/58f3355a5d68d528194d362fb99dd32ea31ec7cf/classes.js#L329-L394
50,075
admoexperience/generator-admo
templates/bower/jquery.transit.js
checkTransform3dSupport
function checkTransform3dSupport() { div.style[support.transform] = ''; div.style[support.transform] = 'rotateY(90deg)'; return div.style[support.transform] !== ''; }
javascript
function checkTransform3dSupport() { div.style[support.transform] = ''; div.style[support.transform] = 'rotateY(90deg)'; return div.style[support.transform] !== ''; }
[ "function", "checkTransform3dSupport", "(", ")", "{", "div", ".", "style", "[", "support", ".", "transform", "]", "=", "''", ";", "div", ".", "style", "[", "support", ".", "transform", "]", "=", "'rotateY(90deg)'", ";", "return", "div", ".", "style", "[", "support", ".", "transform", "]", "!==", "''", ";", "}" ]
Helper function to check if transform3D is supported. Should return true for Webkits and Firefox 10+.
[ "Helper", "function", "to", "check", "if", "transform3D", "is", "supported", ".", "Should", "return", "true", "for", "Webkits", "and", "Firefox", "10", "+", "." ]
f27e261990948860e14f735f3cd7c59bf1130feb
https://github.com/admoexperience/generator-admo/blob/f27e261990948860e14f735f3cd7c59bf1130feb/templates/bower/jquery.transit.js#L56-L60
50,076
admoexperience/generator-admo
templates/bower/jquery.transit.js
function(elem, v) { var value = v; if (!(value instanceof Transform)) { value = new Transform(value); } // We've seen the 3D version of Scale() not work in Chrome when the // element being scaled extends outside of the viewport. Thus, we're // forcing Chrome to not use the 3d transforms as well. Not sure if // translate is affectede, but not risking it. Detection code from // http://davidwalsh.name/detecting-google-chrome-javascript if (support.transform === 'WebkitTransform' && !isChrome) { elem.style[support.transform] = value.toString(true); } else { elem.style[support.transform] = value.toString(); } $(elem).data('transform', value); }
javascript
function(elem, v) { var value = v; if (!(value instanceof Transform)) { value = new Transform(value); } // We've seen the 3D version of Scale() not work in Chrome when the // element being scaled extends outside of the viewport. Thus, we're // forcing Chrome to not use the 3d transforms as well. Not sure if // translate is affectede, but not risking it. Detection code from // http://davidwalsh.name/detecting-google-chrome-javascript if (support.transform === 'WebkitTransform' && !isChrome) { elem.style[support.transform] = value.toString(true); } else { elem.style[support.transform] = value.toString(); } $(elem).data('transform', value); }
[ "function", "(", "elem", ",", "v", ")", "{", "var", "value", "=", "v", ";", "if", "(", "!", "(", "value", "instanceof", "Transform", ")", ")", "{", "value", "=", "new", "Transform", "(", "value", ")", ";", "}", "// We've seen the 3D version of Scale() not work in Chrome when the", "// element being scaled extends outside of the viewport. Thus, we're", "// forcing Chrome to not use the 3d transforms as well. Not sure if", "// translate is affectede, but not risking it. Detection code from", "// http://davidwalsh.name/detecting-google-chrome-javascript", "if", "(", "support", ".", "transform", "===", "'WebkitTransform'", "&&", "!", "isChrome", ")", "{", "elem", ".", "style", "[", "support", ".", "transform", "]", "=", "value", ".", "toString", "(", "true", ")", ";", "}", "else", "{", "elem", ".", "style", "[", "support", ".", "transform", "]", "=", "value", ".", "toString", "(", ")", ";", "}", "$", "(", "elem", ")", ".", "data", "(", "'transform'", ",", "value", ")", ";", "}" ]
The setter accepts a `Transform` object or a string.
[ "The", "setter", "accepts", "a", "Transform", "object", "or", "a", "string", "." ]
f27e261990948860e14f735f3cd7c59bf1130feb
https://github.com/admoexperience/generator-admo/blob/f27e261990948860e14f735f3cd7c59bf1130feb/templates/bower/jquery.transit.js#L143-L162
50,077
admoexperience/generator-admo
templates/bower/jquery.transit.js
function() { if (bound) { self.unbind(transitionEnd, cb); } if (i > 0) { self.each(function() { this.style[support.transition] = (oldTransitions[this] || null); }); } if (typeof callback === 'function') { callback.apply(self); } if (typeof nextCall === 'function') { nextCall(); } }
javascript
function() { if (bound) { self.unbind(transitionEnd, cb); } if (i > 0) { self.each(function() { this.style[support.transition] = (oldTransitions[this] || null); }); } if (typeof callback === 'function') { callback.apply(self); } if (typeof nextCall === 'function') { nextCall(); } }
[ "function", "(", ")", "{", "if", "(", "bound", ")", "{", "self", ".", "unbind", "(", "transitionEnd", ",", "cb", ")", ";", "}", "if", "(", "i", ">", "0", ")", "{", "self", ".", "each", "(", "function", "(", ")", "{", "this", ".", "style", "[", "support", ".", "transition", "]", "=", "(", "oldTransitions", "[", "this", "]", "||", "null", ")", ";", "}", ")", ";", "}", "if", "(", "typeof", "callback", "===", "'function'", ")", "{", "callback", ".", "apply", "(", "self", ")", ";", "}", "if", "(", "typeof", "nextCall", "===", "'function'", ")", "{", "nextCall", "(", ")", ";", "}", "}" ]
Prepare the callback.
[ "Prepare", "the", "callback", "." ]
f27e261990948860e14f735f3cd7c59bf1130feb
https://github.com/admoexperience/generator-admo/blob/f27e261990948860e14f735f3cd7c59bf1130feb/templates/bower/jquery.transit.js#L589-L600
50,078
admoexperience/generator-admo
templates/bower/jquery.transit.js
function(next) { var i = 0; // Durations that are too slow will get transitions mixed up. // (Tested on Mac/FF 7.0.1) if ((support.transition === 'MozTransition') && (i < 25)) { i = 25; } window.setTimeout(function() { run(next); }, i); }
javascript
function(next) { var i = 0; // Durations that are too slow will get transitions mixed up. // (Tested on Mac/FF 7.0.1) if ((support.transition === 'MozTransition') && (i < 25)) { i = 25; } window.setTimeout(function() { run(next); }, i); }
[ "function", "(", "next", ")", "{", "var", "i", "=", "0", ";", "// Durations that are too slow will get transitions mixed up.", "// (Tested on Mac/FF 7.0.1)", "if", "(", "(", "support", ".", "transition", "===", "'MozTransition'", ")", "&&", "(", "i", "<", "25", ")", ")", "{", "i", "=", "25", ";", "}", "window", ".", "setTimeout", "(", "function", "(", ")", "{", "run", "(", "next", ")", ";", "}", ",", "i", ")", ";", "}" ]
Defer running. This allows the browser to paint any pending CSS it hasn't painted yet before doing the transitions.
[ "Defer", "running", ".", "This", "allows", "the", "browser", "to", "paint", "any", "pending", "CSS", "it", "hasn", "t", "painted", "yet", "before", "doing", "the", "transitions", "." ]
f27e261990948860e14f735f3cd7c59bf1130feb
https://github.com/admoexperience/generator-admo/blob/f27e261990948860e14f735f3cd7c59bf1130feb/templates/bower/jquery.transit.js#L622-L630
50,079
getmillipede/millipede-node
lib/millipede.js
Millipede
function Millipede(size, options) { options = options || {}; this.size = size; this.reverse = options.reverse; this.horizontal = options.horizontal; this.position = options.position || 0; this.top = options.top || 0; this.left = options.left || 0; this.validate(); }
javascript
function Millipede(size, options) { options = options || {}; this.size = size; this.reverse = options.reverse; this.horizontal = options.horizontal; this.position = options.position || 0; this.top = options.top || 0; this.left = options.left || 0; this.validate(); }
[ "function", "Millipede", "(", "size", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "size", "=", "size", ";", "this", ".", "reverse", "=", "options", ".", "reverse", ";", "this", ".", "horizontal", "=", "options", ".", "horizontal", ";", "this", ".", "position", "=", "options", ".", "position", "||", "0", ";", "this", ".", "top", "=", "options", ".", "top", "||", "0", ";", "this", ".", "left", "=", "options", ".", "left", "||", "0", ";", "this", ".", "validate", "(", ")", ";", "}" ]
Initialize a new `Millipede` with the given `size` and `options`. @param {Number} size @param {Object} options @return {Millipede} @public
[ "Initialize", "a", "new", "Millipede", "with", "the", "given", "size", "and", "options", "." ]
e68244e91e458a2916a09124847c655f993ff970
https://github.com/getmillipede/millipede-node/blob/e68244e91e458a2916a09124847c655f993ff970/lib/millipede.js#L26-L38
50,080
interlockjs/plugins
packages/share/src/take.js
rawBundleFromFile
function rawBundleFromFile (dir, filename) { return readFilePromise(path.join(dir, filename)) .then(content => { return { dest: filename, raw: content }; }); }
javascript
function rawBundleFromFile (dir, filename) { return readFilePromise(path.join(dir, filename)) .then(content => { return { dest: filename, raw: content }; }); }
[ "function", "rawBundleFromFile", "(", "dir", ",", "filename", ")", "{", "return", "readFilePromise", "(", "path", ".", "join", "(", "dir", ",", "filename", ")", ")", ".", "then", "(", "content", "=>", "{", "return", "{", "dest", ":", "filename", ",", "raw", ":", "content", "}", ";", "}", ")", ";", "}" ]
Given a directory and file in that directory, return a promise that resolves to a bundle that contains the filename and raw content. @param {String} dir Valid path to directory containing Interlock bundles. @param {String} filename Filename of bundle in dir. @returns {Promise} Resolves to bundle matching input file.
[ "Given", "a", "directory", "and", "file", "in", "that", "directory", "return", "a", "promise", "that", "resolves", "to", "a", "bundle", "that", "contains", "the", "filename", "and", "raw", "content", "." ]
05197e4511b64d269260fe3c701ceff864897ab3
https://github.com/interlockjs/plugins/blob/05197e4511b64d269260fe3c701ceff864897ab3/packages/share/src/take.js#L26-L31
50,081
JohnnieFucker/dreamix-rpc
lib/rpc-client/router.js
defRoute
function defRoute(session, msg, context, cb) { const list = context.getServersByType(msg.serverType); if (!list || !list.length) { cb(new Error(`can not find server info for type:${msg.serverType}`)); return; } const uid = session ? (session.uid || '') : ''; const index = Math.abs(crc.crc32(uid.toString())) % list.length; utils.invokeCallback(cb, null, list[index].id); }
javascript
function defRoute(session, msg, context, cb) { const list = context.getServersByType(msg.serverType); if (!list || !list.length) { cb(new Error(`can not find server info for type:${msg.serverType}`)); return; } const uid = session ? (session.uid || '') : ''; const index = Math.abs(crc.crc32(uid.toString())) % list.length; utils.invokeCallback(cb, null, list[index].id); }
[ "function", "defRoute", "(", "session", ",", "msg", ",", "context", ",", "cb", ")", "{", "const", "list", "=", "context", ".", "getServersByType", "(", "msg", ".", "serverType", ")", ";", "if", "(", "!", "list", "||", "!", "list", ".", "length", ")", "{", "cb", "(", "new", "Error", "(", "`", "${", "msg", ".", "serverType", "}", "`", ")", ")", ";", "return", ";", "}", "const", "uid", "=", "session", "?", "(", "session", ".", "uid", "||", "''", ")", ":", "''", ";", "const", "index", "=", "Math", ".", "abs", "(", "crc", ".", "crc32", "(", "uid", ".", "toString", "(", ")", ")", ")", "%", "list", ".", "length", ";", "utils", ".", "invokeCallback", "(", "cb", ",", "null", ",", "list", "[", "index", "]", ".", "id", ")", ";", "}" ]
Calculate route info and return an appropriate server id. @param session {Object} session object for current rpc request @param msg {Object} rpc message. {serverType, service, method, args, opts} @param context {Object} context of client @param cb(err, serverId)
[ "Calculate", "route", "info", "and", "return", "an", "appropriate", "server", "id", "." ]
eb29e247214148c025456b2bb0542e1094fd2edb
https://github.com/JohnnieFucker/dreamix-rpc/blob/eb29e247214148c025456b2bb0542e1094fd2edb/lib/rpc-client/router.js#L13-L22
50,082
JohnnieFucker/dreamix-rpc
lib/rpc-client/router.js
rdRoute
function rdRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } const index = Math.floor(Math.random() * servers.length); utils.invokeCallback(cb, null, servers[index]); }
javascript
function rdRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } const index = Math.floor(Math.random() * servers.length); utils.invokeCallback(cb, null, servers[index]); }
[ "function", "rdRoute", "(", "client", ",", "serverType", ",", "msg", ",", "cb", ")", "{", "const", "servers", "=", "client", ".", "_station", ".", "serversMap", "[", "serverType", "]", ";", "if", "(", "!", "servers", "||", "!", "servers", ".", "length", ")", "{", "utils", ".", "invokeCallback", "(", "cb", ",", "new", "Error", "(", "`", "${", "serverType", "}", "`", ")", ")", ";", "return", ";", "}", "const", "index", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "servers", ".", "length", ")", ";", "utils", ".", "invokeCallback", "(", "cb", ",", "null", ",", "servers", "[", "index", "]", ")", ";", "}" ]
Random algorithm for calculating server id. @param client {Object} rpc client. @param serverType {String} rpc target serverType. @param msg {Object} rpc message. @param cb {Function} cb(err, serverId).
[ "Random", "algorithm", "for", "calculating", "server", "id", "." ]
eb29e247214148c025456b2bb0542e1094fd2edb
https://github.com/JohnnieFucker/dreamix-rpc/blob/eb29e247214148c025456b2bb0542e1094fd2edb/lib/rpc-client/router.js#L32-L40
50,083
JohnnieFucker/dreamix-rpc
lib/rpc-client/router.js
rrRoute
function rrRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } let index; if (!client.rrParam) { client.rrParam = {}; } if (client.rrParam[serverType]) { index = client.rrParam[serverType]; } else { index = 0; } utils.invokeCallback(cb, null, servers[index % servers.length]); if (index++ === Number.MAX_VALUE) { index = 0; } client.rrParam[serverType] = index; }
javascript
function rrRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } let index; if (!client.rrParam) { client.rrParam = {}; } if (client.rrParam[serverType]) { index = client.rrParam[serverType]; } else { index = 0; } utils.invokeCallback(cb, null, servers[index % servers.length]); if (index++ === Number.MAX_VALUE) { index = 0; } client.rrParam[serverType] = index; }
[ "function", "rrRoute", "(", "client", ",", "serverType", ",", "msg", ",", "cb", ")", "{", "const", "servers", "=", "client", ".", "_station", ".", "serversMap", "[", "serverType", "]", ";", "if", "(", "!", "servers", "||", "!", "servers", ".", "length", ")", "{", "utils", ".", "invokeCallback", "(", "cb", ",", "new", "Error", "(", "`", "${", "serverType", "}", "`", ")", ")", ";", "return", ";", "}", "let", "index", ";", "if", "(", "!", "client", ".", "rrParam", ")", "{", "client", ".", "rrParam", "=", "{", "}", ";", "}", "if", "(", "client", ".", "rrParam", "[", "serverType", "]", ")", "{", "index", "=", "client", ".", "rrParam", "[", "serverType", "]", ";", "}", "else", "{", "index", "=", "0", ";", "}", "utils", ".", "invokeCallback", "(", "cb", ",", "null", ",", "servers", "[", "index", "%", "servers", ".", "length", "]", ")", ";", "if", "(", "index", "++", "===", "Number", ".", "MAX_VALUE", ")", "{", "index", "=", "0", ";", "}", "client", ".", "rrParam", "[", "serverType", "]", "=", "index", ";", "}" ]
Round-Robin algorithm for calculating server id. @param client {Object} rpc client. @param serverType {String} rpc target serverType. @param msg {Object} rpc message. @param cb {Function} cb(err, serverId).
[ "Round", "-", "Robin", "algorithm", "for", "calculating", "server", "id", "." ]
eb29e247214148c025456b2bb0542e1094fd2edb
https://github.com/JohnnieFucker/dreamix-rpc/blob/eb29e247214148c025456b2bb0542e1094fd2edb/lib/rpc-client/router.js#L50-L70
50,084
JohnnieFucker/dreamix-rpc
lib/rpc-client/router.js
wrrRoute
function wrrRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } let index; let weight; if (!client.wrrParam) { client.wrrParam = {}; } if (client.wrrParam[serverType]) { index = client.wrrParam[serverType].index; weight = client.wrrParam[serverType].weight; } else { index = -1; weight = 0; } const getMaxWeight = () => { let maxWeight = -1; for (let i = 0; i < servers.length; i++) { const server = client._station.servers[servers[i]]; if (!!server.weight && server.weight > maxWeight) { maxWeight = server.weight; } } return maxWeight; }; while (true) { // eslint-disable-line index = (index + 1) % servers.length; if (index === 0) { weight -= 1; if (weight <= 0) { weight = getMaxWeight(); if (weight <= 0) { utils.invokeCallback(cb, new Error('rpc wrr route get invalid weight.')); return; } } } const server = client._station.servers[servers[index]]; if (server.weight >= weight) { client.wrrParam[serverType] = { index: index, weight: weight }; utils.invokeCallback(cb, null, server.id); return; } } }
javascript
function wrrRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } let index; let weight; if (!client.wrrParam) { client.wrrParam = {}; } if (client.wrrParam[serverType]) { index = client.wrrParam[serverType].index; weight = client.wrrParam[serverType].weight; } else { index = -1; weight = 0; } const getMaxWeight = () => { let maxWeight = -1; for (let i = 0; i < servers.length; i++) { const server = client._station.servers[servers[i]]; if (!!server.weight && server.weight > maxWeight) { maxWeight = server.weight; } } return maxWeight; }; while (true) { // eslint-disable-line index = (index + 1) % servers.length; if (index === 0) { weight -= 1; if (weight <= 0) { weight = getMaxWeight(); if (weight <= 0) { utils.invokeCallback(cb, new Error('rpc wrr route get invalid weight.')); return; } } } const server = client._station.servers[servers[index]]; if (server.weight >= weight) { client.wrrParam[serverType] = { index: index, weight: weight }; utils.invokeCallback(cb, null, server.id); return; } } }
[ "function", "wrrRoute", "(", "client", ",", "serverType", ",", "msg", ",", "cb", ")", "{", "const", "servers", "=", "client", ".", "_station", ".", "serversMap", "[", "serverType", "]", ";", "if", "(", "!", "servers", "||", "!", "servers", ".", "length", ")", "{", "utils", ".", "invokeCallback", "(", "cb", ",", "new", "Error", "(", "`", "${", "serverType", "}", "`", ")", ")", ";", "return", ";", "}", "let", "index", ";", "let", "weight", ";", "if", "(", "!", "client", ".", "wrrParam", ")", "{", "client", ".", "wrrParam", "=", "{", "}", ";", "}", "if", "(", "client", ".", "wrrParam", "[", "serverType", "]", ")", "{", "index", "=", "client", ".", "wrrParam", "[", "serverType", "]", ".", "index", ";", "weight", "=", "client", ".", "wrrParam", "[", "serverType", "]", ".", "weight", ";", "}", "else", "{", "index", "=", "-", "1", ";", "weight", "=", "0", ";", "}", "const", "getMaxWeight", "=", "(", ")", "=>", "{", "let", "maxWeight", "=", "-", "1", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "servers", ".", "length", ";", "i", "++", ")", "{", "const", "server", "=", "client", ".", "_station", ".", "servers", "[", "servers", "[", "i", "]", "]", ";", "if", "(", "!", "!", "server", ".", "weight", "&&", "server", ".", "weight", ">", "maxWeight", ")", "{", "maxWeight", "=", "server", ".", "weight", ";", "}", "}", "return", "maxWeight", ";", "}", ";", "while", "(", "true", ")", "{", "// eslint-disable-line", "index", "=", "(", "index", "+", "1", ")", "%", "servers", ".", "length", ";", "if", "(", "index", "===", "0", ")", "{", "weight", "-=", "1", ";", "if", "(", "weight", "<=", "0", ")", "{", "weight", "=", "getMaxWeight", "(", ")", ";", "if", "(", "weight", "<=", "0", ")", "{", "utils", ".", "invokeCallback", "(", "cb", ",", "new", "Error", "(", "'rpc wrr route get invalid weight.'", ")", ")", ";", "return", ";", "}", "}", "}", "const", "server", "=", "client", ".", "_station", ".", "servers", "[", "servers", "[", "index", "]", "]", ";", "if", "(", "server", ".", "weight", ">=", "weight", ")", "{", "client", ".", "wrrParam", "[", "serverType", "]", "=", "{", "index", ":", "index", ",", "weight", ":", "weight", "}", ";", "utils", ".", "invokeCallback", "(", "cb", ",", "null", ",", "server", ".", "id", ")", ";", "return", ";", "}", "}", "}" ]
Weight-Round-Robin algorithm for calculating server id. @param client {Object} rpc client. @param serverType {String} rpc target serverType. @param msg {Object} rpc message. @param cb {Function} cb(err, serverId).
[ "Weight", "-", "Round", "-", "Robin", "algorithm", "for", "calculating", "server", "id", "." ]
eb29e247214148c025456b2bb0542e1094fd2edb
https://github.com/JohnnieFucker/dreamix-rpc/blob/eb29e247214148c025456b2bb0542e1094fd2edb/lib/rpc-client/router.js#L80-L127
50,085
JohnnieFucker/dreamix-rpc
lib/rpc-client/router.js
laRoute
function laRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } const actives = []; if (!client.laParam) { client.laParam = {}; } if (client.laParam[serverType]) { for (let j = 0; j < servers.length; j++) { let count = client.laParam[serverType][servers[j]]; if (!count) { count = 0; client.laParam[servers[j]] = 0; } actives.push(count); } } else { client.laParam[serverType] = {}; for (let i = 0; i < servers.length; i++) { client.laParam[serverType][servers[i]] = 0; actives.push(0); } } let rs = []; let minInvoke = Number.MAX_VALUE; for (let k = 0; k < actives.length; k++) { if (actives[k] < minInvoke) { minInvoke = actives[k]; rs = []; rs.push(servers[k]); } else if (actives[k] === minInvoke) { rs.push(servers[k]); } } const index = Math.floor(Math.random() * rs.length); const serverId = rs[index]; client.laParam[serverType][serverId] += 1; utils.invokeCallback(cb, null, serverId); }
javascript
function laRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } const actives = []; if (!client.laParam) { client.laParam = {}; } if (client.laParam[serverType]) { for (let j = 0; j < servers.length; j++) { let count = client.laParam[serverType][servers[j]]; if (!count) { count = 0; client.laParam[servers[j]] = 0; } actives.push(count); } } else { client.laParam[serverType] = {}; for (let i = 0; i < servers.length; i++) { client.laParam[serverType][servers[i]] = 0; actives.push(0); } } let rs = []; let minInvoke = Number.MAX_VALUE; for (let k = 0; k < actives.length; k++) { if (actives[k] < minInvoke) { minInvoke = actives[k]; rs = []; rs.push(servers[k]); } else if (actives[k] === minInvoke) { rs.push(servers[k]); } } const index = Math.floor(Math.random() * rs.length); const serverId = rs[index]; client.laParam[serverType][serverId] += 1; utils.invokeCallback(cb, null, serverId); }
[ "function", "laRoute", "(", "client", ",", "serverType", ",", "msg", ",", "cb", ")", "{", "const", "servers", "=", "client", ".", "_station", ".", "serversMap", "[", "serverType", "]", ";", "if", "(", "!", "servers", "||", "!", "servers", ".", "length", ")", "{", "utils", ".", "invokeCallback", "(", "cb", ",", "new", "Error", "(", "`", "${", "serverType", "}", "`", ")", ")", ";", "return", ";", "}", "const", "actives", "=", "[", "]", ";", "if", "(", "!", "client", ".", "laParam", ")", "{", "client", ".", "laParam", "=", "{", "}", ";", "}", "if", "(", "client", ".", "laParam", "[", "serverType", "]", ")", "{", "for", "(", "let", "j", "=", "0", ";", "j", "<", "servers", ".", "length", ";", "j", "++", ")", "{", "let", "count", "=", "client", ".", "laParam", "[", "serverType", "]", "[", "servers", "[", "j", "]", "]", ";", "if", "(", "!", "count", ")", "{", "count", "=", "0", ";", "client", ".", "laParam", "[", "servers", "[", "j", "]", "]", "=", "0", ";", "}", "actives", ".", "push", "(", "count", ")", ";", "}", "}", "else", "{", "client", ".", "laParam", "[", "serverType", "]", "=", "{", "}", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "servers", ".", "length", ";", "i", "++", ")", "{", "client", ".", "laParam", "[", "serverType", "]", "[", "servers", "[", "i", "]", "]", "=", "0", ";", "actives", ".", "push", "(", "0", ")", ";", "}", "}", "let", "rs", "=", "[", "]", ";", "let", "minInvoke", "=", "Number", ".", "MAX_VALUE", ";", "for", "(", "let", "k", "=", "0", ";", "k", "<", "actives", ".", "length", ";", "k", "++", ")", "{", "if", "(", "actives", "[", "k", "]", "<", "minInvoke", ")", "{", "minInvoke", "=", "actives", "[", "k", "]", ";", "rs", "=", "[", "]", ";", "rs", ".", "push", "(", "servers", "[", "k", "]", ")", ";", "}", "else", "if", "(", "actives", "[", "k", "]", "===", "minInvoke", ")", "{", "rs", ".", "push", "(", "servers", "[", "k", "]", ")", ";", "}", "}", "const", "index", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "rs", ".", "length", ")", ";", "const", "serverId", "=", "rs", "[", "index", "]", ";", "client", ".", "laParam", "[", "serverType", "]", "[", "serverId", "]", "+=", "1", ";", "utils", ".", "invokeCallback", "(", "cb", ",", "null", ",", "serverId", ")", ";", "}" ]
Least-Active algorithm for calculating server id. @param client {Object} rpc client. @param serverType {String} rpc target serverType. @param msg {Object} rpc message. @param cb {Function} cb(err, serverId).
[ "Least", "-", "Active", "algorithm", "for", "calculating", "server", "id", "." ]
eb29e247214148c025456b2bb0542e1094fd2edb
https://github.com/JohnnieFucker/dreamix-rpc/blob/eb29e247214148c025456b2bb0542e1094fd2edb/lib/rpc-client/router.js#L137-L178
50,086
JohnnieFucker/dreamix-rpc
lib/rpc-client/router.js
chRoute
function chRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } let con; if (!client.chParam) { client.chParam = {}; } if (client.chParam[serverType]) { con = client.chParam[serverType].consistentHash; } else { client.opts.station = client._station; con = new ConsistentHash(servers, client.opts); } const hashFieldIndex = client.opts.hashFieldIndex; const field = msg.args[hashFieldIndex] || JSON.stringify(msg); utils.invokeCallback(cb, null, con.getNode(field)); client.chParam[serverType] = { consistentHash: con }; }
javascript
function chRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } let con; if (!client.chParam) { client.chParam = {}; } if (client.chParam[serverType]) { con = client.chParam[serverType].consistentHash; } else { client.opts.station = client._station; con = new ConsistentHash(servers, client.opts); } const hashFieldIndex = client.opts.hashFieldIndex; const field = msg.args[hashFieldIndex] || JSON.stringify(msg); utils.invokeCallback(cb, null, con.getNode(field)); client.chParam[serverType] = { consistentHash: con }; }
[ "function", "chRoute", "(", "client", ",", "serverType", ",", "msg", ",", "cb", ")", "{", "const", "servers", "=", "client", ".", "_station", ".", "serversMap", "[", "serverType", "]", ";", "if", "(", "!", "servers", "||", "!", "servers", ".", "length", ")", "{", "utils", ".", "invokeCallback", "(", "cb", ",", "new", "Error", "(", "`", "${", "serverType", "}", "`", ")", ")", ";", "return", ";", "}", "let", "con", ";", "if", "(", "!", "client", ".", "chParam", ")", "{", "client", ".", "chParam", "=", "{", "}", ";", "}", "if", "(", "client", ".", "chParam", "[", "serverType", "]", ")", "{", "con", "=", "client", ".", "chParam", "[", "serverType", "]", ".", "consistentHash", ";", "}", "else", "{", "client", ".", "opts", ".", "station", "=", "client", ".", "_station", ";", "con", "=", "new", "ConsistentHash", "(", "servers", ",", "client", ".", "opts", ")", ";", "}", "const", "hashFieldIndex", "=", "client", ".", "opts", ".", "hashFieldIndex", ";", "const", "field", "=", "msg", ".", "args", "[", "hashFieldIndex", "]", "||", "JSON", ".", "stringify", "(", "msg", ")", ";", "utils", ".", "invokeCallback", "(", "cb", ",", "null", ",", "con", ".", "getNode", "(", "field", ")", ")", ";", "client", ".", "chParam", "[", "serverType", "]", "=", "{", "consistentHash", ":", "con", "}", ";", "}" ]
Consistent-Hash algorithm for calculating server id. @param client {Object} rpc client. @param serverType {String} rpc target serverType. @param msg {Object} rpc message. @param cb {Function} cb(err, serverId).
[ "Consistent", "-", "Hash", "algorithm", "for", "calculating", "server", "id", "." ]
eb29e247214148c025456b2bb0542e1094fd2edb
https://github.com/JohnnieFucker/dreamix-rpc/blob/eb29e247214148c025456b2bb0542e1094fd2edb/lib/rpc-client/router.js#L188-L208
50,087
demmer/validate-options
lib/validate-options.js
isValid
function isValid(options, key) { var value = _.isFunction(options) ? options(key) : options[key]; if (typeof value === 'undefined') { return false; } if (value === null) { return false; } if (value === '') { return false; } if (_.isNaN(value)) { return false; } return true; }
javascript
function isValid(options, key) { var value = _.isFunction(options) ? options(key) : options[key]; if (typeof value === 'undefined') { return false; } if (value === null) { return false; } if (value === '') { return false; } if (_.isNaN(value)) { return false; } return true; }
[ "function", "isValid", "(", "options", ",", "key", ")", "{", "var", "value", "=", "_", ".", "isFunction", "(", "options", ")", "?", "options", "(", "key", ")", ":", "options", "[", "key", "]", ";", "if", "(", "typeof", "value", "===", "'undefined'", ")", "{", "return", "false", ";", "}", "if", "(", "value", "===", "null", ")", "{", "return", "false", ";", "}", "if", "(", "value", "===", "''", ")", "{", "return", "false", ";", "}", "if", "(", "_", ".", "isNaN", "(", "value", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check if the specified option is valid.
[ "Check", "if", "the", "specified", "option", "is", "valid", "." ]
af18816366adca0b6da7347dcb31b9336b862a6d
https://github.com/demmer/validate-options/blob/af18816366adca0b6da7347dcb31b9336b862a6d/lib/validate-options.js#L11-L31
50,088
jsekamane/Cree
cree.js
function(user, stage, method){ switch (method) { case 'withinRooms': var room = user.getRoom(); if(stageCount(stage, room) == room.size) { console.log("Finished syncronising in " + room.name + ". Enough members in stage " + stage); // Once all members are present start experiment for(var key in room.getMembers(true)) { user = cloak.getUser(room.getMembers(true)[key].id); nextStage(user); } } break; case 'acrossRooms': default: if(stageCount(stage) == members.length) { console.log("Finished syncronising. Enough members in stage " + stage); // Once all members are present start experiment for(var key in members) { user = cloak.getUser(members[key]); nextStage(user); } } break; } }
javascript
function(user, stage, method){ switch (method) { case 'withinRooms': var room = user.getRoom(); if(stageCount(stage, room) == room.size) { console.log("Finished syncronising in " + room.name + ". Enough members in stage " + stage); // Once all members are present start experiment for(var key in room.getMembers(true)) { user = cloak.getUser(room.getMembers(true)[key].id); nextStage(user); } } break; case 'acrossRooms': default: if(stageCount(stage) == members.length) { console.log("Finished syncronising. Enough members in stage " + stage); // Once all members are present start experiment for(var key in members) { user = cloak.getUser(members[key]); nextStage(user); } } break; } }
[ "function", "(", "user", ",", "stage", ",", "method", ")", "{", "switch", "(", "method", ")", "{", "case", "'withinRooms'", ":", "var", "room", "=", "user", ".", "getRoom", "(", ")", ";", "if", "(", "stageCount", "(", "stage", ",", "room", ")", "==", "room", ".", "size", ")", "{", "console", ".", "log", "(", "\"Finished syncronising in \"", "+", "room", ".", "name", "+", "\". Enough members in stage \"", "+", "stage", ")", ";", "// Once all members are present start experiment", "for", "(", "var", "key", "in", "room", ".", "getMembers", "(", "true", ")", ")", "{", "user", "=", "cloak", ".", "getUser", "(", "room", ".", "getMembers", "(", "true", ")", "[", "key", "]", ".", "id", ")", ";", "nextStage", "(", "user", ")", ";", "}", "}", "break", ";", "case", "'acrossRooms'", ":", "default", ":", "if", "(", "stageCount", "(", "stage", ")", "==", "members", ".", "length", ")", "{", "console", ".", "log", "(", "\"Finished syncronising. Enough members in stage \"", "+", "stage", ")", ";", "// Once all members are present start experiment", "for", "(", "var", "key", "in", "members", ")", "{", "user", "=", "cloak", ".", "getUser", "(", "members", "[", "key", "]", ")", ";", "nextStage", "(", "user", ")", ";", "}", "}", "break", ";", "}", "}" ]
Syncronise user stages. E.g. wait for other users to catch up to the waiting stage.
[ "Syncronise", "user", "stages", ".", "E", ".", "g", ".", "wait", "for", "other", "users", "to", "catch", "up", "to", "the", "waiting", "stage", "." ]
ccff87d4bb5b95c8d96c44731033f29a82df871e
https://github.com/jsekamane/Cree/blob/ccff87d4bb5b95c8d96c44731033f29a82df871e/cree.js#L161-L190
50,089
jsekamane/Cree
cree.js
function(stage, room) { i = 0; var stagemembers = (typeof room === 'undefined') ? members : _.pluck(room.getMembers(true), 'id'); for(var key in stagemembers) if(cloak.getUser(stagemembers[key]).data._stage == stage) i++; return i; }
javascript
function(stage, room) { i = 0; var stagemembers = (typeof room === 'undefined') ? members : _.pluck(room.getMembers(true), 'id'); for(var key in stagemembers) if(cloak.getUser(stagemembers[key]).data._stage == stage) i++; return i; }
[ "function", "(", "stage", ",", "room", ")", "{", "i", "=", "0", ";", "var", "stagemembers", "=", "(", "typeof", "room", "===", "'undefined'", ")", "?", "members", ":", "_", ".", "pluck", "(", "room", ".", "getMembers", "(", "true", ")", ",", "'id'", ")", ";", "for", "(", "var", "key", "in", "stagemembers", ")", "if", "(", "cloak", ".", "getUser", "(", "stagemembers", "[", "key", "]", ")", ".", "data", ".", "_stage", "==", "stage", ")", "i", "++", ";", "return", "i", ";", "}" ]
Counts and returns the number of users in a particular stage.
[ "Counts", "and", "returns", "the", "number", "of", "users", "in", "a", "particular", "stage", "." ]
ccff87d4bb5b95c8d96c44731033f29a82df871e
https://github.com/jsekamane/Cree/blob/ccff87d4bb5b95c8d96c44731033f29a82df871e/cree.js#L193-L200
50,090
jsekamane/Cree
cree.js
function(url) { i = 0; for(var key in members) if(cloak.getUser(members[key]).data._load == url) i++; return i; }
javascript
function(url) { i = 0; for(var key in members) if(cloak.getUser(members[key]).data._load == url) i++; return i; }
[ "function", "(", "url", ")", "{", "i", "=", "0", ";", "for", "(", "var", "key", "in", "members", ")", "if", "(", "cloak", ".", "getUser", "(", "members", "[", "key", "]", ")", ".", "data", ".", "_load", "==", "url", ")", "i", "++", ";", "return", "i", ";", "}" ]
Counts and returns the number of users in a particular url.
[ "Counts", "and", "returns", "the", "number", "of", "users", "in", "a", "particular", "url", "." ]
ccff87d4bb5b95c8d96c44731033f29a82df871e
https://github.com/jsekamane/Cree/blob/ccff87d4bb5b95c8d96c44731033f29a82df871e/cree.js#L204-L210
50,091
jsekamane/Cree
cree.js
function(user){ // First time nextStage() is called set the stage to zero. Otherwise keep track when continuing to the next stage user.data._stage = (typeof user.data._stage === 'undefined') ? 0 : user.data._stage+1; // Next stage is which type? var type = (typeof experiment.stages[user.data._stage].type === 'undefined') ? null : experiment.stages[user.data._stage].type; // 'undefined' set to null. switch (type) { // Static page. User does not have to wait but can continue to next stage on his/her own. case null: case 'static': var stage = experiment.stages[user.data._stage]; // stage in json file load(user, stage.url); break; // Syncronise users. Such that they proceed, as a group, to the next stage. case 'sync': load(user, experiment.stages[user.data._stage].url); // load waiting stage syncStage(user, user.data._stage, experiment.stages[user.data._stage].method); // syncronise users (wait for others) break; case 'randomise': // We only want to randomise once. So we do it when the first user enters the stage. if(stageCount(user.data._stage) == 1) { randomRooms(experiment.stages[user.data._stage].method); } nextStage(user); break; } }
javascript
function(user){ // First time nextStage() is called set the stage to zero. Otherwise keep track when continuing to the next stage user.data._stage = (typeof user.data._stage === 'undefined') ? 0 : user.data._stage+1; // Next stage is which type? var type = (typeof experiment.stages[user.data._stage].type === 'undefined') ? null : experiment.stages[user.data._stage].type; // 'undefined' set to null. switch (type) { // Static page. User does not have to wait but can continue to next stage on his/her own. case null: case 'static': var stage = experiment.stages[user.data._stage]; // stage in json file load(user, stage.url); break; // Syncronise users. Such that they proceed, as a group, to the next stage. case 'sync': load(user, experiment.stages[user.data._stage].url); // load waiting stage syncStage(user, user.data._stage, experiment.stages[user.data._stage].method); // syncronise users (wait for others) break; case 'randomise': // We only want to randomise once. So we do it when the first user enters the stage. if(stageCount(user.data._stage) == 1) { randomRooms(experiment.stages[user.data._stage].method); } nextStage(user); break; } }
[ "function", "(", "user", ")", "{", "// First time nextStage() is called set the stage to zero. Otherwise keep track when continuing to the next stage", "user", ".", "data", ".", "_stage", "=", "(", "typeof", "user", ".", "data", ".", "_stage", "===", "'undefined'", ")", "?", "0", ":", "user", ".", "data", ".", "_stage", "+", "1", ";", "// Next stage is which type?", "var", "type", "=", "(", "typeof", "experiment", ".", "stages", "[", "user", ".", "data", ".", "_stage", "]", ".", "type", "===", "'undefined'", ")", "?", "null", ":", "experiment", ".", "stages", "[", "user", ".", "data", ".", "_stage", "]", ".", "type", ";", "// 'undefined' set to null.", "switch", "(", "type", ")", "{", "// Static page. User does not have to wait but can continue to next stage on his/her own.", "case", "null", ":", "case", "'static'", ":", "var", "stage", "=", "experiment", ".", "stages", "[", "user", ".", "data", ".", "_stage", "]", ";", "// stage in json file", "load", "(", "user", ",", "stage", ".", "url", ")", ";", "break", ";", "// Syncronise users. Such that they proceed, as a group, to the next stage.", "case", "'sync'", ":", "load", "(", "user", ",", "experiment", ".", "stages", "[", "user", ".", "data", ".", "_stage", "]", ".", "url", ")", ";", "// load waiting stage", "syncStage", "(", "user", ",", "user", ".", "data", ".", "_stage", ",", "experiment", ".", "stages", "[", "user", ".", "data", ".", "_stage", "]", ".", "method", ")", ";", "// syncronise users (wait for others)", "break", ";", "case", "'randomise'", ":", "// We only want to randomise once. So we do it when the first user enters the stage.", "if", "(", "stageCount", "(", "user", ".", "data", ".", "_stage", ")", "==", "1", ")", "{", "randomRooms", "(", "experiment", ".", "stages", "[", "user", ".", "data", ".", "_stage", "]", ".", "method", ")", ";", "}", "nextStage", "(", "user", ")", ";", "break", ";", "}", "}" ]
Push the user to the next stage
[ "Push", "the", "user", "to", "the", "next", "stage" ]
ccff87d4bb5b95c8d96c44731033f29a82df871e
https://github.com/jsekamane/Cree/blob/ccff87d4bb5b95c8d96c44731033f29a82df871e/cree.js#L219-L250
50,092
jsekamane/Cree
cree.js
function(){ console.log("Last user has finished the experiment!"); var userdata = new Object(); for(var key in cloak.getUsers()) { cloak.getUsers()[key].data.device = parser.setUA(cloak.getUsers()[key].data._device).getResult(); // Parse the useragent before saving data. userdata[cloak.getUsers()[key].id] = cloak.getUsers()[key].data; } // Alternatively consider using async.series or RSVP.Promise. var saveDataSuccess = saveExperimentSuccess = saveLogSucess = saveIPSucess= false; var successSave = function (){ if(saveDataSuccess && saveExperimentSuccess && saveLogSucess && saveIPSucess) { // quit proccess console.log(typeof cloak); cloak.stop(function(){ console.log(" -- server closed -- "); process.exit(0); // quit node.js process with succes }) } } // Save user IPs if requireUniqueIP == TRUE, such that when running continues experiments (forever start xxx.js) users can only participate once. // TO-DO /*if(requireUniqueIP) { var experimentConfig = JSON.parse(fs.readFileSync(experimentURL[0], experimentURL[1])); for(var key in cloak.getUsers()) { experimentConfig.ExcludeIPs.push(cloak.getUsers()[key].data.ip); } fs.writeFileSync(experimentURL[0], JSON.stringify(experimentConfig, null, '\t')); console.log(experimentURL[0]); saveIPSucess = true; successSave(); } else { saveIPSucess = true; successSave(); }*/ saveIPSucess = true; // Save user data. fs.writeFile('data/data_'+initTime.valueOf()+'_user.json', JSON.stringify(userdata,null,'\t'), function (err) { if (err) return console.log(err); console.log('data_'+initTime.valueOf()+'_user.json'); saveDataSuccess = true; successSave(); }); // Save additional experiment data. experiment.initTime = initTime.valueOf(); experiment.timeFinalGlobal = timeGlobal.getValue(); var experimentdata = experiment; fs.writeFile('data/data_'+initTime.valueOf()+'_experiment.json', JSON.stringify(experimentdata,null,'\t'), function (err) { if (err) return console.log(err); console.log('data_'+initTime.valueOf()+'_experiment.json'); saveExperimentSuccess = true; successSave(); }); // Save log of all messages send by the users. fs.writeFile('data/data_'+initTime.valueOf()+'_messages.json', JSON.stringify(storeMessage,null,'\t'), function (err) { if (err) return console.log(err); console.log('data_'+initTime.valueOf()+'_message.json'); saveLogSucess = true; successSave(); }); }
javascript
function(){ console.log("Last user has finished the experiment!"); var userdata = new Object(); for(var key in cloak.getUsers()) { cloak.getUsers()[key].data.device = parser.setUA(cloak.getUsers()[key].data._device).getResult(); // Parse the useragent before saving data. userdata[cloak.getUsers()[key].id] = cloak.getUsers()[key].data; } // Alternatively consider using async.series or RSVP.Promise. var saveDataSuccess = saveExperimentSuccess = saveLogSucess = saveIPSucess= false; var successSave = function (){ if(saveDataSuccess && saveExperimentSuccess && saveLogSucess && saveIPSucess) { // quit proccess console.log(typeof cloak); cloak.stop(function(){ console.log(" -- server closed -- "); process.exit(0); // quit node.js process with succes }) } } // Save user IPs if requireUniqueIP == TRUE, such that when running continues experiments (forever start xxx.js) users can only participate once. // TO-DO /*if(requireUniqueIP) { var experimentConfig = JSON.parse(fs.readFileSync(experimentURL[0], experimentURL[1])); for(var key in cloak.getUsers()) { experimentConfig.ExcludeIPs.push(cloak.getUsers()[key].data.ip); } fs.writeFileSync(experimentURL[0], JSON.stringify(experimentConfig, null, '\t')); console.log(experimentURL[0]); saveIPSucess = true; successSave(); } else { saveIPSucess = true; successSave(); }*/ saveIPSucess = true; // Save user data. fs.writeFile('data/data_'+initTime.valueOf()+'_user.json', JSON.stringify(userdata,null,'\t'), function (err) { if (err) return console.log(err); console.log('data_'+initTime.valueOf()+'_user.json'); saveDataSuccess = true; successSave(); }); // Save additional experiment data. experiment.initTime = initTime.valueOf(); experiment.timeFinalGlobal = timeGlobal.getValue(); var experimentdata = experiment; fs.writeFile('data/data_'+initTime.valueOf()+'_experiment.json', JSON.stringify(experimentdata,null,'\t'), function (err) { if (err) return console.log(err); console.log('data_'+initTime.valueOf()+'_experiment.json'); saveExperimentSuccess = true; successSave(); }); // Save log of all messages send by the users. fs.writeFile('data/data_'+initTime.valueOf()+'_messages.json', JSON.stringify(storeMessage,null,'\t'), function (err) { if (err) return console.log(err); console.log('data_'+initTime.valueOf()+'_message.json'); saveLogSucess = true; successSave(); }); }
[ "function", "(", ")", "{", "console", ".", "log", "(", "\"Last user has finished the experiment!\"", ")", ";", "var", "userdata", "=", "new", "Object", "(", ")", ";", "for", "(", "var", "key", "in", "cloak", ".", "getUsers", "(", ")", ")", "{", "cloak", ".", "getUsers", "(", ")", "[", "key", "]", ".", "data", ".", "device", "=", "parser", ".", "setUA", "(", "cloak", ".", "getUsers", "(", ")", "[", "key", "]", ".", "data", ".", "_device", ")", ".", "getResult", "(", ")", ";", "// Parse the useragent before saving data.", "userdata", "[", "cloak", ".", "getUsers", "(", ")", "[", "key", "]", ".", "id", "]", "=", "cloak", ".", "getUsers", "(", ")", "[", "key", "]", ".", "data", ";", "}", "// Alternatively consider using async.series or RSVP.Promise.", "var", "saveDataSuccess", "=", "saveExperimentSuccess", "=", "saveLogSucess", "=", "saveIPSucess", "=", "false", ";", "var", "successSave", "=", "function", "(", ")", "{", "if", "(", "saveDataSuccess", "&&", "saveExperimentSuccess", "&&", "saveLogSucess", "&&", "saveIPSucess", ")", "{", "// quit proccess", "console", ".", "log", "(", "typeof", "cloak", ")", ";", "cloak", ".", "stop", "(", "function", "(", ")", "{", "console", ".", "log", "(", "\" -- server closed -- \"", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "// quit node.js process with succes", "}", ")", "}", "}", "// Save user IPs if requireUniqueIP == TRUE, such that when running continues experiments (forever start xxx.js) users can only participate once.", "// TO-DO", "/*if(requireUniqueIP) {\n\t\t\tvar experimentConfig = JSON.parse(fs.readFileSync(experimentURL[0], experimentURL[1]));\n\t\t\tfor(var key in cloak.getUsers()) {\n\t\t\t\texperimentConfig.ExcludeIPs.push(cloak.getUsers()[key].data.ip);\n\t\t\t}\n\t\t\tfs.writeFileSync(experimentURL[0], JSON.stringify(experimentConfig, null, '\\t'));\n\t\t\tconsole.log(experimentURL[0]);\n\t\t\tsaveIPSucess = true;\n\t\t\tsuccessSave();\n\t\t} else {\n\t\t\tsaveIPSucess = true;\n\t\t\tsuccessSave();\n\t\t}*/", "saveIPSucess", "=", "true", ";", "// Save user data.", "fs", ".", "writeFile", "(", "'data/data_'", "+", "initTime", ".", "valueOf", "(", ")", "+", "'_user.json'", ",", "JSON", ".", "stringify", "(", "userdata", ",", "null", ",", "'\\t'", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "console", ".", "log", "(", "err", ")", ";", "console", ".", "log", "(", "'data_'", "+", "initTime", ".", "valueOf", "(", ")", "+", "'_user.json'", ")", ";", "saveDataSuccess", "=", "true", ";", "successSave", "(", ")", ";", "}", ")", ";", "// Save additional experiment data.", "experiment", ".", "initTime", "=", "initTime", ".", "valueOf", "(", ")", ";", "experiment", ".", "timeFinalGlobal", "=", "timeGlobal", ".", "getValue", "(", ")", ";", "var", "experimentdata", "=", "experiment", ";", "fs", ".", "writeFile", "(", "'data/data_'", "+", "initTime", ".", "valueOf", "(", ")", "+", "'_experiment.json'", ",", "JSON", ".", "stringify", "(", "experimentdata", ",", "null", ",", "'\\t'", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "console", ".", "log", "(", "err", ")", ";", "console", ".", "log", "(", "'data_'", "+", "initTime", ".", "valueOf", "(", ")", "+", "'_experiment.json'", ")", ";", "saveExperimentSuccess", "=", "true", ";", "successSave", "(", ")", ";", "}", ")", ";", "// Save log of all messages send by the users.", "fs", ".", "writeFile", "(", "'data/data_'", "+", "initTime", ".", "valueOf", "(", ")", "+", "'_messages.json'", ",", "JSON", ".", "stringify", "(", "storeMessage", ",", "null", ",", "'\\t'", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "console", ".", "log", "(", "err", ")", ";", "console", ".", "log", "(", "'data_'", "+", "initTime", ".", "valueOf", "(", ")", "+", "'_message.json'", ")", ";", "saveLogSucess", "=", "true", ";", "successSave", "(", ")", ";", "}", ")", ";", "}" ]
Finalize the experiment
[ "Finalize", "the", "experiment" ]
ccff87d4bb5b95c8d96c44731033f29a82df871e
https://github.com/jsekamane/Cree/blob/ccff87d4bb5b95c8d96c44731033f29a82df871e/cree.js#L324-L395
50,093
jsekamane/Cree
cree.js
function(ip) { var unique = true; for(var key in cloak.getLobby().getMembers()) { if(ip == cloak.getLobby().getMembers()[key].data.ip) unique = false; } return unique; }
javascript
function(ip) { var unique = true; for(var key in cloak.getLobby().getMembers()) { if(ip == cloak.getLobby().getMembers()[key].data.ip) unique = false; } return unique; }
[ "function", "(", "ip", ")", "{", "var", "unique", "=", "true", ";", "for", "(", "var", "key", "in", "cloak", ".", "getLobby", "(", ")", ".", "getMembers", "(", ")", ")", "{", "if", "(", "ip", "==", "cloak", ".", "getLobby", "(", ")", ".", "getMembers", "(", ")", "[", "key", "]", ".", "data", ".", "ip", ")", "unique", "=", "false", ";", "}", "return", "unique", ";", "}" ]
Check if user has same IP as a user in the lobby.
[ "Check", "if", "user", "has", "same", "IP", "as", "a", "user", "in", "the", "lobby", "." ]
ccff87d4bb5b95c8d96c44731033f29a82df871e
https://github.com/jsekamane/Cree/blob/ccff87d4bb5b95c8d96c44731033f29a82df871e/cree.js#L420-L427
50,094
fernandofranca/launchpod
lib/repl-socket-server.js
start
function start(config, setDefaultREPLCommands, getAppInstance) { // Defines the IPC socket file path var socketAddr = path.join(process.cwd(), 'socket-ctl'); // Deletes the file if already exists if (fs.existsSync(socketAddr)) fs.unlinkSync(socketAddr); // Create and start the socket server socketServer = net.createServer(function(socket) { if(config.replStartMessage) socket.write(config.replStartMessage+"\n"); // Instantiates a new REPL for this socket var socketReplServer = repl.start({ prompt: config.promptSymbol, eval: replEvaluatorBuilder(getAppInstance()), input: socket, output: socket, writer: replWriter, terminal: true }) .on("exit", () => { socket.end(); }); socket.on("error", (err) => { console.error(err); }); socketReplServer.context.app = getAppInstance(); setDefaultREPLCommands(socketReplServer); }); socketServer.listen(socketAddr); }
javascript
function start(config, setDefaultREPLCommands, getAppInstance) { // Defines the IPC socket file path var socketAddr = path.join(process.cwd(), 'socket-ctl'); // Deletes the file if already exists if (fs.existsSync(socketAddr)) fs.unlinkSync(socketAddr); // Create and start the socket server socketServer = net.createServer(function(socket) { if(config.replStartMessage) socket.write(config.replStartMessage+"\n"); // Instantiates a new REPL for this socket var socketReplServer = repl.start({ prompt: config.promptSymbol, eval: replEvaluatorBuilder(getAppInstance()), input: socket, output: socket, writer: replWriter, terminal: true }) .on("exit", () => { socket.end(); }); socket.on("error", (err) => { console.error(err); }); socketReplServer.context.app = getAppInstance(); setDefaultREPLCommands(socketReplServer); }); socketServer.listen(socketAddr); }
[ "function", "start", "(", "config", ",", "setDefaultREPLCommands", ",", "getAppInstance", ")", "{", "// Defines the IPC socket file path", "var", "socketAddr", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'socket-ctl'", ")", ";", "// Deletes the file if already exists", "if", "(", "fs", ".", "existsSync", "(", "socketAddr", ")", ")", "fs", ".", "unlinkSync", "(", "socketAddr", ")", ";", "// Create and start the socket server", "socketServer", "=", "net", ".", "createServer", "(", "function", "(", "socket", ")", "{", "if", "(", "config", ".", "replStartMessage", ")", "socket", ".", "write", "(", "config", ".", "replStartMessage", "+", "\"\\n\"", ")", ";", "// Instantiates a new REPL for this socket", "var", "socketReplServer", "=", "repl", ".", "start", "(", "{", "prompt", ":", "config", ".", "promptSymbol", ",", "eval", ":", "replEvaluatorBuilder", "(", "getAppInstance", "(", ")", ")", ",", "input", ":", "socket", ",", "output", ":", "socket", ",", "writer", ":", "replWriter", ",", "terminal", ":", "true", "}", ")", ".", "on", "(", "\"exit\"", ",", "(", ")", "=>", "{", "socket", ".", "end", "(", ")", ";", "}", ")", ";", "socket", ".", "on", "(", "\"error\"", ",", "(", "err", ")", "=>", "{", "console", ".", "error", "(", "err", ")", ";", "}", ")", ";", "socketReplServer", ".", "context", ".", "app", "=", "getAppInstance", "(", ")", ";", "setDefaultREPLCommands", "(", "socketReplServer", ")", ";", "}", ")", ";", "socketServer", ".", "listen", "(", "socketAddr", ")", ";", "}" ]
Starts an IPC socket server Every new socket connection will be piped to a REPL
[ "Starts", "an", "IPC", "socket", "server", "Every", "new", "socket", "connection", "will", "be", "piped", "to", "a", "REPL" ]
882d614a4271846e17b3ba0ca319340a607580bc
https://github.com/fernandofranca/launchpod/blob/882d614a4271846e17b3ba0ca319340a607580bc/lib/repl-socket-server.js#L16-L51
50,095
zland/zland-map
stores/MapStore.js
calculatePositionDiff
function calculatePositionDiff(position) { if (!_lastDiffPosition) { return _lastDiffPosition = position; } var dx, dy, p1, p2; p1 = position; p2 = _lastDiffPosition; dx = p2.x - p1.x; dy = p2.y - p1.y; _calcMoveDiffX += dx; _calcMoveDiffY += dy; _overallMoveDiffY += dy; _overallMoveDiffX += dx; _lastDiffPosition = position; }
javascript
function calculatePositionDiff(position) { if (!_lastDiffPosition) { return _lastDiffPosition = position; } var dx, dy, p1, p2; p1 = position; p2 = _lastDiffPosition; dx = p2.x - p1.x; dy = p2.y - p1.y; _calcMoveDiffX += dx; _calcMoveDiffY += dy; _overallMoveDiffY += dy; _overallMoveDiffX += dx; _lastDiffPosition = position; }
[ "function", "calculatePositionDiff", "(", "position", ")", "{", "if", "(", "!", "_lastDiffPosition", ")", "{", "return", "_lastDiffPosition", "=", "position", ";", "}", "var", "dx", ",", "dy", ",", "p1", ",", "p2", ";", "p1", "=", "position", ";", "p2", "=", "_lastDiffPosition", ";", "dx", "=", "p2", ".", "x", "-", "p1", ".", "x", ";", "dy", "=", "p2", ".", "y", "-", "p1", ".", "y", ";", "_calcMoveDiffX", "+=", "dx", ";", "_calcMoveDiffY", "+=", "dy", ";", "_overallMoveDiffY", "+=", "dy", ";", "_overallMoveDiffX", "+=", "dx", ";", "_lastDiffPosition", "=", "position", ";", "}" ]
position diff methods
[ "position", "diff", "methods" ]
adff5510e3c267ce87e166f0a0354c7a85db8752
https://github.com/zland/zland-map/blob/adff5510e3c267ce87e166f0a0354c7a85db8752/stores/MapStore.js#L220-L234
50,096
Encapsule-Annex/onm-server-rest-routes
routes.js
function(req, res) { var packages = {}; var appJSON = require('../../package.json'); packages[appJSON.name] = appJSON; packages['onm'] = require('../onm/package.json'); res.send(packages); }
javascript
function(req, res) { var packages = {}; var appJSON = require('../../package.json'); packages[appJSON.name] = appJSON; packages['onm'] = require('../onm/package.json'); res.send(packages); }
[ "function", "(", "req", ",", "res", ")", "{", "var", "packages", "=", "{", "}", ";", "var", "appJSON", "=", "require", "(", "'../../package.json'", ")", ";", "packages", "[", "appJSON", ".", "name", "]", "=", "appJSON", ";", "packages", "[", "'onm'", "]", "=", "require", "(", "'../onm/package.json'", ")", ";", "res", ".", "send", "(", "packages", ")", ";", "}" ]
Get basic information about this server endpoint.
[ "Get", "basic", "information", "about", "this", "server", "endpoint", "." ]
2d831d46e13be0191c3562df20b61378bed49ee6
https://github.com/Encapsule-Annex/onm-server-rest-routes/blob/2d831d46e13be0191c3562df20b61378bed49ee6/routes.js#L14-L20
50,097
Encapsule-Annex/onm-server-rest-routes
routes.js
function(req, res) { var stores = []; for (key in onmStoreDictionary) { stores.push({ dataModel: onmStoreDictionary[key].model.jsonTag, storeKey: key }); } res.send(200, stores); }
javascript
function(req, res) { var stores = []; for (key in onmStoreDictionary) { stores.push({ dataModel: onmStoreDictionary[key].model.jsonTag, storeKey: key }); } res.send(200, stores); }
[ "function", "(", "req", ",", "res", ")", "{", "var", "stores", "=", "[", "]", ";", "for", "(", "key", "in", "onmStoreDictionary", ")", "{", "stores", ".", "push", "(", "{", "dataModel", ":", "onmStoreDictionary", "[", "key", "]", ".", "model", ".", "jsonTag", ",", "storeKey", ":", "key", "}", ")", ";", "}", "res", ".", "send", "(", "200", ",", "stores", ")", ";", "}" ]
Enumerate the in-memory onm stores managed by this node instance.
[ "Enumerate", "the", "in", "-", "memory", "onm", "stores", "managed", "by", "this", "node", "instance", "." ]
2d831d46e13be0191c3562df20b61378bed49ee6
https://github.com/Encapsule-Annex/onm-server-rest-routes/blob/2d831d46e13be0191c3562df20b61378bed49ee6/routes.js#L39-L48
50,098
Encapsule-Annex/onm-server-rest-routes
routes.js
function(req, res) { if (!req._body || (req.body == null) || !req.body) { res.send(400, "Invalid POST missing required request body."); return; } if ((req.body.model == null) || !req.body.model) { res.send(400, "Invalid POST missing 'model' property in request body."); return; } var onmDataModelRecord = onmModelDictionary[req.body.model]; if ((onmDataModelRecord == null) || !onmDataModelRecord || (onmDataModelRecord.model == null) || !onmDataModelRecord.model) { res.send(403, "The specified onm data model '" + req.body.model + "' is unsupported by this server."); return; } var storeUuid = uuid.v4(); var store = onmStoreDictionary[storeUuid] = new onm.Store(onmDataModelRecord.model); var storeRecord = { dataModel: store.model.jsonTag, storeKey: storeUuid }; console.log("created in-memory data store '" + storeUuid + "'."); res.send(200, storeRecord); }
javascript
function(req, res) { if (!req._body || (req.body == null) || !req.body) { res.send(400, "Invalid POST missing required request body."); return; } if ((req.body.model == null) || !req.body.model) { res.send(400, "Invalid POST missing 'model' property in request body."); return; } var onmDataModelRecord = onmModelDictionary[req.body.model]; if ((onmDataModelRecord == null) || !onmDataModelRecord || (onmDataModelRecord.model == null) || !onmDataModelRecord.model) { res.send(403, "The specified onm data model '" + req.body.model + "' is unsupported by this server."); return; } var storeUuid = uuid.v4(); var store = onmStoreDictionary[storeUuid] = new onm.Store(onmDataModelRecord.model); var storeRecord = { dataModel: store.model.jsonTag, storeKey: storeUuid }; console.log("created in-memory data store '" + storeUuid + "'."); res.send(200, storeRecord); }
[ "function", "(", "req", ",", "res", ")", "{", "if", "(", "!", "req", ".", "_body", "||", "(", "req", ".", "body", "==", "null", ")", "||", "!", "req", ".", "body", ")", "{", "res", ".", "send", "(", "400", ",", "\"Invalid POST missing required request body.\"", ")", ";", "return", ";", "}", "if", "(", "(", "req", ".", "body", ".", "model", "==", "null", ")", "||", "!", "req", ".", "body", ".", "model", ")", "{", "res", ".", "send", "(", "400", ",", "\"Invalid POST missing 'model' property in request body.\"", ")", ";", "return", ";", "}", "var", "onmDataModelRecord", "=", "onmModelDictionary", "[", "req", ".", "body", ".", "model", "]", ";", "if", "(", "(", "onmDataModelRecord", "==", "null", ")", "||", "!", "onmDataModelRecord", "||", "(", "onmDataModelRecord", ".", "model", "==", "null", ")", "||", "!", "onmDataModelRecord", ".", "model", ")", "{", "res", ".", "send", "(", "403", ",", "\"The specified onm data model '\"", "+", "req", ".", "body", ".", "model", "+", "\"' is unsupported by this server.\"", ")", ";", "return", ";", "}", "var", "storeUuid", "=", "uuid", ".", "v4", "(", ")", ";", "var", "store", "=", "onmStoreDictionary", "[", "storeUuid", "]", "=", "new", "onm", ".", "Store", "(", "onmDataModelRecord", ".", "model", ")", ";", "var", "storeRecord", "=", "{", "dataModel", ":", "store", ".", "model", ".", "jsonTag", ",", "storeKey", ":", "storeUuid", "}", ";", "console", ".", "log", "(", "\"created in-memory data store '\"", "+", "storeUuid", "+", "\"'.\"", ")", ";", "res", ".", "send", "(", "200", ",", "storeRecord", ")", ";", "}" ]
Create a new in-memory data store instance using the the indicated onm data model.
[ "Create", "a", "new", "in", "-", "memory", "data", "store", "instance", "using", "the", "the", "indicated", "onm", "data", "model", "." ]
2d831d46e13be0191c3562df20b61378bed49ee6
https://github.com/Encapsule-Annex/onm-server-rest-routes/blob/2d831d46e13be0191c3562df20b61378bed49ee6/routes.js#L116-L138
50,099
Encapsule-Annex/onm-server-rest-routes
routes.js
function(req, res) { if (!req._body || (req.body == null) || !req.body) { res.send(400, "Invalid POST missing required request body."); return; } if ((req.body.store == null) || !req.body.store) { res.send(400, "Invalid POST mising 'store' property in request body."); return; } if ((req.body.address == null) || !req.body.address) { res.send(400, "Invalid POST missing 'address' property in request body."); return; } var store = onmStoreDictionary[req.body.store]; if ((store == null) || !store) { res.send(404, "The specified onm data store '" + req.body.store + "' does not exist on this server."); return; } var address = undefined try { address = store.model.createAddressFromHashString(req.body.address); } catch (exception) { console.error(exception); res.send(403, "Invalid address '" + req.body.address + "' is outside of the data model's address space."); return; } try { var namespace = store.createComponent(address) var namespaceRecord = {}; namespaceRecord['address'] = namespace.getResolvedAddress().getHashString(); namespaceRecord[address.getModel().jsonTag] = namespace.implementation.dataReference; res.send(200, namespaceRecord); } catch (exception) { res.send(412, exception); } }
javascript
function(req, res) { if (!req._body || (req.body == null) || !req.body) { res.send(400, "Invalid POST missing required request body."); return; } if ((req.body.store == null) || !req.body.store) { res.send(400, "Invalid POST mising 'store' property in request body."); return; } if ((req.body.address == null) || !req.body.address) { res.send(400, "Invalid POST missing 'address' property in request body."); return; } var store = onmStoreDictionary[req.body.store]; if ((store == null) || !store) { res.send(404, "The specified onm data store '" + req.body.store + "' does not exist on this server."); return; } var address = undefined try { address = store.model.createAddressFromHashString(req.body.address); } catch (exception) { console.error(exception); res.send(403, "Invalid address '" + req.body.address + "' is outside of the data model's address space."); return; } try { var namespace = store.createComponent(address) var namespaceRecord = {}; namespaceRecord['address'] = namespace.getResolvedAddress().getHashString(); namespaceRecord[address.getModel().jsonTag] = namespace.implementation.dataReference; res.send(200, namespaceRecord); } catch (exception) { res.send(412, exception); } }
[ "function", "(", "req", ",", "res", ")", "{", "if", "(", "!", "req", ".", "_body", "||", "(", "req", ".", "body", "==", "null", ")", "||", "!", "req", ".", "body", ")", "{", "res", ".", "send", "(", "400", ",", "\"Invalid POST missing required request body.\"", ")", ";", "return", ";", "}", "if", "(", "(", "req", ".", "body", ".", "store", "==", "null", ")", "||", "!", "req", ".", "body", ".", "store", ")", "{", "res", ".", "send", "(", "400", ",", "\"Invalid POST mising 'store' property in request body.\"", ")", ";", "return", ";", "}", "if", "(", "(", "req", ".", "body", ".", "address", "==", "null", ")", "||", "!", "req", ".", "body", ".", "address", ")", "{", "res", ".", "send", "(", "400", ",", "\"Invalid POST missing 'address' property in request body.\"", ")", ";", "return", ";", "}", "var", "store", "=", "onmStoreDictionary", "[", "req", ".", "body", ".", "store", "]", ";", "if", "(", "(", "store", "==", "null", ")", "||", "!", "store", ")", "{", "res", ".", "send", "(", "404", ",", "\"The specified onm data store '\"", "+", "req", ".", "body", ".", "store", "+", "\"' does not exist on this server.\"", ")", ";", "return", ";", "}", "var", "address", "=", "undefined", "try", "{", "address", "=", "store", ".", "model", ".", "createAddressFromHashString", "(", "req", ".", "body", ".", "address", ")", ";", "}", "catch", "(", "exception", ")", "{", "console", ".", "error", "(", "exception", ")", ";", "res", ".", "send", "(", "403", ",", "\"Invalid address '\"", "+", "req", ".", "body", ".", "address", "+", "\"' is outside of the data model's address space.\"", ")", ";", "return", ";", "}", "try", "{", "var", "namespace", "=", "store", ".", "createComponent", "(", "address", ")", "var", "namespaceRecord", "=", "{", "}", ";", "namespaceRecord", "[", "'address'", "]", "=", "namespace", ".", "getResolvedAddress", "(", ")", ".", "getHashString", "(", ")", ";", "namespaceRecord", "[", "address", ".", "getModel", "(", ")", ".", "jsonTag", "]", "=", "namespace", ".", "implementation", ".", "dataReference", ";", "res", ".", "send", "(", "200", ",", "namespaceRecord", ")", ";", "}", "catch", "(", "exception", ")", "{", "res", ".", "send", "(", "412", ",", "exception", ")", ";", "}", "}" ]
Create a new component data resource in the indicated store using the specified address hash to indicate the specific component to create.
[ "Create", "a", "new", "component", "data", "resource", "in", "the", "indicated", "store", "using", "the", "specified", "address", "hash", "to", "indicate", "the", "specific", "component", "to", "create", "." ]
2d831d46e13be0191c3562df20b61378bed49ee6
https://github.com/Encapsule-Annex/onm-server-rest-routes/blob/2d831d46e13be0191c3562df20b61378bed49ee6/routes.js#L143-L178