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
partition
stringclasses
1 value
eivindfjeldstad/textarea-editor
src/editor.js
prefixLength
function prefixLength(text, prefix) { const exp = new RegExp(`^${prefix.pattern}`); return matchLength(text, exp); }
javascript
function prefixLength(text, prefix) { const exp = new RegExp(`^${prefix.pattern}`); return matchLength(text, exp); }
[ "function", "prefixLength", "(", "text", ",", "prefix", ")", "{", "const", "exp", "=", "new", "RegExp", "(", "`", "${", "prefix", ".", "pattern", "}", "`", ")", ";", "return", "matchLength", "(", "text", ",", "exp", ")", ";", "}" ]
Get prefix length. @private
[ "Get", "prefix", "length", "." ]
f3c0183291a014a82b5c7657c282bce727323da7
https://github.com/eivindfjeldstad/textarea-editor/blob/f3c0183291a014a82b5c7657c282bce727323da7/src/editor.js#L323-L326
train
eivindfjeldstad/textarea-editor
src/editor.js
suffixLength
function suffixLength(text, suffix) { let exp = new RegExp(`${suffix.pattern}$`); return matchLength(text, exp); }
javascript
function suffixLength(text, suffix) { let exp = new RegExp(`${suffix.pattern}$`); return matchLength(text, exp); }
[ "function", "suffixLength", "(", "text", ",", "suffix", ")", "{", "let", "exp", "=", "new", "RegExp", "(", "`", "${", "suffix", ".", "pattern", "}", "`", ")", ";", "return", "matchLength", "(", "text", ",", "exp", ")", ";", "}" ]
Get suffix length. @private
[ "Get", "suffix", "length", "." ]
f3c0183291a014a82b5c7657c282bce727323da7
https://github.com/eivindfjeldstad/textarea-editor/blob/f3c0183291a014a82b5c7657c282bce727323da7/src/editor.js#L333-L336
train
eivindfjeldstad/textarea-editor
src/editor.js
normalizeFormat
function normalizeFormat(format) { const clone = Object.assign({}, format); clone.prefix = normalizePrefixSuffix(format.prefix); clone.suffix = normalizePrefixSuffix(format.suffix); return clone; }
javascript
function normalizeFormat(format) { const clone = Object.assign({}, format); clone.prefix = normalizePrefixSuffix(format.prefix); clone.suffix = normalizePrefixSuffix(format.suffix); return clone; }
[ "function", "normalizeFormat", "(", "format", ")", "{", "const", "clone", "=", "Object", ".", "assign", "(", "{", "}", ",", "format", ")", ";", "clone", ".", "prefix", "=", "normalizePrefixSuffix", "(", "format", ".", "prefix", ")", ";", "clone", ".", "suffix", "=", "normalizePrefixSuffix", "(", "format", ".", "suffix", ")", ";", "return", "clone", ";", "}" ]
Normalize format. @private
[ "Normalize", "format", "." ]
f3c0183291a014a82b5c7657c282bce727323da7
https://github.com/eivindfjeldstad/textarea-editor/blob/f3c0183291a014a82b5c7657c282bce727323da7/src/editor.js#L352-L357
train
joshmarinacci/aminogfx
demos/slideshow/slideshow.js
scaleImage
function scaleImage(img,prop,obj) { var scale = Math.min(sw/img.w,sh/img.h); obj.sx(scale).sy(scale); }
javascript
function scaleImage(img,prop,obj) { var scale = Math.min(sw/img.w,sh/img.h); obj.sx(scale).sy(scale); }
[ "function", "scaleImage", "(", "img", ",", "prop", ",", "obj", ")", "{", "var", "scale", "=", "Math", ".", "min", "(", "sw", "/", "img", ".", "w", ",", "sh", "/", "img", ".", "h", ")", ";", "obj", ".", "sx", "(", "scale", ")", ".", "sy", "(", "scale", ")", ";", "}" ]
auto scale them
[ "auto", "scale", "them" ]
bafc6567f3fc3f244d7bff3d6c980fd69750b663
https://github.com/joshmarinacci/aminogfx/blob/bafc6567f3fc3f244d7bff3d6c980fd69750b663/demos/slideshow/slideshow.js#L50-L53
train
joshmarinacci/aminogfx
demos/slideshow/slideshow.js
swap
function swap() { iv1.x.anim().delay(1000).from(0).to(-sw).dur(3000).start(); iv2.x.anim().delay(1000).from(sw).to(0).dur(3000) .then(afterAnim).start(); }
javascript
function swap() { iv1.x.anim().delay(1000).from(0).to(-sw).dur(3000).start(); iv2.x.anim().delay(1000).from(sw).to(0).dur(3000) .then(afterAnim).start(); }
[ "function", "swap", "(", ")", "{", "iv1", ".", "x", ".", "anim", "(", ")", ".", "delay", "(", "1000", ")", ".", "from", "(", "0", ")", ".", "to", "(", "-", "sw", ")", ".", "dur", "(", "3000", ")", ".", "start", "(", ")", ";", "iv2", ".", "x", ".", "anim", "(", ")", ".", "delay", "(", "1000", ")", ".", "from", "(", "sw", ")", ".", "to", "(", "0", ")", ".", "dur", "(", "3000", ")", ".", "then", "(", "afterAnim", ")", ".", "start", "(", ")", ";", "}" ]
animate out and in
[ "animate", "out", "and", "in" ]
bafc6567f3fc3f244d7bff3d6c980fd69750b663
https://github.com/joshmarinacci/aminogfx/blob/bafc6567f3fc3f244d7bff3d6c980fd69750b663/demos/slideshow/slideshow.js#L64-L68
train
joshmarinacci/aminogfx
demos/adsr/adsr.js
updatePolys
function updatePolys() { border.geometry([0,200, adsr.a(),50, adsr.d(),adsr.s(), adsr.r(),adsr.s(), 300,200]); aPoly.geometry([ 0,200, adsr.a(),50, adsr.a(),200 ]); dPoly.geometry([ adsr.a(),200, adsr.a(),50, adsr.d(),adsr.s(), adsr.d(),200, ]); sPoly.geometry([ adsr.d(),200, adsr.d(),adsr.s(), adsr.r(),adsr.s(), adsr.r(),200, ]) rPoly.geometry([ adsr.r(),200, adsr.r(),adsr.s(), 300,200 ]); }
javascript
function updatePolys() { border.geometry([0,200, adsr.a(),50, adsr.d(),adsr.s(), adsr.r(),adsr.s(), 300,200]); aPoly.geometry([ 0,200, adsr.a(),50, adsr.a(),200 ]); dPoly.geometry([ adsr.a(),200, adsr.a(),50, adsr.d(),adsr.s(), adsr.d(),200, ]); sPoly.geometry([ adsr.d(),200, adsr.d(),adsr.s(), adsr.r(),adsr.s(), adsr.r(),200, ]) rPoly.geometry([ adsr.r(),200, adsr.r(),adsr.s(), 300,200 ]); }
[ "function", "updatePolys", "(", ")", "{", "border", ".", "geometry", "(", "[", "0", ",", "200", ",", "adsr", ".", "a", "(", ")", ",", "50", ",", "adsr", ".", "d", "(", ")", ",", "adsr", ".", "s", "(", ")", ",", "adsr", ".", "r", "(", ")", ",", "adsr", ".", "s", "(", ")", ",", "300", ",", "200", "]", ")", ";", "aPoly", ".", "geometry", "(", "[", "0", ",", "200", ",", "adsr", ".", "a", "(", ")", ",", "50", ",", "adsr", ".", "a", "(", ")", ",", "200", "]", ")", ";", "dPoly", ".", "geometry", "(", "[", "adsr", ".", "a", "(", ")", ",", "200", ",", "adsr", ".", "a", "(", ")", ",", "50", ",", "adsr", ".", "d", "(", ")", ",", "adsr", ".", "s", "(", ")", ",", "adsr", ".", "d", "(", ")", ",", "200", ",", "]", ")", ";", "sPoly", ".", "geometry", "(", "[", "adsr", ".", "d", "(", ")", ",", "200", ",", "adsr", ".", "d", "(", ")", ",", "adsr", ".", "s", "(", ")", ",", "adsr", ".", "r", "(", ")", ",", "adsr", ".", "s", "(", ")", ",", "adsr", ".", "r", "(", ")", ",", "200", ",", "]", ")", "rPoly", ".", "geometry", "(", "[", "adsr", ".", "r", "(", ")", ",", "200", ",", "adsr", ".", "r", "(", ")", ",", "adsr", ".", "s", "(", ")", ",", "300", ",", "200", "]", ")", ";", "}" ]
update the polygons when the model changes
[ "update", "the", "polygons", "when", "the", "model", "changes" ]
bafc6567f3fc3f244d7bff3d6c980fd69750b663
https://github.com/joshmarinacci/aminogfx/blob/bafc6567f3fc3f244d7bff3d6c980fd69750b663/demos/adsr/adsr.js#L48-L77
train
nathanboktae/q-xhr
q-xhr.js
extend
function extend(dst) { Array.prototype.forEach.call(arguments, function(obj) { if (obj && obj !== dst) { Object.keys(obj).forEach(function(key) { dst[key] = obj[key] }) } }) return dst }
javascript
function extend(dst) { Array.prototype.forEach.call(arguments, function(obj) { if (obj && obj !== dst) { Object.keys(obj).forEach(function(key) { dst[key] = obj[key] }) } }) return dst }
[ "function", "extend", "(", "dst", ")", "{", "Array", ".", "prototype", ".", "forEach", ".", "call", "(", "arguments", ",", "function", "(", "obj", ")", "{", "if", "(", "obj", "&&", "obj", "!==", "dst", ")", "{", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "dst", "[", "key", "]", "=", "obj", "[", "key", "]", "}", ")", "}", "}", ")", "return", "dst", "}" ]
shallow extend with varargs
[ "shallow", "extend", "with", "varargs" ]
40525e1871b8eec8a9ffaf8e222ede6ec5f389bd
https://github.com/nathanboktae/q-xhr/blob/40525e1871b8eec8a9ffaf8e222ede6ec5f389bd/q-xhr.js#L21-L31
train
herrstucki/sprout
src/hasIn.js
hasIn
function hasIn(obj, keys) { var k = keys[0], ks = keys.slice(1); if (ks.length) return !(k in obj) ? false : hasIn(obj[k], ks); return (k in obj); }
javascript
function hasIn(obj, keys) { var k = keys[0], ks = keys.slice(1); if (ks.length) return !(k in obj) ? false : hasIn(obj[k], ks); return (k in obj); }
[ "function", "hasIn", "(", "obj", ",", "keys", ")", "{", "var", "k", "=", "keys", "[", "0", "]", ",", "ks", "=", "keys", ".", "slice", "(", "1", ")", ";", "if", "(", "ks", ".", "length", ")", "return", "!", "(", "k", "in", "obj", ")", "?", "false", ":", "hasIn", "(", "obj", "[", "k", "]", ",", "ks", ")", ";", "return", "(", "k", "in", "obj", ")", ";", "}" ]
Check if a nested property is present. Currently only used internally
[ "Check", "if", "a", "nested", "property", "is", "present", ".", "Currently", "only", "used", "internally" ]
9bb4697cdf6b84411e0e727683e032ee44b5dd83
https://github.com/herrstucki/sprout/blob/9bb4697cdf6b84411e0e727683e032ee44b5dd83/src/hasIn.js#L3-L8
train
herrstucki/sprout
src/getIn.js
getIn
function getIn(obj, keys, orValue) { var k = keys[0], ks = keys.slice(1); return get(obj, k) && ks.length ? getIn(obj[k], ks, orValue) : get(obj, k, orValue); }
javascript
function getIn(obj, keys, orValue) { var k = keys[0], ks = keys.slice(1); return get(obj, k) && ks.length ? getIn(obj[k], ks, orValue) : get(obj, k, orValue); }
[ "function", "getIn", "(", "obj", ",", "keys", ",", "orValue", ")", "{", "var", "k", "=", "keys", "[", "0", "]", ",", "ks", "=", "keys", ".", "slice", "(", "1", ")", ";", "return", "get", "(", "obj", ",", "k", ")", "&&", "ks", ".", "length", "?", "getIn", "(", "obj", "[", "k", "]", ",", "ks", ",", "orValue", ")", ":", "get", "(", "obj", ",", "k", ",", "orValue", ")", ";", "}" ]
Get value from a nested structure or null.
[ "Get", "value", "from", "a", "nested", "structure", "or", "null", "." ]
9bb4697cdf6b84411e0e727683e032ee44b5dd83
https://github.com/herrstucki/sprout/blob/9bb4697cdf6b84411e0e727683e032ee44b5dd83/src/getIn.js#L4-L8
train
75lb/array-tools
lib/array-tools.js
pluck
function pluck (recordset, property) { recordset = arrayify(recordset) var properties = arrayify(property) return recordset .map(function (record) { for (var i = 0; i < properties.length; i++) { var propValue = objectGet(record, properties[i]) if (propValue) return propValue } }) .filter(function (record) { return typeof record !== 'undefined' }) }
javascript
function pluck (recordset, property) { recordset = arrayify(recordset) var properties = arrayify(property) return recordset .map(function (record) { for (var i = 0; i < properties.length; i++) { var propValue = objectGet(record, properties[i]) if (propValue) return propValue } }) .filter(function (record) { return typeof record !== 'undefined' }) }
[ "function", "pluck", "(", "recordset", ",", "property", ")", "{", "recordset", "=", "arrayify", "(", "recordset", ")", "var", "properties", "=", "arrayify", "(", "property", ")", "return", "recordset", ".", "map", "(", "function", "(", "record", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "properties", ".", "length", ";", "i", "++", ")", "{", "var", "propValue", "=", "objectGet", "(", "record", ",", "properties", "[", "i", "]", ")", "if", "(", "propValue", ")", "return", "propValue", "}", "}", ")", ".", "filter", "(", "function", "(", "record", ")", "{", "return", "typeof", "record", "!==", "'undefined'", "}", ")", "}" ]
Returns an array containing each value plucked from the specified property of each object in the input array. @param recordset {object[]} - The input recordset @param property {string|string[]} - Property name, or an array of property names. If an array is supplied, the first existing property will be returned. @returns {Array} @category chainable @static @example with this data.. ```js > var data = [ { name: "Pavel", nick: "Pasha" }, { name: "Richard", nick: "Dick" }, { name: "Trevor" }, ] ``` pluck all the nicknames ```js > a.pluck(data, "nick") [ 'Pasha', 'Dick' ] ``` in the case no nickname exists, take the name instead: ```js > a.pluck(data, [ "nick", "name" ]) [ 'Pasha', 'Dick', 'Trevor' ] ``` the values being plucked can be at any depth: ```js > var data = [ { leeds: { leeds: { leeds: "we" } } }, { leeds: { leeds: { leeds: "are" } } }, { leeds: { leeds: { leeds: "Leeds" } } } ] > a.pluck(data, "leeds.leeds.leeds") [ 'we', 'are', 'Leeds' ] ```
[ "Returns", "an", "array", "containing", "each", "value", "plucked", "from", "the", "specified", "property", "of", "each", "object", "in", "the", "input", "array", "." ]
0b0bc3db025ada4cc58c182b40a45ee641d27a87
https://github.com/75lb/array-tools/blob/0b0bc3db025ada4cc58c182b40a45ee641d27a87/lib/array-tools.js#L289-L303
train
75lb/array-tools
lib/array-tools.js
spliceWhile
function spliceWhile (array, index, test) { for (var i = 0; i < array.length; i++) { if (!testValue(array[i], test)) break } var spliceArgs = [ index, i ] spliceArgs = spliceArgs.concat(arrayify(arguments).slice(3)) return array.splice.apply(array, spliceArgs) }
javascript
function spliceWhile (array, index, test) { for (var i = 0; i < array.length; i++) { if (!testValue(array[i], test)) break } var spliceArgs = [ index, i ] spliceArgs = spliceArgs.concat(arrayify(arguments).slice(3)) return array.splice.apply(array, spliceArgs) }
[ "function", "spliceWhile", "(", "array", ",", "index", ",", "test", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "testValue", "(", "array", "[", "i", "]", ",", "test", ")", ")", "break", "}", "var", "spliceArgs", "=", "[", "index", ",", "i", "]", "spliceArgs", "=", "spliceArgs", ".", "concat", "(", "arrayify", "(", "arguments", ")", ".", "slice", "(", "3", ")", ")", "return", "array", ".", "splice", ".", "apply", "(", "array", ",", "spliceArgs", ")", "}" ]
Splice items from the input array until the matching test fails. Returns an array containing the items removed. @param array {Array} - the input array @param index {number} - the position to begin splicing from @param test {any} - the sequence of items passing this test will be removed @param [elementN] {...*} - elements to add to the array in place @returns {Array} @category chainable @static @example > function under10(n){ return n < 10; } > numbers = [ 1, 2, 4, 6, 12 ] > a.spliceWhile(numbers, 0, under10) [ 1, 2, 4, 6 ] > numbers [ 12 ] > countries = [ "Egypt", "Ethiopia", "France", "Argentina" ] > a.spliceWhile(countries, 0, /^e/i) [ 'Egypt', 'Ethiopia' ] > countries [ 'France', 'Argentina' ]
[ "Splice", "items", "from", "the", "input", "array", "until", "the", "matching", "test", "fails", ".", "Returns", "an", "array", "containing", "the", "items", "removed", "." ]
0b0bc3db025ada4cc58c182b40a45ee641d27a87
https://github.com/75lb/array-tools/blob/0b0bc3db025ada4cc58c182b40a45ee641d27a87/lib/array-tools.js#L434-L441
train
sazze/node-pm
lib/clusterEvents.js
forkTimeoutHandler
function forkTimeoutHandler(worker, cluster) { verbose('worker %d is stuck in fork', worker.process.pid); if (!cluster.workers[worker.id]) { return; } // something is wrong with this worker. Kill it! master.suicideOverrides[worker.id] = worker.id; master.isRunning(worker, function(running) { if (!running) { return; } try { debug('sending SIGKILL to worker %d', worker.process.pid); process.kill(worker.process.pid, 'SIGKILL'); } catch (e) { // this can happen. don't crash!! } }); }
javascript
function forkTimeoutHandler(worker, cluster) { verbose('worker %d is stuck in fork', worker.process.pid); if (!cluster.workers[worker.id]) { return; } // something is wrong with this worker. Kill it! master.suicideOverrides[worker.id] = worker.id; master.isRunning(worker, function(running) { if (!running) { return; } try { debug('sending SIGKILL to worker %d', worker.process.pid); process.kill(worker.process.pid, 'SIGKILL'); } catch (e) { // this can happen. don't crash!! } }); }
[ "function", "forkTimeoutHandler", "(", "worker", ",", "cluster", ")", "{", "verbose", "(", "'worker %d is stuck in fork'", ",", "worker", ".", "process", ".", "pid", ")", ";", "if", "(", "!", "cluster", ".", "workers", "[", "worker", ".", "id", "]", ")", "{", "return", ";", "}", "master", ".", "suicideOverrides", "[", "worker", ".", "id", "]", "=", "worker", ".", "id", ";", "master", ".", "isRunning", "(", "worker", ",", "function", "(", "running", ")", "{", "if", "(", "!", "running", ")", "{", "return", ";", "}", "try", "{", "debug", "(", "'sending SIGKILL to worker %d'", ",", "worker", ".", "process", ".", "pid", ")", ";", "process", ".", "kill", "(", "worker", ".", "process", ".", "pid", ",", "'SIGKILL'", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}", ")", ";", "}" ]
Called when worker takes too long to fork @private @param worker @param cluster
[ "Called", "when", "worker", "takes", "too", "long", "to", "fork" ]
d2f1348cb0446e98dcf873e319b55ce89f79b386
https://github.com/sazze/node-pm/blob/d2f1348cb0446e98dcf873e319b55ce89f79b386/lib/clusterEvents.js#L155-L177
train
sazze/node-pm
lib/clusterEvents.js
disconnectTimeoutHandler
function disconnectTimeoutHandler(worker, cluster) { verbose('worker %d is stuck in disconnect', worker.process.pid); // if this is not a suicide we need to preserve that as worker.kill() will make this a suicide if (!worker.suicide) { master.suicideOverrides[worker.id] = worker.id; } master.isRunning(worker, function(running) { if (!running) { return; } try { debug('sending SIGKILL to worker %d', worker.process.pid); process.kill(worker.process.pid, 'SIGKILL'); } catch (e) { // this can happen. don't crash!! } }); }
javascript
function disconnectTimeoutHandler(worker, cluster) { verbose('worker %d is stuck in disconnect', worker.process.pid); // if this is not a suicide we need to preserve that as worker.kill() will make this a suicide if (!worker.suicide) { master.suicideOverrides[worker.id] = worker.id; } master.isRunning(worker, function(running) { if (!running) { return; } try { debug('sending SIGKILL to worker %d', worker.process.pid); process.kill(worker.process.pid, 'SIGKILL'); } catch (e) { // this can happen. don't crash!! } }); }
[ "function", "disconnectTimeoutHandler", "(", "worker", ",", "cluster", ")", "{", "verbose", "(", "'worker %d is stuck in disconnect'", ",", "worker", ".", "process", ".", "pid", ")", ";", "if", "(", "!", "worker", ".", "suicide", ")", "{", "master", ".", "suicideOverrides", "[", "worker", ".", "id", "]", "=", "worker", ".", "id", ";", "}", "master", ".", "isRunning", "(", "worker", ",", "function", "(", "running", ")", "{", "if", "(", "!", "running", ")", "{", "return", ";", "}", "try", "{", "debug", "(", "'sending SIGKILL to worker %d'", ",", "worker", ".", "process", ".", "pid", ")", ";", "process", ".", "kill", "(", "worker", ".", "process", ".", "pid", ",", "'SIGKILL'", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}", ")", ";", "}" ]
Called when worker is taking too long to disconnect @private @param worker @param cluster
[ "Called", "when", "worker", "is", "taking", "too", "long", "to", "disconnect" ]
d2f1348cb0446e98dcf873e319b55ce89f79b386
https://github.com/sazze/node-pm/blob/d2f1348cb0446e98dcf873e319b55ce89f79b386/lib/clusterEvents.js#L186-L206
train
hapticdata/animitter
index.js
makeThrottle
function makeThrottle(fps){ var delay = 1000/fps; var lastTime = Date.now(); if( fps<=0 || fps === Infinity ){ return returnTrue; } //if an fps throttle has been set then we'll assume //it natively runs at 60fps, var half = Math.ceil(1000 / 60) / 2; return function(){ //if a custom fps is requested var now = Date.now(); //is this frame within 8.5ms of the target? //if so then next frame is gonna be too late if(now - lastTime < delay - half){ return false; } lastTime = now; return true; }; }
javascript
function makeThrottle(fps){ var delay = 1000/fps; var lastTime = Date.now(); if( fps<=0 || fps === Infinity ){ return returnTrue; } //if an fps throttle has been set then we'll assume //it natively runs at 60fps, var half = Math.ceil(1000 / 60) / 2; return function(){ //if a custom fps is requested var now = Date.now(); //is this frame within 8.5ms of the target? //if so then next frame is gonna be too late if(now - lastTime < delay - half){ return false; } lastTime = now; return true; }; }
[ "function", "makeThrottle", "(", "fps", ")", "{", "var", "delay", "=", "1000", "/", "fps", ";", "var", "lastTime", "=", "Date", ".", "now", "(", ")", ";", "if", "(", "fps", "<=", "0", "||", "fps", "===", "Infinity", ")", "{", "return", "returnTrue", ";", "}", "var", "half", "=", "Math", ".", "ceil", "(", "1000", "/", "60", ")", "/", "2", ";", "return", "function", "(", ")", "{", "var", "now", "=", "Date", ".", "now", "(", ")", ";", "if", "(", "now", "-", "lastTime", "<", "delay", "-", "half", ")", "{", "return", "false", ";", "}", "lastTime", "=", "now", ";", "return", "true", ";", "}", ";", "}" ]
manage FPS if < 60, else return true;
[ "manage", "FPS", "if", "<", "60", "else", "return", "true", ";" ]
4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e
https://github.com/hapticdata/animitter/blob/4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e/index.js#L16-L40
train
hapticdata/animitter
index.js
Animitter
function Animitter( opts ){ opts = opts || {}; this.__delay = opts.delay || 0; /** @expose */ this.fixedDelta = !!opts.fixedDelta; /** @expose */ this.frameCount = 0; /** @expose */ this.deltaTime = 0; /** @expose */ this.elapsedTime = 0; /** @private */ this.__running = false; /** @private */ this.__completed = false; this.setFPS(opts.fps || Infinity); this.setRequestAnimationFrameObject(opts.requestAnimationFrameObject || defaultRAFObject); }
javascript
function Animitter( opts ){ opts = opts || {}; this.__delay = opts.delay || 0; /** @expose */ this.fixedDelta = !!opts.fixedDelta; /** @expose */ this.frameCount = 0; /** @expose */ this.deltaTime = 0; /** @expose */ this.elapsedTime = 0; /** @private */ this.__running = false; /** @private */ this.__completed = false; this.setFPS(opts.fps || Infinity); this.setRequestAnimationFrameObject(opts.requestAnimationFrameObject || defaultRAFObject); }
[ "function", "Animitter", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "__delay", "=", "opts", ".", "delay", "||", "0", ";", "this", ".", "fixedDelta", "=", "!", "!", "opts", ".", "fixedDelta", ";", "this", ".", "frameCount", "=", "0", ";", "this", ".", "deltaTime", "=", "0", ";", "this", ".", "elapsedTime", "=", "0", ";", "this", ".", "__running", "=", "false", ";", "this", ".", "__completed", "=", "false", ";", "this", ".", "setFPS", "(", "opts", ".", "fps", "||", "Infinity", ")", ";", "this", ".", "setRequestAnimationFrameObject", "(", "opts", ".", "requestAnimationFrameObject", "||", "defaultRAFObject", ")", ";", "}" ]
Animitter provides event-based loops for the browser and node, using `requestAnimationFrame` @param {Object} [opts] @param {Number} [opts.fps=Infinity] the framerate requested, defaults to as fast as it can (60fps on window) @param {Number} [opts.delay=0] milliseconds delay between invoking `start` and initializing the loop @param {Object} [opts.requestAnimationFrameObject=global] the object on which to find `requestAnimationFrame` and `cancelAnimationFrame` methods @param {Boolean} [opts.fixedDelta=false] if true, timestamps will pretend to be executed at fixed intervals always @constructor
[ "Animitter", "provides", "event", "-", "based", "loops", "for", "the", "browser", "and", "node", "using", "requestAnimationFrame" ]
4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e
https://github.com/hapticdata/animitter/blob/4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e/index.js#L53-L75
train
hapticdata/animitter
index.js
function(){ this.frameCount++; /** @private */ var now = Date.now(); this.__lastTime = this.__lastTime || now; this.deltaTime = (this.fixedDelta || exports.globalFixedDelta) ? 1000/Math.min(60, this.__fps) : now - this.__lastTime; this.elapsedTime += this.deltaTime; this.__lastTime = now; this.emit('update', this.deltaTime, this.elapsedTime, this.frameCount); return this; }
javascript
function(){ this.frameCount++; /** @private */ var now = Date.now(); this.__lastTime = this.__lastTime || now; this.deltaTime = (this.fixedDelta || exports.globalFixedDelta) ? 1000/Math.min(60, this.__fps) : now - this.__lastTime; this.elapsedTime += this.deltaTime; this.__lastTime = now; this.emit('update', this.deltaTime, this.elapsedTime, this.frameCount); return this; }
[ "function", "(", ")", "{", "this", ".", "frameCount", "++", ";", "var", "now", "=", "Date", ".", "now", "(", ")", ";", "this", ".", "__lastTime", "=", "this", ".", "__lastTime", "||", "now", ";", "this", ".", "deltaTime", "=", "(", "this", ".", "fixedDelta", "||", "exports", ".", "globalFixedDelta", ")", "?", "1000", "/", "Math", ".", "min", "(", "60", ",", "this", ".", "__fps", ")", ":", "now", "-", "this", ".", "__lastTime", ";", "this", ".", "elapsedTime", "+=", "this", ".", "deltaTime", ";", "this", ".", "__lastTime", "=", "now", ";", "this", ".", "emit", "(", "'update'", ",", "this", ".", "deltaTime", ",", "this", ".", "elapsedTime", ",", "this", ".", "frameCount", ")", ";", "return", "this", ";", "}" ]
update the animation loop once @emit Animitter#update @return {Animitter}
[ "update", "the", "animation", "loop", "once" ]
4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e
https://github.com/hapticdata/animitter/blob/4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e/index.js#L311-L322
train
hapticdata/animitter
index.js
createAnimitter
function createAnimitter(options, fn){ if( arguments.length === 1 && typeof options === 'function'){ fn = options; options = {}; } var _instance = new Animitter( options ); if( fn ){ _instance.on('update', fn); } return _instance; }
javascript
function createAnimitter(options, fn){ if( arguments.length === 1 && typeof options === 'function'){ fn = options; options = {}; } var _instance = new Animitter( options ); if( fn ){ _instance.on('update', fn); } return _instance; }
[ "function", "createAnimitter", "(", "options", ",", "fn", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", "&&", "typeof", "options", "===", "'function'", ")", "{", "fn", "=", "options", ";", "options", "=", "{", "}", ";", "}", "var", "_instance", "=", "new", "Animitter", "(", "options", ")", ";", "if", "(", "fn", ")", "{", "_instance", ".", "on", "(", "'update'", ",", "fn", ")", ";", "}", "return", "_instance", ";", "}" ]
create an animitter instance, @param {Object} [options] @param {Function} fn( deltaTime:Number, elapsedTime:Number, frameCount:Number ) @returns {Animitter}
[ "create", "an", "animitter", "instance" ]
4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e
https://github.com/hapticdata/animitter/blob/4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e/index.js#L338-L352
train
sazze/node-pm
lib/master.js
fork
function fork(number) { var numProc = number || require('os').cpus().length; config.n = numProc; debug('forking %d workers', numProc); forkLoopProtect(); for (var i = 0; i < numProc; i++) { cluster.fork({PWD: config.CWD}); } }
javascript
function fork(number) { var numProc = number || require('os').cpus().length; config.n = numProc; debug('forking %d workers', numProc); forkLoopProtect(); for (var i = 0; i < numProc; i++) { cluster.fork({PWD: config.CWD}); } }
[ "function", "fork", "(", "number", ")", "{", "var", "numProc", "=", "number", "||", "require", "(", "'os'", ")", ".", "cpus", "(", ")", ".", "length", ";", "config", ".", "n", "=", "numProc", ";", "debug", "(", "'forking %d workers'", ",", "numProc", ")", ";", "forkLoopProtect", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numProc", ";", "i", "++", ")", "{", "cluster", ".", "fork", "(", "{", "PWD", ":", "config", ".", "CWD", "}", ")", ";", "}", "}" ]
Fork Workers N times @private @param {int} [number=cpus.length] the number of processes to start
[ "Fork", "Workers", "N", "times" ]
d2f1348cb0446e98dcf873e319b55ce89f79b386
https://github.com/sazze/node-pm/blob/d2f1348cb0446e98dcf873e319b55ce89f79b386/lib/master.js#L339-L351
train
sazze/node-pm
lib/master.js
lifecycleTimeoutHandler
function lifecycleTimeoutHandler() { if (shutdownCalled) { return; } verbose('workers have reached the end of their life'); master.restart(function () { if (!shutdownCalled) { lifecycleTimer = setTimeout(lifecycleTimeoutHandler.bind(master), config.timeouts.maxAge); } }); }
javascript
function lifecycleTimeoutHandler() { if (shutdownCalled) { return; } verbose('workers have reached the end of their life'); master.restart(function () { if (!shutdownCalled) { lifecycleTimer = setTimeout(lifecycleTimeoutHandler.bind(master), config.timeouts.maxAge); } }); }
[ "function", "lifecycleTimeoutHandler", "(", ")", "{", "if", "(", "shutdownCalled", ")", "{", "return", ";", "}", "verbose", "(", "'workers have reached the end of their life'", ")", ";", "master", ".", "restart", "(", "function", "(", ")", "{", "if", "(", "!", "shutdownCalled", ")", "{", "lifecycleTimer", "=", "setTimeout", "(", "lifecycleTimeoutHandler", ".", "bind", "(", "master", ")", ",", "config", ".", "timeouts", ".", "maxAge", ")", ";", "}", "}", ")", ";", "}" ]
Called when workers have reached the end of their lifespan @private
[ "Called", "when", "workers", "have", "reached", "the", "end", "of", "their", "lifespan" ]
d2f1348cb0446e98dcf873e319b55ce89f79b386
https://github.com/sazze/node-pm/blob/d2f1348cb0446e98dcf873e319b55ce89f79b386/lib/master.js#L358-L370
train
snatalenko/node-cqrs
src/Observer.js
subscribe
function subscribe(observable, observer, options) { if (typeof observable !== 'object' || !observable) throw new TypeError('observable argument must be an Object'); if (typeof observable.on !== 'function') throw new TypeError('observable.on must be a Function'); if (typeof observer !== 'object' || !observer) throw new TypeError('observer argument must be an Object'); const { masterHandler, messageTypes, queueName } = options; if (masterHandler && typeof masterHandler !== 'function') throw new TypeError('masterHandler parameter, when provided, must be a Function'); if (queueName && typeof observable.queue !== 'function') throw new TypeError('observable.queue, when queueName is specified, must be a Function'); const subscribeTo = messageTypes || observer.handles || Object.getPrototypeOf(observer).constructor.handles; if (!Array.isArray(subscribeTo)) throw new TypeError('either options.messageTypes, observer.handles or ObserverType.handles is required'); unique(subscribeTo).forEach(messageType => { const handler = masterHandler || getHandler(observer, messageType); if (!handler) throw new Error(`'${messageType}' handler is not defined or not a function`); if (queueName) observable.queue(queueName).on(messageType, handler.bind(observer)); else observable.on(messageType, handler.bind(observer)); }); }
javascript
function subscribe(observable, observer, options) { if (typeof observable !== 'object' || !observable) throw new TypeError('observable argument must be an Object'); if (typeof observable.on !== 'function') throw new TypeError('observable.on must be a Function'); if (typeof observer !== 'object' || !observer) throw new TypeError('observer argument must be an Object'); const { masterHandler, messageTypes, queueName } = options; if (masterHandler && typeof masterHandler !== 'function') throw new TypeError('masterHandler parameter, when provided, must be a Function'); if (queueName && typeof observable.queue !== 'function') throw new TypeError('observable.queue, when queueName is specified, must be a Function'); const subscribeTo = messageTypes || observer.handles || Object.getPrototypeOf(observer).constructor.handles; if (!Array.isArray(subscribeTo)) throw new TypeError('either options.messageTypes, observer.handles or ObserverType.handles is required'); unique(subscribeTo).forEach(messageType => { const handler = masterHandler || getHandler(observer, messageType); if (!handler) throw new Error(`'${messageType}' handler is not defined or not a function`); if (queueName) observable.queue(queueName).on(messageType, handler.bind(observer)); else observable.on(messageType, handler.bind(observer)); }); }
[ "function", "subscribe", "(", "observable", ",", "observer", ",", "options", ")", "{", "if", "(", "typeof", "observable", "!==", "'object'", "||", "!", "observable", ")", "throw", "new", "TypeError", "(", "'observable argument must be an Object'", ")", ";", "if", "(", "typeof", "observable", ".", "on", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'observable.on must be a Function'", ")", ";", "if", "(", "typeof", "observer", "!==", "'object'", "||", "!", "observer", ")", "throw", "new", "TypeError", "(", "'observer argument must be an Object'", ")", ";", "const", "{", "masterHandler", ",", "messageTypes", ",", "queueName", "}", "=", "options", ";", "if", "(", "masterHandler", "&&", "typeof", "masterHandler", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'masterHandler parameter, when provided, must be a Function'", ")", ";", "if", "(", "queueName", "&&", "typeof", "observable", ".", "queue", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'observable.queue, when queueName is specified, must be a Function'", ")", ";", "const", "subscribeTo", "=", "messageTypes", "||", "observer", ".", "handles", "||", "Object", ".", "getPrototypeOf", "(", "observer", ")", ".", "constructor", ".", "handles", ";", "if", "(", "!", "Array", ".", "isArray", "(", "subscribeTo", ")", ")", "throw", "new", "TypeError", "(", "'either options.messageTypes, observer.handles or ObserverType.handles is required'", ")", ";", "unique", "(", "subscribeTo", ")", ".", "forEach", "(", "messageType", "=>", "{", "const", "handler", "=", "masterHandler", "||", "getHandler", "(", "observer", ",", "messageType", ")", ";", "if", "(", "!", "handler", ")", "throw", "new", "Error", "(", "`", "${", "messageType", "}", "`", ")", ";", "if", "(", "queueName", ")", "observable", ".", "queue", "(", "queueName", ")", ".", "on", "(", "messageType", ",", "handler", ".", "bind", "(", "observer", ")", ")", ";", "else", "observable", ".", "on", "(", "messageType", ",", "handler", ".", "bind", "(", "observer", ")", ")", ";", "}", ")", ";", "}" ]
Subscribe observer to observable @param {IObservable} observable @param {IObserver} observer @param {TSubscribeOptions} [options]
[ "Subscribe", "observer", "to", "observable" ]
32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c
https://github.com/snatalenko/node-cqrs/blob/32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c/src/Observer.js#L14-L44
train
battlejj/recursive-readdir-sync
index.js
recursiveReaddirSync
function recursiveReaddirSync(path) { var list = [] , files = fs.readdirSync(path) , stats ; files.forEach(function (file) { stats = fs.lstatSync(p.join(path, file)); if(stats.isDirectory()) { list = list.concat(recursiveReaddirSync(p.join(path, file))); } else { list.push(p.join(path, file)); } }); return list; }
javascript
function recursiveReaddirSync(path) { var list = [] , files = fs.readdirSync(path) , stats ; files.forEach(function (file) { stats = fs.lstatSync(p.join(path, file)); if(stats.isDirectory()) { list = list.concat(recursiveReaddirSync(p.join(path, file))); } else { list.push(p.join(path, file)); } }); return list; }
[ "function", "recursiveReaddirSync", "(", "path", ")", "{", "var", "list", "=", "[", "]", ",", "files", "=", "fs", ".", "readdirSync", "(", "path", ")", ",", "stats", ";", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "stats", "=", "fs", ".", "lstatSync", "(", "p", ".", "join", "(", "path", ",", "file", ")", ")", ";", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "list", "=", "list", ".", "concat", "(", "recursiveReaddirSync", "(", "p", ".", "join", "(", "path", ",", "file", ")", ")", ")", ";", "}", "else", "{", "list", ".", "push", "(", "p", ".", "join", "(", "path", ",", "file", ")", ")", ";", "}", "}", ")", ";", "return", "list", ";", "}" ]
how to know when you are done?
[ "how", "to", "know", "when", "you", "are", "done?" ]
77b9b005c95128252f9f4a8a17a8318c0219e7c3
https://github.com/battlejj/recursive-readdir-sync/blob/77b9b005c95128252f9f4a8a17a8318c0219e7c3/index.js#L6-L22
train
snatalenko/node-cqrs
src/EventStore.js
validateEvent
function validateEvent(event) { if (typeof event !== 'object' || !event) throw new TypeError('event must be an Object'); if (typeof event.type !== 'string' || !event.type.length) throw new TypeError('event.type must be a non-empty String'); if (!event.aggregateId && !event.sagaId) throw new TypeError('either event.aggregateId or event.sagaId is required'); if (event.sagaId && typeof event.sagaVersion === 'undefined') throw new TypeError('event.sagaVersion is required, when event.sagaId is defined'); }
javascript
function validateEvent(event) { if (typeof event !== 'object' || !event) throw new TypeError('event must be an Object'); if (typeof event.type !== 'string' || !event.type.length) throw new TypeError('event.type must be a non-empty String'); if (!event.aggregateId && !event.sagaId) throw new TypeError('either event.aggregateId or event.sagaId is required'); if (event.sagaId && typeof event.sagaVersion === 'undefined') throw new TypeError('event.sagaVersion is required, when event.sagaId is defined'); }
[ "function", "validateEvent", "(", "event", ")", "{", "if", "(", "typeof", "event", "!==", "'object'", "||", "!", "event", ")", "throw", "new", "TypeError", "(", "'event must be an Object'", ")", ";", "if", "(", "typeof", "event", ".", "type", "!==", "'string'", "||", "!", "event", ".", "type", ".", "length", ")", "throw", "new", "TypeError", "(", "'event.type must be a non-empty String'", ")", ";", "if", "(", "!", "event", ".", "aggregateId", "&&", "!", "event", ".", "sagaId", ")", "throw", "new", "TypeError", "(", "'either event.aggregateId or event.sagaId is required'", ")", ";", "if", "(", "event", ".", "sagaId", "&&", "typeof", "event", ".", "sagaVersion", "===", "'undefined'", ")", "throw", "new", "TypeError", "(", "'event.sagaVersion is required, when event.sagaId is defined'", ")", ";", "}" ]
Validate event structure @param {IEvent} event
[ "Validate", "event", "structure" ]
32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c
https://github.com/snatalenko/node-cqrs/blob/32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c/src/EventStore.js#L19-L24
train
snatalenko/node-cqrs
src/EventStore.js
validateEventStorage
function validateEventStorage(storage) { if (!storage) throw new TypeError('storage argument required'); if (typeof storage !== 'object') throw new TypeError('storage argument must be an Object'); if (typeof storage.commitEvents !== 'function') throw new TypeError('storage.commitEvents must be a Function'); if (typeof storage.getEvents !== 'function') throw new TypeError('storage.getEvents must be a Function'); if (typeof storage.getAggregateEvents !== 'function') throw new TypeError('storage.getAggregateEvents must be a Function'); if (typeof storage.getSagaEvents !== 'function') throw new TypeError('storage.getSagaEvents must be a Function'); if (typeof storage.getNewId !== 'function') throw new TypeError('storage.getNewId must be a Function'); }
javascript
function validateEventStorage(storage) { if (!storage) throw new TypeError('storage argument required'); if (typeof storage !== 'object') throw new TypeError('storage argument must be an Object'); if (typeof storage.commitEvents !== 'function') throw new TypeError('storage.commitEvents must be a Function'); if (typeof storage.getEvents !== 'function') throw new TypeError('storage.getEvents must be a Function'); if (typeof storage.getAggregateEvents !== 'function') throw new TypeError('storage.getAggregateEvents must be a Function'); if (typeof storage.getSagaEvents !== 'function') throw new TypeError('storage.getSagaEvents must be a Function'); if (typeof storage.getNewId !== 'function') throw new TypeError('storage.getNewId must be a Function'); }
[ "function", "validateEventStorage", "(", "storage", ")", "{", "if", "(", "!", "storage", ")", "throw", "new", "TypeError", "(", "'storage argument required'", ")", ";", "if", "(", "typeof", "storage", "!==", "'object'", ")", "throw", "new", "TypeError", "(", "'storage argument must be an Object'", ")", ";", "if", "(", "typeof", "storage", ".", "commitEvents", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'storage.commitEvents must be a Function'", ")", ";", "if", "(", "typeof", "storage", ".", "getEvents", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'storage.getEvents must be a Function'", ")", ";", "if", "(", "typeof", "storage", ".", "getAggregateEvents", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'storage.getAggregateEvents must be a Function'", ")", ";", "if", "(", "typeof", "storage", ".", "getSagaEvents", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'storage.getSagaEvents must be a Function'", ")", ";", "if", "(", "typeof", "storage", ".", "getNewId", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'storage.getNewId must be a Function'", ")", ";", "}" ]
Ensure provided eventStorage matches the expected format @param {IEventStorage} storage
[ "Ensure", "provided", "eventStorage", "matches", "the", "expected", "format" ]
32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c
https://github.com/snatalenko/node-cqrs/blob/32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c/src/EventStore.js#L30-L38
train
snatalenko/node-cqrs
src/EventStore.js
validateSnapshotStorage
function validateSnapshotStorage(snapshotStorage) { if (typeof snapshotStorage !== 'object' || !snapshotStorage) throw new TypeError('snapshotStorage argument must be an Object'); if (typeof snapshotStorage.getAggregateSnapshot !== 'function') throw new TypeError('snapshotStorage.getAggregateSnapshot argument must be a Function'); if (typeof snapshotStorage.saveAggregateSnapshot !== 'function') throw new TypeError('snapshotStorage.saveAggregateSnapshot argument must be a Function'); }
javascript
function validateSnapshotStorage(snapshotStorage) { if (typeof snapshotStorage !== 'object' || !snapshotStorage) throw new TypeError('snapshotStorage argument must be an Object'); if (typeof snapshotStorage.getAggregateSnapshot !== 'function') throw new TypeError('snapshotStorage.getAggregateSnapshot argument must be a Function'); if (typeof snapshotStorage.saveAggregateSnapshot !== 'function') throw new TypeError('snapshotStorage.saveAggregateSnapshot argument must be a Function'); }
[ "function", "validateSnapshotStorage", "(", "snapshotStorage", ")", "{", "if", "(", "typeof", "snapshotStorage", "!==", "'object'", "||", "!", "snapshotStorage", ")", "throw", "new", "TypeError", "(", "'snapshotStorage argument must be an Object'", ")", ";", "if", "(", "typeof", "snapshotStorage", ".", "getAggregateSnapshot", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'snapshotStorage.getAggregateSnapshot argument must be a Function'", ")", ";", "if", "(", "typeof", "snapshotStorage", ".", "saveAggregateSnapshot", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'snapshotStorage.saveAggregateSnapshot argument must be a Function'", ")", ";", "}" ]
Ensure snapshotStorage matches the expected format @param {IAggregateSnapshotStorage} snapshotStorage
[ "Ensure", "snapshotStorage", "matches", "the", "expected", "format" ]
32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c
https://github.com/snatalenko/node-cqrs/blob/32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c/src/EventStore.js#L54-L61
train
snatalenko/node-cqrs
src/EventStore.js
validateMessageBus
function validateMessageBus(messageBus) { if (typeof messageBus !== 'object' || !messageBus) throw new TypeError('messageBus argument must be an Object'); if (typeof messageBus.on !== 'function') throw new TypeError('messageBus.on argument must be a Function'); if (typeof messageBus.publish !== 'function') throw new TypeError('messageBus.publish argument must be a Function'); }
javascript
function validateMessageBus(messageBus) { if (typeof messageBus !== 'object' || !messageBus) throw new TypeError('messageBus argument must be an Object'); if (typeof messageBus.on !== 'function') throw new TypeError('messageBus.on argument must be a Function'); if (typeof messageBus.publish !== 'function') throw new TypeError('messageBus.publish argument must be a Function'); }
[ "function", "validateMessageBus", "(", "messageBus", ")", "{", "if", "(", "typeof", "messageBus", "!==", "'object'", "||", "!", "messageBus", ")", "throw", "new", "TypeError", "(", "'messageBus argument must be an Object'", ")", ";", "if", "(", "typeof", "messageBus", ".", "on", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'messageBus.on argument must be a Function'", ")", ";", "if", "(", "typeof", "messageBus", ".", "publish", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'messageBus.publish argument must be a Function'", ")", ";", "}" ]
Ensure messageBus matches the expected format @param {IMessageBus} messageBus
[ "Ensure", "messageBus", "matches", "the", "expected", "format" ]
32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c
https://github.com/snatalenko/node-cqrs/blob/32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c/src/EventStore.js#L67-L74
train
snatalenko/node-cqrs
src/EventStore.js
setupOneTimeEmitterSubscription
function setupOneTimeEmitterSubscription(emitter, messageTypes, filter, handler) { if (typeof emitter !== 'object' || !emitter) throw new TypeError('emitter argument must be an Object'); if (!Array.isArray(messageTypes) || messageTypes.some(m => !m || typeof m !== 'string')) throw new TypeError('messageTypes argument must be an Array of non-empty Strings'); if (handler && typeof handler !== 'function') throw new TypeError('handler argument, when specified, must be a Function'); if (filter && typeof filter !== 'function') throw new TypeError('filter argument, when specified, must be a Function'); return new Promise(resolve => { // handler will be invoked only once, // even if multiple events have been emitted before subscription was destroyed // https://nodejs.org/api/events.html#events_emitter_removelistener_eventname_listener let handled = false; function filteredHandler(event) { if (filter && !filter(event)) return; if (handled) return; handled = true; for (const messageType of messageTypes) emitter.off(messageType, filteredHandler); debug('\'%s\' received, one-time subscription to \'%s\' removed', event.type, messageTypes.join(',')); if (handler) handler(event); resolve(event); } for (const messageType of messageTypes) emitter.on(messageType, filteredHandler); debug('set up one-time %s to \'%s\'', filter ? 'filtered subscription' : 'subscription', messageTypes.join(',')); }); }
javascript
function setupOneTimeEmitterSubscription(emitter, messageTypes, filter, handler) { if (typeof emitter !== 'object' || !emitter) throw new TypeError('emitter argument must be an Object'); if (!Array.isArray(messageTypes) || messageTypes.some(m => !m || typeof m !== 'string')) throw new TypeError('messageTypes argument must be an Array of non-empty Strings'); if (handler && typeof handler !== 'function') throw new TypeError('handler argument, when specified, must be a Function'); if (filter && typeof filter !== 'function') throw new TypeError('filter argument, when specified, must be a Function'); return new Promise(resolve => { // handler will be invoked only once, // even if multiple events have been emitted before subscription was destroyed // https://nodejs.org/api/events.html#events_emitter_removelistener_eventname_listener let handled = false; function filteredHandler(event) { if (filter && !filter(event)) return; if (handled) return; handled = true; for (const messageType of messageTypes) emitter.off(messageType, filteredHandler); debug('\'%s\' received, one-time subscription to \'%s\' removed', event.type, messageTypes.join(',')); if (handler) handler(event); resolve(event); } for (const messageType of messageTypes) emitter.on(messageType, filteredHandler); debug('set up one-time %s to \'%s\'', filter ? 'filtered subscription' : 'subscription', messageTypes.join(',')); }); }
[ "function", "setupOneTimeEmitterSubscription", "(", "emitter", ",", "messageTypes", ",", "filter", ",", "handler", ")", "{", "if", "(", "typeof", "emitter", "!==", "'object'", "||", "!", "emitter", ")", "throw", "new", "TypeError", "(", "'emitter argument must be an Object'", ")", ";", "if", "(", "!", "Array", ".", "isArray", "(", "messageTypes", ")", "||", "messageTypes", ".", "some", "(", "m", "=>", "!", "m", "||", "typeof", "m", "!==", "'string'", ")", ")", "throw", "new", "TypeError", "(", "'messageTypes argument must be an Array of non-empty Strings'", ")", ";", "if", "(", "handler", "&&", "typeof", "handler", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'handler argument, when specified, must be a Function'", ")", ";", "if", "(", "filter", "&&", "typeof", "filter", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'filter argument, when specified, must be a Function'", ")", ";", "return", "new", "Promise", "(", "resolve", "=>", "{", "let", "handled", "=", "false", ";", "function", "filteredHandler", "(", "event", ")", "{", "if", "(", "filter", "&&", "!", "filter", "(", "event", ")", ")", "return", ";", "if", "(", "handled", ")", "return", ";", "handled", "=", "true", ";", "for", "(", "const", "messageType", "of", "messageTypes", ")", "emitter", ".", "off", "(", "messageType", ",", "filteredHandler", ")", ";", "debug", "(", "'\\'%s\\' received, one-time subscription to \\'%s\\' removed'", ",", "\\'", ",", "\\'", ")", ";", "\\'", "\\'", "}", "event", ".", "type", "messageTypes", ".", "join", "(", "','", ")", "}", ")", ";", "}" ]
Create one-time eventEmitter subscription for one or multiple events that match a filter @param {IEventEmitter} emitter @param {string[]} messageTypes Array of event type to subscribe to @param {function(IEvent):any} [handler] Optional handler to execute for a first event received @param {function(IEvent):boolean} [filter] Optional filter to apply before executing a handler @return {Promise<IEvent>} Resolves to first event that passes filter
[ "Create", "one", "-", "time", "eventEmitter", "subscription", "for", "one", "or", "multiple", "events", "that", "match", "a", "filter" ]
32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c
https://github.com/snatalenko/node-cqrs/blob/32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c/src/EventStore.js#L86-L124
train
sazze/node-pm
lib/main.js
function(settings, callback) { "use strict"; if (typeof settings === 'function') { callback = settings; settings = {}; } if (typeof settings === 'undefined') { settings = {}; } if (typeof callback !== 'function') { callback = function () {}; } getLogFiles(function () { parseOptions(settings, function () { setupLogger(); require('./Logger').verbose('Starting worker manager'); // Start the Master master = require('./master'); registerListeners(master); master.start(); callback(); }); }); }
javascript
function(settings, callback) { "use strict"; if (typeof settings === 'function') { callback = settings; settings = {}; } if (typeof settings === 'undefined') { settings = {}; } if (typeof callback !== 'function') { callback = function () {}; } getLogFiles(function () { parseOptions(settings, function () { setupLogger(); require('./Logger').verbose('Starting worker manager'); // Start the Master master = require('./master'); registerListeners(master); master.start(); callback(); }); }); }
[ "function", "(", "settings", ",", "callback", ")", "{", "\"use strict\"", ";", "if", "(", "typeof", "settings", "===", "'function'", ")", "{", "callback", "=", "settings", ";", "settings", "=", "{", "}", ";", "}", "if", "(", "typeof", "settings", "===", "'undefined'", ")", "{", "settings", "=", "{", "}", ";", "}", "if", "(", "typeof", "callback", "!==", "'function'", ")", "{", "callback", "=", "function", "(", ")", "{", "}", ";", "}", "getLogFiles", "(", "function", "(", ")", "{", "parseOptions", "(", "settings", ",", "function", "(", ")", "{", "setupLogger", "(", ")", ";", "require", "(", "'./Logger'", ")", ".", "verbose", "(", "'Starting worker manager'", ")", ";", "master", "=", "require", "(", "'./master'", ")", ";", "registerListeners", "(", "master", ")", ";", "master", ".", "start", "(", ")", ";", "callback", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Start the Worker Manager @param [settings={}] @param [callback=function]
[ "Start", "the", "Worker", "Manager" ]
d2f1348cb0446e98dcf873e319b55ce89f79b386
https://github.com/sazze/node-pm/blob/d2f1348cb0446e98dcf873e319b55ce89f79b386/lib/main.js#L28-L60
train
sazze/node-pm
lib/Logger.js
log
function log(logLevel, prefix, args) { "use strict"; if (logLevel > level) { return; } args = Array.prototype.slice.call(args); if (typeof args[0] === 'undefined') { return; } var message = args[0]; args.splice(0, 1, prefix + message); console.log.apply(this, args); }
javascript
function log(logLevel, prefix, args) { "use strict"; if (logLevel > level) { return; } args = Array.prototype.slice.call(args); if (typeof args[0] === 'undefined') { return; } var message = args[0]; args.splice(0, 1, prefix + message); console.log.apply(this, args); }
[ "function", "log", "(", "logLevel", ",", "prefix", ",", "args", ")", "{", "\"use strict\"", ";", "if", "(", "logLevel", ">", "level", ")", "{", "return", ";", "}", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "args", ")", ";", "if", "(", "typeof", "args", "[", "0", "]", "===", "'undefined'", ")", "{", "return", ";", "}", "var", "message", "=", "args", "[", "0", "]", ";", "args", ".", "splice", "(", "0", ",", "1", ",", "prefix", "+", "message", ")", ";", "console", ".", "log", ".", "apply", "(", "this", ",", "args", ")", ";", "}" ]
The internal log function @private @param {int} logLevel the log level that is allowed @param prefix the prefix that gets prepended to the message @param args and object of arguments, usually from global [arguments]
[ "The", "internal", "log", "function" ]
d2f1348cb0446e98dcf873e319b55ce89f79b386
https://github.com/sazze/node-pm/blob/d2f1348cb0446e98dcf873e319b55ce89f79b386/lib/Logger.js#L95-L111
train
dpw/promisify
promisify.js
append
function append(arrlike /* , items... */) { return Array.prototype.slice.call(arrlike, 0).concat(Array.prototype.slice.call(arguments, 1)); }
javascript
function append(arrlike /* , items... */) { return Array.prototype.slice.call(arrlike, 0).concat(Array.prototype.slice.call(arguments, 1)); }
[ "function", "append", "(", "arrlike", ")", "{", "return", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arrlike", ",", "0", ")", ".", "concat", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "}" ]
Append items to an array-like object
[ "Append", "items", "to", "an", "array", "-", "like", "object" ]
23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc
https://github.com/dpw/promisify/blob/23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc/promisify.js#L11-L13
train
dpw/promisify
promisify.js
promisify_value
function promisify_value(result_transformer) { result_transformer = result_transformer || identity; var transformer = function (promise) { result_transformer(promise); }; transformer.for_property = function (obj_promise, prop) { return when(obj_promise, function (obj) { result_transformer(obj[prop]); }); }; return transformer; }
javascript
function promisify_value(result_transformer) { result_transformer = result_transformer || identity; var transformer = function (promise) { result_transformer(promise); }; transformer.for_property = function (obj_promise, prop) { return when(obj_promise, function (obj) { result_transformer(obj[prop]); }); }; return transformer; }
[ "function", "promisify_value", "(", "result_transformer", ")", "{", "result_transformer", "=", "result_transformer", "||", "identity", ";", "var", "transformer", "=", "function", "(", "promise", ")", "{", "result_transformer", "(", "promise", ")", ";", "}", ";", "transformer", ".", "for_property", "=", "function", "(", "obj_promise", ",", "prop", ")", "{", "return", "when", "(", "obj_promise", ",", "function", "(", "obj", ")", "{", "result_transformer", "(", "obj", "[", "prop", "]", ")", ";", "}", ")", ";", "}", ";", "return", "transformer", ";", "}" ]
Produces a transformer that takes a value and simply returns it.
[ "Produces", "a", "transformer", "that", "takes", "a", "value", "and", "simply", "returns", "it", "." ]
23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc
https://github.com/dpw/promisify/blob/23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc/promisify.js#L19-L33
train
dpw/promisify
promisify.js
promisify_func
function promisify_func(result_transformer) { result_transformer = result_transformer || identity; var transformer = function (func_promise) { return function (/* ... */) { var args = arguments; return result_transformer(when(func_promise, function (func) { return func.apply(null, args); })); }; }; transformer.for_property = function (obj_promise, prop) { return function (/* ... */) { var args = arguments; return result_transformer(when(obj_promise, function (obj) { return obj[prop].apply(obj, args); })); }; }; return transformer; }
javascript
function promisify_func(result_transformer) { result_transformer = result_transformer || identity; var transformer = function (func_promise) { return function (/* ... */) { var args = arguments; return result_transformer(when(func_promise, function (func) { return func.apply(null, args); })); }; }; transformer.for_property = function (obj_promise, prop) { return function (/* ... */) { var args = arguments; return result_transformer(when(obj_promise, function (obj) { return obj[prop].apply(obj, args); })); }; }; return transformer; }
[ "function", "promisify_func", "(", "result_transformer", ")", "{", "result_transformer", "=", "result_transformer", "||", "identity", ";", "var", "transformer", "=", "function", "(", "func_promise", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "arguments", ";", "return", "result_transformer", "(", "when", "(", "func_promise", ",", "function", "(", "func", ")", "{", "return", "func", ".", "apply", "(", "null", ",", "args", ")", ";", "}", ")", ")", ";", "}", ";", "}", ";", "transformer", ".", "for_property", "=", "function", "(", "obj_promise", ",", "prop", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "arguments", ";", "return", "result_transformer", "(", "when", "(", "obj_promise", ",", "function", "(", "obj", ")", "{", "return", "obj", "[", "prop", "]", ".", "apply", "(", "obj", ",", "args", ")", ";", "}", ")", ")", ";", "}", ";", "}", ";", "return", "transformer", ";", "}" ]
Produces a transformer that takes a promised function, and returns a function returning a promise, optionally transforming that promise.
[ "Produces", "a", "transformer", "that", "takes", "a", "promised", "function", "and", "returns", "a", "function", "returning", "a", "promise", "optionally", "transforming", "that", "promise", "." ]
23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc
https://github.com/dpw/promisify/blob/23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc/promisify.js#L38-L60
train
dpw/promisify
promisify.js
promisify_cb_func_generic
function promisify_cb_func_generic(result_transformer, cb_generator) { result_transformer = result_transformer || identity; var transformer = function (func_promise) { return function (/* ... */) { var args = arguments; return result_transformer(when(func_promise, function (func) { var d = when.defer(); func.apply(null, append(args, cb_generator(d))); return d.promise; })); }; }; transformer.for_property = function (obj_promise, prop) { return function(/* ... */) { var args = arguments; return result_transformer(when(obj_promise, function (obj) { var d = when.defer(); obj[prop].apply(obj, append(args, cb_generator(d))); return d.promise; })); }; }; return transformer; }
javascript
function promisify_cb_func_generic(result_transformer, cb_generator) { result_transformer = result_transformer || identity; var transformer = function (func_promise) { return function (/* ... */) { var args = arguments; return result_transformer(when(func_promise, function (func) { var d = when.defer(); func.apply(null, append(args, cb_generator(d))); return d.promise; })); }; }; transformer.for_property = function (obj_promise, prop) { return function(/* ... */) { var args = arguments; return result_transformer(when(obj_promise, function (obj) { var d = when.defer(); obj[prop].apply(obj, append(args, cb_generator(d))); return d.promise; })); }; }; return transformer; }
[ "function", "promisify_cb_func_generic", "(", "result_transformer", ",", "cb_generator", ")", "{", "result_transformer", "=", "result_transformer", "||", "identity", ";", "var", "transformer", "=", "function", "(", "func_promise", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "arguments", ";", "return", "result_transformer", "(", "when", "(", "func_promise", ",", "function", "(", "func", ")", "{", "var", "d", "=", "when", ".", "defer", "(", ")", ";", "func", ".", "apply", "(", "null", ",", "append", "(", "args", ",", "cb_generator", "(", "d", ")", ")", ")", ";", "return", "d", ".", "promise", ";", "}", ")", ")", ";", "}", ";", "}", ";", "transformer", ".", "for_property", "=", "function", "(", "obj_promise", ",", "prop", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "arguments", ";", "return", "result_transformer", "(", "when", "(", "obj_promise", ",", "function", "(", "obj", ")", "{", "var", "d", "=", "when", ".", "defer", "(", ")", ";", "obj", "[", "prop", "]", ".", "apply", "(", "obj", ",", "append", "(", "args", ",", "cb_generator", "(", "d", ")", ")", ")", ";", "return", "d", ".", "promise", ";", "}", ")", ")", ";", "}", ";", "}", ";", "return", "transformer", ";", "}" ]
Produces a transformer that takes a promised function taking a callback, and returns a function returning a promise, optionally transforming that promise.
[ "Produces", "a", "transformer", "that", "takes", "a", "promised", "function", "taking", "a", "callback", "and", "returns", "a", "function", "returning", "a", "promise", "optionally", "transforming", "that", "promise", "." ]
23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc
https://github.com/dpw/promisify/blob/23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc/promisify.js#L65-L91
train
dpw/promisify
promisify.js
promisify_object
function promisify_object(template, object_creator) { object_creator = object_creator || new_object; var transformer = function (obj_promise) { var res = object_creator(obj_promise); for (var prop in template) { res[prop] = template[prop].for_property(obj_promise, prop); } return res; }; transformer.for_property = function (parent_promise, prop) { return transformer(when(parent_promise, function (obj) { return obj[prop]; })); }; return transformer; }
javascript
function promisify_object(template, object_creator) { object_creator = object_creator || new_object; var transformer = function (obj_promise) { var res = object_creator(obj_promise); for (var prop in template) { res[prop] = template[prop].for_property(obj_promise, prop); } return res; }; transformer.for_property = function (parent_promise, prop) { return transformer(when(parent_promise, function (obj) { return obj[prop]; })); }; return transformer; }
[ "function", "promisify_object", "(", "template", ",", "object_creator", ")", "{", "object_creator", "=", "object_creator", "||", "new_object", ";", "var", "transformer", "=", "function", "(", "obj_promise", ")", "{", "var", "res", "=", "object_creator", "(", "obj_promise", ")", ";", "for", "(", "var", "prop", "in", "template", ")", "{", "res", "[", "prop", "]", "=", "template", "[", "prop", "]", ".", "for_property", "(", "obj_promise", ",", "prop", ")", ";", "}", "return", "res", ";", "}", ";", "transformer", ".", "for_property", "=", "function", "(", "parent_promise", ",", "prop", ")", "{", "return", "transformer", "(", "when", "(", "parent_promise", ",", "function", "(", "obj", ")", "{", "return", "obj", "[", "prop", "]", ";", "}", ")", ")", ";", "}", ";", "return", "transformer", ";", "}" ]
Produces a transformer that takes a promised object, and returns an object with the properties transformed according to the template.
[ "Produces", "a", "transformer", "that", "takes", "a", "promised", "object", "and", "returns", "an", "object", "with", "the", "properties", "transformed", "according", "to", "the", "template", "." ]
23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc
https://github.com/dpw/promisify/blob/23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc/promisify.js#L115-L132
train
dpw/promisify
promisify.js
promisify_read_stream
function promisify_read_stream() { var transformer = function (stream_promise) { var res = new PStream(); res.to = function (dest) { when(stream_promise, function (stream) { PStream.wrap_read_stream(stream).to(dest); }, function (err) { dest.error(err); }); }; return res.sanitize(); }; transformer.for_property = function (obj_promise, prop) { return transformer(when(obj_promise, function (obj) { return obj[prop]; })); }; return transformer; }
javascript
function promisify_read_stream() { var transformer = function (stream_promise) { var res = new PStream(); res.to = function (dest) { when(stream_promise, function (stream) { PStream.wrap_read_stream(stream).to(dest); }, function (err) { dest.error(err); }); }; return res.sanitize(); }; transformer.for_property = function (obj_promise, prop) { return transformer(when(obj_promise, function (obj) { return obj[prop]; })); }; return transformer; }
[ "function", "promisify_read_stream", "(", ")", "{", "var", "transformer", "=", "function", "(", "stream_promise", ")", "{", "var", "res", "=", "new", "PStream", "(", ")", ";", "res", ".", "to", "=", "function", "(", "dest", ")", "{", "when", "(", "stream_promise", ",", "function", "(", "stream", ")", "{", "PStream", ".", "wrap_read_stream", "(", "stream", ")", ".", "to", "(", "dest", ")", ";", "}", ",", "function", "(", "err", ")", "{", "dest", ".", "error", "(", "err", ")", ";", "}", ")", ";", "}", ";", "return", "res", ".", "sanitize", "(", ")", ";", "}", ";", "transformer", ".", "for_property", "=", "function", "(", "obj_promise", ",", "prop", ")", "{", "return", "transformer", "(", "when", "(", "obj_promise", ",", "function", "(", "obj", ")", "{", "return", "obj", "[", "prop", "]", ";", "}", ")", ")", ";", "}", ";", "return", "transformer", ";", "}" ]
Takes a promised read stream and returns a PStream
[ "Takes", "a", "promised", "read", "stream", "and", "returns", "a", "PStream" ]
23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc
https://github.com/dpw/promisify/blob/23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc/promisify.js#L135-L155
train
mattrayner/cordova-plugin-vuforia-sdk
hooks/AfterPluginInstall.js
function() { let xcConfigBuildFilePath = path.join(cwd, 'platforms', 'ios', 'cordova', 'build.xcconfig'); try { let xcConfigBuildFileExists = fs.accessSync(xcConfigBuildFilePath); } catch(e) { console.log('Could not locate build.xcconfig, you will need to set HEADER_SEARCH_PATHS manually'); return; } console.log(`xcConfigBuildFilePath: ${xcConfigBuildFilePath}`); addHeaderSearchPaths(xcConfigBuildFilePath); }
javascript
function() { let xcConfigBuildFilePath = path.join(cwd, 'platforms', 'ios', 'cordova', 'build.xcconfig'); try { let xcConfigBuildFileExists = fs.accessSync(xcConfigBuildFilePath); } catch(e) { console.log('Could not locate build.xcconfig, you will need to set HEADER_SEARCH_PATHS manually'); return; } console.log(`xcConfigBuildFilePath: ${xcConfigBuildFilePath}`); addHeaderSearchPaths(xcConfigBuildFilePath); }
[ "function", "(", ")", "{", "let", "xcConfigBuildFilePath", "=", "path", ".", "join", "(", "cwd", ",", "'platforms'", ",", "'ios'", ",", "'cordova'", ",", "'build.xcconfig'", ")", ";", "try", "{", "let", "xcConfigBuildFileExists", "=", "fs", ".", "accessSync", "(", "xcConfigBuildFilePath", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "'Could not locate build.xcconfig, you will need to set HEADER_SEARCH_PATHS manually'", ")", ";", "return", ";", "}", "console", ".", "log", "(", "`", "${", "xcConfigBuildFilePath", "}", "`", ")", ";", "addHeaderSearchPaths", "(", "xcConfigBuildFilePath", ")", ";", "}" ]
Modify the xcconfig build path and pass the resulting file path to the addHeaderSearchPaths function.
[ "Modify", "the", "xcconfig", "build", "path", "and", "pass", "the", "resulting", "file", "path", "to", "the", "addHeaderSearchPaths", "function", "." ]
d75349a1c4e5a4d6d6890c52fba9602df2ea6bc6
https://github.com/mattrayner/cordova-plugin-vuforia-sdk/blob/d75349a1c4e5a4d6d6890c52fba9602df2ea6bc6/hooks/AfterPluginInstall.js#L12-L26
train
mattrayner/cordova-plugin-vuforia-sdk
hooks/AfterPluginInstall.js
function(xcConfigBuildFilePath) { let lines = fs.readFileSync(xcConfigBuildFilePath, 'utf8').split('\n'); let paths = hookData.headerPaths; let headerSearchPathLineNumber; lines.forEach((l, i) => { if (l.indexOf('HEADER_SEARCH_PATHS') > -1) { headerSearchPathLineNumber = i; } }); if (headerSearchPathLineNumber) { for(let actualPath of paths) { if (lines[headerSearchPathLineNumber].indexOf(actualPath) == -1) { lines[headerSearchPathLineNumber] += ` ${actualPath}`; console.log(`${actualPath} was added to the search paths`); } else { console.log(`${actualPath} was already setup in build.xcconfig`); } } } else { lines[lines.length - 1] = 'HEADER_SEARCH_PATHS = '; for(let actualPath of paths) { lines[lines.length - 1] += actualPath; } } let newConfig = lines.join('\n'); fs.writeFile(xcConfigBuildFilePath, newConfig, function (err) { if (err) { console.log(`Error updating build.xcconfig: ${err}`); return; } console.log('Successfully updated HEADER_SEARCH_PATHS in build.xcconfig'); }); }
javascript
function(xcConfigBuildFilePath) { let lines = fs.readFileSync(xcConfigBuildFilePath, 'utf8').split('\n'); let paths = hookData.headerPaths; let headerSearchPathLineNumber; lines.forEach((l, i) => { if (l.indexOf('HEADER_SEARCH_PATHS') > -1) { headerSearchPathLineNumber = i; } }); if (headerSearchPathLineNumber) { for(let actualPath of paths) { if (lines[headerSearchPathLineNumber].indexOf(actualPath) == -1) { lines[headerSearchPathLineNumber] += ` ${actualPath}`; console.log(`${actualPath} was added to the search paths`); } else { console.log(`${actualPath} was already setup in build.xcconfig`); } } } else { lines[lines.length - 1] = 'HEADER_SEARCH_PATHS = '; for(let actualPath of paths) { lines[lines.length - 1] += actualPath; } } let newConfig = lines.join('\n'); fs.writeFile(xcConfigBuildFilePath, newConfig, function (err) { if (err) { console.log(`Error updating build.xcconfig: ${err}`); return; } console.log('Successfully updated HEADER_SEARCH_PATHS in build.xcconfig'); }); }
[ "function", "(", "xcConfigBuildFilePath", ")", "{", "let", "lines", "=", "fs", ".", "readFileSync", "(", "xcConfigBuildFilePath", ",", "'utf8'", ")", ".", "split", "(", "'\\n'", ")", ";", "\\n", "let", "paths", "=", "hookData", ".", "headerPaths", ";", "let", "headerSearchPathLineNumber", ";", "lines", ".", "forEach", "(", "(", "l", ",", "i", ")", "=>", "{", "if", "(", "l", ".", "indexOf", "(", "'HEADER_SEARCH_PATHS'", ")", ">", "-", "1", ")", "{", "headerSearchPathLineNumber", "=", "i", ";", "}", "}", ")", ";", "if", "(", "headerSearchPathLineNumber", ")", "{", "for", "(", "let", "actualPath", "of", "paths", ")", "{", "if", "(", "lines", "[", "headerSearchPathLineNumber", "]", ".", "indexOf", "(", "actualPath", ")", "==", "-", "1", ")", "{", "lines", "[", "headerSearchPathLineNumber", "]", "+=", "`", "${", "actualPath", "}", "`", ";", "console", ".", "log", "(", "`", "${", "actualPath", "}", "`", ")", ";", "}", "else", "{", "console", ".", "log", "(", "`", "${", "actualPath", "}", "`", ")", ";", "}", "}", "}", "else", "{", "lines", "[", "lines", ".", "length", "-", "1", "]", "=", "'HEADER_SEARCH_PATHS = '", ";", "for", "(", "let", "actualPath", "of", "paths", ")", "{", "lines", "[", "lines", ".", "length", "-", "1", "]", "+=", "actualPath", ";", "}", "}", "let", "newConfig", "=", "lines", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Read the build config, add the correct Header Search Paths to the config before calling modifyAppDelegate.
[ "Read", "the", "build", "config", "add", "the", "correct", "Header", "Search", "Paths", "to", "the", "config", "before", "calling", "modifyAppDelegate", "." ]
d75349a1c4e5a4d6d6890c52fba9602df2ea6bc6
https://github.com/mattrayner/cordova-plugin-vuforia-sdk/blob/d75349a1c4e5a4d6d6890c52fba9602df2ea6bc6/hooks/AfterPluginInstall.js#L29-L69
train
MattL922/implied-volatility
implied-volatility.js
getImpliedVolatility
function getImpliedVolatility(expectedCost, s, k, t, r, callPut, estimate) { estimate = estimate || .1; var low = 0; var high = Infinity; // perform 100 iterations max for(var i = 0; i < 100; i++) { var actualCost = bs.blackScholes(s, k, t, estimate, r, callPut); // compare the price down to the cent if(expectedCost * 100 == Math.floor(actualCost * 100)) { break; } else if(actualCost > expectedCost) { high = estimate; estimate = (estimate - low) / 2 + low } else { low = estimate; estimate = (high - estimate) / 2 + estimate; if(!isFinite(estimate)) estimate = low * 2; } } return estimate; }
javascript
function getImpliedVolatility(expectedCost, s, k, t, r, callPut, estimate) { estimate = estimate || .1; var low = 0; var high = Infinity; // perform 100 iterations max for(var i = 0; i < 100; i++) { var actualCost = bs.blackScholes(s, k, t, estimate, r, callPut); // compare the price down to the cent if(expectedCost * 100 == Math.floor(actualCost * 100)) { break; } else if(actualCost > expectedCost) { high = estimate; estimate = (estimate - low) / 2 + low } else { low = estimate; estimate = (high - estimate) / 2 + estimate; if(!isFinite(estimate)) estimate = low * 2; } } return estimate; }
[ "function", "getImpliedVolatility", "(", "expectedCost", ",", "s", ",", "k", ",", "t", ",", "r", ",", "callPut", ",", "estimate", ")", "{", "estimate", "=", "estimate", "||", ".1", ";", "var", "low", "=", "0", ";", "var", "high", "=", "Infinity", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "100", ";", "i", "++", ")", "{", "var", "actualCost", "=", "bs", ".", "blackScholes", "(", "s", ",", "k", ",", "t", ",", "estimate", ",", "r", ",", "callPut", ")", ";", "if", "(", "expectedCost", "*", "100", "==", "Math", ".", "floor", "(", "actualCost", "*", "100", ")", ")", "{", "break", ";", "}", "else", "if", "(", "actualCost", ">", "expectedCost", ")", "{", "high", "=", "estimate", ";", "estimate", "=", "(", "estimate", "-", "low", ")", "/", "2", "+", "low", "}", "else", "{", "low", "=", "estimate", ";", "estimate", "=", "(", "high", "-", "estimate", ")", "/", "2", "+", "estimate", ";", "if", "(", "!", "isFinite", "(", "estimate", ")", ")", "estimate", "=", "low", "*", "2", ";", "}", "}", "return", "estimate", ";", "}" ]
Calculate a close estimate of implied volatility given an option price. A binary search type approach is used to determine the implied volatility. @param {Number} expectedCost The market price of the option @param {Number} s Current price of the underlying @param {Number} k Strike price @param {Number} t Time to experiation in years @param {Number} r Anual risk-free interest rate as a decimal @param {String} callPut The type of option priced - "call" or "put" @param {Number} [estimate=.1] An initial estimate of implied volatility @returns {Number} The implied volatility estimate
[ "Calculate", "a", "close", "estimate", "of", "implied", "volatility", "given", "an", "option", "price", ".", "A", "binary", "search", "type", "approach", "is", "used", "to", "determine", "the", "implied", "volatility", "." ]
7b9a5e957d895645a46fd910769fe5243ed0d504
https://github.com/MattL922/implied-volatility/blob/7b9a5e957d895645a46fd910769fe5243ed0d504/implied-volatility.js#L23-L50
train
alexeykuzmin/jsonpointer.js
src/jsonpointer.js
getPointedValue
function getPointedValue(target, opt_pointer) { // .get() method implementation. // First argument must be either string or object. if (isString(target)) { // If string it must be valid JSON document. try { // Let's try to parse it as JSON. target = JSON.parse(target); } catch (e) { // If parsing failed, an exception will be thrown. throw getError(ErrorMessage.INVALID_DOCUMENT); } } else if (!isObject(target)) { // If not object or string, an exception will be thrown. throw getError(ErrorMessage.INVALID_DOCUMENT_TYPE); } // |target| is already parsed, let's create evaluator function for it. var evaluator = createPointerEvaluator(target); if (isUndefined(opt_pointer)) { // If pointer was not provided, return evaluator function. return evaluator; } else { // If pointer is provided, return evaluation result. return evaluator(opt_pointer); } }
javascript
function getPointedValue(target, opt_pointer) { // .get() method implementation. // First argument must be either string or object. if (isString(target)) { // If string it must be valid JSON document. try { // Let's try to parse it as JSON. target = JSON.parse(target); } catch (e) { // If parsing failed, an exception will be thrown. throw getError(ErrorMessage.INVALID_DOCUMENT); } } else if (!isObject(target)) { // If not object or string, an exception will be thrown. throw getError(ErrorMessage.INVALID_DOCUMENT_TYPE); } // |target| is already parsed, let's create evaluator function for it. var evaluator = createPointerEvaluator(target); if (isUndefined(opt_pointer)) { // If pointer was not provided, return evaluator function. return evaluator; } else { // If pointer is provided, return evaluation result. return evaluator(opt_pointer); } }
[ "function", "getPointedValue", "(", "target", ",", "opt_pointer", ")", "{", "if", "(", "isString", "(", "target", ")", ")", "{", "try", "{", "target", "=", "JSON", ".", "parse", "(", "target", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "getError", "(", "ErrorMessage", ".", "INVALID_DOCUMENT", ")", ";", "}", "}", "else", "if", "(", "!", "isObject", "(", "target", ")", ")", "{", "throw", "getError", "(", "ErrorMessage", ".", "INVALID_DOCUMENT_TYPE", ")", ";", "}", "var", "evaluator", "=", "createPointerEvaluator", "(", "target", ")", ";", "if", "(", "isUndefined", "(", "opt_pointer", ")", ")", "{", "return", "evaluator", ";", "}", "else", "{", "return", "evaluator", "(", "opt_pointer", ")", ";", "}", "}" ]
Returns |target| object's value pointed by |opt_pointer|, returns undefined if |opt_pointer| points to non-existing value. If pointer is not provided, validates first argument and returns evaluator function that takes pointer as argument. @param {(string|Object|Array)} target Evaluation target. @param {string=} opt_pointer JSON Pointer string. @returns {*} Some value.
[ "Returns", "|target|", "object", "s", "value", "pointed", "by", "|opt_pointer|", "returns", "undefined", "if", "|opt_pointer|", "points", "to", "non", "-", "existing", "value", ".", "If", "pointer", "is", "not", "provided", "validates", "first", "argument", "and", "returns", "evaluator", "function", "that", "takes", "pointer", "as", "argument", "." ]
57d7cf484d906792255a7c30cbb6c2d90d4ab152
https://github.com/alexeykuzmin/jsonpointer.js/blob/57d7cf484d906792255a7c30cbb6c2d90d4ab152/src/jsonpointer.js#L77-L109
train
alexeykuzmin/jsonpointer.js
src/jsonpointer.js
isValidJSONPointer
function isValidJSONPointer(pointer) { // Validates JSON pointer string. if (!isString(pointer)) { // If it's not a string, it obviously is not valid. return false; } if ('' === pointer) { // If it is string and is an empty string, it's valid. return true; } // If it is non-empty string, it must match spec defined format. // Check Section 3 of specification for concrete syntax. return NON_EMPTY_POINTER_REGEXP.test(pointer); }
javascript
function isValidJSONPointer(pointer) { // Validates JSON pointer string. if (!isString(pointer)) { // If it's not a string, it obviously is not valid. return false; } if ('' === pointer) { // If it is string and is an empty string, it's valid. return true; } // If it is non-empty string, it must match spec defined format. // Check Section 3 of specification for concrete syntax. return NON_EMPTY_POINTER_REGEXP.test(pointer); }
[ "function", "isValidJSONPointer", "(", "pointer", ")", "{", "if", "(", "!", "isString", "(", "pointer", ")", ")", "{", "return", "false", ";", "}", "if", "(", "''", "===", "pointer", ")", "{", "return", "true", ";", "}", "return", "NON_EMPTY_POINTER_REGEXP", ".", "test", "(", "pointer", ")", ";", "}" ]
Returns true if given |pointer| is valid, returns false otherwise. @param {!string} pointer @returns {boolean} Whether pointer is valid.
[ "Returns", "true", "if", "given", "|pointer|", "is", "valid", "returns", "false", "otherwise", "." ]
57d7cf484d906792255a7c30cbb6c2d90d4ab152
https://github.com/alexeykuzmin/jsonpointer.js/blob/57d7cf484d906792255a7c30cbb6c2d90d4ab152/src/jsonpointer.js#L164-L180
train
shaun-h/nodejs-disks
lib/disks.js
getDrives
function getDrives(command, callback) { var child = exec( command, function (err, stdout, stderr) { if (err) return callback(err); var drives = stdout.split('\n'); drives.splice(0, 1); drives.splice(-1, 1); // Removes ram drives drives = drives.filter(function(item){ return item != "none"}); callback(null, drives); } ); }
javascript
function getDrives(command, callback) { var child = exec( command, function (err, stdout, stderr) { if (err) return callback(err); var drives = stdout.split('\n'); drives.splice(0, 1); drives.splice(-1, 1); // Removes ram drives drives = drives.filter(function(item){ return item != "none"}); callback(null, drives); } ); }
[ "function", "getDrives", "(", "command", ",", "callback", ")", "{", "var", "child", "=", "exec", "(", "command", ",", "function", "(", "err", ",", "stdout", ",", "stderr", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "var", "drives", "=", "stdout", ".", "split", "(", "'\\n'", ")", ";", "\\n", "drives", ".", "splice", "(", "0", ",", "1", ")", ";", "drives", ".", "splice", "(", "-", "1", ",", "1", ")", ";", "drives", "=", "drives", ".", "filter", "(", "function", "(", "item", ")", "{", "return", "item", "!=", "\"none\"", "}", ")", ";", "}", ")", ";", "}" ]
Execute a command to retrieve disks list. @param command @param callback
[ "Execute", "a", "command", "to", "retrieve", "disks", "list", "." ]
615c2c6477dbf81ff693f0b2ff0c44f669d5892b
https://github.com/shaun-h/nodejs-disks/blob/615c2c6477dbf81ff693f0b2ff0c44f669d5892b/lib/disks.js#L29-L44
train
shaun-h/nodejs-disks
lib/disks.js
detail
function detail(drive, callback) { async.series( { used: function (callback) { switch (os.platform().toLowerCase()) { case'darwin': getDetail('df -kl | grep ' + drive + ' | awk \'{print $3}\'', callback); break; case'linux': default: getDetail('df -P | grep ' + drive + ' | awk \'{print $3}\'', callback); } }, available: function (callback) { switch (os.platform().toLowerCase()) { case'darwin': getDetail('df -kl | grep ' + drive + ' | awk \'{print $4}\'', callback); break; case'linux': default: getDetail('df -P | grep ' + drive + ' | awk \'{print $4}\'', callback); } }, mountpoint: function (callback) { switch (os.platform().toLowerCase()) { case'darwin': getDetailNaN('df -kl | grep ' + drive + ' | awk \'{print $9}\'', function(e, d){ if (d) d = d.trim(); callback(e, d); }); break; case'linux': default: getDetailNaN('df -P | grep ' + drive + ' | awk \'{print $6}\'', function(e, d){ if (d) d = d.trim(); callback(e, d); }); } } }, function (err, results) { if (err) return callback(err); results.freePer = Number(results.available / (results.used + results.available) * 100); results.usedPer = Number(results.used / (results.used + results.available) * 100); results.total = numeral(results.used + results.available).format('0.00 b'); results.used = numeral(results.used).format('0.00 b'); results.available = numeral(results.available).format('0.00 b'); results.drive = drive; callback(null, results); } ); }
javascript
function detail(drive, callback) { async.series( { used: function (callback) { switch (os.platform().toLowerCase()) { case'darwin': getDetail('df -kl | grep ' + drive + ' | awk \'{print $3}\'', callback); break; case'linux': default: getDetail('df -P | grep ' + drive + ' | awk \'{print $3}\'', callback); } }, available: function (callback) { switch (os.platform().toLowerCase()) { case'darwin': getDetail('df -kl | grep ' + drive + ' | awk \'{print $4}\'', callback); break; case'linux': default: getDetail('df -P | grep ' + drive + ' | awk \'{print $4}\'', callback); } }, mountpoint: function (callback) { switch (os.platform().toLowerCase()) { case'darwin': getDetailNaN('df -kl | grep ' + drive + ' | awk \'{print $9}\'', function(e, d){ if (d) d = d.trim(); callback(e, d); }); break; case'linux': default: getDetailNaN('df -P | grep ' + drive + ' | awk \'{print $6}\'', function(e, d){ if (d) d = d.trim(); callback(e, d); }); } } }, function (err, results) { if (err) return callback(err); results.freePer = Number(results.available / (results.used + results.available) * 100); results.usedPer = Number(results.used / (results.used + results.available) * 100); results.total = numeral(results.used + results.available).format('0.00 b'); results.used = numeral(results.used).format('0.00 b'); results.available = numeral(results.available).format('0.00 b'); results.drive = drive; callback(null, results); } ); }
[ "function", "detail", "(", "drive", ",", "callback", ")", "{", "async", ".", "series", "(", "{", "used", ":", "function", "(", "callback", ")", "{", "switch", "(", "os", ".", "platform", "(", ")", ".", "toLowerCase", "(", ")", ")", "{", "case", "'darwin'", ":", "getDetail", "(", "'df -kl | grep '", "+", "drive", "+", "' | awk \\'{print $3}\\''", ",", "\\'", ")", ";", "\\'", "callback", "break", ";", "}", "}", ",", "case", "'linux'", ":", ",", "default", ":", "getDetail", "(", "'df -P | grep '", "+", "drive", "+", "' | awk \\'{print $3}\\''", ",", "\\'", ")", ";", "}", ",", "\\'", ")", ";", "}" ]
Retrieve space information about one drive. @param drive @param callback
[ "Retrieve", "space", "information", "about", "one", "drive", "." ]
615c2c6477dbf81ff693f0b2ff0c44f669d5892b
https://github.com/shaun-h/nodejs-disks/blob/615c2c6477dbf81ff693f0b2ff0c44f669d5892b/lib/disks.js#L90-L142
train
71104/rwlock
src/lock.js
writeLock
function writeLock(key, callback, options) { var lock; if (typeof key !== 'function') { if (!table.hasOwnProperty(key)) { table[key] = new Lock(); } lock = table[key]; } else { options = callback; callback = key; lock = defaultLock; } if (!options) { options = {}; } var scope = null; if (options.hasOwnProperty('scope')) { scope = options.scope; } var release = (function () { var released = false; return function () { if (!released) { released = true; lock.readers = 0; if (lock.queue.length) { lock.queue[0](); } } }; }()); if (lock.readers || lock.queue.length) { var terminated = false; lock.queue.push(function () { if (!terminated && !lock.readers) { terminated = true; lock.queue.shift(); lock.readers = -1; callback.call(options.scope, release); } }); if (options.hasOwnProperty('timeout')) { var timeoutCallback = null; if (options.hasOwnProperty('timeoutCallback')) { timeoutCallback = options.timeoutCallback; } setTimeout(function () { if (!terminated) { terminated = true; lock.queue.shift(); if (timeoutCallback) { timeoutCallback.call(scope); } } }, options.timeout); } } else { lock.readers = -1; callback.call(options.scope, release); } }
javascript
function writeLock(key, callback, options) { var lock; if (typeof key !== 'function') { if (!table.hasOwnProperty(key)) { table[key] = new Lock(); } lock = table[key]; } else { options = callback; callback = key; lock = defaultLock; } if (!options) { options = {}; } var scope = null; if (options.hasOwnProperty('scope')) { scope = options.scope; } var release = (function () { var released = false; return function () { if (!released) { released = true; lock.readers = 0; if (lock.queue.length) { lock.queue[0](); } } }; }()); if (lock.readers || lock.queue.length) { var terminated = false; lock.queue.push(function () { if (!terminated && !lock.readers) { terminated = true; lock.queue.shift(); lock.readers = -1; callback.call(options.scope, release); } }); if (options.hasOwnProperty('timeout')) { var timeoutCallback = null; if (options.hasOwnProperty('timeoutCallback')) { timeoutCallback = options.timeoutCallback; } setTimeout(function () { if (!terminated) { terminated = true; lock.queue.shift(); if (timeoutCallback) { timeoutCallback.call(scope); } } }, options.timeout); } } else { lock.readers = -1; callback.call(options.scope, release); } }
[ "function", "writeLock", "(", "key", ",", "callback", ",", "options", ")", "{", "var", "lock", ";", "if", "(", "typeof", "key", "!==", "'function'", ")", "{", "if", "(", "!", "table", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "table", "[", "key", "]", "=", "new", "Lock", "(", ")", ";", "}", "lock", "=", "table", "[", "key", "]", ";", "}", "else", "{", "options", "=", "callback", ";", "callback", "=", "key", ";", "lock", "=", "defaultLock", ";", "}", "if", "(", "!", "options", ")", "{", "options", "=", "{", "}", ";", "}", "var", "scope", "=", "null", ";", "if", "(", "options", ".", "hasOwnProperty", "(", "'scope'", ")", ")", "{", "scope", "=", "options", ".", "scope", ";", "}", "var", "release", "=", "(", "function", "(", ")", "{", "var", "released", "=", "false", ";", "return", "function", "(", ")", "{", "if", "(", "!", "released", ")", "{", "released", "=", "true", ";", "lock", ".", "readers", "=", "0", ";", "if", "(", "lock", ".", "queue", ".", "length", ")", "{", "lock", ".", "queue", "[", "0", "]", "(", ")", ";", "}", "}", "}", ";", "}", "(", ")", ")", ";", "if", "(", "lock", ".", "readers", "||", "lock", ".", "queue", ".", "length", ")", "{", "var", "terminated", "=", "false", ";", "lock", ".", "queue", ".", "push", "(", "function", "(", ")", "{", "if", "(", "!", "terminated", "&&", "!", "lock", ".", "readers", ")", "{", "terminated", "=", "true", ";", "lock", ".", "queue", ".", "shift", "(", ")", ";", "lock", ".", "readers", "=", "-", "1", ";", "callback", ".", "call", "(", "options", ".", "scope", ",", "release", ")", ";", "}", "}", ")", ";", "if", "(", "options", ".", "hasOwnProperty", "(", "'timeout'", ")", ")", "{", "var", "timeoutCallback", "=", "null", ";", "if", "(", "options", ".", "hasOwnProperty", "(", "'timeoutCallback'", ")", ")", "{", "timeoutCallback", "=", "options", ".", "timeoutCallback", ";", "}", "setTimeout", "(", "function", "(", ")", "{", "if", "(", "!", "terminated", ")", "{", "terminated", "=", "true", ";", "lock", ".", "queue", ".", "shift", "(", ")", ";", "if", "(", "timeoutCallback", ")", "{", "timeoutCallback", ".", "call", "(", "scope", ")", ";", "}", "}", "}", ",", "options", ".", "timeout", ")", ";", "}", "}", "else", "{", "lock", ".", "readers", "=", "-", "1", ";", "callback", ".", "call", "(", "options", ".", "scope", ",", "release", ")", ";", "}", "}" ]
Acquires a write lock and invokes a user-defined callback as soon as it is acquired. The operation might require some time as there may be one or more readers. You can optionally specify a timeout in milliseconds: if it expires before a read lock can be acquired, this request is canceled and no lock will be acquired. The `key` argument allows you to work on a specific lock; omitting it will request the default lock. @method writeLock @param [key] {String} The name of the lock to write-acquire. The default lock will be requested if no key is specified. @param callback {Function} A user-defined function invoked as soon as a write lock is acquired. @param callback.release {Function} A function that releases the lock. This must be called by the ReadWriteLock user at some point, otherwise the write lock will remain and prevent future readers from operating. Anyway you do not necessarily need to call it inside the `callback` function: you can save a reference to the `release` function and call it later. @param [options] {Object} Further optional settings. @param [options.scope] {Object} An optional object to use as `this` when calling the `callback` function. @param [options.timeout] {Number} A timeout in milliseconds within which the lock must be acquired; if one ore more readers are still operating and the timeout expires the request is canceled and no lock is acquired. @param [options.timeoutCallback] {Function} An optional user-defined callback function that gets invokes in case the timeout expires before the lock can be acquired.
[ "Acquires", "a", "write", "lock", "and", "invokes", "a", "user", "-", "defined", "callback", "as", "soon", "as", "it", "is", "acquired", "." ]
86a1affae69c3ec8cd1adbb7dad75befb75ea74e
https://github.com/71104/rwlock/blob/86a1affae69c3ec8cd1adbb7dad75befb75ea74e/src/lock.js#L158-L218
train
http-auth/htdigest
src/processor.js
readPassword
function readPassword(program) { prompt.message = ""; prompt.delimiter = ""; const passportOption = [{name: 'password', description: 'New password:', hidden: true}]; const rePassportOption = [{name: 'rePassword', description: 'Re-type new password:', hidden: true}]; // Try to read password. prompt.get(passportOption, (err, result) => { if (!err) { const password = result.password; setTimeout(function () { prompt.get(rePassportOption, (err, result) => { if (!err && password == result.rePassword) { program.args.push(password); try { processor.syncFile(program); } catch (err) { console.error(err.message); } } else { console.error("\nPassword verification error."); } }); }, 50); } else { console.error("\nPassword verification error."); } }); }
javascript
function readPassword(program) { prompt.message = ""; prompt.delimiter = ""; const passportOption = [{name: 'password', description: 'New password:', hidden: true}]; const rePassportOption = [{name: 'rePassword', description: 'Re-type new password:', hidden: true}]; // Try to read password. prompt.get(passportOption, (err, result) => { if (!err) { const password = result.password; setTimeout(function () { prompt.get(rePassportOption, (err, result) => { if (!err && password == result.rePassword) { program.args.push(password); try { processor.syncFile(program); } catch (err) { console.error(err.message); } } else { console.error("\nPassword verification error."); } }); }, 50); } else { console.error("\nPassword verification error."); } }); }
[ "function", "readPassword", "(", "program", ")", "{", "prompt", ".", "message", "=", "\"\"", ";", "prompt", ".", "delimiter", "=", "\"\"", ";", "const", "passportOption", "=", "[", "{", "name", ":", "'password'", ",", "description", ":", "'New password:'", ",", "hidden", ":", "true", "}", "]", ";", "const", "rePassportOption", "=", "[", "{", "name", ":", "'rePassword'", ",", "description", ":", "'Re-type new password:'", ",", "hidden", ":", "true", "}", "]", ";", "prompt", ".", "get", "(", "passportOption", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "!", "err", ")", "{", "const", "password", "=", "result", ".", "password", ";", "setTimeout", "(", "function", "(", ")", "{", "prompt", ".", "get", "(", "rePassportOption", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "!", "err", "&&", "password", "==", "result", ".", "rePassword", ")", "{", "program", ".", "args", ".", "push", "(", "password", ")", ";", "try", "{", "processor", ".", "syncFile", "(", "program", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "error", "(", "err", ".", "message", ")", ";", "}", "}", "else", "{", "console", ".", "error", "(", "\"\\nPassword verification error.\"", ")", ";", "}", "}", ")", ";", "}", ",", "\\n", ")", ";", "}", "else", "50", "}", ")", ";", "}" ]
Read password.
[ "Read", "password", "." ]
be5222ea2a72509750d4b5822ce55b97ed658d63
https://github.com/http-auth/htdigest/blob/be5222ea2a72509750d4b5822ce55b97ed658d63/src/processor.js#L63-L93
train
alexhisen/mobx-form-store
src/FormStore.js
observableChanged
function observableChanged(change) { const store = this; action(() => { store.dataChanges.set(change.name, change.newValue); if (store.isSame(store.dataChanges.get(change.name), store.dataServer[change.name])) { store.dataChanges.delete(change.name); } })(); }
javascript
function observableChanged(change) { const store = this; action(() => { store.dataChanges.set(change.name, change.newValue); if (store.isSame(store.dataChanges.get(change.name), store.dataServer[change.name])) { store.dataChanges.delete(change.name); } })(); }
[ "function", "observableChanged", "(", "change", ")", "{", "const", "store", "=", "this", ";", "action", "(", "(", ")", "=>", "{", "store", ".", "dataChanges", ".", "set", "(", "change", ".", "name", ",", "change", ".", "newValue", ")", ";", "if", "(", "store", ".", "isSame", "(", "store", ".", "dataChanges", ".", "get", "(", "change", ".", "name", ")", ",", "store", ".", "dataServer", "[", "change", ".", "name", "]", ")", ")", "{", "store", ".", "dataChanges", ".", "delete", "(", "change", ".", "name", ")", ";", "}", "}", ")", "(", ")", ";", "}" ]
Observes data and if changes come, add them to dataChanges, unless it resets back to dataServer value, then clear that change @this {FormStore} @param {Object} change @param {String} change.name - name of property that changed @param {*} change.newValue
[ "Observes", "data", "and", "if", "changes", "come", "add", "them", "to", "dataChanges", "unless", "it", "resets", "back", "to", "dataServer", "value", "then", "clear", "that", "change" ]
c2058a883c4658aaaefcf1dc3429958c68d59343
https://github.com/alexhisen/mobx-form-store/blob/c2058a883c4658aaaefcf1dc3429958c68d59343/src/FormStore.js#L19-L28
train
alexhisen/mobx-form-store
src/FormStore.js
processSaveResponse
async function processSaveResponse(store, updates, response) { store.options.log(`[${store.options.name}] Response received from server.`); if (response.status === 'error') { action(() => { let errorFields = []; if (response.error) { if (typeof response.error === 'string') { store.serverError = response.error; } else { Object.assign(store.dataErrors, response.error); errorFields = Object.keys(response.error); } } // Supports an array of field names in error_field or a string errorFields = errorFields.concat(response.error_field); errorFields.forEach((field) => { if (store.options.autoSaveInterval && !store.dataErrors[field] && store.isSame(updates[field], store.data[field])) { store.data[field] = store.dataServer[field]; // revert or it'll keep trying to autosave it } delete updates[field]; // don't save it as the new dataServer value }); })(); } else { store.serverError = null; } Object.assign(store.dataServer, updates); action(() => { if (response.data) { Object.assign(store.dataServer, response.data); Object.assign(store.data, response.data); } store.dataChanges.forEach((value, key) => { if (store.isSame(value, store.dataServer[key])) { store.dataChanges.delete(key); } }); })(); if (typeof store.options.afterSave === 'function') { await store.options.afterSave(store, updates, response); } return response.status; }
javascript
async function processSaveResponse(store, updates, response) { store.options.log(`[${store.options.name}] Response received from server.`); if (response.status === 'error') { action(() => { let errorFields = []; if (response.error) { if (typeof response.error === 'string') { store.serverError = response.error; } else { Object.assign(store.dataErrors, response.error); errorFields = Object.keys(response.error); } } // Supports an array of field names in error_field or a string errorFields = errorFields.concat(response.error_field); errorFields.forEach((field) => { if (store.options.autoSaveInterval && !store.dataErrors[field] && store.isSame(updates[field], store.data[field])) { store.data[field] = store.dataServer[field]; // revert or it'll keep trying to autosave it } delete updates[field]; // don't save it as the new dataServer value }); })(); } else { store.serverError = null; } Object.assign(store.dataServer, updates); action(() => { if (response.data) { Object.assign(store.dataServer, response.data); Object.assign(store.data, response.data); } store.dataChanges.forEach((value, key) => { if (store.isSame(value, store.dataServer[key])) { store.dataChanges.delete(key); } }); })(); if (typeof store.options.afterSave === 'function') { await store.options.afterSave(store, updates, response); } return response.status; }
[ "async", "function", "processSaveResponse", "(", "store", ",", "updates", ",", "response", ")", "{", "store", ".", "options", ".", "log", "(", "`", "${", "store", ".", "options", ".", "name", "}", "`", ")", ";", "if", "(", "response", ".", "status", "===", "'error'", ")", "{", "action", "(", "(", ")", "=>", "{", "let", "errorFields", "=", "[", "]", ";", "if", "(", "response", ".", "error", ")", "{", "if", "(", "typeof", "response", ".", "error", "===", "'string'", ")", "{", "store", ".", "serverError", "=", "response", ".", "error", ";", "}", "else", "{", "Object", ".", "assign", "(", "store", ".", "dataErrors", ",", "response", ".", "error", ")", ";", "errorFields", "=", "Object", ".", "keys", "(", "response", ".", "error", ")", ";", "}", "}", "errorFields", "=", "errorFields", ".", "concat", "(", "response", ".", "error_field", ")", ";", "errorFields", ".", "forEach", "(", "(", "field", ")", "=>", "{", "if", "(", "store", ".", "options", ".", "autoSaveInterval", "&&", "!", "store", ".", "dataErrors", "[", "field", "]", "&&", "store", ".", "isSame", "(", "updates", "[", "field", "]", ",", "store", ".", "data", "[", "field", "]", ")", ")", "{", "store", ".", "data", "[", "field", "]", "=", "store", ".", "dataServer", "[", "field", "]", ";", "}", "delete", "updates", "[", "field", "]", ";", "}", ")", ";", "}", ")", "(", ")", ";", "}", "else", "{", "store", ".", "serverError", "=", "null", ";", "}", "Object", ".", "assign", "(", "store", ".", "dataServer", ",", "updates", ")", ";", "action", "(", "(", ")", "=>", "{", "if", "(", "response", ".", "data", ")", "{", "Object", ".", "assign", "(", "store", ".", "dataServer", ",", "response", ".", "data", ")", ";", "Object", ".", "assign", "(", "store", ".", "data", ",", "response", ".", "data", ")", ";", "}", "store", ".", "dataChanges", ".", "forEach", "(", "(", "value", ",", "key", ")", "=>", "{", "if", "(", "store", ".", "isSame", "(", "value", ",", "store", ".", "dataServer", "[", "key", "]", ")", ")", "{", "store", ".", "dataChanges", ".", "delete", "(", "key", ")", ";", "}", "}", ")", ";", "}", ")", "(", ")", ";", "if", "(", "typeof", "store", ".", "options", ".", "afterSave", "===", "'function'", ")", "{", "await", "store", ".", "options", ".", "afterSave", "(", "store", ",", "updates", ",", "response", ")", ";", "}", "return", "response", ".", "status", ";", "}" ]
Records successfully saved data as saved and reverts fields server indicates to be in error @param {FormStore} store @param {Object} updates - what we sent to the server @param {Object} response @param {String} [response.data] - optional updated data to merge into the store (server.create can return id here) @param {String} [response.status] - 'error' indicates one or more fields were invalid and not saved. @param {String|Object} [response.error] - either a single error message to show to user if string or field-specific error messages if object @param {String|Array} [response.error_field] - name of the field (or array of field names) in error If autoSave is enabled, any field in error_field for which there is no error message in response.error will be reverted to prevent autoSave from endlessly trying to save the changed field. @returns response.status
[ "Records", "successfully", "saved", "data", "as", "saved", "and", "reverts", "fields", "server", "indicates", "to", "be", "in", "error" ]
c2058a883c4658aaaefcf1dc3429958c68d59343
https://github.com/alexhisen/mobx-form-store/blob/c2058a883c4658aaaefcf1dc3429958c68d59343/src/FormStore.js#L43-L91
train
AZaviruha/react-form-generator
src/tools/routing.js
buildRouter
function buildRouter () { var args = g.argsToArray( arguments ) , simpleConf = {} , regexpConf = [] , reLength , i, len, route, handlers; if ( (args.length === 0) || (args.length % 2 !== 0) ) throw new Error( 'Wrong number of arguments!' ); for ( i = 0, len = args.length; i < len; i+=2 ) { route = args[ i ]; handlers = args[ i + 1 ]; if ( route instanceof RegExp ) regexpConf.push([ route, handlers ]); else simpleConf[ route ] = handlers; } reLength = regexpConf.length; /** * Search path in `simpleConf` and `regexpConf` * and runs all handlers of mathed path. * @param {String} path - path to route. */ return function route ( path ) { var values = g.argsToArray( arguments ).slice( 1 ) , checkedPath, handlers , i, len; /** Checks simple routes first. */ handlers = simpleConf[ path ]; /** Checks regexp routes last. */ if ( !g.getOrNull( handlers, 'length' ) ) for ( i = 0; i < reLength; i++ ) { checkedPath = regexpConf[ i ][ 0 ]; if ( checkedPath.test(path) ) { handlers = regexpConf[ i ][ 1 ]; break; } } /** Run each handler of matched route. */ if ( handlers && handlers.length ) for ( i = 0, len = handlers.length; i < len; i++ ) { handlers[ i ].apply( this, values ); } }; }
javascript
function buildRouter () { var args = g.argsToArray( arguments ) , simpleConf = {} , regexpConf = [] , reLength , i, len, route, handlers; if ( (args.length === 0) || (args.length % 2 !== 0) ) throw new Error( 'Wrong number of arguments!' ); for ( i = 0, len = args.length; i < len; i+=2 ) { route = args[ i ]; handlers = args[ i + 1 ]; if ( route instanceof RegExp ) regexpConf.push([ route, handlers ]); else simpleConf[ route ] = handlers; } reLength = regexpConf.length; /** * Search path in `simpleConf` and `regexpConf` * and runs all handlers of mathed path. * @param {String} path - path to route. */ return function route ( path ) { var values = g.argsToArray( arguments ).slice( 1 ) , checkedPath, handlers , i, len; /** Checks simple routes first. */ handlers = simpleConf[ path ]; /** Checks regexp routes last. */ if ( !g.getOrNull( handlers, 'length' ) ) for ( i = 0; i < reLength; i++ ) { checkedPath = regexpConf[ i ][ 0 ]; if ( checkedPath.test(path) ) { handlers = regexpConf[ i ][ 1 ]; break; } } /** Run each handler of matched route. */ if ( handlers && handlers.length ) for ( i = 0, len = handlers.length; i < len; i++ ) { handlers[ i ].apply( this, values ); } }; }
[ "function", "buildRouter", "(", ")", "{", "var", "args", "=", "g", ".", "argsToArray", "(", "arguments", ")", ",", "simpleConf", "=", "{", "}", ",", "regexpConf", "=", "[", "]", ",", "reLength", ",", "i", ",", "len", ",", "route", ",", "handlers", ";", "if", "(", "(", "args", ".", "length", "===", "0", ")", "||", "(", "args", ".", "length", "%", "2", "!==", "0", ")", ")", "throw", "new", "Error", "(", "'Wrong number of arguments!'", ")", ";", "for", "(", "i", "=", "0", ",", "len", "=", "args", ".", "length", ";", "i", "<", "len", ";", "i", "+=", "2", ")", "{", "route", "=", "args", "[", "i", "]", ";", "handlers", "=", "args", "[", "i", "+", "1", "]", ";", "if", "(", "route", "instanceof", "RegExp", ")", "regexpConf", ".", "push", "(", "[", "route", ",", "handlers", "]", ")", ";", "else", "simpleConf", "[", "route", "]", "=", "handlers", ";", "}", "reLength", "=", "regexpConf", ".", "length", ";", "return", "function", "route", "(", "path", ")", "{", "var", "values", "=", "g", ".", "argsToArray", "(", "arguments", ")", ".", "slice", "(", "1", ")", ",", "checkedPath", ",", "handlers", ",", "i", ",", "len", ";", "handlers", "=", "simpleConf", "[", "path", "]", ";", "if", "(", "!", "g", ".", "getOrNull", "(", "handlers", ",", "'length'", ")", ")", "for", "(", "i", "=", "0", ";", "i", "<", "reLength", ";", "i", "++", ")", "{", "checkedPath", "=", "regexpConf", "[", "i", "]", "[", "0", "]", ";", "if", "(", "checkedPath", ".", "test", "(", "path", ")", ")", "{", "handlers", "=", "regexpConf", "[", "i", "]", "[", "1", "]", ";", "break", ";", "}", "}", "if", "(", "handlers", "&&", "handlers", ".", "length", ")", "for", "(", "i", "=", "0", ",", "len", "=", "handlers", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "handlers", "[", "i", "]", ".", "apply", "(", "this", ",", "values", ")", ";", "}", "}", ";", "}" ]
Builds a routing function, that matches event's name to the list of handlers and executes all of them. @param {string|RegExp} event1 - event's mask. @param [Function] handlers1 - handlers for event1. @param {string|RegExp} event2 - event's mask. @param [Function] handlers2 - handlers for event2. ... @returns {Function}
[ "Builds", "a", "routing", "function", "that", "matches", "event", "s", "name", "to", "the", "list", "of", "handlers", "and", "executes", "all", "of", "them", "." ]
d3ce8ef216f9d888f5ed641c33456821fce902c2
https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/tools/routing.js#L15-L66
train
AZaviruha/react-form-generator
src/validation/index.js
composite
function composite ( comb, zero ) { return function ( conf, value, fieldMeta ) { var validators = conf.value; return reduce(function ( acc, v ) { var f = VALIDATORS[ v.rule ]; checkRuleExistence( f, v.rule ); return comb( acc, f( v, value, fieldMeta ) ); }, zero, validators ); }; }
javascript
function composite ( comb, zero ) { return function ( conf, value, fieldMeta ) { var validators = conf.value; return reduce(function ( acc, v ) { var f = VALIDATORS[ v.rule ]; checkRuleExistence( f, v.rule ); return comb( acc, f( v, value, fieldMeta ) ); }, zero, validators ); }; }
[ "function", "composite", "(", "comb", ",", "zero", ")", "{", "return", "function", "(", "conf", ",", "value", ",", "fieldMeta", ")", "{", "var", "validators", "=", "conf", ".", "value", ";", "return", "reduce", "(", "function", "(", "acc", ",", "v", ")", "{", "var", "f", "=", "VALIDATORS", "[", "v", ".", "rule", "]", ";", "checkRuleExistence", "(", "f", ",", "v", ".", "rule", ")", ";", "return", "comb", "(", "acc", ",", "f", "(", "v", ",", "value", ",", "fieldMeta", ")", ")", ";", "}", ",", "zero", ",", "validators", ")", ";", "}", ";", "}" ]
Build composite validator, which combines result of all nested validators by `comb` function. @param {Function} comp - `and`, `or`, etc. @param {Object} zero - intital value of composite validator result. @returns {Function)
[ "Build", "composite", "validator", "which", "combines", "result", "of", "all", "nested", "validators", "by", "comb", "function", "." ]
d3ce8ef216f9d888f5ed641c33456821fce902c2
https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/validation/index.js#L32-L41
train
AZaviruha/react-form-generator
src/validation/index.js
checkByRule
function checkByRule ( ruleInfo, value, fieldMeta ) { var rule = ruleInfo.rule , isValid = VALIDATORS[ rule ]; checkRuleExistence( isValid, rule ); return isValid( ruleInfo, value, fieldMeta ) ? null : ruleInfo; }
javascript
function checkByRule ( ruleInfo, value, fieldMeta ) { var rule = ruleInfo.rule , isValid = VALIDATORS[ rule ]; checkRuleExistence( isValid, rule ); return isValid( ruleInfo, value, fieldMeta ) ? null : ruleInfo; }
[ "function", "checkByRule", "(", "ruleInfo", ",", "value", ",", "fieldMeta", ")", "{", "var", "rule", "=", "ruleInfo", ".", "rule", ",", "isValid", "=", "VALIDATORS", "[", "rule", "]", ";", "checkRuleExistence", "(", "isValid", ",", "rule", ")", ";", "return", "isValid", "(", "ruleInfo", ",", "value", ",", "fieldMeta", ")", "?", "null", ":", "ruleInfo", ";", "}" ]
Validates field's value against of validation rule. Returs sublist of validateion rules that was not sutisfied by value. @param {Object} ruleInfo - validation rules. @param {Object} value - value to validate. @param {Object} fieldMeta - for some validation rules field meta is required. @returns {Object}
[ "Validates", "field", "s", "value", "against", "of", "validation", "rule", ".", "Returs", "sublist", "of", "validateion", "rules", "that", "was", "not", "sutisfied", "by", "value", "." ]
d3ce8ef216f9d888f5ed641c33456821fce902c2
https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/validation/index.js#L54-L60
train
AZaviruha/react-form-generator
src/validation/index.js
checkByAll
function checkByAll ( rules, value, fieldMeta ) { return (rules || []) .map(function ( rule ) { return checkByRule( rule, value, fieldMeta ); }) .filter(function ( el ) { return null !== el; }); }
javascript
function checkByAll ( rules, value, fieldMeta ) { return (rules || []) .map(function ( rule ) { return checkByRule( rule, value, fieldMeta ); }) .filter(function ( el ) { return null !== el; }); }
[ "function", "checkByAll", "(", "rules", ",", "value", ",", "fieldMeta", ")", "{", "return", "(", "rules", "||", "[", "]", ")", ".", "map", "(", "function", "(", "rule", ")", "{", "return", "checkByRule", "(", "rule", ",", "value", ",", "fieldMeta", ")", ";", "}", ")", ".", "filter", "(", "function", "(", "el", ")", "{", "return", "null", "!==", "el", ";", "}", ")", ";", "}" ]
Validates field's value against list of validation rules. Returs sublist of validation rules that was not sutisfied by value. @param {Object[]} rules - list of validation rules. @param {Object} value - value to validate. @returns {Object[]}
[ "Validates", "field", "s", "value", "against", "list", "of", "validation", "rules", ".", "Returs", "sublist", "of", "validation", "rules", "that", "was", "not", "sutisfied", "by", "value", "." ]
d3ce8ef216f9d888f5ed641c33456821fce902c2
https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/validation/index.js#L76-L82
train
AZaviruha/react-form-generator
src/validation/index.js
validateField
function validateField ( fldID, fieldMeta, value ) { var res = {} , errs = checkByAll( fieldMeta.validators, value, fieldMeta ); res[ fldID ] = errs.length ? errs : null; return res; }
javascript
function validateField ( fldID, fieldMeta, value ) { var res = {} , errs = checkByAll( fieldMeta.validators, value, fieldMeta ); res[ fldID ] = errs.length ? errs : null; return res; }
[ "function", "validateField", "(", "fldID", ",", "fieldMeta", ",", "value", ")", "{", "var", "res", "=", "{", "}", ",", "errs", "=", "checkByAll", "(", "fieldMeta", ".", "validators", ",", "value", ",", "fieldMeta", ")", ";", "res", "[", "fldID", "]", "=", "errs", ".", "length", "?", "errs", ":", "null", ";", "return", "res", ";", "}" ]
Calculates field's validity by it's meta and value. @param {Object} fieldMeta - metadata of one field in FormGenerator format. @param {Object} value - { %fieldID%: %fieldValue% } @return {Object[]} - [ %failed_validators% ]
[ "Calculates", "field", "s", "validity", "by", "it", "s", "meta", "and", "value", "." ]
d3ce8ef216f9d888f5ed641c33456821fce902c2
https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/validation/index.js#L92-L97
train
AZaviruha/react-form-generator
src/validation/index.js
validateFields
function validateFields ( fldsMeta, fldsValue ) { return reduce(function ( acc, fldMeta, fldID ) { var value = getOrNull( fldsValue, fldID ) , errors = validateField( fldID, fldMeta, value ); return t.merge( acc, errors ); }, {}, fldsMeta ); }
javascript
function validateFields ( fldsMeta, fldsValue ) { return reduce(function ( acc, fldMeta, fldID ) { var value = getOrNull( fldsValue, fldID ) , errors = validateField( fldID, fldMeta, value ); return t.merge( acc, errors ); }, {}, fldsMeta ); }
[ "function", "validateFields", "(", "fldsMeta", ",", "fldsValue", ")", "{", "return", "reduce", "(", "function", "(", "acc", ",", "fldMeta", ",", "fldID", ")", "{", "var", "value", "=", "getOrNull", "(", "fldsValue", ",", "fldID", ")", ",", "errors", "=", "validateField", "(", "fldID", ",", "fldMeta", ",", "value", ")", ";", "return", "t", ".", "merge", "(", "acc", ",", "errors", ")", ";", "}", ",", "{", "}", ",", "fldsMeta", ")", ";", "}" ]
Calculates validity of the array of fields. @param {Object[]} fldsMeta - array of metadata. @param {Object[]} fldsValue - map with fields value. @returns {Object} - { %fieldID%: [ %failed_validators% ], ... }
[ "Calculates", "validity", "of", "the", "array", "of", "fields", "." ]
d3ce8ef216f9d888f5ed641c33456821fce902c2
https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/validation/index.js#L109-L115
train
AZaviruha/react-form-generator
src/validation/index.js
validateForm
function validateForm ( formMeta, formValue ) { var fields = getOrNull( formMeta, 'fields' ) , validable = reduce(function ( acc, fld, fldID ) { var noValidate = !t.isDefined( fld.validators ) || fld.isHidden || fld.isReadOnly , fldMeta = {}; if ( noValidate ) return acc; else { fldMeta[ fldID ] = fld; return t.merge( acc, fldMeta ); } }, {}, fields ); return validateFields( validable, formValue ); }
javascript
function validateForm ( formMeta, formValue ) { var fields = getOrNull( formMeta, 'fields' ) , validable = reduce(function ( acc, fld, fldID ) { var noValidate = !t.isDefined( fld.validators ) || fld.isHidden || fld.isReadOnly , fldMeta = {}; if ( noValidate ) return acc; else { fldMeta[ fldID ] = fld; return t.merge( acc, fldMeta ); } }, {}, fields ); return validateFields( validable, formValue ); }
[ "function", "validateForm", "(", "formMeta", ",", "formValue", ")", "{", "var", "fields", "=", "getOrNull", "(", "formMeta", ",", "'fields'", ")", ",", "validable", "=", "reduce", "(", "function", "(", "acc", ",", "fld", ",", "fldID", ")", "{", "var", "noValidate", "=", "!", "t", ".", "isDefined", "(", "fld", ".", "validators", ")", "||", "fld", ".", "isHidden", "||", "fld", ".", "isReadOnly", ",", "fldMeta", "=", "{", "}", ";", "if", "(", "noValidate", ")", "return", "acc", ";", "else", "{", "fldMeta", "[", "fldID", "]", "=", "fld", ";", "return", "t", ".", "merge", "(", "acc", ",", "fldMeta", ")", ";", "}", "}", ",", "{", "}", ",", "fields", ")", ";", "return", "validateFields", "(", "validable", ",", "formValue", ")", ";", "}" ]
Calculates form's validity by it's meta and value. Wraps `validateFields` and filters array of fields before validation. @param {Object} formMeta - metadata in GeneratedForm format. @param {Object} formValue - data in GeneratedForm format. @returns {Object} - { %fieldID%: [ %failed_validators% ], ... }
[ "Calculates", "form", "s", "validity", "by", "it", "s", "meta", "and", "value", ".", "Wraps", "validateFields", "and", "filters", "array", "of", "fields", "before", "validation", "." ]
d3ce8ef216f9d888f5ed641c33456821fce902c2
https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/validation/index.js#L129-L146
train
AZaviruha/react-form-generator
src/validation/index.js
isFormValid
function isFormValid ( formErrors ) { return t.reduce(function ( acc, v, k ) { return acc && !(v && v.length); }, true, formErrors ); }
javascript
function isFormValid ( formErrors ) { return t.reduce(function ( acc, v, k ) { return acc && !(v && v.length); }, true, formErrors ); }
[ "function", "isFormValid", "(", "formErrors", ")", "{", "return", "t", ".", "reduce", "(", "function", "(", "acc", ",", "v", ",", "k", ")", "{", "return", "acc", "&&", "!", "(", "v", "&&", "v", ".", "length", ")", ";", "}", ",", "true", ",", "formErrors", ")", ";", "}" ]
Accepts result of `validateForm` and returns true if `formErrors` contains only null-values. @param {Object} formErrors - { %fieldID%: [ %failed_validators% ], ... } @returns {Boolean}
[ "Accepts", "result", "of", "validateForm", "and", "returns", "true", "if", "formErrors", "contains", "only", "null", "-", "values", "." ]
d3ce8ef216f9d888f5ed641c33456821fce902c2
https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/validation/index.js#L158-L162
train
julienetie/resizilla
dist/resizilla.js
setTimeoutWithTimestamp
function setTimeoutWithTimestamp(callback) { const immediateTime = Date.now(); let lapsedTime = Math.max(previousTime + 16, immediateTime); return setTimeout(function () { callback(previousTime = lapsedTime); }, lapsedTime - immediateTime); }
javascript
function setTimeoutWithTimestamp(callback) { const immediateTime = Date.now(); let lapsedTime = Math.max(previousTime + 16, immediateTime); return setTimeout(function () { callback(previousTime = lapsedTime); }, lapsedTime - immediateTime); }
[ "function", "setTimeoutWithTimestamp", "(", "callback", ")", "{", "const", "immediateTime", "=", "Date", ".", "now", "(", ")", ";", "let", "lapsedTime", "=", "Math", ".", "max", "(", "previousTime", "+", "16", ",", "immediateTime", ")", ";", "return", "setTimeout", "(", "function", "(", ")", "{", "callback", "(", "previousTime", "=", "lapsedTime", ")", ";", "}", ",", "lapsedTime", "-", "immediateTime", ")", ";", "}" ]
IE-9 Polyfill for requestAnimationFrame @callback {Number} Timestamp. @return {Function} setTimeout Function.
[ "IE", "-", "9", "Polyfill", "for", "requestAnimationFrame" ]
a73b4177dcf303438c6a93e8d33bd6dd578d3910
https://github.com/julienetie/resizilla/blob/a73b4177dcf303438c6a93e8d33bd6dd578d3910/dist/resizilla.js#L45-L51
train
julienetie/resizilla
dist/resizilla.js
debounce
function debounce(callback, delay, lead) { var debounceRange = 0; var currentTime; var lastCall; var setDelay; var timeoutId; const call = parameters => { callback(parameters); }; return parameters => { if (lead) { currentTime = Date.now(); if (currentTime > debounceRange) { callback(parameters); } debounceRange = currentTime + delay; } else { /** * setTimeout is only used with the trail option. */ clearTimeout(timeoutId); timeoutId = setTimeout(function () { call(parameters); }, delay); } }; }
javascript
function debounce(callback, delay, lead) { var debounceRange = 0; var currentTime; var lastCall; var setDelay; var timeoutId; const call = parameters => { callback(parameters); }; return parameters => { if (lead) { currentTime = Date.now(); if (currentTime > debounceRange) { callback(parameters); } debounceRange = currentTime + delay; } else { /** * setTimeout is only used with the trail option. */ clearTimeout(timeoutId); timeoutId = setTimeout(function () { call(parameters); }, delay); } }; }
[ "function", "debounce", "(", "callback", ",", "delay", ",", "lead", ")", "{", "var", "debounceRange", "=", "0", ";", "var", "currentTime", ";", "var", "lastCall", ";", "var", "setDelay", ";", "var", "timeoutId", ";", "const", "call", "=", "parameters", "=>", "{", "callback", "(", "parameters", ")", ";", "}", ";", "return", "parameters", "=>", "{", "if", "(", "lead", ")", "{", "currentTime", "=", "Date", ".", "now", "(", ")", ";", "if", "(", "currentTime", ">", "debounceRange", ")", "{", "callback", "(", "parameters", ")", ";", "}", "debounceRange", "=", "currentTime", "+", "delay", ";", "}", "else", "{", "clearTimeout", "(", "timeoutId", ")", ";", "timeoutId", "=", "setTimeout", "(", "function", "(", ")", "{", "call", "(", "parameters", ")", ";", "}", ",", "delay", ")", ";", "}", "}", ";", "}" ]
Debounce a function call during repetiton. @param {Function} callback - Callback function. @param {Number} delay - Delay in milliseconds. @param {Boolean} lead - Leading or trailing. @return {Function} - The debounce function.
[ "Debounce", "a", "function", "call", "during", "repetiton", "." ]
a73b4177dcf303438c6a93e8d33bd6dd578d3910
https://github.com/julienetie/resizilla/blob/a73b4177dcf303438c6a93e8d33bd6dd578d3910/dist/resizilla.js#L90-L118
train
timwhitlock/node-twitter-api
lib/twitter.js
uriEncodeParams
function uriEncodeParams( obj ){ var pairs = [], key; for( key in obj ){ pairs.push( uriEncodeString(key) +'='+ uriEncodeString(obj[key]) ); } return pairs.join('&'); }
javascript
function uriEncodeParams( obj ){ var pairs = [], key; for( key in obj ){ pairs.push( uriEncodeString(key) +'='+ uriEncodeString(obj[key]) ); } return pairs.join('&'); }
[ "function", "uriEncodeParams", "(", "obj", ")", "{", "var", "pairs", "=", "[", "]", ",", "key", ";", "for", "(", "key", "in", "obj", ")", "{", "pairs", ".", "push", "(", "uriEncodeString", "(", "key", ")", "+", "'='", "+", "uriEncodeString", "(", "obj", "[", "key", "]", ")", ")", ";", "}", "return", "pairs", ".", "join", "(", "'&'", ")", ";", "}" ]
OAuth safe encodeURIComponent of params object
[ "OAuth", "safe", "encodeURIComponent", "of", "params", "object" ]
6ac423f9c718153c7fac24ce76fb6ae90707ec30
https://github.com/timwhitlock/node-twitter-api/blob/6ac423f9c718153c7fac24ce76fb6ae90707ec30/lib/twitter.js#L39-L45
train
timwhitlock/node-twitter-api
lib/twitter.js
OAuthToken
function OAuthToken( key, secret ){ if( ! key || ! secret ){ throw new Error('OAuthToken params must not be empty'); } this.key = key; this.secret = secret; }
javascript
function OAuthToken( key, secret ){ if( ! key || ! secret ){ throw new Error('OAuthToken params must not be empty'); } this.key = key; this.secret = secret; }
[ "function", "OAuthToken", "(", "key", ",", "secret", ")", "{", "if", "(", "!", "key", "||", "!", "secret", ")", "{", "throw", "new", "Error", "(", "'OAuthToken params must not be empty'", ")", ";", "}", "this", ".", "key", "=", "key", ";", "this", ".", "secret", "=", "secret", ";", "}" ]
Simple token object that holds key and secret
[ "Simple", "token", "object", "that", "holds", "key", "and", "secret" ]
6ac423f9c718153c7fac24ce76fb6ae90707ec30
https://github.com/timwhitlock/node-twitter-api/blob/6ac423f9c718153c7fac24ce76fb6ae90707ec30/lib/twitter.js#L51-L57
train
FormidableLabs/multibot
lib/repos.js
function (cb) { async.map(self._repos, function (repo, repoCb) { self._client.gitdata.getReference({ user: self._repoParts[repo].org, repo: self._repoParts[repo].repo, ref: branchSrcFull }, function (err, res) { if (self._checkAndHandleError(err, repo, repoCb)) { return; } repoCb(null, { repo: repo, sha: res.object.sha }); }); }, cb); }
javascript
function (cb) { async.map(self._repos, function (repo, repoCb) { self._client.gitdata.getReference({ user: self._repoParts[repo].org, repo: self._repoParts[repo].repo, ref: branchSrcFull }, function (err, res) { if (self._checkAndHandleError(err, repo, repoCb)) { return; } repoCb(null, { repo: repo, sha: res.object.sha }); }); }, cb); }
[ "function", "(", "cb", ")", "{", "async", ".", "map", "(", "self", ".", "_repos", ",", "function", "(", "repo", ",", "repoCb", ")", "{", "self", ".", "_client", ".", "gitdata", ".", "getReference", "(", "{", "user", ":", "self", ".", "_repoParts", "[", "repo", "]", ".", "org", ",", "repo", ":", "self", ".", "_repoParts", "[", "repo", "]", ".", "repo", ",", "ref", ":", "branchSrcFull", "}", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "self", ".", "_checkAndHandleError", "(", "err", ",", "repo", ",", "repoCb", ")", ")", "{", "return", ";", "}", "repoCb", "(", "null", ",", "{", "repo", ":", "repo", ",", "sha", ":", "res", ".", "object", ".", "sha", "}", ")", ";", "}", ")", ";", "}", ",", "cb", ")", ";", "}" ]
Get the most recent commit of the source branch.
[ "Get", "the", "most", "recent", "commit", "of", "the", "source", "branch", "." ]
2434455354f74926aa85b2bbf2eb1548e873cc82
https://github.com/FormidableLabs/multibot/blob/2434455354f74926aa85b2bbf2eb1548e873cc82/lib/repos.js#L372-L386
train
FormidableLabs/multibot
lib/repos.js
function (cb) { async.map(self._repos, function (repo, repoCb) { self._client.gitdata.getReference({ user: self._repoParts[repo].org, repo: self._repoParts[repo].repo, ref: branchDestFull }, function (err, res) { // Allow not found. if (err && err.code === NOT_FOUND) { repoCb(null, { repo: repo, exists: false, sha: null }); return; } // Real error. if (self._checkAndHandleError(err, "branch.getDestRefs - " + repo, repoCb)) { return; } // Error if existing branches are not allowed. var sha = res.object.sha; if (!self._allowExisting) { self._checkAndHandleError( new Error("Found existing dest branch in repo: " + repo + " with sha: " + sha), null, repoCb); return; } // Have an allowed, existing branch. repoCb(null, { repo: repo, exists: true, sha: sha }); }); }, cb); }
javascript
function (cb) { async.map(self._repos, function (repo, repoCb) { self._client.gitdata.getReference({ user: self._repoParts[repo].org, repo: self._repoParts[repo].repo, ref: branchDestFull }, function (err, res) { // Allow not found. if (err && err.code === NOT_FOUND) { repoCb(null, { repo: repo, exists: false, sha: null }); return; } // Real error. if (self._checkAndHandleError(err, "branch.getDestRefs - " + repo, repoCb)) { return; } // Error if existing branches are not allowed. var sha = res.object.sha; if (!self._allowExisting) { self._checkAndHandleError( new Error("Found existing dest branch in repo: " + repo + " with sha: " + sha), null, repoCb); return; } // Have an allowed, existing branch. repoCb(null, { repo: repo, exists: true, sha: sha }); }); }, cb); }
[ "function", "(", "cb", ")", "{", "async", ".", "map", "(", "self", ".", "_repos", ",", "function", "(", "repo", ",", "repoCb", ")", "{", "self", ".", "_client", ".", "gitdata", ".", "getReference", "(", "{", "user", ":", "self", ".", "_repoParts", "[", "repo", "]", ".", "org", ",", "repo", ":", "self", ".", "_repoParts", "[", "repo", "]", ".", "repo", ",", "ref", ":", "branchDestFull", "}", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", "&&", "err", ".", "code", "===", "NOT_FOUND", ")", "{", "repoCb", "(", "null", ",", "{", "repo", ":", "repo", ",", "exists", ":", "false", ",", "sha", ":", "null", "}", ")", ";", "return", ";", "}", "if", "(", "self", ".", "_checkAndHandleError", "(", "err", ",", "\"branch.getDestRefs - \"", "+", "repo", ",", "repoCb", ")", ")", "{", "return", ";", "}", "var", "sha", "=", "res", ".", "object", ".", "sha", ";", "if", "(", "!", "self", ".", "_allowExisting", ")", "{", "self", ".", "_checkAndHandleError", "(", "new", "Error", "(", "\"Found existing dest branch in repo: \"", "+", "repo", "+", "\" with sha: \"", "+", "sha", ")", ",", "null", ",", "repoCb", ")", ";", "return", ";", "}", "repoCb", "(", "null", ",", "{", "repo", ":", "repo", ",", "exists", ":", "true", ",", "sha", ":", "sha", "}", ")", ";", "}", ")", ";", "}", ",", "cb", ")", ";", "}" ]
Check if the destination branches exist.
[ "Check", "if", "the", "destination", "branches", "exist", "." ]
2434455354f74926aa85b2bbf2eb1548e873cc82
https://github.com/FormidableLabs/multibot/blob/2434455354f74926aa85b2bbf2eb1548e873cc82/lib/repos.js#L389-L429
train
balderdashy/angularSails
lib/sails.io.js
ajax
function ajax(opts, cb) { opts = opts || {}; var xmlhttp; if (typeof window === 'undefined') { // TODO: refactor node usage to live in here return cb(); } if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { cb(xmlhttp.responseText); } }; xmlhttp.open(opts.method, opts.url, true); xmlhttp.send(); return xmlhttp; }
javascript
function ajax(opts, cb) { opts = opts || {}; var xmlhttp; if (typeof window === 'undefined') { // TODO: refactor node usage to live in here return cb(); } if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { cb(xmlhttp.responseText); } }; xmlhttp.open(opts.method, opts.url, true); xmlhttp.send(); return xmlhttp; }
[ "function", "ajax", "(", "opts", ",", "cb", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "var", "xmlhttp", ";", "if", "(", "typeof", "window", "===", "'undefined'", ")", "{", "return", "cb", "(", ")", ";", "}", "if", "(", "window", ".", "XMLHttpRequest", ")", "{", "xmlhttp", "=", "new", "XMLHttpRequest", "(", ")", ";", "}", "else", "{", "xmlhttp", "=", "new", "ActiveXObject", "(", "\"Microsoft.XMLHTTP\"", ")", ";", "}", "xmlhttp", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "xmlhttp", ".", "readyState", "==", "4", "&&", "xmlhttp", ".", "status", "==", "200", ")", "{", "cb", "(", "xmlhttp", ".", "responseText", ")", ";", "}", "}", ";", "xmlhttp", ".", "open", "(", "opts", ".", "method", ",", "opts", ".", "url", ",", "true", ")", ";", "xmlhttp", ".", "send", "(", ")", ";", "return", "xmlhttp", ";", "}" ]
Send an AJAX request. @param {Object} opts [optional] @param {Function} cb @return {XMLHttpRequest}
[ "Send", "an", "AJAX", "request", "." ]
1deb8a05d737e5cb9224096378ebe949586cf570
https://github.com/balderdashy/angularSails/blob/1deb8a05d737e5cb9224096378ebe949586cf570/lib/sails.io.js#L260-L286
train
AZaviruha/react-form-generator
src/tools/general.js
getOrDefault
function getOrDefault ( source, path, defaultVal ) { var isAlreadySplitted = isArray( path ); if ( !isDefined(source) ) return defaultVal; if ( !isString(path) && !isAlreadySplitted ) return defaultVal; var tokens = isAlreadySplitted ? path : path.split( '.' ) , idx, key; for ( idx in tokens ) { key = tokens[ idx ]; if ( isDefined( source[key] ) ) source = source[ key ]; else return defaultVal; } return source; }
javascript
function getOrDefault ( source, path, defaultVal ) { var isAlreadySplitted = isArray( path ); if ( !isDefined(source) ) return defaultVal; if ( !isString(path) && !isAlreadySplitted ) return defaultVal; var tokens = isAlreadySplitted ? path : path.split( '.' ) , idx, key; for ( idx in tokens ) { key = tokens[ idx ]; if ( isDefined( source[key] ) ) source = source[ key ]; else return defaultVal; } return source; }
[ "function", "getOrDefault", "(", "source", ",", "path", ",", "defaultVal", ")", "{", "var", "isAlreadySplitted", "=", "isArray", "(", "path", ")", ";", "if", "(", "!", "isDefined", "(", "source", ")", ")", "return", "defaultVal", ";", "if", "(", "!", "isString", "(", "path", ")", "&&", "!", "isAlreadySplitted", ")", "return", "defaultVal", ";", "var", "tokens", "=", "isAlreadySplitted", "?", "path", ":", "path", ".", "split", "(", "'.'", ")", ",", "idx", ",", "key", ";", "for", "(", "idx", "in", "tokens", ")", "{", "key", "=", "tokens", "[", "idx", "]", ";", "if", "(", "isDefined", "(", "source", "[", "key", "]", ")", ")", "source", "=", "source", "[", "key", "]", ";", "else", "return", "defaultVal", ";", "}", "return", "source", ";", "}" ]
Returns path's value or null if path's chain has undefined member. @param {Object} source - root object. @param {string} path - path to `source` value. @return {Object}
[ "Returns", "path", "s", "value", "or", "null", "if", "path", "s", "chain", "has", "undefined", "member", "." ]
d3ce8ef216f9d888f5ed641c33456821fce902c2
https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/tools/general.js#L33-L52
train
AZaviruha/react-form-generator
src/tools/general.js
arrayToObject
function arrayToObject ( keyPath, arr ) { var res = {}, key, element; for ( var i = 0, len = arr.length; i < len; i++ ) { element = arr[ i ]; key = getOrNull( element, keyPath ); if ( key ) res[ key ] = element; } return res; }
javascript
function arrayToObject ( keyPath, arr ) { var res = {}, key, element; for ( var i = 0, len = arr.length; i < len; i++ ) { element = arr[ i ]; key = getOrNull( element, keyPath ); if ( key ) res[ key ] = element; } return res; }
[ "function", "arrayToObject", "(", "keyPath", ",", "arr", ")", "{", "var", "res", "=", "{", "}", ",", "key", ",", "element", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "arr", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "element", "=", "arr", "[", "i", "]", ";", "key", "=", "getOrNull", "(", "element", ",", "keyPath", ")", ";", "if", "(", "key", ")", "res", "[", "key", "]", "=", "element", ";", "}", "return", "res", ";", "}" ]
Converts array to object, using `keyPath` for building unique keys. @param {(String|Array)} keyPath - path to `key` value in the array element. @param {Object[]} - array to convert. @return {Object}
[ "Converts", "array", "to", "object", "using", "keyPath", "for", "building", "unique", "keys", "." ]
d3ce8ef216f9d888f5ed641c33456821fce902c2
https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/tools/general.js#L69-L79
train
vincentmorneau/node-package-configurator
lib/src/js/bf.js
createPropertyProvider
function createPropertyProvider(getValue, onchange) { var ret = new Object(); ret.getValue = getValue; ret.onchange = onchange; return ret; }
javascript
function createPropertyProvider(getValue, onchange) { var ret = new Object(); ret.getValue = getValue; ret.onchange = onchange; return ret; }
[ "function", "createPropertyProvider", "(", "getValue", ",", "onchange", ")", "{", "var", "ret", "=", "new", "Object", "(", ")", ";", "ret", ".", "getValue", "=", "getValue", ";", "ret", ".", "onchange", "=", "onchange", ";", "return", "ret", ";", "}" ]
Used in object additionalProperties and arrays @param {type} getValue @param {type} onchange @returns {Object.create.createPropertyProvider.ret}
[ "Used", "in", "object", "additionalProperties", "and", "arrays" ]
489df6129a26238e8d783a3dfab1f354e27994a9
https://github.com/vincentmorneau/node-package-configurator/blob/489df6129a26238e8d783a3dfab1f354e27994a9/lib/src/js/bf.js#L1239-L1244
train
jwilsson/domtokenlist
dist/domtokenlist.js
function (fn) { return function () { var tokens = arguments; var i; for (i = 0; i < tokens.length; i += 1) { fn.call(this, tokens[i]); } }; }
javascript
function (fn) { return function () { var tokens = arguments; var i; for (i = 0; i < tokens.length; i += 1) { fn.call(this, tokens[i]); } }; }
[ "function", "(", "fn", ")", "{", "return", "function", "(", ")", "{", "var", "tokens", "=", "arguments", ";", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "tokens", ".", "length", ";", "i", "+=", "1", ")", "{", "fn", ".", "call", "(", "this", ",", "tokens", "[", "i", "]", ")", ";", "}", "}", ";", "}" ]
Older versions of the HTMLElement.classList spec didn't allow multiple arguments, easy to test for
[ "Older", "versions", "of", "the", "HTMLElement", ".", "classList", "spec", "didn", "t", "allow", "multiple", "arguments", "easy", "to", "test", "for" ]
4c643cd6aef8b8051822d86f60a4cdbccdca7dd2
https://github.com/jwilsson/domtokenlist/blob/4c643cd6aef8b8051822d86f60a4cdbccdca7dd2/dist/domtokenlist.js#L19-L28
train
Couto/Blueprint
src/Blueprint.js
function (methods) { methods = [].concat(methods); var i = methods.length - 1; for (i; i >= 0; i -= 1) { this[methods[i]] = proxy(this[methods[i]], this); } return this; }
javascript
function (methods) { methods = [].concat(methods); var i = methods.length - 1; for (i; i >= 0; i -= 1) { this[methods[i]] = proxy(this[methods[i]], this); } return this; }
[ "function", "(", "methods", ")", "{", "methods", "=", "[", "]", ".", "concat", "(", "methods", ")", ";", "var", "i", "=", "methods", ".", "length", "-", "1", ";", "for", "(", "i", ";", "i", ">=", "0", ";", "i", "-=", "1", ")", "{", "this", "[", "methods", "[", "i", "]", "]", "=", "proxy", "(", "this", "[", "methods", "[", "i", "]", "]", ",", "this", ")", ";", "}", "return", "this", ";", "}" ]
Describe what this method does @public @param {String|Object|Array|Boolean|Number} paramName Describe this parameter @returns Describe what it returns @type String|Object|Array|Boolean|Number
[ "Describe", "what", "this", "method", "does" ]
90dd099f40c6d6313a12a83d3450685704b6f6e0
https://github.com/Couto/Blueprint/blob/90dd099f40c6d6313a12a83d3450685704b6f6e0/src/Blueprint.js#L123-L132
train
voxel/voxel-mesher
mesh-buffer.js
createVoxelMesh
function createVoxelMesh(gl, voxels, voxelSideTextureIDs, voxelSideTextureSizes, position, pad, that) { //Create mesh var vert_data = createAOMesh(voxels, voxelSideTextureIDs, voxelSideTextureSizes) var vertexArrayObjects = {} if (vert_data === null) { // no vertices allocated } else { //Upload triangle mesh to WebGL var vert_buf = createBuffer(gl, vert_data) var triangleVAO = createVAO(gl, [ { "buffer": vert_buf, "type": gl.UNSIGNED_BYTE, "size": 4, "offset": 0, "stride": 8, "normalized": false }, { "buffer": vert_buf, "type": gl.UNSIGNED_BYTE, "size": 4, "offset": 4, "stride": 8, "normalized": false } ]) triangleVAO.length = Math.floor(vert_data.length/8) vertexArrayObjects.surface = triangleVAO } // move the chunk into place var modelMatrix = mat4.create() var w = voxels.shape[2] - pad // =[1]=[0]=game.chunkSize var translateVector = [ position[0] * w, position[1] * w, position[2] * w] mat4.translate(modelMatrix, modelMatrix, translateVector) //Bundle result and return var result = { vertexArrayObjects: vertexArrayObjects, // other plugins can add their own VAOs center: [w>>1, w>>1, w>>1], radius: w, modelMatrix: modelMatrix } if (that) that.emit('meshed', result, gl, vert_data, voxels) return result }
javascript
function createVoxelMesh(gl, voxels, voxelSideTextureIDs, voxelSideTextureSizes, position, pad, that) { //Create mesh var vert_data = createAOMesh(voxels, voxelSideTextureIDs, voxelSideTextureSizes) var vertexArrayObjects = {} if (vert_data === null) { // no vertices allocated } else { //Upload triangle mesh to WebGL var vert_buf = createBuffer(gl, vert_data) var triangleVAO = createVAO(gl, [ { "buffer": vert_buf, "type": gl.UNSIGNED_BYTE, "size": 4, "offset": 0, "stride": 8, "normalized": false }, { "buffer": vert_buf, "type": gl.UNSIGNED_BYTE, "size": 4, "offset": 4, "stride": 8, "normalized": false } ]) triangleVAO.length = Math.floor(vert_data.length/8) vertexArrayObjects.surface = triangleVAO } // move the chunk into place var modelMatrix = mat4.create() var w = voxels.shape[2] - pad // =[1]=[0]=game.chunkSize var translateVector = [ position[0] * w, position[1] * w, position[2] * w] mat4.translate(modelMatrix, modelMatrix, translateVector) //Bundle result and return var result = { vertexArrayObjects: vertexArrayObjects, // other plugins can add their own VAOs center: [w>>1, w>>1, w>>1], radius: w, modelMatrix: modelMatrix } if (that) that.emit('meshed', result, gl, vert_data, voxels) return result }
[ "function", "createVoxelMesh", "(", "gl", ",", "voxels", ",", "voxelSideTextureIDs", ",", "voxelSideTextureSizes", ",", "position", ",", "pad", ",", "that", ")", "{", "var", "vert_data", "=", "createAOMesh", "(", "voxels", ",", "voxelSideTextureIDs", ",", "voxelSideTextureSizes", ")", "var", "vertexArrayObjects", "=", "{", "}", "if", "(", "vert_data", "===", "null", ")", "{", "}", "else", "{", "var", "vert_buf", "=", "createBuffer", "(", "gl", ",", "vert_data", ")", "var", "triangleVAO", "=", "createVAO", "(", "gl", ",", "[", "{", "\"buffer\"", ":", "vert_buf", ",", "\"type\"", ":", "gl", ".", "UNSIGNED_BYTE", ",", "\"size\"", ":", "4", ",", "\"offset\"", ":", "0", ",", "\"stride\"", ":", "8", ",", "\"normalized\"", ":", "false", "}", ",", "{", "\"buffer\"", ":", "vert_buf", ",", "\"type\"", ":", "gl", ".", "UNSIGNED_BYTE", ",", "\"size\"", ":", "4", ",", "\"offset\"", ":", "4", ",", "\"stride\"", ":", "8", ",", "\"normalized\"", ":", "false", "}", "]", ")", "triangleVAO", ".", "length", "=", "Math", ".", "floor", "(", "vert_data", ".", "length", "/", "8", ")", "vertexArrayObjects", ".", "surface", "=", "triangleVAO", "}", "var", "modelMatrix", "=", "mat4", ".", "create", "(", ")", "var", "w", "=", "voxels", ".", "shape", "[", "2", "]", "-", "pad", "var", "translateVector", "=", "[", "position", "[", "0", "]", "*", "w", ",", "position", "[", "1", "]", "*", "w", ",", "position", "[", "2", "]", "*", "w", "]", "mat4", ".", "translate", "(", "modelMatrix", ",", "modelMatrix", ",", "translateVector", ")", "var", "result", "=", "{", "vertexArrayObjects", ":", "vertexArrayObjects", ",", "center", ":", "[", "w", ">>", "1", ",", "w", ">>", "1", ",", "w", ">>", "1", "]", ",", "radius", ":", "w", ",", "modelMatrix", ":", "modelMatrix", "}", "if", "(", "that", ")", "that", ".", "emit", "(", "'meshed'", ",", "result", ",", "gl", ",", "vert_data", ",", "voxels", ")", "return", "result", "}" ]
Creates a mesh from a set of voxels
[ "Creates", "a", "mesh", "from", "a", "set", "of", "voxels" ]
fc6d48247fd9393e32db89a6f239317212fdbb9b
https://github.com/voxel/voxel-mesher/blob/fc6d48247fd9393e32db89a6f239317212fdbb9b/mesh-buffer.js#L11-L63
train
TendaDigital/Tournamenter
controllers/Group.js
function(req, res, next){ // Search for ID if requested var id = req.param('id'); findAssociated(id, finishRendering); // Render JSON content function finishRendering(data){ // If none object found with given id return error if(id && !data[0]) return next(); // If querying for id, then returns only the object if(id) data = data[0]; // Render the json res.send(data); } }
javascript
function(req, res, next){ // Search for ID if requested var id = req.param('id'); findAssociated(id, finishRendering); // Render JSON content function finishRendering(data){ // If none object found with given id return error if(id && !data[0]) return next(); // If querying for id, then returns only the object if(id) data = data[0]; // Render the json res.send(data); } }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "id", "=", "req", ".", "param", "(", "'id'", ")", ";", "findAssociated", "(", "id", ",", "finishRendering", ")", ";", "function", "finishRendering", "(", "data", ")", "{", "if", "(", "id", "&&", "!", "data", "[", "0", "]", ")", "return", "next", "(", ")", ";", "if", "(", "id", ")", "data", "=", "data", "[", "0", "]", ";", "res", ".", "send", "(", "data", ")", ";", "}", "}" ]
Mix in matches inside groups data
[ "Mix", "in", "matches", "inside", "groups", "data" ]
2733ae9b454ae90896249ab1d7a07007eb4a69e4
https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/controllers/Group.js#L19-L39
train
TendaDigital/Tournamenter
controllers/Group.js
finishRendering
function finishRendering(data){ // If none object found with given id return error if(id && !data[0]) return next(); // If querying for id, then returns only the object if(id) data = data[0]; // Render the json res.send(data); }
javascript
function finishRendering(data){ // If none object found with given id return error if(id && !data[0]) return next(); // If querying for id, then returns only the object if(id) data = data[0]; // Render the json res.send(data); }
[ "function", "finishRendering", "(", "data", ")", "{", "if", "(", "id", "&&", "!", "data", "[", "0", "]", ")", "return", "next", "(", ")", ";", "if", "(", "id", ")", "data", "=", "data", "[", "0", "]", ";", "res", ".", "send", "(", "data", ")", ";", "}" ]
Render JSON content
[ "Render", "JSON", "content" ]
2733ae9b454ae90896249ab1d7a07007eb4a69e4
https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/controllers/Group.js#L27-L38
train
TendaDigital/Tournamenter
controllers/Group.js
afterFindGroups
function afterFindGroups(models){ data = models; completed = 0; if(data.length <= 0) return next([]); // Load Matches for each Group and associates data.forEach(function(group){ app.models.Match.find() .where({'groupId': group.id}) .sort('state DESC') .sort('day ASC') .sort('hour ASC') .sort('id') .then(function(matches){ // Associate matches with groups group.matches = matches; // Compute scoring table for each group // (must be computed AFTER associating matches with it) group.table = group.table(); // Callback loadedModel(); }); }); }
javascript
function afterFindGroups(models){ data = models; completed = 0; if(data.length <= 0) return next([]); // Load Matches for each Group and associates data.forEach(function(group){ app.models.Match.find() .where({'groupId': group.id}) .sort('state DESC') .sort('day ASC') .sort('hour ASC') .sort('id') .then(function(matches){ // Associate matches with groups group.matches = matches; // Compute scoring table for each group // (must be computed AFTER associating matches with it) group.table = group.table(); // Callback loadedModel(); }); }); }
[ "function", "afterFindGroups", "(", "models", ")", "{", "data", "=", "models", ";", "completed", "=", "0", ";", "if", "(", "data", ".", "length", "<=", "0", ")", "return", "next", "(", "[", "]", ")", ";", "data", ".", "forEach", "(", "function", "(", "group", ")", "{", "app", ".", "models", ".", "Match", ".", "find", "(", ")", ".", "where", "(", "{", "'groupId'", ":", "group", ".", "id", "}", ")", ".", "sort", "(", "'state DESC'", ")", ".", "sort", "(", "'day ASC'", ")", ".", "sort", "(", "'hour ASC'", ")", ".", "sort", "(", "'id'", ")", ".", "then", "(", "function", "(", "matches", ")", "{", "group", ".", "matches", "=", "matches", ";", "group", ".", "table", "=", "group", ".", "table", "(", ")", ";", "loadedModel", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
After finishing search
[ "After", "finishing", "search" ]
2733ae9b454ae90896249ab1d7a07007eb4a69e4
https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/controllers/Group.js#L78-L106
train
TendaDigital/Tournamenter
controllers/Group.js
afterFindTeams
function afterFindTeams(err, teamData){ var teamList = {}; // Load teams and assing it's key as it's id teamData.forEach(function(team){ teamList[team.id] = team; }); // Includes team object in 'table' data data.forEach(function(group){ // console.log(group); // Go trough all the table adding key 'team' with team data _.forEach(group.table, function(row){ row.team = teamList[row.teamId]; }); }); // Includes team object in 'match' data data.forEach(function(group){ // console.log(group); // Go trough all the table adding key 'team' with team data _.forEach(group.matches, function(row){ row.teamA = teamList[row.teamAId]; row.teamB = teamList[row.teamBId]; }); }); next(data); }
javascript
function afterFindTeams(err, teamData){ var teamList = {}; // Load teams and assing it's key as it's id teamData.forEach(function(team){ teamList[team.id] = team; }); // Includes team object in 'table' data data.forEach(function(group){ // console.log(group); // Go trough all the table adding key 'team' with team data _.forEach(group.table, function(row){ row.team = teamList[row.teamId]; }); }); // Includes team object in 'match' data data.forEach(function(group){ // console.log(group); // Go trough all the table adding key 'team' with team data _.forEach(group.matches, function(row){ row.teamA = teamList[row.teamAId]; row.teamB = teamList[row.teamBId]; }); }); next(data); }
[ "function", "afterFindTeams", "(", "err", ",", "teamData", ")", "{", "var", "teamList", "=", "{", "}", ";", "teamData", ".", "forEach", "(", "function", "(", "team", ")", "{", "teamList", "[", "team", ".", "id", "]", "=", "team", ";", "}", ")", ";", "data", ".", "forEach", "(", "function", "(", "group", ")", "{", "_", ".", "forEach", "(", "group", ".", "table", ",", "function", "(", "row", ")", "{", "row", ".", "team", "=", "teamList", "[", "row", ".", "teamId", "]", ";", "}", ")", ";", "}", ")", ";", "data", ".", "forEach", "(", "function", "(", "group", ")", "{", "_", ".", "forEach", "(", "group", ".", "matches", ",", "function", "(", "row", ")", "{", "row", ".", "teamA", "=", "teamList", "[", "row", ".", "teamAId", "]", ";", "row", ".", "teamB", "=", "teamList", "[", "row", ".", "teamBId", "]", ";", "}", ")", ";", "}", ")", ";", "next", "(", "data", ")", ";", "}" ]
Associate keys with teams
[ "Associate", "keys", "with", "teams" ]
2733ae9b454ae90896249ab1d7a07007eb4a69e4
https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/controllers/Group.js#L122-L152
train
jhaynie/request-ssl
lib/index.js
RequestSSLError
function RequestSSLError(message, id) { Error.call(this); Error.captureStackTrace(this, RequestSSLError); this.id = id; this.name = 'RequestSSLError'; this.message = message; }
javascript
function RequestSSLError(message, id) { Error.call(this); Error.captureStackTrace(this, RequestSSLError); this.id = id; this.name = 'RequestSSLError'; this.message = message; }
[ "function", "RequestSSLError", "(", "message", ",", "id", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "RequestSSLError", ")", ";", "this", ".", "id", "=", "id", ";", "this", ".", "name", "=", "'RequestSSLError'", ";", "this", ".", "message", "=", "message", ";", "}" ]
create a custom error so we can get proper error code
[ "create", "a", "custom", "error", "so", "we", "can", "get", "proper", "error", "code" ]
715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06
https://github.com/jhaynie/request-ssl/blob/715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06/lib/index.js#L131-L137
train
jhaynie/request-ssl
lib/index.js
createErrorMessage
function createErrorMessage(errorcode) { if (errorcode in ERRORS) { var args = Array.prototype.slice.call(arguments,1); var entry = ERRORS[errorcode]; if (entry.argcount && entry.argcount!==args.length) { // this should only ever get called if we have a bug in this library throw new Error("Internal failure. Unexpected usage of internal command. Please report error code: "+errorcode+"(invalid args) to the developer with the following stack trace:"+new Error().stack); } return new RequestSSLError((args.length ? util.format.apply(util.format,[entry.message].concat(args)) : entry.message), errorcode); } else { // this should only ever get called if we have a bug in this library throw new Error("Internal failure. Unexpected usage of internal command. Please report error code: "+errorcode+"(invalid error code) to the developer with the following stack trace:"+new Error().stack); } }
javascript
function createErrorMessage(errorcode) { if (errorcode in ERRORS) { var args = Array.prototype.slice.call(arguments,1); var entry = ERRORS[errorcode]; if (entry.argcount && entry.argcount!==args.length) { // this should only ever get called if we have a bug in this library throw new Error("Internal failure. Unexpected usage of internal command. Please report error code: "+errorcode+"(invalid args) to the developer with the following stack trace:"+new Error().stack); } return new RequestSSLError((args.length ? util.format.apply(util.format,[entry.message].concat(args)) : entry.message), errorcode); } else { // this should only ever get called if we have a bug in this library throw new Error("Internal failure. Unexpected usage of internal command. Please report error code: "+errorcode+"(invalid error code) to the developer with the following stack trace:"+new Error().stack); } }
[ "function", "createErrorMessage", "(", "errorcode", ")", "{", "if", "(", "errorcode", "in", "ERRORS", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "var", "entry", "=", "ERRORS", "[", "errorcode", "]", ";", "if", "(", "entry", ".", "argcount", "&&", "entry", ".", "argcount", "!==", "args", ".", "length", ")", "{", "throw", "new", "Error", "(", "\"Internal failure. Unexpected usage of internal command. Please report error code: \"", "+", "errorcode", "+", "\"(invalid args) to the developer with the following stack trace:\"", "+", "new", "Error", "(", ")", ".", "stack", ")", ";", "}", "return", "new", "RequestSSLError", "(", "(", "args", ".", "length", "?", "util", ".", "format", ".", "apply", "(", "util", ".", "format", ",", "[", "entry", ".", "message", "]", ".", "concat", "(", "args", ")", ")", ":", "entry", ".", "message", ")", ",", "errorcode", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"Internal failure. Unexpected usage of internal command. Please report error code: \"", "+", "errorcode", "+", "\"(invalid error code) to the developer with the following stack trace:\"", "+", "new", "Error", "(", ")", ".", "stack", ")", ";", "}", "}" ]
construct the proper error message
[ "construct", "the", "proper", "error", "message" ]
715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06
https://github.com/jhaynie/request-ssl/blob/715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06/lib/index.js#L158-L172
train
jhaynie/request-ssl
lib/index.js
getDomain
function getDomain(url) { var domain = _.isObject(url) ? url.host : urlib.parse(url).host; return domain || url; }
javascript
function getDomain(url) { var domain = _.isObject(url) ? url.host : urlib.parse(url).host; return domain || url; }
[ "function", "getDomain", "(", "url", ")", "{", "var", "domain", "=", "_", ".", "isObject", "(", "url", ")", "?", "url", ".", "host", ":", "urlib", ".", "parse", "(", "url", ")", ".", "host", ";", "return", "domain", "||", "url", ";", "}" ]
given a url return a domain part
[ "given", "a", "url", "return", "a", "domain", "part" ]
715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06
https://github.com/jhaynie/request-ssl/blob/715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06/lib/index.js#L177-L180
train
jhaynie/request-ssl
lib/index.js
getFingerprintForURL
function getFingerprintForURL(url) { var domain = getDomain(url); var found = global.requestSSLFingerprints[domain]; debug('getFingerprintForURL %s -> %s=%s',url,domain,found); if (!found) { // try a wildcard search var u = urlib.parse(domain), tokens = (u && u.host || domain).split('.'); domain = '*.'+tokens.splice(tokens.length > 1 ? 0 : 1).join('.'); found = global.requestSSLFingerprints[domain]; debug('getFingerprintForURL (wildcard) %s -> %s=%s',url,domain,found); } return found; }
javascript
function getFingerprintForURL(url) { var domain = getDomain(url); var found = global.requestSSLFingerprints[domain]; debug('getFingerprintForURL %s -> %s=%s',url,domain,found); if (!found) { // try a wildcard search var u = urlib.parse(domain), tokens = (u && u.host || domain).split('.'); domain = '*.'+tokens.splice(tokens.length > 1 ? 0 : 1).join('.'); found = global.requestSSLFingerprints[domain]; debug('getFingerprintForURL (wildcard) %s -> %s=%s',url,domain,found); } return found; }
[ "function", "getFingerprintForURL", "(", "url", ")", "{", "var", "domain", "=", "getDomain", "(", "url", ")", ";", "var", "found", "=", "global", ".", "requestSSLFingerprints", "[", "domain", "]", ";", "debug", "(", "'getFingerprintForURL %s -> %s=%s'", ",", "url", ",", "domain", ",", "found", ")", ";", "if", "(", "!", "found", ")", "{", "var", "u", "=", "urlib", ".", "parse", "(", "domain", ")", ",", "tokens", "=", "(", "u", "&&", "u", ".", "host", "||", "domain", ")", ".", "split", "(", "'.'", ")", ";", "domain", "=", "'*.'", "+", "tokens", ".", "splice", "(", "tokens", ".", "length", ">", "1", "?", "0", ":", "1", ")", ".", "join", "(", "'.'", ")", ";", "found", "=", "global", ".", "requestSSLFingerprints", "[", "domain", "]", ";", "debug", "(", "'getFingerprintForURL (wildcard) %s -> %s=%s'", ",", "url", ",", "domain", ",", "found", ")", ";", "}", "return", "found", ";", "}" ]
lookup a fingerprint for a given URL by using the domain. returns null if not found
[ "lookup", "a", "fingerprint", "for", "a", "given", "URL", "by", "using", "the", "domain", ".", "returns", "null", "if", "not", "found" ]
715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06
https://github.com/jhaynie/request-ssl/blob/715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06/lib/index.js#L186-L199
train
stoprocent/node-itunesconnect
index.js
Connect
function Connect(username, password, options) { // Default Options this.options = { baseURL : "https://itunesconnect.apple.com", apiURL : "https://reportingitc2.apple.com/api/", loginURL : "https://idmsa.apple.com/appleauth/auth/signin", appleWidgetKey : "22d448248055bab0dc197c6271d738c3", concurrentRequests : 2, errorCallback : function(e) {}, loginCallback : function(c) {} }; // Extend options _.extend(this.options, options); // Set cookies this._cookies = []; // Task Executor this._queue = async.queue( this.executeRequest.bind(this), this.options.concurrentRequests ); // Pasue queue and wait for login to complete this._queue.pause(); // Login to iTunes Connect if(typeof this.options["cookies"] !== 'undefined') { this._cookies = this.options.cookies; this._queue.resume(); } else { this.login(username, password); } }
javascript
function Connect(username, password, options) { // Default Options this.options = { baseURL : "https://itunesconnect.apple.com", apiURL : "https://reportingitc2.apple.com/api/", loginURL : "https://idmsa.apple.com/appleauth/auth/signin", appleWidgetKey : "22d448248055bab0dc197c6271d738c3", concurrentRequests : 2, errorCallback : function(e) {}, loginCallback : function(c) {} }; // Extend options _.extend(this.options, options); // Set cookies this._cookies = []; // Task Executor this._queue = async.queue( this.executeRequest.bind(this), this.options.concurrentRequests ); // Pasue queue and wait for login to complete this._queue.pause(); // Login to iTunes Connect if(typeof this.options["cookies"] !== 'undefined') { this._cookies = this.options.cookies; this._queue.resume(); } else { this.login(username, password); } }
[ "function", "Connect", "(", "username", ",", "password", ",", "options", ")", "{", "this", ".", "options", "=", "{", "baseURL", ":", "\"https://itunesconnect.apple.com\"", ",", "apiURL", ":", "\"https://reportingitc2.apple.com/api/\"", ",", "loginURL", ":", "\"https://idmsa.apple.com/appleauth/auth/signin\"", ",", "appleWidgetKey", ":", "\"22d448248055bab0dc197c6271d738c3\"", ",", "concurrentRequests", ":", "2", ",", "errorCallback", ":", "function", "(", "e", ")", "{", "}", ",", "loginCallback", ":", "function", "(", "c", ")", "{", "}", "}", ";", "_", ".", "extend", "(", "this", ".", "options", ",", "options", ")", ";", "this", ".", "_cookies", "=", "[", "]", ";", "this", ".", "_queue", "=", "async", ".", "queue", "(", "this", ".", "executeRequest", ".", "bind", "(", "this", ")", ",", "this", ".", "options", ".", "concurrentRequests", ")", ";", "this", ".", "_queue", ".", "pause", "(", ")", ";", "if", "(", "typeof", "this", ".", "options", "[", "\"cookies\"", "]", "!==", "'undefined'", ")", "{", "this", ".", "_cookies", "=", "this", ".", "options", ".", "cookies", ";", "this", ".", "_queue", ".", "resume", "(", ")", ";", "}", "else", "{", "this", ".", "login", "(", "username", ",", "password", ")", ";", "}", "}" ]
Initialize a new `Connect` with the given `username`, `password` and `options`. Examples: // Import itc-report var itc = require("itunesconnect"), Report = itc.Report; // Init new iTunes Connect var itunes = new itc.Connect('[email protected]', 'password'); // Init new iTunes Connect var itunes = new itc.Connect('[email protected]', 'password', { errorCallback: function(error) { console.log(error); }, concurrentRequests: 1 }); @class Connect @constructor @param {String} username Apple ID login @param {String} password Apple ID password @param {Object} [options] @param {String} [options.baseURL] iTunes Connect Login URL @param {String} [options.apiURL] iTunes Connect API URL @param {Number} [options.concurrentRequests] Number of concurrent requests @param {Array} [options.cookies] Cookies array. If you provide cookies array it will not login and use this instead. @param {Function} [options.errorCallback] Error callback function called when requests are failing @param {Function} [options.errorCallback.error] Login error @param {Function} [options.loginCallback] Login callback function called when login to iTunes Connect was a success. @param {Function} [options.loginCallback.cookies] cookies are passed as a first argument. You can get it and cache it for later.
[ "Initialize", "a", "new", "Connect", "with", "the", "given", "username", "password", "and", "options", "." ]
9d7c7ebe79eb8708a92631c55ce71e85ff89d1af
https://github.com/stoprocent/node-itunesconnect/blob/9d7c7ebe79eb8708a92631c55ce71e85ff89d1af/index.js#L110-L143
train
stoprocent/node-itunesconnect
index.js
Report
function Report(type, config) { var fn = Query.prototype[type]; if(typeof fn !== 'function') { throw new Error('Unknown Report type: ' + type); } return new Query(config)[type](); }
javascript
function Report(type, config) { var fn = Query.prototype[type]; if(typeof fn !== 'function') { throw new Error('Unknown Report type: ' + type); } return new Query(config)[type](); }
[ "function", "Report", "(", "type", ",", "config", ")", "{", "var", "fn", "=", "Query", ".", "prototype", "[", "type", "]", ";", "if", "(", "typeof", "fn", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Unknown Report type: '", "+", "type", ")", ";", "}", "return", "new", "Query", "(", "config", ")", "[", "type", "]", "(", ")", ";", "}" ]
Initialize a new `Query` with the given `type` and `config`. Examples: // Import itc-report var itc = require("itunesconnect"), Report = itc.Report; // Init new iTunes Connect var itunes = new itc.Connect('[email protected]', 'password'); // Timed type query var query = Report('timed'); // Ranked type query with config object var query = Report('ranked', { limit: 100 }); // Advanced Example var advancedQuery = Report('timed', { start : '2014-04-08', end : '2014-04-25', limit : 100, filters : { content: [{AppID}, {AppID}, {AppID}], location: [{LocationID}, {LocationID}], transaction: itc.transaction.free, type: [ itc.type.inapp, itc.type.app ], category: {CategoryID} }, group: 'content' }); @class Report @constructor @param {String} <type> @param {Object} [config] @param {String|Date} [config.start] Date or if String must be in format YYYY-MM-DD @param {Object} [config.end] Date or if String must be in format YYYY-MM-DD @param {String} [config.interval] One of the following: @param {String} config.interval.day @param {String} config.interval.week @param {String} config.interval.month @param {String} config.interval.quarter @param {String} config.interval.year @param {Object} [config.filters] Possible keys: @param {Number|Array} [config.filters.content] @param {String|Array} [config.filters.type] @param {String|Array} [config.filters.transaction] @param {Number|Array} [config.filters.category] @param {String|Array} [config.filters.platform] @param {Number|Array} [config.filters.location] @param {String} [config.group] One of following: @param {String} config.group.content @param {String} config.group.type @param {String} config.group.transaction @param {String} config.group.category @param {String} config.group.platform @param {String} config.group.location @param {Object} [config.measures] @param {Number} [config.limit] @return {Query}
[ "Initialize", "a", "new", "Query", "with", "the", "given", "type", "and", "config", "." ]
9d7c7ebe79eb8708a92631c55ce71e85ff89d1af
https://github.com/stoprocent/node-itunesconnect/blob/9d7c7ebe79eb8708a92631c55ce71e85ff89d1af/index.js#L397-L403
train
stoprocent/node-itunesconnect
index.js
Query
function Query(config) { this.type = null; this.endpoint = null; this.config = { start : moment(), end : moment(), filters : {}, measures : ['units'], limit : 100 }; // Extend options with user stuff _.extend(this.config, config); // Private Options this._time = null; this._body = {}; }
javascript
function Query(config) { this.type = null; this.endpoint = null; this.config = { start : moment(), end : moment(), filters : {}, measures : ['units'], limit : 100 }; // Extend options with user stuff _.extend(this.config, config); // Private Options this._time = null; this._body = {}; }
[ "function", "Query", "(", "config", ")", "{", "this", ".", "type", "=", "null", ";", "this", ".", "endpoint", "=", "null", ";", "this", ".", "config", "=", "{", "start", ":", "moment", "(", ")", ",", "end", ":", "moment", "(", ")", ",", "filters", ":", "{", "}", ",", "measures", ":", "[", "'units'", "]", ",", "limit", ":", "100", "}", ";", "_", ".", "extend", "(", "this", ".", "config", ",", "config", ")", ";", "this", ".", "_time", "=", "null", ";", "this", ".", "_body", "=", "{", "}", ";", "}" ]
Initialize a new `Query` with the given `query`. Constants to use with Query // Import itc-report var itc = require("itunesconnect"), // Types itc.type.inapp itc.type.app // Transactions itc.transaction.free itc.transaction.paid itc.transaction.redownload itc.transaction.update itc.transaction.refund // Platforms itc.platform.desktop itc.platform.iphone itc.platform.ipad itc.platform.ipod // Measures itc.measure.proceeds itc.measure.units @class Query @constructor @private @param {Object} config @chainable @return {Query}
[ "Initialize", "a", "new", "Query", "with", "the", "given", "query", "." ]
9d7c7ebe79eb8708a92631c55ce71e85ff89d1af
https://github.com/stoprocent/node-itunesconnect/blob/9d7c7ebe79eb8708a92631c55ce71e85ff89d1af/index.js#L504-L521
train
TendaDigital/Tournamenter
controllers/Match.js
afterFindMatch
function afterFindMatch(models){ if(models.length != 1) return next(404); model = models[0]; // Fetch Both Teams app.models.Team.findById(model.teamAId).exec(function(err, models){ model.teamA = models.length ? models[0] : null; checkFetch(); }); app.models.Team.findById(model.teamBId).exec(function(err, models){ model.teamB = models.length ? models[0] : null; checkFetch(); }); // Fetch Group app.models.Group.findById(model.groupId).exec(function(err, models){ model.group = models.length ? models[0] : null; checkFetch(); }); }
javascript
function afterFindMatch(models){ if(models.length != 1) return next(404); model = models[0]; // Fetch Both Teams app.models.Team.findById(model.teamAId).exec(function(err, models){ model.teamA = models.length ? models[0] : null; checkFetch(); }); app.models.Team.findById(model.teamBId).exec(function(err, models){ model.teamB = models.length ? models[0] : null; checkFetch(); }); // Fetch Group app.models.Group.findById(model.groupId).exec(function(err, models){ model.group = models.length ? models[0] : null; checkFetch(); }); }
[ "function", "afterFindMatch", "(", "models", ")", "{", "if", "(", "models", ".", "length", "!=", "1", ")", "return", "next", "(", "404", ")", ";", "model", "=", "models", "[", "0", "]", ";", "app", ".", "models", ".", "Team", ".", "findById", "(", "model", ".", "teamAId", ")", ".", "exec", "(", "function", "(", "err", ",", "models", ")", "{", "model", ".", "teamA", "=", "models", ".", "length", "?", "models", "[", "0", "]", ":", "null", ";", "checkFetch", "(", ")", ";", "}", ")", ";", "app", ".", "models", ".", "Team", ".", "findById", "(", "model", ".", "teamBId", ")", ".", "exec", "(", "function", "(", "err", ",", "models", ")", "{", "model", ".", "teamB", "=", "models", ".", "length", "?", "models", "[", "0", "]", ":", "null", ";", "checkFetch", "(", ")", ";", "}", ")", ";", "app", ".", "models", ".", "Group", ".", "findById", "(", "model", ".", "groupId", ")", ".", "exec", "(", "function", "(", "err", ",", "models", ")", "{", "model", ".", "group", "=", "models", ".", "length", "?", "models", "[", "0", "]", ":", "null", ";", "checkFetch", "(", ")", ";", "}", ")", ";", "}" ]
Called after match is fetched. Associate with Group and Teams
[ "Called", "after", "match", "is", "fetched", ".", "Associate", "with", "Group", "and", "Teams" ]
2733ae9b454ae90896249ab1d7a07007eb4a69e4
https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/controllers/Match.js#L56-L77
train
voxel/voxel-mesher
mesh.js
computeMesh
function computeMesh(array, voxelSideTextureIDs, voxelSideTextureSizes) { var shp = array.shape.slice(0) var nx = (shp[0]-2)|0 var ny = (shp[1]-2)|0 var nz = (shp[2]-2)|0 var sz = nx * ny * nz var scratch0 = pool.mallocInt32(sz) var scratch1 = pool.mallocInt32(sz) var scratch2 = pool.mallocInt32(sz) var rshp = [nx, ny, nz] var ao0 = ndarray(scratch0, rshp) var ao1 = ndarray(scratch1, rshp) var ao2 = ndarray(scratch2, rshp) //Calculate ao fields surfaceStencil(ao0, ao1, ao2, array) //Build mesh slices meshBuilder.ptr = 0 meshBuilder.voxelSideTextureIDs = voxelSideTextureIDs meshBuilder.voxelSideTextureSizes = voxelSideTextureSizes var buffers = [ao0, ao1, ao2] for(var d=0; d<3; ++d) { var u = (d+1)%3 var v = (d+2)%3 //Create slice var st = buffers[d].transpose(d, u, v) var slice = st.pick(0) var n = rshp[d]|0 meshBuilder.d = d meshBuilder.u = v meshBuilder.v = u //Generate slices for(var i=0; i<n; ++i) { meshBuilder.z = i meshSlice(slice) slice.offset += st.stride[0] } } //Release buffers pool.freeInt32(scratch0) pool.freeInt32(scratch1) pool.freeInt32(scratch2) //Release uint8 array if no vertices were allocated if(meshBuilder.ptr === 0) { return null } //Slice out buffer var rbuffer = meshBuilder.buffer var rptr = meshBuilder.ptr meshBuilder.buffer = pool.mallocUint8(1024) meshBuilder.ptr = 0 return rbuffer.subarray(0, rptr) }
javascript
function computeMesh(array, voxelSideTextureIDs, voxelSideTextureSizes) { var shp = array.shape.slice(0) var nx = (shp[0]-2)|0 var ny = (shp[1]-2)|0 var nz = (shp[2]-2)|0 var sz = nx * ny * nz var scratch0 = pool.mallocInt32(sz) var scratch1 = pool.mallocInt32(sz) var scratch2 = pool.mallocInt32(sz) var rshp = [nx, ny, nz] var ao0 = ndarray(scratch0, rshp) var ao1 = ndarray(scratch1, rshp) var ao2 = ndarray(scratch2, rshp) //Calculate ao fields surfaceStencil(ao0, ao1, ao2, array) //Build mesh slices meshBuilder.ptr = 0 meshBuilder.voxelSideTextureIDs = voxelSideTextureIDs meshBuilder.voxelSideTextureSizes = voxelSideTextureSizes var buffers = [ao0, ao1, ao2] for(var d=0; d<3; ++d) { var u = (d+1)%3 var v = (d+2)%3 //Create slice var st = buffers[d].transpose(d, u, v) var slice = st.pick(0) var n = rshp[d]|0 meshBuilder.d = d meshBuilder.u = v meshBuilder.v = u //Generate slices for(var i=0; i<n; ++i) { meshBuilder.z = i meshSlice(slice) slice.offset += st.stride[0] } } //Release buffers pool.freeInt32(scratch0) pool.freeInt32(scratch1) pool.freeInt32(scratch2) //Release uint8 array if no vertices were allocated if(meshBuilder.ptr === 0) { return null } //Slice out buffer var rbuffer = meshBuilder.buffer var rptr = meshBuilder.ptr meshBuilder.buffer = pool.mallocUint8(1024) meshBuilder.ptr = 0 return rbuffer.subarray(0, rptr) }
[ "function", "computeMesh", "(", "array", ",", "voxelSideTextureIDs", ",", "voxelSideTextureSizes", ")", "{", "var", "shp", "=", "array", ".", "shape", ".", "slice", "(", "0", ")", "var", "nx", "=", "(", "shp", "[", "0", "]", "-", "2", ")", "|", "0", "var", "ny", "=", "(", "shp", "[", "1", "]", "-", "2", ")", "|", "0", "var", "nz", "=", "(", "shp", "[", "2", "]", "-", "2", ")", "|", "0", "var", "sz", "=", "nx", "*", "ny", "*", "nz", "var", "scratch0", "=", "pool", ".", "mallocInt32", "(", "sz", ")", "var", "scratch1", "=", "pool", ".", "mallocInt32", "(", "sz", ")", "var", "scratch2", "=", "pool", ".", "mallocInt32", "(", "sz", ")", "var", "rshp", "=", "[", "nx", ",", "ny", ",", "nz", "]", "var", "ao0", "=", "ndarray", "(", "scratch0", ",", "rshp", ")", "var", "ao1", "=", "ndarray", "(", "scratch1", ",", "rshp", ")", "var", "ao2", "=", "ndarray", "(", "scratch2", ",", "rshp", ")", "surfaceStencil", "(", "ao0", ",", "ao1", ",", "ao2", ",", "array", ")", "meshBuilder", ".", "ptr", "=", "0", "meshBuilder", ".", "voxelSideTextureIDs", "=", "voxelSideTextureIDs", "meshBuilder", ".", "voxelSideTextureSizes", "=", "voxelSideTextureSizes", "var", "buffers", "=", "[", "ao0", ",", "ao1", ",", "ao2", "]", "for", "(", "var", "d", "=", "0", ";", "d", "<", "3", ";", "++", "d", ")", "{", "var", "u", "=", "(", "d", "+", "1", ")", "%", "3", "var", "v", "=", "(", "d", "+", "2", ")", "%", "3", "var", "st", "=", "buffers", "[", "d", "]", ".", "transpose", "(", "d", ",", "u", ",", "v", ")", "var", "slice", "=", "st", ".", "pick", "(", "0", ")", "var", "n", "=", "rshp", "[", "d", "]", "|", "0", "meshBuilder", ".", "d", "=", "d", "meshBuilder", ".", "u", "=", "v", "meshBuilder", ".", "v", "=", "u", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "++", "i", ")", "{", "meshBuilder", ".", "z", "=", "i", "meshSlice", "(", "slice", ")", "slice", ".", "offset", "+=", "st", ".", "stride", "[", "0", "]", "}", "}", "pool", ".", "freeInt32", "(", "scratch0", ")", "pool", ".", "freeInt32", "(", "scratch1", ")", "pool", ".", "freeInt32", "(", "scratch2", ")", "if", "(", "meshBuilder", ".", "ptr", "===", "0", ")", "{", "return", "null", "}", "var", "rbuffer", "=", "meshBuilder", ".", "buffer", "var", "rptr", "=", "meshBuilder", ".", "ptr", "meshBuilder", ".", "buffer", "=", "pool", ".", "mallocUint8", "(", "1024", ")", "meshBuilder", ".", "ptr", "=", "0", "return", "rbuffer", ".", "subarray", "(", "0", ",", "rptr", ")", "}" ]
Compute a mesh
[ "Compute", "a", "mesh" ]
fc6d48247fd9393e32db89a6f239317212fdbb9b
https://github.com/voxel/voxel-mesher/blob/fc6d48247fd9393e32db89a6f239317212fdbb9b/mesh.js#L487-L547
train
mafintosh/pbs
index.js
function () { var self = this pb.toJSON().enums.forEach(function (e) { self[e.name] = e.values }) pb.toJSON().messages.forEach(function (m) { var message = {} m.enums.forEach(function (e) { message[e.name] = e }) message.name = m.name message.encode = encoder(m, pb) message.decode = decoder(m, pb) self[m.name] = message }) }
javascript
function () { var self = this pb.toJSON().enums.forEach(function (e) { self[e.name] = e.values }) pb.toJSON().messages.forEach(function (m) { var message = {} m.enums.forEach(function (e) { message[e.name] = e }) message.name = m.name message.encode = encoder(m, pb) message.decode = decoder(m, pb) self[m.name] = message }) }
[ "function", "(", ")", "{", "var", "self", "=", "this", "pb", ".", "toJSON", "(", ")", ".", "enums", ".", "forEach", "(", "function", "(", "e", ")", "{", "self", "[", "e", ".", "name", "]", "=", "e", ".", "values", "}", ")", "pb", ".", "toJSON", "(", ")", ".", "messages", ".", "forEach", "(", "function", "(", "m", ")", "{", "var", "message", "=", "{", "}", "m", ".", "enums", ".", "forEach", "(", "function", "(", "e", ")", "{", "message", "[", "e", ".", "name", "]", "=", "e", "}", ")", "message", ".", "name", "=", "m", ".", "name", "message", ".", "encode", "=", "encoder", "(", "m", ",", "pb", ")", "message", ".", "decode", "=", "decoder", "(", "m", ",", "pb", ")", "self", "[", "m", ".", "name", "]", "=", "message", "}", ")", "}" ]
to not make toString,toJSON enumarable we make a fire-and-forget prototype
[ "to", "not", "make", "toString", "toJSON", "enumarable", "we", "make", "a", "fire", "-", "and", "-", "forget", "prototype" ]
163e2390e01bf81b83f3fda0ca2823d7eea96e2b
https://github.com/mafintosh/pbs/blob/163e2390e01bf81b83f3fda0ca2823d7eea96e2b/index.js#L9-L26
train
TendaDigital/Tournamenter
modules/pageview-live-match/public/js/pageview-live-match.js
function($root) { var match = this.model.get('data'); this.updateScore(match.teamAScore, $root.find('.team.left .team-score')); this.updateScore(match.teamBScore, $root.find('.team.right .team-score')); }
javascript
function($root) { var match = this.model.get('data'); this.updateScore(match.teamAScore, $root.find('.team.left .team-score')); this.updateScore(match.teamBScore, $root.find('.team.right .team-score')); }
[ "function", "(", "$root", ")", "{", "var", "match", "=", "this", ".", "model", ".", "get", "(", "'data'", ")", ";", "this", ".", "updateScore", "(", "match", ".", "teamAScore", ",", "$root", ".", "find", "(", "'.team.left .team-score'", ")", ")", ";", "this", ".", "updateScore", "(", "match", ".", "teamBScore", ",", "$root", ".", "find", "(", "'.team.right .team-score'", ")", ")", ";", "}" ]
Update both score values
[ "Update", "both", "score", "values" ]
2733ae9b454ae90896249ab1d7a07007eb4a69e4
https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/modules/pageview-live-match/public/js/pageview-live-match.js#L182-L187
train
TendaDigital/Tournamenter
modules/pageview-live-match/public/js/pageview-live-match.js
function(state){ var match = this.model.get('data'); var countryA = match.teamA ? match.teamA.country : null; this.setFlagsState(state, countryA, this.$('.flag-3d-left')); var countryB = match.teamB ? match.teamB.country : null; this.setFlagsState(state, countryB, this.$('.flag-3d-right')); }
javascript
function(state){ var match = this.model.get('data'); var countryA = match.teamA ? match.teamA.country : null; this.setFlagsState(state, countryA, this.$('.flag-3d-left')); var countryB = match.teamB ? match.teamB.country : null; this.setFlagsState(state, countryB, this.$('.flag-3d-right')); }
[ "function", "(", "state", ")", "{", "var", "match", "=", "this", ".", "model", ".", "get", "(", "'data'", ")", ";", "var", "countryA", "=", "match", ".", "teamA", "?", "match", ".", "teamA", ".", "country", ":", "null", ";", "this", ".", "setFlagsState", "(", "state", ",", "countryA", ",", "this", ".", "$", "(", "'.flag-3d-left'", ")", ")", ";", "var", "countryB", "=", "match", ".", "teamB", "?", "match", ".", "teamB", ".", "country", ":", "null", ";", "this", ".", "setFlagsState", "(", "state", ",", "countryB", ",", "this", ".", "$", "(", "'.flag-3d-right'", ")", ")", ";", "}" ]
Animate both flags
[ "Animate", "both", "flags" ]
2733ae9b454ae90896249ab1d7a07007eb4a69e4
https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/modules/pageview-live-match/public/js/pageview-live-match.js#L204-L212
train
fnogatz/CHR.js
src/index.js
tag
function tag (chrSource) { var program var replacements // Examine caller format if (typeof chrSource === 'object' && chrSource.type && chrSource.type === 'Program') { // called with already parsed source code // e.g. tag({ type: 'Program', body: [ ... ] }) program = chrSource replacements = [] // allow to specify replacements as second argument if (arguments[1] && typeof arguments[1] === 'object' && arguments[1] instanceof Array) { replacements = arguments[1] } } else if (typeof chrSource === 'object' && chrSource instanceof Array && typeof chrSource[0] === 'string') { // called as template tag // e.g. tag`a ==> b` // or tag`a ==> ${ function() { console.log('Replacement test') } }` var combined = [ chrSource[0] ] Array.prototype.slice.call(arguments, 1).forEach(function (repl, ix) { combined.push(repl) combined.push(chrSource[ix + 1]) }) chrSource = joinParts(combined) replacements = Array.prototype.slice.call(arguments, 1) program = parse(chrSource) } else if (typeof chrSource === 'string' && arguments[1] && arguments[1] instanceof Array) { // called with program and replacements array // e.g. tag( // 'a ==> ${ function() { console.log("Replacement test") } }', // [ eval('( function() { console.log("Replacement test") } )') ] // ) // this is useful to ensure the scope of the given replacements program = parse(chrSource) replacements = arguments[1] } else if (typeof chrSource === 'string') { // called as normal function // e.g. tag('a ==> b') // or tag('a ==> ', function() { console.log('Replacement test') }) replacements = Array.prototype.filter.call(arguments, isFunction) chrSource = joinParts(Array.prototype.slice.call(arguments)) program = parse(chrSource) } var rules = program.body rules.forEach(function (rule) { tag.Rules.Add(rule, replacements) }) }
javascript
function tag (chrSource) { var program var replacements // Examine caller format if (typeof chrSource === 'object' && chrSource.type && chrSource.type === 'Program') { // called with already parsed source code // e.g. tag({ type: 'Program', body: [ ... ] }) program = chrSource replacements = [] // allow to specify replacements as second argument if (arguments[1] && typeof arguments[1] === 'object' && arguments[1] instanceof Array) { replacements = arguments[1] } } else if (typeof chrSource === 'object' && chrSource instanceof Array && typeof chrSource[0] === 'string') { // called as template tag // e.g. tag`a ==> b` // or tag`a ==> ${ function() { console.log('Replacement test') } }` var combined = [ chrSource[0] ] Array.prototype.slice.call(arguments, 1).forEach(function (repl, ix) { combined.push(repl) combined.push(chrSource[ix + 1]) }) chrSource = joinParts(combined) replacements = Array.prototype.slice.call(arguments, 1) program = parse(chrSource) } else if (typeof chrSource === 'string' && arguments[1] && arguments[1] instanceof Array) { // called with program and replacements array // e.g. tag( // 'a ==> ${ function() { console.log("Replacement test") } }', // [ eval('( function() { console.log("Replacement test") } )') ] // ) // this is useful to ensure the scope of the given replacements program = parse(chrSource) replacements = arguments[1] } else if (typeof chrSource === 'string') { // called as normal function // e.g. tag('a ==> b') // or tag('a ==> ', function() { console.log('Replacement test') }) replacements = Array.prototype.filter.call(arguments, isFunction) chrSource = joinParts(Array.prototype.slice.call(arguments)) program = parse(chrSource) } var rules = program.body rules.forEach(function (rule) { tag.Rules.Add(rule, replacements) }) }
[ "function", "tag", "(", "chrSource", ")", "{", "var", "program", "var", "replacements", "if", "(", "typeof", "chrSource", "===", "'object'", "&&", "chrSource", ".", "type", "&&", "chrSource", ".", "type", "===", "'Program'", ")", "{", "program", "=", "chrSource", "replacements", "=", "[", "]", "if", "(", "arguments", "[", "1", "]", "&&", "typeof", "arguments", "[", "1", "]", "===", "'object'", "&&", "arguments", "[", "1", "]", "instanceof", "Array", ")", "{", "replacements", "=", "arguments", "[", "1", "]", "}", "}", "else", "if", "(", "typeof", "chrSource", "===", "'object'", "&&", "chrSource", "instanceof", "Array", "&&", "typeof", "chrSource", "[", "0", "]", "===", "'string'", ")", "{", "var", "combined", "=", "[", "chrSource", "[", "0", "]", "]", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ".", "forEach", "(", "function", "(", "repl", ",", "ix", ")", "{", "combined", ".", "push", "(", "repl", ")", "combined", ".", "push", "(", "chrSource", "[", "ix", "+", "1", "]", ")", "}", ")", "chrSource", "=", "joinParts", "(", "combined", ")", "replacements", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", "program", "=", "parse", "(", "chrSource", ")", "}", "else", "if", "(", "typeof", "chrSource", "===", "'string'", "&&", "arguments", "[", "1", "]", "&&", "arguments", "[", "1", "]", "instanceof", "Array", ")", "{", "program", "=", "parse", "(", "chrSource", ")", "replacements", "=", "arguments", "[", "1", "]", "}", "else", "if", "(", "typeof", "chrSource", "===", "'string'", ")", "{", "replacements", "=", "Array", ".", "prototype", ".", "filter", ".", "call", "(", "arguments", ",", "isFunction", ")", "chrSource", "=", "joinParts", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", "program", "=", "parse", "(", "chrSource", ")", "}", "var", "rules", "=", "program", ".", "body", "rules", ".", "forEach", "(", "function", "(", "rule", ")", "{", "tag", ".", "Rules", ".", "Add", "(", "rule", ",", "replacements", ")", "}", ")", "}" ]
Adds a number of rules given.
[ "Adds", "a", "number", "of", "rules", "given", "." ]
d87688327f139d726993537c7da98fcac0a4a89f
https://github.com/fnogatz/CHR.js/blob/d87688327f139d726993537c7da98fcac0a4a89f/src/index.js#L30-L81
train
TendaDigital/Tournamenter
controllers/Table.js
associateWithTeams
function associateWithTeams(teams, tableModel){ // Go through all team rows inside the table's data, and add's team object // _.forEach(tableModel.table, function(teamRow){ // teamRow['team'] = teams[teamRow.teamId] || {}; // }); // Go through all team rows inside scores, and add's a team object _.forEach(tableModel.scores, function(teamRow){ teamRow['team'] = teams[teamRow.teamId] || {}; }); }
javascript
function associateWithTeams(teams, tableModel){ // Go through all team rows inside the table's data, and add's team object // _.forEach(tableModel.table, function(teamRow){ // teamRow['team'] = teams[teamRow.teamId] || {}; // }); // Go through all team rows inside scores, and add's a team object _.forEach(tableModel.scores, function(teamRow){ teamRow['team'] = teams[teamRow.teamId] || {}; }); }
[ "function", "associateWithTeams", "(", "teams", ",", "tableModel", ")", "{", "_", ".", "forEach", "(", "tableModel", ".", "scores", ",", "function", "(", "teamRow", ")", "{", "teamRow", "[", "'team'", "]", "=", "teams", "[", "teamRow", ".", "teamId", "]", "||", "{", "}", ";", "}", ")", ";", "}" ]
Helper method used to save team data inside each table row
[ "Helper", "method", "used", "to", "save", "team", "data", "inside", "each", "table", "row" ]
2733ae9b454ae90896249ab1d7a07007eb4a69e4
https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/controllers/Table.js#L217-L227
train
suskind/network-list
src/index.js
checkPort
function checkPort(port, host, callback) { var socket = new Socket(), status = null; socket.on('connect', () => { status = 'open'; socket.end(); }); socket.setTimeout(1500); socket.on('timeout', () => { status = 'closed'; socket.destroy(); }); socket.on('error', (exception) => { status = 'closed'; }); socket.on('close', (exception) => { callback(null, status,host,port); }); socket.connect(port, host); }
javascript
function checkPort(port, host, callback) { var socket = new Socket(), status = null; socket.on('connect', () => { status = 'open'; socket.end(); }); socket.setTimeout(1500); socket.on('timeout', () => { status = 'closed'; socket.destroy(); }); socket.on('error', (exception) => { status = 'closed'; }); socket.on('close', (exception) => { callback(null, status,host,port); }); socket.connect(port, host); }
[ "function", "checkPort", "(", "port", ",", "host", ",", "callback", ")", "{", "var", "socket", "=", "new", "Socket", "(", ")", ",", "status", "=", "null", ";", "socket", ".", "on", "(", "'connect'", ",", "(", ")", "=>", "{", "status", "=", "'open'", ";", "socket", ".", "end", "(", ")", ";", "}", ")", ";", "socket", ".", "setTimeout", "(", "1500", ")", ";", "socket", ".", "on", "(", "'timeout'", ",", "(", ")", "=>", "{", "status", "=", "'closed'", ";", "socket", ".", "destroy", "(", ")", ";", "}", ")", ";", "socket", ".", "on", "(", "'error'", ",", "(", "exception", ")", "=>", "{", "status", "=", "'closed'", ";", "}", ")", ";", "socket", ".", "on", "(", "'close'", ",", "(", "exception", ")", "=>", "{", "callback", "(", "null", ",", "status", ",", "host", ",", "port", ")", ";", "}", ")", ";", "socket", ".", "connect", "(", "port", ",", "host", ")", ";", "}" ]
Keep this function to use in a future version to port scan
[ "Keep", "this", "function", "to", "use", "in", "a", "future", "version", "to", "port", "scan" ]
1e3289a13df866954576089334b1a8012091784b
https://github.com/suskind/network-list/blob/1e3289a13df866954576089334b1a8012091784b/src/index.js#L77-L96
train
TendaDigital/Tournamenter
models/View.js
getNextID
function getNextID () { var max = 0; _.forEach(newPages, function(page){ if(page.id) max = Math.max(max, page.id*1); }); var next = max*1+1; return next; }
javascript
function getNextID () { var max = 0; _.forEach(newPages, function(page){ if(page.id) max = Math.max(max, page.id*1); }); var next = max*1+1; return next; }
[ "function", "getNextID", "(", ")", "{", "var", "max", "=", "0", ";", "_", ".", "forEach", "(", "newPages", ",", "function", "(", "page", ")", "{", "if", "(", "page", ".", "id", ")", "max", "=", "Math", ".", "max", "(", "max", ",", "page", ".", "id", "*", "1", ")", ";", "}", ")", ";", "var", "next", "=", "max", "*", "1", "+", "1", ";", "return", "next", ";", "}" ]
Helper function that will return next available ID
[ "Helper", "function", "that", "will", "return", "next", "available", "ID" ]
2733ae9b454ae90896249ab1d7a07007eb4a69e4
https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/models/View.js#L140-L147
train
hcodes/yandex-speller
lib/yandex-speller.js
checkText
function checkText(text, callback, settings) { const form = prepareSettings(settings); form.text = text; post({ host: YASPELLER_HOST, path: YASPELLER_PATH + 'checkText', form: form, }, function(error, response, body) { if (error) { callback(error, null); } else { if (response.statusCode === 200) { callback(null, body); } else { callback( Error('Yandex.Speller API returns status code is ' + response.statusCode, null) ); } } }); }
javascript
function checkText(text, callback, settings) { const form = prepareSettings(settings); form.text = text; post({ host: YASPELLER_HOST, path: YASPELLER_PATH + 'checkText', form: form, }, function(error, response, body) { if (error) { callback(error, null); } else { if (response.statusCode === 200) { callback(null, body); } else { callback( Error('Yandex.Speller API returns status code is ' + response.statusCode, null) ); } } }); }
[ "function", "checkText", "(", "text", ",", "callback", ",", "settings", ")", "{", "const", "form", "=", "prepareSettings", "(", "settings", ")", ";", "form", ".", "text", "=", "text", ";", "post", "(", "{", "host", ":", "YASPELLER_HOST", ",", "path", ":", "YASPELLER_PATH", "+", "'checkText'", ",", "form", ":", "form", ",", "}", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ",", "null", ")", ";", "}", "else", "{", "if", "(", "response", ".", "statusCode", "===", "200", ")", "{", "callback", "(", "null", ",", "body", ")", ";", "}", "else", "{", "callback", "(", "Error", "(", "'Yandex.Speller API returns status code is '", "+", "response", ".", "statusCode", ",", "null", ")", ")", ";", "}", "}", "}", ")", ";", "}" ]
Check text for typos. @param {string} text @param {Function} callback @param {Settings} settings @see {@link https://tech.yandex.ru/speller/doc/dg/reference/checkText-docpage/}
[ "Check", "text", "for", "typos", "." ]
78d641980fdf594e417e22e370752e79a1799798
https://github.com/hcodes/yandex-speller/blob/78d641980fdf594e417e22e370752e79a1799798/lib/yandex-speller.js#L16-L38
train
TendaDigital/Tournamenter
models/Table.js
resolveMethod
function resolveMethod(wrapedMethod, methodRaw){ // Get method string and `methodify` it recursivelly var method = getMethodFor(methodRaw); // Check if method is ok to continue, or, return null if(!method) throw new Error('Could not parse method: '+methodRaw); // Create a wrapped method of the current one, with this one return function(scores){ return wrapedMethod(method(scores)); } }
javascript
function resolveMethod(wrapedMethod, methodRaw){ // Get method string and `methodify` it recursivelly var method = getMethodFor(methodRaw); // Check if method is ok to continue, or, return null if(!method) throw new Error('Could not parse method: '+methodRaw); // Create a wrapped method of the current one, with this one return function(scores){ return wrapedMethod(method(scores)); } }
[ "function", "resolveMethod", "(", "wrapedMethod", ",", "methodRaw", ")", "{", "var", "method", "=", "getMethodFor", "(", "methodRaw", ")", ";", "if", "(", "!", "method", ")", "throw", "new", "Error", "(", "'Could not parse method: '", "+", "methodRaw", ")", ";", "return", "function", "(", "scores", ")", "{", "return", "wrapedMethod", "(", "method", "(", "scores", ")", ")", ";", "}", "}" ]
Default function to resolve methods
[ "Default", "function", "to", "resolve", "methods" ]
2733ae9b454ae90896249ab1d7a07007eb4a69e4
https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/models/Table.js#L591-L603
train
TendaDigital/Tournamenter
modules/pageview-group/public/js/pageview-group.js
function(match){ /* Depending on the match state, we shall render a different match view. Templates are: + pageview-group.match.scheduled + pageview-group.match.playing + pageview-group.match.endend */ var templates = { 'scheduled': JST['pageview-group.match.scheduled'], 'playing': JST['pageview-group.match.playing'], 'ended': JST['pageview-group.match.ended'], }; if(match.state == 'scheduled'){ return JST['pageview-group.match.scheduled']({match: match}); }else if(match.state == 'playing'){ return JST['pageview-group.match.playing']({match: match}); }else if(match.state == 'ended'){ // In this case, we need to set the class for A and B. // (teamAClass and teamBClass to null, team-win, team-loose) return JST['pageview-group.match.ended']({ match: match, teamAClass: (match.teamAScore > match.teamBScore ? 'team-win' :match.teamAScore < match.teamBScore ? 'team-loose' : ''), teamBClass: (match.teamBScore > match.teamAScore ? 'team-win' :match.teamBScore < match.teamAScore ? 'team-loose' : ''), }); } }
javascript
function(match){ /* Depending on the match state, we shall render a different match view. Templates are: + pageview-group.match.scheduled + pageview-group.match.playing + pageview-group.match.endend */ var templates = { 'scheduled': JST['pageview-group.match.scheduled'], 'playing': JST['pageview-group.match.playing'], 'ended': JST['pageview-group.match.ended'], }; if(match.state == 'scheduled'){ return JST['pageview-group.match.scheduled']({match: match}); }else if(match.state == 'playing'){ return JST['pageview-group.match.playing']({match: match}); }else if(match.state == 'ended'){ // In this case, we need to set the class for A and B. // (teamAClass and teamBClass to null, team-win, team-loose) return JST['pageview-group.match.ended']({ match: match, teamAClass: (match.teamAScore > match.teamBScore ? 'team-win' :match.teamAScore < match.teamBScore ? 'team-loose' : ''), teamBClass: (match.teamBScore > match.teamAScore ? 'team-win' :match.teamBScore < match.teamAScore ? 'team-loose' : ''), }); } }
[ "function", "(", "match", ")", "{", "var", "templates", "=", "{", "'scheduled'", ":", "JST", "[", "'pageview-group.match.scheduled'", "]", ",", "'playing'", ":", "JST", "[", "'pageview-group.match.playing'", "]", ",", "'ended'", ":", "JST", "[", "'pageview-group.match.ended'", "]", ",", "}", ";", "if", "(", "match", ".", "state", "==", "'scheduled'", ")", "{", "return", "JST", "[", "'pageview-group.match.scheduled'", "]", "(", "{", "match", ":", "match", "}", ")", ";", "}", "else", "if", "(", "match", ".", "state", "==", "'playing'", ")", "{", "return", "JST", "[", "'pageview-group.match.playing'", "]", "(", "{", "match", ":", "match", "}", ")", ";", "}", "else", "if", "(", "match", ".", "state", "==", "'ended'", ")", "{", "return", "JST", "[", "'pageview-group.match.ended'", "]", "(", "{", "match", ":", "match", ",", "teamAClass", ":", "(", "match", ".", "teamAScore", ">", "match", ".", "teamBScore", "?", "'team-win'", ":", "match", ".", "teamAScore", "<", "match", ".", "teamBScore", "?", "'team-loose'", ":", "''", ")", ",", "teamBClass", ":", "(", "match", ".", "teamBScore", ">", "match", ".", "teamAScore", "?", "'team-win'", ":", "match", ".", "teamBScore", "<", "match", ".", "teamAScore", "?", "'team-loose'", ":", "''", ")", ",", "}", ")", ";", "}", "}" ]
Render a single match view with the correct view state
[ "Render", "a", "single", "match", "view", "with", "the", "correct", "view", "state" ]
2733ae9b454ae90896249ab1d7a07007eb4a69e4
https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/modules/pageview-group/public/js/pageview-group.js#L641-L677
train
neoziro/angular-draganddrop
angular-draganddrop.js
draggableDirective
function draggableDirective() { return { restrict: 'A', link: function (scope, element, attrs) { var domElement = element[0]; var effectAllowed = attrs.effectAllowed; var draggableData = attrs.draggableData; var draggableType = attrs.draggableType; var draggable = attrs.draggable === 'false' ? false : true; // Make element draggable or not. domElement.draggable = draggable; if (! draggable) return ; domElement.addEventListener('dragstart', function (e) { // Restrict drag effect. e.dataTransfer.effectAllowed = effectAllowed || e.dataTransfer.effectAllowed; // Eval and serialize data. var data = scope.$eval(draggableData); var jsonData = angular.toJson(data); // Set drag data and drag type. e.dataTransfer.setData('json/' + draggableType, jsonData); e.stopPropagation(); }); } }; }
javascript
function draggableDirective() { return { restrict: 'A', link: function (scope, element, attrs) { var domElement = element[0]; var effectAllowed = attrs.effectAllowed; var draggableData = attrs.draggableData; var draggableType = attrs.draggableType; var draggable = attrs.draggable === 'false' ? false : true; // Make element draggable or not. domElement.draggable = draggable; if (! draggable) return ; domElement.addEventListener('dragstart', function (e) { // Restrict drag effect. e.dataTransfer.effectAllowed = effectAllowed || e.dataTransfer.effectAllowed; // Eval and serialize data. var data = scope.$eval(draggableData); var jsonData = angular.toJson(data); // Set drag data and drag type. e.dataTransfer.setData('json/' + draggableType, jsonData); e.stopPropagation(); }); } }; }
[ "function", "draggableDirective", "(", ")", "{", "return", "{", "restrict", ":", "'A'", ",", "link", ":", "function", "(", "scope", ",", "element", ",", "attrs", ")", "{", "var", "domElement", "=", "element", "[", "0", "]", ";", "var", "effectAllowed", "=", "attrs", ".", "effectAllowed", ";", "var", "draggableData", "=", "attrs", ".", "draggableData", ";", "var", "draggableType", "=", "attrs", ".", "draggableType", ";", "var", "draggable", "=", "attrs", ".", "draggable", "===", "'false'", "?", "false", ":", "true", ";", "domElement", ".", "draggable", "=", "draggable", ";", "if", "(", "!", "draggable", ")", "return", ";", "domElement", ".", "addEventListener", "(", "'dragstart'", ",", "function", "(", "e", ")", "{", "e", ".", "dataTransfer", ".", "effectAllowed", "=", "effectAllowed", "||", "e", ".", "dataTransfer", ".", "effectAllowed", ";", "var", "data", "=", "scope", ".", "$eval", "(", "draggableData", ")", ";", "var", "jsonData", "=", "angular", ".", "toJson", "(", "data", ")", ";", "e", ".", "dataTransfer", ".", "setData", "(", "'json/'", "+", "draggableType", ",", "jsonData", ")", ";", "e", ".", "stopPropagation", "(", ")", ";", "}", ")", ";", "}", "}", ";", "}" ]
Draggable directive. @example <div draggable="true" effect-allowed="link" draggable-type="image" draggable-data="{foo: 'bar'}"></div> - "draggable" Make the element draggable. Accepts a boolean. - "effect-allowed" Allowed effects for the dragged element, see https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer#effectAllowed.28.29. Accepts a string. - "draggable-type" Type of data object attached to the dragged element, this type is prefixed by "json/". Accepts a string. - "draggable-data" Data attached to the dragged element, data are serialized in JSON. Accepts an Angular expression.
[ "Draggable", "directive", "." ]
69b1fafd48a6d288fd39cf6e29813ad328c096ec
https://github.com/neoziro/angular-draganddrop/blob/69b1fafd48a6d288fd39cf6e29813ad328c096ec/angular-draganddrop.js#L24-L54
train
neoziro/angular-draganddrop
angular-draganddrop.js
accepts
function accepts(type, event) { if (typeof type === 'boolean') return type; if (typeof type === 'string') return accepts([type], event); if (Array.isArray(type)) { return accepts(function (types) { return types.some(function (_type) { return type.indexOf(_type) !== -1; }); }, event); } if (typeof type === 'function') return type(toArray(event.dataTransfer.types)); return false; }
javascript
function accepts(type, event) { if (typeof type === 'boolean') return type; if (typeof type === 'string') return accepts([type], event); if (Array.isArray(type)) { return accepts(function (types) { return types.some(function (_type) { return type.indexOf(_type) !== -1; }); }, event); } if (typeof type === 'function') return type(toArray(event.dataTransfer.types)); return false; }
[ "function", "accepts", "(", "type", ",", "event", ")", "{", "if", "(", "typeof", "type", "===", "'boolean'", ")", "return", "type", ";", "if", "(", "typeof", "type", "===", "'string'", ")", "return", "accepts", "(", "[", "type", "]", ",", "event", ")", ";", "if", "(", "Array", ".", "isArray", "(", "type", ")", ")", "{", "return", "accepts", "(", "function", "(", "types", ")", "{", "return", "types", ".", "some", "(", "function", "(", "_type", ")", "{", "return", "type", ".", "indexOf", "(", "_type", ")", "!==", "-", "1", ";", "}", ")", ";", "}", ",", "event", ")", ";", "}", "if", "(", "typeof", "type", "===", "'function'", ")", "return", "type", "(", "toArray", "(", "event", ".", "dataTransfer", ".", "types", ")", ")", ";", "return", "false", ";", "}" ]
Test if a type is accepted. @param {String|Array|Function} type @param {Event} event @returns {Boolean}
[ "Test", "if", "a", "type", "is", "accepted", "." ]
69b1fafd48a6d288fd39cf6e29813ad328c096ec
https://github.com/neoziro/angular-draganddrop/blob/69b1fafd48a6d288fd39cf6e29813ad328c096ec/angular-draganddrop.js#L143-L156
train
neoziro/angular-draganddrop
angular-draganddrop.js
getData
function getData(event) { var types = toArray(event.dataTransfer.types); return types.reduce(function (collection, type) { // Get data. var data = event.dataTransfer.getData(type); // Get data format. var format = /(.*)\//.exec(type); format = format ? format[1] : null; // Parse data. if (format === 'json') data = JSON.parse(data); collection[type] = data; return collection; }, {}); }
javascript
function getData(event) { var types = toArray(event.dataTransfer.types); return types.reduce(function (collection, type) { // Get data. var data = event.dataTransfer.getData(type); // Get data format. var format = /(.*)\//.exec(type); format = format ? format[1] : null; // Parse data. if (format === 'json') data = JSON.parse(data); collection[type] = data; return collection; }, {}); }
[ "function", "getData", "(", "event", ")", "{", "var", "types", "=", "toArray", "(", "event", ".", "dataTransfer", ".", "types", ")", ";", "return", "types", ".", "reduce", "(", "function", "(", "collection", ",", "type", ")", "{", "var", "data", "=", "event", ".", "dataTransfer", ".", "getData", "(", "type", ")", ";", "var", "format", "=", "/", "(.*)\\/", "/", ".", "exec", "(", "type", ")", ";", "format", "=", "format", "?", "format", "[", "1", "]", ":", "null", ";", "if", "(", "format", "===", "'json'", ")", "data", "=", "JSON", ".", "parse", "(", "data", ")", ";", "collection", "[", "type", "]", "=", "data", ";", "return", "collection", ";", "}", ",", "{", "}", ")", ";", "}" ]
Get data from a drag event. @param {Event} event @returns {Object}
[ "Get", "data", "from", "a", "drag", "event", "." ]
69b1fafd48a6d288fd39cf6e29813ad328c096ec
https://github.com/neoziro/angular-draganddrop/blob/69b1fafd48a6d288fd39cf6e29813ad328c096ec/angular-draganddrop.js#L165-L183
train
TendaDigital/Tournamenter
modules/view-default/public/js/page-indicator.js
function(el){ if(!el) el = this.$el.last(); else el = $(el); el.fadeOut(el.remove); }
javascript
function(el){ if(!el) el = this.$el.last(); else el = $(el); el.fadeOut(el.remove); }
[ "function", "(", "el", ")", "{", "if", "(", "!", "el", ")", "el", "=", "this", ".", "$el", ".", "last", "(", ")", ";", "else", "el", "=", "$", "(", "el", ")", ";", "el", ".", "fadeOut", "(", "el", ".", "remove", ")", ";", "}" ]
Remove the element "el". If not set, will remove the last one
[ "Remove", "the", "element", "el", ".", "If", "not", "set", "will", "remove", "the", "last", "one" ]
2733ae9b454ae90896249ab1d7a07007eb4a69e4
https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/modules/view-default/public/js/page-indicator.js#L98-L105
train
onury/jsdoc-x
src/index.js
sortDocs
function sortDocs(docs, sortType) { if (!sortType) return; const fnSorter = sorter.getSymbolsComparer(sortType, '$longname'); const fnPropSorter = sorter.getSymbolsComparer(sortType, 'name'); docs.sort(fnSorter); docs.forEach(symbol => { if (symbol && Array.isArray(symbol.properties)) { symbol.properties.sort(fnPropSorter); } }); }
javascript
function sortDocs(docs, sortType) { if (!sortType) return; const fnSorter = sorter.getSymbolsComparer(sortType, '$longname'); const fnPropSorter = sorter.getSymbolsComparer(sortType, 'name'); docs.sort(fnSorter); docs.forEach(symbol => { if (symbol && Array.isArray(symbol.properties)) { symbol.properties.sort(fnPropSorter); } }); }
[ "function", "sortDocs", "(", "docs", ",", "sortType", ")", "{", "if", "(", "!", "sortType", ")", "return", ";", "const", "fnSorter", "=", "sorter", ".", "getSymbolsComparer", "(", "sortType", ",", "'$longname'", ")", ";", "const", "fnPropSorter", "=", "sorter", ".", "getSymbolsComparer", "(", "sortType", ",", "'name'", ")", ";", "docs", ".", "sort", "(", "fnSorter", ")", ";", "docs", ".", "forEach", "(", "symbol", "=>", "{", "if", "(", "symbol", "&&", "Array", ".", "isArray", "(", "symbol", ".", "properties", ")", ")", "{", "symbol", ".", "properties", ".", "sort", "(", "fnPropSorter", ")", ";", "}", "}", ")", ";", "}" ]
sorts documentation symbols and properties of each symbol, if any.
[ "sorts", "documentation", "symbols", "and", "properties", "of", "each", "symbol", "if", "any", "." ]
33e4e0cc3e3c5ad9b17589b42e7a9dfa706b7d30
https://github.com/onury/jsdoc-x/blob/33e4e0cc3e3c5ad9b17589b42e7a9dfa706b7d30/src/index.js#L132-L142
train
philgs/grunt-available-tasks
lib/filterTasks.js
filterTasks
function filterTasks (type, tasks, alltasks) { var contains = function (task) { return _.includes(tasks, task.name); }; if (type === 'include') { return _.filter(alltasks, contains); } else if (type === 'exclude') { return _.reject(alltasks, contains); } return alltasks; }
javascript
function filterTasks (type, tasks, alltasks) { var contains = function (task) { return _.includes(tasks, task.name); }; if (type === 'include') { return _.filter(alltasks, contains); } else if (type === 'exclude') { return _.reject(alltasks, contains); } return alltasks; }
[ "function", "filterTasks", "(", "type", ",", "tasks", ",", "alltasks", ")", "{", "var", "contains", "=", "function", "(", "task", ")", "{", "return", "_", ".", "includes", "(", "tasks", ",", "task", ".", "name", ")", ";", "}", ";", "if", "(", "type", "===", "'include'", ")", "{", "return", "_", ".", "filter", "(", "alltasks", ",", "contains", ")", ";", "}", "else", "if", "(", "type", "===", "'exclude'", ")", "{", "return", "_", ".", "reject", "(", "alltasks", ",", "contains", ")", ";", "}", "return", "alltasks", ";", "}" ]
Filtering rules are optional; delete those tasks that don't pass a filter
[ "Filtering", "rules", "are", "optional", ";", "delete", "those", "tasks", "that", "don", "t", "pass", "a", "filter" ]
faf0c76196cde8b3ed377fed2c2fae3ec1c33f6b
https://github.com/philgs/grunt-available-tasks/blob/faf0c76196cde8b3ed377fed2c2fae3ec1c33f6b/lib/filterTasks.js#L6-L17
train
bambusoideae/passport-firebase-auth
lib/errors/internalautherror.js
InternalAuthError
function InternalAuthError(message, err) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = message; this.authError = err; }
javascript
function InternalAuthError(message, err) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = message; this.authError = err; }
[ "function", "InternalAuthError", "(", "message", ",", "err", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", ";", "this", ".", "message", "=", "message", ";", "this", ".", "authError", "=", "err", ";", "}" ]
`InternalAuthError` error. InternalAuthError wraps errors generated by node-oauth. By wrapping these objects, error messages can be formatted in a manner that aids in debugging OAuth issues. @constructor @param {String} [message] @param {Object|Error} [err] @api public
[ "InternalAuthError", "error", "." ]
149a78c4e4cdc5315722b2f7bb7c0a0552c4500a
https://github.com/bambusoideae/passport-firebase-auth/blob/149a78c4e4cdc5315722b2f7bb7c0a0552c4500a/lib/errors/internalautherror.js#L13-L19
train
fxa/uritemplate-js
bin/uritemplate.js
encodeCharacter
function encodeCharacter (chr) { var result = '', octets = utf8.encode(chr), octet, index; for (index = 0; index < octets.length; index += 1) { octet = octets.charCodeAt(index); result += '%' + (octet < 0x10 ? '0' : '') + octet.toString(16).toUpperCase(); } return result; }
javascript
function encodeCharacter (chr) { var result = '', octets = utf8.encode(chr), octet, index; for (index = 0; index < octets.length; index += 1) { octet = octets.charCodeAt(index); result += '%' + (octet < 0x10 ? '0' : '') + octet.toString(16).toUpperCase(); } return result; }
[ "function", "encodeCharacter", "(", "chr", ")", "{", "var", "result", "=", "''", ",", "octets", "=", "utf8", ".", "encode", "(", "chr", ")", ",", "octet", ",", "index", ";", "for", "(", "index", "=", "0", ";", "index", "<", "octets", ".", "length", ";", "index", "+=", "1", ")", "{", "octet", "=", "octets", ".", "charCodeAt", "(", "index", ")", ";", "result", "+=", "'%'", "+", "(", "octet", "<", "0x10", "?", "'0'", ":", "''", ")", "+", "octet", ".", "toString", "(", "16", ")", ".", "toUpperCase", "(", ")", ";", "}", "return", "result", ";", "}" ]
encodes a character, if needed or not. @param chr @return pct-encoded character
[ "encodes", "a", "character", "if", "needed", "or", "not", "." ]
d9c73932b42173c0f1bbafa88badc7a8e0cd6c06
https://github.com/fxa/uritemplate-js/blob/d9c73932b42173c0f1bbafa88badc7a8e0cd6c06/bin/uritemplate.js#L176-L187
train
fxa/uritemplate-js
bin/uritemplate.js
isPercentDigitDigit
function isPercentDigitDigit (text, start) { return text.charAt(start) === '%' && charHelper.isHexDigit(text.charAt(start + 1)) && charHelper.isHexDigit(text.charAt(start + 2)); }
javascript
function isPercentDigitDigit (text, start) { return text.charAt(start) === '%' && charHelper.isHexDigit(text.charAt(start + 1)) && charHelper.isHexDigit(text.charAt(start + 2)); }
[ "function", "isPercentDigitDigit", "(", "text", ",", "start", ")", "{", "return", "text", ".", "charAt", "(", "start", ")", "===", "'%'", "&&", "charHelper", ".", "isHexDigit", "(", "text", ".", "charAt", "(", "start", "+", "1", ")", ")", "&&", "charHelper", ".", "isHexDigit", "(", "text", ".", "charAt", "(", "start", "+", "2", ")", ")", ";", "}" ]
Returns, whether the given text at start is in the form 'percent hex-digit hex-digit', like '%3F' @param text @param start @return {boolean|*|*}
[ "Returns", "whether", "the", "given", "text", "at", "start", "is", "in", "the", "form", "percent", "hex", "-", "digit", "hex", "-", "digit", "like", "%3F" ]
d9c73932b42173c0f1bbafa88badc7a8e0cd6c06
https://github.com/fxa/uritemplate-js/blob/d9c73932b42173c0f1bbafa88badc7a8e0cd6c06/bin/uritemplate.js#L195-L197
train
fxa/uritemplate-js
bin/uritemplate.js
isPctEncoded
function isPctEncoded (chr) { if (!isPercentDigitDigit(chr, 0)) { return false; } var firstCharCode = parseHex2(chr, 1); var numBytes = utf8.numBytes(firstCharCode); if (numBytes === 0) { return false; } for (var byteNumber = 1; byteNumber < numBytes; byteNumber += 1) { if (!isPercentDigitDigit(chr, 3*byteNumber) || !utf8.isValidFollowingCharCode(parseHex2(chr, 3*byteNumber + 1))) { return false; } } return true; }
javascript
function isPctEncoded (chr) { if (!isPercentDigitDigit(chr, 0)) { return false; } var firstCharCode = parseHex2(chr, 1); var numBytes = utf8.numBytes(firstCharCode); if (numBytes === 0) { return false; } for (var byteNumber = 1; byteNumber < numBytes; byteNumber += 1) { if (!isPercentDigitDigit(chr, 3*byteNumber) || !utf8.isValidFollowingCharCode(parseHex2(chr, 3*byteNumber + 1))) { return false; } } return true; }
[ "function", "isPctEncoded", "(", "chr", ")", "{", "if", "(", "!", "isPercentDigitDigit", "(", "chr", ",", "0", ")", ")", "{", "return", "false", ";", "}", "var", "firstCharCode", "=", "parseHex2", "(", "chr", ",", "1", ")", ";", "var", "numBytes", "=", "utf8", ".", "numBytes", "(", "firstCharCode", ")", ";", "if", "(", "numBytes", "===", "0", ")", "{", "return", "false", ";", "}", "for", "(", "var", "byteNumber", "=", "1", ";", "byteNumber", "<", "numBytes", ";", "byteNumber", "+=", "1", ")", "{", "if", "(", "!", "isPercentDigitDigit", "(", "chr", ",", "3", "*", "byteNumber", ")", "||", "!", "utf8", ".", "isValidFollowingCharCode", "(", "parseHex2", "(", "chr", ",", "3", "*", "byteNumber", "+", "1", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Returns whether or not the given char sequence is a correctly pct-encoded sequence. @param chr @return {boolean}
[ "Returns", "whether", "or", "not", "the", "given", "char", "sequence", "is", "a", "correctly", "pct", "-", "encoded", "sequence", "." ]
d9c73932b42173c0f1bbafa88badc7a8e0cd6c06
https://github.com/fxa/uritemplate-js/blob/d9c73932b42173c0f1bbafa88badc7a8e0cd6c06/bin/uritemplate.js#L214-L229
train
fxa/uritemplate-js
bin/uritemplate.js
isVarchar
function isVarchar (chr) { return charHelper.isAlpha(chr) || charHelper.isDigit(chr) || chr === '_' || pctEncoder.isPctEncoded(chr); }
javascript
function isVarchar (chr) { return charHelper.isAlpha(chr) || charHelper.isDigit(chr) || chr === '_' || pctEncoder.isPctEncoded(chr); }
[ "function", "isVarchar", "(", "chr", ")", "{", "return", "charHelper", ".", "isAlpha", "(", "chr", ")", "||", "charHelper", ".", "isDigit", "(", "chr", ")", "||", "chr", "===", "'_'", "||", "pctEncoder", ".", "isPctEncoded", "(", "chr", ")", ";", "}" ]
Returns if an character is an varchar character according 2.3 of rfc 6570 @param chr @return (Boolean)
[ "Returns", "if", "an", "character", "is", "an", "varchar", "character", "according", "2", ".", "3", "of", "rfc", "6570" ]
d9c73932b42173c0f1bbafa88badc7a8e0cd6c06
https://github.com/fxa/uritemplate-js/blob/d9c73932b42173c0f1bbafa88badc7a8e0cd6c06/bin/uritemplate.js#L269-L271
train