id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
56,000
dimitrievski/sumov
lib/index.js
sumov
function sumov(object, depth = 0) { if (isNumber(object)) { return parseFloat(object); } else if (isObject(object) && Number.isInteger(depth)) { return sumObjectValues(object, depth); } return 0; }
javascript
function sumov(object, depth = 0) { if (isNumber(object)) { return parseFloat(object); } else if (isObject(object) && Number.isInteger(depth)) { return sumObjectValues(object, depth); } return 0; }
[ "function", "sumov", "(", "object", ",", "depth", "=", "0", ")", "{", "if", "(", "isNumber", "(", "object", ")", ")", "{", "return", "parseFloat", "(", "object", ")", ";", "}", "else", "if", "(", "isObject", "(", "object", ")", "&&", "Number", ".", "isInteger", "(", "depth", ")", ")", "{", "return", "sumObjectValues", "(", "object", ",", "depth", ")", ";", "}", "return", "0", ";", "}" ]
Computes the sum of all numeric values in an object @param {Object} object @param {Integer} depth @returns {Number} @example sumov({a: 2, b: ["2", null, [], {a: {a: -1.0}}], c: {quick: "maths"}}); // => 3 //sum up to 2 levels sumov({a: 2, b: ["2", null, [], {a: {a: -1.0}}], c: {quick: "maths"}}, 2); // => 4
[ "Computes", "the", "sum", "of", "all", "numeric", "values", "in", "an", "object" ]
bdbdae19305f9c7e86c2a9124b64d664c0893fab
https://github.com/dimitrievski/sumov/blob/bdbdae19305f9c7e86c2a9124b64d664c0893fab/lib/index.js#L66-L73
56,001
thiagodp/shuffle-obj-arrays
index.js
shuffleObjArrays
function shuffleObjArrays( map, options ) { var newMap = !! options && true === options.copy ? {} : map; var copyNonArrays = !! options && true === options.copy && true === ( options.copyNonArrays || options.copyNonArray ); var values = null; for ( var key in map ) { values = map[ key ]; if ( isArray( values ) ) { newMap[ key ] = shuffle( values, options ); } else if ( copyNonArrays ) { newMap[ key ] = map[ key ]; } } return newMap; }
javascript
function shuffleObjArrays( map, options ) { var newMap = !! options && true === options.copy ? {} : map; var copyNonArrays = !! options && true === options.copy && true === ( options.copyNonArrays || options.copyNonArray ); var values = null; for ( var key in map ) { values = map[ key ]; if ( isArray( values ) ) { newMap[ key ] = shuffle( values, options ); } else if ( copyNonArrays ) { newMap[ key ] = map[ key ]; } } return newMap; }
[ "function", "shuffleObjArrays", "(", "map", ",", "options", ")", "{", "var", "newMap", "=", "!", "!", "options", "&&", "true", "===", "options", ".", "copy", "?", "{", "}", ":", "map", ";", "var", "copyNonArrays", "=", "!", "!", "options", "&&", "true", "===", "options", ".", "copy", "&&", "true", "===", "(", "options", ".", "copyNonArrays", "||", "options", ".", "copyNonArray", ")", ";", "var", "values", "=", "null", ";", "for", "(", "var", "key", "in", "map", ")", "{", "values", "=", "map", "[", "key", "]", ";", "if", "(", "isArray", "(", "values", ")", ")", "{", "newMap", "[", "key", "]", "=", "shuffle", "(", "values", ",", "options", ")", ";", "}", "else", "if", "(", "copyNonArrays", ")", "{", "newMap", "[", "key", "]", "=", "map", "[", "key", "]", ";", "}", "}", "return", "newMap", ";", "}" ]
Shuffles the arrays of the given map. @param {object} map Maps string => array of values, e.g. `{ "foo": [ "x", "y" ], "bar": [ "a", "b", "c" ] }`. @param {object} options All the options from [shuffle-array](https://github.com/pazguille/shuffle-array) plus: - `copyNonArrays`: boolean -> If you want to copy non-array properties. Defaults to false. @returns {object} A map with its arrays shuffled.
[ "Shuffles", "the", "arrays", "of", "the", "given", "map", "." ]
1ef61c75a37fd3e6ba95935ea936b2811c72dd03
https://github.com/thiagodp/shuffle-obj-arrays/blob/1ef61c75a37fd3e6ba95935ea936b2811c72dd03/index.js#L21-L34
56,002
mdp/dotp-crypt
lib/tweetnacl-fast.js
crypto_stream_salsa20_xor
function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { var z = new Uint8Array(16), x = new Uint8Array(64); var u, i; for (i = 0; i < 16; i++) z[i] = 0; for (i = 0; i < 8; i++) z[i] = n[i]; while (b >= 64) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; u = 1; for (i = 8; i < 16; i++) { u = u + (z[i] & 0xff) | 0; z[i] = u & 0xff; u >>>= 8; } b -= 64; cpos += 64; mpos += 64; } if (b > 0) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; } return 0; }
javascript
function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { var z = new Uint8Array(16), x = new Uint8Array(64); var u, i; for (i = 0; i < 16; i++) z[i] = 0; for (i = 0; i < 8; i++) z[i] = n[i]; while (b >= 64) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; u = 1; for (i = 8; i < 16; i++) { u = u + (z[i] & 0xff) | 0; z[i] = u & 0xff; u >>>= 8; } b -= 64; cpos += 64; mpos += 64; } if (b > 0) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; } return 0; }
[ "function", "crypto_stream_salsa20_xor", "(", "c", ",", "cpos", ",", "m", ",", "mpos", ",", "b", ",", "n", ",", "k", ")", "{", "var", "z", "=", "new", "Uint8Array", "(", "16", ")", ",", "x", "=", "new", "Uint8Array", "(", "64", ")", ";", "var", "u", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "16", ";", "i", "++", ")", "z", "[", "i", "]", "=", "0", ";", "for", "(", "i", "=", "0", ";", "i", "<", "8", ";", "i", "++", ")", "z", "[", "i", "]", "=", "n", "[", "i", "]", ";", "while", "(", "b", ">=", "64", ")", "{", "crypto_core_salsa20", "(", "x", ",", "z", ",", "k", ",", "sigma", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "64", ";", "i", "++", ")", "c", "[", "cpos", "+", "i", "]", "=", "m", "[", "mpos", "+", "i", "]", "^", "x", "[", "i", "]", ";", "u", "=", "1", ";", "for", "(", "i", "=", "8", ";", "i", "<", "16", ";", "i", "++", ")", "{", "u", "=", "u", "+", "(", "z", "[", "i", "]", "&", "0xff", ")", "|", "0", ";", "z", "[", "i", "]", "=", "u", "&", "0xff", ";", "u", ">>>=", "8", ";", "}", "b", "-=", "64", ";", "cpos", "+=", "64", ";", "mpos", "+=", "64", ";", "}", "if", "(", "b", ">", "0", ")", "{", "crypto_core_salsa20", "(", "x", ",", "z", ",", "k", ",", "sigma", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "b", ";", "i", "++", ")", "c", "[", "cpos", "+", "i", "]", "=", "m", "[", "mpos", "+", "i", "]", "^", "x", "[", "i", "]", ";", "}", "return", "0", ";", "}" ]
"expand 32-byte k"
[ "expand", "32", "-", "byte", "k" ]
d8b99a3d0e4dafbeeee4926138b398a7f52ee4e8
https://github.com/mdp/dotp-crypt/blob/d8b99a3d0e4dafbeeee4926138b398a7f52ee4e8/lib/tweetnacl-fast.js#L397-L420
56,003
nomocas/yamvish
lib/interpolable.js
handler
function handler(instance, context, func, index, callback) { return function() { var old = instance.results[index]; instance.results[index] = tryExpr(func, context); if (old === instance.results[index]) return; if (instance.dependenciesCount === 1 || !Interpolable.allowDelayedUpdate) callback(instance.output(context), 'set'); else if (!instance.willFire) instance.willFire = context.delay(function() { // call on nextTick to manage other dependencies update without multiple rerender if (instance.willFire) { instance.willFire = null; callback(instance.output(context), 'set'); } }, 0); }; }
javascript
function handler(instance, context, func, index, callback) { return function() { var old = instance.results[index]; instance.results[index] = tryExpr(func, context); if (old === instance.results[index]) return; if (instance.dependenciesCount === 1 || !Interpolable.allowDelayedUpdate) callback(instance.output(context), 'set'); else if (!instance.willFire) instance.willFire = context.delay(function() { // call on nextTick to manage other dependencies update without multiple rerender if (instance.willFire) { instance.willFire = null; callback(instance.output(context), 'set'); } }, 0); }; }
[ "function", "handler", "(", "instance", ",", "context", ",", "func", ",", "index", ",", "callback", ")", "{", "return", "function", "(", ")", "{", "var", "old", "=", "instance", ".", "results", "[", "index", "]", ";", "instance", ".", "results", "[", "index", "]", "=", "tryExpr", "(", "func", ",", "context", ")", ";", "if", "(", "old", "===", "instance", ".", "results", "[", "index", "]", ")", "return", ";", "if", "(", "instance", ".", "dependenciesCount", "===", "1", "||", "!", "Interpolable", ".", "allowDelayedUpdate", ")", "callback", "(", "instance", ".", "output", "(", "context", ")", ",", "'set'", ")", ";", "else", "if", "(", "!", "instance", ".", "willFire", ")", "instance", ".", "willFire", "=", "context", ".", "delay", "(", "function", "(", ")", "{", "// call on nextTick to manage other dependencies update without multiple rerender", "if", "(", "instance", ".", "willFire", ")", "{", "instance", ".", "willFire", "=", "null", ";", "callback", "(", "instance", ".", "output", "(", "context", ")", ",", "'set'", ")", ";", "}", "}", ",", "0", ")", ";", "}", ";", "}" ]
produce context's subscibtion event handler
[ "produce", "context", "s", "subscibtion", "event", "handler" ]
017a536bb6bafddf1b31c0c7af6f723be58e9f0e
https://github.com/nomocas/yamvish/blob/017a536bb6bafddf1b31c0c7af6f723be58e9f0e/lib/interpolable.js#L77-L93
56,004
nomocas/yamvish
lib/interpolable.js
directOutput
function directOutput(context) { var o = tryExpr(this.parts[1].func, context); return (typeof o === 'undefined' && !this._strict) ? '' : o; }
javascript
function directOutput(context) { var o = tryExpr(this.parts[1].func, context); return (typeof o === 'undefined' && !this._strict) ? '' : o; }
[ "function", "directOutput", "(", "context", ")", "{", "var", "o", "=", "tryExpr", "(", "this", ".", "parts", "[", "1", "]", ".", "func", ",", "context", ")", ";", "return", "(", "typeof", "o", "===", "'undefined'", "&&", "!", "this", ".", "_strict", ")", "?", "''", ":", "o", ";", "}" ]
special case when interpolable is composed of only one expression with no text decoration return expr result directly
[ "special", "case", "when", "interpolable", "is", "composed", "of", "only", "one", "expression", "with", "no", "text", "decoration", "return", "expr", "result", "directly" ]
017a536bb6bafddf1b31c0c7af6f723be58e9f0e
https://github.com/nomocas/yamvish/blob/017a536bb6bafddf1b31c0c7af6f723be58e9f0e/lib/interpolable.js#L97-L100
56,005
nomocas/yamvish
lib/interpolable.js
function(context, callback, binds) { var instance = new Instance(this); var count = 0, binded = false; for (var i = 1, len = this.parts.length; i < len; i = i + 2) { var block = this.parts[i]; if (block.binded) { binded = true; var h = handler(instance, context, block.func, count, callback), dep = block.dep; for (var j = 0, lenJ = dep.length; j < lenJ; j++) context.subscribe(dep[j], h, false, instance.binds); } count++; } if (binded && binds) binds.push(unsub(instance)); return instance; }
javascript
function(context, callback, binds) { var instance = new Instance(this); var count = 0, binded = false; for (var i = 1, len = this.parts.length; i < len; i = i + 2) { var block = this.parts[i]; if (block.binded) { binded = true; var h = handler(instance, context, block.func, count, callback), dep = block.dep; for (var j = 0, lenJ = dep.length; j < lenJ; j++) context.subscribe(dep[j], h, false, instance.binds); } count++; } if (binded && binds) binds.push(unsub(instance)); return instance; }
[ "function", "(", "context", ",", "callback", ",", "binds", ")", "{", "var", "instance", "=", "new", "Instance", "(", "this", ")", ";", "var", "count", "=", "0", ",", "binded", "=", "false", ";", "for", "(", "var", "i", "=", "1", ",", "len", "=", "this", ".", "parts", ".", "length", ";", "i", "<", "len", ";", "i", "=", "i", "+", "2", ")", "{", "var", "block", "=", "this", ".", "parts", "[", "i", "]", ";", "if", "(", "block", ".", "binded", ")", "{", "binded", "=", "true", ";", "var", "h", "=", "handler", "(", "instance", ",", "context", ",", "block", ".", "func", ",", "count", ",", "callback", ")", ",", "dep", "=", "block", ".", "dep", ";", "for", "(", "var", "j", "=", "0", ",", "lenJ", "=", "dep", ".", "length", ";", "j", "<", "lenJ", ";", "j", "++", ")", "context", ".", "subscribe", "(", "dep", "[", "j", "]", ",", "h", ",", "false", ",", "instance", ".", "binds", ")", ";", "}", "count", "++", ";", "}", "if", "(", "binded", "&&", "binds", ")", "binds", ".", "push", "(", "unsub", "(", "instance", ")", ")", ";", "return", "instance", ";", "}" ]
produce instance and bind to context
[ "produce", "instance", "and", "bind", "to", "context" ]
017a536bb6bafddf1b31c0c7af6f723be58e9f0e
https://github.com/nomocas/yamvish/blob/017a536bb6bafddf1b31c0c7af6f723be58e9f0e/lib/interpolable.js#L191-L209
56,006
nomocas/yamvish
lib/interpolable.js
function(context) { if (this.directOutput) return this.directOutput(context); var out = "", odd = true, parts = this.parts; for (var j = 0, len = parts.length; j < len; ++j) { if (odd) out += parts[j]; else { var r = tryExpr(parts[j].func, context); if (typeof r === 'undefined') { if (this._strict) return; out += ''; } out += r; } odd = !odd; } return out; }
javascript
function(context) { if (this.directOutput) return this.directOutput(context); var out = "", odd = true, parts = this.parts; for (var j = 0, len = parts.length; j < len; ++j) { if (odd) out += parts[j]; else { var r = tryExpr(parts[j].func, context); if (typeof r === 'undefined') { if (this._strict) return; out += ''; } out += r; } odd = !odd; } return out; }
[ "function", "(", "context", ")", "{", "if", "(", "this", ".", "directOutput", ")", "return", "this", ".", "directOutput", "(", "context", ")", ";", "var", "out", "=", "\"\"", ",", "odd", "=", "true", ",", "parts", "=", "this", ".", "parts", ";", "for", "(", "var", "j", "=", "0", ",", "len", "=", "parts", ".", "length", ";", "j", "<", "len", ";", "++", "j", ")", "{", "if", "(", "odd", ")", "out", "+=", "parts", "[", "j", "]", ";", "else", "{", "var", "r", "=", "tryExpr", "(", "parts", "[", "j", "]", ".", "func", ",", "context", ")", ";", "if", "(", "typeof", "r", "===", "'undefined'", ")", "{", "if", "(", "this", ".", "_strict", ")", "return", ";", "out", "+=", "''", ";", "}", "out", "+=", "r", ";", "}", "odd", "=", "!", "odd", ";", "}", "return", "out", ";", "}" ]
output interpolable with given context
[ "output", "interpolable", "with", "given", "context" ]
017a536bb6bafddf1b31c0c7af6f723be58e9f0e
https://github.com/nomocas/yamvish/blob/017a536bb6bafddf1b31c0c7af6f723be58e9f0e/lib/interpolable.js#L211-L232
56,007
doowb/base-tree
index.js
tree
function tree(app, options) { var opts = extend({}, options); var node = { label: getLabel(app, opts), metadata: getMetadata(app, opts) }; // get the names of the children to lookup var names = arrayify(opts.names || ['nodes']); return names.reduce(function(acc, name) { var children = app[name]; if (typeof children !== 'object') { return node; } // build a tree for each child node var nodes = []; for (var key in children) { var child = children[key]; if (typeof child[opts.method] === 'function') { nodes.push(child[opts.method](opts)); } else { var res = tree(child, opts); nodes.push(res); } } if (nodes.length) { node.nodes = (node.nodes || []).concat(nodes); } return node; }, node); }
javascript
function tree(app, options) { var opts = extend({}, options); var node = { label: getLabel(app, opts), metadata: getMetadata(app, opts) }; // get the names of the children to lookup var names = arrayify(opts.names || ['nodes']); return names.reduce(function(acc, name) { var children = app[name]; if (typeof children !== 'object') { return node; } // build a tree for each child node var nodes = []; for (var key in children) { var child = children[key]; if (typeof child[opts.method] === 'function') { nodes.push(child[opts.method](opts)); } else { var res = tree(child, opts); nodes.push(res); } } if (nodes.length) { node.nodes = (node.nodes || []).concat(nodes); } return node; }, node); }
[ "function", "tree", "(", "app", ",", "options", ")", "{", "var", "opts", "=", "extend", "(", "{", "}", ",", "options", ")", ";", "var", "node", "=", "{", "label", ":", "getLabel", "(", "app", ",", "opts", ")", ",", "metadata", ":", "getMetadata", "(", "app", ",", "opts", ")", "}", ";", "// get the names of the children to lookup", "var", "names", "=", "arrayify", "(", "opts", ".", "names", "||", "[", "'nodes'", "]", ")", ";", "return", "names", ".", "reduce", "(", "function", "(", "acc", ",", "name", ")", "{", "var", "children", "=", "app", "[", "name", "]", ";", "if", "(", "typeof", "children", "!==", "'object'", ")", "{", "return", "node", ";", "}", "// build a tree for each child node", "var", "nodes", "=", "[", "]", ";", "for", "(", "var", "key", "in", "children", ")", "{", "var", "child", "=", "children", "[", "key", "]", ";", "if", "(", "typeof", "child", "[", "opts", ".", "method", "]", "===", "'function'", ")", "{", "nodes", ".", "push", "(", "child", "[", "opts", ".", "method", "]", "(", "opts", ")", ")", ";", "}", "else", "{", "var", "res", "=", "tree", "(", "child", ",", "opts", ")", ";", "nodes", ".", "push", "(", "res", ")", ";", "}", "}", "if", "(", "nodes", ".", "length", ")", "{", "node", ".", "nodes", "=", "(", "node", ".", "nodes", "||", "[", "]", ")", ".", "concat", "(", "nodes", ")", ";", "}", "return", "node", ";", "}", ",", "node", ")", ";", "}" ]
Default tree building function. Gets the label and metadata properties for the current `app` and recursively generates the child nodes and child trees if possible. This method may be overriden by passing a `.tree` function on options. @param {Object} `app` Current application to build a node and tree from. @param {Object} `options` Options used to control how the `label` and `metadata` properties are retreived. @return {Object} Generated node containing `label`, `metadata`, and `nodes` properties for current segment of a tree. @api public @name options.tree
[ "Default", "tree", "building", "function", ".", "Gets", "the", "label", "and", "metadata", "properties", "for", "the", "current", "app", "and", "recursively", "generates", "the", "child", "nodes", "and", "child", "trees", "if", "possible", "." ]
32f9fd3015460512a5f4013990048827329146ee
https://github.com/doowb/base-tree/blob/32f9fd3015460512a5f4013990048827329146ee/index.js#L78-L112
56,008
doowb/base-tree
index.js
getLabel
function getLabel(app, options) { if (typeof options.getLabel === 'function') { return options.getLabel(app, options); } return app.full_name || app.nickname || app.name; }
javascript
function getLabel(app, options) { if (typeof options.getLabel === 'function') { return options.getLabel(app, options); } return app.full_name || app.nickname || app.name; }
[ "function", "getLabel", "(", "app", ",", "options", ")", "{", "if", "(", "typeof", "options", ".", "getLabel", "===", "'function'", ")", "{", "return", "options", ".", "getLabel", "(", "app", ",", "options", ")", ";", "}", "return", "app", ".", "full_name", "||", "app", ".", "nickname", "||", "app", ".", "name", ";", "}" ]
Figure out a label to add for a node in the tree. @param {Object} `app` Current node/app being iterated over @param {Object} `options` Pass `getLabel` on options to handle yourself. @return {String} label to be shown @api public @name options.getLabel
[ "Figure", "out", "a", "label", "to", "add", "for", "a", "node", "in", "the", "tree", "." ]
32f9fd3015460512a5f4013990048827329146ee
https://github.com/doowb/base-tree/blob/32f9fd3015460512a5f4013990048827329146ee/index.js#L124-L129
56,009
homerjam/angular-modal-service2
angular-modal-service2.js
function(template, templateUrl) { var deferred = $q.defer(); if (template) { deferred.resolve(template); } else if (templateUrl) { // Check to see if the template has already been loaded. var cachedTemplate = $templateCache.get(templateUrl); if (cachedTemplate) { deferred.resolve(cachedTemplate); } else { // If not, let's grab the template for the first time. $http.get(templateUrl).then(function(result) { // Save template into the cache and return the template. $templateCache.put(templateUrl, result.data); deferred.resolve(result.data); }, function(error) { deferred.reject(error); }); } } else { deferred.reject('No template or templateUrl has been specified.'); } return deferred.promise; }
javascript
function(template, templateUrl) { var deferred = $q.defer(); if (template) { deferred.resolve(template); } else if (templateUrl) { // Check to see if the template has already been loaded. var cachedTemplate = $templateCache.get(templateUrl); if (cachedTemplate) { deferred.resolve(cachedTemplate); } else { // If not, let's grab the template for the first time. $http.get(templateUrl).then(function(result) { // Save template into the cache and return the template. $templateCache.put(templateUrl, result.data); deferred.resolve(result.data); }, function(error) { deferred.reject(error); }); } } else { deferred.reject('No template or templateUrl has been specified.'); } return deferred.promise; }
[ "function", "(", "template", ",", "templateUrl", ")", "{", "var", "deferred", "=", "$q", ".", "defer", "(", ")", ";", "if", "(", "template", ")", "{", "deferred", ".", "resolve", "(", "template", ")", ";", "}", "else", "if", "(", "templateUrl", ")", "{", "// Check to see if the template has already been loaded.", "var", "cachedTemplate", "=", "$templateCache", ".", "get", "(", "templateUrl", ")", ";", "if", "(", "cachedTemplate", ")", "{", "deferred", ".", "resolve", "(", "cachedTemplate", ")", ";", "}", "else", "{", "// If not, let's grab the template for the first time.", "$http", ".", "get", "(", "templateUrl", ")", ".", "then", "(", "function", "(", "result", ")", "{", "// Save template into the cache and return the template.", "$templateCache", ".", "put", "(", "templateUrl", ",", "result", ".", "data", ")", ";", "deferred", ".", "resolve", "(", "result", ".", "data", ")", ";", "}", ",", "function", "(", "error", ")", "{", "deferred", ".", "reject", "(", "error", ")", ";", "}", ")", ";", "}", "}", "else", "{", "deferred", ".", "reject", "(", "'No template or templateUrl has been specified.'", ")", ";", "}", "return", "deferred", ".", "promise", ";", "}" ]
Returns a promise which gets the template, either from the template parameter or via a request to the templateUrl parameter.
[ "Returns", "a", "promise", "which", "gets", "the", "template", "either", "from", "the", "template", "parameter", "or", "via", "a", "request", "to", "the", "templateUrl", "parameter", "." ]
9d8fc0f590cdea198a214a1a7bf088f3abfc3a99
https://github.com/homerjam/angular-modal-service2/blob/9d8fc0f590cdea198a214a1a7bf088f3abfc3a99/angular-modal-service2.js#L20-L52
56,010
johnwebbcole/gulp-openjscad-standalone
docs/openjscad.js
function(e) { this.touch.cur = 'dragging'; var delta = 0; if (this.touch.lastY && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) { //tilt delta = e.gesture.deltaY - this.touch.lastY; this.angleX += delta; } else if (this.touch.lastX && (e.gesture.direction == 'left' || e.gesture.direction == 'right')) { //pan delta = e.gesture.deltaX - this.touch.lastX; this.angleZ += delta; } if (delta) this.onDraw(); this.touch.lastX = e.gesture.deltaX; this.touch.lastY = e.gesture.deltaY; }
javascript
function(e) { this.touch.cur = 'dragging'; var delta = 0; if (this.touch.lastY && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) { //tilt delta = e.gesture.deltaY - this.touch.lastY; this.angleX += delta; } else if (this.touch.lastX && (e.gesture.direction == 'left' || e.gesture.direction == 'right')) { //pan delta = e.gesture.deltaX - this.touch.lastX; this.angleZ += delta; } if (delta) this.onDraw(); this.touch.lastX = e.gesture.deltaX; this.touch.lastY = e.gesture.deltaY; }
[ "function", "(", "e", ")", "{", "this", ".", "touch", ".", "cur", "=", "'dragging'", ";", "var", "delta", "=", "0", ";", "if", "(", "this", ".", "touch", ".", "lastY", "&&", "(", "e", ".", "gesture", ".", "direction", "==", "'up'", "||", "e", ".", "gesture", ".", "direction", "==", "'down'", ")", ")", "{", "//tilt", "delta", "=", "e", ".", "gesture", ".", "deltaY", "-", "this", ".", "touch", ".", "lastY", ";", "this", ".", "angleX", "+=", "delta", ";", "}", "else", "if", "(", "this", ".", "touch", ".", "lastX", "&&", "(", "e", ".", "gesture", ".", "direction", "==", "'left'", "||", "e", ".", "gesture", ".", "direction", "==", "'right'", ")", ")", "{", "//pan", "delta", "=", "e", ".", "gesture", ".", "deltaX", "-", "this", ".", "touch", ".", "lastX", ";", "this", ".", "angleZ", "+=", "delta", ";", "}", "if", "(", "delta", ")", "this", ".", "onDraw", "(", ")", ";", "this", ".", "touch", ".", "lastX", "=", "e", ".", "gesture", ".", "deltaX", ";", "this", ".", "touch", ".", "lastY", "=", "e", ".", "gesture", ".", "deltaY", ";", "}" ]
pan & tilt with one finger
[ "pan", "&", "tilt", "with", "one", "finger" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/openjscad.js#L421-L437
56,011
johnwebbcole/gulp-openjscad-standalone
docs/openjscad.js
function(e) { this.touch.cur = 'shifting'; var factor = 5e-3; var delta = 0; if (this.touch.lastY && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) { this.touch.shiftControl .removeClass('shift-horizontal') .addClass('shift-vertical') .css('top', e.gesture.center.pageY + 'px'); delta = e.gesture.deltaY - this.touch.lastY; this.viewpointY -= factor * delta * this.viewpointZ; this.angleX += delta; } if (this.touch.lastX && (e.gesture.direction == 'left' || e.gesture.direction == 'right')) { this.touch.shiftControl .removeClass('shift-vertical') .addClass('shift-horizontal') .css('left', e.gesture.center.pageX + 'px'); delta = e.gesture.deltaX - this.touch.lastX; this.viewpointX += factor * delta * this.viewpointZ; this.angleZ += delta; } if (delta) this.onDraw(); this.touch.lastX = e.gesture.deltaX; this.touch.lastY = e.gesture.deltaY; }
javascript
function(e) { this.touch.cur = 'shifting'; var factor = 5e-3; var delta = 0; if (this.touch.lastY && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) { this.touch.shiftControl .removeClass('shift-horizontal') .addClass('shift-vertical') .css('top', e.gesture.center.pageY + 'px'); delta = e.gesture.deltaY - this.touch.lastY; this.viewpointY -= factor * delta * this.viewpointZ; this.angleX += delta; } if (this.touch.lastX && (e.gesture.direction == 'left' || e.gesture.direction == 'right')) { this.touch.shiftControl .removeClass('shift-vertical') .addClass('shift-horizontal') .css('left', e.gesture.center.pageX + 'px'); delta = e.gesture.deltaX - this.touch.lastX; this.viewpointX += factor * delta * this.viewpointZ; this.angleZ += delta; } if (delta) this.onDraw(); this.touch.lastX = e.gesture.deltaX; this.touch.lastY = e.gesture.deltaY; }
[ "function", "(", "e", ")", "{", "this", ".", "touch", ".", "cur", "=", "'shifting'", ";", "var", "factor", "=", "5e-3", ";", "var", "delta", "=", "0", ";", "if", "(", "this", ".", "touch", ".", "lastY", "&&", "(", "e", ".", "gesture", ".", "direction", "==", "'up'", "||", "e", ".", "gesture", ".", "direction", "==", "'down'", ")", ")", "{", "this", ".", "touch", ".", "shiftControl", ".", "removeClass", "(", "'shift-horizontal'", ")", ".", "addClass", "(", "'shift-vertical'", ")", ".", "css", "(", "'top'", ",", "e", ".", "gesture", ".", "center", ".", "pageY", "+", "'px'", ")", ";", "delta", "=", "e", ".", "gesture", ".", "deltaY", "-", "this", ".", "touch", ".", "lastY", ";", "this", ".", "viewpointY", "-=", "factor", "*", "delta", "*", "this", ".", "viewpointZ", ";", "this", ".", "angleX", "+=", "delta", ";", "}", "if", "(", "this", ".", "touch", ".", "lastX", "&&", "(", "e", ".", "gesture", ".", "direction", "==", "'left'", "||", "e", ".", "gesture", ".", "direction", "==", "'right'", ")", ")", "{", "this", ".", "touch", ".", "shiftControl", ".", "removeClass", "(", "'shift-vertical'", ")", ".", "addClass", "(", "'shift-horizontal'", ")", ".", "css", "(", "'left'", ",", "e", ".", "gesture", ".", "center", ".", "pageX", "+", "'px'", ")", ";", "delta", "=", "e", ".", "gesture", ".", "deltaX", "-", "this", ".", "touch", ".", "lastX", ";", "this", ".", "viewpointX", "+=", "factor", "*", "delta", "*", "this", ".", "viewpointZ", ";", "this", ".", "angleZ", "+=", "delta", ";", "}", "if", "(", "delta", ")", "this", ".", "onDraw", "(", ")", ";", "this", ".", "touch", ".", "lastX", "=", "e", ".", "gesture", ".", "deltaX", ";", "this", ".", "touch", ".", "lastY", "=", "e", ".", "gesture", ".", "deltaY", ";", "}" ]
shift after 0.5s touch&hold
[ "shift", "after", "0", ".", "5s", "touch&hold" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/openjscad.js#L440-L467
56,012
johnwebbcole/gulp-openjscad-standalone
docs/openjscad.js
function(initial_csg) { var csg = initial_csg.canonicalized(); var mesh = new GL.Mesh({ normals: true, colors: true }); var meshes = [ mesh ]; var vertexTag2Index = {}; var vertices = []; var colors = []; var triangles = []; // set to true if we want to use interpolated vertex normals // this creates nice round spheres but does not represent the shape of // the actual model var smoothlighting = this.solid.smooth; var polygons = csg.toPolygons(); var numpolygons = polygons.length; for(var j = 0; j < numpolygons; j++) { var polygon = polygons[j]; var color = this.solid.color; // default color if(polygon.shared && polygon.shared.color) { color = polygon.shared.color; } else if(polygon.color) { color = polygon.color; } if (color.length < 4) color.push(1.); //opaque var indices = polygon.vertices.map(function(vertex) { var vertextag = vertex.getTag(); var vertexindex = vertexTag2Index[vertextag]; var prevcolor = colors[vertexindex]; if(smoothlighting && (vertextag in vertexTag2Index) && (prevcolor[0] == color[0]) && (prevcolor[1] == color[1]) && (prevcolor[2] == color[2]) ) { vertexindex = vertexTag2Index[vertextag]; } else { vertexindex = vertices.length; vertexTag2Index[vertextag] = vertexindex; vertices.push([vertex.pos.x, vertex.pos.y, vertex.pos.z]); colors.push(color); } return vertexindex; }); for (var i = 2; i < indices.length; i++) { triangles.push([indices[0], indices[i - 1], indices[i]]); } // if too many vertices, start a new mesh; if (vertices.length > 65000) { // finalize the old mesh mesh.triangles = triangles; mesh.vertices = vertices; mesh.colors = colors; mesh.computeWireframe(); mesh.computeNormals(); if ( mesh.vertices.length ) { meshes.push(mesh); } // start a new mesh mesh = new GL.Mesh({ normals: true, colors: true }); triangles = []; colors = []; vertices = []; } } // finalize last mesh mesh.triangles = triangles; mesh.vertices = vertices; mesh.colors = colors; mesh.computeWireframe(); mesh.computeNormals(); if ( mesh.vertices.length ) { meshes.push(mesh); } return meshes; }
javascript
function(initial_csg) { var csg = initial_csg.canonicalized(); var mesh = new GL.Mesh({ normals: true, colors: true }); var meshes = [ mesh ]; var vertexTag2Index = {}; var vertices = []; var colors = []; var triangles = []; // set to true if we want to use interpolated vertex normals // this creates nice round spheres but does not represent the shape of // the actual model var smoothlighting = this.solid.smooth; var polygons = csg.toPolygons(); var numpolygons = polygons.length; for(var j = 0; j < numpolygons; j++) { var polygon = polygons[j]; var color = this.solid.color; // default color if(polygon.shared && polygon.shared.color) { color = polygon.shared.color; } else if(polygon.color) { color = polygon.color; } if (color.length < 4) color.push(1.); //opaque var indices = polygon.vertices.map(function(vertex) { var vertextag = vertex.getTag(); var vertexindex = vertexTag2Index[vertextag]; var prevcolor = colors[vertexindex]; if(smoothlighting && (vertextag in vertexTag2Index) && (prevcolor[0] == color[0]) && (prevcolor[1] == color[1]) && (prevcolor[2] == color[2]) ) { vertexindex = vertexTag2Index[vertextag]; } else { vertexindex = vertices.length; vertexTag2Index[vertextag] = vertexindex; vertices.push([vertex.pos.x, vertex.pos.y, vertex.pos.z]); colors.push(color); } return vertexindex; }); for (var i = 2; i < indices.length; i++) { triangles.push([indices[0], indices[i - 1], indices[i]]); } // if too many vertices, start a new mesh; if (vertices.length > 65000) { // finalize the old mesh mesh.triangles = triangles; mesh.vertices = vertices; mesh.colors = colors; mesh.computeWireframe(); mesh.computeNormals(); if ( mesh.vertices.length ) { meshes.push(mesh); } // start a new mesh mesh = new GL.Mesh({ normals: true, colors: true }); triangles = []; colors = []; vertices = []; } } // finalize last mesh mesh.triangles = triangles; mesh.vertices = vertices; mesh.colors = colors; mesh.computeWireframe(); mesh.computeNormals(); if ( mesh.vertices.length ) { meshes.push(mesh); } return meshes; }
[ "function", "(", "initial_csg", ")", "{", "var", "csg", "=", "initial_csg", ".", "canonicalized", "(", ")", ";", "var", "mesh", "=", "new", "GL", ".", "Mesh", "(", "{", "normals", ":", "true", ",", "colors", ":", "true", "}", ")", ";", "var", "meshes", "=", "[", "mesh", "]", ";", "var", "vertexTag2Index", "=", "{", "}", ";", "var", "vertices", "=", "[", "]", ";", "var", "colors", "=", "[", "]", ";", "var", "triangles", "=", "[", "]", ";", "// set to true if we want to use interpolated vertex normals", "// this creates nice round spheres but does not represent the shape of", "// the actual model", "var", "smoothlighting", "=", "this", ".", "solid", ".", "smooth", ";", "var", "polygons", "=", "csg", ".", "toPolygons", "(", ")", ";", "var", "numpolygons", "=", "polygons", ".", "length", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "numpolygons", ";", "j", "++", ")", "{", "var", "polygon", "=", "polygons", "[", "j", "]", ";", "var", "color", "=", "this", ".", "solid", ".", "color", ";", "// default color", "if", "(", "polygon", ".", "shared", "&&", "polygon", ".", "shared", ".", "color", ")", "{", "color", "=", "polygon", ".", "shared", ".", "color", ";", "}", "else", "if", "(", "polygon", ".", "color", ")", "{", "color", "=", "polygon", ".", "color", ";", "}", "if", "(", "color", ".", "length", "<", "4", ")", "color", ".", "push", "(", "1.", ")", ";", "//opaque", "var", "indices", "=", "polygon", ".", "vertices", ".", "map", "(", "function", "(", "vertex", ")", "{", "var", "vertextag", "=", "vertex", ".", "getTag", "(", ")", ";", "var", "vertexindex", "=", "vertexTag2Index", "[", "vertextag", "]", ";", "var", "prevcolor", "=", "colors", "[", "vertexindex", "]", ";", "if", "(", "smoothlighting", "&&", "(", "vertextag", "in", "vertexTag2Index", ")", "&&", "(", "prevcolor", "[", "0", "]", "==", "color", "[", "0", "]", ")", "&&", "(", "prevcolor", "[", "1", "]", "==", "color", "[", "1", "]", ")", "&&", "(", "prevcolor", "[", "2", "]", "==", "color", "[", "2", "]", ")", ")", "{", "vertexindex", "=", "vertexTag2Index", "[", "vertextag", "]", ";", "}", "else", "{", "vertexindex", "=", "vertices", ".", "length", ";", "vertexTag2Index", "[", "vertextag", "]", "=", "vertexindex", ";", "vertices", ".", "push", "(", "[", "vertex", ".", "pos", ".", "x", ",", "vertex", ".", "pos", ".", "y", ",", "vertex", ".", "pos", ".", "z", "]", ")", ";", "colors", ".", "push", "(", "color", ")", ";", "}", "return", "vertexindex", ";", "}", ")", ";", "for", "(", "var", "i", "=", "2", ";", "i", "<", "indices", ".", "length", ";", "i", "++", ")", "{", "triangles", ".", "push", "(", "[", "indices", "[", "0", "]", ",", "indices", "[", "i", "-", "1", "]", ",", "indices", "[", "i", "]", "]", ")", ";", "}", "// if too many vertices, start a new mesh;", "if", "(", "vertices", ".", "length", ">", "65000", ")", "{", "// finalize the old mesh", "mesh", ".", "triangles", "=", "triangles", ";", "mesh", ".", "vertices", "=", "vertices", ";", "mesh", ".", "colors", "=", "colors", ";", "mesh", ".", "computeWireframe", "(", ")", ";", "mesh", ".", "computeNormals", "(", ")", ";", "if", "(", "mesh", ".", "vertices", ".", "length", ")", "{", "meshes", ".", "push", "(", "mesh", ")", ";", "}", "// start a new mesh", "mesh", "=", "new", "GL", ".", "Mesh", "(", "{", "normals", ":", "true", ",", "colors", ":", "true", "}", ")", ";", "triangles", "=", "[", "]", ";", "colors", "=", "[", "]", ";", "vertices", "=", "[", "]", ";", "}", "}", "// finalize last mesh", "mesh", ".", "triangles", "=", "triangles", ";", "mesh", ".", "vertices", "=", "vertices", ";", "mesh", ".", "colors", "=", "colors", ";", "mesh", ".", "computeWireframe", "(", ")", ";", "mesh", ".", "computeNormals", "(", ")", ";", "if", "(", "mesh", ".", "vertices", ".", "length", ")", "{", "meshes", ".", "push", "(", "mesh", ")", ";", "}", "return", "meshes", ";", "}" ]
Convert from CSG solid to an array of GL.Mesh objects limiting the number of vertices per mesh to less than 2^16
[ "Convert", "from", "CSG", "solid", "to", "an", "array", "of", "GL", ".", "Mesh", "objects", "limiting", "the", "number", "of", "vertices", "per", "mesh", "to", "less", "than", "2^16" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/openjscad.js#L581-L661
56,013
johnwebbcole/gulp-openjscad-standalone
docs/openjscad.js
function(err, objs) { that.worker = null; if(err) { that.setError(err); that.setStatus("Error."); that.state = 3; // incomplete } else { that.setCurrentObjects(objs); that.setStatus("Ready."); that.state = 2; // complete } that.enableItems(); }
javascript
function(err, objs) { that.worker = null; if(err) { that.setError(err); that.setStatus("Error."); that.state = 3; // incomplete } else { that.setCurrentObjects(objs); that.setStatus("Ready."); that.state = 2; // complete } that.enableItems(); }
[ "function", "(", "err", ",", "objs", ")", "{", "that", ".", "worker", "=", "null", ";", "if", "(", "err", ")", "{", "that", ".", "setError", "(", "err", ")", ";", "that", ".", "setStatus", "(", "\"Error.\"", ")", ";", "that", ".", "state", "=", "3", ";", "// incomplete", "}", "else", "{", "that", ".", "setCurrentObjects", "(", "objs", ")", ";", "that", ".", "setStatus", "(", "\"Ready.\"", ")", ";", "that", ".", "state", "=", "2", ";", "// complete", "}", "that", ".", "enableItems", "(", ")", ";", "}" ]
handle the results
[ "handle", "the", "results" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/openjscad.js#L1306-L1318
56,014
catbee/appstate
src/appstate.js
runBranch
function runBranch (index, options) { var { tree, signal, start, promise } = options; var currentBranch = tree.branches[index]; if (!currentBranch && tree.branches === signal.branches) { if (tree.branches[index - 1]) { tree.branches[index - 1].duration = Date.now() - start; } signal.isExecuting = false; if (promise) { promise.resolve(signal); } return; } if (!currentBranch) { return; } if (Array.isArray(currentBranch)) { return runAsyncBranch(index, currentBranch, options); } else { return runSyncBranch(index, currentBranch, options); } }
javascript
function runBranch (index, options) { var { tree, signal, start, promise } = options; var currentBranch = tree.branches[index]; if (!currentBranch && tree.branches === signal.branches) { if (tree.branches[index - 1]) { tree.branches[index - 1].duration = Date.now() - start; } signal.isExecuting = false; if (promise) { promise.resolve(signal); } return; } if (!currentBranch) { return; } if (Array.isArray(currentBranch)) { return runAsyncBranch(index, currentBranch, options); } else { return runSyncBranch(index, currentBranch, options); } }
[ "function", "runBranch", "(", "index", ",", "options", ")", "{", "var", "{", "tree", ",", "signal", ",", "start", ",", "promise", "}", "=", "options", ";", "var", "currentBranch", "=", "tree", ".", "branches", "[", "index", "]", ";", "if", "(", "!", "currentBranch", "&&", "tree", ".", "branches", "===", "signal", ".", "branches", ")", "{", "if", "(", "tree", ".", "branches", "[", "index", "-", "1", "]", ")", "{", "tree", ".", "branches", "[", "index", "-", "1", "]", ".", "duration", "=", "Date", ".", "now", "(", ")", "-", "start", ";", "}", "signal", ".", "isExecuting", "=", "false", ";", "if", "(", "promise", ")", "{", "promise", ".", "resolve", "(", "signal", ")", ";", "}", "return", ";", "}", "if", "(", "!", "currentBranch", ")", "{", "return", ";", "}", "if", "(", "Array", ".", "isArray", "(", "currentBranch", ")", ")", "{", "return", "runAsyncBranch", "(", "index", ",", "currentBranch", ",", "options", ")", ";", "}", "else", "{", "return", "runSyncBranch", "(", "index", ",", "currentBranch", ",", "options", ")", ";", "}", "}" ]
Run tree branch, or resolve signal if no more branches in recursion. @param {Number} index @param {Object} options @param {Object} options.tree @param {Object} options.args @param {Object} options.signal @param {Object} options.promise @param {Date} options.start @param {Baobab} options.state @param {Object} options.services
[ "Run", "tree", "branch", "or", "resolve", "signal", "if", "no", "more", "branches", "in", "recursion", "." ]
44c404f18e6c2716452567d91a5231a53d67e892
https://github.com/catbee/appstate/blob/44c404f18e6c2716452567d91a5231a53d67e892/src/appstate.js#L72-L99
56,015
catbee/appstate
src/appstate.js
runAsyncBranch
function runAsyncBranch (index, currentBranch, options) { var { tree, args, signal, state, promise, start, services } = options; var promises = currentBranch .map(action => { var actionFunc = tree.actions[action.actionIndex]; var actionArgs = createActionArgs(args, action, state, true); var outputs = action.outputs ? Object.keys(action.outputs) : []; action.isExecuting = true; action.args = merge({}, args); var nextActionPromise; var foundResult = signal.asyncActionResults.find((result) => isEqualArrays(result.outputPath, action.path)); // If actions results provided, you run it in replay mode if (foundResult) { nextActionPromise = Promise.resolve(foundResult); } else { var next = createNextAsyncAction(actionFunc, outputs); actionFunc.apply(null, actionArgs.concat(next.fn, services)); nextActionPromise = next.promise; } return nextActionPromise .then(result => { action.hasExecuted = true; action.isExecuting = false; action.output = result.args; // Save short results snippet for replay signal.asyncActionResults.push({ outputPath: action.path, path: result.path, args: result.args }); merge(args, result.args); if (result.path) { action.outputPath = result.path; var output = action.outputs[result.path]; return runBranch(0, { args, signal, state, start, promise, services, tree: { actions: tree.actions, branches: output } }); } }) .catch((e) => promise.reject(e)); }); return Promise.all(promises) .then(() => runBranch(index + 1, options)); }
javascript
function runAsyncBranch (index, currentBranch, options) { var { tree, args, signal, state, promise, start, services } = options; var promises = currentBranch .map(action => { var actionFunc = tree.actions[action.actionIndex]; var actionArgs = createActionArgs(args, action, state, true); var outputs = action.outputs ? Object.keys(action.outputs) : []; action.isExecuting = true; action.args = merge({}, args); var nextActionPromise; var foundResult = signal.asyncActionResults.find((result) => isEqualArrays(result.outputPath, action.path)); // If actions results provided, you run it in replay mode if (foundResult) { nextActionPromise = Promise.resolve(foundResult); } else { var next = createNextAsyncAction(actionFunc, outputs); actionFunc.apply(null, actionArgs.concat(next.fn, services)); nextActionPromise = next.promise; } return nextActionPromise .then(result => { action.hasExecuted = true; action.isExecuting = false; action.output = result.args; // Save short results snippet for replay signal.asyncActionResults.push({ outputPath: action.path, path: result.path, args: result.args }); merge(args, result.args); if (result.path) { action.outputPath = result.path; var output = action.outputs[result.path]; return runBranch(0, { args, signal, state, start, promise, services, tree: { actions: tree.actions, branches: output } }); } }) .catch((e) => promise.reject(e)); }); return Promise.all(promises) .then(() => runBranch(index + 1, options)); }
[ "function", "runAsyncBranch", "(", "index", ",", "currentBranch", ",", "options", ")", "{", "var", "{", "tree", ",", "args", ",", "signal", ",", "state", ",", "promise", ",", "start", ",", "services", "}", "=", "options", ";", "var", "promises", "=", "currentBranch", ".", "map", "(", "action", "=>", "{", "var", "actionFunc", "=", "tree", ".", "actions", "[", "action", ".", "actionIndex", "]", ";", "var", "actionArgs", "=", "createActionArgs", "(", "args", ",", "action", ",", "state", ",", "true", ")", ";", "var", "outputs", "=", "action", ".", "outputs", "?", "Object", ".", "keys", "(", "action", ".", "outputs", ")", ":", "[", "]", ";", "action", ".", "isExecuting", "=", "true", ";", "action", ".", "args", "=", "merge", "(", "{", "}", ",", "args", ")", ";", "var", "nextActionPromise", ";", "var", "foundResult", "=", "signal", ".", "asyncActionResults", ".", "find", "(", "(", "result", ")", "=>", "isEqualArrays", "(", "result", ".", "outputPath", ",", "action", ".", "path", ")", ")", ";", "// If actions results provided, you run it in replay mode", "if", "(", "foundResult", ")", "{", "nextActionPromise", "=", "Promise", ".", "resolve", "(", "foundResult", ")", ";", "}", "else", "{", "var", "next", "=", "createNextAsyncAction", "(", "actionFunc", ",", "outputs", ")", ";", "actionFunc", ".", "apply", "(", "null", ",", "actionArgs", ".", "concat", "(", "next", ".", "fn", ",", "services", ")", ")", ";", "nextActionPromise", "=", "next", ".", "promise", ";", "}", "return", "nextActionPromise", ".", "then", "(", "result", "=>", "{", "action", ".", "hasExecuted", "=", "true", ";", "action", ".", "isExecuting", "=", "false", ";", "action", ".", "output", "=", "result", ".", "args", ";", "// Save short results snippet for replay", "signal", ".", "asyncActionResults", ".", "push", "(", "{", "outputPath", ":", "action", ".", "path", ",", "path", ":", "result", ".", "path", ",", "args", ":", "result", ".", "args", "}", ")", ";", "merge", "(", "args", ",", "result", ".", "args", ")", ";", "if", "(", "result", ".", "path", ")", "{", "action", ".", "outputPath", "=", "result", ".", "path", ";", "var", "output", "=", "action", ".", "outputs", "[", "result", ".", "path", "]", ";", "return", "runBranch", "(", "0", ",", "{", "args", ",", "signal", ",", "state", ",", "start", ",", "promise", ",", "services", ",", "tree", ":", "{", "actions", ":", "tree", ".", "actions", ",", "branches", ":", "output", "}", "}", ")", ";", "}", "}", ")", ".", "catch", "(", "(", "e", ")", "=>", "promise", ".", "reject", "(", "e", ")", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "promises", ")", ".", "then", "(", "(", ")", "=>", "runBranch", "(", "index", "+", "1", ",", "options", ")", ")", ";", "}" ]
Run async branch @param {Number} index @param {Object} currentBranch @param {Object} options @param {Object} options.tree @param {Object} options.args @param {Object} options.signal @param {Object} options.promise @param {Date} options.start @param {Baobab} options.state @param {Object} options.services @returns {Promise}
[ "Run", "async", "branch" ]
44c404f18e6c2716452567d91a5231a53d67e892
https://github.com/catbee/appstate/blob/44c404f18e6c2716452567d91a5231a53d67e892/src/appstate.js#L115-L172
56,016
catbee/appstate
src/appstate.js
runSyncBranch
function runSyncBranch (index, currentBranch, options) { var { args, tree, signal, state, start, promise, services } = options; try { var action = currentBranch; var actionFunc = tree.actions[action.actionIndex]; var actionArgs = createActionArgs(args, action, state, false); var outputs = action.outputs ? Object.keys(action.outputs) : []; action.mutations = []; action.args = merge({}, args); var next = createNextSyncAction(actionFunc, outputs); actionFunc.apply(null, actionArgs.concat(next, services)); var result = next._result || {}; merge(args, result.args); action.isExecuting = false; action.hasExecuted = true; action.output = result.args; if (result.path) { action.outputPath = result.path; var output = action.outputs[result.path]; var runResult = runBranch(0, { args, signal, state, start, promise, services, tree: { actions: tree.actions, branches: output } }); if (runResult && runResult.then) { return runResult.then(() => { return runBranch(index + 1, options); }); } return runBranch(index + 1, options); } return runBranch(index + 1, options); } catch (e) { promise.reject(e); } }
javascript
function runSyncBranch (index, currentBranch, options) { var { args, tree, signal, state, start, promise, services } = options; try { var action = currentBranch; var actionFunc = tree.actions[action.actionIndex]; var actionArgs = createActionArgs(args, action, state, false); var outputs = action.outputs ? Object.keys(action.outputs) : []; action.mutations = []; action.args = merge({}, args); var next = createNextSyncAction(actionFunc, outputs); actionFunc.apply(null, actionArgs.concat(next, services)); var result = next._result || {}; merge(args, result.args); action.isExecuting = false; action.hasExecuted = true; action.output = result.args; if (result.path) { action.outputPath = result.path; var output = action.outputs[result.path]; var runResult = runBranch(0, { args, signal, state, start, promise, services, tree: { actions: tree.actions, branches: output } }); if (runResult && runResult.then) { return runResult.then(() => { return runBranch(index + 1, options); }); } return runBranch(index + 1, options); } return runBranch(index + 1, options); } catch (e) { promise.reject(e); } }
[ "function", "runSyncBranch", "(", "index", ",", "currentBranch", ",", "options", ")", "{", "var", "{", "args", ",", "tree", ",", "signal", ",", "state", ",", "start", ",", "promise", ",", "services", "}", "=", "options", ";", "try", "{", "var", "action", "=", "currentBranch", ";", "var", "actionFunc", "=", "tree", ".", "actions", "[", "action", ".", "actionIndex", "]", ";", "var", "actionArgs", "=", "createActionArgs", "(", "args", ",", "action", ",", "state", ",", "false", ")", ";", "var", "outputs", "=", "action", ".", "outputs", "?", "Object", ".", "keys", "(", "action", ".", "outputs", ")", ":", "[", "]", ";", "action", ".", "mutations", "=", "[", "]", ";", "action", ".", "args", "=", "merge", "(", "{", "}", ",", "args", ")", ";", "var", "next", "=", "createNextSyncAction", "(", "actionFunc", ",", "outputs", ")", ";", "actionFunc", ".", "apply", "(", "null", ",", "actionArgs", ".", "concat", "(", "next", ",", "services", ")", ")", ";", "var", "result", "=", "next", ".", "_result", "||", "{", "}", ";", "merge", "(", "args", ",", "result", ".", "args", ")", ";", "action", ".", "isExecuting", "=", "false", ";", "action", ".", "hasExecuted", "=", "true", ";", "action", ".", "output", "=", "result", ".", "args", ";", "if", "(", "result", ".", "path", ")", "{", "action", ".", "outputPath", "=", "result", ".", "path", ";", "var", "output", "=", "action", ".", "outputs", "[", "result", ".", "path", "]", ";", "var", "runResult", "=", "runBranch", "(", "0", ",", "{", "args", ",", "signal", ",", "state", ",", "start", ",", "promise", ",", "services", ",", "tree", ":", "{", "actions", ":", "tree", ".", "actions", ",", "branches", ":", "output", "}", "}", ")", ";", "if", "(", "runResult", "&&", "runResult", ".", "then", ")", "{", "return", "runResult", ".", "then", "(", "(", ")", "=>", "{", "return", "runBranch", "(", "index", "+", "1", ",", "options", ")", ";", "}", ")", ";", "}", "return", "runBranch", "(", "index", "+", "1", ",", "options", ")", ";", "}", "return", "runBranch", "(", "index", "+", "1", ",", "options", ")", ";", "}", "catch", "(", "e", ")", "{", "promise", ".", "reject", "(", "e", ")", ";", "}", "}" ]
Run sync branch @param {Number} index @param {Object} currentBranch @param {Object} options @param {Object} options.tree @param {Object} options.args @param {Object} options.signal @param {Object} options.promise @param {Date} options.start @param {Baobab} options.state @param {Object} options.services @returns {Promise|undefined}
[ "Run", "sync", "branch" ]
44c404f18e6c2716452567d91a5231a53d67e892
https://github.com/catbee/appstate/blob/44c404f18e6c2716452567d91a5231a53d67e892/src/appstate.js#L188-L234
56,017
catbee/appstate
src/appstate.js
addOutputs
function addOutputs (next, outputs) { if (Array.isArray(outputs)) { outputs.forEach(key => { next[key] = next.bind(null, key); }); } return next; }
javascript
function addOutputs (next, outputs) { if (Array.isArray(outputs)) { outputs.forEach(key => { next[key] = next.bind(null, key); }); } return next; }
[ "function", "addOutputs", "(", "next", ",", "outputs", ")", "{", "if", "(", "Array", ".", "isArray", "(", "outputs", ")", ")", "{", "outputs", ".", "forEach", "(", "key", "=>", "{", "next", "[", "key", "]", "=", "next", ".", "bind", "(", "null", ",", "key", ")", ";", "}", ")", ";", "}", "return", "next", ";", "}" ]
Add output paths to next function. Outputs takes from branches tree object. @example: var actions = [ syncAction, [ asyncAction, { custom1: [custom1SyncAction], custom2: [custom2SyncAction] } ] ]; function asyncAction ({}, state, output) { if ( ... ) { output.custom1(); } else { output.custom2(); } } @param {Function} next @param {Array} outputs @returns {*}
[ "Add", "output", "paths", "to", "next", "function", "." ]
44c404f18e6c2716452567d91a5231a53d67e892
https://github.com/catbee/appstate/blob/44c404f18e6c2716452567d91a5231a53d67e892/src/appstate.js#L264-L272
56,018
catbee/appstate
src/appstate.js
createNextFunction
function createNextFunction (action, resolver) { return function next (...args) { var path = typeof args[0] === 'string' ? args[0] : null; var arg = path ? args[1] : args[0]; var result = { path: path ? path : action.defaultOutput, args: arg }; if (resolver) { resolver(result); } else { next._result = result; } }; }
javascript
function createNextFunction (action, resolver) { return function next (...args) { var path = typeof args[0] === 'string' ? args[0] : null; var arg = path ? args[1] : args[0]; var result = { path: path ? path : action.defaultOutput, args: arg }; if (resolver) { resolver(result); } else { next._result = result; } }; }
[ "function", "createNextFunction", "(", "action", ",", "resolver", ")", "{", "return", "function", "next", "(", "...", "args", ")", "{", "var", "path", "=", "typeof", "args", "[", "0", "]", "===", "'string'", "?", "args", "[", "0", "]", ":", "null", ";", "var", "arg", "=", "path", "?", "args", "[", "1", "]", ":", "args", "[", "0", "]", ";", "var", "result", "=", "{", "path", ":", "path", "?", "path", ":", "action", ".", "defaultOutput", ",", "args", ":", "arg", "}", ";", "if", "(", "resolver", ")", "{", "resolver", "(", "result", ")", ";", "}", "else", "{", "next", ".", "_result", "=", "result", ";", "}", "}", ";", "}" ]
Create next function in signal chain. It's unified method for async and sync actions. @param {Function} action @param {Function} [resolver] @returns {Function}
[ "Create", "next", "function", "in", "signal", "chain", ".", "It", "s", "unified", "method", "for", "async", "and", "sync", "actions", "." ]
44c404f18e6c2716452567d91a5231a53d67e892
https://github.com/catbee/appstate/blob/44c404f18e6c2716452567d91a5231a53d67e892/src/appstate.js#L281-L297
56,019
catbee/appstate
src/appstate.js
getStateMutatorsAndAccessors
function getStateMutatorsAndAccessors (state, action, isAsync) { var mutators = [ 'apply', 'concat', 'deepMerge', 'push', 'merge', 'unset', 'set', 'splice', 'unshift' ]; var accessors = [ 'get', 'exists' ]; var methods = []; if (isAsync) { methods = methods.concat(accessors); } else { methods = methods.concat(mutators); methods = methods.concat(accessors); } return methods.reduce((stateMethods, methodName) => { var method = state[methodName].bind(state); stateMethods[methodName] = (...args) => { var path = []; var firstArg = args[0]; if (Array.isArray(firstArg)) { path = args.shift(); } else if (typeof firstArg === 'string') { path = [args.shift()]; } if (args.length === 0) { return method.apply(null, [path.slice()]); } action.mutations.push({ name: methodName, path: path.slice(), args: args }); return method.apply(null, [path.slice()].concat(args)); }; return stateMethods; }, Object.create(null)); }
javascript
function getStateMutatorsAndAccessors (state, action, isAsync) { var mutators = [ 'apply', 'concat', 'deepMerge', 'push', 'merge', 'unset', 'set', 'splice', 'unshift' ]; var accessors = [ 'get', 'exists' ]; var methods = []; if (isAsync) { methods = methods.concat(accessors); } else { methods = methods.concat(mutators); methods = methods.concat(accessors); } return methods.reduce((stateMethods, methodName) => { var method = state[methodName].bind(state); stateMethods[methodName] = (...args) => { var path = []; var firstArg = args[0]; if (Array.isArray(firstArg)) { path = args.shift(); } else if (typeof firstArg === 'string') { path = [args.shift()]; } if (args.length === 0) { return method.apply(null, [path.slice()]); } action.mutations.push({ name: methodName, path: path.slice(), args: args }); return method.apply(null, [path.slice()].concat(args)); }; return stateMethods; }, Object.create(null)); }
[ "function", "getStateMutatorsAndAccessors", "(", "state", ",", "action", ",", "isAsync", ")", "{", "var", "mutators", "=", "[", "'apply'", ",", "'concat'", ",", "'deepMerge'", ",", "'push'", ",", "'merge'", ",", "'unset'", ",", "'set'", ",", "'splice'", ",", "'unshift'", "]", ";", "var", "accessors", "=", "[", "'get'", ",", "'exists'", "]", ";", "var", "methods", "=", "[", "]", ";", "if", "(", "isAsync", ")", "{", "methods", "=", "methods", ".", "concat", "(", "accessors", ")", ";", "}", "else", "{", "methods", "=", "methods", ".", "concat", "(", "mutators", ")", ";", "methods", "=", "methods", ".", "concat", "(", "accessors", ")", ";", "}", "return", "methods", ".", "reduce", "(", "(", "stateMethods", ",", "methodName", ")", "=>", "{", "var", "method", "=", "state", "[", "methodName", "]", ".", "bind", "(", "state", ")", ";", "stateMethods", "[", "methodName", "]", "=", "(", "...", "args", ")", "=>", "{", "var", "path", "=", "[", "]", ";", "var", "firstArg", "=", "args", "[", "0", "]", ";", "if", "(", "Array", ".", "isArray", "(", "firstArg", ")", ")", "{", "path", "=", "args", ".", "shift", "(", ")", ";", "}", "else", "if", "(", "typeof", "firstArg", "===", "'string'", ")", "{", "path", "=", "[", "args", ".", "shift", "(", ")", "]", ";", "}", "if", "(", "args", ".", "length", "===", "0", ")", "{", "return", "method", ".", "apply", "(", "null", ",", "[", "path", ".", "slice", "(", ")", "]", ")", ";", "}", "action", ".", "mutations", ".", "push", "(", "{", "name", ":", "methodName", ",", "path", ":", "path", ".", "slice", "(", ")", ",", "args", ":", "args", "}", ")", ";", "return", "method", ".", "apply", "(", "null", ",", "[", "path", ".", "slice", "(", ")", "]", ".", "concat", "(", "args", ")", ")", ";", "}", ";", "return", "stateMethods", ";", "}", ",", "Object", ".", "create", "(", "null", ")", ")", ";", "}" ]
Get state mutators and accessors Each mutation will save in action descriptor. This method allow add ability to gather information about call every function. @param {Object} state @param {Object} action @param {Boolean} isAsync @return {Object}
[ "Get", "state", "mutators", "and", "accessors", "Each", "mutation", "will", "save", "in", "action", "descriptor", ".", "This", "method", "allow", "add", "ability", "to", "gather", "information", "about", "call", "every", "function", "." ]
44c404f18e6c2716452567d91a5231a53d67e892
https://github.com/catbee/appstate/blob/44c404f18e6c2716452567d91a5231a53d67e892/src/appstate.js#L352-L407
56,020
catbee/appstate
src/appstate.js
staticTree
function staticTree (signalActions) { var actions = []; var branches = transformBranch(signalActions, [], [], actions, false); return { actions, branches }; }
javascript
function staticTree (signalActions) { var actions = []; var branches = transformBranch(signalActions, [], [], actions, false); return { actions, branches }; }
[ "function", "staticTree", "(", "signalActions", ")", "{", "var", "actions", "=", "[", "]", ";", "var", "branches", "=", "transformBranch", "(", "signalActions", ",", "[", "]", ",", "[", "]", ",", "actions", ",", "false", ")", ";", "return", "{", "actions", ",", "branches", "}", ";", "}" ]
Transform signal actions to static tree. Every function will be exposed as object definition, that will store meta information and function call results. @param {Array} signalActions @returns {{ actions: [], branches: [] }}
[ "Transform", "signal", "actions", "to", "static", "tree", ".", "Every", "function", "will", "be", "exposed", "as", "object", "definition", "that", "will", "store", "meta", "information", "and", "function", "call", "results", "." ]
44c404f18e6c2716452567d91a5231a53d67e892
https://github.com/catbee/appstate/blob/44c404f18e6c2716452567d91a5231a53d67e892/src/appstate.js#L416-L420
56,021
catbee/appstate
src/appstate.js
transformBranch
function transformBranch (action, ...args) { return Array.isArray(action) ? transformAsyncBranch.apply(null, [action, ...args]) : transformSyncBranch.apply(null, [action, ...args]); }
javascript
function transformBranch (action, ...args) { return Array.isArray(action) ? transformAsyncBranch.apply(null, [action, ...args]) : transformSyncBranch.apply(null, [action, ...args]); }
[ "function", "transformBranch", "(", "action", ",", "...", "args", ")", "{", "return", "Array", ".", "isArray", "(", "action", ")", "?", "transformAsyncBranch", ".", "apply", "(", "null", ",", "[", "action", ",", "...", "args", "]", ")", ":", "transformSyncBranch", ".", "apply", "(", "null", ",", "[", "action", ",", "...", "args", "]", ")", ";", "}" ]
Transform tree branch @param {Function} action @param {Array} args @param {Array|Function} args.parentAction @param {Array} args.path @param {Array} args.actions @param {Boolean} args.isSync @return {Object}
[ "Transform", "tree", "branch" ]
44c404f18e6c2716452567d91a5231a53d67e892
https://github.com/catbee/appstate/blob/44c404f18e6c2716452567d91a5231a53d67e892/src/appstate.js#L432-L436
56,022
catbee/appstate
src/appstate.js
transformAsyncBranch
function transformAsyncBranch (action, parentAction, path, actions, isSync) { action = action.slice(); isSync = !isSync; return action .map((subAction, index) => { path.push(index); var result = transformBranch(subAction, action, path, actions, isSync); path.pop(); return result; }) .filter(branch => !!branch); }
javascript
function transformAsyncBranch (action, parentAction, path, actions, isSync) { action = action.slice(); isSync = !isSync; return action .map((subAction, index) => { path.push(index); var result = transformBranch(subAction, action, path, actions, isSync); path.pop(); return result; }) .filter(branch => !!branch); }
[ "function", "transformAsyncBranch", "(", "action", ",", "parentAction", ",", "path", ",", "actions", ",", "isSync", ")", "{", "action", "=", "action", ".", "slice", "(", ")", ";", "isSync", "=", "!", "isSync", ";", "return", "action", ".", "map", "(", "(", "subAction", ",", "index", ")", "=>", "{", "path", ".", "push", "(", "index", ")", ";", "var", "result", "=", "transformBranch", "(", "subAction", ",", "action", ",", "path", ",", "actions", ",", "isSync", ")", ";", "path", ".", "pop", "(", ")", ";", "return", "result", ";", "}", ")", ".", "filter", "(", "branch", "=>", "!", "!", "branch", ")", ";", "}" ]
Transform action to async branch @param {Function} action @param {Array|Function} parentAction @param {Array} path @param {Array} actions @param {Boolean} isSync @returns {*}
[ "Transform", "action", "to", "async", "branch" ]
44c404f18e6c2716452567d91a5231a53d67e892
https://github.com/catbee/appstate/blob/44c404f18e6c2716452567d91a5231a53d67e892/src/appstate.js#L447-L458
56,023
catbee/appstate
src/appstate.js
transformSyncBranch
function transformSyncBranch (action, parentAction, path, actions, isSync) { var branch = { name: getFunctionName(action), args: {}, output: null, duration: 0, mutations: [], isAsync: !isSync, outputPath: null, isExecuting: false, hasExecuted: false, path: path.slice(), outputs: null, actionIndex: actions.indexOf(action) === -1 ? actions.push(action) - 1 : actions.indexOf(action) }; var nextAction = parentAction[parentAction.indexOf(action) + 1]; if (!Array.isArray(nextAction) && typeof nextAction === 'object') { parentAction.splice(parentAction.indexOf(nextAction), 1); branch.outputs = Object.keys(nextAction) .reduce((paths, key) => { path = path.concat('outputs', key); paths[key] = transformBranch(nextAction[key], parentAction, path, actions, false); path.pop(); path.pop(); return paths; }, {}); } return branch; }
javascript
function transformSyncBranch (action, parentAction, path, actions, isSync) { var branch = { name: getFunctionName(action), args: {}, output: null, duration: 0, mutations: [], isAsync: !isSync, outputPath: null, isExecuting: false, hasExecuted: false, path: path.slice(), outputs: null, actionIndex: actions.indexOf(action) === -1 ? actions.push(action) - 1 : actions.indexOf(action) }; var nextAction = parentAction[parentAction.indexOf(action) + 1]; if (!Array.isArray(nextAction) && typeof nextAction === 'object') { parentAction.splice(parentAction.indexOf(nextAction), 1); branch.outputs = Object.keys(nextAction) .reduce((paths, key) => { path = path.concat('outputs', key); paths[key] = transformBranch(nextAction[key], parentAction, path, actions, false); path.pop(); path.pop(); return paths; }, {}); } return branch; }
[ "function", "transformSyncBranch", "(", "action", ",", "parentAction", ",", "path", ",", "actions", ",", "isSync", ")", "{", "var", "branch", "=", "{", "name", ":", "getFunctionName", "(", "action", ")", ",", "args", ":", "{", "}", ",", "output", ":", "null", ",", "duration", ":", "0", ",", "mutations", ":", "[", "]", ",", "isAsync", ":", "!", "isSync", ",", "outputPath", ":", "null", ",", "isExecuting", ":", "false", ",", "hasExecuted", ":", "false", ",", "path", ":", "path", ".", "slice", "(", ")", ",", "outputs", ":", "null", ",", "actionIndex", ":", "actions", ".", "indexOf", "(", "action", ")", "===", "-", "1", "?", "actions", ".", "push", "(", "action", ")", "-", "1", ":", "actions", ".", "indexOf", "(", "action", ")", "}", ";", "var", "nextAction", "=", "parentAction", "[", "parentAction", ".", "indexOf", "(", "action", ")", "+", "1", "]", ";", "if", "(", "!", "Array", ".", "isArray", "(", "nextAction", ")", "&&", "typeof", "nextAction", "===", "'object'", ")", "{", "parentAction", ".", "splice", "(", "parentAction", ".", "indexOf", "(", "nextAction", ")", ",", "1", ")", ";", "branch", ".", "outputs", "=", "Object", ".", "keys", "(", "nextAction", ")", ".", "reduce", "(", "(", "paths", ",", "key", ")", "=>", "{", "path", "=", "path", ".", "concat", "(", "'outputs'", ",", "key", ")", ";", "paths", "[", "key", "]", "=", "transformBranch", "(", "nextAction", "[", "key", "]", ",", "parentAction", ",", "path", ",", "actions", ",", "false", ")", ";", "path", ".", "pop", "(", ")", ";", "path", ".", "pop", "(", ")", ";", "return", "paths", ";", "}", ",", "{", "}", ")", ";", "}", "return", "branch", ";", "}" ]
Transform action to sync branch @param {Function} action @param {Array|Function} parentAction @param {Array} path @param {Array} actions @param {Boolean} isSync @returns {{ name: *, args: {}, output: null, duration: number, mutations: Array, isAsync: boolean, outputPath: null, isExecuting: boolean, hasExecuted: boolean, path: *, outputs: null, actionIndex: number }|undefined}
[ "Transform", "action", "to", "sync", "branch" ]
44c404f18e6c2716452567d91a5231a53d67e892
https://github.com/catbee/appstate/blob/44c404f18e6c2716452567d91a5231a53d67e892/src/appstate.js#L474-L505
56,024
catbee/appstate
src/appstate.js
analyze
function analyze (actions) { if (!Array.isArray(actions)) { throw new Error('State: Signal actions should be array'); } actions.forEach((action, index) => { if (typeof action === 'undefined' || typeof action === 'string') { throw new Error( ` State: Action number "${index}" in signal does not exist. Check that you have spelled it correctly! ` ); } if (Array.isArray(action)) { analyze(action); } else if (Object.prototype.toString.call(action) === "[object Object]") { Object.keys(action).forEach(function (output) { analyze(action[output]); }); } }); }
javascript
function analyze (actions) { if (!Array.isArray(actions)) { throw new Error('State: Signal actions should be array'); } actions.forEach((action, index) => { if (typeof action === 'undefined' || typeof action === 'string') { throw new Error( ` State: Action number "${index}" in signal does not exist. Check that you have spelled it correctly! ` ); } if (Array.isArray(action)) { analyze(action); } else if (Object.prototype.toString.call(action) === "[object Object]") { Object.keys(action).forEach(function (output) { analyze(action[output]); }); } }); }
[ "function", "analyze", "(", "actions", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "actions", ")", ")", "{", "throw", "new", "Error", "(", "'State: Signal actions should be array'", ")", ";", "}", "actions", ".", "forEach", "(", "(", "action", ",", "index", ")", "=>", "{", "if", "(", "typeof", "action", "===", "'undefined'", "||", "typeof", "action", "===", "'string'", ")", "{", "throw", "new", "Error", "(", "`", "${", "index", "}", "`", ")", ";", "}", "if", "(", "Array", ".", "isArray", "(", "action", ")", ")", "{", "analyze", "(", "action", ")", ";", "}", "else", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "action", ")", "===", "\"[object Object]\"", ")", "{", "Object", ".", "keys", "(", "action", ")", ".", "forEach", "(", "function", "(", "output", ")", "{", "analyze", "(", "action", "[", "output", "]", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Analyze actions for errors @param {Array} actions
[ "Analyze", "actions", "for", "errors" ]
44c404f18e6c2716452567d91a5231a53d67e892
https://github.com/catbee/appstate/blob/44c404f18e6c2716452567d91a5231a53d67e892/src/appstate.js#L511-L534
56,025
catbee/appstate
src/appstate.js
getFunctionName
function getFunctionName (fn) { var name = fn.toString(); name = name.substr('function '.length); name = name.substr(0, name.indexOf('(')); return name; }
javascript
function getFunctionName (fn) { var name = fn.toString(); name = name.substr('function '.length); name = name.substr(0, name.indexOf('(')); return name; }
[ "function", "getFunctionName", "(", "fn", ")", "{", "var", "name", "=", "fn", ".", "toString", "(", ")", ";", "name", "=", "name", ".", "substr", "(", "'function '", ".", "length", ")", ";", "name", "=", "name", ".", "substr", "(", "0", ",", "name", ".", "indexOf", "(", "'('", ")", ")", ";", "return", "name", ";", "}" ]
Get function name @param {Function} fn @returns {String}
[ "Get", "function", "name" ]
44c404f18e6c2716452567d91a5231a53d67e892
https://github.com/catbee/appstate/blob/44c404f18e6c2716452567d91a5231a53d67e892/src/appstate.js#L554-L559
56,026
porkchop/leetcoin-js
lib/leetcoin.js
Player
function Player(params) { this.platformID = this.key = params.key; this.kills = params.kills; this.deaths = params.deaths; this.name = params.name; this.rank = params.rank; this.weapon = params.weapon; }
javascript
function Player(params) { this.platformID = this.key = params.key; this.kills = params.kills; this.deaths = params.deaths; this.name = params.name; this.rank = params.rank; this.weapon = params.weapon; }
[ "function", "Player", "(", "params", ")", "{", "this", ".", "platformID", "=", "this", ".", "key", "=", "params", ".", "key", ";", "this", ".", "kills", "=", "params", ".", "kills", ";", "this", ".", "deaths", "=", "params", ".", "deaths", ";", "this", ".", "name", "=", "params", ".", "name", ";", "this", ".", "rank", "=", "params", ".", "rank", ";", "this", ".", "weapon", "=", "params", ".", "weapon", ";", "}" ]
a leetcoin player
[ "a", "leetcoin", "player" ]
86e086dbd90753cdd4bb8d56f79aa7d04228c30a
https://github.com/porkchop/leetcoin-js/blob/86e086dbd90753cdd4bb8d56f79aa7d04228c30a/lib/leetcoin.js#L37-L44
56,027
posttool/currentcms
lib/cms.js
Cms
function Cms(module, with_app) { if (!module) throw new Error('Requires a module'); if (!module.config) throw new Error('Module requires config'); if (!module.config.name) logger.info('No name specified in config. Calling it null.') if (!module.config.mongoConnectString) throw new Error('Config requires mongoConnectString'); if (!module.models) throw new Error('Module requires models'); // module info and shortcut to configuration this.module = module; this.config = module.config; // connection to mongo this.connection = null; // the storage client this.client = null; // gridfs storage (untested) this.gfs = null; // the express app this.app = null; // login, logout this.auth = null; // meta info for models this.meta = null; // guard manages view permissions this.guard = null; // workflow provides state transition info to view this.workflow = null; logger.info('cms init'); //process.nextTick(this._init.bind(this)); this._init(with_app === undefined ? true : with_app); }
javascript
function Cms(module, with_app) { if (!module) throw new Error('Requires a module'); if (!module.config) throw new Error('Module requires config'); if (!module.config.name) logger.info('No name specified in config. Calling it null.') if (!module.config.mongoConnectString) throw new Error('Config requires mongoConnectString'); if (!module.models) throw new Error('Module requires models'); // module info and shortcut to configuration this.module = module; this.config = module.config; // connection to mongo this.connection = null; // the storage client this.client = null; // gridfs storage (untested) this.gfs = null; // the express app this.app = null; // login, logout this.auth = null; // meta info for models this.meta = null; // guard manages view permissions this.guard = null; // workflow provides state transition info to view this.workflow = null; logger.info('cms init'); //process.nextTick(this._init.bind(this)); this._init(with_app === undefined ? true : with_app); }
[ "function", "Cms", "(", "module", ",", "with_app", ")", "{", "if", "(", "!", "module", ")", "throw", "new", "Error", "(", "'Requires a module'", ")", ";", "if", "(", "!", "module", ".", "config", ")", "throw", "new", "Error", "(", "'Module requires config'", ")", ";", "if", "(", "!", "module", ".", "config", ".", "name", ")", "logger", ".", "info", "(", "'No name specified in config. Calling it null.'", ")", "if", "(", "!", "module", ".", "config", ".", "mongoConnectString", ")", "throw", "new", "Error", "(", "'Config requires mongoConnectString'", ")", ";", "if", "(", "!", "module", ".", "models", ")", "throw", "new", "Error", "(", "'Module requires models'", ")", ";", "// module info and shortcut to configuration", "this", ".", "module", "=", "module", ";", "this", ".", "config", "=", "module", ".", "config", ";", "// connection to mongo", "this", ".", "connection", "=", "null", ";", "// the storage client", "this", ".", "client", "=", "null", ";", "// gridfs storage (untested)", "this", ".", "gfs", "=", "null", ";", "// the express app", "this", ".", "app", "=", "null", ";", "// login, logout", "this", ".", "auth", "=", "null", ";", "// meta info for models", "this", ".", "meta", "=", "null", ";", "// guard manages view permissions", "this", ".", "guard", "=", "null", ";", "// workflow provides state transition info to view", "this", ".", "workflow", "=", "null", ";", "logger", ".", "info", "(", "'cms init'", ")", ";", "//process.nextTick(this._init.bind(this));", "this", ".", "_init", "(", "with_app", "===", "undefined", "?", "true", ":", "with_app", ")", ";", "}" ]
Construct the Cms with a module. Cms ready modules must export at least `models` and `config`. @constructor
[ "Construct", "the", "Cms", "with", "a", "module", ".", "Cms", "ready", "modules", "must", "export", "at", "least", "models", "and", "config", "." ]
9afc9f907bad3b018d961af66c3abb33cd82b051
https://github.com/posttool/currentcms/blob/9afc9f907bad3b018d961af66c3abb33cd82b051/lib/cms.js#L31-L65
56,028
activethread/vulpejs
lib/mongoose/paginate.js
handlePromise
function handlePromise(query, q, model, resultsPerPage) { return Promise.all([ query.exec(), model.count(q).exec() ]).spread(function(results, count) { return [ results, Math.ceil(count / resultsPerPage) || 1, count ] }); }
javascript
function handlePromise(query, q, model, resultsPerPage) { return Promise.all([ query.exec(), model.count(q).exec() ]).spread(function(results, count) { return [ results, Math.ceil(count / resultsPerPage) || 1, count ] }); }
[ "function", "handlePromise", "(", "query", ",", "q", ",", "model", ",", "resultsPerPage", ")", "{", "return", "Promise", ".", "all", "(", "[", "query", ".", "exec", "(", ")", ",", "model", ".", "count", "(", "q", ")", ".", "exec", "(", ")", "]", ")", ".", "spread", "(", "function", "(", "results", ",", "count", ")", "{", "return", "[", "results", ",", "Math", ".", "ceil", "(", "count", "/", "resultsPerPage", ")", "||", "1", ",", "count", "]", "}", ")", ";", "}" ]
Return a promise with results @method handlePromise @param {Object} query - mongoose query object @param {Object} q - query @param {Object} model - mongoose model @param {Number} resultsPerPage @returns {Promise}
[ "Return", "a", "promise", "with", "results" ]
cba9529ebb13892b2c7d07219c7fa69137151fbd
https://github.com/activethread/vulpejs/blob/cba9529ebb13892b2c7d07219c7fa69137151fbd/lib/mongoose/paginate.js#L67-L78
56,029
activethread/vulpejs
lib/mongoose/paginate.js
handleCallback
function handleCallback(query, q, model, resultsPerPage, callback) { return async.parallel({ results: function(callback) { query.exec(callback); }, count: function(callback) { model.count(q, function(err, count) { callback(err, count); }); } }, function(error, data) { if (error) { return callback(error); } callback(null, data.results, Math.ceil(data.count / resultsPerPage) || 1, data.count); }); }
javascript
function handleCallback(query, q, model, resultsPerPage, callback) { return async.parallel({ results: function(callback) { query.exec(callback); }, count: function(callback) { model.count(q, function(err, count) { callback(err, count); }); } }, function(error, data) { if (error) { return callback(error); } callback(null, data.results, Math.ceil(data.count / resultsPerPage) || 1, data.count); }); }
[ "function", "handleCallback", "(", "query", ",", "q", ",", "model", ",", "resultsPerPage", ",", "callback", ")", "{", "return", "async", ".", "parallel", "(", "{", "results", ":", "function", "(", "callback", ")", "{", "query", ".", "exec", "(", "callback", ")", ";", "}", ",", "count", ":", "function", "(", "callback", ")", "{", "model", ".", "count", "(", "q", ",", "function", "(", "err", ",", "count", ")", "{", "callback", "(", "err", ",", "count", ")", ";", "}", ")", ";", "}", "}", ",", "function", "(", "error", ",", "data", ")", "{", "if", "(", "error", ")", "{", "return", "callback", "(", "error", ")", ";", "}", "callback", "(", "null", ",", "data", ".", "results", ",", "Math", ".", "ceil", "(", "data", ".", "count", "/", "resultsPerPage", ")", "||", "1", ",", "data", ".", "count", ")", ";", "}", ")", ";", "}" ]
Call callback function passed with results @method handleCallback @param {Object} query - mongoose query object @param {Object} q - query @param {Object} model - mongoose model @param {Number} resultsPerPage @param {Function} callback @returns {void}
[ "Call", "callback", "function", "passed", "with", "results" ]
cba9529ebb13892b2c7d07219c7fa69137151fbd
https://github.com/activethread/vulpejs/blob/cba9529ebb13892b2c7d07219c7fa69137151fbd/lib/mongoose/paginate.js#L92-L108
56,030
wesleytodd/foreach-in-dir
index.js
foreachInDir
function foreachInDir (dirpath, fnc, done) { // Read the files fs.readdir(dirpath, function (err, files) { // Return error if (err) { return done(err); } // Process each file parallel(files.map(function (f) { return fnc.bind(null, f); }), done); }); }
javascript
function foreachInDir (dirpath, fnc, done) { // Read the files fs.readdir(dirpath, function (err, files) { // Return error if (err) { return done(err); } // Process each file parallel(files.map(function (f) { return fnc.bind(null, f); }), done); }); }
[ "function", "foreachInDir", "(", "dirpath", ",", "fnc", ",", "done", ")", "{", "// Read the files", "fs", ".", "readdir", "(", "dirpath", ",", "function", "(", "err", ",", "files", ")", "{", "// Return error", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", ";", "}", "// Process each file", "parallel", "(", "files", ".", "map", "(", "function", "(", "f", ")", "{", "return", "fnc", ".", "bind", "(", "null", ",", "f", ")", ";", "}", ")", ",", "done", ")", ";", "}", ")", ";", "}" ]
Execute a callback for each file in a directory
[ "Execute", "a", "callback", "for", "each", "file", "in", "a", "directory" ]
1215c889d45681804c8d31a13721bad242655002
https://github.com/wesleytodd/foreach-in-dir/blob/1215c889d45681804c8d31a13721bad242655002/index.js#L12-L25
56,031
melvincarvalho/rdf-shell
rdf.js
rdf
function rdf(argv, callback) { var command = argv[2]; var exec; if (!command) { console.log('rdf help for command list'); process.exit(-1); } try { exec = require('./bin/' + command + '.js'); } catch (err) { console.error(command + ': command not found'); process.exit(-1); } argv.splice(2, 1); exec(argv, callback); }
javascript
function rdf(argv, callback) { var command = argv[2]; var exec; if (!command) { console.log('rdf help for command list'); process.exit(-1); } try { exec = require('./bin/' + command + '.js'); } catch (err) { console.error(command + ': command not found'); process.exit(-1); } argv.splice(2, 1); exec(argv, callback); }
[ "function", "rdf", "(", "argv", ",", "callback", ")", "{", "var", "command", "=", "argv", "[", "2", "]", ";", "var", "exec", ";", "if", "(", "!", "command", ")", "{", "console", ".", "log", "(", "'rdf help for command list'", ")", ";", "process", ".", "exit", "(", "-", "1", ")", ";", "}", "try", "{", "exec", "=", "require", "(", "'./bin/'", "+", "command", "+", "'.js'", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "error", "(", "command", "+", "': command not found'", ")", ";", "process", ".", "exit", "(", "-", "1", ")", ";", "}", "argv", ".", "splice", "(", "2", ",", "1", ")", ";", "exec", "(", "argv", ",", "callback", ")", ";", "}" ]
rdf calls child script @param {string} argv[2] command @callback {bin~cb} callback
[ "rdf", "calls", "child", "script" ]
bf2015f6f333855e69a18ce3ec9e917bbddfb425
https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/rdf.js#L9-L29
56,032
melvincarvalho/rdf-shell
rdf.js
bin
function bin() { rdf(process.argv, function(err, res) { if (Array.isArray(res)) { for (var i=0; i<res.length; i++) { console.log(res[i]); } } else { console.log(res); } }); }
javascript
function bin() { rdf(process.argv, function(err, res) { if (Array.isArray(res)) { for (var i=0; i<res.length; i++) { console.log(res[i]); } } else { console.log(res); } }); }
[ "function", "bin", "(", ")", "{", "rdf", "(", "process", ".", "argv", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "Array", ".", "isArray", "(", "res", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "res", ".", "length", ";", "i", "++", ")", "{", "console", ".", "log", "(", "res", "[", "i", "]", ")", ";", "}", "}", "else", "{", "console", ".", "log", "(", "res", ")", ";", "}", "}", ")", ";", "}" ]
rdf as a command
[ "rdf", "as", "a", "command" ]
bf2015f6f333855e69a18ce3ec9e917bbddfb425
https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/rdf.js#L35-L45
56,033
mwaylabs/update-manager
update-manager.js
update
function update(options) { var reqOpt = { host: url.parse(options.updateVersionURL).host, uri: url.parse(options.updateVersionURL), path: url.parse(options.updateVersionURL).pathname, port: options.port }; options.error = options.error || function () { }; options.success = options.success || function () { }; doLog = options.log || false; log(doLog); _handleUpdateProcess(reqOpt, options); }
javascript
function update(options) { var reqOpt = { host: url.parse(options.updateVersionURL).host, uri: url.parse(options.updateVersionURL), path: url.parse(options.updateVersionURL).pathname, port: options.port }; options.error = options.error || function () { }; options.success = options.success || function () { }; doLog = options.log || false; log(doLog); _handleUpdateProcess(reqOpt, options); }
[ "function", "update", "(", "options", ")", "{", "var", "reqOpt", "=", "{", "host", ":", "url", ".", "parse", "(", "options", ".", "updateVersionURL", ")", ".", "host", ",", "uri", ":", "url", ".", "parse", "(", "options", ".", "updateVersionURL", ")", ",", "path", ":", "url", ".", "parse", "(", "options", ".", "updateVersionURL", ")", ".", "pathname", ",", "port", ":", "options", ".", "port", "}", ";", "options", ".", "error", "=", "options", ".", "error", "||", "function", "(", ")", "{", "}", ";", "options", ".", "success", "=", "options", ".", "success", "||", "function", "(", ")", "{", "}", ";", "doLog", "=", "options", ".", "log", "||", "false", ";", "log", "(", "doLog", ")", ";", "_handleUpdateProcess", "(", "reqOpt", ",", "options", ")", ";", "}" ]
parses the given URL and passes to handler @param {options} contains URL to the remote version-file
[ "parses", "the", "given", "URL", "and", "passes", "to", "handler" ]
50aac6759f8697c7bd89611df3c8065a8493cdde
https://github.com/mwaylabs/update-manager/blob/50aac6759f8697c7bd89611df3c8065a8493cdde/update-manager.js#L17-L35
56,034
deepjs/deep-restful
lib/collection.js
function(start, end, query) { //console.log("deep.store.Collection.range : ", start, end, query); var res = null; var total = 0; query = query || ""; return deep.when(this.get(query)) .done(function(res) { total = res.length; if (typeof start === 'string') start = parseInt(start); if (typeof end === 'string') end = parseInt(end); start = Math.min(start, total); res = res.slice(start, end + 1); end = start + res.length - 1; query += "&limit(" + (res.length) + "," + start + ")"; return ranger.createRangeObject(start, end, total, res.length, deep.utils.copy(res), query); }); }
javascript
function(start, end, query) { //console.log("deep.store.Collection.range : ", start, end, query); var res = null; var total = 0; query = query || ""; return deep.when(this.get(query)) .done(function(res) { total = res.length; if (typeof start === 'string') start = parseInt(start); if (typeof end === 'string') end = parseInt(end); start = Math.min(start, total); res = res.slice(start, end + 1); end = start + res.length - 1; query += "&limit(" + (res.length) + "," + start + ")"; return ranger.createRangeObject(start, end, total, res.length, deep.utils.copy(res), query); }); }
[ "function", "(", "start", ",", "end", ",", "query", ")", "{", "//console.log(\"deep.store.Collection.range : \", start, end, query);", "var", "res", "=", "null", ";", "var", "total", "=", "0", ";", "query", "=", "query", "||", "\"\"", ";", "return", "deep", ".", "when", "(", "this", ".", "get", "(", "query", ")", ")", ".", "done", "(", "function", "(", "res", ")", "{", "total", "=", "res", ".", "length", ";", "if", "(", "typeof", "start", "===", "'string'", ")", "start", "=", "parseInt", "(", "start", ")", ";", "if", "(", "typeof", "end", "===", "'string'", ")", "end", "=", "parseInt", "(", "end", ")", ";", "start", "=", "Math", ".", "min", "(", "start", ",", "total", ")", ";", "res", "=", "res", ".", "slice", "(", "start", ",", "end", "+", "1", ")", ";", "end", "=", "start", "+", "res", ".", "length", "-", "1", ";", "query", "+=", "\"&limit(\"", "+", "(", "res", ".", "length", ")", "+", "\",\"", "+", "start", "+", "\")\"", ";", "return", "ranger", ".", "createRangeObject", "(", "start", ",", "end", ",", "total", ",", "res", ".", "length", ",", "deep", ".", "utils", ".", "copy", "(", "res", ")", ",", "query", ")", ";", "}", ")", ";", "}" ]
select a range in collection @method range @param {Number} start @param {Number} end @return {deep.NodesChain} a chain that hold the selected range and has injected values as success object.
[ "select", "a", "range", "in", "collection" ]
44c5e1e5526a821522ab5e3004f66ffc7840f551
https://github.com/deepjs/deep-restful/blob/44c5e1e5526a821522ab5e3004f66ffc7840f551/lib/collection.js#L189-L207
56,035
erktime/express-jslint-reporter
reporter.js
function (lintFile) { var deferred = new Deferred(); parseJslintXml(lintFile, function (err, lintErrors) { if (lintErrors) { deferred.resolve(lintErrors); } else { if (err && err.code === 'ENOENT') { console.warn('No jslint xml file found at:', lintFile); } else if (err) { console.log(err); } deferred.reject(); } }); return deferred.promise; }
javascript
function (lintFile) { var deferred = new Deferred(); parseJslintXml(lintFile, function (err, lintErrors) { if (lintErrors) { deferred.resolve(lintErrors); } else { if (err && err.code === 'ENOENT') { console.warn('No jslint xml file found at:', lintFile); } else if (err) { console.log(err); } deferred.reject(); } }); return deferred.promise; }
[ "function", "(", "lintFile", ")", "{", "var", "deferred", "=", "new", "Deferred", "(", ")", ";", "parseJslintXml", "(", "lintFile", ",", "function", "(", "err", ",", "lintErrors", ")", "{", "if", "(", "lintErrors", ")", "{", "deferred", ".", "resolve", "(", "lintErrors", ")", ";", "}", "else", "{", "if", "(", "err", "&&", "err", ".", "code", "===", "'ENOENT'", ")", "{", "console", ".", "warn", "(", "'No jslint xml file found at:'", ",", "lintFile", ")", ";", "}", "else", "if", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", ";", "}", "deferred", ".", "reject", "(", ")", ";", "}", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Get the lint errors from an jslint xml file.o @param {String} lintFile The path of the jslint xml file. @return {Deferred} A promise object. It will resolve only if there are jslint errors found.
[ "Get", "the", "lint", "errors", "from", "an", "jslint", "xml", "file", ".", "o" ]
eaafd8c095655db57ef6bc2a5edbc860cafb1e35
https://github.com/erktime/express-jslint-reporter/blob/eaafd8c095655db57ef6bc2a5edbc860cafb1e35/reporter.js#L41-L58
56,036
erktime/express-jslint-reporter
reporter.js
function (lintFile, callback) { fs.readFile(lintFile, function (err, data) { if (err) { callback(err); } else { var parser = new xml2js.Parser({ mergeAttrs: true }); parser.parseString(data, function (err, result) { if (err) { callback(err); } else if (result && result.jslint) { callback(null, result.jslint.file); } else { callback('Invalid jslint xml file'); } }); } }); }
javascript
function (lintFile, callback) { fs.readFile(lintFile, function (err, data) { if (err) { callback(err); } else { var parser = new xml2js.Parser({ mergeAttrs: true }); parser.parseString(data, function (err, result) { if (err) { callback(err); } else if (result && result.jslint) { callback(null, result.jslint.file); } else { callback('Invalid jslint xml file'); } }); } }); }
[ "function", "(", "lintFile", ",", "callback", ")", "{", "fs", ".", "readFile", "(", "lintFile", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "else", "{", "var", "parser", "=", "new", "xml2js", ".", "Parser", "(", "{", "mergeAttrs", ":", "true", "}", ")", ";", "parser", ".", "parseString", "(", "data", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "else", "if", "(", "result", "&&", "result", ".", "jslint", ")", "{", "callback", "(", "null", ",", "result", ".", "jslint", ".", "file", ")", ";", "}", "else", "{", "callback", "(", "'Invalid jslint xml file'", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}" ]
Parse a jslint xml report. @param {String} lintFile The path of the jslint xml file. @param {Function} callback The function to invoke when the file is read. The callback will be called with the following params: callback(err, lintErrors).
[ "Parse", "a", "jslint", "xml", "report", "." ]
eaafd8c095655db57ef6bc2a5edbc860cafb1e35
https://github.com/erktime/express-jslint-reporter/blob/eaafd8c095655db57ef6bc2a5edbc860cafb1e35/reporter.js#L66-L85
56,037
erktime/express-jslint-reporter
reporter.js
function (req, res, lintErrors) { var html = template({ lintErrors: lintErrors }); res.end(html); }
javascript
function (req, res, lintErrors) { var html = template({ lintErrors: lintErrors }); res.end(html); }
[ "function", "(", "req", ",", "res", ",", "lintErrors", ")", "{", "var", "html", "=", "template", "(", "{", "lintErrors", ":", "lintErrors", "}", ")", ";", "res", ".", "end", "(", "html", ")", ";", "}" ]
Render the error report. @param {Request} req The incoming request. @param {Response} res The outgoing response. @param {Array} lintErrors The jslint errors to render.
[ "Render", "the", "error", "report", "." ]
eaafd8c095655db57ef6bc2a5edbc860cafb1e35
https://github.com/erktime/express-jslint-reporter/blob/eaafd8c095655db57ef6bc2a5edbc860cafb1e35/reporter.js#L93-L98
56,038
RnbWd/parse-browserify
lib/promise.js
function(predicate, asyncFunction) { if (predicate()) { return asyncFunction().then(function() { return Parse.Promise._continueWhile(predicate, asyncFunction); }); } return Parse.Promise.as(); }
javascript
function(predicate, asyncFunction) { if (predicate()) { return asyncFunction().then(function() { return Parse.Promise._continueWhile(predicate, asyncFunction); }); } return Parse.Promise.as(); }
[ "function", "(", "predicate", ",", "asyncFunction", ")", "{", "if", "(", "predicate", "(", ")", ")", "{", "return", "asyncFunction", "(", ")", ".", "then", "(", "function", "(", ")", "{", "return", "Parse", ".", "Promise", ".", "_continueWhile", "(", "predicate", ",", "asyncFunction", ")", ";", "}", ")", ";", "}", "return", "Parse", ".", "Promise", ".", "as", "(", ")", ";", "}" ]
Runs the given asyncFunction repeatedly, as long as the predicate function returns a truthy value. Stops repeating if asyncFunction returns a rejected promise. @param {Function} predicate should return false when ready to stop. @param {Function} asyncFunction should return a Promise.
[ "Runs", "the", "given", "asyncFunction", "repeatedly", "as", "long", "as", "the", "predicate", "function", "returns", "a", "truthy", "value", ".", "Stops", "repeating", "if", "asyncFunction", "returns", "a", "rejected", "promise", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/promise.js#L144-L151
56,039
RnbWd/parse-browserify
lib/promise.js
function(resolvedCallback, rejectedCallback) { var promise = new Parse.Promise(); var wrappedResolvedCallback = function() { var result = arguments; if (resolvedCallback) { result = [resolvedCallback.apply(this, result)]; } if (result.length === 1 && Parse.Promise.is(result[0])) { result[0].then(function() { promise.resolve.apply(promise, arguments); }, function(error) { promise.reject(error); }); } else { promise.resolve.apply(promise, result); } }; var wrappedRejectedCallback = function(error) { var result = []; if (rejectedCallback) { result = [rejectedCallback(error)]; if (result.length === 1 && Parse.Promise.is(result[0])) { result[0].then(function() { promise.resolve.apply(promise, arguments); }, function(error) { promise.reject(error); }); } else { // A Promises/A+ compliant implementation would call: // promise.resolve.apply(promise, result); promise.reject(result[0]); } } else { promise.reject(error); } }; if (this._resolved) { wrappedResolvedCallback.apply(this, this._result); } else if (this._rejected) { wrappedRejectedCallback(this._error); } else { this._resolvedCallbacks.push(wrappedResolvedCallback); this._rejectedCallbacks.push(wrappedRejectedCallback); } return promise; }
javascript
function(resolvedCallback, rejectedCallback) { var promise = new Parse.Promise(); var wrappedResolvedCallback = function() { var result = arguments; if (resolvedCallback) { result = [resolvedCallback.apply(this, result)]; } if (result.length === 1 && Parse.Promise.is(result[0])) { result[0].then(function() { promise.resolve.apply(promise, arguments); }, function(error) { promise.reject(error); }); } else { promise.resolve.apply(promise, result); } }; var wrappedRejectedCallback = function(error) { var result = []; if (rejectedCallback) { result = [rejectedCallback(error)]; if (result.length === 1 && Parse.Promise.is(result[0])) { result[0].then(function() { promise.resolve.apply(promise, arguments); }, function(error) { promise.reject(error); }); } else { // A Promises/A+ compliant implementation would call: // promise.resolve.apply(promise, result); promise.reject(result[0]); } } else { promise.reject(error); } }; if (this._resolved) { wrappedResolvedCallback.apply(this, this._result); } else if (this._rejected) { wrappedRejectedCallback(this._error); } else { this._resolvedCallbacks.push(wrappedResolvedCallback); this._rejectedCallbacks.push(wrappedRejectedCallback); } return promise; }
[ "function", "(", "resolvedCallback", ",", "rejectedCallback", ")", "{", "var", "promise", "=", "new", "Parse", ".", "Promise", "(", ")", ";", "var", "wrappedResolvedCallback", "=", "function", "(", ")", "{", "var", "result", "=", "arguments", ";", "if", "(", "resolvedCallback", ")", "{", "result", "=", "[", "resolvedCallback", ".", "apply", "(", "this", ",", "result", ")", "]", ";", "}", "if", "(", "result", ".", "length", "===", "1", "&&", "Parse", ".", "Promise", ".", "is", "(", "result", "[", "0", "]", ")", ")", "{", "result", "[", "0", "]", ".", "then", "(", "function", "(", ")", "{", "promise", ".", "resolve", ".", "apply", "(", "promise", ",", "arguments", ")", ";", "}", ",", "function", "(", "error", ")", "{", "promise", ".", "reject", "(", "error", ")", ";", "}", ")", ";", "}", "else", "{", "promise", ".", "resolve", ".", "apply", "(", "promise", ",", "result", ")", ";", "}", "}", ";", "var", "wrappedRejectedCallback", "=", "function", "(", "error", ")", "{", "var", "result", "=", "[", "]", ";", "if", "(", "rejectedCallback", ")", "{", "result", "=", "[", "rejectedCallback", "(", "error", ")", "]", ";", "if", "(", "result", ".", "length", "===", "1", "&&", "Parse", ".", "Promise", ".", "is", "(", "result", "[", "0", "]", ")", ")", "{", "result", "[", "0", "]", ".", "then", "(", "function", "(", ")", "{", "promise", ".", "resolve", ".", "apply", "(", "promise", ",", "arguments", ")", ";", "}", ",", "function", "(", "error", ")", "{", "promise", ".", "reject", "(", "error", ")", ";", "}", ")", ";", "}", "else", "{", "// A Promises/A+ compliant implementation would call:", "// promise.resolve.apply(promise, result);", "promise", ".", "reject", "(", "result", "[", "0", "]", ")", ";", "}", "}", "else", "{", "promise", ".", "reject", "(", "error", ")", ";", "}", "}", ";", "if", "(", "this", ".", "_resolved", ")", "{", "wrappedResolvedCallback", ".", "apply", "(", "this", ",", "this", ".", "_result", ")", ";", "}", "else", "if", "(", "this", ".", "_rejected", ")", "{", "wrappedRejectedCallback", "(", "this", ".", "_error", ")", ";", "}", "else", "{", "this", ".", "_resolvedCallbacks", ".", "push", "(", "wrappedResolvedCallback", ")", ";", "this", ".", "_rejectedCallbacks", ".", "push", "(", "wrappedRejectedCallback", ")", ";", "}", "return", "promise", ";", "}" ]
Adds callbacks to be called when this promise is fulfilled. Returns a new Promise that will be fulfilled when the callback is complete. It allows chaining. If the callback itself returns a Promise, then the one returned by "then" will not be fulfilled until that one returned by the callback is fulfilled. @param {Function} resolvedCallback Function that is called when this Promise is resolved. Once the callback is complete, then the Promise returned by "then" will also be fulfilled. @param {Function} rejectedCallback Function that is called when this Promise is rejected with an error. Once the callback is complete, then the promise returned by "then" with be resolved successfully. If rejectedCallback is null, or it returns a rejected Promise, then the Promise returned by "then" will be rejected with that error. @return {Parse.Promise} A new Promise that will be fulfilled after this Promise is fulfilled and either callback has completed. If the callback returned a Promise, then this Promise will not be fulfilled until that one is.
[ "Adds", "callbacks", "to", "be", "called", "when", "this", "promise", "is", "fulfilled", ".", "Returns", "a", "new", "Promise", "that", "will", "be", "fulfilled", "when", "the", "callback", "is", "complete", ".", "It", "allows", "chaining", ".", "If", "the", "callback", "itself", "returns", "a", "Promise", "then", "the", "one", "returned", "by", "then", "will", "not", "be", "fulfilled", "until", "that", "one", "returned", "by", "the", "callback", "is", "fulfilled", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/promise.js#L212-L261
56,040
RnbWd/parse-browserify
lib/promise.js
function(optionsOrCallback, model) { var options; if (_.isFunction(optionsOrCallback)) { var callback = optionsOrCallback; options = { success: function(result) { callback(result, null); }, error: function(error) { callback(null, error); } }; } else { options = _.clone(optionsOrCallback); } options = options || {}; return this.then(function(result) { if (options.success) { options.success.apply(this, arguments); } else if (model) { // When there's no callback, a sync event should be triggered. model.trigger('sync', model, result, options); } return Parse.Promise.as.apply(Parse.Promise, arguments); }, function(error) { if (options.error) { if (!_.isUndefined(model)) { options.error(model, error); } else { options.error(error); } } else if (model) { // When there's no error callback, an error event should be triggered. model.trigger('error', model, error, options); } // By explicitly returning a rejected Promise, this will work with // either jQuery or Promises/A semantics. return Parse.Promise.error(error); }); }
javascript
function(optionsOrCallback, model) { var options; if (_.isFunction(optionsOrCallback)) { var callback = optionsOrCallback; options = { success: function(result) { callback(result, null); }, error: function(error) { callback(null, error); } }; } else { options = _.clone(optionsOrCallback); } options = options || {}; return this.then(function(result) { if (options.success) { options.success.apply(this, arguments); } else if (model) { // When there's no callback, a sync event should be triggered. model.trigger('sync', model, result, options); } return Parse.Promise.as.apply(Parse.Promise, arguments); }, function(error) { if (options.error) { if (!_.isUndefined(model)) { options.error(model, error); } else { options.error(error); } } else if (model) { // When there's no error callback, an error event should be triggered. model.trigger('error', model, error, options); } // By explicitly returning a rejected Promise, this will work with // either jQuery or Promises/A semantics. return Parse.Promise.error(error); }); }
[ "function", "(", "optionsOrCallback", ",", "model", ")", "{", "var", "options", ";", "if", "(", "_", ".", "isFunction", "(", "optionsOrCallback", ")", ")", "{", "var", "callback", "=", "optionsOrCallback", ";", "options", "=", "{", "success", ":", "function", "(", "result", ")", "{", "callback", "(", "result", ",", "null", ")", ";", "}", ",", "error", ":", "function", "(", "error", ")", "{", "callback", "(", "null", ",", "error", ")", ";", "}", "}", ";", "}", "else", "{", "options", "=", "_", ".", "clone", "(", "optionsOrCallback", ")", ";", "}", "options", "=", "options", "||", "{", "}", ";", "return", "this", ".", "then", "(", "function", "(", "result", ")", "{", "if", "(", "options", ".", "success", ")", "{", "options", ".", "success", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "else", "if", "(", "model", ")", "{", "// When there's no callback, a sync event should be triggered.", "model", ".", "trigger", "(", "'sync'", ",", "model", ",", "result", ",", "options", ")", ";", "}", "return", "Parse", ".", "Promise", ".", "as", ".", "apply", "(", "Parse", ".", "Promise", ",", "arguments", ")", ";", "}", ",", "function", "(", "error", ")", "{", "if", "(", "options", ".", "error", ")", "{", "if", "(", "!", "_", ".", "isUndefined", "(", "model", ")", ")", "{", "options", ".", "error", "(", "model", ",", "error", ")", ";", "}", "else", "{", "options", ".", "error", "(", "error", ")", ";", "}", "}", "else", "if", "(", "model", ")", "{", "// When there's no error callback, an error event should be triggered.", "model", ".", "trigger", "(", "'error'", ",", "model", ",", "error", ",", "options", ")", ";", "}", "// By explicitly returning a rejected Promise, this will work with", "// either jQuery or Promises/A semantics.", "return", "Parse", ".", "Promise", ".", "error", "(", "error", ")", ";", "}", ")", ";", "}" ]
Run the given callbacks after this promise is fulfilled. @param optionsOrCallback {} A Backbone-style options callback, or a callback function. If this is an options object and contains a "model" attributes, that will be passed to error callbacks as the first argument. @param model {} If truthy, this will be passed as the first result of error callbacks. This is for Backbone-compatability. @return {Parse.Promise} A promise that will be resolved after the callbacks are run, with the same result as this.
[ "Run", "the", "given", "callbacks", "after", "this", "promise", "is", "fulfilled", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/promise.js#L295-L335
56,041
mercmobily/simpledblayer-tingo
TingoMixin.js
function( s ){ if( s.match(/\./ ) ){ var l = s.split( /\./ ); for( var i = 0; i < l.length-1; i++ ){ l[ i ] = '_children.' + l[ i ]; } return l.join( '.' ); } else { return s; } }
javascript
function( s ){ if( s.match(/\./ ) ){ var l = s.split( /\./ ); for( var i = 0; i < l.length-1; i++ ){ l[ i ] = '_children.' + l[ i ]; } return l.join( '.' ); } else { return s; } }
[ "function", "(", "s", ")", "{", "if", "(", "s", ".", "match", "(", "/", "\\.", "/", ")", ")", "{", "var", "l", "=", "s", ".", "split", "(", "/", "\\.", "/", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "l", ".", "length", "-", "1", ";", "i", "++", ")", "{", "l", "[", "i", "]", "=", "'_children.'", "+", "l", "[", "i", "]", ";", "}", "return", "l", ".", "join", "(", "'.'", ")", ";", "}", "else", "{", "return", "s", ";", "}", "}" ]
If there are ".", then some children records are being referenced. The actual way they are placed in the record is in _children; so, add _children where needed.
[ "If", "there", "are", ".", "then", "some", "children", "records", "are", "being", "referenced", ".", "The", "actual", "way", "they", "are", "placed", "in", "the", "record", "is", "in", "_children", ";", "so", "add", "_children", "where", "needed", "." ]
1cd5ac89b0825343b6045ddd40ef45f138a86b0a
https://github.com/mercmobily/simpledblayer-tingo/blob/1cd5ac89b0825343b6045ddd40ef45f138a86b0a/TingoMixin.js#L97-L110
56,042
mercmobily/simpledblayer-tingo
TingoMixin.js
function( filters, fieldPrefix, selectorWithoutBells ){ return { querySelector: this._makeMongoConditions( filters.conditions || {}, fieldPrefix, selectorWithoutBells ), sortHash: this._makeMongoSortHash( filters.sort || {}, fieldPrefix ) }; }
javascript
function( filters, fieldPrefix, selectorWithoutBells ){ return { querySelector: this._makeMongoConditions( filters.conditions || {}, fieldPrefix, selectorWithoutBells ), sortHash: this._makeMongoSortHash( filters.sort || {}, fieldPrefix ) }; }
[ "function", "(", "filters", ",", "fieldPrefix", ",", "selectorWithoutBells", ")", "{", "return", "{", "querySelector", ":", "this", ".", "_makeMongoConditions", "(", "filters", ".", "conditions", "||", "{", "}", ",", "fieldPrefix", ",", "selectorWithoutBells", ")", ",", "sortHash", ":", "this", ".", "_makeMongoSortHash", "(", "filters", ".", "sort", "||", "{", "}", ",", "fieldPrefix", ")", "}", ";", "}" ]
Make parameters for queries. It's the equivalent of what would be an SQL creator for a SQL layer
[ "Make", "parameters", "for", "queries", ".", "It", "s", "the", "equivalent", "of", "what", "would", "be", "an", "SQL", "creator", "for", "a", "SQL", "layer" ]
1cd5ac89b0825343b6045ddd40ef45f138a86b0a
https://github.com/mercmobily/simpledblayer-tingo/blob/1cd5ac89b0825343b6045ddd40ef45f138a86b0a/TingoMixin.js#L158-L163
56,043
mercmobily/simpledblayer-tingo
TingoMixin.js
function( cb ){ if( ! self.positionField ){ cb( null ); } else { // If repositioning is required, do it if( self.positionField ){ var where, beforeId; if( ! options.position ){ where = 'end'; } else { where = options.position.where; beforeId = options.position.beforeId; } self.reposition( recordWithLookups, where, beforeId, cb ); } } }
javascript
function( cb ){ if( ! self.positionField ){ cb( null ); } else { // If repositioning is required, do it if( self.positionField ){ var where, beforeId; if( ! options.position ){ where = 'end'; } else { where = options.position.where; beforeId = options.position.beforeId; } self.reposition( recordWithLookups, where, beforeId, cb ); } } }
[ "function", "(", "cb", ")", "{", "if", "(", "!", "self", ".", "positionField", ")", "{", "cb", "(", "null", ")", ";", "}", "else", "{", "// If repositioning is required, do it", "if", "(", "self", ".", "positionField", ")", "{", "var", "where", ",", "beforeId", ";", "if", "(", "!", "options", ".", "position", ")", "{", "where", "=", "'end'", ";", "}", "else", "{", "where", "=", "options", ".", "position", ".", "where", ";", "beforeId", "=", "options", ".", "position", ".", "beforeId", ";", "}", "self", ".", "reposition", "(", "recordWithLookups", ",", "where", ",", "beforeId", ",", "cb", ")", ";", "}", "}", "}" ]
This will get called shortly. Bypasses straight to callback or calls reposition with right parameters and then calls callback
[ "This", "will", "get", "called", "shortly", ".", "Bypasses", "straight", "to", "callback", "or", "calls", "reposition", "with", "right", "parameters", "and", "then", "calls", "callback" ]
1cd5ac89b0825343b6045ddd40ef45f138a86b0a
https://github.com/mercmobily/simpledblayer-tingo/blob/1cd5ac89b0825343b6045ddd40ef45f138a86b0a/TingoMixin.js#L904-L921
56,044
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/button/plugin.js
function( state ) { if ( this._.state == state ) return false; this._.state = state; var element = CKEDITOR.document.getById( this._.id ); if ( element ) { element.setState( state, 'cke_button' ); state == CKEDITOR.TRISTATE_DISABLED ? element.setAttribute( 'aria-disabled', true ) : element.removeAttribute( 'aria-disabled' ); if ( !this.hasArrow ) { // Note: aria-pressed attribute should not be added to menuButton instances. (#11331) state == CKEDITOR.TRISTATE_ON ? element.setAttribute( 'aria-pressed', true ) : element.removeAttribute( 'aria-pressed' ); } else { var newLabel = state == CKEDITOR.TRISTATE_ON ? this._.editor.lang.button.selectedLabel.replace( /%1/g, this.label ) : this.label; CKEDITOR.document.getById( this._.id + '_label' ).setText( newLabel ); } return true; } else return false; }
javascript
function( state ) { if ( this._.state == state ) return false; this._.state = state; var element = CKEDITOR.document.getById( this._.id ); if ( element ) { element.setState( state, 'cke_button' ); state == CKEDITOR.TRISTATE_DISABLED ? element.setAttribute( 'aria-disabled', true ) : element.removeAttribute( 'aria-disabled' ); if ( !this.hasArrow ) { // Note: aria-pressed attribute should not be added to menuButton instances. (#11331) state == CKEDITOR.TRISTATE_ON ? element.setAttribute( 'aria-pressed', true ) : element.removeAttribute( 'aria-pressed' ); } else { var newLabel = state == CKEDITOR.TRISTATE_ON ? this._.editor.lang.button.selectedLabel.replace( /%1/g, this.label ) : this.label; CKEDITOR.document.getById( this._.id + '_label' ).setText( newLabel ); } return true; } else return false; }
[ "function", "(", "state", ")", "{", "if", "(", "this", ".", "_", ".", "state", "==", "state", ")", "return", "false", ";", "this", ".", "_", ".", "state", "=", "state", ";", "var", "element", "=", "CKEDITOR", ".", "document", ".", "getById", "(", "this", ".", "_", ".", "id", ")", ";", "if", "(", "element", ")", "{", "element", ".", "setState", "(", "state", ",", "'cke_button'", ")", ";", "state", "==", "CKEDITOR", ".", "TRISTATE_DISABLED", "?", "element", ".", "setAttribute", "(", "'aria-disabled'", ",", "true", ")", ":", "element", ".", "removeAttribute", "(", "'aria-disabled'", ")", ";", "if", "(", "!", "this", ".", "hasArrow", ")", "{", "// Note: aria-pressed attribute should not be added to menuButton instances. (#11331)\r", "state", "==", "CKEDITOR", ".", "TRISTATE_ON", "?", "element", ".", "setAttribute", "(", "'aria-pressed'", ",", "true", ")", ":", "element", ".", "removeAttribute", "(", "'aria-pressed'", ")", ";", "}", "else", "{", "var", "newLabel", "=", "state", "==", "CKEDITOR", ".", "TRISTATE_ON", "?", "this", ".", "_", ".", "editor", ".", "lang", ".", "button", ".", "selectedLabel", ".", "replace", "(", "/", "%1", "/", "g", ",", "this", ".", "label", ")", ":", "this", ".", "label", ";", "CKEDITOR", ".", "document", ".", "getById", "(", "this", ".", "_", ".", "id", "+", "'_label'", ")", ".", "setText", "(", "newLabel", ")", ";", "}", "return", "true", ";", "}", "else", "return", "false", ";", "}" ]
Sets the button state. @param {Number} state Indicates the button state. One of {@link CKEDITOR#TRISTATE_ON}, {@link CKEDITOR#TRISTATE_OFF}, or {@link CKEDITOR#TRISTATE_DISABLED}.
[ "Sets", "the", "button", "state", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/button/plugin.js#L287-L316
56,045
nodys/htmly
lib/transform.js
rPath
function rPath (htmlyFile, sourceFilepath) { htmlyFile = pathResolve(__dirname, htmlyFile) htmlyFile = pathRelative(dirname(sourceFilepath), htmlyFile) htmlyFile = slash(htmlyFile) if (!/^(\.|\/)/.test(htmlyFile)) { return './' + htmlyFile } else { return htmlyFile } }
javascript
function rPath (htmlyFile, sourceFilepath) { htmlyFile = pathResolve(__dirname, htmlyFile) htmlyFile = pathRelative(dirname(sourceFilepath), htmlyFile) htmlyFile = slash(htmlyFile) if (!/^(\.|\/)/.test(htmlyFile)) { return './' + htmlyFile } else { return htmlyFile } }
[ "function", "rPath", "(", "htmlyFile", ",", "sourceFilepath", ")", "{", "htmlyFile", "=", "pathResolve", "(", "__dirname", ",", "htmlyFile", ")", "htmlyFile", "=", "pathRelative", "(", "dirname", "(", "sourceFilepath", ")", ",", "htmlyFile", ")", "htmlyFile", "=", "slash", "(", "htmlyFile", ")", "if", "(", "!", "/", "^(\\.|\\/)", "/", ".", "test", "(", "htmlyFile", ")", ")", "{", "return", "'./'", "+", "htmlyFile", "}", "else", "{", "return", "htmlyFile", "}", "}" ]
Generate a relative path to a htmly file, relative to source file @param {string} htmlyFile Path relative to current module @param {string} sourceFilepath The source filepath @return {string} A relative path to htmlyFile from a transformed source
[ "Generate", "a", "relative", "path", "to", "a", "htmly", "file", "relative", "to", "source", "file" ]
770560274167b7efd78cf56544ec72f52efb3fb8
https://github.com/nodys/htmly/blob/770560274167b7efd78cf56544ec72f52efb3fb8/lib/transform.js#L72-L81
56,046
hillscottc/nostra
src/word_library.js
warning
function warning() { let sentence = ""; const avoidList = getWords("avoid_list"); const avoid = nu.chooseFrom(avoidList); const rnum = Math.floor(Math.random() * 10); if (rnum <= 3) { sentence = `You would be well advised to avoid ${avoid}`; } else if (rnum <= 6){ sentence = `Avoid ${avoid} at all costs`; } else if (rnum <= 8) { sentence = `Steer clear of ${avoid} for a stress-free week`; } else { sentence = `For a peaceful week, avoid ${avoid}`; } return nu.sentenceCase(sentence); }
javascript
function warning() { let sentence = ""; const avoidList = getWords("avoid_list"); const avoid = nu.chooseFrom(avoidList); const rnum = Math.floor(Math.random() * 10); if (rnum <= 3) { sentence = `You would be well advised to avoid ${avoid}`; } else if (rnum <= 6){ sentence = `Avoid ${avoid} at all costs`; } else if (rnum <= 8) { sentence = `Steer clear of ${avoid} for a stress-free week`; } else { sentence = `For a peaceful week, avoid ${avoid}`; } return nu.sentenceCase(sentence); }
[ "function", "warning", "(", ")", "{", "let", "sentence", "=", "\"\"", ";", "const", "avoidList", "=", "getWords", "(", "\"avoid_list\"", ")", ";", "const", "avoid", "=", "nu", ".", "chooseFrom", "(", "avoidList", ")", ";", "const", "rnum", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "10", ")", ";", "if", "(", "rnum", "<=", "3", ")", "{", "sentence", "=", "`", "${", "avoid", "}", "`", ";", "}", "else", "if", "(", "rnum", "<=", "6", ")", "{", "sentence", "=", "`", "${", "avoid", "}", "`", ";", "}", "else", "if", "(", "rnum", "<=", "8", ")", "{", "sentence", "=", "`", "${", "avoid", "}", "`", ";", "}", "else", "{", "sentence", "=", "`", "${", "avoid", "}", "`", ";", "}", "return", "nu", ".", "sentenceCase", "(", "sentence", ")", ";", "}" ]
Warns of what to avoid @returns {*}
[ "Warns", "of", "what", "to", "avoid" ]
1801c8e19f7fab91dd29fea07195789d41624915
https://github.com/hillscottc/nostra/blob/1801c8e19f7fab91dd29fea07195789d41624915/src/word_library.js#L209-L224
56,047
ottopecz/talentcomposer
lib/util.js
getIterableObjectEntries
function getIterableObjectEntries(obj) { let index = 0; const propKeys = Reflect.ownKeys(obj); return { [Symbol.iterator]() { return this; }, next() { if (index < propKeys.length) { const key = propKeys[index]; index += 1; return {"value": [key, obj[key]]}; } return {"done": true}; } }; }
javascript
function getIterableObjectEntries(obj) { let index = 0; const propKeys = Reflect.ownKeys(obj); return { [Symbol.iterator]() { return this; }, next() { if (index < propKeys.length) { const key = propKeys[index]; index += 1; return {"value": [key, obj[key]]}; } return {"done": true}; } }; }
[ "function", "getIterableObjectEntries", "(", "obj", ")", "{", "let", "index", "=", "0", ";", "const", "propKeys", "=", "Reflect", ".", "ownKeys", "(", "obj", ")", ";", "return", "{", "[", "Symbol", ".", "iterator", "]", "(", ")", "{", "return", "this", ";", "}", ",", "next", "(", ")", "{", "if", "(", "index", "<", "propKeys", ".", "length", ")", "{", "const", "key", "=", "propKeys", "[", "index", "]", ";", "index", "+=", "1", ";", "return", "{", "\"value\"", ":", "[", "key", ",", "obj", "[", "key", "]", "]", "}", ";", "}", "return", "{", "\"done\"", ":", "true", "}", ";", "}", "}", ";", "}" ]
Creates an iterable based on an object literal @param {Object} obj The source object which own keys should be iterable @returns {Object} The iterable with the own keys
[ "Creates", "an", "iterable", "based", "on", "an", "object", "literal" ]
440c73248ccb6538c7805ada6a8feb5b3ae4a973
https://github.com/ottopecz/talentcomposer/blob/440c73248ccb6538c7805ada6a8feb5b3ae4a973/lib/util.js#L6-L28
56,048
ottopecz/talentcomposer
lib/util.js
findWhere
function findWhere(arr, key, value) { return arr.find(elem => { for (const [k, v] of getIterableObjectEntries(elem)) { if (k === key && v === value) { return true; } } }); }
javascript
function findWhere(arr, key, value) { return arr.find(elem => { for (const [k, v] of getIterableObjectEntries(elem)) { if (k === key && v === value) { return true; } } }); }
[ "function", "findWhere", "(", "arr", ",", "key", ",", "value", ")", "{", "return", "arr", ".", "find", "(", "elem", "=>", "{", "for", "(", "const", "[", "k", ",", "v", "]", "of", "getIterableObjectEntries", "(", "elem", ")", ")", "{", "if", "(", "k", "===", "key", "&&", "v", "===", "value", ")", "{", "return", "true", ";", "}", "}", "}", ")", ";", "}" ]
Returns the object where the given own key exists and equal with value @param {Array.<Object>} arr The source array of objects @param {string} key The name of the own key to filter with @param {*} value The value of the key to filter with @returns {Object} The found object specified by the key value pair
[ "Returns", "the", "object", "where", "the", "given", "own", "key", "exists", "and", "equal", "with", "value" ]
440c73248ccb6538c7805ada6a8feb5b3ae4a973
https://github.com/ottopecz/talentcomposer/blob/440c73248ccb6538c7805ada6a8feb5b3ae4a973/lib/util.js#L37-L48
56,049
ottopecz/talentcomposer
lib/util.js
findWhereKey
function findWhereKey(arr, key) { return arr.find(elem => { for (const [k] of getIterableObjectEntries(elem)) { if (k === key) { return true; } } }); }
javascript
function findWhereKey(arr, key) { return arr.find(elem => { for (const [k] of getIterableObjectEntries(elem)) { if (k === key) { return true; } } }); }
[ "function", "findWhereKey", "(", "arr", ",", "key", ")", "{", "return", "arr", ".", "find", "(", "elem", "=>", "{", "for", "(", "const", "[", "k", "]", "of", "getIterableObjectEntries", "(", "elem", ")", ")", "{", "if", "(", "k", "===", "key", ")", "{", "return", "true", ";", "}", "}", "}", ")", ";", "}" ]
Returns the object where the given own key exists @param {Array.<Object>} arr The source array of objects @param {string} key The name of the own key to filter with @returns {Object} The found object specified by the name of the given own key
[ "Returns", "the", "object", "where", "the", "given", "own", "key", "exists" ]
440c73248ccb6538c7805ada6a8feb5b3ae4a973
https://github.com/ottopecz/talentcomposer/blob/440c73248ccb6538c7805ada6a8feb5b3ae4a973/lib/util.js#L56-L67
56,050
bmustiata/promised-node
lib/promised-node.js
load
function load(module) { var toTransform, transformedModule = {}; if (typeof module === "string") { toTransform = require(module); } else { toTransform = module; } for (var item in toTransform) { // transform only sync/async methods to promiseable since having utility methods also promiseable // could do more harm than good. if (typeof toTransform[item] === "function" && isFunctionPromiseable( toTransform, item, toTransform[item] )) { transformedModule[item] = rebuildAsPromise( toTransform, item, toTransform[item] ); } else { transformedModule[item] = toTransform[item]; } } return transformedModule; }
javascript
function load(module) { var toTransform, transformedModule = {}; if (typeof module === "string") { toTransform = require(module); } else { toTransform = module; } for (var item in toTransform) { // transform only sync/async methods to promiseable since having utility methods also promiseable // could do more harm than good. if (typeof toTransform[item] === "function" && isFunctionPromiseable( toTransform, item, toTransform[item] )) { transformedModule[item] = rebuildAsPromise( toTransform, item, toTransform[item] ); } else { transformedModule[item] = toTransform[item]; } } return transformedModule; }
[ "function", "load", "(", "module", ")", "{", "var", "toTransform", ",", "transformedModule", "=", "{", "}", ";", "if", "(", "typeof", "module", "===", "\"string\"", ")", "{", "toTransform", "=", "require", "(", "module", ")", ";", "}", "else", "{", "toTransform", "=", "module", ";", "}", "for", "(", "var", "item", "in", "toTransform", ")", "{", "// transform only sync/async methods to promiseable since having utility methods also promiseable", "// could do more harm than good.", "if", "(", "typeof", "toTransform", "[", "item", "]", "===", "\"function\"", "&&", "isFunctionPromiseable", "(", "toTransform", ",", "item", ",", "toTransform", "[", "item", "]", ")", ")", "{", "transformedModule", "[", "item", "]", "=", "rebuildAsPromise", "(", "toTransform", ",", "item", ",", "toTransform", "[", "item", "]", ")", ";", "}", "else", "{", "transformedModule", "[", "item", "]", "=", "toTransform", "[", "item", "]", ";", "}", "}", "return", "transformedModule", ";", "}" ]
Load a module transforming all the async methods that have callbacks into promises enabled functions. @param {string|object} module The module name, or the object to transform its functions. @return {object} Loaded module with methods transformed.
[ "Load", "a", "module", "transforming", "all", "the", "async", "methods", "that", "have", "callbacks", "into", "promises", "enabled", "functions", "." ]
0f39c6dc5a06a3d347053a99b5311836df8258fb
https://github.com/bmustiata/promised-node/blob/0f39c6dc5a06a3d347053a99b5311836df8258fb/lib/promised-node.js#L9-L30
56,051
bmustiata/promised-node
lib/promised-node.js
rebuildAsPromise
function rebuildAsPromise(_thisObject, name, fn) { // if is a regular function, that has an async correspondent also make it promiseable if (!isFunctionAsync(_thisObject, name, fn)) { return function() { var that = this, args = arguments; return blinkts.lang.promiseCode(function() { return fn.apply(that, args); }); }; } // if it's an async function, make it promiseable. return function() { var args = Array.prototype.slice.apply(arguments), that = this; return new blinkts.lang.Promise(function(fulfill, reject) { args.push(function(err, r) { if (err) { reject(err); } if (arguments.length > 2) { // if the callback received multiple arguments, put them into an array. fulfill(Array.prototype.slice.call(arguments, 1)); } else { fulfill(r); } }); try { var result = fn.apply(that, args); } catch (e) { // if the function failed, so we don't get a chance to get our callback called. reject(e); } }); }; }
javascript
function rebuildAsPromise(_thisObject, name, fn) { // if is a regular function, that has an async correspondent also make it promiseable if (!isFunctionAsync(_thisObject, name, fn)) { return function() { var that = this, args = arguments; return blinkts.lang.promiseCode(function() { return fn.apply(that, args); }); }; } // if it's an async function, make it promiseable. return function() { var args = Array.prototype.slice.apply(arguments), that = this; return new blinkts.lang.Promise(function(fulfill, reject) { args.push(function(err, r) { if (err) { reject(err); } if (arguments.length > 2) { // if the callback received multiple arguments, put them into an array. fulfill(Array.prototype.slice.call(arguments, 1)); } else { fulfill(r); } }); try { var result = fn.apply(that, args); } catch (e) { // if the function failed, so we don't get a chance to get our callback called. reject(e); } }); }; }
[ "function", "rebuildAsPromise", "(", "_thisObject", ",", "name", ",", "fn", ")", "{", "// if is a regular function, that has an async correspondent also make it promiseable", "if", "(", "!", "isFunctionAsync", "(", "_thisObject", ",", "name", ",", "fn", ")", ")", "{", "return", "function", "(", ")", "{", "var", "that", "=", "this", ",", "args", "=", "arguments", ";", "return", "blinkts", ".", "lang", ".", "promiseCode", "(", "function", "(", ")", "{", "return", "fn", ".", "apply", "(", "that", ",", "args", ")", ";", "}", ")", ";", "}", ";", "}", "// if it's an async function, make it promiseable.", "return", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "apply", "(", "arguments", ")", ",", "that", "=", "this", ";", "return", "new", "blinkts", ".", "lang", ".", "Promise", "(", "function", "(", "fulfill", ",", "reject", ")", "{", "args", ".", "push", "(", "function", "(", "err", ",", "r", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "if", "(", "arguments", ".", "length", ">", "2", ")", "{", "// if the callback received multiple arguments, put them into an array.", "fulfill", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "}", "else", "{", "fulfill", "(", "r", ")", ";", "}", "}", ")", ";", "try", "{", "var", "result", "=", "fn", ".", "apply", "(", "that", ",", "args", ")", ";", "}", "catch", "(", "e", ")", "{", "// if the function failed, so we don't get a chance to get our callback called.", "reject", "(", "e", ")", ";", "}", "}", ")", ";", "}", ";", "}" ]
Takes the current function and wraps it around a promise.
[ "Takes", "the", "current", "function", "and", "wraps", "it", "around", "a", "promise", "." ]
0f39c6dc5a06a3d347053a99b5311836df8258fb
https://github.com/bmustiata/promised-node/blob/0f39c6dc5a06a3d347053a99b5311836df8258fb/lib/promised-node.js#L54-L92
56,052
clusterpoint/nodejs-client-api
lib/reply.js
function(err, res) { if (err) return callback(err); self._rawResponse = res; if (!res || !res['cps:reply']) return callback(new Error("Invalid reply")); self.seconds = res['cps:reply']['cps:seconds']; if (res['cps:reply']['cps:content']) { var content = res['cps:reply']['cps:content']; self = _.merge(self, content); } callback(res['cps:reply']['cps:error'], self); }
javascript
function(err, res) { if (err) return callback(err); self._rawResponse = res; if (!res || !res['cps:reply']) return callback(new Error("Invalid reply")); self.seconds = res['cps:reply']['cps:seconds']; if (res['cps:reply']['cps:content']) { var content = res['cps:reply']['cps:content']; self = _.merge(self, content); } callback(res['cps:reply']['cps:error'], self); }
[ "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "self", ".", "_rawResponse", "=", "res", ";", "if", "(", "!", "res", "||", "!", "res", "[", "'cps:reply'", "]", ")", "return", "callback", "(", "new", "Error", "(", "\"Invalid reply\"", ")", ")", ";", "self", ".", "seconds", "=", "res", "[", "'cps:reply'", "]", "[", "'cps:seconds'", "]", ";", "if", "(", "res", "[", "'cps:reply'", "]", "[", "'cps:content'", "]", ")", "{", "var", "content", "=", "res", "[", "'cps:reply'", "]", "[", "'cps:content'", "]", ";", "self", "=", "_", ".", "merge", "(", "self", ",", "content", ")", ";", "}", "callback", "(", "res", "[", "'cps:reply'", "]", "[", "'cps:error'", "]", ",", "self", ")", ";", "}" ]
Merges response content into objects variables, so it can be easily accessible
[ "Merges", "response", "content", "into", "objects", "variables", "so", "it", "can", "be", "easily", "accessible" ]
ca9322eab3d11f7cc43ce0e6f6e2403f5b3712a0
https://github.com/clusterpoint/nodejs-client-api/blob/ca9322eab3d11f7cc43ce0e6f6e2403f5b3712a0/lib/reply.js#L20-L31
56,053
byu-oit/fully-typed
bin/number.js
TypedNumber
function TypedNumber (config) { const number = this; // validate min if (config.hasOwnProperty('min') && !util.isNumber(config.min)) { const message = util.propertyErrorMessage('min', config.min, 'Must be a number.'); throw Error(message); } // validate max if (config.hasOwnProperty('max') && !util.isNumber(config.max)) { const message = util.propertyErrorMessage('max', config.max, 'Must be a number.'); throw Error(message); } // validate max is greater than min if (config.hasOwnProperty('max') && config.hasOwnProperty('min') && config.min > config.max) { const message = util.propertyErrorMessage('max', config.max, 'Must be a number that is less than the minimum: ' + config.min + '.'); throw Error(message); } // define properties Object.defineProperties(number, { exclusiveMax: { /** * @property * @name TypedNumber#exclusiveMax * @type {boolean} */ value: !!config.exclusiveMax, writable: false }, exclusiveMin: { /** * @property * @name TypedNumber#exclusiveMin * @type {boolean} */ value: !!config.exclusiveMin, writable: false }, integer: { /** * @property * @name TypedNumber#integer * @type {boolean} */ value: !!config.integer, writable: false }, max: { /** * @property * @name TypedNumber#max * @type {number} */ value: Number(config.max), writable: false }, min: { /** * @property * @name TypedNumber#min * @type {number} */ value: Number(config.min), writable: false } }); return number; }
javascript
function TypedNumber (config) { const number = this; // validate min if (config.hasOwnProperty('min') && !util.isNumber(config.min)) { const message = util.propertyErrorMessage('min', config.min, 'Must be a number.'); throw Error(message); } // validate max if (config.hasOwnProperty('max') && !util.isNumber(config.max)) { const message = util.propertyErrorMessage('max', config.max, 'Must be a number.'); throw Error(message); } // validate max is greater than min if (config.hasOwnProperty('max') && config.hasOwnProperty('min') && config.min > config.max) { const message = util.propertyErrorMessage('max', config.max, 'Must be a number that is less than the minimum: ' + config.min + '.'); throw Error(message); } // define properties Object.defineProperties(number, { exclusiveMax: { /** * @property * @name TypedNumber#exclusiveMax * @type {boolean} */ value: !!config.exclusiveMax, writable: false }, exclusiveMin: { /** * @property * @name TypedNumber#exclusiveMin * @type {boolean} */ value: !!config.exclusiveMin, writable: false }, integer: { /** * @property * @name TypedNumber#integer * @type {boolean} */ value: !!config.integer, writable: false }, max: { /** * @property * @name TypedNumber#max * @type {number} */ value: Number(config.max), writable: false }, min: { /** * @property * @name TypedNumber#min * @type {number} */ value: Number(config.min), writable: false } }); return number; }
[ "function", "TypedNumber", "(", "config", ")", "{", "const", "number", "=", "this", ";", "// validate min", "if", "(", "config", ".", "hasOwnProperty", "(", "'min'", ")", "&&", "!", "util", ".", "isNumber", "(", "config", ".", "min", ")", ")", "{", "const", "message", "=", "util", ".", "propertyErrorMessage", "(", "'min'", ",", "config", ".", "min", ",", "'Must be a number.'", ")", ";", "throw", "Error", "(", "message", ")", ";", "}", "// validate max", "if", "(", "config", ".", "hasOwnProperty", "(", "'max'", ")", "&&", "!", "util", ".", "isNumber", "(", "config", ".", "max", ")", ")", "{", "const", "message", "=", "util", ".", "propertyErrorMessage", "(", "'max'", ",", "config", ".", "max", ",", "'Must be a number.'", ")", ";", "throw", "Error", "(", "message", ")", ";", "}", "// validate max is greater than min", "if", "(", "config", ".", "hasOwnProperty", "(", "'max'", ")", "&&", "config", ".", "hasOwnProperty", "(", "'min'", ")", "&&", "config", ".", "min", ">", "config", ".", "max", ")", "{", "const", "message", "=", "util", ".", "propertyErrorMessage", "(", "'max'", ",", "config", ".", "max", ",", "'Must be a number that is less than the minimum: '", "+", "config", ".", "min", "+", "'.'", ")", ";", "throw", "Error", "(", "message", ")", ";", "}", "// define properties", "Object", ".", "defineProperties", "(", "number", ",", "{", "exclusiveMax", ":", "{", "/**\n * @property\n * @name TypedNumber#exclusiveMax\n * @type {boolean}\n */", "value", ":", "!", "!", "config", ".", "exclusiveMax", ",", "writable", ":", "false", "}", ",", "exclusiveMin", ":", "{", "/**\n * @property\n * @name TypedNumber#exclusiveMin\n * @type {boolean}\n */", "value", ":", "!", "!", "config", ".", "exclusiveMin", ",", "writable", ":", "false", "}", ",", "integer", ":", "{", "/**\n * @property\n * @name TypedNumber#integer\n * @type {boolean}\n */", "value", ":", "!", "!", "config", ".", "integer", ",", "writable", ":", "false", "}", ",", "max", ":", "{", "/**\n * @property\n * @name TypedNumber#max\n * @type {number}\n */", "value", ":", "Number", "(", "config", ".", "max", ")", ",", "writable", ":", "false", "}", ",", "min", ":", "{", "/**\n * @property\n * @name TypedNumber#min\n * @type {number}\n */", "value", ":", "Number", "(", "config", ".", "min", ")", ",", "writable", ":", "false", "}", "}", ")", ";", "return", "number", ";", "}" ]
Create a TypedNumber instance. @param {object} config @returns {TypedNumber} @augments Typed @constructor
[ "Create", "a", "TypedNumber", "instance", "." ]
ed6b3ed88ffc72990acffb765232eaaee261afef
https://github.com/byu-oit/fully-typed/blob/ed6b3ed88ffc72990acffb765232eaaee261afef/bin/number.js#L29-L106
56,054
soajs/grunt-soajs
lib/swagger/swagger.js
recursiveMapping
function recursiveMapping(source) { if (source.type === 'array') { if (source.items['$ref'] || source.items.type === 'object') { source.items = mapSimpleField(source.items); } else if (source.items.type === 'object') { recursiveMapping(source.items); } else mapSimpleField(source); } else if (source.type === 'object') { for (var property in source.properties) { if (source.properties[property]['$ref']) { source.properties[property] = mapSimpleField(source.properties[property]); } else if (source.properties[property].type === 'object' || source.properties[property].type === 'array') { recursiveMapping(source.properties[property]); } } } else if (source.schema) { if (source.schema.type === 'object') { for (var property in source.schema.properties) { if (source.schema.properties[property]['$ref']) { source.schema.properties[property] = mapSimpleField(source.schema.properties[property]); } } } } else { //map simple inputs if any source = mapSimpleField(source); } }
javascript
function recursiveMapping(source) { if (source.type === 'array') { if (source.items['$ref'] || source.items.type === 'object') { source.items = mapSimpleField(source.items); } else if (source.items.type === 'object') { recursiveMapping(source.items); } else mapSimpleField(source); } else if (source.type === 'object') { for (var property in source.properties) { if (source.properties[property]['$ref']) { source.properties[property] = mapSimpleField(source.properties[property]); } else if (source.properties[property].type === 'object' || source.properties[property].type === 'array') { recursiveMapping(source.properties[property]); } } } else if (source.schema) { if (source.schema.type === 'object') { for (var property in source.schema.properties) { if (source.schema.properties[property]['$ref']) { source.schema.properties[property] = mapSimpleField(source.schema.properties[property]); } } } } else { //map simple inputs if any source = mapSimpleField(source); } }
[ "function", "recursiveMapping", "(", "source", ")", "{", "if", "(", "source", ".", "type", "===", "'array'", ")", "{", "if", "(", "source", ".", "items", "[", "'$ref'", "]", "||", "source", ".", "items", ".", "type", "===", "'object'", ")", "{", "source", ".", "items", "=", "mapSimpleField", "(", "source", ".", "items", ")", ";", "}", "else", "if", "(", "source", ".", "items", ".", "type", "===", "'object'", ")", "{", "recursiveMapping", "(", "source", ".", "items", ")", ";", "}", "else", "mapSimpleField", "(", "source", ")", ";", "}", "else", "if", "(", "source", ".", "type", "===", "'object'", ")", "{", "for", "(", "var", "property", "in", "source", ".", "properties", ")", "{", "if", "(", "source", ".", "properties", "[", "property", "]", "[", "'$ref'", "]", ")", "{", "source", ".", "properties", "[", "property", "]", "=", "mapSimpleField", "(", "source", ".", "properties", "[", "property", "]", ")", ";", "}", "else", "if", "(", "source", ".", "properties", "[", "property", "]", ".", "type", "===", "'object'", "||", "source", ".", "properties", "[", "property", "]", ".", "type", "===", "'array'", ")", "{", "recursiveMapping", "(", "source", ".", "properties", "[", "property", "]", ")", ";", "}", "}", "}", "else", "if", "(", "source", ".", "schema", ")", "{", "if", "(", "source", ".", "schema", ".", "type", "===", "'object'", ")", "{", "for", "(", "var", "property", "in", "source", ".", "schema", ".", "properties", ")", "{", "if", "(", "source", ".", "schema", ".", "properties", "[", "property", "]", "[", "'$ref'", "]", ")", "{", "source", ".", "schema", ".", "properties", "[", "property", "]", "=", "mapSimpleField", "(", "source", ".", "schema", ".", "properties", "[", "property", "]", ")", ";", "}", "}", "}", "}", "else", "{", "//map simple inputs if any", "source", "=", "mapSimpleField", "(", "source", ")", ";", "}", "}" ]
loop through one common field recursively constructing and populating all its children imfv
[ "loop", "through", "one", "common", "field", "recursively", "constructing", "and", "populating", "all", "its", "children", "imfv" ]
89b9583d2b62229430f4d710107c285149174a87
https://github.com/soajs/grunt-soajs/blob/89b9583d2b62229430f4d710107c285149174a87/lib/swagger/swagger.js#L337-L370
56,055
soajs/grunt-soajs
lib/swagger/swagger.js
function (yamlContent, context, callback) { var jsonAPISchema; try { jsonAPISchema = yamljs.parse(yamlContent); } catch (e) { return callback({"code": 851, "msg": e.message}); } try { swagger.validateYaml(jsonAPISchema); } catch (e) { return callback({"code": 173, "msg": e.message}); } context.yaml = jsonAPISchema; swagger.mapAPis(jsonAPISchema, function (response) { context.soajs.config.schema = response.schema; context.soajs.config.errors = response.errors; var myValidator = new Validator(); var check = myValidator.validate(context.soajs.config, schema); if (check.valid) { return callback(null, true); } else { var errMsgs = []; check.errors.forEach(function (oneError) { errMsgs.push(oneError.stack); }); return callback({"code": 172, "msg": new Error(errMsgs.join(" - ")).message}); } }); }
javascript
function (yamlContent, context, callback) { var jsonAPISchema; try { jsonAPISchema = yamljs.parse(yamlContent); } catch (e) { return callback({"code": 851, "msg": e.message}); } try { swagger.validateYaml(jsonAPISchema); } catch (e) { return callback({"code": 173, "msg": e.message}); } context.yaml = jsonAPISchema; swagger.mapAPis(jsonAPISchema, function (response) { context.soajs.config.schema = response.schema; context.soajs.config.errors = response.errors; var myValidator = new Validator(); var check = myValidator.validate(context.soajs.config, schema); if (check.valid) { return callback(null, true); } else { var errMsgs = []; check.errors.forEach(function (oneError) { errMsgs.push(oneError.stack); }); return callback({"code": 172, "msg": new Error(errMsgs.join(" - ")).message}); } }); }
[ "function", "(", "yamlContent", ",", "context", ",", "callback", ")", "{", "var", "jsonAPISchema", ";", "try", "{", "jsonAPISchema", "=", "yamljs", ".", "parse", "(", "yamlContent", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "callback", "(", "{", "\"code\"", ":", "851", ",", "\"msg\"", ":", "e", ".", "message", "}", ")", ";", "}", "try", "{", "swagger", ".", "validateYaml", "(", "jsonAPISchema", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "callback", "(", "{", "\"code\"", ":", "173", ",", "\"msg\"", ":", "e", ".", "message", "}", ")", ";", "}", "context", ".", "yaml", "=", "jsonAPISchema", ";", "swagger", ".", "mapAPis", "(", "jsonAPISchema", ",", "function", "(", "response", ")", "{", "context", ".", "soajs", ".", "config", ".", "schema", "=", "response", ".", "schema", ";", "context", ".", "soajs", ".", "config", ".", "errors", "=", "response", ".", "errors", ";", "var", "myValidator", "=", "new", "Validator", "(", ")", ";", "var", "check", "=", "myValidator", ".", "validate", "(", "context", ".", "soajs", ".", "config", ",", "schema", ")", ";", "if", "(", "check", ".", "valid", ")", "{", "return", "callback", "(", "null", ",", "true", ")", ";", "}", "else", "{", "var", "errMsgs", "=", "[", "]", ";", "check", ".", "errors", ".", "forEach", "(", "function", "(", "oneError", ")", "{", "errMsgs", ".", "push", "(", "oneError", ".", "stack", ")", ";", "}", ")", ";", "return", "callback", "(", "{", "\"code\"", ":", "172", ",", "\"msg\"", ":", "new", "Error", "(", "errMsgs", ".", "join", "(", "\" - \"", ")", ")", ".", "message", "}", ")", ";", "}", "}", ")", ";", "}" ]
parse the yaml and generate a config.js content from it @param cb @returns {*}
[ "parse", "the", "yaml", "and", "generate", "a", "config", ".", "js", "content", "from", "it" ]
89b9583d2b62229430f4d710107c285149174a87
https://github.com/soajs/grunt-soajs/blob/89b9583d2b62229430f4d710107c285149174a87/lib/swagger/swagger.js#L402-L438
56,056
soajs/grunt-soajs
lib/swagger/swagger.js
function (yamlJson) { if (typeof yamlJson !== 'object') { throw new Error("Yaml file was converted to a string"); } if (!yamlJson.paths || Object.keys(yamlJson.paths).length === 0) { throw new Error("Yaml file is missing api schema"); } //loop in path for (var onePath in yamlJson.paths) { //loop in methods for (var oneMethod in yamlJson.paths[onePath]) { if (!yamlJson.paths[onePath][oneMethod].summary || yamlJson.paths[onePath][oneMethod].summary === "") { throw new Error("Please enter a summary for API " + oneMethod + ": " + onePath + " you want to build."); } } } }
javascript
function (yamlJson) { if (typeof yamlJson !== 'object') { throw new Error("Yaml file was converted to a string"); } if (!yamlJson.paths || Object.keys(yamlJson.paths).length === 0) { throw new Error("Yaml file is missing api schema"); } //loop in path for (var onePath in yamlJson.paths) { //loop in methods for (var oneMethod in yamlJson.paths[onePath]) { if (!yamlJson.paths[onePath][oneMethod].summary || yamlJson.paths[onePath][oneMethod].summary === "") { throw new Error("Please enter a summary for API " + oneMethod + ": " + onePath + " you want to build."); } } } }
[ "function", "(", "yamlJson", ")", "{", "if", "(", "typeof", "yamlJson", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "\"Yaml file was converted to a string\"", ")", ";", "}", "if", "(", "!", "yamlJson", ".", "paths", "||", "Object", ".", "keys", "(", "yamlJson", ".", "paths", ")", ".", "length", "===", "0", ")", "{", "throw", "new", "Error", "(", "\"Yaml file is missing api schema\"", ")", ";", "}", "//loop in path", "for", "(", "var", "onePath", "in", "yamlJson", ".", "paths", ")", "{", "//loop in methods", "for", "(", "var", "oneMethod", "in", "yamlJson", ".", "paths", "[", "onePath", "]", ")", "{", "if", "(", "!", "yamlJson", ".", "paths", "[", "onePath", "]", "[", "oneMethod", "]", ".", "summary", "||", "yamlJson", ".", "paths", "[", "onePath", "]", "[", "oneMethod", "]", ".", "summary", "===", "\"\"", ")", "{", "throw", "new", "Error", "(", "\"Please enter a summary for API \"", "+", "oneMethod", "+", "\": \"", "+", "onePath", "+", "\" you want to build.\"", ")", ";", "}", "}", "}", "}" ]
validate that parsed yaml content has the minimum required fields @param yamlJson
[ "validate", "that", "parsed", "yaml", "content", "has", "the", "minimum", "required", "fields" ]
89b9583d2b62229430f4d710107c285149174a87
https://github.com/soajs/grunt-soajs/blob/89b9583d2b62229430f4d710107c285149174a87/lib/swagger/swagger.js#L444-L462
56,057
soajs/grunt-soajs
lib/swagger/swagger.js
function (obj) { if (typeof obj !== "object" || obj === null) { return obj; } if (obj instanceof Date) { return new Date(obj.getTime()); } if (obj instanceof RegExp) { return new RegExp(obj); } if (obj instanceof Array && Object.keys(obj).every(function (k) { return !isNaN(k); })) { return obj.slice(0); } var _obj = {}; for (var attr in obj) { if (Object.hasOwnProperty.call(obj, attr)) { _obj[attr] = swagger.cloneObj(obj[attr]); } } return _obj; }
javascript
function (obj) { if (typeof obj !== "object" || obj === null) { return obj; } if (obj instanceof Date) { return new Date(obj.getTime()); } if (obj instanceof RegExp) { return new RegExp(obj); } if (obj instanceof Array && Object.keys(obj).every(function (k) { return !isNaN(k); })) { return obj.slice(0); } var _obj = {}; for (var attr in obj) { if (Object.hasOwnProperty.call(obj, attr)) { _obj[attr] = swagger.cloneObj(obj[attr]); } } return _obj; }
[ "function", "(", "obj", ")", "{", "if", "(", "typeof", "obj", "!==", "\"object\"", "||", "obj", "===", "null", ")", "{", "return", "obj", ";", "}", "if", "(", "obj", "instanceof", "Date", ")", "{", "return", "new", "Date", "(", "obj", ".", "getTime", "(", ")", ")", ";", "}", "if", "(", "obj", "instanceof", "RegExp", ")", "{", "return", "new", "RegExp", "(", "obj", ")", ";", "}", "if", "(", "obj", "instanceof", "Array", "&&", "Object", ".", "keys", "(", "obj", ")", ".", "every", "(", "function", "(", "k", ")", "{", "return", "!", "isNaN", "(", "k", ")", ";", "}", ")", ")", "{", "return", "obj", ".", "slice", "(", "0", ")", ";", "}", "var", "_obj", "=", "{", "}", ";", "for", "(", "var", "attr", "in", "obj", ")", "{", "if", "(", "Object", ".", "hasOwnProperty", ".", "call", "(", "obj", ",", "attr", ")", ")", "{", "_obj", "[", "attr", "]", "=", "swagger", ".", "cloneObj", "(", "obj", "[", "attr", "]", ")", ";", "}", "}", "return", "_obj", ";", "}" ]
clone a javascript object with type casting @param obj @returns {*}
[ "clone", "a", "javascript", "object", "with", "type", "casting" ]
89b9583d2b62229430f4d710107c285149174a87
https://github.com/soajs/grunt-soajs/blob/89b9583d2b62229430f4d710107c285149174a87/lib/swagger/swagger.js#L469-L494
56,058
soajs/grunt-soajs
lib/swagger/swagger.js
function (serviceInfo) { var config = { "type": "service", "prerequisites": { "cpu": " ", "memory": " " }, "swagger": true, "injection": true, "serviceName": serviceInfo.serviceName, "serviceGroup": serviceInfo.serviceGroup, "serviceVersion": serviceInfo.serviceVersion, "servicePort": serviceInfo.servicePort, "requestTimeout": serviceInfo.requestTimeout, "requestTimeoutRenewal": serviceInfo.requestTimeoutRenewal, "extKeyRequired": serviceInfo.extKeyRequired, "oauth": serviceInfo.oauth, "session": serviceInfo.session, "errors": {}, "schema": {} }; if (serviceInfo.dbs && Array.isArray(serviceInfo.dbs) && serviceInfo.dbs.length > 0) { config["dbs"] = serviceInfo.dbs; config["models"] = { "path": '%__dirname% + "/lib/models/"', "name": "" }; var modelProps = Object.keys(serviceInfo.dbs[0]); if (modelProps.indexOf("mongo") !== -1) { config.models.name = serviceInfo.dbs[0] = "mongo"; } else { config.models.name = serviceInfo.dbs[0] = "es"; } } return config; }
javascript
function (serviceInfo) { var config = { "type": "service", "prerequisites": { "cpu": " ", "memory": " " }, "swagger": true, "injection": true, "serviceName": serviceInfo.serviceName, "serviceGroup": serviceInfo.serviceGroup, "serviceVersion": serviceInfo.serviceVersion, "servicePort": serviceInfo.servicePort, "requestTimeout": serviceInfo.requestTimeout, "requestTimeoutRenewal": serviceInfo.requestTimeoutRenewal, "extKeyRequired": serviceInfo.extKeyRequired, "oauth": serviceInfo.oauth, "session": serviceInfo.session, "errors": {}, "schema": {} }; if (serviceInfo.dbs && Array.isArray(serviceInfo.dbs) && serviceInfo.dbs.length > 0) { config["dbs"] = serviceInfo.dbs; config["models"] = { "path": '%__dirname% + "/lib/models/"', "name": "" }; var modelProps = Object.keys(serviceInfo.dbs[0]); if (modelProps.indexOf("mongo") !== -1) { config.models.name = serviceInfo.dbs[0] = "mongo"; } else { config.models.name = serviceInfo.dbs[0] = "es"; } } return config; }
[ "function", "(", "serviceInfo", ")", "{", "var", "config", "=", "{", "\"type\"", ":", "\"service\"", ",", "\"prerequisites\"", ":", "{", "\"cpu\"", ":", "\" \"", ",", "\"memory\"", ":", "\" \"", "}", ",", "\"swagger\"", ":", "true", ",", "\"injection\"", ":", "true", ",", "\"serviceName\"", ":", "serviceInfo", ".", "serviceName", ",", "\"serviceGroup\"", ":", "serviceInfo", ".", "serviceGroup", ",", "\"serviceVersion\"", ":", "serviceInfo", ".", "serviceVersion", ",", "\"servicePort\"", ":", "serviceInfo", ".", "servicePort", ",", "\"requestTimeout\"", ":", "serviceInfo", ".", "requestTimeout", ",", "\"requestTimeoutRenewal\"", ":", "serviceInfo", ".", "requestTimeoutRenewal", ",", "\"extKeyRequired\"", ":", "serviceInfo", ".", "extKeyRequired", ",", "\"oauth\"", ":", "serviceInfo", ".", "oauth", ",", "\"session\"", ":", "serviceInfo", ".", "session", ",", "\"errors\"", ":", "{", "}", ",", "\"schema\"", ":", "{", "}", "}", ";", "if", "(", "serviceInfo", ".", "dbs", "&&", "Array", ".", "isArray", "(", "serviceInfo", ".", "dbs", ")", "&&", "serviceInfo", ".", "dbs", ".", "length", ">", "0", ")", "{", "config", "[", "\"dbs\"", "]", "=", "serviceInfo", ".", "dbs", ";", "config", "[", "\"models\"", "]", "=", "{", "\"path\"", ":", "'%__dirname% + \"/lib/models/\"'", ",", "\"name\"", ":", "\"\"", "}", ";", "var", "modelProps", "=", "Object", ".", "keys", "(", "serviceInfo", ".", "dbs", "[", "0", "]", ")", ";", "if", "(", "modelProps", ".", "indexOf", "(", "\"mongo\"", ")", "!==", "-", "1", ")", "{", "config", ".", "models", ".", "name", "=", "serviceInfo", ".", "dbs", "[", "0", "]", "=", "\"mongo\"", ";", "}", "else", "{", "config", ".", "models", ".", "name", "=", "serviceInfo", ".", "dbs", "[", "0", "]", "=", "\"es\"", ";", "}", "}", "return", "config", ";", "}" ]
map variables to meet the service configuration object schema @param serviceInfo @returns {{type: string, prerequisites: {cpu: string, memory: string}, swagger: boolean, dbs, serviceName, serviceGroup, serviceVersion, servicePort, requestTimeout, requestTimeoutRenewal, extKeyRequired, oauth, session, errors: {}, schema: {}}}
[ "map", "variables", "to", "meet", "the", "service", "configuration", "object", "schema" ]
89b9583d2b62229430f4d710107c285149174a87
https://github.com/soajs/grunt-soajs/blob/89b9583d2b62229430f4d710107c285149174a87/lib/swagger/swagger.js#L501-L540
56,059
soajs/grunt-soajs
lib/swagger/swagger.js
function (yamlJson, cb) { let all_apis = {}; let all_errors = {}; let paths = reformatPaths(yamlJson.paths); let definitions = yamlJson.definitions; let parameters = yamlJson.parameters; let convertedDefinitions = {}; let convertedParameters = {}; // convert definitions first if (definitions) { let definitionsKeys = Object.keys(definitions); definitionsKeys.forEach(function (eachDef) { convertedDefinitions[eachDef] = convertItem(null, definitions[eachDef], 1); // 1 ??? definitions should never have schema -=-=-=-=-= }); } // convert parameters then if (parameters) { let parametersKeys = Object.keys(parameters); parametersKeys.forEach(function (eachParam) { convertedParameters[eachParam] = convertItem(convertedDefinitions, parameters[eachParam], 1); }); all_apis.commonFields = convertedParameters; } let pathsKeys = Object.keys(paths); pathsKeys.forEach(function (eachPath) { let methods = paths[eachPath]; let methodsKeys = Object.keys(methods); methodsKeys.forEach(function (eachMethod) { let apiData = methods[eachMethod]; if (!all_apis[eachMethod]) { all_apis[eachMethod] = {}; } var mwFile = eachPath.replace(/\\/g, "_").replace(/:/g, "_").replace(/\//g, "_").replace(/[_]{2,}/g, "_").replace(/{/g, "").replace(/}/g, ""); mwFile = mwFile.toLowerCase(); if (mwFile[0] === "_") { mwFile = mwFile.substring(1); } mwFile += "_" + eachMethod.toLowerCase() + ".js"; all_apis[eachMethod][eachPath] = { _apiInfo: {}, "mw": '%dirname% + "/lib/mw/' + mwFile + '"' }; let newSoajsApi = all_apis[eachMethod][eachPath]; let params = apiData.parameters; let group = apiData.tags ? apiData.tags[0] : ""; newSoajsApi._apiInfo.group = group && group !== '' ? group : "general"; newSoajsApi._apiInfo.l = apiData.summary; newSoajsApi.imfv = convertParams(convertedDefinitions, convertedParameters, params); }); }); // todo: convert errors return cb({"schema": all_apis, "errors": all_errors}); }
javascript
function (yamlJson, cb) { let all_apis = {}; let all_errors = {}; let paths = reformatPaths(yamlJson.paths); let definitions = yamlJson.definitions; let parameters = yamlJson.parameters; let convertedDefinitions = {}; let convertedParameters = {}; // convert definitions first if (definitions) { let definitionsKeys = Object.keys(definitions); definitionsKeys.forEach(function (eachDef) { convertedDefinitions[eachDef] = convertItem(null, definitions[eachDef], 1); // 1 ??? definitions should never have schema -=-=-=-=-= }); } // convert parameters then if (parameters) { let parametersKeys = Object.keys(parameters); parametersKeys.forEach(function (eachParam) { convertedParameters[eachParam] = convertItem(convertedDefinitions, parameters[eachParam], 1); }); all_apis.commonFields = convertedParameters; } let pathsKeys = Object.keys(paths); pathsKeys.forEach(function (eachPath) { let methods = paths[eachPath]; let methodsKeys = Object.keys(methods); methodsKeys.forEach(function (eachMethod) { let apiData = methods[eachMethod]; if (!all_apis[eachMethod]) { all_apis[eachMethod] = {}; } var mwFile = eachPath.replace(/\\/g, "_").replace(/:/g, "_").replace(/\//g, "_").replace(/[_]{2,}/g, "_").replace(/{/g, "").replace(/}/g, ""); mwFile = mwFile.toLowerCase(); if (mwFile[0] === "_") { mwFile = mwFile.substring(1); } mwFile += "_" + eachMethod.toLowerCase() + ".js"; all_apis[eachMethod][eachPath] = { _apiInfo: {}, "mw": '%dirname% + "/lib/mw/' + mwFile + '"' }; let newSoajsApi = all_apis[eachMethod][eachPath]; let params = apiData.parameters; let group = apiData.tags ? apiData.tags[0] : ""; newSoajsApi._apiInfo.group = group && group !== '' ? group : "general"; newSoajsApi._apiInfo.l = apiData.summary; newSoajsApi.imfv = convertParams(convertedDefinitions, convertedParameters, params); }); }); // todo: convert errors return cb({"schema": all_apis, "errors": all_errors}); }
[ "function", "(", "yamlJson", ",", "cb", ")", "{", "let", "all_apis", "=", "{", "}", ";", "let", "all_errors", "=", "{", "}", ";", "let", "paths", "=", "reformatPaths", "(", "yamlJson", ".", "paths", ")", ";", "let", "definitions", "=", "yamlJson", ".", "definitions", ";", "let", "parameters", "=", "yamlJson", ".", "parameters", ";", "let", "convertedDefinitions", "=", "{", "}", ";", "let", "convertedParameters", "=", "{", "}", ";", "// convert definitions first", "if", "(", "definitions", ")", "{", "let", "definitionsKeys", "=", "Object", ".", "keys", "(", "definitions", ")", ";", "definitionsKeys", ".", "forEach", "(", "function", "(", "eachDef", ")", "{", "convertedDefinitions", "[", "eachDef", "]", "=", "convertItem", "(", "null", ",", "definitions", "[", "eachDef", "]", ",", "1", ")", ";", "// 1 ??? definitions should never have schema -=-=-=-=-=", "}", ")", ";", "}", "// convert parameters then", "if", "(", "parameters", ")", "{", "let", "parametersKeys", "=", "Object", ".", "keys", "(", "parameters", ")", ";", "parametersKeys", ".", "forEach", "(", "function", "(", "eachParam", ")", "{", "convertedParameters", "[", "eachParam", "]", "=", "convertItem", "(", "convertedDefinitions", ",", "parameters", "[", "eachParam", "]", ",", "1", ")", ";", "}", ")", ";", "all_apis", ".", "commonFields", "=", "convertedParameters", ";", "}", "let", "pathsKeys", "=", "Object", ".", "keys", "(", "paths", ")", ";", "pathsKeys", ".", "forEach", "(", "function", "(", "eachPath", ")", "{", "let", "methods", "=", "paths", "[", "eachPath", "]", ";", "let", "methodsKeys", "=", "Object", ".", "keys", "(", "methods", ")", ";", "methodsKeys", ".", "forEach", "(", "function", "(", "eachMethod", ")", "{", "let", "apiData", "=", "methods", "[", "eachMethod", "]", ";", "if", "(", "!", "all_apis", "[", "eachMethod", "]", ")", "{", "all_apis", "[", "eachMethod", "]", "=", "{", "}", ";", "}", "var", "mwFile", "=", "eachPath", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "\"_\"", ")", ".", "replace", "(", "/", ":", "/", "g", ",", "\"_\"", ")", ".", "replace", "(", "/", "\\/", "/", "g", ",", "\"_\"", ")", ".", "replace", "(", "/", "[_]{2,}", "/", "g", ",", "\"_\"", ")", ".", "replace", "(", "/", "{", "/", "g", ",", "\"\"", ")", ".", "replace", "(", "/", "}", "/", "g", ",", "\"\"", ")", ";", "mwFile", "=", "mwFile", ".", "toLowerCase", "(", ")", ";", "if", "(", "mwFile", "[", "0", "]", "===", "\"_\"", ")", "{", "mwFile", "=", "mwFile", ".", "substring", "(", "1", ")", ";", "}", "mwFile", "+=", "\"_\"", "+", "eachMethod", ".", "toLowerCase", "(", ")", "+", "\".js\"", ";", "all_apis", "[", "eachMethod", "]", "[", "eachPath", "]", "=", "{", "_apiInfo", ":", "{", "}", ",", "\"mw\"", ":", "'%dirname% + \"/lib/mw/'", "+", "mwFile", "+", "'\"'", "}", ";", "let", "newSoajsApi", "=", "all_apis", "[", "eachMethod", "]", "[", "eachPath", "]", ";", "let", "params", "=", "apiData", ".", "parameters", ";", "let", "group", "=", "apiData", ".", "tags", "?", "apiData", ".", "tags", "[", "0", "]", ":", "\"\"", ";", "newSoajsApi", ".", "_apiInfo", ".", "group", "=", "group", "&&", "group", "!==", "''", "?", "group", ":", "\"general\"", ";", "newSoajsApi", ".", "_apiInfo", ".", "l", "=", "apiData", ".", "summary", ";", "newSoajsApi", ".", "imfv", "=", "convertParams", "(", "convertedDefinitions", ",", "convertedParameters", ",", "params", ")", ";", "}", ")", ";", "}", ")", ";", "// todo: convert errors", "return", "cb", "(", "{", "\"schema\"", ":", "all_apis", ",", "\"errors\"", ":", "all_errors", "}", ")", ";", "}" ]
map apis to meet service configuraiton schema from a parsed swagger yaml json object @param yamlJson @param cb @returns {*}
[ "map", "apis", "to", "meet", "service", "configuraiton", "schema", "from", "a", "parsed", "swagger", "yaml", "json", "object" ]
89b9583d2b62229430f4d710107c285149174a87
https://github.com/soajs/grunt-soajs/blob/89b9583d2b62229430f4d710107c285149174a87/lib/swagger/swagger.js#L548-L614
56,060
soajs/grunt-soajs
lib/swagger/swagger.js
function (files, callback) { //loop on all files and write them async.each(files, function (fileObj, mCb) { var data = swagger.cloneObj(fileObj.data); //if tokens, replace all occurences with corresponding values if (fileObj.tokens) { for (var i in fileObj.tokens) { var regexp = new RegExp("%" + i + "%", "g"); data = data.replace(regexp, fileObj.tokens[i]); } } if (fileObj.purify) { data = data.replace(/\\"/g, '"').replace(/["]+/g, '"').replace(/"__dirname/g, '__dirname'); data = data.replace(/("group": "__empty__")/g, '"group": ""'); data = data.replace(/("prefix": "(\s?|\s+),)/g, '"prefix": "",'); data = data.replace(/("l": "__empty__")/g, '"l": ""'); //"__dirname + \"/lib/mw/_get.js\"" //"__dirname + "/lib/mw/_get.js"" //"__dirname + "/lib/mw/_get.js" //__dirname + "/lib/mw/_get.js" } console.log("creating file:", fileObj.file); fs.writeFile(fileObj.file, data, "utf8", mCb); }, function (error) { if (error) { return callback({"code": 854, "msg": error.message}); } return callback(null, true); }); }
javascript
function (files, callback) { //loop on all files and write them async.each(files, function (fileObj, mCb) { var data = swagger.cloneObj(fileObj.data); //if tokens, replace all occurences with corresponding values if (fileObj.tokens) { for (var i in fileObj.tokens) { var regexp = new RegExp("%" + i + "%", "g"); data = data.replace(regexp, fileObj.tokens[i]); } } if (fileObj.purify) { data = data.replace(/\\"/g, '"').replace(/["]+/g, '"').replace(/"__dirname/g, '__dirname'); data = data.replace(/("group": "__empty__")/g, '"group": ""'); data = data.replace(/("prefix": "(\s?|\s+),)/g, '"prefix": "",'); data = data.replace(/("l": "__empty__")/g, '"l": ""'); //"__dirname + \"/lib/mw/_get.js\"" //"__dirname + "/lib/mw/_get.js"" //"__dirname + "/lib/mw/_get.js" //__dirname + "/lib/mw/_get.js" } console.log("creating file:", fileObj.file); fs.writeFile(fileObj.file, data, "utf8", mCb); }, function (error) { if (error) { return callback({"code": 854, "msg": error.message}); } return callback(null, true); }); }
[ "function", "(", "files", ",", "callback", ")", "{", "//loop on all files and write them", "async", ".", "each", "(", "files", ",", "function", "(", "fileObj", ",", "mCb", ")", "{", "var", "data", "=", "swagger", ".", "cloneObj", "(", "fileObj", ".", "data", ")", ";", "//if tokens, replace all occurences with corresponding values", "if", "(", "fileObj", ".", "tokens", ")", "{", "for", "(", "var", "i", "in", "fileObj", ".", "tokens", ")", "{", "var", "regexp", "=", "new", "RegExp", "(", "\"%\"", "+", "i", "+", "\"%\"", ",", "\"g\"", ")", ";", "data", "=", "data", ".", "replace", "(", "regexp", ",", "fileObj", ".", "tokens", "[", "i", "]", ")", ";", "}", "}", "if", "(", "fileObj", ".", "purify", ")", "{", "data", "=", "data", ".", "replace", "(", "/", "\\\\\"", "/", "g", ",", "'\"'", ")", ".", "replace", "(", "/", "[\"]+", "/", "g", ",", "'\"'", ")", ".", "replace", "(", "/", "\"__dirname", "/", "g", ",", "'__dirname'", ")", ";", "data", "=", "data", ".", "replace", "(", "/", "(\"group\": \"__empty__\")", "/", "g", ",", "'\"group\": \"\"'", ")", ";", "data", "=", "data", ".", "replace", "(", "/", "(\"prefix\": \"(\\s?|\\s+),)", "/", "g", ",", "'\"prefix\": \"\",'", ")", ";", "data", "=", "data", ".", "replace", "(", "/", "(\"l\": \"__empty__\")", "/", "g", ",", "'\"l\": \"\"'", ")", ";", "//\"__dirname + \\\"/lib/mw/_get.js\\\"\"", "//\"__dirname + \"/lib/mw/_get.js\"\"", "//\"__dirname + \"/lib/mw/_get.js\"", "//__dirname + \"/lib/mw/_get.js\"", "}", "console", ".", "log", "(", "\"creating file:\"", ",", "fileObj", ".", "file", ")", ";", "fs", ".", "writeFile", "(", "fileObj", ".", "file", ",", "data", ",", "\"utf8\"", ",", "mCb", ")", ";", "}", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "return", "callback", "(", "{", "\"code\"", ":", "854", ",", "\"msg\"", ":", "error", ".", "message", "}", ")", ";", "}", "return", "callback", "(", "null", ",", "true", ")", ";", "}", ")", ";", "}" ]
function that generates the files for the microservice @param files @param callback
[ "function", "that", "generates", "the", "files", "for", "the", "microservice" ]
89b9583d2b62229430f4d710107c285149174a87
https://github.com/soajs/grunt-soajs/blob/89b9583d2b62229430f4d710107c285149174a87/lib/swagger/swagger.js#L621-L651
56,061
neurospeech/web-atoms-unit
index.js
function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this.testCategory = name; return construct(original, args); }
javascript
function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this.testCategory = name; return construct(original, args); }
[ "function", "(", ")", "{", "var", "args", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "args", "[", "_i", "]", "=", "arguments", "[", "_i", "]", ";", "}", "this", ".", "testCategory", "=", "name", ";", "return", "construct", "(", "original", ",", "args", ")", ";", "}" ]
the new constructor behaviour
[ "the", "new", "constructor", "behaviour" ]
16f51dd9a73a3c4ad896bc999c4b2ba05375158e
https://github.com/neurospeech/web-atoms-unit/blob/16f51dd9a73a3c4ad896bc999c4b2ba05375158e/index.js#L330-L337
56,062
muraken720/retext-japanese
index.js
createWordNode
function createWordNode (item) { var wordNode = parser.createParentNode('Word') if (options && options.pos) { wordNode.data = item } var textNode = parser.createTextNode('Text', item.surface_form) parser.add(textNode, wordNode) return wordNode }
javascript
function createWordNode (item) { var wordNode = parser.createParentNode('Word') if (options && options.pos) { wordNode.data = item } var textNode = parser.createTextNode('Text', item.surface_form) parser.add(textNode, wordNode) return wordNode }
[ "function", "createWordNode", "(", "item", ")", "{", "var", "wordNode", "=", "parser", ".", "createParentNode", "(", "'Word'", ")", "if", "(", "options", "&&", "options", ".", "pos", ")", "{", "wordNode", ".", "data", "=", "item", "}", "var", "textNode", "=", "parser", ".", "createTextNode", "(", "'Text'", ",", "item", ".", "surface_form", ")", "parser", ".", "add", "(", "textNode", ",", "wordNode", ")", "return", "wordNode", "}" ]
Create WordNode with POS. @param item @returns {{type: string, value: *}}
[ "Create", "WordNode", "with", "POS", "." ]
a6b0c7da32be012618be848654924ea3e4fc2aed
https://github.com/muraken720/retext-japanese/blob/a6b0c7da32be012618be848654924ea3e4fc2aed/index.js#L42-L54
56,063
muraken720/retext-japanese
index.js
createTextNode
function createTextNode (type, item) { var node = parser.createTextNode(type, item.surface_form) if (options && options.pos) { node.data = item } return node }
javascript
function createTextNode (type, item) { var node = parser.createTextNode(type, item.surface_form) if (options && options.pos) { node.data = item } return node }
[ "function", "createTextNode", "(", "type", ",", "item", ")", "{", "var", "node", "=", "parser", ".", "createTextNode", "(", "type", ",", "item", ".", "surface_form", ")", "if", "(", "options", "&&", "options", ".", "pos", ")", "{", "node", ".", "data", "=", "item", "}", "return", "node", "}" ]
Create TextNode for SymbolNode, PunctuationNode, WhiteSpaceNode and SourceNode with POS. @param type @param item @returns {{type: string, value: *}}
[ "Create", "TextNode", "for", "SymbolNode", "PunctuationNode", "WhiteSpaceNode", "and", "SourceNode", "with", "POS", "." ]
a6b0c7da32be012618be848654924ea3e4fc2aed
https://github.com/muraken720/retext-japanese/blob/a6b0c7da32be012618be848654924ea3e4fc2aed/index.js#L62-L70
56,064
crispy1989/node-xerror
xerror.js
XError
function XError(/*code, message, data, privateData, cause*/) { if (Error.captureStackTrace) Error.captureStackTrace(this, this); else this.stack = new Error().stack; var code, message, data, cause, privateData; for(var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if(XError.isXError(arg) || arg instanceof Error) { if(cause !== undefined) { data = cause; } cause = arg; } else if(typeof arg === 'string' || typeof arg === 'number') { if(typeof arg !== 'string') arg = '' + arg; if(code === undefined && arg.indexOf(' ') == -1) code = arg; else if(message === undefined) message = arg; else if(data === undefined) data = arg; else if(privateData === undefined) privateData = arg; else if(cause === undefined) cause = new Error(arg); } else if(arg === null || arg === undefined) { if(code === undefined) code = null; else if(message === undefined) message = null; else if(data === undefined) data = null; else if(privateData === undefined) privateData = null; else if(cause === undefined) cause = null; } else { if(data === undefined) data = arg; else if(privateData === undefined) privateData = arg; } } code = code || (cause && cause.code) || XError.INTERNAL_ERROR; message = message || (cause && cause.message); if(code) { var errorCodeInfo = registry.getErrorCode(code); if(errorCodeInfo) { if(errorCodeInfo.code) code = errorCodeInfo.code; // in case of aliased error codes if(!message && errorCodeInfo.message) message = errorCodeInfo.message; } } this.code = code; this.message = message || 'An error occurred'; this.data = data; this.privateData = privateData; this.cause = cause; this.name = 'XError'; Object.defineProperty(this, '_isXError', { configurable: false, enumerable: false, writable: false, value: true }); }
javascript
function XError(/*code, message, data, privateData, cause*/) { if (Error.captureStackTrace) Error.captureStackTrace(this, this); else this.stack = new Error().stack; var code, message, data, cause, privateData; for(var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if(XError.isXError(arg) || arg instanceof Error) { if(cause !== undefined) { data = cause; } cause = arg; } else if(typeof arg === 'string' || typeof arg === 'number') { if(typeof arg !== 'string') arg = '' + arg; if(code === undefined && arg.indexOf(' ') == -1) code = arg; else if(message === undefined) message = arg; else if(data === undefined) data = arg; else if(privateData === undefined) privateData = arg; else if(cause === undefined) cause = new Error(arg); } else if(arg === null || arg === undefined) { if(code === undefined) code = null; else if(message === undefined) message = null; else if(data === undefined) data = null; else if(privateData === undefined) privateData = null; else if(cause === undefined) cause = null; } else { if(data === undefined) data = arg; else if(privateData === undefined) privateData = arg; } } code = code || (cause && cause.code) || XError.INTERNAL_ERROR; message = message || (cause && cause.message); if(code) { var errorCodeInfo = registry.getErrorCode(code); if(errorCodeInfo) { if(errorCodeInfo.code) code = errorCodeInfo.code; // in case of aliased error codes if(!message && errorCodeInfo.message) message = errorCodeInfo.message; } } this.code = code; this.message = message || 'An error occurred'; this.data = data; this.privateData = privateData; this.cause = cause; this.name = 'XError'; Object.defineProperty(this, '_isXError', { configurable: false, enumerable: false, writable: false, value: true }); }
[ "function", "XError", "(", "/*code, message, data, privateData, cause*/", ")", "{", "if", "(", "Error", ".", "captureStackTrace", ")", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ")", ";", "else", "this", ".", "stack", "=", "new", "Error", "(", ")", ".", "stack", ";", "var", "code", ",", "message", ",", "data", ",", "cause", ",", "privateData", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "var", "arg", "=", "arguments", "[", "i", "]", ";", "if", "(", "XError", ".", "isXError", "(", "arg", ")", "||", "arg", "instanceof", "Error", ")", "{", "if", "(", "cause", "!==", "undefined", ")", "{", "data", "=", "cause", ";", "}", "cause", "=", "arg", ";", "}", "else", "if", "(", "typeof", "arg", "===", "'string'", "||", "typeof", "arg", "===", "'number'", ")", "{", "if", "(", "typeof", "arg", "!==", "'string'", ")", "arg", "=", "''", "+", "arg", ";", "if", "(", "code", "===", "undefined", "&&", "arg", ".", "indexOf", "(", "' '", ")", "==", "-", "1", ")", "code", "=", "arg", ";", "else", "if", "(", "message", "===", "undefined", ")", "message", "=", "arg", ";", "else", "if", "(", "data", "===", "undefined", ")", "data", "=", "arg", ";", "else", "if", "(", "privateData", "===", "undefined", ")", "privateData", "=", "arg", ";", "else", "if", "(", "cause", "===", "undefined", ")", "cause", "=", "new", "Error", "(", "arg", ")", ";", "}", "else", "if", "(", "arg", "===", "null", "||", "arg", "===", "undefined", ")", "{", "if", "(", "code", "===", "undefined", ")", "code", "=", "null", ";", "else", "if", "(", "message", "===", "undefined", ")", "message", "=", "null", ";", "else", "if", "(", "data", "===", "undefined", ")", "data", "=", "null", ";", "else", "if", "(", "privateData", "===", "undefined", ")", "privateData", "=", "null", ";", "else", "if", "(", "cause", "===", "undefined", ")", "cause", "=", "null", ";", "}", "else", "{", "if", "(", "data", "===", "undefined", ")", "data", "=", "arg", ";", "else", "if", "(", "privateData", "===", "undefined", ")", "privateData", "=", "arg", ";", "}", "}", "code", "=", "code", "||", "(", "cause", "&&", "cause", ".", "code", ")", "||", "XError", ".", "INTERNAL_ERROR", ";", "message", "=", "message", "||", "(", "cause", "&&", "cause", ".", "message", ")", ";", "if", "(", "code", ")", "{", "var", "errorCodeInfo", "=", "registry", ".", "getErrorCode", "(", "code", ")", ";", "if", "(", "errorCodeInfo", ")", "{", "if", "(", "errorCodeInfo", ".", "code", ")", "code", "=", "errorCodeInfo", ".", "code", ";", "// in case of aliased error codes", "if", "(", "!", "message", "&&", "errorCodeInfo", ".", "message", ")", "message", "=", "errorCodeInfo", ".", "message", ";", "}", "}", "this", ".", "code", "=", "code", ";", "this", ".", "message", "=", "message", "||", "'An error occurred'", ";", "this", ".", "data", "=", "data", ";", "this", ".", "privateData", "=", "privateData", ";", "this", ".", "cause", "=", "cause", ";", "this", ".", "name", "=", "'XError'", ";", "Object", ".", "defineProperty", "(", "this", ",", "'_isXError'", ",", "{", "configurable", ":", "false", ",", "enumerable", ":", "false", ",", "writable", ":", "false", ",", "value", ":", "true", "}", ")", ";", "}" ]
Construct a Extended Error instance. All parameters are optional, with the exception that a code is required if a message is given, and that data is required if privateData is given. @class XError @constructor @extends Error @uses ErrorCodeRegistry @param {String} [code="internal_error"] - The error code of the error. These are short string codes. They may not contain spaces. @param {String} [message] - Human-readable error message. @param {Object} [data] - Additional data about the error. @param {Object} [privateData] - Data that should be considered private to the application and is not displayed to users. @param {Error|XError} [cause] - The error which caused this error. Used to create error cause chains.
[ "Construct", "a", "Extended", "Error", "instance", ".", "All", "parameters", "are", "optional", "with", "the", "exception", "that", "a", "code", "is", "required", "if", "a", "message", "is", "given", "and", "that", "data", "is", "required", "if", "privateData", "is", "given", "." ]
d736c29d72dcdb6a93223073b9dcd05b08e5e07d
https://github.com/crispy1989/node-xerror/blob/d736c29d72dcdb6a93223073b9dcd05b08e5e07d/xerror.js#L19-L69
56,065
cuiyongjian/resource-meter
lib/myos.js
cpuAverage
function cpuAverage() { //Initialise sum of idle and time of cores and fetch CPU info var totalIdle = 0, totalTick = 0; var cpus = os.cpus(); //Loop through CPU cores for(var i = 0, len = cpus.length; i < len; i++) { //Select CPU core var cpu = cpus[i]; //Total up the time in the cores tick for(type in cpu.times) { totalTick += cpu.times[type]; } //Total up the idle time of the core totalIdle += cpu.times.idle; } //Return the average Idle and Tick times return {idle: totalIdle / cpus.length, total: totalTick / cpus.length}; }
javascript
function cpuAverage() { //Initialise sum of idle and time of cores and fetch CPU info var totalIdle = 0, totalTick = 0; var cpus = os.cpus(); //Loop through CPU cores for(var i = 0, len = cpus.length; i < len; i++) { //Select CPU core var cpu = cpus[i]; //Total up the time in the cores tick for(type in cpu.times) { totalTick += cpu.times[type]; } //Total up the idle time of the core totalIdle += cpu.times.idle; } //Return the average Idle and Tick times return {idle: totalIdle / cpus.length, total: totalTick / cpus.length}; }
[ "function", "cpuAverage", "(", ")", "{", "//Initialise sum of idle and time of cores and fetch CPU info", "var", "totalIdle", "=", "0", ",", "totalTick", "=", "0", ";", "var", "cpus", "=", "os", ".", "cpus", "(", ")", ";", "//Loop through CPU cores", "for", "(", "var", "i", "=", "0", ",", "len", "=", "cpus", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "//Select CPU core", "var", "cpu", "=", "cpus", "[", "i", "]", ";", "//Total up the time in the cores tick", "for", "(", "type", "in", "cpu", ".", "times", ")", "{", "totalTick", "+=", "cpu", ".", "times", "[", "type", "]", ";", "}", "//Total up the idle time of the core", "totalIdle", "+=", "cpu", ".", "times", ".", "idle", ";", "}", "//Return the average Idle and Tick times", "return", "{", "idle", ":", "totalIdle", "/", "cpus", ".", "length", ",", "total", ":", "totalTick", "/", "cpus", ".", "length", "}", ";", "}" ]
Create function to get CPU information
[ "Create", "function", "to", "get", "CPU", "information" ]
00298b6afa19e4b06cf344849a7c9559e2775d60
https://github.com/cuiyongjian/resource-meter/blob/00298b6afa19e4b06cf344849a7c9559e2775d60/lib/myos.js#L89-L111
56,066
mattdesl/kami-base-batch
mixins.js
function(r, g, b, a) { var rnum = typeof r === "number"; if (rnum && typeof g === "number" && typeof b === "number") { //default alpha to one a = typeof a === "number" ? a : 1.0; } else { r = g = b = a = rnum ? r : 1.0; } if (this.premultiplied) { r *= a; g *= a; b *= a; } this.color = colorToFloat( ~~(r * 255), ~~(g * 255), ~~(b * 255), ~~(a * 255) ); }
javascript
function(r, g, b, a) { var rnum = typeof r === "number"; if (rnum && typeof g === "number" && typeof b === "number") { //default alpha to one a = typeof a === "number" ? a : 1.0; } else { r = g = b = a = rnum ? r : 1.0; } if (this.premultiplied) { r *= a; g *= a; b *= a; } this.color = colorToFloat( ~~(r * 255), ~~(g * 255), ~~(b * 255), ~~(a * 255) ); }
[ "function", "(", "r", ",", "g", ",", "b", ",", "a", ")", "{", "var", "rnum", "=", "typeof", "r", "===", "\"number\"", ";", "if", "(", "rnum", "&&", "typeof", "g", "===", "\"number\"", "&&", "typeof", "b", "===", "\"number\"", ")", "{", "//default alpha to one ", "a", "=", "typeof", "a", "===", "\"number\"", "?", "a", ":", "1.0", ";", "}", "else", "{", "r", "=", "g", "=", "b", "=", "a", "=", "rnum", "?", "r", ":", "1.0", ";", "}", "if", "(", "this", ".", "premultiplied", ")", "{", "r", "*=", "a", ";", "g", "*=", "a", ";", "b", "*=", "a", ";", "}", "this", ".", "color", "=", "colorToFloat", "(", "~", "~", "(", "r", "*", "255", ")", ",", "~", "~", "(", "g", "*", "255", ")", ",", "~", "~", "(", "b", "*", "255", ")", ",", "~", "~", "(", "a", "*", "255", ")", ")", ";", "}" ]
Sets the color of this sprite batcher, which is used in subsequent draw calls. This does not flush the batch. If r, g, b, are all numbers, this method assumes that RGB or RGBA float values (0.0 to 1.0) are being passed. Alpha defaults to one if undefined. If one or more of the (r, g, b) arguments are non-numbers, we only consider the first argument and assign it to all four components -- this is useful for setting transparency in a premultiplied alpha stage. If the first argument is invalid or not a number, the color defaults to (1, 1, 1, 1). @method setColor @param {Number} r the red component, normalized @param {Number} g the green component, normalized @param {Number} b the blue component, normalized @param {Number} a the alpha component, normalized
[ "Sets", "the", "color", "of", "this", "sprite", "batcher", "which", "is", "used", "in", "subsequent", "draw", "calls", ".", "This", "does", "not", "flush", "the", "batch", "." ]
a090162d21959bc44832d724f1d12868883ec2ac
https://github.com/mattdesl/kami-base-batch/blob/a090162d21959bc44832d724f1d12868883ec2ac/mixins.js#L216-L239
56,067
muraken720/parse-japanese-basic
lib/parse-japanese-basic.js
ParseJapaneseBasic
function ParseJapaneseBasic (file, options) { var offset = 0 var line = 1 var column = 1 var position if (!(this instanceof ParseJapaneseBasic)) { return new ParseJapaneseBasic(file, options) } if (file && file.message) { this.file = file } else { options = file } position = options && options.position if (position !== null && position !== undefined) { this.position = Boolean(position) } this.offset = offset this.line = line this.column = column }
javascript
function ParseJapaneseBasic (file, options) { var offset = 0 var line = 1 var column = 1 var position if (!(this instanceof ParseJapaneseBasic)) { return new ParseJapaneseBasic(file, options) } if (file && file.message) { this.file = file } else { options = file } position = options && options.position if (position !== null && position !== undefined) { this.position = Boolean(position) } this.offset = offset this.line = line this.column = column }
[ "function", "ParseJapaneseBasic", "(", "file", ",", "options", ")", "{", "var", "offset", "=", "0", "var", "line", "=", "1", "var", "column", "=", "1", "var", "position", "if", "(", "!", "(", "this", "instanceof", "ParseJapaneseBasic", ")", ")", "{", "return", "new", "ParseJapaneseBasic", "(", "file", ",", "options", ")", "}", "if", "(", "file", "&&", "file", ".", "message", ")", "{", "this", ".", "file", "=", "file", "}", "else", "{", "options", "=", "file", "}", "position", "=", "options", "&&", "options", ".", "position", "if", "(", "position", "!==", "null", "&&", "position", "!==", "undefined", ")", "{", "this", ".", "position", "=", "Boolean", "(", "position", ")", "}", "this", ".", "offset", "=", "offset", "this", ".", "line", "=", "line", "this", ".", "column", "=", "column", "}" ]
Transform Japanese natural language into an NLCST-tree. @param {VFile?} file - Virtual file. @param {Object?} options - Configuration. @constructor {ParseJapanese}
[ "Transform", "Japanese", "natural", "language", "into", "an", "NLCST", "-", "tree", "." ]
ecbb712a11eed402192a17978e0079d6eb1a5888
https://github.com/muraken720/parse-japanese-basic/blob/ecbb712a11eed402192a17978e0079d6eb1a5888/lib/parse-japanese-basic.js#L77-L102
56,068
purplecabbage/cordova-paramedic-OLD
paramedic.js
ParamedicRunner
function ParamedicRunner(_platformId,_plugins,_callback,bJustBuild,nPort,msTimeout,browserify,bSilent,bVerbose,platformPath) { this.tunneledUrl = ""; this.port = nPort; this.justBuild = bJustBuild; this.plugins = _plugins; this.platformId = _platformId; this.callback = _callback; this.tempFolder = null; this.timeout = msTimeout; this.verbose = bVerbose; this.platformPath = platformPath; if(browserify) { this.browserify = "--browserify"; } else { this.browserify = ''; } if(bSilent) { var logOutput = this.logOutput = []; this.logMessage = function(msg) { logOutput.push(msg); }; } else { this.logMessage = function(msg) { console.log(msg); }; } }
javascript
function ParamedicRunner(_platformId,_plugins,_callback,bJustBuild,nPort,msTimeout,browserify,bSilent,bVerbose,platformPath) { this.tunneledUrl = ""; this.port = nPort; this.justBuild = bJustBuild; this.plugins = _plugins; this.platformId = _platformId; this.callback = _callback; this.tempFolder = null; this.timeout = msTimeout; this.verbose = bVerbose; this.platformPath = platformPath; if(browserify) { this.browserify = "--browserify"; } else { this.browserify = ''; } if(bSilent) { var logOutput = this.logOutput = []; this.logMessage = function(msg) { logOutput.push(msg); }; } else { this.logMessage = function(msg) { console.log(msg); }; } }
[ "function", "ParamedicRunner", "(", "_platformId", ",", "_plugins", ",", "_callback", ",", "bJustBuild", ",", "nPort", ",", "msTimeout", ",", "browserify", ",", "bSilent", ",", "bVerbose", ",", "platformPath", ")", "{", "this", ".", "tunneledUrl", "=", "\"\"", ";", "this", ".", "port", "=", "nPort", ";", "this", ".", "justBuild", "=", "bJustBuild", ";", "this", ".", "plugins", "=", "_plugins", ";", "this", ".", "platformId", "=", "_platformId", ";", "this", ".", "callback", "=", "_callback", ";", "this", ".", "tempFolder", "=", "null", ";", "this", ".", "timeout", "=", "msTimeout", ";", "this", ".", "verbose", "=", "bVerbose", ";", "this", ".", "platformPath", "=", "platformPath", ";", "if", "(", "browserify", ")", "{", "this", ".", "browserify", "=", "\"--browserify\"", ";", "}", "else", "{", "this", ".", "browserify", "=", "''", ";", "}", "if", "(", "bSilent", ")", "{", "var", "logOutput", "=", "this", ".", "logOutput", "=", "[", "]", ";", "this", ".", "logMessage", "=", "function", "(", "msg", ")", "{", "logOutput", ".", "push", "(", "msg", ")", ";", "}", ";", "}", "else", "{", "this", ".", "logMessage", "=", "function", "(", "msg", ")", "{", "console", ".", "log", "(", "msg", ")", ";", "}", ";", "}", "}" ]
10 minutes in msec - this will become a param
[ "10", "minutes", "in", "msec", "-", "this", "will", "become", "a", "param" ]
8615f31c9bca2f152a409d38a48c5c9587abf67d
https://github.com/purplecabbage/cordova-paramedic-OLD/blob/8615f31c9bca2f152a409d38a48c5c9587abf67d/paramedic.js#L17-L46
56,069
bammoo/get-less-imports
index.js
findImports
function findImports(filePath, result) { var importPaths = getImportPaths(filePath); var importPathsAbs = resolveImportPaths(filePath, importPaths); if( importPathsAbs.length ) result.full[filePath] = importPathsAbs; importPathsAbs.forEach(function(path){ if (result.simple.indexOf(path) === -1) { result.simple.push(path); findImports(path, result); } }); return result; }
javascript
function findImports(filePath, result) { var importPaths = getImportPaths(filePath); var importPathsAbs = resolveImportPaths(filePath, importPaths); if( importPathsAbs.length ) result.full[filePath] = importPathsAbs; importPathsAbs.forEach(function(path){ if (result.simple.indexOf(path) === -1) { result.simple.push(path); findImports(path, result); } }); return result; }
[ "function", "findImports", "(", "filePath", ",", "result", ")", "{", "var", "importPaths", "=", "getImportPaths", "(", "filePath", ")", ";", "var", "importPathsAbs", "=", "resolveImportPaths", "(", "filePath", ",", "importPaths", ")", ";", "if", "(", "importPathsAbs", ".", "length", ")", "result", ".", "full", "[", "filePath", "]", "=", "importPathsAbs", ";", "importPathsAbs", ".", "forEach", "(", "function", "(", "path", ")", "{", "if", "(", "result", ".", "simple", ".", "indexOf", "(", "path", ")", "===", "-", "1", ")", "{", "result", ".", "simple", ".", "push", "(", "path", ")", ";", "findImports", "(", "path", ",", "result", ")", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
Recursivley finds all @import paths of a LESS file, using a nice RegEx @param {string} filePath - The path of the LESS file. @param {Object} result @returns {Object}
[ "Recursivley", "finds", "all" ]
5577d46c95afecd4cde6889e991276b8ade02d93
https://github.com/bammoo/get-less-imports/blob/5577d46c95afecd4cde6889e991276b8ade02d93/index.js#L16-L28
56,070
bammoo/get-less-imports
index.js
getImportPaths
function getImportPaths(filePath){ var importPaths = []; try{ var contents = fs.readFileSync(filePath).toString('utf8'); importPaths = parseImpt(contents); } catch(exception){} return importPaths; }
javascript
function getImportPaths(filePath){ var importPaths = []; try{ var contents = fs.readFileSync(filePath).toString('utf8'); importPaths = parseImpt(contents); } catch(exception){} return importPaths; }
[ "function", "getImportPaths", "(", "filePath", ")", "{", "var", "importPaths", "=", "[", "]", ";", "try", "{", "var", "contents", "=", "fs", ".", "readFileSync", "(", "filePath", ")", ".", "toString", "(", "'utf8'", ")", ";", "importPaths", "=", "parseImpt", "(", "contents", ")", ";", "}", "catch", "(", "exception", ")", "{", "}", "return", "importPaths", ";", "}" ]
Finds all the @import paths in a LESS file. @param {string} filePath - The path of the LESS file.
[ "Finds", "all", "the" ]
5577d46c95afecd4cde6889e991276b8ade02d93
https://github.com/bammoo/get-less-imports/blob/5577d46c95afecd4cde6889e991276b8ade02d93/index.js#L46-L54
56,071
seznam/szn-tethered
szn-tethered.js
updatePosition
function updatePosition(instance, tetherBounds) { const x = tetherBounds.x + (instance.horizontalAlignment === HORIZONTAL_ALIGN.LEFT ? 0 : tetherBounds.width) const y = tetherBounds.y + (instance.verticalAlignment === VERTICAL_ALIGN.TOP ? 0 : tetherBounds.height) if (transformsSupported) { instance._root.style.transform = `translate(${x}px, ${y}px)` } else { instance._root.style.left = `${x}px` instance._root.style.top = `${y}px` } }
javascript
function updatePosition(instance, tetherBounds) { const x = tetherBounds.x + (instance.horizontalAlignment === HORIZONTAL_ALIGN.LEFT ? 0 : tetherBounds.width) const y = tetherBounds.y + (instance.verticalAlignment === VERTICAL_ALIGN.TOP ? 0 : tetherBounds.height) if (transformsSupported) { instance._root.style.transform = `translate(${x}px, ${y}px)` } else { instance._root.style.left = `${x}px` instance._root.style.top = `${y}px` } }
[ "function", "updatePosition", "(", "instance", ",", "tetherBounds", ")", "{", "const", "x", "=", "tetherBounds", ".", "x", "+", "(", "instance", ".", "horizontalAlignment", "===", "HORIZONTAL_ALIGN", ".", "LEFT", "?", "0", ":", "tetherBounds", ".", "width", ")", "const", "y", "=", "tetherBounds", ".", "y", "+", "(", "instance", ".", "verticalAlignment", "===", "VERTICAL_ALIGN", ".", "TOP", "?", "0", ":", "tetherBounds", ".", "height", ")", "if", "(", "transformsSupported", ")", "{", "instance", ".", "_root", ".", "style", ".", "transform", "=", "`", "${", "x", "}", "${", "y", "}", "`", "}", "else", "{", "instance", ".", "_root", ".", "style", ".", "left", "=", "`", "${", "x", "}", "`", "instance", ".", "_root", ".", "style", ".", "top", "=", "`", "${", "y", "}", "`", "}", "}" ]
Updates the position of the szn-tethered element according to the current tethering alignment and the provided bounds of the tethering element. @param {SznElements.SznTethered} instance The szn-tethered element instance. @param {TetherBounds} tetherBounds The bounds (location and size) of the tethering element.
[ "Updates", "the", "position", "of", "the", "szn", "-", "tethered", "element", "according", "to", "the", "current", "tethering", "alignment", "and", "the", "provided", "bounds", "of", "the", "tethering", "element", "." ]
31e84b54b1fe66d5491d0913987c3a475b0d549b
https://github.com/seznam/szn-tethered/blob/31e84b54b1fe66d5491d0913987c3a475b0d549b/szn-tethered.js#L244-L254
56,072
seznam/szn-tethered
szn-tethered.js
updateAttributes
function updateAttributes(instance) { if (instance.horizontalAlignment !== instance._lastHorizontalAlignment) { const horizontalAlignment = instance.horizontalAlignment === HORIZONTAL_ALIGN.LEFT ? 'left' : 'right' instance._root.setAttribute('data-horizontal-align', horizontalAlignment) instance._lastHorizontalAlignment = instance.horizontalAlignment } if (instance.verticalAlignment !== instance._lastVerticalAlignment) { const verticalAlignment = instance.verticalAlignment === VERTICAL_ALIGN.TOP ? 'top' : 'bottom' instance._root.setAttribute('data-vertical-align', verticalAlignment) instance._lastVerticalAlignment = instance.verticalAlignment } }
javascript
function updateAttributes(instance) { if (instance.horizontalAlignment !== instance._lastHorizontalAlignment) { const horizontalAlignment = instance.horizontalAlignment === HORIZONTAL_ALIGN.LEFT ? 'left' : 'right' instance._root.setAttribute('data-horizontal-align', horizontalAlignment) instance._lastHorizontalAlignment = instance.horizontalAlignment } if (instance.verticalAlignment !== instance._lastVerticalAlignment) { const verticalAlignment = instance.verticalAlignment === VERTICAL_ALIGN.TOP ? 'top' : 'bottom' instance._root.setAttribute('data-vertical-align', verticalAlignment) instance._lastVerticalAlignment = instance.verticalAlignment } }
[ "function", "updateAttributes", "(", "instance", ")", "{", "if", "(", "instance", ".", "horizontalAlignment", "!==", "instance", ".", "_lastHorizontalAlignment", ")", "{", "const", "horizontalAlignment", "=", "instance", ".", "horizontalAlignment", "===", "HORIZONTAL_ALIGN", ".", "LEFT", "?", "'left'", ":", "'right'", "instance", ".", "_root", ".", "setAttribute", "(", "'data-horizontal-align'", ",", "horizontalAlignment", ")", "instance", ".", "_lastHorizontalAlignment", "=", "instance", ".", "horizontalAlignment", "}", "if", "(", "instance", ".", "verticalAlignment", "!==", "instance", ".", "_lastVerticalAlignment", ")", "{", "const", "verticalAlignment", "=", "instance", ".", "verticalAlignment", "===", "VERTICAL_ALIGN", ".", "TOP", "?", "'top'", ":", "'bottom'", "instance", ".", "_root", ".", "setAttribute", "(", "'data-vertical-align'", ",", "verticalAlignment", ")", "instance", ".", "_lastVerticalAlignment", "=", "instance", ".", "verticalAlignment", "}", "}" ]
Updates the attributes on the szn-tethered element reporting the current alignment to the tethering element. @param {SznElements.SznTethered} instance The szn-tethered element instance.
[ "Updates", "the", "attributes", "on", "the", "szn", "-", "tethered", "element", "reporting", "the", "current", "alignment", "to", "the", "tethering", "element", "." ]
31e84b54b1fe66d5491d0913987c3a475b0d549b
https://github.com/seznam/szn-tethered/blob/31e84b54b1fe66d5491d0913987c3a475b0d549b/szn-tethered.js#L261-L272
56,073
seznam/szn-tethered
szn-tethered.js
getTetherBounds
function getTetherBounds(tether) { const bounds = tether.getBoundingClientRect() const width = bounds.width const height = bounds.height let x = 0 let y = 0 let tetherOffsetContainer = tether while (tetherOffsetContainer) { x += tetherOffsetContainer.offsetLeft y += tetherOffsetContainer.offsetTop tetherOffsetContainer = tetherOffsetContainer.offsetParent } return { screenX: bounds.left, screenY: bounds.top, x, y, width, height, } }
javascript
function getTetherBounds(tether) { const bounds = tether.getBoundingClientRect() const width = bounds.width const height = bounds.height let x = 0 let y = 0 let tetherOffsetContainer = tether while (tetherOffsetContainer) { x += tetherOffsetContainer.offsetLeft y += tetherOffsetContainer.offsetTop tetherOffsetContainer = tetherOffsetContainer.offsetParent } return { screenX: bounds.left, screenY: bounds.top, x, y, width, height, } }
[ "function", "getTetherBounds", "(", "tether", ")", "{", "const", "bounds", "=", "tether", ".", "getBoundingClientRect", "(", ")", "const", "width", "=", "bounds", ".", "width", "const", "height", "=", "bounds", ".", "height", "let", "x", "=", "0", "let", "y", "=", "0", "let", "tetherOffsetContainer", "=", "tether", "while", "(", "tetherOffsetContainer", ")", "{", "x", "+=", "tetherOffsetContainer", ".", "offsetLeft", "y", "+=", "tetherOffsetContainer", ".", "offsetTop", "tetherOffsetContainer", "=", "tetherOffsetContainer", ".", "offsetParent", "}", "return", "{", "screenX", ":", "bounds", ".", "left", ",", "screenY", ":", "bounds", ".", "top", ",", "x", ",", "y", ",", "width", ",", "height", ",", "}", "}" ]
Calculates and returns both the on-screen and on-page location and dimensions of the provided tether element. @param {Element} tether The tethering element. @return {TetherBounds} The on-screen and on-page location and dimensions of the element.
[ "Calculates", "and", "returns", "both", "the", "on", "-", "screen", "and", "on", "-", "page", "location", "and", "dimensions", "of", "the", "provided", "tether", "element", "." ]
31e84b54b1fe66d5491d0913987c3a475b0d549b
https://github.com/seznam/szn-tethered/blob/31e84b54b1fe66d5491d0913987c3a475b0d549b/szn-tethered.js#L280-L302
56,074
seznam/szn-tethered
szn-tethered.js
getContentDimensions
function getContentDimensions(instance) { const contentElement = instance._root.firstElementChild if (!contentElement) { return { width: 0, height: 0, } } let width let height if (window.devicePixelRatio > 1) { // This is much less performant, so we use in only on HiDPi displays const bounds = contentElement.getBoundingClientRect() width = bounds.width height = bounds.height } else { width = contentElement.scrollWidth height = contentElement.scrollHeight } return { width, height, } }
javascript
function getContentDimensions(instance) { const contentElement = instance._root.firstElementChild if (!contentElement) { return { width: 0, height: 0, } } let width let height if (window.devicePixelRatio > 1) { // This is much less performant, so we use in only on HiDPi displays const bounds = contentElement.getBoundingClientRect() width = bounds.width height = bounds.height } else { width = contentElement.scrollWidth height = contentElement.scrollHeight } return { width, height, } }
[ "function", "getContentDimensions", "(", "instance", ")", "{", "const", "contentElement", "=", "instance", ".", "_root", ".", "firstElementChild", "if", "(", "!", "contentElement", ")", "{", "return", "{", "width", ":", "0", ",", "height", ":", "0", ",", "}", "}", "let", "width", "let", "height", "if", "(", "window", ".", "devicePixelRatio", ">", "1", ")", "{", "// This is much less performant, so we use in only on HiDPi displays", "const", "bounds", "=", "contentElement", ".", "getBoundingClientRect", "(", ")", "width", "=", "bounds", ".", "width", "height", "=", "bounds", ".", "height", "}", "else", "{", "width", "=", "contentElement", ".", "scrollWidth", "height", "=", "contentElement", ".", "scrollHeight", "}", "return", "{", "width", ",", "height", ",", "}", "}" ]
Returns the dimensions of the content of the provided szn-tethered element. @param {SznElements.SznTethered} instance The instance of the szn-tethered element. @return {ContentDimensions} The dimensions of the tethered content.
[ "Returns", "the", "dimensions", "of", "the", "content", "of", "the", "provided", "szn", "-", "tethered", "element", "." ]
31e84b54b1fe66d5491d0913987c3a475b0d549b
https://github.com/seznam/szn-tethered/blob/31e84b54b1fe66d5491d0913987c3a475b0d549b/szn-tethered.js#L310-L335
56,075
jivesoftware/jive-persistence-sqlite
sqlite-dynamic.js
function( collectionID, criteria, cursor, limit) { collectionID = collectionID.toLowerCase(); var deferred = q.defer(); // acquire a connection from the pool db.getClient().then( function(dbClient) { if ( !dbClient ) { throw Error("Failed to acquire sqlite client"); } // do any necessary dynamic schema syncs, if its supported schemaSyncer.prepCollection(collectionID) .then( function() { return expandIfNecessary(collectionID, schemaSyncer.getTableSchema(collectionID), null, criteria); }) // perform the query .then( function() { var sql = sqlAdaptor.createSelectSQL(collectionID, criteria, limit); query(dbClient, sql).then( // success function(r) { var results = dbClient.results(); if ( !results || results.rowCount < 1 ) { // if no results, return empty array deferred.resolve([]); return; } var hydratedResults = sqlAdaptor.hydrateResults(results); if ( !cursor ) { deferred.resolve( hydratedResults ); } else { var stream = createStreamFrom(hydratedResults); deferred.resolve(stream ); } }, // error function(e) { jive.logger.error(e.stack); deferred.reject(e); } ); }) .fail(function(e){ deferred.reject(e); }) // always try to release the client, if it exists .finally(function() { if ( dbClient ) { // always try to release the client, if it exists dbClient.release(); } }); }) // failed to acquire the client .fail( function(e) { deferred.reject(e); }); return deferred.promise; }
javascript
function( collectionID, criteria, cursor, limit) { collectionID = collectionID.toLowerCase(); var deferred = q.defer(); // acquire a connection from the pool db.getClient().then( function(dbClient) { if ( !dbClient ) { throw Error("Failed to acquire sqlite client"); } // do any necessary dynamic schema syncs, if its supported schemaSyncer.prepCollection(collectionID) .then( function() { return expandIfNecessary(collectionID, schemaSyncer.getTableSchema(collectionID), null, criteria); }) // perform the query .then( function() { var sql = sqlAdaptor.createSelectSQL(collectionID, criteria, limit); query(dbClient, sql).then( // success function(r) { var results = dbClient.results(); if ( !results || results.rowCount < 1 ) { // if no results, return empty array deferred.resolve([]); return; } var hydratedResults = sqlAdaptor.hydrateResults(results); if ( !cursor ) { deferred.resolve( hydratedResults ); } else { var stream = createStreamFrom(hydratedResults); deferred.resolve(stream ); } }, // error function(e) { jive.logger.error(e.stack); deferred.reject(e); } ); }) .fail(function(e){ deferred.reject(e); }) // always try to release the client, if it exists .finally(function() { if ( dbClient ) { // always try to release the client, if it exists dbClient.release(); } }); }) // failed to acquire the client .fail( function(e) { deferred.reject(e); }); return deferred.promise; }
[ "function", "(", "collectionID", ",", "criteria", ",", "cursor", ",", "limit", ")", "{", "collectionID", "=", "collectionID", ".", "toLowerCase", "(", ")", ";", "var", "deferred", "=", "q", ".", "defer", "(", ")", ";", "// acquire a connection from the pool", "db", ".", "getClient", "(", ")", ".", "then", "(", "function", "(", "dbClient", ")", "{", "if", "(", "!", "dbClient", ")", "{", "throw", "Error", "(", "\"Failed to acquire sqlite client\"", ")", ";", "}", "// do any necessary dynamic schema syncs, if its supported", "schemaSyncer", ".", "prepCollection", "(", "collectionID", ")", ".", "then", "(", "function", "(", ")", "{", "return", "expandIfNecessary", "(", "collectionID", ",", "schemaSyncer", ".", "getTableSchema", "(", "collectionID", ")", ",", "null", ",", "criteria", ")", ";", "}", ")", "// perform the query", ".", "then", "(", "function", "(", ")", "{", "var", "sql", "=", "sqlAdaptor", ".", "createSelectSQL", "(", "collectionID", ",", "criteria", ",", "limit", ")", ";", "query", "(", "dbClient", ",", "sql", ")", ".", "then", "(", "// success", "function", "(", "r", ")", "{", "var", "results", "=", "dbClient", ".", "results", "(", ")", ";", "if", "(", "!", "results", "||", "results", ".", "rowCount", "<", "1", ")", "{", "// if no results, return empty array", "deferred", ".", "resolve", "(", "[", "]", ")", ";", "return", ";", "}", "var", "hydratedResults", "=", "sqlAdaptor", ".", "hydrateResults", "(", "results", ")", ";", "if", "(", "!", "cursor", ")", "{", "deferred", ".", "resolve", "(", "hydratedResults", ")", ";", "}", "else", "{", "var", "stream", "=", "createStreamFrom", "(", "hydratedResults", ")", ";", "deferred", ".", "resolve", "(", "stream", ")", ";", "}", "}", ",", "// error", "function", "(", "e", ")", "{", "jive", ".", "logger", ".", "error", "(", "e", ".", "stack", ")", ";", "deferred", ".", "reject", "(", "e", ")", ";", "}", ")", ";", "}", ")", ".", "fail", "(", "function", "(", "e", ")", "{", "deferred", ".", "reject", "(", "e", ")", ";", "}", ")", "// always try to release the client, if it exists", ".", "finally", "(", "function", "(", ")", "{", "if", "(", "dbClient", ")", "{", "// always try to release the client, if it exists", "dbClient", ".", "release", "(", ")", ";", "}", "}", ")", ";", "}", ")", "// failed to acquire the client", ".", "fail", "(", "function", "(", "e", ")", "{", "deferred", ".", "reject", "(", "e", ")", ";", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Retrieve a piece of data from a named collection, based on the criteria, return promise with an array of the results when done. @param collectionID @param criteria @param cursor if true, then returned item is a cursor; otherwise its a concrete collection (array) of items @param limit optional
[ "Retrieve", "a", "piece", "of", "data", "from", "a", "named", "collection", "based", "on", "the", "criteria", "return", "promise", "with", "an", "array", "of", "the", "results", "when", "done", "." ]
e61374ba629159d69e0239e1fe7f609c8654dc32
https://github.com/jivesoftware/jive-persistence-sqlite/blob/e61374ba629159d69e0239e1fe7f609c8654dc32/sqlite-dynamic.js#L237-L301
56,076
jivesoftware/jive-persistence-sqlite
sqlite-dynamic.js
function( collectionID, key ) { collectionID = collectionID.toLowerCase(); var deferred = q.defer(); schemaSyncer.prepCollection(collectionID) .then( function() { sqliteObj.find( collectionID, {'_id': key}, false, 1 ).then( // success function(r) { if ( r && r.length > 0 ) { var firstElement = r[0]; if ( isValue(firstElement[key]) ) { var value = firstElement[key]; deferred.resolve(value); } else { deferred.resolve(firstElement); } } return deferred.resolve(null); }, // failure function(e) { return q.reject(e); } ); }); return deferred.promise; }
javascript
function( collectionID, key ) { collectionID = collectionID.toLowerCase(); var deferred = q.defer(); schemaSyncer.prepCollection(collectionID) .then( function() { sqliteObj.find( collectionID, {'_id': key}, false, 1 ).then( // success function(r) { if ( r && r.length > 0 ) { var firstElement = r[0]; if ( isValue(firstElement[key]) ) { var value = firstElement[key]; deferred.resolve(value); } else { deferred.resolve(firstElement); } } return deferred.resolve(null); }, // failure function(e) { return q.reject(e); } ); }); return deferred.promise; }
[ "function", "(", "collectionID", ",", "key", ")", "{", "collectionID", "=", "collectionID", ".", "toLowerCase", "(", ")", ";", "var", "deferred", "=", "q", ".", "defer", "(", ")", ";", "schemaSyncer", ".", "prepCollection", "(", "collectionID", ")", ".", "then", "(", "function", "(", ")", "{", "sqliteObj", ".", "find", "(", "collectionID", ",", "{", "'_id'", ":", "key", "}", ",", "false", ",", "1", ")", ".", "then", "(", "// success", "function", "(", "r", ")", "{", "if", "(", "r", "&&", "r", ".", "length", ">", "0", ")", "{", "var", "firstElement", "=", "r", "[", "0", "]", ";", "if", "(", "isValue", "(", "firstElement", "[", "key", "]", ")", ")", "{", "var", "value", "=", "firstElement", "[", "key", "]", ";", "deferred", ".", "resolve", "(", "value", ")", ";", "}", "else", "{", "deferred", ".", "resolve", "(", "firstElement", ")", ";", "}", "}", "return", "deferred", ".", "resolve", "(", "null", ")", ";", "}", ",", "// failure", "function", "(", "e", ")", "{", "return", "q", ".", "reject", "(", "e", ")", ";", "}", ")", ";", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Retrieve a piece of data from a named collection whose key is the one provided. @param collectionID @param key
[ "Retrieve", "a", "piece", "of", "data", "from", "a", "named", "collection", "whose", "key", "is", "the", "one", "provided", "." ]
e61374ba629159d69e0239e1fe7f609c8654dc32
https://github.com/jivesoftware/jive-persistence-sqlite/blob/e61374ba629159d69e0239e1fe7f609c8654dc32/sqlite-dynamic.js#L308-L337
56,077
jivesoftware/jive-persistence-sqlite
sqlite-dynamic.js
function( collectionID, key ) { collectionID = collectionID.toLowerCase(); var deferred = q.defer(); // acquire a connection from the pool db.getClient().then( function(dbClient) { if ( !dbClient ) { throw Error("Failed to acquire sqlite client"); } // start a transaction using the acquired db connection startTx(dbClient) .then( function() { var sql = sqlAdaptor.createDeleteSQL(collectionID, key); return query(dbClient, sql); }) // commit the transaction if no problems are encountered, this should also close the acquired db client // and return it to the connection pool .then( function(r) { return commitTx(dbClient).then( function() { deferred.resolve(r); } ); }) // ultimately rollback if there is any upstream thrown exception caught .catch( function(e) { return rollbackTx(dbClient, e).finally( function() { deferred.reject(e); }); }) // always try to release the client, if it exists .finally(function() { if ( dbClient ) { // always try to release the client, if it exists dbClient.release(); } }); }) // failed to acquire the client .fail( function(e) { deferred.reject(e); }); return deferred.promise; }
javascript
function( collectionID, key ) { collectionID = collectionID.toLowerCase(); var deferred = q.defer(); // acquire a connection from the pool db.getClient().then( function(dbClient) { if ( !dbClient ) { throw Error("Failed to acquire sqlite client"); } // start a transaction using the acquired db connection startTx(dbClient) .then( function() { var sql = sqlAdaptor.createDeleteSQL(collectionID, key); return query(dbClient, sql); }) // commit the transaction if no problems are encountered, this should also close the acquired db client // and return it to the connection pool .then( function(r) { return commitTx(dbClient).then( function() { deferred.resolve(r); } ); }) // ultimately rollback if there is any upstream thrown exception caught .catch( function(e) { return rollbackTx(dbClient, e).finally( function() { deferred.reject(e); }); }) // always try to release the client, if it exists .finally(function() { if ( dbClient ) { // always try to release the client, if it exists dbClient.release(); } }); }) // failed to acquire the client .fail( function(e) { deferred.reject(e); }); return deferred.promise; }
[ "function", "(", "collectionID", ",", "key", ")", "{", "collectionID", "=", "collectionID", ".", "toLowerCase", "(", ")", ";", "var", "deferred", "=", "q", ".", "defer", "(", ")", ";", "// acquire a connection from the pool", "db", ".", "getClient", "(", ")", ".", "then", "(", "function", "(", "dbClient", ")", "{", "if", "(", "!", "dbClient", ")", "{", "throw", "Error", "(", "\"Failed to acquire sqlite client\"", ")", ";", "}", "// start a transaction using the acquired db connection", "startTx", "(", "dbClient", ")", ".", "then", "(", "function", "(", ")", "{", "var", "sql", "=", "sqlAdaptor", ".", "createDeleteSQL", "(", "collectionID", ",", "key", ")", ";", "return", "query", "(", "dbClient", ",", "sql", ")", ";", "}", ")", "// commit the transaction if no problems are encountered, this should also close the acquired db client", "// and return it to the connection pool", ".", "then", "(", "function", "(", "r", ")", "{", "return", "commitTx", "(", "dbClient", ")", ".", "then", "(", "function", "(", ")", "{", "deferred", ".", "resolve", "(", "r", ")", ";", "}", ")", ";", "}", ")", "// ultimately rollback if there is any upstream thrown exception caught", ".", "catch", "(", "function", "(", "e", ")", "{", "return", "rollbackTx", "(", "dbClient", ",", "e", ")", ".", "finally", "(", "function", "(", ")", "{", "deferred", ".", "reject", "(", "e", ")", ";", "}", ")", ";", "}", ")", "// always try to release the client, if it exists", ".", "finally", "(", "function", "(", ")", "{", "if", "(", "dbClient", ")", "{", "// always try to release the client, if it exists", "dbClient", ".", "release", "(", ")", ";", "}", "}", ")", ";", "}", ")", "// failed to acquire the client", ".", "fail", "(", "function", "(", "e", ")", "{", "deferred", ".", "reject", "(", "e", ")", ";", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Remove a piece of data from a name collection, based to the provided key, return promise containing removed items when done. If no key is provided, all the data from the collection is removed. Is transactional - will rollback on error. @param collectionID @param key
[ "Remove", "a", "piece", "of", "data", "from", "a", "name", "collection", "based", "to", "the", "provided", "key", "return", "promise", "containing", "removed", "items", "when", "done", ".", "If", "no", "key", "is", "provided", "all", "the", "data", "from", "the", "collection", "is", "removed", ".", "Is", "transactional", "-", "will", "rollback", "on", "error", "." ]
e61374ba629159d69e0239e1fe7f609c8654dc32
https://github.com/jivesoftware/jive-persistence-sqlite/blob/e61374ba629159d69e0239e1fe7f609c8654dc32/sqlite-dynamic.js#L347-L396
56,078
yanni4night/jsdoc
src/jsdoc.js
Comment
function Comment() { this.type = 'func'; //func or attr this.descs = []; this.attr = { name: null }; this.func = { name: null, params: null }; this.clazz = null; //class this.zuper = null; //super this.tags = { /* name:[val1,val2] */ }; }
javascript
function Comment() { this.type = 'func'; //func or attr this.descs = []; this.attr = { name: null }; this.func = { name: null, params: null }; this.clazz = null; //class this.zuper = null; //super this.tags = { /* name:[val1,val2] */ }; }
[ "function", "Comment", "(", ")", "{", "this", ".", "type", "=", "'func'", ";", "//func or attr", "this", ".", "descs", "=", "[", "]", ";", "this", ".", "attr", "=", "{", "name", ":", "null", "}", ";", "this", ".", "func", "=", "{", "name", ":", "null", ",", "params", ":", "null", "}", ";", "this", ".", "clazz", "=", "null", ";", "//class", "this", ".", "zuper", "=", "null", ";", "//super", "this", ".", "tags", "=", "{", "/*\n name:[val1,val2]\n */", "}", ";", "}" ]
Comment is a block of source comemnt. As comment is only for function(class) and attribute, so we define a type which indicates what type it is. For different,'attr'/'func' saves the real payload data. @class @since 0.1.0 @version 0.1.0
[ "Comment", "is", "a", "block", "of", "source", "comemnt", "." ]
76a0804cfc96b267061079bb80d337a7ea9b029a
https://github.com/yanni4night/jsdoc/blob/76a0804cfc96b267061079bb80d337a7ea9b029a/src/jsdoc.js#L34-L53
56,079
yanni4night/jsdoc
src/jsdoc.js
function(name, value) { name = name.trim(); value = (value || "").trim(); switch (name) { //The following are single allowed. case 'return': case 'copyright': case 'author': case 'since': case 'description': case 'example': case 'version': case 'override': case 'todo': case 'type': case 'ignore': case 'deprecated': this.tags[name] = value; break; //The following are multiple allowed case 'param': case 'see': case 'throws': if (!Array.isArray(this.tags[name])) { this.tags[name] = [value]; } else { this.tags[name].push(value); } break; //The following are meaning stuff. case 'class': this.clazz = value; break; case 'extends': this.zuper = value; break; default: //ignore others } }
javascript
function(name, value) { name = name.trim(); value = (value || "").trim(); switch (name) { //The following are single allowed. case 'return': case 'copyright': case 'author': case 'since': case 'description': case 'example': case 'version': case 'override': case 'todo': case 'type': case 'ignore': case 'deprecated': this.tags[name] = value; break; //The following are multiple allowed case 'param': case 'see': case 'throws': if (!Array.isArray(this.tags[name])) { this.tags[name] = [value]; } else { this.tags[name].push(value); } break; //The following are meaning stuff. case 'class': this.clazz = value; break; case 'extends': this.zuper = value; break; default: //ignore others } }
[ "function", "(", "name", ",", "value", ")", "{", "name", "=", "name", ".", "trim", "(", ")", ";", "value", "=", "(", "value", "||", "\"\"", ")", ".", "trim", "(", ")", ";", "switch", "(", "name", ")", "{", "//The following are single allowed.", "case", "'return'", ":", "case", "'copyright'", ":", "case", "'author'", ":", "case", "'since'", ":", "case", "'description'", ":", "case", "'example'", ":", "case", "'version'", ":", "case", "'override'", ":", "case", "'todo'", ":", "case", "'type'", ":", "case", "'ignore'", ":", "case", "'deprecated'", ":", "this", ".", "tags", "[", "name", "]", "=", "value", ";", "break", ";", "//The following are multiple allowed", "case", "'param'", ":", "case", "'see'", ":", "case", "'throws'", ":", "if", "(", "!", "Array", ".", "isArray", "(", "this", ".", "tags", "[", "name", "]", ")", ")", "{", "this", ".", "tags", "[", "name", "]", "=", "[", "value", "]", ";", "}", "else", "{", "this", ".", "tags", "[", "name", "]", ".", "push", "(", "value", ")", ";", "}", "break", ";", "//The following are meaning stuff.", "case", "'class'", ":", "this", ".", "clazz", "=", "value", ";", "break", ";", "case", "'extends'", ":", "this", ".", "zuper", "=", "value", ";", "break", ";", "default", ":", "//ignore others", "}", "}" ]
Add a tag except 'class','extends' @param {String} name @param {String} value @class Comment @since 0.1.0
[ "Add", "a", "tag", "except", "class", "extends" ]
76a0804cfc96b267061079bb80d337a7ea9b029a
https://github.com/yanni4night/jsdoc/blob/76a0804cfc96b267061079bb80d337a7ea9b029a/src/jsdoc.js#L120-L159
56,080
yanni4night/jsdoc
src/jsdoc.js
SourceTextParser
function SourceTextParser(sourceText, classes, methods) { this.Comments = []; this.sourceText = sourceText; this.classes = classes; this.methods = methods; }
javascript
function SourceTextParser(sourceText, classes, methods) { this.Comments = []; this.sourceText = sourceText; this.classes = classes; this.methods = methods; }
[ "function", "SourceTextParser", "(", "sourceText", ",", "classes", ",", "methods", ")", "{", "this", ".", "Comments", "=", "[", "]", ";", "this", ".", "sourceText", "=", "sourceText", ";", "this", ".", "classes", "=", "classes", ";", "this", ".", "methods", "=", "methods", ";", "}" ]
Source text parser. @class @param {String} sourceText @param {Object} classes @param {Object} methods @since 0.1.0
[ "Source", "text", "parser", "." ]
76a0804cfc96b267061079bb80d337a7ea9b029a
https://github.com/yanni4night/jsdoc/blob/76a0804cfc96b267061079bb80d337a7ea9b029a/src/jsdoc.js#L193-L199
56,081
yanni4night/jsdoc
src/jsdoc.js
function() { var line, lines = this.sourceText.split(/\n/mg), lineLen = lines.length; var inCommenting, curComment, closeCommentIdx; for (var i = 0; i < lineLen; ++i) { line = lines[i].trim(); if (line.startsWith('/**')) { inCommenting = true; curComment = new Comment(); //Comment closed has to starts with "*/" } else if (line.startsWith('*/')) { inCommenting = false; closeCommentIdx = i; } else if (!inCommenting && (1 === i - closeCommentIdx) && /(\bfunction\b\s*?(\w+?)\s*\(([^\(\)]*)\))|((\w+)?\s*(?::|=)\s*function\s*\(([^\(\)]*)\))/.test(line)) { curComment.setFunc(RegExp.$2 || RegExp.$5, RegExp.$3 || RegExp.$6); if ('string' !== typeof curComment.getTag('ignore')) { this.Comments.push(curComment); } curComment = null; } else if (!inCommenting && (1 === i - closeCommentIdx) && /(\w+)\s*(?::|=)(?!\s*function)/.test(line)) { curComment.setAttr(RegExp.$1); if ('string' !== typeof curComment.getTag('ignore')) { this.Comments.push(curComment); } curComment = null; } else if (inCommenting) { line = line.replace(/^\*/, '').trim(); if (/^@(\w+)([^\r\n]*)/.test(line)) { curComment.addTag(RegExp.$1, RegExp.$2 || ""); } else { curComment.addDesc(line); } } } //for this._merge(); }
javascript
function() { var line, lines = this.sourceText.split(/\n/mg), lineLen = lines.length; var inCommenting, curComment, closeCommentIdx; for (var i = 0; i < lineLen; ++i) { line = lines[i].trim(); if (line.startsWith('/**')) { inCommenting = true; curComment = new Comment(); //Comment closed has to starts with "*/" } else if (line.startsWith('*/')) { inCommenting = false; closeCommentIdx = i; } else if (!inCommenting && (1 === i - closeCommentIdx) && /(\bfunction\b\s*?(\w+?)\s*\(([^\(\)]*)\))|((\w+)?\s*(?::|=)\s*function\s*\(([^\(\)]*)\))/.test(line)) { curComment.setFunc(RegExp.$2 || RegExp.$5, RegExp.$3 || RegExp.$6); if ('string' !== typeof curComment.getTag('ignore')) { this.Comments.push(curComment); } curComment = null; } else if (!inCommenting && (1 === i - closeCommentIdx) && /(\w+)\s*(?::|=)(?!\s*function)/.test(line)) { curComment.setAttr(RegExp.$1); if ('string' !== typeof curComment.getTag('ignore')) { this.Comments.push(curComment); } curComment = null; } else if (inCommenting) { line = line.replace(/^\*/, '').trim(); if (/^@(\w+)([^\r\n]*)/.test(line)) { curComment.addTag(RegExp.$1, RegExp.$2 || ""); } else { curComment.addDesc(line); } } } //for this._merge(); }
[ "function", "(", ")", "{", "var", "line", ",", "lines", "=", "this", ".", "sourceText", ".", "split", "(", "/", "\\n", "/", "mg", ")", ",", "lineLen", "=", "lines", ".", "length", ";", "var", "inCommenting", ",", "curComment", ",", "closeCommentIdx", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lineLen", ";", "++", "i", ")", "{", "line", "=", "lines", "[", "i", "]", ".", "trim", "(", ")", ";", "if", "(", "line", ".", "startsWith", "(", "'/**'", ")", ")", "{", "inCommenting", "=", "true", ";", "curComment", "=", "new", "Comment", "(", ")", ";", "//Comment closed has to starts with \"*/\"", "}", "else", "if", "(", "line", ".", "startsWith", "(", "'*/'", ")", ")", "{", "inCommenting", "=", "false", ";", "closeCommentIdx", "=", "i", ";", "}", "else", "if", "(", "!", "inCommenting", "&&", "(", "1", "===", "i", "-", "closeCommentIdx", ")", "&&", "/", "(\\bfunction\\b\\s*?(\\w+?)\\s*\\(([^\\(\\)]*)\\))|((\\w+)?\\s*(?::|=)\\s*function\\s*\\(([^\\(\\)]*)\\))", "/", ".", "test", "(", "line", ")", ")", "{", "curComment", ".", "setFunc", "(", "RegExp", ".", "$2", "||", "RegExp", ".", "$5", ",", "RegExp", ".", "$3", "||", "RegExp", ".", "$6", ")", ";", "if", "(", "'string'", "!==", "typeof", "curComment", ".", "getTag", "(", "'ignore'", ")", ")", "{", "this", ".", "Comments", ".", "push", "(", "curComment", ")", ";", "}", "curComment", "=", "null", ";", "}", "else", "if", "(", "!", "inCommenting", "&&", "(", "1", "===", "i", "-", "closeCommentIdx", ")", "&&", "/", "(\\w+)\\s*(?::|=)(?!\\s*function)", "/", ".", "test", "(", "line", ")", ")", "{", "curComment", ".", "setAttr", "(", "RegExp", ".", "$1", ")", ";", "if", "(", "'string'", "!==", "typeof", "curComment", ".", "getTag", "(", "'ignore'", ")", ")", "{", "this", ".", "Comments", ".", "push", "(", "curComment", ")", ";", "}", "curComment", "=", "null", ";", "}", "else", "if", "(", "inCommenting", ")", "{", "line", "=", "line", ".", "replace", "(", "/", "^\\*", "/", ",", "''", ")", ".", "trim", "(", ")", ";", "if", "(", "/", "^@(\\w+)([^\\r\\n]*)", "/", ".", "test", "(", "line", ")", ")", "{", "curComment", ".", "addTag", "(", "RegExp", ".", "$1", ",", "RegExp", ".", "$2", "||", "\"\"", ")", ";", "}", "else", "{", "curComment", ".", "addDesc", "(", "line", ")", ";", "}", "}", "}", "//for", "this", ".", "_merge", "(", ")", ";", "}" ]
Parse the source text to Comment structure. @since 0.1.0 @class SourceTextParser @return {Undefined}
[ "Parse", "the", "source", "text", "to", "Comment", "structure", "." ]
76a0804cfc96b267061079bb80d337a7ea9b029a
https://github.com/yanni4night/jsdoc/blob/76a0804cfc96b267061079bb80d337a7ea9b029a/src/jsdoc.js#L209-L248
56,082
mode777/page-gen
js/index.js
createPage
function createPage(filename) { let page = { path: filename, rawContent: fs.readFileSync(filename, "utf8"), name: path.basename(filename).replace(/\.[^/.]+$/, ""), filename: path.basename(filename), folder: path.dirname(filename), ext: path.extname(filename), userData: {} }; page.isMarkdown = page.ext.toLocaleUpperCase() == ".MD"; if (page.isMarkdown) page.ext = ".html"; page.template = doT.template(page.rawContent, null, page.userData); page.outPath = path.join(path.relative(CONTENT, page.folder), page.name + page.ext); page.href = CONFIG.prefix + page.outPath; return page; }
javascript
function createPage(filename) { let page = { path: filename, rawContent: fs.readFileSync(filename, "utf8"), name: path.basename(filename).replace(/\.[^/.]+$/, ""), filename: path.basename(filename), folder: path.dirname(filename), ext: path.extname(filename), userData: {} }; page.isMarkdown = page.ext.toLocaleUpperCase() == ".MD"; if (page.isMarkdown) page.ext = ".html"; page.template = doT.template(page.rawContent, null, page.userData); page.outPath = path.join(path.relative(CONTENT, page.folder), page.name + page.ext); page.href = CONFIG.prefix + page.outPath; return page; }
[ "function", "createPage", "(", "filename", ")", "{", "let", "page", "=", "{", "path", ":", "filename", ",", "rawContent", ":", "fs", ".", "readFileSync", "(", "filename", ",", "\"utf8\"", ")", ",", "name", ":", "path", ".", "basename", "(", "filename", ")", ".", "replace", "(", "/", "\\.[^/.]+$", "/", ",", "\"\"", ")", ",", "filename", ":", "path", ".", "basename", "(", "filename", ")", ",", "folder", ":", "path", ".", "dirname", "(", "filename", ")", ",", "ext", ":", "path", ".", "extname", "(", "filename", ")", ",", "userData", ":", "{", "}", "}", ";", "page", ".", "isMarkdown", "=", "page", ".", "ext", ".", "toLocaleUpperCase", "(", ")", "==", "\".MD\"", ";", "if", "(", "page", ".", "isMarkdown", ")", "page", ".", "ext", "=", "\".html\"", ";", "page", ".", "template", "=", "doT", ".", "template", "(", "page", ".", "rawContent", ",", "null", ",", "page", ".", "userData", ")", ";", "page", ".", "outPath", "=", "path", ".", "join", "(", "path", ".", "relative", "(", "CONTENT", ",", "page", ".", "folder", ")", ",", "page", ".", "name", "+", "page", ".", "ext", ")", ";", "page", ".", "href", "=", "CONFIG", ".", "prefix", "+", "page", ".", "outPath", ";", "return", "page", ";", "}" ]
Create page-templates
[ "Create", "page", "-", "templates" ]
bf7e15187f12f554c46c9a2b9759a97bd5220721
https://github.com/mode777/page-gen/blob/bf7e15187f12f554c46c9a2b9759a97bd5220721/js/index.js#L74-L91
56,083
kmalakoff/knockback-inspector
vendor/backbone-relational-0.6.0.js
function( model ) { model.unbind( 'destroy', this.unregister ); var coll = this.getCollection( model ); coll && coll.remove( model ); }
javascript
function( model ) { model.unbind( 'destroy', this.unregister ); var coll = this.getCollection( model ); coll && coll.remove( model ); }
[ "function", "(", "model", ")", "{", "model", ".", "unbind", "(", "'destroy'", ",", "this", ".", "unregister", ")", ";", "var", "coll", "=", "this", ".", "getCollection", "(", "model", ")", ";", "coll", "&&", "coll", ".", "remove", "(", "model", ")", ";", "}" ]
Remove a 'model' from the store. @param {Backbone.RelationalModel} model
[ "Remove", "a", "model", "from", "the", "store", "." ]
9c3f6dbdc490c8a799e199f1925485055fccac42
https://github.com/kmalakoff/knockback-inspector/blob/9c3f6dbdc490c8a799e199f1925485055fccac42/vendor/backbone-relational-0.6.0.js#L367-L371
56,084
kmalakoff/knockback-inspector
vendor/backbone-relational-0.6.0.js
function( collection ) { if ( this.related ) { this.related .unbind( 'relational:add', this.handleAddition ) .unbind( 'relational:remove', this.handleRemoval ) .unbind( 'relational:reset', this.handleReset ) } if ( !collection || !( collection instanceof Backbone.Collection ) ) { collection = new this.collectionType( [], this._getCollectionOptions() ); } collection.model = this.relatedModel; if ( this.options.collectionKey ) { var key = this.options.collectionKey === true ? this.options.reverseRelation.key : this.options.collectionKey; if ( collection[ key ] && collection[ key ] !== this.instance ) { if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) { console.warn( 'Relation=%o; collectionKey=%s already exists on collection=%o', this, key, this.options.collectionKey ); } } else if ( key ) { collection[ key ] = this.instance; } } collection .bind( 'relational:add', this.handleAddition ) .bind( 'relational:remove', this.handleRemoval ) .bind( 'relational:reset', this.handleReset ); return collection; }
javascript
function( collection ) { if ( this.related ) { this.related .unbind( 'relational:add', this.handleAddition ) .unbind( 'relational:remove', this.handleRemoval ) .unbind( 'relational:reset', this.handleReset ) } if ( !collection || !( collection instanceof Backbone.Collection ) ) { collection = new this.collectionType( [], this._getCollectionOptions() ); } collection.model = this.relatedModel; if ( this.options.collectionKey ) { var key = this.options.collectionKey === true ? this.options.reverseRelation.key : this.options.collectionKey; if ( collection[ key ] && collection[ key ] !== this.instance ) { if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) { console.warn( 'Relation=%o; collectionKey=%s already exists on collection=%o', this, key, this.options.collectionKey ); } } else if ( key ) { collection[ key ] = this.instance; } } collection .bind( 'relational:add', this.handleAddition ) .bind( 'relational:remove', this.handleRemoval ) .bind( 'relational:reset', this.handleReset ); return collection; }
[ "function", "(", "collection", ")", "{", "if", "(", "this", ".", "related", ")", "{", "this", ".", "related", ".", "unbind", "(", "'relational:add'", ",", "this", ".", "handleAddition", ")", ".", "unbind", "(", "'relational:remove'", ",", "this", ".", "handleRemoval", ")", ".", "unbind", "(", "'relational:reset'", ",", "this", ".", "handleReset", ")", "}", "if", "(", "!", "collection", "||", "!", "(", "collection", "instanceof", "Backbone", ".", "Collection", ")", ")", "{", "collection", "=", "new", "this", ".", "collectionType", "(", "[", "]", ",", "this", ".", "_getCollectionOptions", "(", ")", ")", ";", "}", "collection", ".", "model", "=", "this", ".", "relatedModel", ";", "if", "(", "this", ".", "options", ".", "collectionKey", ")", "{", "var", "key", "=", "this", ".", "options", ".", "collectionKey", "===", "true", "?", "this", ".", "options", ".", "reverseRelation", ".", "key", ":", "this", ".", "options", ".", "collectionKey", ";", "if", "(", "collection", "[", "key", "]", "&&", "collection", "[", "key", "]", "!==", "this", ".", "instance", ")", "{", "if", "(", "Backbone", ".", "Relational", ".", "showWarnings", "&&", "typeof", "console", "!==", "'undefined'", ")", "{", "console", ".", "warn", "(", "'Relation=%o; collectionKey=%s already exists on collection=%o'", ",", "this", ",", "key", ",", "this", ".", "options", ".", "collectionKey", ")", ";", "}", "}", "else", "if", "(", "key", ")", "{", "collection", "[", "key", "]", "=", "this", ".", "instance", ";", "}", "}", "collection", ".", "bind", "(", "'relational:add'", ",", "this", ".", "handleAddition", ")", ".", "bind", "(", "'relational:remove'", ",", "this", ".", "handleRemoval", ")", ".", "bind", "(", "'relational:reset'", ",", "this", ".", "handleReset", ")", ";", "return", "collection", ";", "}" ]
Bind events and setup collectionKeys for a collection that is to be used as the backing store for a HasMany. If no 'collection' is supplied, a new collection will be created of the specified 'collectionType' option. @param {Backbone.Collection} [collection]
[ "Bind", "events", "and", "setup", "collectionKeys", "for", "a", "collection", "that", "is", "to", "be", "used", "as", "the", "backing", "store", "for", "a", "HasMany", ".", "If", "no", "collection", "is", "supplied", "a", "new", "collection", "will", "be", "created", "of", "the", "specified", "collectionType", "option", "." ]
9c3f6dbdc490c8a799e199f1925485055fccac42
https://github.com/kmalakoff/knockback-inspector/blob/9c3f6dbdc490c8a799e199f1925485055fccac42/vendor/backbone-relational-0.6.0.js#L804-L837
56,085
kmalakoff/knockback-inspector
vendor/backbone-relational-0.6.0.js
function( attributes, options ) { var model = this; // 'build' is a possible entrypoint; it's possible no model hierarchy has been determined yet. this.initializeModelHierarchy(); // Determine what type of (sub)model should be built if applicable. // Lookup the proper subModelType in 'this._subModels'. if ( this._subModels && this.prototype.subModelTypeAttribute in attributes ) { var subModelTypeAttribute = attributes[ this.prototype.subModelTypeAttribute ]; var subModelType = this._subModels[ subModelTypeAttribute ]; if ( subModelType ) { model = subModelType; } } return new model( attributes, options ); }
javascript
function( attributes, options ) { var model = this; // 'build' is a possible entrypoint; it's possible no model hierarchy has been determined yet. this.initializeModelHierarchy(); // Determine what type of (sub)model should be built if applicable. // Lookup the proper subModelType in 'this._subModels'. if ( this._subModels && this.prototype.subModelTypeAttribute in attributes ) { var subModelTypeAttribute = attributes[ this.prototype.subModelTypeAttribute ]; var subModelType = this._subModels[ subModelTypeAttribute ]; if ( subModelType ) { model = subModelType; } } return new model( attributes, options ); }
[ "function", "(", "attributes", ",", "options", ")", "{", "var", "model", "=", "this", ";", "// 'build' is a possible entrypoint; it's possible no model hierarchy has been determined yet.", "this", ".", "initializeModelHierarchy", "(", ")", ";", "// Determine what type of (sub)model should be built if applicable.", "// Lookup the proper subModelType in 'this._subModels'.", "if", "(", "this", ".", "_subModels", "&&", "this", ".", "prototype", ".", "subModelTypeAttribute", "in", "attributes", ")", "{", "var", "subModelTypeAttribute", "=", "attributes", "[", "this", ".", "prototype", ".", "subModelTypeAttribute", "]", ";", "var", "subModelType", "=", "this", ".", "_subModels", "[", "subModelTypeAttribute", "]", ";", "if", "(", "subModelType", ")", "{", "model", "=", "subModelType", ";", "}", "}", "return", "new", "model", "(", "attributes", ",", "options", ")", ";", "}" ]
Create a 'Backbone.Model' instance based on 'attributes'. @param {Object} attributes @param {Object} [options] @return {Backbone.Model}
[ "Create", "a", "Backbone", ".", "Model", "instance", "based", "on", "attributes", "." ]
9c3f6dbdc490c8a799e199f1925485055fccac42
https://github.com/kmalakoff/knockback-inspector/blob/9c3f6dbdc490c8a799e199f1925485055fccac42/vendor/backbone-relational-0.6.0.js#L1450-L1467
56,086
ReaxDev/accessible-bootstrap3
index.js
function (element) { var event = document.createEvent('MouseEvents'); event.initMouseEvent('mousedown', true, true, window); element.dispatchEvent(event); }
javascript
function (element) { var event = document.createEvent('MouseEvents'); event.initMouseEvent('mousedown', true, true, window); element.dispatchEvent(event); }
[ "function", "(", "element", ")", "{", "var", "event", "=", "document", ".", "createEvent", "(", "'MouseEvents'", ")", ";", "event", ".", "initMouseEvent", "(", "'mousedown'", ",", "true", ",", "true", ",", "window", ")", ";", "element", ".", "dispatchEvent", "(", "event", ")", ";", "}" ]
click element with virtual mouse.
[ "click", "element", "with", "virtual", "mouse", "." ]
7a9c0c904f27a0524d6e1c53deacdd6437a6837d
https://github.com/ReaxDev/accessible-bootstrap3/blob/7a9c0c904f27a0524d6e1c53deacdd6437a6837d/index.js#L160-L164
56,087
ReaxDev/accessible-bootstrap3
index.js
function(event) { var inputs = $(event.target).parents("form").eq(0).find(":input:visible"); var inputIndex = inputs.index(event.target); // If at end of focusable elements return false, if not move forward one. if (inputIndex == inputs.length - 1) { // return false on last form input so we know to let the form submit. return false } else {inputs[inputIndex + 1].focus();} }
javascript
function(event) { var inputs = $(event.target).parents("form").eq(0).find(":input:visible"); var inputIndex = inputs.index(event.target); // If at end of focusable elements return false, if not move forward one. if (inputIndex == inputs.length - 1) { // return false on last form input so we know to let the form submit. return false } else {inputs[inputIndex + 1].focus();} }
[ "function", "(", "event", ")", "{", "var", "inputs", "=", "$", "(", "event", ".", "target", ")", ".", "parents", "(", "\"form\"", ")", ".", "eq", "(", "0", ")", ".", "find", "(", "\":input:visible\"", ")", ";", "var", "inputIndex", "=", "inputs", ".", "index", "(", "event", ".", "target", ")", ";", "// If at end of focusable elements return false, if not move forward one.", "if", "(", "inputIndex", "==", "inputs", ".", "length", "-", "1", ")", "{", "// return false on last form input so we know to let the form submit.", "return", "false", "}", "else", "{", "inputs", "[", "inputIndex", "+", "1", "]", ".", "focus", "(", ")", ";", "}", "}" ]
Move tab index forward one input inside the form an event originates.
[ "Move", "tab", "index", "forward", "one", "input", "inside", "the", "form", "an", "event", "originates", "." ]
7a9c0c904f27a0524d6e1c53deacdd6437a6837d
https://github.com/ReaxDev/accessible-bootstrap3/blob/7a9c0c904f27a0524d6e1c53deacdd6437a6837d/index.js#L167-L175
56,088
robzolkos/courier_finder
couriers/australia_post/index.js
valid
function valid(connote) { if (typeof connote != "string") { return false; } connote = connote.trim().toUpperCase(); // handle 14 character couriers please if (connote.length === 14 && connote.indexOf("CP") === 0) { return false; } return [10, 14, 18, 21, 39, 40].indexOf(connote.length) != -1; }
javascript
function valid(connote) { if (typeof connote != "string") { return false; } connote = connote.trim().toUpperCase(); // handle 14 character couriers please if (connote.length === 14 && connote.indexOf("CP") === 0) { return false; } return [10, 14, 18, 21, 39, 40].indexOf(connote.length) != -1; }
[ "function", "valid", "(", "connote", ")", "{", "if", "(", "typeof", "connote", "!=", "\"string\"", ")", "{", "return", "false", ";", "}", "connote", "=", "connote", ".", "trim", "(", ")", ".", "toUpperCase", "(", ")", ";", "// handle 14 character couriers please", "if", "(", "connote", ".", "length", "===", "14", "&&", "connote", ".", "indexOf", "(", "\"CP\"", ")", "===", "0", ")", "{", "return", "false", ";", "}", "return", "[", "10", ",", "14", ",", "18", ",", "21", ",", "39", ",", "40", "]", ".", "indexOf", "(", "connote", ".", "length", ")", "!=", "-", "1", ";", "}" ]
AustraliaPost connotes are various lengths
[ "AustraliaPost", "connotes", "are", "various", "lengths" ]
b5e5d43ce3329569270fb0e7765d49697ba25e87
https://github.com/robzolkos/courier_finder/blob/b5e5d43ce3329569270fb0e7765d49697ba25e87/couriers/australia_post/index.js#L6-L19
56,089
mayanklahiri/node-runtype
lib/enforce.js
enforce
function enforce(targetFunction) { assert(_.isFunction(targetFunction), 'argument to wrap must be a function'); assert( _.isObject(targetFunction.$schema), `Function "${targetFunction.name}" has no $schema property.`); assert( _.isArray(targetFunction.$schema.arguments), `Function "${targetFunction.name}" has an invalid $schema.arguments property.`); assert( _.isArray(targetFunction.$schema.callbackResult), `Function "${targetFunction.name}" has an invalid ` + '$schema.callbackResult property.'); const fnName = _.toString(targetFunction.name); // Return wrapped function, executes in a new context.. const wrappedFunc = function wrappedFunc(...args) { if (!args.length) { throw new Error( `Function "${fnName}" invoked without arguments, callback required.`); } // // Splice callback out of arguments array. // let originalCb = _.last(args); assert( _.isFunction(originalCb), `Function "${fnName}" requires a callback function as its last argument.`); args.splice(args.length - 1, 1); originalCb = _.once(originalCb); // // Type-check arguments against "arguments" schema, invoke callback with // schema validation errors. This will throw its own errors. // const schemaArgs = { type: 'array', elements: targetFunction.$schema.arguments, }; try { construct(schemaArgs, args); } catch (e) { return originalCb(new Error( `Function "${fnName}" called with invalid arguments: ${e.message}`)); } // // Replace callback argument with an intercepting callback function. // args.push((...resultArray) => { const err = resultArray.length ? resultArray[0] : undefined; const results = resultArray.slice(1); if (err) { // Pass errors through unfiltered. return originalCb(err); } // Type-check results, these must be passed to the callback, since they // cannot be thrown. const schemaCbResult = { type: 'array', elements: targetFunction.$schema.callbackResult, }; try { construct(schemaCbResult, results); } catch (e) { return originalCb(new Error( `Function "${fnName}" invoked its callback with invalid arguments: ` + `${e.message}`)); } // Success, invoke original callback with results. return originalCb(...resultArray); }); // // Invoke target function, pass exceptions to callback. // let rv; try { rv = targetFunction.call(this, ...args); } catch (e) { return originalCb(e); } return rv; }; wrappedFunc.$schema = targetFunction.$schema; return wrappedFunc; }
javascript
function enforce(targetFunction) { assert(_.isFunction(targetFunction), 'argument to wrap must be a function'); assert( _.isObject(targetFunction.$schema), `Function "${targetFunction.name}" has no $schema property.`); assert( _.isArray(targetFunction.$schema.arguments), `Function "${targetFunction.name}" has an invalid $schema.arguments property.`); assert( _.isArray(targetFunction.$schema.callbackResult), `Function "${targetFunction.name}" has an invalid ` + '$schema.callbackResult property.'); const fnName = _.toString(targetFunction.name); // Return wrapped function, executes in a new context.. const wrappedFunc = function wrappedFunc(...args) { if (!args.length) { throw new Error( `Function "${fnName}" invoked without arguments, callback required.`); } // // Splice callback out of arguments array. // let originalCb = _.last(args); assert( _.isFunction(originalCb), `Function "${fnName}" requires a callback function as its last argument.`); args.splice(args.length - 1, 1); originalCb = _.once(originalCb); // // Type-check arguments against "arguments" schema, invoke callback with // schema validation errors. This will throw its own errors. // const schemaArgs = { type: 'array', elements: targetFunction.$schema.arguments, }; try { construct(schemaArgs, args); } catch (e) { return originalCb(new Error( `Function "${fnName}" called with invalid arguments: ${e.message}`)); } // // Replace callback argument with an intercepting callback function. // args.push((...resultArray) => { const err = resultArray.length ? resultArray[0] : undefined; const results = resultArray.slice(1); if (err) { // Pass errors through unfiltered. return originalCb(err); } // Type-check results, these must be passed to the callback, since they // cannot be thrown. const schemaCbResult = { type: 'array', elements: targetFunction.$schema.callbackResult, }; try { construct(schemaCbResult, results); } catch (e) { return originalCb(new Error( `Function "${fnName}" invoked its callback with invalid arguments: ` + `${e.message}`)); } // Success, invoke original callback with results. return originalCb(...resultArray); }); // // Invoke target function, pass exceptions to callback. // let rv; try { rv = targetFunction.call(this, ...args); } catch (e) { return originalCb(e); } return rv; }; wrappedFunc.$schema = targetFunction.$schema; return wrappedFunc; }
[ "function", "enforce", "(", "targetFunction", ")", "{", "assert", "(", "_", ".", "isFunction", "(", "targetFunction", ")", ",", "'argument to wrap must be a function'", ")", ";", "assert", "(", "_", ".", "isObject", "(", "targetFunction", ".", "$schema", ")", ",", "`", "${", "targetFunction", ".", "name", "}", "`", ")", ";", "assert", "(", "_", ".", "isArray", "(", "targetFunction", ".", "$schema", ".", "arguments", ")", ",", "`", "${", "targetFunction", ".", "name", "}", "`", ")", ";", "assert", "(", "_", ".", "isArray", "(", "targetFunction", ".", "$schema", ".", "callbackResult", ")", ",", "`", "${", "targetFunction", ".", "name", "}", "`", "+", "'$schema.callbackResult property.'", ")", ";", "const", "fnName", "=", "_", ".", "toString", "(", "targetFunction", ".", "name", ")", ";", "// Return wrapped function, executes in a new context..", "const", "wrappedFunc", "=", "function", "wrappedFunc", "(", "...", "args", ")", "{", "if", "(", "!", "args", ".", "length", ")", "{", "throw", "new", "Error", "(", "`", "${", "fnName", "}", "`", ")", ";", "}", "//", "// Splice callback out of arguments array.", "//", "let", "originalCb", "=", "_", ".", "last", "(", "args", ")", ";", "assert", "(", "_", ".", "isFunction", "(", "originalCb", ")", ",", "`", "${", "fnName", "}", "`", ")", ";", "args", ".", "splice", "(", "args", ".", "length", "-", "1", ",", "1", ")", ";", "originalCb", "=", "_", ".", "once", "(", "originalCb", ")", ";", "//", "// Type-check arguments against \"arguments\" schema, invoke callback with", "// schema validation errors. This will throw its own errors.", "//", "const", "schemaArgs", "=", "{", "type", ":", "'array'", ",", "elements", ":", "targetFunction", ".", "$schema", ".", "arguments", ",", "}", ";", "try", "{", "construct", "(", "schemaArgs", ",", "args", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "originalCb", "(", "new", "Error", "(", "`", "${", "fnName", "}", "${", "e", ".", "message", "}", "`", ")", ")", ";", "}", "//", "// Replace callback argument with an intercepting callback function.", "//", "args", ".", "push", "(", "(", "...", "resultArray", ")", "=>", "{", "const", "err", "=", "resultArray", ".", "length", "?", "resultArray", "[", "0", "]", ":", "undefined", ";", "const", "results", "=", "resultArray", ".", "slice", "(", "1", ")", ";", "if", "(", "err", ")", "{", "// Pass errors through unfiltered.", "return", "originalCb", "(", "err", ")", ";", "}", "// Type-check results, these must be passed to the callback, since they", "// cannot be thrown.", "const", "schemaCbResult", "=", "{", "type", ":", "'array'", ",", "elements", ":", "targetFunction", ".", "$schema", ".", "callbackResult", ",", "}", ";", "try", "{", "construct", "(", "schemaCbResult", ",", "results", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "originalCb", "(", "new", "Error", "(", "`", "${", "fnName", "}", "`", "+", "`", "${", "e", ".", "message", "}", "`", ")", ")", ";", "}", "// Success, invoke original callback with results.", "return", "originalCb", "(", "...", "resultArray", ")", ";", "}", ")", ";", "//", "// Invoke target function, pass exceptions to callback.", "//", "let", "rv", ";", "try", "{", "rv", "=", "targetFunction", ".", "call", "(", "this", ",", "...", "args", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "originalCb", "(", "e", ")", ";", "}", "return", "rv", ";", "}", ";", "wrappedFunc", ".", "$schema", "=", "targetFunction", ".", "$schema", ";", "return", "wrappedFunc", ";", "}" ]
Wraps an asychronous function with runtime type argument and return value type checking. @param {function} targetFunction The asynchronous function to wrap; its last argument must be a callback function. @return {function} An asynchronous function that will synchronously throw on argument errors, or pass a type-checking exception to the callback for asynchronous return type errors.
[ "Wraps", "an", "asychronous", "function", "with", "runtime", "type", "argument", "and", "return", "value", "type", "checking", "." ]
efcf457ae797535b0e6e98bbeac461e66327c88e
https://github.com/mayanklahiri/node-runtype/blob/efcf457ae797535b0e6e98bbeac461e66327c88e/lib/enforce.js#L16-L106
56,090
mayanklahiri/node-runtype
lib/enforce.js
wrappedFunc
function wrappedFunc(...args) { if (!args.length) { throw new Error( `Function "${fnName}" invoked without arguments, callback required.`); } // // Splice callback out of arguments array. // let originalCb = _.last(args); assert( _.isFunction(originalCb), `Function "${fnName}" requires a callback function as its last argument.`); args.splice(args.length - 1, 1); originalCb = _.once(originalCb); // // Type-check arguments against "arguments" schema, invoke callback with // schema validation errors. This will throw its own errors. // const schemaArgs = { type: 'array', elements: targetFunction.$schema.arguments, }; try { construct(schemaArgs, args); } catch (e) { return originalCb(new Error( `Function "${fnName}" called with invalid arguments: ${e.message}`)); } // // Replace callback argument with an intercepting callback function. // args.push((...resultArray) => { const err = resultArray.length ? resultArray[0] : undefined; const results = resultArray.slice(1); if (err) { // Pass errors through unfiltered. return originalCb(err); } // Type-check results, these must be passed to the callback, since they // cannot be thrown. const schemaCbResult = { type: 'array', elements: targetFunction.$schema.callbackResult, }; try { construct(schemaCbResult, results); } catch (e) { return originalCb(new Error( `Function "${fnName}" invoked its callback with invalid arguments: ` + `${e.message}`)); } // Success, invoke original callback with results. return originalCb(...resultArray); }); // // Invoke target function, pass exceptions to callback. // let rv; try { rv = targetFunction.call(this, ...args); } catch (e) { return originalCb(e); } return rv; }
javascript
function wrappedFunc(...args) { if (!args.length) { throw new Error( `Function "${fnName}" invoked without arguments, callback required.`); } // // Splice callback out of arguments array. // let originalCb = _.last(args); assert( _.isFunction(originalCb), `Function "${fnName}" requires a callback function as its last argument.`); args.splice(args.length - 1, 1); originalCb = _.once(originalCb); // // Type-check arguments against "arguments" schema, invoke callback with // schema validation errors. This will throw its own errors. // const schemaArgs = { type: 'array', elements: targetFunction.$schema.arguments, }; try { construct(schemaArgs, args); } catch (e) { return originalCb(new Error( `Function "${fnName}" called with invalid arguments: ${e.message}`)); } // // Replace callback argument with an intercepting callback function. // args.push((...resultArray) => { const err = resultArray.length ? resultArray[0] : undefined; const results = resultArray.slice(1); if (err) { // Pass errors through unfiltered. return originalCb(err); } // Type-check results, these must be passed to the callback, since they // cannot be thrown. const schemaCbResult = { type: 'array', elements: targetFunction.$schema.callbackResult, }; try { construct(schemaCbResult, results); } catch (e) { return originalCb(new Error( `Function "${fnName}" invoked its callback with invalid arguments: ` + `${e.message}`)); } // Success, invoke original callback with results. return originalCb(...resultArray); }); // // Invoke target function, pass exceptions to callback. // let rv; try { rv = targetFunction.call(this, ...args); } catch (e) { return originalCb(e); } return rv; }
[ "function", "wrappedFunc", "(", "...", "args", ")", "{", "if", "(", "!", "args", ".", "length", ")", "{", "throw", "new", "Error", "(", "`", "${", "fnName", "}", "`", ")", ";", "}", "//", "// Splice callback out of arguments array.", "//", "let", "originalCb", "=", "_", ".", "last", "(", "args", ")", ";", "assert", "(", "_", ".", "isFunction", "(", "originalCb", ")", ",", "`", "${", "fnName", "}", "`", ")", ";", "args", ".", "splice", "(", "args", ".", "length", "-", "1", ",", "1", ")", ";", "originalCb", "=", "_", ".", "once", "(", "originalCb", ")", ";", "//", "// Type-check arguments against \"arguments\" schema, invoke callback with", "// schema validation errors. This will throw its own errors.", "//", "const", "schemaArgs", "=", "{", "type", ":", "'array'", ",", "elements", ":", "targetFunction", ".", "$schema", ".", "arguments", ",", "}", ";", "try", "{", "construct", "(", "schemaArgs", ",", "args", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "originalCb", "(", "new", "Error", "(", "`", "${", "fnName", "}", "${", "e", ".", "message", "}", "`", ")", ")", ";", "}", "//", "// Replace callback argument with an intercepting callback function.", "//", "args", ".", "push", "(", "(", "...", "resultArray", ")", "=>", "{", "const", "err", "=", "resultArray", ".", "length", "?", "resultArray", "[", "0", "]", ":", "undefined", ";", "const", "results", "=", "resultArray", ".", "slice", "(", "1", ")", ";", "if", "(", "err", ")", "{", "// Pass errors through unfiltered.", "return", "originalCb", "(", "err", ")", ";", "}", "// Type-check results, these must be passed to the callback, since they", "// cannot be thrown.", "const", "schemaCbResult", "=", "{", "type", ":", "'array'", ",", "elements", ":", "targetFunction", ".", "$schema", ".", "callbackResult", ",", "}", ";", "try", "{", "construct", "(", "schemaCbResult", ",", "results", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "originalCb", "(", "new", "Error", "(", "`", "${", "fnName", "}", "`", "+", "`", "${", "e", ".", "message", "}", "`", ")", ")", ";", "}", "// Success, invoke original callback with results.", "return", "originalCb", "(", "...", "resultArray", ")", ";", "}", ")", ";", "//", "// Invoke target function, pass exceptions to callback.", "//", "let", "rv", ";", "try", "{", "rv", "=", "targetFunction", ".", "call", "(", "this", ",", "...", "args", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "originalCb", "(", "e", ")", ";", "}", "return", "rv", ";", "}" ]
Return wrapped function, executes in a new context..
[ "Return", "wrapped", "function", "executes", "in", "a", "new", "context", ".." ]
efcf457ae797535b0e6e98bbeac461e66327c88e
https://github.com/mayanklahiri/node-runtype/blob/efcf457ae797535b0e6e98bbeac461e66327c88e/lib/enforce.js#L31-L102
56,091
hl198181/neptune
misc/demo/public/vendor/angular-ui-tree/angular-ui-tree.js
countSubTreeDepth
function countSubTreeDepth(scope) { var thisLevelDepth = 0, childNodes = scope.childNodes(), childNode, childDepth, i; if (!childNodes || childNodes.length === 0) { return 0; } for (i = childNodes.length - 1; i >= 0 ; i--) { childNode = childNodes[i], childDepth = 1 + countSubTreeDepth(childNode); thisLevelDepth = Math.max(thisLevelDepth, childDepth); } return thisLevelDepth; }
javascript
function countSubTreeDepth(scope) { var thisLevelDepth = 0, childNodes = scope.childNodes(), childNode, childDepth, i; if (!childNodes || childNodes.length === 0) { return 0; } for (i = childNodes.length - 1; i >= 0 ; i--) { childNode = childNodes[i], childDepth = 1 + countSubTreeDepth(childNode); thisLevelDepth = Math.max(thisLevelDepth, childDepth); } return thisLevelDepth; }
[ "function", "countSubTreeDepth", "(", "scope", ")", "{", "var", "thisLevelDepth", "=", "0", ",", "childNodes", "=", "scope", ".", "childNodes", "(", ")", ",", "childNode", ",", "childDepth", ",", "i", ";", "if", "(", "!", "childNodes", "||", "childNodes", ".", "length", "===", "0", ")", "{", "return", "0", ";", "}", "for", "(", "i", "=", "childNodes", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "childNode", "=", "childNodes", "[", "i", "]", ",", "childDepth", "=", "1", "+", "countSubTreeDepth", "(", "childNode", ")", ";", "thisLevelDepth", "=", "Math", ".", "max", "(", "thisLevelDepth", ",", "childDepth", ")", ";", "}", "return", "thisLevelDepth", ";", "}" ]
Returns the depth of the deepest subtree under this node @param scope a TreeNodesController scope object @returns Depth of all nodes *beneath* this node. If scope belongs to a leaf node, the result is 0 (it has no subtree).
[ "Returns", "the", "depth", "of", "the", "deepest", "subtree", "under", "this", "node" ]
88030bb4222945900e6a225469380cc43a016c13
https://github.com/hl198181/neptune/blob/88030bb4222945900e6a225469380cc43a016c13/misc/demo/public/vendor/angular-ui-tree/angular-ui-tree.js#L162-L177
56,092
hl198181/neptune
misc/demo/public/vendor/angular-ui-tree/angular-ui-tree.js
function (parent, siblings, index) { this.parent = parent; this.siblings = siblings.slice(0); // If source node is in the target nodes var i = this.siblings.indexOf(this.source); if (i > -1) { this.siblings.splice(i, 1); if (this.source.index() < index) { index--; } } this.siblings.splice(index, 0, this.source); this.index = index; }
javascript
function (parent, siblings, index) { this.parent = parent; this.siblings = siblings.slice(0); // If source node is in the target nodes var i = this.siblings.indexOf(this.source); if (i > -1) { this.siblings.splice(i, 1); if (this.source.index() < index) { index--; } } this.siblings.splice(index, 0, this.source); this.index = index; }
[ "function", "(", "parent", ",", "siblings", ",", "index", ")", "{", "this", ".", "parent", "=", "parent", ";", "this", ".", "siblings", "=", "siblings", ".", "slice", "(", "0", ")", ";", "// If source node is in the target nodes", "var", "i", "=", "this", ".", "siblings", ".", "indexOf", "(", "this", ".", "source", ")", ";", "if", "(", "i", ">", "-", "1", ")", "{", "this", ".", "siblings", ".", "splice", "(", "i", ",", "1", ")", ";", "if", "(", "this", ".", "source", ".", "index", "(", ")", "<", "index", ")", "{", "index", "--", ";", "}", "}", "this", ".", "siblings", ".", "splice", "(", "index", ",", "0", ",", "this", ".", "source", ")", ";", "this", ".", "index", "=", "index", ";", "}" ]
Move the node to a new position
[ "Move", "the", "node", "to", "a", "new", "position" ]
88030bb4222945900e6a225469380cc43a016c13
https://github.com/hl198181/neptune/blob/88030bb4222945900e6a225469380cc43a016c13/misc/demo/public/vendor/angular-ui-tree/angular-ui-tree.js#L1181-L1196
56,093
mgesmundo/multicast-events
lib/multicast-events.js
encrypt
function encrypt(message) { if (this.secure && this.cipher && this.secret) { if (this.secret === 'secret') { console.warn('PLEASE change default secret password!'); } debug('%s encrypt message with %s', this.name, this.cipher); var cipher = crypto.createCipher(this.cipher, this.secret); return Buffer.concat([cipher.update(message), cipher.final()]); } return message; }
javascript
function encrypt(message) { if (this.secure && this.cipher && this.secret) { if (this.secret === 'secret') { console.warn('PLEASE change default secret password!'); } debug('%s encrypt message with %s', this.name, this.cipher); var cipher = crypto.createCipher(this.cipher, this.secret); return Buffer.concat([cipher.update(message), cipher.final()]); } return message; }
[ "function", "encrypt", "(", "message", ")", "{", "if", "(", "this", ".", "secure", "&&", "this", ".", "cipher", "&&", "this", ".", "secret", ")", "{", "if", "(", "this", ".", "secret", "===", "'secret'", ")", "{", "console", ".", "warn", "(", "'PLEASE change default secret password!'", ")", ";", "}", "debug", "(", "'%s encrypt message with %s'", ",", "this", ".", "name", ",", "this", ".", "cipher", ")", ";", "var", "cipher", "=", "crypto", ".", "createCipher", "(", "this", ".", "cipher", ",", "this", ".", "secret", ")", ";", "return", "Buffer", ".", "concat", "(", "[", "cipher", ".", "update", "(", "message", ")", ",", "cipher", ".", "final", "(", ")", "]", ")", ";", "}", "return", "message", ";", "}" ]
Encrypt a message @param {Buffer} message The message to encrypt @return {Buffer} The encrypted message @ignore
[ "Encrypt", "a", "message" ]
1e6d0a9828ec82ec5854af82c13ae9a7c554ff35
https://github.com/mgesmundo/multicast-events/blob/1e6d0a9828ec82ec5854af82c13ae9a7c554ff35/lib/multicast-events.js#L93-L103
56,094
mgesmundo/multicast-events
lib/multicast-events.js
decrypt
function decrypt(message) { if (this.secure && this.cipher && this.secret) { if (this.secret === 'secret') { console.warn('PLEASE change default secret password!'); } debug('%s decrypt message with %s', this.name, this.cipher); var decipher = crypto.createDecipher(this.cipher, this.secret); return Buffer.concat([decipher.update(message), decipher.final()]); } return message; }
javascript
function decrypt(message) { if (this.secure && this.cipher && this.secret) { if (this.secret === 'secret') { console.warn('PLEASE change default secret password!'); } debug('%s decrypt message with %s', this.name, this.cipher); var decipher = crypto.createDecipher(this.cipher, this.secret); return Buffer.concat([decipher.update(message), decipher.final()]); } return message; }
[ "function", "decrypt", "(", "message", ")", "{", "if", "(", "this", ".", "secure", "&&", "this", ".", "cipher", "&&", "this", ".", "secret", ")", "{", "if", "(", "this", ".", "secret", "===", "'secret'", ")", "{", "console", ".", "warn", "(", "'PLEASE change default secret password!'", ")", ";", "}", "debug", "(", "'%s decrypt message with %s'", ",", "this", ".", "name", ",", "this", ".", "cipher", ")", ";", "var", "decipher", "=", "crypto", ".", "createDecipher", "(", "this", ".", "cipher", ",", "this", ".", "secret", ")", ";", "return", "Buffer", ".", "concat", "(", "[", "decipher", ".", "update", "(", "message", ")", ",", "decipher", ".", "final", "(", ")", "]", ")", ";", "}", "return", "message", ";", "}" ]
Decrypt a message @param {Buffer} message The encrypted message @return {Buffer} The decrypted buffer @ignore
[ "Decrypt", "a", "message" ]
1e6d0a9828ec82ec5854af82c13ae9a7c554ff35
https://github.com/mgesmundo/multicast-events/blob/1e6d0a9828ec82ec5854af82c13ae9a7c554ff35/lib/multicast-events.js#L111-L121
56,095
mgesmundo/multicast-events
lib/multicast-events.js
verifyAddress
function verifyAddress(address) { var ifs = os.networkInterfaces(); var nics = Object.keys(ifs); var i, j, match = false; nicLoop: for (i = 0; i < nics.length; i++) { var nic = ifs[nics[i]]; for (j = 0; j < nic.length; j++) { if (nic[j].address === address && !nic[j].internal) { match = true; break nicLoop; } } } return match; }
javascript
function verifyAddress(address) { var ifs = os.networkInterfaces(); var nics = Object.keys(ifs); var i, j, match = false; nicLoop: for (i = 0; i < nics.length; i++) { var nic = ifs[nics[i]]; for (j = 0; j < nic.length; j++) { if (nic[j].address === address && !nic[j].internal) { match = true; break nicLoop; } } } return match; }
[ "function", "verifyAddress", "(", "address", ")", "{", "var", "ifs", "=", "os", ".", "networkInterfaces", "(", ")", ";", "var", "nics", "=", "Object", ".", "keys", "(", "ifs", ")", ";", "var", "i", ",", "j", ",", "match", "=", "false", ";", "nicLoop", ":", "for", "(", "i", "=", "0", ";", "i", "<", "nics", ".", "length", ";", "i", "++", ")", "{", "var", "nic", "=", "ifs", "[", "nics", "[", "i", "]", "]", ";", "for", "(", "j", "=", "0", ";", "j", "<", "nic", ".", "length", ";", "j", "++", ")", "{", "if", "(", "nic", "[", "j", "]", ".", "address", "===", "address", "&&", "!", "nic", "[", "j", "]", ".", "internal", ")", "{", "match", "=", "true", ";", "break", "nicLoop", ";", "}", "}", "}", "return", "match", ";", "}" ]
Verify that a provided address is configured on a NIC @param {String} address The address to verify @return {Boolean} True if the address is configured on a NIC
[ "Verify", "that", "a", "provided", "address", "is", "configured", "on", "a", "NIC" ]
1e6d0a9828ec82ec5854af82c13ae9a7c554ff35
https://github.com/mgesmundo/multicast-events/blob/1e6d0a9828ec82ec5854af82c13ae9a7c554ff35/lib/multicast-events.js#L148-L163
56,096
mnichols/ankh
lib/registrations.js
flatten
function flatten(arr) { return arr.reduce(function (flat, toFlatten) { // See if this index is an array that itself needs to be flattened. if(toFlatten.some && toFlatten.some(Array.isArray)) { return flat.concat(flatten(toFlatten)); // Otherwise just add the current index to the end of the flattened array. } else { return flat.concat(toFlatten); } }, []); }
javascript
function flatten(arr) { return arr.reduce(function (flat, toFlatten) { // See if this index is an array that itself needs to be flattened. if(toFlatten.some && toFlatten.some(Array.isArray)) { return flat.concat(flatten(toFlatten)); // Otherwise just add the current index to the end of the flattened array. } else { return flat.concat(toFlatten); } }, []); }
[ "function", "flatten", "(", "arr", ")", "{", "return", "arr", ".", "reduce", "(", "function", "(", "flat", ",", "toFlatten", ")", "{", "// See if this index is an array that itself needs to be flattened.", "if", "(", "toFlatten", ".", "some", "&&", "toFlatten", ".", "some", "(", "Array", ".", "isArray", ")", ")", "{", "return", "flat", ".", "concat", "(", "flatten", "(", "toFlatten", ")", ")", ";", "// Otherwise just add the current index to the end of the flattened array.", "}", "else", "{", "return", "flat", ".", "concat", "(", "toFlatten", ")", ";", "}", "}", ",", "[", "]", ")", ";", "}" ]
flattens array of arrays of arrays...
[ "flattens", "array", "of", "arrays", "of", "arrays", "..." ]
b5f6eae24b2dece4025b4f11cea7f1560d3b345f
https://github.com/mnichols/ankh/blob/b5f6eae24b2dece4025b4f11cea7f1560d3b345f/lib/registrations.js#L26-L36
56,097
mnichols/ankh
lib/registrations.js
Registrations
function Registrations() { Object.defineProperty(this,'_registrations',{ value: {} ,enumerable: false ,configurable: false ,writable: false }) this.get = this.get.bind(this) this.put = this.put.bind(this) this.clear = this.clear.bind(this) this.has = this.has.bind(this) }
javascript
function Registrations() { Object.defineProperty(this,'_registrations',{ value: {} ,enumerable: false ,configurable: false ,writable: false }) this.get = this.get.bind(this) this.put = this.put.bind(this) this.clear = this.clear.bind(this) this.has = this.has.bind(this) }
[ "function", "Registrations", "(", ")", "{", "Object", ".", "defineProperty", "(", "this", ",", "'_registrations'", ",", "{", "value", ":", "{", "}", ",", "enumerable", ":", "false", ",", "configurable", ":", "false", ",", "writable", ":", "false", "}", ")", "this", ".", "get", "=", "this", ".", "get", ".", "bind", "(", "this", ")", "this", ".", "put", "=", "this", ".", "put", ".", "bind", "(", "this", ")", "this", ".", "clear", "=", "this", ".", "clear", ".", "bind", "(", "this", ")", "this", ".", "has", "=", "this", ".", "has", ".", "bind", "(", "this", ")", "}" ]
Registrations collection stores all configurations created for the container to resolve at runtime
[ "Registrations", "collection", "stores", "all", "configurations", "created", "for", "the", "container", "to", "resolve", "at", "runtime" ]
b5f6eae24b2dece4025b4f11cea7f1560d3b345f
https://github.com/mnichols/ankh/blob/b5f6eae24b2dece4025b4f11cea7f1560d3b345f/lib/registrations.js#L41-L52
56,098
KonstantinKo/rform
src/containers/Form.js
assembleAttrsFromServer
function assembleAttrsFromServer(seedData, formObjectClass) { // Early return when there was no serialized object provided by the server if (!seedData) { return {} } // Otherwise assemble main and submodels' fields let attrs = merge({}, seedData.fields, seedData.errors) // TODO: reenable this, but consider there might be ids/ id arrays in there // for (let submodel of formObjectClass.submodels) { // if (seedData.fields[submodel]) { // let submodelData = seedData.fields[submodel] // attrs[submodel] = merge({}, submodelData.fields, submodelData.errors) // } // } return attrs }
javascript
function assembleAttrsFromServer(seedData, formObjectClass) { // Early return when there was no serialized object provided by the server if (!seedData) { return {} } // Otherwise assemble main and submodels' fields let attrs = merge({}, seedData.fields, seedData.errors) // TODO: reenable this, but consider there might be ids/ id arrays in there // for (let submodel of formObjectClass.submodels) { // if (seedData.fields[submodel]) { // let submodelData = seedData.fields[submodel] // attrs[submodel] = merge({}, submodelData.fields, submodelData.errors) // } // } return attrs }
[ "function", "assembleAttrsFromServer", "(", "seedData", ",", "formObjectClass", ")", "{", "// Early return when there was no serialized object provided by the server", "if", "(", "!", "seedData", ")", "{", "return", "{", "}", "}", "// Otherwise assemble main and submodels' fields", "let", "attrs", "=", "merge", "(", "{", "}", ",", "seedData", ".", "fields", ",", "seedData", ".", "errors", ")", "// TODO: reenable this, but consider there might be ids/ id arrays in there", "// for (let submodel of formObjectClass.submodels) {", "// if (seedData.fields[submodel]) {", "// let submodelData = seedData.fields[submodel]", "// attrs[submodel] = merge({}, submodelData.fields, submodelData.errors)", "// }", "// }", "return", "attrs", "}" ]
the values we want from the server-provided serialized object are nested under `fields`. The same is true for included submodels.
[ "the", "values", "we", "want", "from", "the", "server", "-", "provided", "serialized", "object", "are", "nested", "under", "fields", ".", "The", "same", "is", "true", "for", "included", "submodels", "." ]
35213340dc8e792583ff4f089a62e2dfa60c5657
https://github.com/KonstantinKo/rform/blob/35213340dc8e792583ff4f089a62e2dfa60c5657/src/containers/Form.js#L58-L72
56,099
CCISEL/connect-controller
lib/connectController.js
addCtrActionsToRouter
function addCtrActionsToRouter(ctr, router, name, options) { for(let prop in ctr) { if(ctr[prop] instanceof Function) { const info = new RouteInfo(ctr, name, prop, ctr[prop], options) /** * e.g. router.get(path, Middleware). */ const path = name ? '/' + name + info.path : info.path const mw = newMiddleware(info) debug('Add route to %s %s', info.method, path) router[info.method].call(router, path, mw) } } return router }
javascript
function addCtrActionsToRouter(ctr, router, name, options) { for(let prop in ctr) { if(ctr[prop] instanceof Function) { const info = new RouteInfo(ctr, name, prop, ctr[prop], options) /** * e.g. router.get(path, Middleware). */ const path = name ? '/' + name + info.path : info.path const mw = newMiddleware(info) debug('Add route to %s %s', info.method, path) router[info.method].call(router, path, mw) } } return router }
[ "function", "addCtrActionsToRouter", "(", "ctr", ",", "router", ",", "name", ",", "options", ")", "{", "for", "(", "let", "prop", "in", "ctr", ")", "{", "if", "(", "ctr", "[", "prop", "]", "instanceof", "Function", ")", "{", "const", "info", "=", "new", "RouteInfo", "(", "ctr", ",", "name", ",", "prop", ",", "ctr", "[", "prop", "]", ",", "options", ")", "/**\r\n * e.g. router.get(path, Middleware).\r\n */", "const", "path", "=", "name", "?", "'/'", "+", "name", "+", "info", ".", "path", ":", "info", ".", "path", "const", "mw", "=", "newMiddleware", "(", "info", ")", "debug", "(", "'Add route to %s %s'", ",", "info", ".", "method", ",", "path", ")", "router", "[", "info", ".", "method", "]", ".", "call", "(", "router", ",", "path", ",", "mw", ")", "}", "}", "return", "router", "}" ]
For each method of ctr object creates a new Middleware that is added to router argument. Route, query or body parameters are automatically mapped to method arguments. @param {Object} ctr Controller instance @param {Router} router express.Router instance @param {String} name controller name @param {Object} options object with optional properties: name, redirectOnStringResult and resultHandler @return {Router} express.Router instance
[ "For", "each", "method", "of", "ctr", "object", "creates", "a", "new", "Middleware", "that", "is", "added", "to", "router", "argument", ".", "Route", "query", "or", "body", "parameters", "are", "automatically", "mapped", "to", "method", "arguments", "." ]
c8e2587c5a31e3cb54e3668c4b98b7b7526d69b4
https://github.com/CCISEL/connect-controller/blob/c8e2587c5a31e3cb54e3668c4b98b7b7526d69b4/lib/connectController.js#L69-L83