repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
alexlafroscia/postcss-retina-bg-img
lib/utils/media-query.js
queryCoversRange
function queryCoversRange(lessRestrictive, moreRestrictive) { // Short curcuit if there is an exact match if (lessRestrictive === moreRestrictive) { return true; } const lessRestrictiveParts = explodeMediaQuery(lessRestrictive); const moreRestrictiveParts = explodeMediaQuery(moreRestrictive); return lessRestrictiveParts.reduce((orPrevious, lessAndParts) => { // Short curcuit if a previous part was not satisfied if (!orPrevious) { return false; } return moreRestrictiveParts.reduce((prev, moreAndParts) => { return ( prev || arrayContainsAllElementsOfArray(lessAndParts, moreAndParts) ); }, false); }, true); }
javascript
function queryCoversRange(lessRestrictive, moreRestrictive) { // Short curcuit if there is an exact match if (lessRestrictive === moreRestrictive) { return true; } const lessRestrictiveParts = explodeMediaQuery(lessRestrictive); const moreRestrictiveParts = explodeMediaQuery(moreRestrictive); return lessRestrictiveParts.reduce((orPrevious, lessAndParts) => { // Short curcuit if a previous part was not satisfied if (!orPrevious) { return false; } return moreRestrictiveParts.reduce((prev, moreAndParts) => { return ( prev || arrayContainsAllElementsOfArray(lessAndParts, moreAndParts) ); }, false); }, true); }
[ "function", "queryCoversRange", "(", "lessRestrictive", ",", "moreRestrictive", ")", "{", "if", "(", "lessRestrictive", "===", "moreRestrictive", ")", "{", "return", "true", ";", "}", "const", "lessRestrictiveParts", "=", "explodeMediaQuery", "(", "lessRestrictive", ")", ";", "const", "moreRestrictiveParts", "=", "explodeMediaQuery", "(", "moreRestrictive", ")", ";", "return", "lessRestrictiveParts", ".", "reduce", "(", "(", "orPrevious", ",", "lessAndParts", ")", "=>", "{", "if", "(", "!", "orPrevious", ")", "{", "return", "false", ";", "}", "return", "moreRestrictiveParts", ".", "reduce", "(", "(", "prev", ",", "moreAndParts", ")", "=>", "{", "return", "(", "prev", "||", "arrayContainsAllElementsOfArray", "(", "lessAndParts", ",", "moreAndParts", ")", ")", ";", "}", ",", "false", ")", ";", "}", ",", "true", ")", ";", "}" ]
Determine if the more restrictive media query covers all cases of the less restrictive one For MQ "A" to contain MQ "B", "A" must be at least as specific as "B". @example // returns `true` queryCoversRange('(min-width: 600px)', '(min-width: 600px) and (max-width: 800px)'); @example // returns `false` queryCoversRange('(min-width: 600px), (max-width: 700px)', '(min-width: 600px) and (max-width: 800px)'); @param {string} lessRestrictive @param {string} moreRestrictive the media query to check membership of @return {boolean}
[ "Determine", "if", "the", "more", "restrictive", "media", "query", "covers", "all", "cases", "of", "the", "less", "restrictive", "one" ]
4ff929815be2f76fe930335e2facc486df3f9dda
https://github.com/alexlafroscia/postcss-retina-bg-img/blob/4ff929815be2f76fe930335e2facc486df3f9dda/lib/utils/media-query.js#L18-L39
train
alexlafroscia/postcss-retina-bg-img
lib/utils/media-query.js
explodeMediaQuery
function explodeMediaQuery(query) { return query .split(',') .map(part => part.trim()) .map(orSection => orSection.split('and').map(part => part.trim())); }
javascript
function explodeMediaQuery(query) { return query .split(',') .map(part => part.trim()) .map(orSection => orSection.split('and').map(part => part.trim())); }
[ "function", "explodeMediaQuery", "(", "query", ")", "{", "return", "query", ".", "split", "(", "','", ")", ".", "map", "(", "part", "=>", "part", ".", "trim", "(", ")", ")", ".", "map", "(", "orSection", "=>", "orSection", ".", "split", "(", "'and'", ")", ".", "map", "(", "part", "=>", "part", ".", "trim", "(", ")", ")", ")", ";", "}" ]
Break a media query string into parts @example const q = '(-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi)'; explodeMediaQuery(q); // => ['(-webkit-min-device-pixel-ratio: 2)', '(min-resolution: 192dpi)'] @param {string} query the media query string to break apart @return {array} the structure of the provided media query
[ "Break", "a", "media", "query", "string", "into", "parts" ]
4ff929815be2f76fe930335e2facc486df3f9dda
https://github.com/alexlafroscia/postcss-retina-bg-img/blob/4ff929815be2f76fe930335e2facc486df3f9dda/lib/utils/media-query.js#L53-L58
train
alexlafroscia/postcss-retina-bg-img
lib/utils/media-query.js
arrayContainsAllElementsOfArray
function arrayContainsAllElementsOfArray(smaller, larger) { return smaller.reduce((prev, element) => { return prev && larger.indexOf(element) >= 0; }, true); }
javascript
function arrayContainsAllElementsOfArray(smaller, larger) { return smaller.reduce((prev, element) => { return prev && larger.indexOf(element) >= 0; }, true); }
[ "function", "arrayContainsAllElementsOfArray", "(", "smaller", ",", "larger", ")", "{", "return", "smaller", ".", "reduce", "(", "(", "prev", ",", "element", ")", "=>", "{", "return", "prev", "&&", "larger", ".", "indexOf", "(", "element", ")", ">=", "0", ";", "}", ",", "true", ")", ";", "}" ]
Verify that one array contains all the elements of another @example const smaller = ['a']; const larger = ['b']; arrayContainsAllElementsOfArray(smaller, larger); // => true @param {array} smaller the array to ensure is contained by the other @param {array} larger the array to ensure contains the other @return {boolean}
[ "Verify", "that", "one", "array", "contains", "all", "the", "elements", "of", "another" ]
4ff929815be2f76fe930335e2facc486df3f9dda
https://github.com/alexlafroscia/postcss-retina-bg-img/blob/4ff929815be2f76fe930335e2facc486df3f9dda/lib/utils/media-query.js#L74-L78
train
alexlafroscia/postcss-retina-bg-img
lib/utils/media-query.js
distributeQueryAcrossQuery
function distributeQueryAcrossQuery(firstQuery, secondQuery) { const aParts = explodeMediaQuery(firstQuery); const bParts = explodeMediaQuery(secondQuery); return aParts .map(aPart => bParts.map(bPart => `${aPart} and ${bPart}`).join(', ')) .join(', '); }
javascript
function distributeQueryAcrossQuery(firstQuery, secondQuery) { const aParts = explodeMediaQuery(firstQuery); const bParts = explodeMediaQuery(secondQuery); return aParts .map(aPart => bParts.map(bPart => `${aPart} and ${bPart}`).join(', ')) .join(', '); }
[ "function", "distributeQueryAcrossQuery", "(", "firstQuery", ",", "secondQuery", ")", "{", "const", "aParts", "=", "explodeMediaQuery", "(", "firstQuery", ")", ";", "const", "bParts", "=", "explodeMediaQuery", "(", "secondQuery", ")", ";", "return", "aParts", ".", "map", "(", "aPart", "=>", "bParts", ".", "map", "(", "bPart", "=>", "`", "${", "aPart", "}", "${", "bPart", "}", "`", ")", ".", "join", "(", "', '", ")", ")", ".", "join", "(", "', '", ")", ";", "}" ]
Perform a "logic AND" on the two media queries @example const a = '(min-width: 600px)'; const b = '(max-width: 800px)'; distributeQueryAcrossQuery(a, b); // => '(min-width: 600px), (max-width: 800px)' @example const a = '(min-width: 600px)'; const b = '(-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi)'; distributeQueryAcrossQuery(a, b); // => '(-webkit-min-device-pixel-ratio: 2) and (min-width: 600px), (min-resolution: 192dpi) and (min-width: 600px)' @param {string} firstQuery the first query to include @param {string} secondQuery the second query to include @return {string} the combined query
[ "Perform", "a", "logic", "AND", "on", "the", "two", "media", "queries" ]
4ff929815be2f76fe930335e2facc486df3f9dda
https://github.com/alexlafroscia/postcss-retina-bg-img/blob/4ff929815be2f76fe930335e2facc486df3f9dda/lib/utils/media-query.js#L101-L108
train
royalpinto/node-cares
lib/cares.js
Resolver
function Resolver(options) { if (!(this instanceof Resolver)) { return new Resolver(options); } options = options || {}; if (!isObject(options)) { throw new Error('options must be an object'); } this._resolver = new cares.Resolver(options); if (options.servers) { this.setServers(options.servers); } }
javascript
function Resolver(options) { if (!(this instanceof Resolver)) { return new Resolver(options); } options = options || {}; if (!isObject(options)) { throw new Error('options must be an object'); } this._resolver = new cares.Resolver(options); if (options.servers) { this.setServers(options.servers); } }
[ "function", "Resolver", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Resolver", ")", ")", "{", "return", "new", "Resolver", "(", "options", ")", ";", "}", "options", "=", "options", "||", "{", "}", ";", "if", "(", "!", "isObject", "(", "options", ")", ")", "{", "throw", "new", "Error", "(", "'options must be an object'", ")", ";", "}", "this", ".", "_resolver", "=", "new", "cares", ".", "Resolver", "(", "options", ")", ";", "if", "(", "options", ".", "servers", ")", "{", "this", ".", "setServers", "(", "options", ".", "servers", ")", ";", "}", "}" ]
Initialize the resolver with given options. @param {Object} [options={}] The options to be used with the resolver. @param {Number} [options.timeout=5000] The number of milliseconds each name server should be given to respond to a query on the first try. (After the first try, the timeout algorithm becomes more complicated, but scales linearly with the value of timeout.) @param {Number} [options.tries=4] The number of times the resolver should try contacting each name server before giving up. @param {Number} [options.ndots=1] The number of dots which must be present in a domain name for it to be queried for "as is" prior to querying for it with the default domain extensions appended. The default value is 1 unless set otherwise by resolv.conf or the RES_OPTIONS environment variable. @param {Number} [options.tcp_port] The tcp port to use for queries. @param {Number} [options.udp_port] The udp port to use for queries. @param {Array} [options.servers] An array of IP addresses as strings, set them as the servers to use for resolving. @param {Number} [options.flags] The flags field should be the bitwise or of some subset of ARES_FLAG_*. @class @classdesc Instances of the Resolver class represent a single `ares_channel`.
[ "Initialize", "the", "resolver", "with", "given", "options", "." ]
6a38a49a8baf080d33d4520567f8eee5fb74f249
https://github.com/royalpinto/node-cares/blob/6a38a49a8baf080d33d4520567f8eee5fb74f249/lib/cares.js#L179-L195
train
dominicbarnes/json-string
index.js
format
function format(input, level, options) { if (util.isArray(input)) { return array(input, level, options); } else if (util.isObject(input)) { return object(input, level, options); } else { return stringify(input, options); } }
javascript
function format(input, level, options) { if (util.isArray(input)) { return array(input, level, options); } else if (util.isObject(input)) { return object(input, level, options); } else { return stringify(input, options); } }
[ "function", "format", "(", "input", ",", "level", ",", "options", ")", "{", "if", "(", "util", ".", "isArray", "(", "input", ")", ")", "{", "return", "array", "(", "input", ",", "level", ",", "options", ")", ";", "}", "else", "if", "(", "util", ".", "isObject", "(", "input", ")", ")", "{", "return", "object", "(", "input", ",", "level", ",", "options", ")", ";", "}", "else", "{", "return", "stringify", "(", "input", ",", "options", ")", ";", "}", "}" ]
Turns the `input` object into a string with options for human-friendly output. @param {Object} input @param {Object} [options] @returns {String}
[ "Turns", "the", "input", "object", "into", "a", "string", "with", "options", "for", "human", "-", "friendly", "output", "." ]
3c41894b2040b9542f6aedb0d5fd0fbdb54e0a5d
https://github.com/dominicbarnes/json-string/blob/3c41894b2040b9542f6aedb0d5fd0fbdb54e0a5d/index.js#L41-L49
train
dominicbarnes/json-string
index.js
object
function object(input, level, options) { var spaces = options.spaces; var inner = indent(level, spaces); var outer = indent(level - 1, spaces); var keys = Object.keys(input); if (options.sortKeys) keys.sort(naturalSort()); var str = keys.map(function (key) { return inner + stringify(key) + ': ' + format(input[key], level + 1, options); }).join(',\n'); return [ '{', str, outer + '}' ].join('\n'); }
javascript
function object(input, level, options) { var spaces = options.spaces; var inner = indent(level, spaces); var outer = indent(level - 1, spaces); var keys = Object.keys(input); if (options.sortKeys) keys.sort(naturalSort()); var str = keys.map(function (key) { return inner + stringify(key) + ': ' + format(input[key], level + 1, options); }).join(',\n'); return [ '{', str, outer + '}' ].join('\n'); }
[ "function", "object", "(", "input", ",", "level", ",", "options", ")", "{", "var", "spaces", "=", "options", ".", "spaces", ";", "var", "inner", "=", "indent", "(", "level", ",", "spaces", ")", ";", "var", "outer", "=", "indent", "(", "level", "-", "1", ",", "spaces", ")", ";", "var", "keys", "=", "Object", ".", "keys", "(", "input", ")", ";", "if", "(", "options", ".", "sortKeys", ")", "keys", ".", "sort", "(", "naturalSort", "(", ")", ")", ";", "var", "str", "=", "keys", ".", "map", "(", "function", "(", "key", ")", "{", "return", "inner", "+", "stringify", "(", "key", ")", "+", "': '", "+", "format", "(", "input", "[", "key", "]", ",", "level", "+", "1", ",", "options", ")", ";", "}", ")", ".", "join", "(", "',\\n'", ")", ";", "\\n", "}" ]
JSON format an object directly. @param {Object} input @param {Number} level @param {Object} options @returns {String}
[ "JSON", "format", "an", "object", "directly", "." ]
3c41894b2040b9542f6aedb0d5fd0fbdb54e0a5d
https://github.com/dominicbarnes/json-string/blob/3c41894b2040b9542f6aedb0d5fd0fbdb54e0a5d/index.js#L74-L88
train
dominicbarnes/json-string
index.js
array
function array(input, level, options) { var spaces = options.spaces; var inner = indent(level, spaces); var outer = indent(level - 1, spaces); var str = input .map(function (value) { return inner + format(value, level + 1, options); }) .join(',\n'); return [ '[', str, outer + ']' ].join('\n'); }
javascript
function array(input, level, options) { var spaces = options.spaces; var inner = indent(level, spaces); var outer = indent(level - 1, spaces); var str = input .map(function (value) { return inner + format(value, level + 1, options); }) .join(',\n'); return [ '[', str, outer + ']' ].join('\n'); }
[ "function", "array", "(", "input", ",", "level", ",", "options", ")", "{", "var", "spaces", "=", "options", ".", "spaces", ";", "var", "inner", "=", "indent", "(", "level", ",", "spaces", ")", ";", "var", "outer", "=", "indent", "(", "level", "-", "1", ",", "spaces", ")", ";", "var", "str", "=", "input", ".", "map", "(", "function", "(", "value", ")", "{", "return", "inner", "+", "format", "(", "value", ",", "level", "+", "1", ",", "options", ")", ";", "}", ")", ".", "join", "(", "',\\n'", ")", ";", "\\n", "}" ]
JSON format an array directly. @param {Object} input @param {Number} level @param {Object} options @returns {String}
[ "JSON", "format", "an", "array", "directly", "." ]
3c41894b2040b9542f6aedb0d5fd0fbdb54e0a5d
https://github.com/dominicbarnes/json-string/blob/3c41894b2040b9542f6aedb0d5fd0fbdb54e0a5d/index.js#L99-L111
train
knee-cola/SphereViewer
src/equi2recti-worker.js
outImgToXYZ
function outImgToXYZ(i, j, faceIdx, faceSize) { var a = 2 * i / faceSize, b = 2 * j / faceSize; switch(faceIdx) { case 0: // back return({x:-1, y:1-a, z:1-b}); case 1: // left return({x:a-1, y:-1, z:1-b}); case 2: // front return({x: 1, y:a-1, z:1-b}); case 3: // right return({x:1-a, y:1, z:1-b}); case 4: // top return({x:b-1, y:a-1, z:1}); case 5: // bottom return({x:1-b, y:a-1, z:-1}); } }
javascript
function outImgToXYZ(i, j, faceIdx, faceSize) { var a = 2 * i / faceSize, b = 2 * j / faceSize; switch(faceIdx) { case 0: // back return({x:-1, y:1-a, z:1-b}); case 1: // left return({x:a-1, y:-1, z:1-b}); case 2: // front return({x: 1, y:a-1, z:1-b}); case 3: // right return({x:1-a, y:1, z:1-b}); case 4: // top return({x:b-1, y:a-1, z:1}); case 5: // bottom return({x:1-b, y:a-1, z:-1}); } }
[ "function", "outImgToXYZ", "(", "i", ",", "j", ",", "faceIdx", ",", "faceSize", ")", "{", "var", "a", "=", "2", "*", "i", "/", "faceSize", ",", "b", "=", "2", "*", "j", "/", "faceSize", ";", "switch", "(", "faceIdx", ")", "{", "case", "0", ":", "return", "(", "{", "x", ":", "-", "1", ",", "y", ":", "1", "-", "a", ",", "z", ":", "1", "-", "b", "}", ")", ";", "case", "1", ":", "return", "(", "{", "x", ":", "a", "-", "1", ",", "y", ":", "-", "1", ",", "z", ":", "1", "-", "b", "}", ")", ";", "case", "2", ":", "return", "(", "{", "x", ":", "1", ",", "y", ":", "a", "-", "1", ",", "z", ":", "1", "-", "b", "}", ")", ";", "case", "3", ":", "return", "(", "{", "x", ":", "1", "-", "a", ",", "y", ":", "1", ",", "z", ":", "1", "-", "b", "}", ")", ";", "case", "4", ":", "return", "(", "{", "x", ":", "b", "-", "1", ",", "y", ":", "a", "-", "1", ",", "z", ":", "1", "}", ")", ";", "case", "5", ":", "return", "(", "{", "x", ":", "1", "-", "b", ",", "y", ":", "a", "-", "1", ",", "z", ":", "-", "1", "}", ")", ";", "}", "}" ]
get x,y,z coords from out image pixels coords i,j are pixel coords faceIdx is face number faceSize is edge length
[ "get", "x", "y", "z", "coords", "from", "out", "image", "pixels", "coords", "i", "j", "are", "pixel", "coords", "faceIdx", "is", "face", "number", "faceSize", "is", "edge", "length" ]
e87cded5bd1635334612ac4b22d69355ec3e1d19
https://github.com/knee-cola/SphereViewer/blob/e87cded5bd1635334612ac4b22d69355ec3e1d19/src/equi2recti-worker.js#L102-L120
train
gl-vis/regl-splom
index.js
passId
function passId (trace, i, j) { let id = (trace.id != null ? trace.id : trace) let n = i let m = j let key = id << 16 | (n & 0xff) << 8 | m & 0xff return key }
javascript
function passId (trace, i, j) { let id = (trace.id != null ? trace.id : trace) let n = i let m = j let key = id << 16 | (n & 0xff) << 8 | m & 0xff return key }
[ "function", "passId", "(", "trace", ",", "i", ",", "j", ")", "{", "let", "id", "=", "(", "trace", ".", "id", "!=", "null", "?", "trace", ".", "id", ":", "trace", ")", "let", "n", "=", "i", "let", "m", "=", "j", "let", "key", "=", "id", "<<", "16", "|", "(", "n", "&", "0xff", ")", "<<", "8", "|", "m", "&", "0xff", "return", "key", "}" ]
return pass corresponding to trace i- j- square
[ "return", "pass", "corresponding", "to", "trace", "i", "-", "j", "-", "square" ]
a98ee4f4da9ca2773b81ed1d066cefc06f7400f1
https://github.com/gl-vis/regl-splom/blob/a98ee4f4da9ca2773b81ed1d066cefc06f7400f1/index.js#L338-L345
train
gl-vis/regl-splom
index.js
getBox
function getBox (items, i, j) { let ilox, iloy, ihix, ihiy, jlox, jloy, jhix, jhiy let iitem = items[i], jitem = items[j] if (iitem.length > 2) { ilox = iitem[0] ihix = iitem[2] iloy = iitem[1] ihiy = iitem[3] } else if (iitem.length) { ilox = iloy = iitem[0] ihix = ihiy = iitem[1] } else { ilox = iitem.x iloy = iitem.y ihix = iitem.x + iitem.width ihiy = iitem.y + iitem.height } if (jitem.length > 2) { jlox = jitem[0] jhix = jitem[2] jloy = jitem[1] jhiy = jitem[3] } else if (jitem.length) { jlox = jloy = jitem[0] jhix = jhiy = jitem[1] } else { jlox = jitem.x jloy = jitem.y jhix = jitem.x + jitem.width jhiy = jitem.y + jitem.height } return [ jlox, iloy, jhix, ihiy ] }
javascript
function getBox (items, i, j) { let ilox, iloy, ihix, ihiy, jlox, jloy, jhix, jhiy let iitem = items[i], jitem = items[j] if (iitem.length > 2) { ilox = iitem[0] ihix = iitem[2] iloy = iitem[1] ihiy = iitem[3] } else if (iitem.length) { ilox = iloy = iitem[0] ihix = ihiy = iitem[1] } else { ilox = iitem.x iloy = iitem.y ihix = iitem.x + iitem.width ihiy = iitem.y + iitem.height } if (jitem.length > 2) { jlox = jitem[0] jhix = jitem[2] jloy = jitem[1] jhiy = jitem[3] } else if (jitem.length) { jlox = jloy = jitem[0] jhix = jhiy = jitem[1] } else { jlox = jitem.x jloy = jitem.y jhix = jitem.x + jitem.width jhiy = jitem.y + jitem.height } return [ jlox, iloy, jhix, ihiy ] }
[ "function", "getBox", "(", "items", ",", "i", ",", "j", ")", "{", "let", "ilox", ",", "iloy", ",", "ihix", ",", "ihiy", ",", "jlox", ",", "jloy", ",", "jhix", ",", "jhiy", "let", "iitem", "=", "items", "[", "i", "]", ",", "jitem", "=", "items", "[", "j", "]", "if", "(", "iitem", ".", "length", ">", "2", ")", "{", "ilox", "=", "iitem", "[", "0", "]", "ihix", "=", "iitem", "[", "2", "]", "iloy", "=", "iitem", "[", "1", "]", "ihiy", "=", "iitem", "[", "3", "]", "}", "else", "if", "(", "iitem", ".", "length", ")", "{", "ilox", "=", "iloy", "=", "iitem", "[", "0", "]", "ihix", "=", "ihiy", "=", "iitem", "[", "1", "]", "}", "else", "{", "ilox", "=", "iitem", ".", "x", "iloy", "=", "iitem", ".", "y", "ihix", "=", "iitem", ".", "x", "+", "iitem", ".", "width", "ihiy", "=", "iitem", ".", "y", "+", "iitem", ".", "height", "}", "if", "(", "jitem", ".", "length", ">", "2", ")", "{", "jlox", "=", "jitem", "[", "0", "]", "jhix", "=", "jitem", "[", "2", "]", "jloy", "=", "jitem", "[", "1", "]", "jhiy", "=", "jitem", "[", "3", "]", "}", "else", "if", "(", "jitem", ".", "length", ")", "{", "jlox", "=", "jloy", "=", "jitem", "[", "0", "]", "jhix", "=", "jhiy", "=", "jitem", "[", "1", "]", "}", "else", "{", "jlox", "=", "jitem", ".", "x", "jloy", "=", "jitem", ".", "y", "jhix", "=", "jitem", ".", "x", "+", "jitem", ".", "width", "jhiy", "=", "jitem", ".", "y", "+", "jitem", ".", "height", "}", "return", "[", "jlox", ",", "iloy", ",", "jhix", ",", "ihiy", "]", "}" ]
return bounding box corresponding to a pass
[ "return", "bounding", "box", "corresponding", "to", "a", "pass" ]
a98ee4f4da9ca2773b81ed1d066cefc06f7400f1
https://github.com/gl-vis/regl-splom/blob/a98ee4f4da9ca2773b81ed1d066cefc06f7400f1/index.js#L349-L388
train
glaunay/nslurm
index.js
function(opt) { var vKeys = ["cancelBin", "queueBin", "submitBin"]; var msg = "Missing engine binaries parameters keys \"cancelBin\", \"queueBin\", \"submitBin\""; for (var k in vKeys) if (!opt.hasOwnProperty(k)) throw (msg); engine.configure(opt); }
javascript
function(opt) { var vKeys = ["cancelBin", "queueBin", "submitBin"]; var msg = "Missing engine binaries parameters keys \"cancelBin\", \"queueBin\", \"submitBin\""; for (var k in vKeys) if (!opt.hasOwnProperty(k)) throw (msg); engine.configure(opt); }
[ "function", "(", "opt", ")", "{", "var", "vKeys", "=", "[", "\"cancelBin\"", ",", "\"queueBin\"", ",", "\"submitBin\"", "]", ";", "var", "msg", "=", "\"Missing engine binaries parameters keys \\\"cancelBin\\\", \\\"queueBin\\\", \\\"submitBin\\\"\"", ";", "\\\"", "\\\"", "}" ]
Check the existence of the bare minimum set of parameters to configure an engine @param {Object}managerOptions: Litteral of options @return null
[ "Check", "the", "existence", "of", "the", "bare", "minimum", "set", "of", "parameters", "to", "configure", "an", "engine" ]
002b064a700d3596d82e1c57110c0100a389f792
https://github.com/glaunay/nslurm/blob/002b064a700d3596d82e1c57110c0100a389f792/index.js#L83-L90
train
glaunay/nslurm
index.js
function() { var displayString = '###############################\n' + '###### Current jobs pool ######\n' + '###############################\n'; var c = 0; for (var key in jobsArray) {; c++; displayString += '# ' + key + ' : ' + jobsArray[key].status + '\n'; } if (c === 0) displayString += ' EMPTY \n'; console.log(displayString); return null; }
javascript
function() { var displayString = '###############################\n' + '###### Current jobs pool ######\n' + '###############################\n'; var c = 0; for (var key in jobsArray) {; c++; displayString += '# ' + key + ' : ' + jobsArray[key].status + '\n'; } if (c === 0) displayString += ' EMPTY \n'; console.log(displayString); return null; }
[ "function", "(", ")", "{", "var", "displayString", "=", "'###############################\\n'", "+", "\\n", "+", "'###### Current jobs pool ######\\n'", ";", "\\n", "'###############################\\n'", "\\n", "var", "c", "=", "0", ";", "for", "(", "var", "key", "in", "jobsArray", ")", "{", ";", "c", "++", ";", "displayString", "+=", "'# '", "+", "key", "+", "' : '", "+", "jobsArray", "[", "key", "]", ".", "status", "+", "'\\n'", ";", "}", "}" ]
Display on console.log the current list of "pushed" jobs and their status @param None @return null
[ "Display", "on", "console", ".", "log", "the", "current", "list", "of", "pushed", "jobs", "and", "their", "status" ]
002b064a700d3596d82e1c57110c0100a389f792
https://github.com/glaunay/nslurm/blob/002b064a700d3596d82e1c57110c0100a389f792/index.js#L109-L121
train
glaunay/nslurm
index.js
function(opt) { //console.log(opt) if (isStarted) return; var self = this; if (!opt) { throw "Options required to start manager : \"cacheDir\", \"tcp\", \"port\""; } cacheDir = opt.cacheDir + '/' + scheduler_id; TCPip = opt.tcp; TCPport = opt.port; jobProfiles = opt.jobProfiles; cycleLength = opt.cycleLength ? parseInt(opt.cycleLength) : 5000; if (opt.hasOwnProperty('forceCache')) { cacheDir = opt.forceCache; } if (opt.hasOwnProperty('probPreviousCacheDir')) { probPreviousCacheDir = opt.probPreviousCacheDir; } if(debugMode) console.log("Attempting to create cache for process at " + cacheDir); try { fs.mkdirSync(cacheDir); } catch (e) { if (e.code != 'EEXIST') throw e; console.log("Cache found already found at " + cacheDir); } if(debugMode) console.log('[' + TCPip + '] opening socket at port ' + TCPport); var s = _openSocket(TCPport); data = ''; s.on('listening', function(socket) { isStarted = true; if(debugMode) { console.log("Starting pulse monitoring"); console.log("cache Directory is " + cacheDir); } core = setInterval(function() { _pulse() }, 500); warden = setInterval(function() { self.jobWarden() }, cycleLength); console.log(" --->jobManager " + scheduler_id + " ready to process jobs<---\n\n"); eventEmitter.emit("ready"); }) .on('data', _parseMessage); }
javascript
function(opt) { //console.log(opt) if (isStarted) return; var self = this; if (!opt) { throw "Options required to start manager : \"cacheDir\", \"tcp\", \"port\""; } cacheDir = opt.cacheDir + '/' + scheduler_id; TCPip = opt.tcp; TCPport = opt.port; jobProfiles = opt.jobProfiles; cycleLength = opt.cycleLength ? parseInt(opt.cycleLength) : 5000; if (opt.hasOwnProperty('forceCache')) { cacheDir = opt.forceCache; } if (opt.hasOwnProperty('probPreviousCacheDir')) { probPreviousCacheDir = opt.probPreviousCacheDir; } if(debugMode) console.log("Attempting to create cache for process at " + cacheDir); try { fs.mkdirSync(cacheDir); } catch (e) { if (e.code != 'EEXIST') throw e; console.log("Cache found already found at " + cacheDir); } if(debugMode) console.log('[' + TCPip + '] opening socket at port ' + TCPport); var s = _openSocket(TCPport); data = ''; s.on('listening', function(socket) { isStarted = true; if(debugMode) { console.log("Starting pulse monitoring"); console.log("cache Directory is " + cacheDir); } core = setInterval(function() { _pulse() }, 500); warden = setInterval(function() { self.jobWarden() }, cycleLength); console.log(" --->jobManager " + scheduler_id + " ready to process jobs<---\n\n"); eventEmitter.emit("ready"); }) .on('data', _parseMessage); }
[ "function", "(", "opt", ")", "{", "if", "(", "isStarted", ")", "return", ";", "var", "self", "=", "this", ";", "if", "(", "!", "opt", ")", "{", "throw", "\"Options required to start manager : \\\"cacheDir\\\", \\\"tcp\\\", \\\"port\\\"\"", ";", "}", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "cacheDir", "=", "opt", ".", "cacheDir", "+", "'/'", "+", "scheduler_id", ";", "TCPip", "=", "opt", ".", "tcp", ";", "TCPport", "=", "opt", ".", "port", ";", "jobProfiles", "=", "opt", ".", "jobProfiles", ";", "cycleLength", "=", "opt", ".", "cycleLength", "?", "parseInt", "(", "opt", ".", "cycleLength", ")", ":", "5000", ";", "if", "(", "opt", ".", "hasOwnProperty", "(", "'forceCache'", ")", ")", "{", "cacheDir", "=", "opt", ".", "forceCache", ";", "}", "if", "(", "opt", ".", "hasOwnProperty", "(", "'probPreviousCacheDir'", ")", ")", "{", "probPreviousCacheDir", "=", "opt", ".", "probPreviousCacheDir", ";", "}", "}" ]
Starts the job manager @param {Object}ManagerSpecs @param {ManagerSpecs} cacheDir{String} Directory used for jobs caching @param {ManagerSpecs} tcp{String} ip adress of the master node for netSocket @param {ManagerSpecs} port{String} port number of the netSocket @param {ManagerSpecs} slurmBinaries{String} path to slurm executable binaries @return {String}
[ "Starts", "the", "job", "manager" ]
002b064a700d3596d82e1c57110c0100a389f792
https://github.com/glaunay/nslurm/blob/002b064a700d3596d82e1c57110c0100a389f792/index.js#L403-L452
train
commercetools/commercetools-sunrise-scenarios
features/utils/async.js
serial
function serial(promises) { const results = []; return promises .reduce((chain, promise) => chain.then(result => { results.push(result); return promise }), Promise.resolve()) .then(result => { results.push(result); results.shift(); return results; }) }
javascript
function serial(promises) { const results = []; return promises .reduce((chain, promise) => chain.then(result => { results.push(result); return promise }), Promise.resolve()) .then(result => { results.push(result); results.shift(); return results; }) }
[ "function", "serial", "(", "promises", ")", "{", "const", "results", "=", "[", "]", ";", "return", "promises", ".", "reduce", "(", "(", "chain", ",", "promise", ")", "=>", "chain", ".", "then", "(", "result", "=>", "{", "results", ".", "push", "(", "result", ")", ";", "return", "promise", "}", ")", ",", "Promise", ".", "resolve", "(", ")", ")", ".", "then", "(", "result", "=>", "{", "results", ".", "push", "(", "result", ")", ";", "results", ".", "shift", "(", ")", ";", "return", "results", ";", "}", ")", "}" ]
Take an iterable of Promises and invoke them serially, otherwise identical to the `Promise.all` static method. @param {Promise[]} promises @return {Promise}
[ "Take", "an", "iterable", "of", "Promises", "and", "invoke", "them", "serially", "otherwise", "identical", "to", "the", "Promise", ".", "all", "static", "method", "." ]
e84fa2f774b9be899939e3e58455eaff3298cf79
https://github.com/commercetools/commercetools-sunrise-scenarios/blob/e84fa2f774b9be899939e3e58455eaff3298cf79/features/utils/async.js#L14-L28
train
mojaie/kiwiii
src/common/mapper.js
singleToMulti
function singleToMulti(mapping) { const newMapping = {}; Object.entries(mapping.mapping).forEach(m => { newMapping[m[0]] = [m[1]]; }); return { created: mapping.created, fields: [mapping.field], key: mapping.key, mapping: newMapping }; }
javascript
function singleToMulti(mapping) { const newMapping = {}; Object.entries(mapping.mapping).forEach(m => { newMapping[m[0]] = [m[1]]; }); return { created: mapping.created, fields: [mapping.field], key: mapping.key, mapping: newMapping }; }
[ "function", "singleToMulti", "(", "mapping", ")", "{", "const", "newMapping", "=", "{", "}", ";", "Object", ".", "entries", "(", "mapping", ".", "mapping", ")", ".", "forEach", "(", "m", "=>", "{", "newMapping", "[", "m", "[", "0", "]", "]", "=", "[", "m", "[", "1", "]", "]", ";", "}", ")", ";", "return", "{", "created", ":", "mapping", ".", "created", ",", "fields", ":", "[", "mapping", ".", "field", "]", ",", "key", ":", "mapping", ".", "key", ",", "mapping", ":", "newMapping", "}", ";", "}" ]
Convert single field mapping to multi field mapping @param {object} mapping - single field mapping @return {object} multi field mapping
[ "Convert", "single", "field", "mapping", "to", "multi", "field", "mapping" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/mapper.js#L12-L23
train
mojaie/kiwiii
src/common/mapper.js
mappingToTable
function mappingToTable(mapping) { const mp = mapping.hasOwnProperty('field') ? singleToMulti(mapping) : mapping; const keyField = {key: mp.key, format: 'text'}; const data = { fields: [keyField].concat(mp.fields), records: Object.entries(mp.mapping).map(entry => { const rcd = {}; rcd[mp.key] = entry[0]; mp.fields.forEach((f, i) => { rcd[f.key] = entry[1][i]; }); return rcd; }) }; return data; }
javascript
function mappingToTable(mapping) { const mp = mapping.hasOwnProperty('field') ? singleToMulti(mapping) : mapping; const keyField = {key: mp.key, format: 'text'}; const data = { fields: [keyField].concat(mp.fields), records: Object.entries(mp.mapping).map(entry => { const rcd = {}; rcd[mp.key] = entry[0]; mp.fields.forEach((f, i) => { rcd[f.key] = entry[1][i]; }); return rcd; }) }; return data; }
[ "function", "mappingToTable", "(", "mapping", ")", "{", "const", "mp", "=", "mapping", ".", "hasOwnProperty", "(", "'field'", ")", "?", "singleToMulti", "(", "mapping", ")", ":", "mapping", ";", "const", "keyField", "=", "{", "key", ":", "mp", ".", "key", ",", "format", ":", "'text'", "}", ";", "const", "data", "=", "{", "fields", ":", "[", "keyField", "]", ".", "concat", "(", "mp", ".", "fields", ")", ",", "records", ":", "Object", ".", "entries", "(", "mp", ".", "mapping", ")", ".", "map", "(", "entry", "=>", "{", "const", "rcd", "=", "{", "}", ";", "rcd", "[", "mp", ".", "key", "]", "=", "entry", "[", "0", "]", ";", "mp", ".", "fields", ".", "forEach", "(", "(", "f", ",", "i", ")", "=>", "{", "rcd", "[", "f", ".", "key", "]", "=", "entry", "[", "1", "]", "[", "i", "]", ";", "}", ")", ";", "return", "rcd", ";", "}", ")", "}", ";", "return", "data", ";", "}" ]
Convert field mapping to table @param {object} mapping - field mapping @return {object} table object
[ "Convert", "field", "mapping", "to", "table" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/mapper.js#L31-L46
train
mojaie/kiwiii
src/common/mapper.js
tableToMapping
function tableToMapping(table, key, ignore=['index']) { const now = new Date(); const mapping = { created: now.toString(), fields: table.fields.filter(e => e.key !== key) .filter(e => !ignore.includes(e.key)), key: key, mapping: {} }; table.records.forEach(row => { mapping.mapping[row[key]] = mapping.fields.map(e => row[e.key]); }); return mapping; }
javascript
function tableToMapping(table, key, ignore=['index']) { const now = new Date(); const mapping = { created: now.toString(), fields: table.fields.filter(e => e.key !== key) .filter(e => !ignore.includes(e.key)), key: key, mapping: {} }; table.records.forEach(row => { mapping.mapping[row[key]] = mapping.fields.map(e => row[e.key]); }); return mapping; }
[ "function", "tableToMapping", "(", "table", ",", "key", ",", "ignore", "=", "[", "'index'", "]", ")", "{", "const", "now", "=", "new", "Date", "(", ")", ";", "const", "mapping", "=", "{", "created", ":", "now", ".", "toString", "(", ")", ",", "fields", ":", "table", ".", "fields", ".", "filter", "(", "e", "=>", "e", ".", "key", "!==", "key", ")", ".", "filter", "(", "e", "=>", "!", "ignore", ".", "includes", "(", "e", ".", "key", ")", ")", ",", "key", ":", "key", ",", "mapping", ":", "{", "}", "}", ";", "table", ".", "records", ".", "forEach", "(", "row", "=>", "{", "mapping", ".", "mapping", "[", "row", "[", "key", "]", "]", "=", "mapping", ".", "fields", ".", "map", "(", "e", "=>", "row", "[", "e", ".", "key", "]", ")", ";", "}", ")", ";", "return", "mapping", ";", "}" ]
Convert table to field mapping @param {object} table - table @param {object} key - key @return {object} field mapping
[ "Convert", "table", "to", "field", "mapping" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/mapper.js#L55-L68
train
mojaie/kiwiii
src/common/mapper.js
csvToMapping
function csvToMapping(csvString) { const lines = csvString.split(/\n|\r|\r\n/); const header = lines.shift().split(','); const key = header.shift(); const now = new Date(); const headerIdx = []; const fields = []; header.forEach((h, i) => { if (h === '') return; headerIdx.push(i); fields.push({key: h, format: 'text'}); }); const mapping = { created: now.toString(), fields: fields, key: key, mapping: {} }; lines.forEach(line => { const values = line.split(','); const k = values.shift(); mapping.mapping[k] = Array(headerIdx.length); headerIdx.forEach(i => { mapping.mapping[k][i] = values[i]; }); }); return mapping; }
javascript
function csvToMapping(csvString) { const lines = csvString.split(/\n|\r|\r\n/); const header = lines.shift().split(','); const key = header.shift(); const now = new Date(); const headerIdx = []; const fields = []; header.forEach((h, i) => { if (h === '') return; headerIdx.push(i); fields.push({key: h, format: 'text'}); }); const mapping = { created: now.toString(), fields: fields, key: key, mapping: {} }; lines.forEach(line => { const values = line.split(','); const k = values.shift(); mapping.mapping[k] = Array(headerIdx.length); headerIdx.forEach(i => { mapping.mapping[k][i] = values[i]; }); }); return mapping; }
[ "function", "csvToMapping", "(", "csvString", ")", "{", "const", "lines", "=", "csvString", ".", "split", "(", "/", "\\n|\\r|\\r\\n", "/", ")", ";", "const", "header", "=", "lines", ".", "shift", "(", ")", ".", "split", "(", "','", ")", ";", "const", "key", "=", "header", ".", "shift", "(", ")", ";", "const", "now", "=", "new", "Date", "(", ")", ";", "const", "headerIdx", "=", "[", "]", ";", "const", "fields", "=", "[", "]", ";", "header", ".", "forEach", "(", "(", "h", ",", "i", ")", "=>", "{", "if", "(", "h", "===", "''", ")", "return", ";", "headerIdx", ".", "push", "(", "i", ")", ";", "fields", ".", "push", "(", "{", "key", ":", "h", ",", "format", ":", "'text'", "}", ")", ";", "}", ")", ";", "const", "mapping", "=", "{", "created", ":", "now", ".", "toString", "(", ")", ",", "fields", ":", "fields", ",", "key", ":", "key", ",", "mapping", ":", "{", "}", "}", ";", "lines", ".", "forEach", "(", "line", "=>", "{", "const", "values", "=", "line", ".", "split", "(", "','", ")", ";", "const", "k", "=", "values", ".", "shift", "(", ")", ";", "mapping", ".", "mapping", "[", "k", "]", "=", "Array", "(", "headerIdx", ".", "length", ")", ";", "headerIdx", ".", "forEach", "(", "i", "=>", "{", "mapping", ".", "mapping", "[", "k", "]", "[", "i", "]", "=", "values", "[", "i", "]", ";", "}", ")", ";", "}", ")", ";", "return", "mapping", ";", "}" ]
Convert csv text to field mapping @param {string} csvString - csv data text @return {object} field mapping
[ "Convert", "csv", "text", "to", "field", "mapping" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/mapper.js#L76-L103
train
nwtjs/nwt
plugins/calendar.js
function(milliseconds) { var formattedDate = '', self = this, dateObj = new Date(milliseconds), format = { d: function() { var day = format.j() return (day < 10) ? '0' + day : day }, D: function() { return self.weekdays[format.w()].substring(0, 3) }, j: function() { return dateObj.getDate() }, l: function() { return self.weekdays[format.w()] + 'day' }, S: function() { return self.suffix[format.j()] || 'th' }, w: function() { return dateObj.getDay() }, F: function() { return self._convertMonthIdx(format.n(), true) }, m: function() { var month = format.n() + 1 return (month < 10) ? '0' + month : month }, M: function() { return self._convertMonthIdx(format.n(), false) }, n: function() { return dateObj.getMonth() }, Y: function() { return dateObj.getFullYear() }, y: function() { return format.Y().substring(2, 4) } }, formatPieces = this.dateFormat.split('') for(i = 0, x = formatPieces.length; i < x; i++) { formattedDate += format[formatPieces[i]] ? format[formatPieces[i]]() : formatPieces[i] } return formattedDate }
javascript
function(milliseconds) { var formattedDate = '', self = this, dateObj = new Date(milliseconds), format = { d: function() { var day = format.j() return (day < 10) ? '0' + day : day }, D: function() { return self.weekdays[format.w()].substring(0, 3) }, j: function() { return dateObj.getDate() }, l: function() { return self.weekdays[format.w()] + 'day' }, S: function() { return self.suffix[format.j()] || 'th' }, w: function() { return dateObj.getDay() }, F: function() { return self._convertMonthIdx(format.n(), true) }, m: function() { var month = format.n() + 1 return (month < 10) ? '0' + month : month }, M: function() { return self._convertMonthIdx(format.n(), false) }, n: function() { return dateObj.getMonth() }, Y: function() { return dateObj.getFullYear() }, y: function() { return format.Y().substring(2, 4) } }, formatPieces = this.dateFormat.split('') for(i = 0, x = formatPieces.length; i < x; i++) { formattedDate += format[formatPieces[i]] ? format[formatPieces[i]]() : formatPieces[i] } return formattedDate }
[ "function", "(", "milliseconds", ")", "{", "var", "formattedDate", "=", "''", ",", "self", "=", "this", ",", "dateObj", "=", "new", "Date", "(", "milliseconds", ")", ",", "format", "=", "{", "d", ":", "function", "(", ")", "{", "var", "day", "=", "format", ".", "j", "(", ")", "return", "(", "day", "<", "10", ")", "?", "'0'", "+", "day", ":", "day", "}", ",", "D", ":", "function", "(", ")", "{", "return", "self", ".", "weekdays", "[", "format", ".", "w", "(", ")", "]", ".", "substring", "(", "0", ",", "3", ")", "}", ",", "j", ":", "function", "(", ")", "{", "return", "dateObj", ".", "getDate", "(", ")", "}", ",", "l", ":", "function", "(", ")", "{", "return", "self", ".", "weekdays", "[", "format", ".", "w", "(", ")", "]", "+", "'day'", "}", ",", "S", ":", "function", "(", ")", "{", "return", "self", ".", "suffix", "[", "format", ".", "j", "(", ")", "]", "||", "'th'", "}", ",", "w", ":", "function", "(", ")", "{", "return", "dateObj", ".", "getDay", "(", ")", "}", ",", "F", ":", "function", "(", ")", "{", "return", "self", ".", "_convertMonthIdx", "(", "format", ".", "n", "(", ")", ",", "true", ")", "}", ",", "m", ":", "function", "(", ")", "{", "var", "month", "=", "format", ".", "n", "(", ")", "+", "1", "return", "(", "month", "<", "10", ")", "?", "'0'", "+", "month", ":", "month", "}", ",", "M", ":", "function", "(", ")", "{", "return", "self", ".", "_convertMonthIdx", "(", "format", ".", "n", "(", ")", ",", "false", ")", "}", ",", "n", ":", "function", "(", ")", "{", "return", "dateObj", ".", "getMonth", "(", ")", "}", ",", "Y", ":", "function", "(", ")", "{", "return", "dateObj", ".", "getFullYear", "(", ")", "}", ",", "y", ":", "function", "(", ")", "{", "return", "format", ".", "Y", "(", ")", ".", "substring", "(", "2", ",", "4", ")", "}", "}", ",", "formatPieces", "=", "this", ".", "dateFormat", ".", "split", "(", "''", ")", "for", "(", "i", "=", "0", ",", "x", "=", "formatPieces", ".", "length", ";", "i", "<", "x", ";", "i", "++", ")", "{", "formattedDate", "+=", "format", "[", "formatPieces", "[", "i", "]", "]", "?", "format", "[", "formatPieces", "[", "i", "]", "]", "(", ")", ":", "formatPieces", "[", "i", "]", "}", "return", "formattedDate", "}" ]
Formats a date
[ "Formats", "a", "date" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/calendar.js#L49-L104
train
nwtjs/nwt
plugins/calendar.js
function(date, full) { return ((full == true) ? this.months[date] : ((this.months[date].length > 3) ? this.months[date].substring(0, 3) : this.months[date])) }
javascript
function(date, full) { return ((full == true) ? this.months[date] : ((this.months[date].length > 3) ? this.months[date].substring(0, 3) : this.months[date])) }
[ "function", "(", "date", ",", "full", ")", "{", "return", "(", "(", "full", "==", "true", ")", "?", "this", ".", "months", "[", "date", "]", ":", "(", "(", "this", ".", "months", "[", "date", "]", ".", "length", ">", "3", ")", "?", "this", ".", "months", "[", "date", "]", ".", "substring", "(", "0", ",", "3", ")", ":", "this", ".", "months", "[", "date", "]", ")", ")", "}" ]
Converts a month index to a string @param object Month index @param bool Whether or not to display the full string
[ "Converts", "a", "month", "index", "to", "a", "string" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/calendar.js#L111-L113
train
nwtjs/nwt
plugins/calendar.js
function(offset) { offset = offset || 0 var year = this.year var monthNum = this.month monthNum += offset if(monthNum < 0) { year-- } if(monthNum > 11) { year++ } return year }
javascript
function(offset) { offset = offset || 0 var year = this.year var monthNum = this.month monthNum += offset if(monthNum < 0) { year-- } if(monthNum > 11) { year++ } return year }
[ "function", "(", "offset", ")", "{", "offset", "=", "offset", "||", "0", "var", "year", "=", "this", ".", "year", "var", "monthNum", "=", "this", ".", "month", "monthNum", "+=", "offset", "if", "(", "monthNum", "<", "0", ")", "{", "year", "--", "}", "if", "(", "monthNum", ">", "11", ")", "{", "year", "++", "}", "return", "year", "}" ]
Returns the year based on month offset The year only changes if the month wraps to the next year @param integer month offset
[ "Returns", "the", "year", "based", "on", "month", "offset", "The", "year", "only", "changes", "if", "the", "month", "wraps", "to", "the", "next", "year" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/calendar.js#L120-L130
train
nwtjs/nwt
plugins/calendar.js
function(offset) { var month = this.getOffsetMonth(offset) , year = this.getOffsetYear(offset) // checks to see if february is a leap year otherwise return the respective # of days return (month == 1 && !(year & 3) && (year % 1e2 || !(year % 4e2))) ? 29 : this.daysInMonth[month] }
javascript
function(offset) { var month = this.getOffsetMonth(offset) , year = this.getOffsetYear(offset) // checks to see if february is a leap year otherwise return the respective # of days return (month == 1 && !(year & 3) && (year % 1e2 || !(year % 4e2))) ? 29 : this.daysInMonth[month] }
[ "function", "(", "offset", ")", "{", "var", "month", "=", "this", ".", "getOffsetMonth", "(", "offset", ")", ",", "year", "=", "this", ".", "getOffsetYear", "(", "offset", ")", "return", "(", "month", "==", "1", "&&", "!", "(", "year", "&", "3", ")", "&&", "(", "year", "%", "1e2", "||", "!", "(", "year", "%", "4e2", ")", ")", ")", "?", "29", ":", "this", ".", "daysInMonth", "[", "month", "]", "}" ]
Returns the current number of days in the month @param integer Month offset for multi-pane implementation
[ "Returns", "the", "current", "number", "of", "days", "in", "the", "month" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/calendar.js#L173-L179
train
nwtjs/nwt
plugins/calendar.js
function() { var html = '' for(i = 0, x = this.weekdays.length; i < x; i++) { html += '<th>' + this.weekdays[i].substring(0, 2) + '</th>' } return html }
javascript
function() { var html = '' for(i = 0, x = this.weekdays.length; i < x; i++) { html += '<th>' + this.weekdays[i].substring(0, 2) + '</th>' } return html }
[ "function", "(", ")", "{", "var", "html", "=", "''", "for", "(", "i", "=", "0", ",", "x", "=", "this", ".", "weekdays", ".", "length", ";", "i", "<", "x", ";", "i", "++", ")", "{", "html", "+=", "'<th>'", "+", "this", ".", "weekdays", "[", "i", "]", ".", "substring", "(", "0", ",", "2", ")", "+", "'</th>'", "}", "return", "html", "}" ]
Gets HTML for weekdays
[ "Gets", "HTML", "for", "weekdays" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/calendar.js#L210-L217
train
nwtjs/nwt
plugins/calendar.js
function(offset) { var monthNum = this.month offset = offset || 0 monthNum += offset if(monthNum < 0) { monthNum = 11 } if(monthNum > 11) { monthNum = 0 } var month = this.getOffsetMonth(offset) , year = this.getOffsetYear(offset) // get the first day of the month we are currently viewing var firstOfMonth = new Date(year, month, 1).getDay(), // get the total number of days in the month we are currently viewing numDays = this.offsetDaysInMonth(offset), // declare our day counter dayCount = 0, html = '', row = '<tr>' // print out previous month's "days" for(i = 1; i <= firstOfMonth; i++) { row += '<td>&nbsp;</td>' dayCount++ } for(i = 1; i <= numDays; i++) { // if we have reached the end of a week, wrap to the next line if(dayCount == 7) { row += '</tr>' html += row row = '<tr>' dayCount = 0 } // output the text that goes inside each td // if the day is the current day, add a class of "selected" // Only show a default date if the selection mode is 'single' row += '<td data-day="' + i + '" class=""><a href="#">' + i + '</a></td>' dayCount++ } // if we haven't finished at the end of the week, start writing out the "days" for the next month for(i = 1; i <= (7 - dayCount); i++) { row += '<td>&nbsp;</td>' } html += row return html }
javascript
function(offset) { var monthNum = this.month offset = offset || 0 monthNum += offset if(monthNum < 0) { monthNum = 11 } if(monthNum > 11) { monthNum = 0 } var month = this.getOffsetMonth(offset) , year = this.getOffsetYear(offset) // get the first day of the month we are currently viewing var firstOfMonth = new Date(year, month, 1).getDay(), // get the total number of days in the month we are currently viewing numDays = this.offsetDaysInMonth(offset), // declare our day counter dayCount = 0, html = '', row = '<tr>' // print out previous month's "days" for(i = 1; i <= firstOfMonth; i++) { row += '<td>&nbsp;</td>' dayCount++ } for(i = 1; i <= numDays; i++) { // if we have reached the end of a week, wrap to the next line if(dayCount == 7) { row += '</tr>' html += row row = '<tr>' dayCount = 0 } // output the text that goes inside each td // if the day is the current day, add a class of "selected" // Only show a default date if the selection mode is 'single' row += '<td data-day="' + i + '" class=""><a href="#">' + i + '</a></td>' dayCount++ } // if we haven't finished at the end of the week, start writing out the "days" for the next month for(i = 1; i <= (7 - dayCount); i++) { row += '<td>&nbsp;</td>' } html += row return html }
[ "function", "(", "offset", ")", "{", "var", "monthNum", "=", "this", ".", "month", "offset", "=", "offset", "||", "0", "monthNum", "+=", "offset", "if", "(", "monthNum", "<", "0", ")", "{", "monthNum", "=", "11", "}", "if", "(", "monthNum", ">", "11", ")", "{", "monthNum", "=", "0", "}", "var", "month", "=", "this", ".", "getOffsetMonth", "(", "offset", ")", ",", "year", "=", "this", ".", "getOffsetYear", "(", "offset", ")", "var", "firstOfMonth", "=", "new", "Date", "(", "year", ",", "month", ",", "1", ")", ".", "getDay", "(", ")", ",", "numDays", "=", "this", ".", "offsetDaysInMonth", "(", "offset", ")", ",", "dayCount", "=", "0", ",", "html", "=", "''", ",", "row", "=", "'<tr>'", "for", "(", "i", "=", "1", ";", "i", "<=", "firstOfMonth", ";", "i", "++", ")", "{", "row", "+=", "'<td>&nbsp;</td>'", "dayCount", "++", "}", "for", "(", "i", "=", "1", ";", "i", "<=", "numDays", ";", "i", "++", ")", "{", "if", "(", "dayCount", "==", "7", ")", "{", "row", "+=", "'</tr>'", "html", "+=", "row", "row", "=", "'<tr>'", "dayCount", "=", "0", "}", "row", "+=", "'<td data-day=\"'", "+", "i", "+", "'\" class=\"\"><a href=\"#\">'", "+", "i", "+", "'</a></td>'", "dayCount", "++", "}", "for", "(", "i", "=", "1", ";", "i", "<=", "(", "7", "-", "dayCount", ")", ";", "i", "++", ")", "{", "row", "+=", "'<td>&nbsp;</td>'", "}", "html", "+=", "row", "return", "html", "}" ]
Builds calendar markup @param integer month offset
[ "Builds", "calendar", "markup" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/calendar.js#L224-L278
train
nwtjs/nwt
plugins/calendar.js
function() { // First deselect everything this.el.all('td.selected').removeClass('selected') for (var i=0,date;date=this.selected[i];i++) { var cell = this.el.one('.pane[data-month="' + date.month + '"][data-year="' + date.year + '"] td[data-day="' + date.day + '"]') if (cell._node) { cell.addClass('selected') } } }
javascript
function() { // First deselect everything this.el.all('td.selected').removeClass('selected') for (var i=0,date;date=this.selected[i];i++) { var cell = this.el.one('.pane[data-month="' + date.month + '"][data-year="' + date.year + '"] td[data-day="' + date.day + '"]') if (cell._node) { cell.addClass('selected') } } }
[ "function", "(", ")", "{", "this", ".", "el", ".", "all", "(", "'td.selected'", ")", ".", "removeClass", "(", "'selected'", ")", "for", "(", "var", "i", "=", "0", ",", "date", ";", "date", "=", "this", ".", "selected", "[", "i", "]", ";", "i", "++", ")", "{", "var", "cell", "=", "this", ".", "el", ".", "one", "(", "'.pane[data-month=\"'", "+", "date", ".", "month", "+", "'\"][data-year=\"'", "+", "date", ".", "year", "+", "'\"] td[data-day=\"'", "+", "date", ".", "day", "+", "'\"]'", ")", "if", "(", "cell", ".", "_node", ")", "{", "cell", ".", "addClass", "(", "'selected'", ")", "}", "}", "}" ]
Selects all cells in this.selection
[ "Selects", "all", "cells", "in", "this", ".", "selection" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/calendar.js#L284-L294
train
danShumway/serverboy.js
src/interface.js
function () { let _that = this[PRIVATE]; if (_that.initialized() && _that.running()) { _that.gameboy.stopEmulator |= 2; _that.frames = 0; //Reset internal variables } }
javascript
function () { let _that = this[PRIVATE]; if (_that.initialized() && _that.running()) { _that.gameboy.stopEmulator |= 2; _that.frames = 0; //Reset internal variables } }
[ "function", "(", ")", "{", "let", "_that", "=", "this", "[", "PRIVATE", "]", ";", "if", "(", "_that", ".", "initialized", "(", ")", "&&", "_that", ".", "running", "(", ")", ")", "{", "_that", ".", "gameboy", ".", "stopEmulator", "|=", "2", ";", "_that", ".", "frames", "=", "0", ";", "}", "}" ]
Stop emulator, reset relevant variables
[ "Stop", "emulator", "reset", "relevant", "variables" ]
68f0ac88b5b280f64de2c8ae6d57d8a84cbe3628
https://github.com/danShumway/serverboy.js/blob/68f0ac88b5b280f64de2c8ae6d57d8a84cbe3628/src/interface.js#L61-L67
train
xiaoyuze88/isomorphic-pkg-reader
lib/plistParser/bplistParser.js
readUInt64BE
function readUInt64BE(buffer, start) { var data = buffer.slice(start, start + 8); return data.readUInt32BE(4, 8); }
javascript
function readUInt64BE(buffer, start) { var data = buffer.slice(start, start + 8); return data.readUInt32BE(4, 8); }
[ "function", "readUInt64BE", "(", "buffer", ",", "start", ")", "{", "var", "data", "=", "buffer", ".", "slice", "(", "start", ",", "start", "+", "8", ")", ";", "return", "data", ".", "readUInt32BE", "(", "4", ",", "8", ")", ";", "}" ]
we're just going to toss the high order bits because javascript doesn't have 64-bit ints
[ "we", "re", "just", "going", "to", "toss", "the", "high", "order", "bits", "because", "javascript", "doesn", "t", "have", "64", "-", "bit", "ints" ]
d38a409035d0b4f50df4659a95695a27e7b3078c
https://github.com/xiaoyuze88/isomorphic-pkg-reader/blob/d38a409035d0b4f50df4659a95695a27e7b3078c/lib/plistParser/bplistParser.js#L296-L299
train
LeanKit-Labs/autohost
src/http/http.js
expressInit
function expressInit( req, res, next ) { req.next = next; req.context = {}; // patching this according to how express does it // not jshint ignoring the following lines because then it // warns that expreq and expres aren't used. // This works according to express implemenetation // DO NOT CHANGE IT req.__proto__ = expreq; res.__proto__ = expres; next(); }
javascript
function expressInit( req, res, next ) { req.next = next; req.context = {}; // patching this according to how express does it // not jshint ignoring the following lines because then it // warns that expreq and expres aren't used. // This works according to express implemenetation // DO NOT CHANGE IT req.__proto__ = expreq; res.__proto__ = expres; next(); }
[ "function", "expressInit", "(", "req", ",", "res", ",", "next", ")", "{", "req", ".", "next", "=", "next", ";", "req", ".", "context", "=", "{", "}", ";", "req", ".", "__proto__", "=", "expreq", ";", "res", ".", "__proto__", "=", "expres", ";", "next", "(", ")", ";", "}" ]
adaptation of express's initializing middleware the original approach breaks engine-io
[ "adaptation", "of", "express", "s", "initializing", "middleware", "the", "original", "approach", "breaks", "engine", "-", "io" ]
b143e99336cbecf5ac5712c2b0c77cc091081983
https://github.com/LeanKit-Labs/autohost/blob/b143e99336cbecf5ac5712c2b0c77cc091081983/src/http/http.js#L63-L75
train
LeanKit-Labs/autohost
src/http/http.js
parseAhead
function parseAhead( router, req, done ) { var idx = 0; var stack = router.stack; var params = {}; var method = req.method ? req.method.toLowerCase() : undefined; next(); function next() { var layer = stack[ idx++ ]; if ( !layer ) { // strip dangling query params params = _.transform( params, function( acc, v, k ) { acc[ k ] = v.split( '?' )[ 0 ]; return acc; }, {} ); return done( params ); } if ( layer.method && layer.method !== method ) { return next(); } layer.match( req.originalUrl ); params = _.merge( params, layer.params ); next(); } }
javascript
function parseAhead( router, req, done ) { var idx = 0; var stack = router.stack; var params = {}; var method = req.method ? req.method.toLowerCase() : undefined; next(); function next() { var layer = stack[ idx++ ]; if ( !layer ) { // strip dangling query params params = _.transform( params, function( acc, v, k ) { acc[ k ] = v.split( '?' )[ 0 ]; return acc; }, {} ); return done( params ); } if ( layer.method && layer.method !== method ) { return next(); } layer.match( req.originalUrl ); params = _.merge( params, layer.params ); next(); } }
[ "function", "parseAhead", "(", "router", ",", "req", ",", "done", ")", "{", "var", "idx", "=", "0", ";", "var", "stack", "=", "router", ".", "stack", ";", "var", "params", "=", "{", "}", ";", "var", "method", "=", "req", ".", "method", "?", "req", ".", "method", ".", "toLowerCase", "(", ")", ":", "undefined", ";", "next", "(", ")", ";", "function", "next", "(", ")", "{", "var", "layer", "=", "stack", "[", "idx", "++", "]", ";", "if", "(", "!", "layer", ")", "{", "params", "=", "_", ".", "transform", "(", "params", ",", "function", "(", "acc", ",", "v", ",", "k", ")", "{", "acc", "[", "k", "]", "=", "v", ".", "split", "(", "'?'", ")", "[", "0", "]", ";", "return", "acc", ";", "}", ",", "{", "}", ")", ";", "return", "done", "(", "params", ")", ";", "}", "if", "(", "layer", ".", "method", "&&", "layer", ".", "method", "!==", "method", ")", "{", "return", "next", "(", ")", ";", "}", "layer", ".", "match", "(", "req", ".", "originalUrl", ")", ";", "params", "=", "_", ".", "merge", "(", "params", ",", "layer", ".", "params", ")", ";", "next", "(", ")", ";", "}", "}" ]
this might be the worst thing to ever happen to anything ever this is adapted directly from express layer.match
[ "this", "might", "be", "the", "worst", "thing", "to", "ever", "happen", "to", "anything", "ever", "this", "is", "adapted", "directly", "from", "express", "layer", ".", "match" ]
b143e99336cbecf5ac5712c2b0c77cc091081983
https://github.com/LeanKit-Labs/autohost/blob/b143e99336cbecf5ac5712c2b0c77cc091081983/src/http/http.js#L114-L138
train
LeanKit-Labs/autohost
src/http/http.js
prefix
function prefix( state, url ) { if ( state.config.urlPrefix ) { if ( _.isRegExp( url ) ) { return regex.prefix( state.config.urlPrefix, url ); } else { var prefixIndex = url.indexOf( state.config.urlPrefix ); var appliedPrefix = prefixIndex === 0 ? '' : state.config.urlPrefix; return buildUrl( appliedPrefix, url ); } } else { return url; } }
javascript
function prefix( state, url ) { if ( state.config.urlPrefix ) { if ( _.isRegExp( url ) ) { return regex.prefix( state.config.urlPrefix, url ); } else { var prefixIndex = url.indexOf( state.config.urlPrefix ); var appliedPrefix = prefixIndex === 0 ? '' : state.config.urlPrefix; return buildUrl( appliedPrefix, url ); } } else { return url; } }
[ "function", "prefix", "(", "state", ",", "url", ")", "{", "if", "(", "state", ".", "config", ".", "urlPrefix", ")", "{", "if", "(", "_", ".", "isRegExp", "(", "url", ")", ")", "{", "return", "regex", ".", "prefix", "(", "state", ".", "config", ".", "urlPrefix", ",", "url", ")", ";", "}", "else", "{", "var", "prefixIndex", "=", "url", ".", "indexOf", "(", "state", ".", "config", ".", "urlPrefix", ")", ";", "var", "appliedPrefix", "=", "prefixIndex", "===", "0", "?", "''", ":", "state", ".", "config", ".", "urlPrefix", ";", "return", "buildUrl", "(", "appliedPrefix", ",", "url", ")", ";", "}", "}", "else", "{", "return", "url", ";", "}", "}" ]
apply prefix to url if one exists
[ "apply", "prefix", "to", "url", "if", "one", "exists" ]
b143e99336cbecf5ac5712c2b0c77cc091081983
https://github.com/LeanKit-Labs/autohost/blob/b143e99336cbecf5ac5712c2b0c77cc091081983/src/http/http.js#L141-L153
train
nwtjs/nwt
src/nodelist/js/nodelist.js
NWTNodeList
function NWTNodeList(nodes) { localnwt.implement('DelayableQueue', this); var wrappedNodes = []; for( var i = 0, node ; node = nodes[i] ; i++ ) { wrappedNodes.push(new NWTNodeInstance(node)); } this.nodes = wrappedNodes; var iteratedFunctions = [ 'anim', 'appendTo', 'remove', 'addClass', 'removeClass', 'setStyle', 'setStyles', 'removeStyle', 'removeStyles', 'swapClass', 'plug' ], mythis = this; function getIteratedCallback(method) { return function() { for( var j = 0 , node ; node = mythis.nodes[j] ; j++ ) { node[method].apply(node, arguments); } return mythis; }; }; for( var i = 0, func; func = iteratedFunctions[i] ; i++ ) { this[func] = getIteratedCallback(func); } }
javascript
function NWTNodeList(nodes) { localnwt.implement('DelayableQueue', this); var wrappedNodes = []; for( var i = 0, node ; node = nodes[i] ; i++ ) { wrappedNodes.push(new NWTNodeInstance(node)); } this.nodes = wrappedNodes; var iteratedFunctions = [ 'anim', 'appendTo', 'remove', 'addClass', 'removeClass', 'setStyle', 'setStyles', 'removeStyle', 'removeStyles', 'swapClass', 'plug' ], mythis = this; function getIteratedCallback(method) { return function() { for( var j = 0 , node ; node = mythis.nodes[j] ; j++ ) { node[method].apply(node, arguments); } return mythis; }; }; for( var i = 0, func; func = iteratedFunctions[i] ; i++ ) { this[func] = getIteratedCallback(func); } }
[ "function", "NWTNodeList", "(", "nodes", ")", "{", "localnwt", ".", "implement", "(", "'DelayableQueue'", ",", "this", ")", ";", "var", "wrappedNodes", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "node", ";", "node", "=", "nodes", "[", "i", "]", ";", "i", "++", ")", "{", "wrappedNodes", ".", "push", "(", "new", "NWTNodeInstance", "(", "node", ")", ")", ";", "}", "this", ".", "nodes", "=", "wrappedNodes", ";", "var", "iteratedFunctions", "=", "[", "'anim'", ",", "'appendTo'", ",", "'remove'", ",", "'addClass'", ",", "'removeClass'", ",", "'setStyle'", ",", "'setStyles'", ",", "'removeStyle'", ",", "'removeStyles'", ",", "'swapClass'", ",", "'plug'", "]", ",", "mythis", "=", "this", ";", "function", "getIteratedCallback", "(", "method", ")", "{", "return", "function", "(", ")", "{", "for", "(", "var", "j", "=", "0", ",", "node", ";", "node", "=", "mythis", ".", "nodes", "[", "j", "]", ";", "j", "++", ")", "{", "node", "[", "method", "]", ".", "apply", "(", "node", ",", "arguments", ")", ";", "}", "return", "mythis", ";", "}", ";", "}", ";", "for", "(", "var", "i", "=", "0", ",", "func", ";", "func", "=", "iteratedFunctions", "[", "i", "]", ";", "i", "++", ")", "{", "this", "[", "func", "]", "=", "getIteratedCallback", "(", "func", ")", ";", "}", "}" ]
A node iterator @constructor
[ "A", "node", "iterator" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/nodelist/js/nodelist.js#L5-L34
train
CodeCatalyst/grunt-sketch
tasks/sketch.js
registerTask
function registerTask( task ) { grunt.registerMultiTask( task.name, task.help, function () { var done = this.async(); if ( ensureSketchtool() ) { var options = this.options(); var commands = []; this.files.forEach( function( file ) { file.src.filter( function ( src ) { var command = createCommand( task, src, file.dest, options ); if ( command ) { commands.push( command ); } } ); }); async.eachLimit( commands, numCPUs, function ( command, next ) { executeCommand( command, next ); }, done ); } else { done(false); } } ); }
javascript
function registerTask( task ) { grunt.registerMultiTask( task.name, task.help, function () { var done = this.async(); if ( ensureSketchtool() ) { var options = this.options(); var commands = []; this.files.forEach( function( file ) { file.src.filter( function ( src ) { var command = createCommand( task, src, file.dest, options ); if ( command ) { commands.push( command ); } } ); }); async.eachLimit( commands, numCPUs, function ( command, next ) { executeCommand( command, next ); }, done ); } else { done(false); } } ); }
[ "function", "registerTask", "(", "task", ")", "{", "grunt", ".", "registerMultiTask", "(", "task", ".", "name", ",", "task", ".", "help", ",", "function", "(", ")", "{", "var", "done", "=", "this", ".", "async", "(", ")", ";", "if", "(", "ensureSketchtool", "(", ")", ")", "{", "var", "options", "=", "this", ".", "options", "(", ")", ";", "var", "commands", "=", "[", "]", ";", "this", ".", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "file", ".", "src", ".", "filter", "(", "function", "(", "src", ")", "{", "var", "command", "=", "createCommand", "(", "task", ",", "src", ",", "file", ".", "dest", ",", "options", ")", ";", "if", "(", "command", ")", "{", "commands", ".", "push", "(", "command", ")", ";", "}", "}", ")", ";", "}", ")", ";", "async", ".", "eachLimit", "(", "commands", ",", "numCPUs", ",", "function", "(", "command", ",", "next", ")", "{", "executeCommand", "(", "command", ",", "next", ")", ";", "}", ",", "done", ")", ";", "}", "else", "{", "done", "(", "false", ")", ";", "}", "}", ")", ";", "}" ]
Internal helper functions.
[ "Internal", "helper", "functions", "." ]
4ba6591c93f5d65d8abde702a40f7d778cb469b5
https://github.com/CodeCatalyst/grunt-sketch/blob/4ba6591c93f5d65d8abde702a40f7d778cb469b5/tasks/sketch.js#L147-L170
train
xiaoyuze88/isomorphic-pkg-reader
lib/plistParser/xmlPlistParser.js
parseString
function parseString (xml, callback) { var doc, error, plist; try { doc = new DOMParser().parseFromString(xml); plist = parsePlistXML(doc.documentElement); } catch(e) { error = e; } callback(error, plist); }
javascript
function parseString (xml, callback) { var doc, error, plist; try { doc = new DOMParser().parseFromString(xml); plist = parsePlistXML(doc.documentElement); } catch(e) { error = e; } callback(error, plist); }
[ "function", "parseString", "(", "xml", ",", "callback", ")", "{", "var", "doc", ",", "error", ",", "plist", ";", "try", "{", "doc", "=", "new", "DOMParser", "(", ")", ".", "parseFromString", "(", "xml", ")", ";", "plist", "=", "parsePlistXML", "(", "doc", ".", "documentElement", ")", ";", "}", "catch", "(", "e", ")", "{", "error", "=", "e", ";", "}", "callback", "(", "error", ",", "plist", ")", ";", "}" ]
Parses a Plist XML string. Returns an Object. Takes a `callback` function. @param {String} xml - the XML String to decode @param {Function} callback - callback function @returns {Mixed} the decoded value from the Plist XML @api public @deprecated not actually async. use parse() instead
[ "Parses", "a", "Plist", "XML", "string", ".", "Returns", "an", "Object", ".", "Takes", "a", "callback", "function", "." ]
d38a409035d0b4f50df4659a95695a27e7b3078c
https://github.com/xiaoyuze88/isomorphic-pkg-reader/blob/d38a409035d0b4f50df4659a95695a27e7b3078c/lib/plistParser/xmlPlistParser.js#L57-L66
train
xiaoyuze88/isomorphic-pkg-reader
lib/plistParser/xmlPlistParser.js
parseStringSync
function parseStringSync (xml) { var doc = new DOMParser().parseFromString(xml); var plist; if (doc.documentElement.nodeName !== 'plist') { throw new Error('malformed document. First element should be <plist>'); } plist = parsePlistXML(doc.documentElement); // if the plist is an array with 1 element, pull it out of the array if (plist.length == 1) { plist = plist[0]; } return plist; }
javascript
function parseStringSync (xml) { var doc = new DOMParser().parseFromString(xml); var plist; if (doc.documentElement.nodeName !== 'plist') { throw new Error('malformed document. First element should be <plist>'); } plist = parsePlistXML(doc.documentElement); // if the plist is an array with 1 element, pull it out of the array if (plist.length == 1) { plist = plist[0]; } return plist; }
[ "function", "parseStringSync", "(", "xml", ")", "{", "var", "doc", "=", "new", "DOMParser", "(", ")", ".", "parseFromString", "(", "xml", ")", ";", "var", "plist", ";", "if", "(", "doc", ".", "documentElement", ".", "nodeName", "!==", "'plist'", ")", "{", "throw", "new", "Error", "(", "'malformed document. First element should be <plist>'", ")", ";", "}", "plist", "=", "parsePlistXML", "(", "doc", ".", "documentElement", ")", ";", "if", "(", "plist", ".", "length", "==", "1", ")", "{", "plist", "=", "plist", "[", "0", "]", ";", "}", "return", "plist", ";", "}" ]
Parses a Plist XML string. Returns an Object. @param {String} xml - the XML String to decode @param {Function} callback - callback function @returns {Mixed} the decoded value from the Plist XML @api public @deprecated use parse() instead
[ "Parses", "a", "Plist", "XML", "string", ".", "Returns", "an", "Object", "." ]
d38a409035d0b4f50df4659a95695a27e7b3078c
https://github.com/xiaoyuze88/isomorphic-pkg-reader/blob/d38a409035d0b4f50df4659a95695a27e7b3078c/lib/plistParser/xmlPlistParser.js#L78-L91
train
nwtjs/nwt
nwt.js
function(implClass, modClass) { var impls = { DelayableQueue : [ /** * Returns a queueable interface to the original object * This allows us to insert delays between chainable method calls using the .wait() method * Currently this is only implemented for the node class, but it should be possible to use this with any object. */ 'wait', function () { /** * Queueable object which implements methods from another interface * @param object Context for the callback */ function QueueableObject(context) { this.queue = []; this.context = context; this.inWork = false; } QueueableObject.prototype = { _add: function(func, args) { var self = this; self.queue.push({type: 'chain', func: func, args: args}); if (!self.inWork) { return self._process(); } }, /** * Process the queue * Shifts an item off the queue and waits for it to finish */ _process: function() { var self = this, item; self.inWork = true; if (!self.queue.length) { return; } item = self.queue.shift(); if (item.type == 'wait') { setTimeout(function(){ self._process(); }, item.duration*1000); } else { self.context = item.func.apply(self.context, item.args); self._process(); } return self; }, /** * Updates the current delay timer */ wait: function(duration) { this.queue.push({type: 'wait', duration: duration}); return this; } }; return function (duration) { var self = this, mockObj = new QueueableObject(self); /** * Returns an executable function * uses setTimeout and the total queueTimer */ getQueuedFunction = function(func) { return function() { mockObj._add(func, arguments); return mockObj; } }; /** * Wrap all class functions * We can unwrap at the end if the current wait is 0 */ for( var i in self ) { if (typeof self[i] != 'function' || i == 'wait' ) { continue; } mockObj[i] = getQueuedFunction(self[i]); } mockObj.wait(duration); return mockObj; } } ] }; modClass[impls[implClass][0]] = impls[implClass][1](); }
javascript
function(implClass, modClass) { var impls = { DelayableQueue : [ /** * Returns a queueable interface to the original object * This allows us to insert delays between chainable method calls using the .wait() method * Currently this is only implemented for the node class, but it should be possible to use this with any object. */ 'wait', function () { /** * Queueable object which implements methods from another interface * @param object Context for the callback */ function QueueableObject(context) { this.queue = []; this.context = context; this.inWork = false; } QueueableObject.prototype = { _add: function(func, args) { var self = this; self.queue.push({type: 'chain', func: func, args: args}); if (!self.inWork) { return self._process(); } }, /** * Process the queue * Shifts an item off the queue and waits for it to finish */ _process: function() { var self = this, item; self.inWork = true; if (!self.queue.length) { return; } item = self.queue.shift(); if (item.type == 'wait') { setTimeout(function(){ self._process(); }, item.duration*1000); } else { self.context = item.func.apply(self.context, item.args); self._process(); } return self; }, /** * Updates the current delay timer */ wait: function(duration) { this.queue.push({type: 'wait', duration: duration}); return this; } }; return function (duration) { var self = this, mockObj = new QueueableObject(self); /** * Returns an executable function * uses setTimeout and the total queueTimer */ getQueuedFunction = function(func) { return function() { mockObj._add(func, arguments); return mockObj; } }; /** * Wrap all class functions * We can unwrap at the end if the current wait is 0 */ for( var i in self ) { if (typeof self[i] != 'function' || i == 'wait' ) { continue; } mockObj[i] = getQueuedFunction(self[i]); } mockObj.wait(duration); return mockObj; } } ] }; modClass[impls[implClass][0]] = impls[implClass][1](); }
[ "function", "(", "implClass", ",", "modClass", ")", "{", "var", "impls", "=", "{", "DelayableQueue", ":", "[", "'wait'", ",", "function", "(", ")", "{", "function", "QueueableObject", "(", "context", ")", "{", "this", ".", "queue", "=", "[", "]", ";", "this", ".", "context", "=", "context", ";", "this", ".", "inWork", "=", "false", ";", "}", "QueueableObject", ".", "prototype", "=", "{", "_add", ":", "function", "(", "func", ",", "args", ")", "{", "var", "self", "=", "this", ";", "self", ".", "queue", ".", "push", "(", "{", "type", ":", "'chain'", ",", "func", ":", "func", ",", "args", ":", "args", "}", ")", ";", "if", "(", "!", "self", ".", "inWork", ")", "{", "return", "self", ".", "_process", "(", ")", ";", "}", "}", ",", "_process", ":", "function", "(", ")", "{", "var", "self", "=", "this", ",", "item", ";", "self", ".", "inWork", "=", "true", ";", "if", "(", "!", "self", ".", "queue", ".", "length", ")", "{", "return", ";", "}", "item", "=", "self", ".", "queue", ".", "shift", "(", ")", ";", "if", "(", "item", ".", "type", "==", "'wait'", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "self", ".", "_process", "(", ")", ";", "}", ",", "item", ".", "duration", "*", "1000", ")", ";", "}", "else", "{", "self", ".", "context", "=", "item", ".", "func", ".", "apply", "(", "self", ".", "context", ",", "item", ".", "args", ")", ";", "self", ".", "_process", "(", ")", ";", "}", "return", "self", ";", "}", ",", "wait", ":", "function", "(", "duration", ")", "{", "this", ".", "queue", ".", "push", "(", "{", "type", ":", "'wait'", ",", "duration", ":", "duration", "}", ")", ";", "return", "this", ";", "}", "}", ";", "return", "function", "(", "duration", ")", "{", "var", "self", "=", "this", ",", "mockObj", "=", "new", "QueueableObject", "(", "self", ")", ";", "getQueuedFunction", "=", "function", "(", "func", ")", "{", "return", "function", "(", ")", "{", "mockObj", ".", "_add", "(", "func", ",", "arguments", ")", ";", "return", "mockObj", ";", "}", "}", ";", "for", "(", "var", "i", "in", "self", ")", "{", "if", "(", "typeof", "self", "[", "i", "]", "!=", "'function'", "||", "i", "==", "'wait'", ")", "{", "continue", ";", "}", "mockObj", "[", "i", "]", "=", "getQueuedFunction", "(", "self", "[", "i", "]", ")", ";", "}", "mockObj", ".", "wait", "(", "duration", ")", ";", "return", "mockObj", ";", "}", "}", "]", "}", ";", "modClass", "[", "impls", "[", "implClass", "]", "[", "0", "]", "]", "=", "impls", "[", "implClass", "]", "[", "1", "]", "(", ")", ";", "}" ]
Implements an interface on an object
[ "Implements", "an", "interface", "on", "an", "object" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/nwt.js#L15-L118
train
nwtjs/nwt
nwt.js
function() { var self = this, item; self.inWork = true; if (!self.queue.length) { return; } item = self.queue.shift(); if (item.type == 'wait') { setTimeout(function(){ self._process(); }, item.duration*1000); } else { self.context = item.func.apply(self.context, item.args); self._process(); } return self; }
javascript
function() { var self = this, item; self.inWork = true; if (!self.queue.length) { return; } item = self.queue.shift(); if (item.type == 'wait') { setTimeout(function(){ self._process(); }, item.duration*1000); } else { self.context = item.func.apply(self.context, item.args); self._process(); } return self; }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "item", ";", "self", ".", "inWork", "=", "true", ";", "if", "(", "!", "self", ".", "queue", ".", "length", ")", "{", "return", ";", "}", "item", "=", "self", ".", "queue", ".", "shift", "(", ")", ";", "if", "(", "item", ".", "type", "==", "'wait'", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "self", ".", "_process", "(", ")", ";", "}", ",", "item", ".", "duration", "*", "1000", ")", ";", "}", "else", "{", "self", ".", "context", "=", "item", ".", "func", ".", "apply", "(", "self", ".", "context", ",", "item", ".", "args", ")", ";", "self", ".", "_process", "(", ")", ";", "}", "return", "self", ";", "}" ]
Process the queue Shifts an item off the queue and waits for it to finish
[ "Process", "the", "queue", "Shifts", "an", "item", "off", "the", "queue", "and", "waits", "for", "it", "to", "finish" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/nwt.js#L52-L73
train
nwtjs/nwt
nwt.js
function(event, callback) { var args = Array.prototype.slice.call(arguments, 1); localnwt.event._eventData = args; var customEvt = y.createEvent("UIEvents"); customEvt.initEvent(event, true, false); this._node.dispatchEvent(customEvt); }
javascript
function(event, callback) { var args = Array.prototype.slice.call(arguments, 1); localnwt.event._eventData = args; var customEvt = y.createEvent("UIEvents"); customEvt.initEvent(event, true, false); this._node.dispatchEvent(customEvt); }
[ "function", "(", "event", ",", "callback", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "localnwt", ".", "event", ".", "_eventData", "=", "args", ";", "var", "customEvt", "=", "y", ".", "createEvent", "(", "\"UIEvents\"", ")", ";", "customEvt", ".", "initEvent", "(", "event", ",", "true", ",", "false", ")", ";", "this", ".", "_node", ".", "dispatchEvent", "(", "customEvt", ")", ";", "}" ]
Fires an event on a node
[ "Fires", "an", "event", "on", "a", "node" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/nwt.js#L1034-L1042
train
mojaie/kiwiii
src/common/specs.js
isRunning
function isRunning(specs) { return specs.dataset.some(coll => { return coll.contents.some(e => { return ['ready', 'queued', 'running', 'interrupted'].includes(e.status); }); }); }
javascript
function isRunning(specs) { return specs.dataset.some(coll => { return coll.contents.some(e => { return ['ready', 'queued', 'running', 'interrupted'].includes(e.status); }); }); }
[ "function", "isRunning", "(", "specs", ")", "{", "return", "specs", ".", "dataset", ".", "some", "(", "coll", "=>", "{", "return", "coll", ".", "contents", ".", "some", "(", "e", "=>", "{", "return", "[", "'ready'", ",", "'queued'", ",", "'running'", ",", "'interrupted'", "]", ".", "includes", "(", "e", ".", "status", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Retern if the package has running tasks @param {object} specs - package JSON @return {bool} if there are any ongoing tasks
[ "Retern", "if", "the", "package", "has", "running", "tasks" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/specs.js#L12-L18
train
nwtjs/nwt
plugins/bootstrap/typeahead.js
function(dir) { var curr = this.menu.one('li.active'), targetNode = curr[dir](); this.menu.one('li.active').removeClass('active'); targetNode.addClass('active'); return this; }
javascript
function(dir) { var curr = this.menu.one('li.active'), targetNode = curr[dir](); this.menu.one('li.active').removeClass('active'); targetNode.addClass('active'); return this; }
[ "function", "(", "dir", ")", "{", "var", "curr", "=", "this", ".", "menu", ".", "one", "(", "'li.active'", ")", ",", "targetNode", "=", "curr", "[", "dir", "]", "(", ")", ";", "this", ".", "menu", ".", "one", "(", "'li.active'", ")", ".", "removeClass", "(", "'active'", ")", ";", "targetNode", ".", "addClass", "(", "'active'", ")", ";", "return", "this", ";", "}" ]
Moves the active selected item @param string (next | previous)
[ "Moves", "the", "active", "selected", "item" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/typeahead.js#L105-L113
train
nwtjs/nwt
plugins/bootstrap/typeahead.js
function(items) { var itemMarkup = '', i; for (i=0; i< items.length; i++) { itemMarkup += '<li><a href="#" data-value="' + items[i] + '">' + this.highlighter(items[i]) + '</a></li>'; } var inputRegion = this.node.region(); this.menu.setHtml(itemMarkup) this.menu.one('li').addClass('active') this.menu.setStyles({ left: inputRegion.left, top: inputRegion.bottom, display:'block' }); this.node.fire('typeahead:show') return this; }
javascript
function(items) { var itemMarkup = '', i; for (i=0; i< items.length; i++) { itemMarkup += '<li><a href="#" data-value="' + items[i] + '">' + this.highlighter(items[i]) + '</a></li>'; } var inputRegion = this.node.region(); this.menu.setHtml(itemMarkup) this.menu.one('li').addClass('active') this.menu.setStyles({ left: inputRegion.left, top: inputRegion.bottom, display:'block' }); this.node.fire('typeahead:show') return this; }
[ "function", "(", "items", ")", "{", "var", "itemMarkup", "=", "''", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "items", ".", "length", ";", "i", "++", ")", "{", "itemMarkup", "+=", "'<li><a href=\"#\" data-value=\"'", "+", "items", "[", "i", "]", "+", "'\">'", "+", "this", ".", "highlighter", "(", "items", "[", "i", "]", ")", "+", "'</a></li>'", ";", "}", "var", "inputRegion", "=", "this", ".", "node", ".", "region", "(", ")", ";", "this", ".", "menu", ".", "setHtml", "(", "itemMarkup", ")", "this", ".", "menu", ".", "one", "(", "'li'", ")", ".", "addClass", "(", "'active'", ")", "this", ".", "menu", ".", "setStyles", "(", "{", "left", ":", "inputRegion", ".", "left", ",", "top", ":", "inputRegion", ".", "bottom", ",", "display", ":", "'block'", "}", ")", ";", "this", ".", "node", ".", "fire", "(", "'typeahead:show'", ")", "return", "this", ";", "}" ]
Renders the typeahead items @param array Matched items to render
[ "Renders", "the", "typeahead", "items" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/typeahead.js#L132-L153
train
artdecocode/erotic
build/index.js
erotic
function erotic(transparent) { const { stack } = new Error() const caller = getCallerFromArguments(arguments) const entryStack = getEntryStack(stack, transparent) return makeCallback(caller, entryStack, transparent) }
javascript
function erotic(transparent) { const { stack } = new Error() const caller = getCallerFromArguments(arguments) const entryStack = getEntryStack(stack, transparent) return makeCallback(caller, entryStack, transparent) }
[ "function", "erotic", "(", "transparent", ")", "{", "const", "{", "stack", "}", "=", "new", "Error", "(", ")", "const", "caller", "=", "getCallerFromArguments", "(", "arguments", ")", "const", "entryStack", "=", "getEntryStack", "(", "stack", ",", "transparent", ")", "return", "makeCallback", "(", "caller", ",", "entryStack", ",", "transparent", ")", "}" ]
Returns a function to create an error with a stack trace starting at the line in code when the call was made by the callee. @param {boolean} [transparent] Pretend as if the call to the function lead to the error, without exposing any of the internal stack.
[ "Returns", "a", "function", "to", "create", "an", "error", "with", "a", "stack", "trace", "starting", "at", "the", "line", "in", "code", "when", "the", "call", "was", "made", "by", "the", "callee", "." ]
2d8cb268bd6ddc64a8bb90ac25d388e553866a0a
https://github.com/artdecocode/erotic/blob/2d8cb268bd6ddc64a8bb90ac25d388e553866a0a/build/index.js#L10-L16
train
chriskinsman/s3-stream-download
index.js
S3StreamDownload
function S3StreamDownload (s3, s3Params, options) { var downloader = new Downloader(s3, s3Params, options); return new DownloadStream(downloader); }
javascript
function S3StreamDownload (s3, s3Params, options) { var downloader = new Downloader(s3, s3Params, options); return new DownloadStream(downloader); }
[ "function", "S3StreamDownload", "(", "s3", ",", "s3Params", ",", "options", ")", "{", "var", "downloader", "=", "new", "Downloader", "(", "s3", ",", "s3Params", ",", "options", ")", ";", "return", "new", "DownloadStream", "(", "downloader", ")", ";", "}" ]
Creates a stream for download via multipart stream to S3. @params {S3} s3 @params {Object} s3Params @params {Object} options
[ "Creates", "a", "stream", "for", "download", "via", "multipart", "stream", "to", "S3", "." ]
e78dcd38e6a06ef0d8f47f1c8951d65ad5c6f93c
https://github.com/chriskinsman/s3-stream-download/blob/e78dcd38e6a06ef0d8f47f1c8951d65ad5c6f93c/index.js#L18-L21
train
recidive/choko
lib/application.js
function(next) { self.loadAllExtensions(function() { // Add middleware to make html5mode work in angular. self.routers.page.use(function(request, response, next) { // If between JSON and HTML it prefers HTML, return index.html content since // we know its a direct browser request or another HTML consuming client. if (request.accepts(['json', 'html']) === 'html') { // Serve the right index.html taking into account overrides. return self.staticDiscover('index.html', function(indexFile) { response.status(200).sendFile(indexFile); }); } next(); }); next(); }); }
javascript
function(next) { self.loadAllExtensions(function() { // Add middleware to make html5mode work in angular. self.routers.page.use(function(request, response, next) { // If between JSON and HTML it prefers HTML, return index.html content since // we know its a direct browser request or another HTML consuming client. if (request.accepts(['json', 'html']) === 'html') { // Serve the right index.html taking into account overrides. return self.staticDiscover('index.html', function(indexFile) { response.status(200).sendFile(indexFile); }); } next(); }); next(); }); }
[ "function", "(", "next", ")", "{", "self", ".", "loadAllExtensions", "(", "function", "(", ")", "{", "self", ".", "routers", ".", "page", ".", "use", "(", "function", "(", "request", ",", "response", ",", "next", ")", "{", "if", "(", "request", ".", "accepts", "(", "[", "'json'", ",", "'html'", "]", ")", "===", "'html'", ")", "{", "return", "self", ".", "staticDiscover", "(", "'index.html'", ",", "function", "(", "indexFile", ")", "{", "response", ".", "status", "(", "200", ")", ".", "sendFile", "(", "indexFile", ")", ";", "}", ")", ";", "}", "next", "(", ")", ";", "}", ")", ";", "next", "(", ")", ";", "}", ")", ";", "}" ]
Load all extensions and call init hooks on all of them.
[ "Load", "all", "extensions", "and", "call", "init", "hooks", "on", "all", "of", "them", "." ]
7c0576c8c55543ec99d04ea609700765f178f73a
https://github.com/recidive/choko/blob/7c0576c8c55543ec99d04ea609700765f178f73a/lib/application.js#L125-L141
train
recidive/choko
lib/application.js
function(next) { self.collect('field', function(error, fields) { if (error) { return callback(error); } self.fields = fields; self.loadAllTypes(next); }); }
javascript
function(next) { self.collect('field', function(error, fields) { if (error) { return callback(error); } self.fields = fields; self.loadAllTypes(next); }); }
[ "function", "(", "next", ")", "{", "self", ".", "collect", "(", "'field'", ",", "function", "(", "error", ",", "fields", ")", "{", "if", "(", "error", ")", "{", "return", "callback", "(", "error", ")", ";", "}", "self", ".", "fields", "=", "fields", ";", "self", ".", "loadAllTypes", "(", "next", ")", ";", "}", ")", ";", "}" ]
Load all fields and types.
[ "Load", "all", "fields", "and", "types", "." ]
7c0576c8c55543ec99d04ea609700765f178f73a
https://github.com/recidive/choko/blob/7c0576c8c55543ec99d04ea609700765f178f73a/lib/application.js#L144-L153
train
recidive/choko
lib/application.js
function(next) { self.storage.init(function(error, collections) { if (error) { return next(error); } self.collections = collections; next(); }); }
javascript
function(next) { self.storage.init(function(error, collections) { if (error) { return next(error); } self.collections = collections; next(); }); }
[ "function", "(", "next", ")", "{", "self", ".", "storage", ".", "init", "(", "function", "(", "error", ",", "collections", ")", "{", "if", "(", "error", ")", "{", "return", "next", "(", "error", ")", ";", "}", "self", ".", "collections", "=", "collections", ";", "next", "(", ")", ";", "}", ")", ";", "}" ]
Initialize Storage.
[ "Initialize", "Storage", "." ]
7c0576c8c55543ec99d04ea609700765f178f73a
https://github.com/recidive/choko/blob/7c0576c8c55543ec99d04ea609700765f178f73a/lib/application.js#L156-L164
train
cludden/mycro
hooks/routes/index.js
processHandler
function processHandler(fn) { if (_.isFunction(handler)) { return fn(null, handler); } if (_.isString(handler)) { return self.processStringHandler(mycro, handler, fn); } if (_.isObject(handler)) { // make sure the object defines a `handler` attribute if (!handler.handler) { return fn('Unable to locate handler for ' + verb.toUpperCase() + ' ' + path.toString()); } // extend options with any route specific options if (handler.options && _.isObject(handler.options)) { _.extend(options.defaultOptions, handler.options); } // allow route to override policy chain if (handler.policies && _.isArray(handler.policies)) { options.defaultPolicies = handler.policies; } // allow route to augment policy chain if (handler.additionalPolicies && _.isArray(handler.additionalPolicies)) { options.defaultPolicies = options.defaultPolicies.concat(handler.additionalPolicies); } if (_.isFunction(handler.handler)) { return fn(null, handler.handler); } if (_.isString(handler.handler)) { return self.processStringHandler(mycro, handler.handler, fn); } } return fn('Unsupported handler type for '+ verb.toUpperCase() + ' ' + path.toString()); }
javascript
function processHandler(fn) { if (_.isFunction(handler)) { return fn(null, handler); } if (_.isString(handler)) { return self.processStringHandler(mycro, handler, fn); } if (_.isObject(handler)) { // make sure the object defines a `handler` attribute if (!handler.handler) { return fn('Unable to locate handler for ' + verb.toUpperCase() + ' ' + path.toString()); } // extend options with any route specific options if (handler.options && _.isObject(handler.options)) { _.extend(options.defaultOptions, handler.options); } // allow route to override policy chain if (handler.policies && _.isArray(handler.policies)) { options.defaultPolicies = handler.policies; } // allow route to augment policy chain if (handler.additionalPolicies && _.isArray(handler.additionalPolicies)) { options.defaultPolicies = options.defaultPolicies.concat(handler.additionalPolicies); } if (_.isFunction(handler.handler)) { return fn(null, handler.handler); } if (_.isString(handler.handler)) { return self.processStringHandler(mycro, handler.handler, fn); } } return fn('Unsupported handler type for '+ verb.toUpperCase() + ' ' + path.toString()); }
[ "function", "processHandler", "(", "fn", ")", "{", "if", "(", "_", ".", "isFunction", "(", "handler", ")", ")", "{", "return", "fn", "(", "null", ",", "handler", ")", ";", "}", "if", "(", "_", ".", "isString", "(", "handler", ")", ")", "{", "return", "self", ".", "processStringHandler", "(", "mycro", ",", "handler", ",", "fn", ")", ";", "}", "if", "(", "_", ".", "isObject", "(", "handler", ")", ")", "{", "if", "(", "!", "handler", ".", "handler", ")", "{", "return", "fn", "(", "'Unable to locate handler for '", "+", "verb", ".", "toUpperCase", "(", ")", "+", "' '", "+", "path", ".", "toString", "(", ")", ")", ";", "}", "if", "(", "handler", ".", "options", "&&", "_", ".", "isObject", "(", "handler", ".", "options", ")", ")", "{", "_", ".", "extend", "(", "options", ".", "defaultOptions", ",", "handler", ".", "options", ")", ";", "}", "if", "(", "handler", ".", "policies", "&&", "_", ".", "isArray", "(", "handler", ".", "policies", ")", ")", "{", "options", ".", "defaultPolicies", "=", "handler", ".", "policies", ";", "}", "if", "(", "handler", ".", "additionalPolicies", "&&", "_", ".", "isArray", "(", "handler", ".", "additionalPolicies", ")", ")", "{", "options", ".", "defaultPolicies", "=", "options", ".", "defaultPolicies", ".", "concat", "(", "handler", ".", "additionalPolicies", ")", ";", "}", "if", "(", "_", ".", "isFunction", "(", "handler", ".", "handler", ")", ")", "{", "return", "fn", "(", "null", ",", "handler", ".", "handler", ")", ";", "}", "if", "(", "_", ".", "isString", "(", "handler", ".", "handler", ")", ")", "{", "return", "self", ".", "processStringHandler", "(", "mycro", ",", "handler", ".", "handler", ",", "fn", ")", ";", "}", "}", "return", "fn", "(", "'Unsupported handler type for '", "+", "verb", ".", "toUpperCase", "(", ")", "+", "' '", "+", "path", ".", "toString", "(", ")", ")", ";", "}" ]
process handler definition
[ "process", "handler", "definition" ]
762e6ba0f38f37497eefb933252edc2c16bfb40b
https://github.com/cludden/mycro/blob/762e6ba0f38f37497eefb933252edc2c16bfb40b/hooks/routes/index.js#L145-L177
train
besync/graphstore
packages/graphstore-dev/src/firebase/jparser.js
cleanItem
function cleanItem(value) { var newvalue = null; if (Array.isArray(value)) { if (value.indexOf("consumer") > -1) { value.forEach(function (key2) { ids[key2] = "roles"; }); } newvalue = []; value.forEach(function (item) { newvalue.push(cleanItem(item)); }) return newvalue; } if ((typeof value !== "object") || (value == null)) { return value; } Object.keys(value).forEach(function (key) { if (key == "orgs") { Object.keys(value[key]).forEach(function (key2) { ids[key2] = "orgs"; }); } if (key == "_temp") { return; } else if (key == "encData" || key == "signature" || key == "encPrivateKey" || key == "publicKey") { newvalue = newvalue || {}; if (typeof newvalue !== "object") throw new Error("Not Object" + key) newvalue[key] = "..." } else { newvalue = newvalue || {}; if (typeof newvalue !== "object") throw new Error("Not Object" + key) newvalue[key] = cleanItem(value[key]) } }); return newvalue; }
javascript
function cleanItem(value) { var newvalue = null; if (Array.isArray(value)) { if (value.indexOf("consumer") > -1) { value.forEach(function (key2) { ids[key2] = "roles"; }); } newvalue = []; value.forEach(function (item) { newvalue.push(cleanItem(item)); }) return newvalue; } if ((typeof value !== "object") || (value == null)) { return value; } Object.keys(value).forEach(function (key) { if (key == "orgs") { Object.keys(value[key]).forEach(function (key2) { ids[key2] = "orgs"; }); } if (key == "_temp") { return; } else if (key == "encData" || key == "signature" || key == "encPrivateKey" || key == "publicKey") { newvalue = newvalue || {}; if (typeof newvalue !== "object") throw new Error("Not Object" + key) newvalue[key] = "..." } else { newvalue = newvalue || {}; if (typeof newvalue !== "object") throw new Error("Not Object" + key) newvalue[key] = cleanItem(value[key]) } }); return newvalue; }
[ "function", "cleanItem", "(", "value", ")", "{", "var", "newvalue", "=", "null", ";", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "if", "(", "value", ".", "indexOf", "(", "\"consumer\"", ")", ">", "-", "1", ")", "{", "value", ".", "forEach", "(", "function", "(", "key2", ")", "{", "ids", "[", "key2", "]", "=", "\"roles\"", ";", "}", ")", ";", "}", "newvalue", "=", "[", "]", ";", "value", ".", "forEach", "(", "function", "(", "item", ")", "{", "newvalue", ".", "push", "(", "cleanItem", "(", "item", ")", ")", ";", "}", ")", "return", "newvalue", ";", "}", "if", "(", "(", "typeof", "value", "!==", "\"object\"", ")", "||", "(", "value", "==", "null", ")", ")", "{", "return", "value", ";", "}", "Object", ".", "keys", "(", "value", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "key", "==", "\"orgs\"", ")", "{", "Object", ".", "keys", "(", "value", "[", "key", "]", ")", ".", "forEach", "(", "function", "(", "key2", ")", "{", "ids", "[", "key2", "]", "=", "\"orgs\"", ";", "}", ")", ";", "}", "if", "(", "key", "==", "\"_temp\"", ")", "{", "return", ";", "}", "else", "if", "(", "key", "==", "\"encData\"", "||", "key", "==", "\"signature\"", "||", "key", "==", "\"encPrivateKey\"", "||", "key", "==", "\"publicKey\"", ")", "{", "newvalue", "=", "newvalue", "||", "{", "}", ";", "if", "(", "typeof", "newvalue", "!==", "\"object\"", ")", "throw", "new", "Error", "(", "\"Not Object\"", "+", "key", ")", "newvalue", "[", "key", "]", "=", "\"...\"", "}", "else", "{", "newvalue", "=", "newvalue", "||", "{", "}", ";", "if", "(", "typeof", "newvalue", "!==", "\"object\"", ")", "throw", "new", "Error", "(", "\"Not Object\"", "+", "key", ")", "newvalue", "[", "key", "]", "=", "cleanItem", "(", "value", "[", "key", "]", ")", "}", "}", ")", ";", "return", "newvalue", ";", "}" ]
REMOVE _temp and clean encrypted data
[ "REMOVE", "_temp", "and", "clean", "encrypted", "data" ]
e615349a58c02e387768ee15044fbda237c6818b
https://github.com/besync/graphstore/blob/e615349a58c02e387768ee15044fbda237c6818b/packages/graphstore-dev/src/firebase/jparser.js#L38-L85
train
besync/graphstore
packages/graphstore-dev/src/firebase/jparser.js
cleanItem3
function cleanItem3(value, parent) { var newvalue = null; if (Array.isArray(value)) { newvalue = []; var isAllNumbers = (value.length > 0); var isAllStrings = (value.length > 0) value.forEach(function (item) { if (typeof item !== 'number') isAllNumbers = false; if (typeof item !== 'string') isAllStrings = false; }) if (isAllNumbers) return [cleanItem3(value[0], parent)]; if (isAllStrings) { var enumKey = "Enum" + getTypeFromKey(parent); var hash = value.join("!"); if (hash in enumFromHash) enumKey = enumFromHash[hash] else { var found = true; value.forEach(function (key) { if (!(key in enumFromKey)) found = false; }) if (found) { enumKey = enumFromKey[value[0]]; } else { enums[enumKey] = value; enumFromHash[hash] = enumKey; value.forEach(function (key) { enumFromKey[key] = "Enum" + getTypeFromKey(parent); }) } } return [enumKey]; } value.forEach(function (item) { newvalue.push(cleanItem3(item, parent)); }) return newvalue; } if ((typeof value !== "object") || (value == null)) { switch (typeof value) { case 'string': if (isId(value)) return 'ID'; if (isUser(value)) return 'UserId'; if (isUserOrgPrefix(value)) return 'UserOrOrgIdPrefixed'; if (ids[value] == "orgs") return 'OrgId'; if (ids[value] == "roles") return 'EnumConfigRole'; if (value in enumDefaultKeys.values) return enumDefaultKeys.values[value]; if (ids[value]) return ids[value] + "Id"; return 'String'; case 'number': if (value > 1300000000 && value < 1700000000) return value % 1 == 0 ? 'Date' : 'Time' return value % 1 == 0 ? 'Int' : 'Float' case 'boolean': return 'Boolean'; default: return value == null ? 'NULL' : value; } } var newvalue = {}; Object.keys(value).forEach(function (key) { newvalue[key] = cleanItem3(value[key], parent + key.substr(0, 1).toUpperCase() + key.substr(1)); }); return newvalue; }
javascript
function cleanItem3(value, parent) { var newvalue = null; if (Array.isArray(value)) { newvalue = []; var isAllNumbers = (value.length > 0); var isAllStrings = (value.length > 0) value.forEach(function (item) { if (typeof item !== 'number') isAllNumbers = false; if (typeof item !== 'string') isAllStrings = false; }) if (isAllNumbers) return [cleanItem3(value[0], parent)]; if (isAllStrings) { var enumKey = "Enum" + getTypeFromKey(parent); var hash = value.join("!"); if (hash in enumFromHash) enumKey = enumFromHash[hash] else { var found = true; value.forEach(function (key) { if (!(key in enumFromKey)) found = false; }) if (found) { enumKey = enumFromKey[value[0]]; } else { enums[enumKey] = value; enumFromHash[hash] = enumKey; value.forEach(function (key) { enumFromKey[key] = "Enum" + getTypeFromKey(parent); }) } } return [enumKey]; } value.forEach(function (item) { newvalue.push(cleanItem3(item, parent)); }) return newvalue; } if ((typeof value !== "object") || (value == null)) { switch (typeof value) { case 'string': if (isId(value)) return 'ID'; if (isUser(value)) return 'UserId'; if (isUserOrgPrefix(value)) return 'UserOrOrgIdPrefixed'; if (ids[value] == "orgs") return 'OrgId'; if (ids[value] == "roles") return 'EnumConfigRole'; if (value in enumDefaultKeys.values) return enumDefaultKeys.values[value]; if (ids[value]) return ids[value] + "Id"; return 'String'; case 'number': if (value > 1300000000 && value < 1700000000) return value % 1 == 0 ? 'Date' : 'Time' return value % 1 == 0 ? 'Int' : 'Float' case 'boolean': return 'Boolean'; default: return value == null ? 'NULL' : value; } } var newvalue = {}; Object.keys(value).forEach(function (key) { newvalue[key] = cleanItem3(value[key], parent + key.substr(0, 1).toUpperCase() + key.substr(1)); }); return newvalue; }
[ "function", "cleanItem3", "(", "value", ",", "parent", ")", "{", "var", "newvalue", "=", "null", ";", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "newvalue", "=", "[", "]", ";", "var", "isAllNumbers", "=", "(", "value", ".", "length", ">", "0", ")", ";", "var", "isAllStrings", "=", "(", "value", ".", "length", ">", "0", ")", "value", ".", "forEach", "(", "function", "(", "item", ")", "{", "if", "(", "typeof", "item", "!==", "'number'", ")", "isAllNumbers", "=", "false", ";", "if", "(", "typeof", "item", "!==", "'string'", ")", "isAllStrings", "=", "false", ";", "}", ")", "if", "(", "isAllNumbers", ")", "return", "[", "cleanItem3", "(", "value", "[", "0", "]", ",", "parent", ")", "]", ";", "if", "(", "isAllStrings", ")", "{", "var", "enumKey", "=", "\"Enum\"", "+", "getTypeFromKey", "(", "parent", ")", ";", "var", "hash", "=", "value", ".", "join", "(", "\"!\"", ")", ";", "if", "(", "hash", "in", "enumFromHash", ")", "enumKey", "=", "enumFromHash", "[", "hash", "]", "else", "{", "var", "found", "=", "true", ";", "value", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "!", "(", "key", "in", "enumFromKey", ")", ")", "found", "=", "false", ";", "}", ")", "if", "(", "found", ")", "{", "enumKey", "=", "enumFromKey", "[", "value", "[", "0", "]", "]", ";", "}", "else", "{", "enums", "[", "enumKey", "]", "=", "value", ";", "enumFromHash", "[", "hash", "]", "=", "enumKey", ";", "value", ".", "forEach", "(", "function", "(", "key", ")", "{", "enumFromKey", "[", "key", "]", "=", "\"Enum\"", "+", "getTypeFromKey", "(", "parent", ")", ";", "}", ")", "}", "}", "return", "[", "enumKey", "]", ";", "}", "value", ".", "forEach", "(", "function", "(", "item", ")", "{", "newvalue", ".", "push", "(", "cleanItem3", "(", "item", ",", "parent", ")", ")", ";", "}", ")", "return", "newvalue", ";", "}", "if", "(", "(", "typeof", "value", "!==", "\"object\"", ")", "||", "(", "value", "==", "null", ")", ")", "{", "switch", "(", "typeof", "value", ")", "{", "case", "'string'", ":", "if", "(", "isId", "(", "value", ")", ")", "return", "'ID'", ";", "if", "(", "isUser", "(", "value", ")", ")", "return", "'UserId'", ";", "if", "(", "isUserOrgPrefix", "(", "value", ")", ")", "return", "'UserOrOrgIdPrefixed'", ";", "if", "(", "ids", "[", "value", "]", "==", "\"orgs\"", ")", "return", "'OrgId'", ";", "if", "(", "ids", "[", "value", "]", "==", "\"roles\"", ")", "return", "'EnumConfigRole'", ";", "if", "(", "value", "in", "enumDefaultKeys", ".", "values", ")", "return", "enumDefaultKeys", ".", "values", "[", "value", "]", ";", "if", "(", "ids", "[", "value", "]", ")", "return", "ids", "[", "value", "]", "+", "\"Id\"", ";", "return", "'String'", ";", "case", "'number'", ":", "if", "(", "value", ">", "1300000000", "&&", "value", "<", "1700000000", ")", "return", "value", "%", "1", "==", "0", "?", "'Date'", ":", "'Time'", "return", "value", "%", "1", "==", "0", "?", "'Int'", ":", "'Float'", "case", "'boolean'", ":", "return", "'Boolean'", ";", "default", ":", "return", "value", "==", "null", "?", "'NULL'", ":", "value", ";", "}", "}", "var", "newvalue", "=", "{", "}", ";", "Object", ".", "keys", "(", "value", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "newvalue", "[", "key", "]", "=", "cleanItem3", "(", "value", "[", "key", "]", ",", "parent", "+", "key", ".", "substr", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "key", ".", "substr", "(", "1", ")", ")", ";", "}", ")", ";", "return", "newvalue", ";", "}" ]
REMOVE DUPLICATE ENTITIES INSTANCE STRUCTURES
[ "REMOVE", "DUPLICATE", "ENTITIES", "INSTANCE", "STRUCTURES" ]
e615349a58c02e387768ee15044fbda237c6818b
https://github.com/besync/graphstore/blob/e615349a58c02e387768ee15044fbda237c6818b/packages/graphstore-dev/src/firebase/jparser.js#L167-L248
train
LLK/po2icu
lib/po2icu.js
function (icuString, options) { icuString = this.cleanWhiteSpace(icuString); //args before kwargs if (typeof options !== 'undefined') { if (typeof options.string !== 'undefined') { var stringRe = new RegExp(('\{' + options.string + '\}'), 'g'); icuString = icuString.replace(stringRe, '%s'); } if (typeof options.number !== 'undefined') { var numberRe = new RegExp(('\{' + options.number + ', number\}'), 'g'); icuString = icuString.replace(numberRe, '%d'); } } icuString = icuString.replace(/\{[a-zA-Z0-9_.|]+\}/g, function (variable_name) { var name = variable_name.substring(1, (variable_name.length - 1)); return '%(' + name + ')s'; }); icuString = icuString.replace(/\{[a-zA-Z0-9_.|]+, number\}/g, function (variable_name) { var name = variable_name.substring(1, (variable_name.length - 9)); return '%(' + name + ')d'; }); return icuString; }
javascript
function (icuString, options) { icuString = this.cleanWhiteSpace(icuString); //args before kwargs if (typeof options !== 'undefined') { if (typeof options.string !== 'undefined') { var stringRe = new RegExp(('\{' + options.string + '\}'), 'g'); icuString = icuString.replace(stringRe, '%s'); } if (typeof options.number !== 'undefined') { var numberRe = new RegExp(('\{' + options.number + ', number\}'), 'g'); icuString = icuString.replace(numberRe, '%d'); } } icuString = icuString.replace(/\{[a-zA-Z0-9_.|]+\}/g, function (variable_name) { var name = variable_name.substring(1, (variable_name.length - 1)); return '%(' + name + ')s'; }); icuString = icuString.replace(/\{[a-zA-Z0-9_.|]+, number\}/g, function (variable_name) { var name = variable_name.substring(1, (variable_name.length - 9)); return '%(' + name + ')d'; }); return icuString; }
[ "function", "(", "icuString", ",", "options", ")", "{", "icuString", "=", "this", ".", "cleanWhiteSpace", "(", "icuString", ")", ";", "if", "(", "typeof", "options", "!==", "'undefined'", ")", "{", "if", "(", "typeof", "options", ".", "string", "!==", "'undefined'", ")", "{", "var", "stringRe", "=", "new", "RegExp", "(", "(", "'\\{'", "+", "\\{", "+", "options", ".", "string", ")", ",", "'\\}'", ")", ";", "\\}", "}", "'g'", "}", "icuString", "=", "icuString", ".", "replace", "(", "stringRe", ",", "'%s'", ")", ";", "if", "(", "typeof", "options", ".", "number", "!==", "'undefined'", ")", "{", "var", "numberRe", "=", "new", "RegExp", "(", "(", "'\\{'", "+", "\\{", "+", "options", ".", "number", ")", ",", "', number\\}'", ")", ";", "\\}", "}", "'g'", "}" ]
Converts an icu-formatted string into a po-formatted one for pytho @param {string} icuString icu-formatted string @param {object} options gives icu keywords that should be turned into python args in po rather than python kwargs. Possible keys to use: `string`, `number`. @return {string} po-formatted string
[ "Converts", "an", "icu", "-", "formatted", "string", "into", "a", "po", "-", "formatted", "one", "for", "pytho" ]
9eb97f81f72b2fee02b77f1424702e019647e9b9
https://github.com/LLK/po2icu/blob/9eb97f81f72b2fee02b77f1424702e019647e9b9/lib/po2icu.js#L48-L72
train
LLK/po2icu
lib/po2icu.js
function (msgs, pluralForms) { var msgKey = 'digit'; var hasVariableName = false; for (var i=0; i<msgs.length; i++) { if (msgs[i].match(/%\([a-zA-Z0-9_.|]+\)d/g) !== null) { var match = msgs[i].match(/%\([a-zA-Z0-9_.|]+\)d/g)[0]; msgKey = match.substring(2, (match.length - 2)); hasVariableName = true; break; } } var icuMsg = '{' + msgKey + ', plural,\n'; var self = this; pluralForms.forEach(function (plural) { var msg = msgs[plural.poPlural]; msg = self.cleanWhiteSpace(msg); if (hasVariableName) { msg = msg.replace(/%\([a-zA-Z0-9_.|]+\)d/g, '{' + msgKey + '}'); } else { msg = msg.replace(/%(d|i)/g, '{' + msgKey + '}'); } icuMsg = icuMsg + ' ' + plural.icuPlural + ' {' + msg + '}\n'; }); icuMsg = icuMsg + '}'; return icuMsg; }
javascript
function (msgs, pluralForms) { var msgKey = 'digit'; var hasVariableName = false; for (var i=0; i<msgs.length; i++) { if (msgs[i].match(/%\([a-zA-Z0-9_.|]+\)d/g) !== null) { var match = msgs[i].match(/%\([a-zA-Z0-9_.|]+\)d/g)[0]; msgKey = match.substring(2, (match.length - 2)); hasVariableName = true; break; } } var icuMsg = '{' + msgKey + ', plural,\n'; var self = this; pluralForms.forEach(function (plural) { var msg = msgs[plural.poPlural]; msg = self.cleanWhiteSpace(msg); if (hasVariableName) { msg = msg.replace(/%\([a-zA-Z0-9_.|]+\)d/g, '{' + msgKey + '}'); } else { msg = msg.replace(/%(d|i)/g, '{' + msgKey + '}'); } icuMsg = icuMsg + ' ' + plural.icuPlural + ' {' + msg + '}\n'; }); icuMsg = icuMsg + '}'; return icuMsg; }
[ "function", "(", "msgs", ",", "pluralForms", ")", "{", "var", "msgKey", "=", "'digit'", ";", "var", "hasVariableName", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "msgs", ".", "length", ";", "i", "++", ")", "{", "if", "(", "msgs", "[", "i", "]", ".", "match", "(", "/", "%\\([a-zA-Z0-9_.|]+\\)d", "/", "g", ")", "!==", "null", ")", "{", "var", "match", "=", "msgs", "[", "i", "]", ".", "match", "(", "/", "%\\([a-zA-Z0-9_.|]+\\)d", "/", "g", ")", "[", "0", "]", ";", "msgKey", "=", "match", ".", "substring", "(", "2", ",", "(", "match", ".", "length", "-", "2", ")", ")", ";", "hasVariableName", "=", "true", ";", "break", ";", "}", "}", "var", "icuMsg", "=", "'{'", "+", "msgKey", "+", "', plural,\\n'", ";", "\\n", "var", "self", "=", "this", ";", "pluralForms", ".", "forEach", "(", "function", "(", "plural", ")", "{", "var", "msg", "=", "msgs", "[", "plural", ".", "poPlural", "]", ";", "msg", "=", "self", ".", "cleanWhiteSpace", "(", "msg", ")", ";", "if", "(", "hasVariableName", ")", "{", "msg", "=", "msg", ".", "replace", "(", "/", "%\\([a-zA-Z0-9_.|]+\\)d", "/", "g", ",", "'{'", "+", "msgKey", "+", "'}'", ")", ";", "}", "else", "{", "msg", "=", "msg", ".", "replace", "(", "/", "%(d|i)", "/", "g", ",", "'{'", "+", "msgKey", "+", "'}'", ")", ";", "}", "icuMsg", "=", "icuMsg", "+", "' '", "+", "plural", ".", "icuPlural", "+", "' {'", "+", "msg", "+", "'}\\n'", ";", "}", ")", ";", "\\n", "}" ]
Converts a python po-formatted plural msg into an icu-formatted plural. @param {list} [msgs] list of strings for each plural form @param {list} [pluralForms] list of icu plural forms used by this language choices are: ['zero', 'one', 'two', 'few', 'many', 'other']
[ "Converts", "a", "python", "po", "-", "formatted", "plural", "msg", "into", "an", "icu", "-", "formatted", "plural", "." ]
9eb97f81f72b2fee02b77f1424702e019647e9b9
https://github.com/LLK/po2icu/blob/9eb97f81f72b2fee02b77f1424702e019647e9b9/lib/po2icu.js#L81-L107
train
jsantell/mock-s3
lib/utils.js
removeFromList
function removeFromList (array, obj) { for (var i = 0; i < array.length; i++) { if (array[i] === obj) { array.splice(i, 1); } return; } }
javascript
function removeFromList (array, obj) { for (var i = 0; i < array.length; i++) { if (array[i] === obj) { array.splice(i, 1); } return; } }
[ "function", "removeFromList", "(", "array", ",", "obj", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "if", "(", "array", "[", "i", "]", "===", "obj", ")", "{", "array", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "return", ";", "}", "}" ]
Remove `obj` from `array`. @param {Array} array @param {Mixed} object
[ "Remove", "obj", "from", "array", "." ]
d02e3b0558cc60c7887232b69df41e2b0fe09147
https://github.com/jsantell/mock-s3/blob/d02e3b0558cc60c7887232b69df41e2b0fe09147/lib/utils.js#L22-L29
train
jsantell/mock-s3
lib/utils.js
findWhere
function findWhere (array, obj) { var props = Object.keys(obj); for (var i = 0; i < array.length; i++) { var passable = true; for (var j = 0; j < props.length; j++) { if (array[i][props[j]] !== obj[props[j]]) { passable = false; } } if (passable) return array[i]; } return null; }
javascript
function findWhere (array, obj) { var props = Object.keys(obj); for (var i = 0; i < array.length; i++) { var passable = true; for (var j = 0; j < props.length; j++) { if (array[i][props[j]] !== obj[props[j]]) { passable = false; } } if (passable) return array[i]; } return null; }
[ "function", "findWhere", "(", "array", ",", "obj", ")", "{", "var", "props", "=", "Object", ".", "keys", "(", "obj", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "var", "passable", "=", "true", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "props", ".", "length", ";", "j", "++", ")", "{", "if", "(", "array", "[", "i", "]", "[", "props", "[", "j", "]", "]", "!==", "obj", "[", "props", "[", "j", "]", "]", ")", "{", "passable", "=", "false", ";", "}", "}", "if", "(", "passable", ")", "return", "array", "[", "i", "]", ";", "}", "return", "null", ";", "}" ]
Finds an object in `array` that matches all key-value pairs defined in `obj`. Returns first object that matches. Similar to underscore's `_.findWhere`. @param {Array} array @param {Object} obj @return {Mixed}
[ "Finds", "an", "object", "in", "array", "that", "matches", "all", "key", "-", "value", "pairs", "defined", "in", "obj", ".", "Returns", "first", "object", "that", "matches", ".", "Similar", "to", "underscore", "s", "_", ".", "findWhere", "." ]
d02e3b0558cc60c7887232b69df41e2b0fe09147
https://github.com/jsantell/mock-s3/blob/d02e3b0558cc60c7887232b69df41e2b0fe09147/lib/utils.js#L42-L55
train
jsantell/mock-s3
lib/utils.js
update
function update (obj1, obj2) { Object.keys(obj2).forEach(function (prop) { obj1[prop] = obj2[prop]; }); return obj1; }
javascript
function update (obj1, obj2) { Object.keys(obj2).forEach(function (prop) { obj1[prop] = obj2[prop]; }); return obj1; }
[ "function", "update", "(", "obj1", ",", "obj2", ")", "{", "Object", ".", "keys", "(", "obj2", ")", ".", "forEach", "(", "function", "(", "prop", ")", "{", "obj1", "[", "prop", "]", "=", "obj2", "[", "prop", "]", ";", "}", ")", ";", "return", "obj1", ";", "}" ]
Merges properties of obj2 into obj1. @param {Object} obj1 @param {Object} obj2 @return {Object}
[ "Merges", "properties", "of", "obj2", "into", "obj1", "." ]
d02e3b0558cc60c7887232b69df41e2b0fe09147
https://github.com/jsantell/mock-s3/blob/d02e3b0558cc60c7887232b69df41e2b0fe09147/lib/utils.js#L78-L83
train
jsantell/mock-s3
lib/utils.js
randomAlpha
function randomAlpha (n) { var alpha = "abcdefghijklmnopqrstuvwxyz"; var res = ""; for (var i = 0; i < n; i++) { res += alpha.charAt(Math.floor(Math.random() * alpha.length)); } return res; }
javascript
function randomAlpha (n) { var alpha = "abcdefghijklmnopqrstuvwxyz"; var res = ""; for (var i = 0; i < n; i++) { res += alpha.charAt(Math.floor(Math.random() * alpha.length)); } return res; }
[ "function", "randomAlpha", "(", "n", ")", "{", "var", "alpha", "=", "\"abcdefghijklmnopqrstuvwxyz\"", ";", "var", "res", "=", "\"\"", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "res", "+=", "alpha", ".", "charAt", "(", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "alpha", ".", "length", ")", ")", ";", "}", "return", "res", ";", "}" ]
Generates a string of `n` random lowercase characters. @param {Number} n @return {String}
[ "Generates", "a", "string", "of", "n", "random", "lowercase", "characters", "." ]
d02e3b0558cc60c7887232b69df41e2b0fe09147
https://github.com/jsantell/mock-s3/blob/d02e3b0558cc60c7887232b69df41e2b0fe09147/lib/utils.js#L144-L151
train
impromptu/impromptu
lib/impromptu.js
Impromptu
function Impromptu() { this.state = new Impromptu.State() this._setRootPath(Impromptu.DEFAULT_CONFIG_DIR) this.log = new Impromptu.Log(this.state) this.exec = Impromptu.Exec(this.log) this.color = new Impromptu.Color(this.state) this.repository = new Impromptu.RepositoryFactory() this.db = new Impromptu.DB() this.cache = new Impromptu.CacheFactory(this.state) this._addCacheProviders() this.module = new Impromptu.ModuleFactory(this) this.plugin = new Impromptu.PluginFactory(this.cache) this._loadPlugins = this.plugin.claimPluginLoader() this.prompt = new Impromptu.Prompt(this.color) }
javascript
function Impromptu() { this.state = new Impromptu.State() this._setRootPath(Impromptu.DEFAULT_CONFIG_DIR) this.log = new Impromptu.Log(this.state) this.exec = Impromptu.Exec(this.log) this.color = new Impromptu.Color(this.state) this.repository = new Impromptu.RepositoryFactory() this.db = new Impromptu.DB() this.cache = new Impromptu.CacheFactory(this.state) this._addCacheProviders() this.module = new Impromptu.ModuleFactory(this) this.plugin = new Impromptu.PluginFactory(this.cache) this._loadPlugins = this.plugin.claimPluginLoader() this.prompt = new Impromptu.Prompt(this.color) }
[ "function", "Impromptu", "(", ")", "{", "this", ".", "state", "=", "new", "Impromptu", ".", "State", "(", ")", "this", ".", "_setRootPath", "(", "Impromptu", ".", "DEFAULT_CONFIG_DIR", ")", "this", ".", "log", "=", "new", "Impromptu", ".", "Log", "(", "this", ".", "state", ")", "this", ".", "exec", "=", "Impromptu", ".", "Exec", "(", "this", ".", "log", ")", "this", ".", "color", "=", "new", "Impromptu", ".", "Color", "(", "this", ".", "state", ")", "this", ".", "repository", "=", "new", "Impromptu", ".", "RepositoryFactory", "(", ")", "this", ".", "db", "=", "new", "Impromptu", ".", "DB", "(", ")", "this", ".", "cache", "=", "new", "Impromptu", ".", "CacheFactory", "(", "this", ".", "state", ")", "this", ".", "_addCacheProviders", "(", ")", "this", ".", "module", "=", "new", "Impromptu", ".", "ModuleFactory", "(", "this", ")", "this", ".", "plugin", "=", "new", "Impromptu", ".", "PluginFactory", "(", "this", ".", "cache", ")", "this", ".", "_loadPlugins", "=", "this", ".", "plugin", ".", "claimPluginLoader", "(", ")", "this", ".", "prompt", "=", "new", "Impromptu", ".", "Prompt", "(", "this", ".", "color", ")", "}" ]
The base Impromptu class. @constructor
[ "The", "base", "Impromptu", "class", "." ]
829798eda62771d6a6ed971d87eef7a461932704
https://github.com/impromptu/impromptu/blob/829798eda62771d6a6ed971d87eef7a461932704/lib/impromptu.js#L14-L31
train
MathiasPaumgarten/grunt-json-bake
tasks/json_bake.js
checkFile
function checkFile( path ) { if ( typeof path === "undefined" || ! grunt.file.exists( path ) ) { grunt.log.error( "Source file \"" + path + "\" not found." ); return false; } return true; }
javascript
function checkFile( path ) { if ( typeof path === "undefined" || ! grunt.file.exists( path ) ) { grunt.log.error( "Source file \"" + path + "\" not found." ); return false; } return true; }
[ "function", "checkFile", "(", "path", ")", "{", "if", "(", "typeof", "path", "===", "\"undefined\"", "||", "!", "grunt", ".", "file", ".", "exists", "(", "path", ")", ")", "{", "grunt", ".", "log", ".", "error", "(", "\"Source file \\\"\"", "+", "\\\"", "+", "path", ")", ";", "\"\\\" not found.\"", "}", "\\\"", "}" ]
Returns true if source points to a file
[ "Returns", "true", "if", "source", "points", "to", "a", "file" ]
315b1b95e95b9e54101cd51309a711e31ffcbb46
https://github.com/MathiasPaumgarten/grunt-json-bake/blob/315b1b95e95b9e54101cd51309a711e31ffcbb46/tasks/json_bake.js#L82-L89
train
MathiasPaumgarten/grunt-json-bake
tasks/json_bake.js
isIncludeFile
function isIncludeFile( path ) { if ( fs.statSync( path ).isFile() && getIncludeFileExtensions().indexOf( getFileExtension( path ) ) !== - 1 ) return true; return false; }
javascript
function isIncludeFile( path ) { if ( fs.statSync( path ).isFile() && getIncludeFileExtensions().indexOf( getFileExtension( path ) ) !== - 1 ) return true; return false; }
[ "function", "isIncludeFile", "(", "path", ")", "{", "if", "(", "fs", ".", "statSync", "(", "path", ")", ".", "isFile", "(", ")", "&&", "getIncludeFileExtensions", "(", ")", ".", "indexOf", "(", "getFileExtension", "(", "path", ")", ")", "!==", "-", "1", ")", "return", "true", ";", "return", "false", ";", "}" ]
Returns true if the path given points at a JSON file or accepted include file
[ "Returns", "true", "if", "the", "path", "given", "points", "at", "a", "JSON", "file", "or", "accepted", "include", "file" ]
315b1b95e95b9e54101cd51309a711e31ffcbb46
https://github.com/MathiasPaumgarten/grunt-json-bake/blob/315b1b95e95b9e54101cd51309a711e31ffcbb46/tasks/json_bake.js#L103-L108
train
MathiasPaumgarten/grunt-json-bake
tasks/json_bake.js
parseJSON
function parseJSON( path, content ) { return JSON.parse( content, function( key, value ) { if ( options.stripComments && key === "{{comment}}" ) return undefined; // Replace variables in their values if ( Object.keys( options.variables ).length && typeof value === "string" ) { value = replaceVariables( value ); } var match = ( typeof value === "string" ) ? value.match( options.parsePattern ) : null; if ( match ) { var folderPath = getFolder( path ) || "."; var fullPath = folderPath + "/" + match[ 1 ]; return isDirectory( fullPath ) ? parseDirectory( fullPath ) : parseFile( fullPath ); } return value; } ); }
javascript
function parseJSON( path, content ) { return JSON.parse( content, function( key, value ) { if ( options.stripComments && key === "{{comment}}" ) return undefined; // Replace variables in their values if ( Object.keys( options.variables ).length && typeof value === "string" ) { value = replaceVariables( value ); } var match = ( typeof value === "string" ) ? value.match( options.parsePattern ) : null; if ( match ) { var folderPath = getFolder( path ) || "."; var fullPath = folderPath + "/" + match[ 1 ]; return isDirectory( fullPath ) ? parseDirectory( fullPath ) : parseFile( fullPath ); } return value; } ); }
[ "function", "parseJSON", "(", "path", ",", "content", ")", "{", "return", "JSON", ".", "parse", "(", "content", ",", "function", "(", "key", ",", "value", ")", "{", "if", "(", "options", ".", "stripComments", "&&", "key", "===", "\"{{comment}}\"", ")", "return", "undefined", ";", "if", "(", "Object", ".", "keys", "(", "options", ".", "variables", ")", ".", "length", "&&", "typeof", "value", "===", "\"string\"", ")", "{", "value", "=", "replaceVariables", "(", "value", ")", ";", "}", "var", "match", "=", "(", "typeof", "value", "===", "\"string\"", ")", "?", "value", ".", "match", "(", "options", ".", "parsePattern", ")", ":", "null", ";", "if", "(", "match", ")", "{", "var", "folderPath", "=", "getFolder", "(", "path", ")", "||", "\".\"", ";", "var", "fullPath", "=", "folderPath", "+", "\"/\"", "+", "match", "[", "1", "]", ";", "return", "isDirectory", "(", "fullPath", ")", "?", "parseDirectory", "(", "fullPath", ")", ":", "parseFile", "(", "fullPath", ")", ";", "}", "return", "value", ";", "}", ")", ";", "}" ]
Parses a JSON file and returns value as object
[ "Parses", "a", "JSON", "file", "and", "returns", "value", "as", "object" ]
315b1b95e95b9e54101cd51309a711e31ffcbb46
https://github.com/MathiasPaumgarten/grunt-json-bake/blob/315b1b95e95b9e54101cd51309a711e31ffcbb46/tasks/json_bake.js#L160-L184
train
MathiasPaumgarten/grunt-json-bake
tasks/json_bake.js
replaceVariables
function replaceVariables( value ) { return value.replace( options.variableRegex, function( match, key ) { if ( options.variables[ key ] === undefined ) { grunt.log.warn( "No variable definition found for: " + key ); return ""; } return options.variables[ key ]; } ); }
javascript
function replaceVariables( value ) { return value.replace( options.variableRegex, function( match, key ) { if ( options.variables[ key ] === undefined ) { grunt.log.warn( "No variable definition found for: " + key ); return ""; } return options.variables[ key ]; } ); }
[ "function", "replaceVariables", "(", "value", ")", "{", "return", "value", ".", "replace", "(", "options", ".", "variableRegex", ",", "function", "(", "match", ",", "key", ")", "{", "if", "(", "options", ".", "variables", "[", "key", "]", "===", "undefined", ")", "{", "grunt", ".", "log", ".", "warn", "(", "\"No variable definition found for: \"", "+", "key", ")", ";", "return", "\"\"", ";", "}", "return", "options", ".", "variables", "[", "key", "]", ";", "}", ")", ";", "}" ]
Replaces defined variables in the given value
[ "Replaces", "defined", "variables", "in", "the", "given", "value" ]
315b1b95e95b9e54101cd51309a711e31ffcbb46
https://github.com/MathiasPaumgarten/grunt-json-bake/blob/315b1b95e95b9e54101cd51309a711e31ffcbb46/tasks/json_bake.js#L189-L201
train
MathiasPaumgarten/grunt-json-bake
tasks/json_bake.js
parseDirectory
function parseDirectory( path ) { return fs.readdirSync( path ) .map( function( file ) { var filePath = path + "/" + file; if ( isIncludeFile( filePath ) ) return parseFile( filePath ); else if ( isDirectory( filePath ) ) return parseDirectory( filePath ); return null; } ) .filter( function( value ) { return value !== null; } ); }
javascript
function parseDirectory( path ) { return fs.readdirSync( path ) .map( function( file ) { var filePath = path + "/" + file; if ( isIncludeFile( filePath ) ) return parseFile( filePath ); else if ( isDirectory( filePath ) ) return parseDirectory( filePath ); return null; } ) .filter( function( value ) { return value !== null; } ); }
[ "function", "parseDirectory", "(", "path", ")", "{", "return", "fs", ".", "readdirSync", "(", "path", ")", ".", "map", "(", "function", "(", "file", ")", "{", "var", "filePath", "=", "path", "+", "\"/\"", "+", "file", ";", "if", "(", "isIncludeFile", "(", "filePath", ")", ")", "return", "parseFile", "(", "filePath", ")", ";", "else", "if", "(", "isDirectory", "(", "filePath", ")", ")", "return", "parseDirectory", "(", "filePath", ")", ";", "return", "null", ";", "}", ")", ".", "filter", "(", "function", "(", "value", ")", "{", "return", "value", "!==", "null", ";", "}", ")", ";", "}" ]
Parses a directory and returns content as array
[ "Parses", "a", "directory", "and", "returns", "content", "as", "array" ]
315b1b95e95b9e54101cd51309a711e31ffcbb46
https://github.com/MathiasPaumgarten/grunt-json-bake/blob/315b1b95e95b9e54101cd51309a711e31ffcbb46/tasks/json_bake.js#L213-L232
train
nwtjs/nwt
plugins/scroller.js
function(e) { var thumbOffset = this.thumb.region().height/2; this.setPositionIfValid(e._e.pageY - (this.node.region().top + this.scrollbarOffset) - thumbOffset); }
javascript
function(e) { var thumbOffset = this.thumb.region().height/2; this.setPositionIfValid(e._e.pageY - (this.node.region().top + this.scrollbarOffset) - thumbOffset); }
[ "function", "(", "e", ")", "{", "var", "thumbOffset", "=", "this", ".", "thumb", ".", "region", "(", ")", ".", "height", "/", "2", ";", "this", ".", "setPositionIfValid", "(", "e", ".", "_e", ".", "pageY", "-", "(", "this", ".", "node", ".", "region", "(", ")", ".", "top", "+", "this", ".", "scrollbarOffset", ")", "-", "thumbOffset", ")", ";", "}" ]
Update the position of the thumb from an event
[ "Update", "the", "position", "of", "the", "thumb", "from", "an", "event" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/scroller.js#L107-L110
train
philidem/url-util-js
URL.js
_parseNetworkLocation
function _parseNetworkLocation(networkLocation, obj) { var pos = networkLocation.indexOf(':'); if (pos === -1) { obj.host = networkLocation; } else { obj.host = networkLocation.substring(0, pos); if (pos < (networkLocation.length - 1)) { obj.port = networkLocation.substring(pos + 1); } } }
javascript
function _parseNetworkLocation(networkLocation, obj) { var pos = networkLocation.indexOf(':'); if (pos === -1) { obj.host = networkLocation; } else { obj.host = networkLocation.substring(0, pos); if (pos < (networkLocation.length - 1)) { obj.port = networkLocation.substring(pos + 1); } } }
[ "function", "_parseNetworkLocation", "(", "networkLocation", ",", "obj", ")", "{", "var", "pos", "=", "networkLocation", ".", "indexOf", "(", "':'", ")", ";", "if", "(", "pos", "===", "-", "1", ")", "{", "obj", ".", "host", "=", "networkLocation", ";", "}", "else", "{", "obj", ".", "host", "=", "networkLocation", ".", "substring", "(", "0", ",", "pos", ")", ";", "if", "(", "pos", "<", "(", "networkLocation", ".", "length", "-", "1", ")", ")", "{", "obj", ".", "port", "=", "networkLocation", ".", "substring", "(", "pos", "+", "1", ")", ";", "}", "}", "}" ]
Parse the network location which will contain the host and possibly the port. @param networkLocation the network location portion of URL being parsed
[ "Parse", "the", "network", "location", "which", "will", "contain", "the", "host", "and", "possibly", "the", "port", "." ]
0c7575900028094ebaeb70d74f85dacf4b8680ef
https://github.com/philidem/url-util-js/blob/0c7575900028094ebaeb70d74f85dacf4b8680ef/URL.js#L33-L43
train
impromptu/impromptu
lib/cache/GlobalCache.js
function(exists, done) { if (exists) { done(new AbstractCache.Error('The cache is currently locked.')) } else { client.get("lock-process:" + name, done) } }
javascript
function(exists, done) { if (exists) { done(new AbstractCache.Error('The cache is currently locked.')) } else { client.get("lock-process:" + name, done) } }
[ "function", "(", "exists", ",", "done", ")", "{", "if", "(", "exists", ")", "{", "done", "(", "new", "AbstractCache", ".", "Error", "(", "'The cache is currently locked.'", ")", ")", "}", "else", "{", "client", ".", "get", "(", "\"lock-process:\"", "+", "name", ",", "done", ")", "}", "}" ]
Check if there's a process already running to update the cache.
[ "Check", "if", "there", "s", "a", "process", "already", "running", "to", "update", "the", "cache", "." ]
829798eda62771d6a6ed971d87eef7a461932704
https://github.com/impromptu/impromptu/blob/829798eda62771d6a6ed971d87eef7a461932704/lib/cache/GlobalCache.js#L86-L92
train
wprl/baucis-swagger
Controller.js
capitalize
function capitalize (s) { if (!s) return s; if (s.length === 1) return s.toUpperCase(); return s[0].toUpperCase() + s.substring(1); }
javascript
function capitalize (s) { if (!s) return s; if (s.length === 1) return s.toUpperCase(); return s[0].toUpperCase() + s.substring(1); }
[ "function", "capitalize", "(", "s", ")", "{", "if", "(", "!", "s", ")", "return", "s", ";", "if", "(", "s", ".", "length", "===", "1", ")", "return", "s", ".", "toUpperCase", "(", ")", ";", "return", "s", "[", "0", "]", ".", "toUpperCase", "(", ")", "+", "s", ".", "substring", "(", "1", ")", ";", "}" ]
A method for capitalizing the first letter of a string
[ "A", "method", "for", "capitalizing", "the", "first", "letter", "of", "a", "string" ]
405ffc754555034b57ca633b9c2c30454789169e
https://github.com/wprl/baucis-swagger/blob/405ffc754555034b57ca633b9c2c30454789169e/Controller.js#L27-L31
train
wprl/baucis-swagger
Controller.js
generateOperations
function generateOperations (plural) { var operations = []; controller.methods().forEach(function (verb) { var operation = {}; var titlePlural = capitalize(controller.model().plural()); var titleSingular = capitalize(controller.model().singular()); // Don't do head, post/put for single/plural if (verb === 'head') return; if (verb === 'post' && !plural) return; if (verb === 'put' && plural) return; // Use the full word if (verb === 'del') verb = 'delete'; operation.httpMethod = verb.toUpperCase(); if (plural) operation.nickname = verb + titlePlural; else operation.nickname = verb + titleSingular + 'ById'; operation.responseClass = titleSingular; // TODO sometimes an array! if (plural) operation.summary = capitalize(verb) + ' some ' + controller.model().plural(); else operation.summary = capitalize(verb) + ' a ' + controller.model().singular() + ' by its unique ID'; operation.parameters = generateParameters(verb, plural); operation.errorResponses = generateErrorResponses(plural); operations.push(operation); }); return operations; }
javascript
function generateOperations (plural) { var operations = []; controller.methods().forEach(function (verb) { var operation = {}; var titlePlural = capitalize(controller.model().plural()); var titleSingular = capitalize(controller.model().singular()); // Don't do head, post/put for single/plural if (verb === 'head') return; if (verb === 'post' && !plural) return; if (verb === 'put' && plural) return; // Use the full word if (verb === 'del') verb = 'delete'; operation.httpMethod = verb.toUpperCase(); if (plural) operation.nickname = verb + titlePlural; else operation.nickname = verb + titleSingular + 'ById'; operation.responseClass = titleSingular; // TODO sometimes an array! if (plural) operation.summary = capitalize(verb) + ' some ' + controller.model().plural(); else operation.summary = capitalize(verb) + ' a ' + controller.model().singular() + ' by its unique ID'; operation.parameters = generateParameters(verb, plural); operation.errorResponses = generateErrorResponses(plural); operations.push(operation); }); return operations; }
[ "function", "generateOperations", "(", "plural", ")", "{", "var", "operations", "=", "[", "]", ";", "controller", ".", "methods", "(", ")", ".", "forEach", "(", "function", "(", "verb", ")", "{", "var", "operation", "=", "{", "}", ";", "var", "titlePlural", "=", "capitalize", "(", "controller", ".", "model", "(", ")", ".", "plural", "(", ")", ")", ";", "var", "titleSingular", "=", "capitalize", "(", "controller", ".", "model", "(", ")", ".", "singular", "(", ")", ")", ";", "if", "(", "verb", "===", "'head'", ")", "return", ";", "if", "(", "verb", "===", "'post'", "&&", "!", "plural", ")", "return", ";", "if", "(", "verb", "===", "'put'", "&&", "plural", ")", "return", ";", "if", "(", "verb", "===", "'del'", ")", "verb", "=", "'delete'", ";", "operation", ".", "httpMethod", "=", "verb", ".", "toUpperCase", "(", ")", ";", "if", "(", "plural", ")", "operation", ".", "nickname", "=", "verb", "+", "titlePlural", ";", "else", "operation", ".", "nickname", "=", "verb", "+", "titleSingular", "+", "'ById'", ";", "operation", ".", "responseClass", "=", "titleSingular", ";", "if", "(", "plural", ")", "operation", ".", "summary", "=", "capitalize", "(", "verb", ")", "+", "' some '", "+", "controller", ".", "model", "(", ")", ".", "plural", "(", ")", ";", "else", "operation", ".", "summary", "=", "capitalize", "(", "verb", ")", "+", "' a '", "+", "controller", ".", "model", "(", ")", ".", "singular", "(", ")", "+", "' by its unique ID'", ";", "operation", ".", "parameters", "=", "generateParameters", "(", "verb", ",", "plural", ")", ";", "operation", ".", "errorResponses", "=", "generateErrorResponses", "(", "plural", ")", ";", "operations", ".", "push", "(", "operation", ")", ";", "}", ")", ";", "return", "operations", ";", "}" ]
Generate a list of a controller's operations
[ "Generate", "a", "list", "of", "a", "controller", "s", "operations" ]
405ffc754555034b57ca633b9c2c30454789169e
https://github.com/wprl/baucis-swagger/blob/405ffc754555034b57ca633b9c2c30454789169e/Controller.js#L260-L293
train
impromptu/impromptu
lib/DB.js
DB
function DB() { this.requests = {} process.on('message', function(message) { if (message.type !== 'cache:response') { return } /** @type {{error: Error, response: string, uid: string, method: string}} */ var data = message.data // The requests for this UID may not exist because there can be multiple // instances of Impromptu. if (!(this.requests[data.method] && this.requests[data.method][data.uid])) { return } var callbacks = this.requests[data.method][data.uid] for (var i = 0; i < callbacks.length; i++) { var callback = callbacks[i] callback(data.error, data.response) } delete this.requests[data.method][data.uid] }.bind(this)) }
javascript
function DB() { this.requests = {} process.on('message', function(message) { if (message.type !== 'cache:response') { return } /** @type {{error: Error, response: string, uid: string, method: string}} */ var data = message.data // The requests for this UID may not exist because there can be multiple // instances of Impromptu. if (!(this.requests[data.method] && this.requests[data.method][data.uid])) { return } var callbacks = this.requests[data.method][data.uid] for (var i = 0; i < callbacks.length; i++) { var callback = callbacks[i] callback(data.error, data.response) } delete this.requests[data.method][data.uid] }.bind(this)) }
[ "function", "DB", "(", ")", "{", "this", ".", "requests", "=", "{", "}", "process", ".", "on", "(", "'message'", ",", "function", "(", "message", ")", "{", "if", "(", "message", ".", "type", "!==", "'cache:response'", ")", "{", "return", "}", "var", "data", "=", "message", ".", "data", "if", "(", "!", "(", "this", ".", "requests", "[", "data", ".", "method", "]", "&&", "this", ".", "requests", "[", "data", ".", "method", "]", "[", "data", ".", "uid", "]", ")", ")", "{", "return", "}", "var", "callbacks", "=", "this", ".", "requests", "[", "data", ".", "method", "]", "[", "data", ".", "uid", "]", "for", "(", "var", "i", "=", "0", ";", "i", "<", "callbacks", ".", "length", ";", "i", "++", ")", "{", "var", "callback", "=", "callbacks", "[", "i", "]", "callback", "(", "data", ".", "error", ",", "data", ".", "response", ")", "}", "delete", "this", ".", "requests", "[", "data", ".", "method", "]", "[", "data", ".", "uid", "]", "}", ".", "bind", "(", "this", ")", ")", "}" ]
The Impromptu database client. @constructor
[ "The", "Impromptu", "database", "client", "." ]
829798eda62771d6a6ed971d87eef7a461932704
https://github.com/impromptu/impromptu/blob/829798eda62771d6a6ed971d87eef7a461932704/lib/DB.js#L7-L30
train
michaelnisi/pickup
repl.js
read
function read (parser, type, key, limit = Infinity) { let count = 0 pipeline(parser, new Writable({ write (obj, enc, cb) { if (typeof type === 'string') key = type if (typeof type === 'number') { limit = type type = undefined } if (typeof key === 'number') { limit = key key = undefined } if (count >= limit) { return cb() } if (type instanceof Object && !(obj instanceof type)) { return cb() } dir(key ? obj[key] : obj, { colors: true }) count++ cb() }, objectMode: true }), er => { log(er || 'ok') server.displayPrompt() }) }
javascript
function read (parser, type, key, limit = Infinity) { let count = 0 pipeline(parser, new Writable({ write (obj, enc, cb) { if (typeof type === 'string') key = type if (typeof type === 'number') { limit = type type = undefined } if (typeof key === 'number') { limit = key key = undefined } if (count >= limit) { return cb() } if (type instanceof Object && !(obj instanceof type)) { return cb() } dir(key ? obj[key] : obj, { colors: true }) count++ cb() }, objectMode: true }), er => { log(er || 'ok') server.displayPrompt() }) }
[ "function", "read", "(", "parser", ",", "type", ",", "key", ",", "limit", "=", "Infinity", ")", "{", "let", "count", "=", "0", "pipeline", "(", "parser", ",", "new", "Writable", "(", "{", "write", "(", "obj", ",", "enc", ",", "cb", ")", "{", "if", "(", "typeof", "type", "===", "'string'", ")", "key", "=", "type", "if", "(", "typeof", "type", "===", "'number'", ")", "{", "limit", "=", "type", "type", "=", "undefined", "}", "if", "(", "typeof", "key", "===", "'number'", ")", "{", "limit", "=", "key", "key", "=", "undefined", "}", "if", "(", "count", ">=", "limit", ")", "{", "return", "cb", "(", ")", "}", "if", "(", "type", "instanceof", "Object", "&&", "!", "(", "obj", "instanceof", "type", ")", ")", "{", "return", "cb", "(", ")", "}", "dir", "(", "key", "?", "obj", "[", "key", "]", ":", "obj", ",", "{", "colors", ":", "true", "}", ")", "count", "++", "cb", "(", ")", "}", ",", "objectMode", ":", "true", "}", ")", ",", "er", "=>", "{", "log", "(", "er", "||", "'ok'", ")", "server", ".", "displayPrompt", "(", ")", "}", ")", "}" ]
Reads all data of type from parser matching key. You can skip type or pass Feed or Entry for only seeing to those. You might also limit messages.
[ "Reads", "all", "data", "of", "type", "from", "parser", "matching", "key", ".", "You", "can", "skip", "type", "or", "pass", "Feed", "or", "Entry", "for", "only", "seeing", "to", "those", ".", "You", "might", "also", "limit", "messages", "." ]
582fba3f866a5c92bd46498323c3d11cc341183c
https://github.com/michaelnisi/pickup/blob/582fba3f866a5c92bd46498323c3d11cc341183c/repl.js#L43-L79
train
rfink/verdict.js
lib/index.js
Ruleset
function Ruleset(rules, composite) { if (!(this instanceof Ruleset)) { return new Ruleset(rules, composite); } this.composite = composite || 'all'; this.rules = rules || []; }
javascript
function Ruleset(rules, composite) { if (!(this instanceof Ruleset)) { return new Ruleset(rules, composite); } this.composite = composite || 'all'; this.rules = rules || []; }
[ "function", "Ruleset", "(", "rules", ",", "composite", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Ruleset", ")", ")", "{", "return", "new", "Ruleset", "(", "rules", ",", "composite", ")", ";", "}", "this", ".", "composite", "=", "composite", "||", "'all'", ";", "this", ".", "rules", "=", "rules", "||", "[", "]", ";", "}" ]
Construct a new ruleset
[ "Construct", "a", "new", "ruleset" ]
e7681c0593806ac097c01af7581a174227dc85d6
https://github.com/rfink/verdict.js/blob/e7681c0593806ac097c01af7581a174227dc85d6/lib/index.js#L11-L17
train
levexis/grunt-selenium-webdriver
tasks/selenium_webdriver.js
stop
function stop(next) { if (phantomProcess) { seleniumServerProcess.on('close', function (code, signal) { // this should really resolve both callbacks rather than guessing phantom wrapper will terminate instantly if (typeof next === 'function' && !seleniumServerProcess ) { next(); } }); // SIGTERM should ensure processes end cleanly, can do killall -9 java if getting startup errors phantomProcess.kill('SIGTERM'); started = false; starting = false; } if (seleniumServerProcess) { seleniumServerProcess.on('close', function (code, signal) { if (typeof next === 'function' ) { // need to stub out the other callback next(); } }); seleniumServerProcess.kill('SIGTERM'); started = false; starting = false; } }
javascript
function stop(next) { if (phantomProcess) { seleniumServerProcess.on('close', function (code, signal) { // this should really resolve both callbacks rather than guessing phantom wrapper will terminate instantly if (typeof next === 'function' && !seleniumServerProcess ) { next(); } }); // SIGTERM should ensure processes end cleanly, can do killall -9 java if getting startup errors phantomProcess.kill('SIGTERM'); started = false; starting = false; } if (seleniumServerProcess) { seleniumServerProcess.on('close', function (code, signal) { if (typeof next === 'function' ) { // need to stub out the other callback next(); } }); seleniumServerProcess.kill('SIGTERM'); started = false; starting = false; } }
[ "function", "stop", "(", "next", ")", "{", "if", "(", "phantomProcess", ")", "{", "seleniumServerProcess", ".", "on", "(", "'close'", ",", "function", "(", "code", ",", "signal", ")", "{", "if", "(", "typeof", "next", "===", "'function'", "&&", "!", "seleniumServerProcess", ")", "{", "next", "(", ")", ";", "}", "}", ")", ";", "phantomProcess", ".", "kill", "(", "'SIGTERM'", ")", ";", "started", "=", "false", ";", "starting", "=", "false", ";", "}", "if", "(", "seleniumServerProcess", ")", "{", "seleniumServerProcess", ".", "on", "(", "'close'", ",", "function", "(", "code", ",", "signal", ")", "{", "if", "(", "typeof", "next", "===", "'function'", ")", "{", "next", "(", ")", ";", "}", "}", ")", ";", "seleniumServerProcess", ".", "kill", "(", "'SIGTERM'", ")", ";", "started", "=", "false", ";", "starting", "=", "false", ";", "}", "}" ]
Stop the servers @param function optional callback @private
[ "Stop", "the", "servers" ]
e9f63af80c8e6738b00812370c6f1ba13c5dc817
https://github.com/levexis/grunt-selenium-webdriver/blob/e9f63af80c8e6738b00812370c6f1ba13c5dc817/tasks/selenium_webdriver.js#L216-L240
train
mojaie/kiwiii
src/component/formBoxGroup.js
scaleBoxGroup
function scaleBoxGroup(selection) { selection.classed('mb-3', true); // Scale type const scaleOptions = [ {key: 'linear', name: 'Linear'}, {key: 'log', name: 'Log'} ]; selection.append('div') .classed('scale', true) .classed('mb-1', true) .call(lbox.selectBox, 'Scale') .call(lbox.updateSelectBoxOptions, scaleOptions) .on('change', function () { const isLog = box.formValue(d3.select(this)) === 'log'; selection.select('.domain') .call(isLog ? rbox.logRange : rbox.linearRange) .call(badge.updateInvalidMessage, isLog ? 'Please provide a valid range (larger than 0)' : 'Please provide a valid number'); }); selection.append('div') .classed('domain', true) .classed('mb-1', true) .call(rbox.rangeBox, 'Domain'); }
javascript
function scaleBoxGroup(selection) { selection.classed('mb-3', true); // Scale type const scaleOptions = [ {key: 'linear', name: 'Linear'}, {key: 'log', name: 'Log'} ]; selection.append('div') .classed('scale', true) .classed('mb-1', true) .call(lbox.selectBox, 'Scale') .call(lbox.updateSelectBoxOptions, scaleOptions) .on('change', function () { const isLog = box.formValue(d3.select(this)) === 'log'; selection.select('.domain') .call(isLog ? rbox.logRange : rbox.linearRange) .call(badge.updateInvalidMessage, isLog ? 'Please provide a valid range (larger than 0)' : 'Please provide a valid number'); }); selection.append('div') .classed('domain', true) .classed('mb-1', true) .call(rbox.rangeBox, 'Domain'); }
[ "function", "scaleBoxGroup", "(", "selection", ")", "{", "selection", ".", "classed", "(", "'mb-3'", ",", "true", ")", ";", "const", "scaleOptions", "=", "[", "{", "key", ":", "'linear'", ",", "name", ":", "'Linear'", "}", ",", "{", "key", ":", "'log'", ",", "name", ":", "'Log'", "}", "]", ";", "selection", ".", "append", "(", "'div'", ")", ".", "classed", "(", "'scale'", ",", "true", ")", ".", "classed", "(", "'mb-1'", ",", "true", ")", ".", "call", "(", "lbox", ".", "selectBox", ",", "'Scale'", ")", ".", "call", "(", "lbox", ".", "updateSelectBoxOptions", ",", "scaleOptions", ")", ".", "on", "(", "'change'", ",", "function", "(", ")", "{", "const", "isLog", "=", "box", ".", "formValue", "(", "d3", ".", "select", "(", "this", ")", ")", "===", "'log'", ";", "selection", ".", "select", "(", "'.domain'", ")", ".", "call", "(", "isLog", "?", "rbox", ".", "logRange", ":", "rbox", ".", "linearRange", ")", ".", "call", "(", "badge", ".", "updateInvalidMessage", ",", "isLog", "?", "'Please provide a valid range (larger than 0)'", ":", "'Please provide a valid number'", ")", ";", "}", ")", ";", "selection", ".", "append", "(", "'div'", ")", ".", "classed", "(", "'domain'", ",", "true", ")", ".", "classed", "(", "'mb-1'", ",", "true", ")", ".", "call", "(", "rbox", ".", "rangeBox", ",", "'Domain'", ")", ";", "}" ]
Render scale and domain control box group @param {d3.selection} selection - selection of box container (div element)
[ "Render", "scale", "and", "domain", "control", "box", "group" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/component/formBoxGroup.js#L107-L132
train
impromptu/impromptu
lib/cache/AbstractCache.js
AbstractCache
function AbstractCache(state, name, options) { this.state = state this.name = name this.options = options this._update = this._update.bind(this) this._setLock = false this._setCallbacks = [] this._needsRefresh = false this.state.on('refreshCache', function (needsRefresh) { this._needsRefresh = needsRefresh }.bind(this)) // Build our own `run` instance-method to accurately reflect the fact that // `run` is always asynchronous and requires an argument to declare itself // as such to our API. var protoRun = this.run this.run = function(done) { if (this.options.run) { return this.options.run.apply(this, arguments) } else { return protoRun.apply(this, arguments) } }.bind(this) }
javascript
function AbstractCache(state, name, options) { this.state = state this.name = name this.options = options this._update = this._update.bind(this) this._setLock = false this._setCallbacks = [] this._needsRefresh = false this.state.on('refreshCache', function (needsRefresh) { this._needsRefresh = needsRefresh }.bind(this)) // Build our own `run` instance-method to accurately reflect the fact that // `run` is always asynchronous and requires an argument to declare itself // as such to our API. var protoRun = this.run this.run = function(done) { if (this.options.run) { return this.options.run.apply(this, arguments) } else { return protoRun.apply(this, arguments) } }.bind(this) }
[ "function", "AbstractCache", "(", "state", ",", "name", ",", "options", ")", "{", "this", ".", "state", "=", "state", "this", ".", "name", "=", "name", "this", ".", "options", "=", "options", "this", ".", "_update", "=", "this", ".", "_update", ".", "bind", "(", "this", ")", "this", ".", "_setLock", "=", "false", "this", ".", "_setCallbacks", "=", "[", "]", "this", ".", "_needsRefresh", "=", "false", "this", ".", "state", ".", "on", "(", "'refreshCache'", ",", "function", "(", "needsRefresh", ")", "{", "this", ".", "_needsRefresh", "=", "needsRefresh", "}", ".", "bind", "(", "this", ")", ")", "var", "protoRun", "=", "this", ".", "run", "this", ".", "run", "=", "function", "(", "done", ")", "{", "if", "(", "this", ".", "options", ".", "run", ")", "{", "return", "this", ".", "options", ".", "run", ".", "apply", "(", "this", ",", "arguments", ")", "}", "else", "{", "return", "protoRun", ".", "apply", "(", "this", ",", "arguments", ")", "}", "}", ".", "bind", "(", "this", ")", "}" ]
An abstract class that manages how a method is cached. @constructor @param {State} state @param {string} name The name of the cache key. @param {Object} options The options for this instance of the cache.
[ "An", "abstract", "class", "that", "manages", "how", "a", "method", "is", "cached", "." ]
829798eda62771d6a6ed971d87eef7a461932704
https://github.com/impromptu/impromptu/blob/829798eda62771d6a6ed971d87eef7a461932704/lib/cache/AbstractCache.js#L16-L42
train
byron-dupreez/aws-core-utils
other-lambdas.js
succeedLambdaCallback
function succeedLambdaCallback(callback, response, event, context) { return executePreSuccessCallback(response, event, context) .then(() => callback(null, response)) .catch(err => { console.error(`Unexpected failure after executePreSuccessCallback`, err); return callback(null, response); }); }
javascript
function succeedLambdaCallback(callback, response, event, context) { return executePreSuccessCallback(response, event, context) .then(() => callback(null, response)) .catch(err => { console.error(`Unexpected failure after executePreSuccessCallback`, err); return callback(null, response); }); }
[ "function", "succeedLambdaCallback", "(", "callback", ",", "response", ",", "event", ",", "context", ")", "{", "return", "executePreSuccessCallback", "(", "response", ",", "event", ",", "context", ")", ".", "then", "(", "(", ")", "=>", "callback", "(", "null", ",", "response", ")", ")", ".", "catch", "(", "err", "=>", "{", "console", ".", "error", "(", "`", "`", ",", "err", ")", ";", "return", "callback", "(", "null", ",", "response", ")", ";", "}", ")", ";", "}" ]
Succeeds the given callback of an AWS Lambda, by invoking the given callback with the given response. @param {Function} callback - the callback function passed as the last argument to your Lambda function on invocation. @param {Object} response - a normal or Lambda Proxy integration response to be returned @param {AWSEvent} event - the AWS event passed to your handler @param {StandardHandlerContext} context - the context to use
[ "Succeeds", "the", "given", "callback", "of", "an", "AWS", "Lambda", "by", "invoking", "the", "given", "callback", "with", "the", "given", "response", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/other-lambdas.js#L261-L268
train
mailsvb/node-red-contrib-twitter-stream
twitter/twitter.js
TwitterAPIConnection
function TwitterAPIConnection(n) { RED.nodes.createNode(this,n); var node = this; node.consumerKey = n.consumerKey; node.consumerSecret = n.consumerSecret; node.accessToken = n.accessToken; node.accessSecret = n.accessSecret; var id = node.consumerKey; node.log('create new Twitter instance for: ' + id); clients[id] = new Twit({ consumer_key: node.consumerKey, consumer_secret: node.consumerSecret, access_token: node.accessToken, access_token_secret: node.accessSecret }); node.client = clients[id]; this.on("close", function() { node.log('delete Twitter instance on close event'); delete clients[id]; }); }
javascript
function TwitterAPIConnection(n) { RED.nodes.createNode(this,n); var node = this; node.consumerKey = n.consumerKey; node.consumerSecret = n.consumerSecret; node.accessToken = n.accessToken; node.accessSecret = n.accessSecret; var id = node.consumerKey; node.log('create new Twitter instance for: ' + id); clients[id] = new Twit({ consumer_key: node.consumerKey, consumer_secret: node.consumerSecret, access_token: node.accessToken, access_token_secret: node.accessSecret }); node.client = clients[id]; this.on("close", function() { node.log('delete Twitter instance on close event'); delete clients[id]; }); }
[ "function", "TwitterAPIConnection", "(", "n", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "n", ")", ";", "var", "node", "=", "this", ";", "node", ".", "consumerKey", "=", "n", ".", "consumerKey", ";", "node", ".", "consumerSecret", "=", "n", ".", "consumerSecret", ";", "node", ".", "accessToken", "=", "n", ".", "accessToken", ";", "node", ".", "accessSecret", "=", "n", ".", "accessSecret", ";", "var", "id", "=", "node", ".", "consumerKey", ";", "node", ".", "log", "(", "'create new Twitter instance for: '", "+", "id", ")", ";", "clients", "[", "id", "]", "=", "new", "Twit", "(", "{", "consumer_key", ":", "node", ".", "consumerKey", ",", "consumer_secret", ":", "node", ".", "consumerSecret", ",", "access_token", ":", "node", ".", "accessToken", ",", "access_token_secret", ":", "node", ".", "accessSecret", "}", ")", ";", "node", ".", "client", "=", "clients", "[", "id", "]", ";", "this", ".", "on", "(", "\"close\"", ",", "function", "(", ")", "{", "node", ".", "log", "(", "'delete Twitter instance on close event'", ")", ";", "delete", "clients", "[", "id", "]", ";", "}", ")", ";", "}" ]
handle the connection to the Twitter API
[ "handle", "the", "connection", "to", "the", "Twitter", "API" ]
edc54952576006f46faf4cbc05f82bbf413a0c0c
https://github.com/mailsvb/node-red-contrib-twitter-stream/blob/edc54952576006f46faf4cbc05f82bbf413a0c0c/twitter/twitter.js#L11-L36
train
wwayne/mooseql
lib/schema/index.js
buildSchema
function buildSchema(models, typeMap) { let type; var _models$map$reduce = models.map(model => { type = typeMap[model.modelName]; return { query: (0, _buildQuery2.default)(model, type), mutation: (0, _buildMutation2.default)(model, type) }; }).reduce((fields, modelField) => { fields.query = (0, _assign2.default)({}, fields.query, modelField.query); fields.mutation = (0, _assign2.default)({}, fields.mutation, modelField.mutation); return fields; }, { query: {}, mutation: {} }); const query = _models$map$reduce.query; const mutation = _models$map$reduce.mutation; return { query: query, mutation: mutation }; }
javascript
function buildSchema(models, typeMap) { let type; var _models$map$reduce = models.map(model => { type = typeMap[model.modelName]; return { query: (0, _buildQuery2.default)(model, type), mutation: (0, _buildMutation2.default)(model, type) }; }).reduce((fields, modelField) => { fields.query = (0, _assign2.default)({}, fields.query, modelField.query); fields.mutation = (0, _assign2.default)({}, fields.mutation, modelField.mutation); return fields; }, { query: {}, mutation: {} }); const query = _models$map$reduce.query; const mutation = _models$map$reduce.mutation; return { query: query, mutation: mutation }; }
[ "function", "buildSchema", "(", "models", ",", "typeMap", ")", "{", "let", "type", ";", "var", "_models$map$reduce", "=", "models", ".", "map", "(", "model", "=>", "{", "type", "=", "typeMap", "[", "model", ".", "modelName", "]", ";", "return", "{", "query", ":", "(", "0", ",", "_buildQuery2", ".", "default", ")", "(", "model", ",", "type", ")", ",", "mutation", ":", "(", "0", ",", "_buildMutation2", ".", "default", ")", "(", "model", ",", "type", ")", "}", ";", "}", ")", ".", "reduce", "(", "(", "fields", ",", "modelField", ")", "=>", "{", "fields", ".", "query", "=", "(", "0", ",", "_assign2", ".", "default", ")", "(", "{", "}", ",", "fields", ".", "query", ",", "modelField", ".", "query", ")", ";", "fields", ".", "mutation", "=", "(", "0", ",", "_assign2", ".", "default", ")", "(", "{", "}", ",", "fields", ".", "mutation", ",", "modelField", ".", "mutation", ")", ";", "return", "fields", ";", "}", ",", "{", "query", ":", "{", "}", ",", "mutation", ":", "{", "}", "}", ")", ";", "const", "query", "=", "_models$map$reduce", ".", "query", ";", "const", "mutation", "=", "_models$map$reduce", ".", "mutation", ";", "return", "{", "query", ":", "query", ",", "mutation", ":", "mutation", "}", ";", "}" ]
Build graphql CRUD schema based on models and types @params - models {Array} mongoose models - typeMap {Object} map of model and corresponding graphql type @return - grapqhl schema which has query and mutation
[ "Build", "graphql", "CRUD", "schema", "based", "on", "models", "and", "types" ]
4bd5f1e0e378fee59524d79c42154dbe9b07421b
https://github.com/wwayne/mooseql/blob/4bd5f1e0e378fee59524d79c42154dbe9b07421b/lib/schema/index.js#L31-L54
train
byron-dupreez/aws-core-utils
stages.js
loadDefaultStageHandlingOptions
function loadDefaultStageHandlingOptions() { const options = require('./stages-options.json'); const defaultOptions = options ? options.stageHandlingOptions : {}; const defaults = { envStageName: 'STAGE', streamNameStageSeparator: '_', resourceNameStageSeparator: '_', injectInCase: 'upper', extractInCase: 'lower', defaultStage: undefined }; return merge(defaults, defaultOptions); }
javascript
function loadDefaultStageHandlingOptions() { const options = require('./stages-options.json'); const defaultOptions = options ? options.stageHandlingOptions : {}; const defaults = { envStageName: 'STAGE', streamNameStageSeparator: '_', resourceNameStageSeparator: '_', injectInCase: 'upper', extractInCase: 'lower', defaultStage: undefined }; return merge(defaults, defaultOptions); }
[ "function", "loadDefaultStageHandlingOptions", "(", ")", "{", "const", "options", "=", "require", "(", "'./stages-options.json'", ")", ";", "const", "defaultOptions", "=", "options", "?", "options", ".", "stageHandlingOptions", ":", "{", "}", ";", "const", "defaults", "=", "{", "envStageName", ":", "'STAGE'", ",", "streamNameStageSeparator", ":", "'_'", ",", "resourceNameStageSeparator", ":", "'_'", ",", "injectInCase", ":", "'upper'", ",", "extractInCase", ":", "'lower'", ",", "defaultStage", ":", "undefined", "}", ";", "return", "merge", "(", "defaults", ",", "defaultOptions", ")", ";", "}" ]
Loads the default stage handling options from the local stages-options.json file and fills in any missing options with the static default options. @returns {StageHandlingOptions} the default stage handling options
[ "Loads", "the", "default", "stage", "handling", "options", "from", "the", "local", "stages", "-", "options", ".", "json", "file", "and", "fills", "in", "any", "missing", "options", "with", "the", "static", "default", "options", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stages.js#L231-L244
train
byron-dupreez/aws-core-utils
stages.js
toStageSuffixedName
function toStageSuffixedName(unsuffixedName, separator, stage, inCase) { const name = trim(unsuffixedName); const stageSuffix = isNotBlank(stage) ? `${trimOrEmpty(separator)}${toCase(trim(stage), inCase)}` : ''; return isNotBlank(name) && isNotBlank(stageSuffix) && !name.endsWith(stageSuffix) ? `${name}${stageSuffix}` : name; }
javascript
function toStageSuffixedName(unsuffixedName, separator, stage, inCase) { const name = trim(unsuffixedName); const stageSuffix = isNotBlank(stage) ? `${trimOrEmpty(separator)}${toCase(trim(stage), inCase)}` : ''; return isNotBlank(name) && isNotBlank(stageSuffix) && !name.endsWith(stageSuffix) ? `${name}${stageSuffix}` : name; }
[ "function", "toStageSuffixedName", "(", "unsuffixedName", ",", "separator", ",", "stage", ",", "inCase", ")", "{", "const", "name", "=", "trim", "(", "unsuffixedName", ")", ";", "const", "stageSuffix", "=", "isNotBlank", "(", "stage", ")", "?", "`", "${", "trimOrEmpty", "(", "separator", ")", "}", "${", "toCase", "(", "trim", "(", "stage", ")", ",", "inCase", ")", "}", "`", ":", "''", ";", "return", "isNotBlank", "(", "name", ")", "&&", "isNotBlank", "(", "stageSuffix", ")", "&&", "!", "name", ".", "endsWith", "(", "stageSuffix", ")", "?", "`", "${", "name", "}", "${", "stageSuffix", "}", "`", ":", "name", ";", "}" ]
Returns a stage-suffixed version of the given unsuffixed name with an appended stage suffix, which will contain the given separator followed by the given stage, which will be appended in uppercase, lowercase or kept as is according to the given inCase. @param {string} unsuffixedName - the unsuffixed name @param {string} separator - the separator to use to separate the resource name from the stage @param {string} stage - the stage to append @param {string} inCase - specifies whether to convert the stage to uppercase (if 'uppercase' or 'upper') or to lowercase (if 'lowercase' or 'lower') or keep it as provided (if 'as_is' or anything else) @return {string} the stage-suffixed name
[ "Returns", "a", "stage", "-", "suffixed", "version", "of", "the", "given", "unsuffixed", "name", "with", "an", "appended", "stage", "suffix", "which", "will", "contain", "the", "given", "separator", "followed", "by", "the", "given", "stage", "which", "will", "be", "appended", "in", "uppercase", "lowercase", "or", "kept", "as", "is", "according", "to", "the", "given", "inCase", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stages.js#L864-L868
train
byron-dupreez/aws-core-utils
stages.js
toCase
function toCase(value, asCase) { if (isNotBlank(value)) { // Convert the given asCase argument to lowercase to facilitate matching const caseToUse = trimOrEmpty(asCase && asCase.toLowerCase ? asCase.toLowerCase() : asCase); // Convert the given stage into the requested case return caseToUse === 'lowercase' || caseToUse === 'lower' ? value.toLowerCase() : caseToUse === 'uppercase' || caseToUse === 'upper' ? value.toUpperCase() : value; } return value; }
javascript
function toCase(value, asCase) { if (isNotBlank(value)) { // Convert the given asCase argument to lowercase to facilitate matching const caseToUse = trimOrEmpty(asCase && asCase.toLowerCase ? asCase.toLowerCase() : asCase); // Convert the given stage into the requested case return caseToUse === 'lowercase' || caseToUse === 'lower' ? value.toLowerCase() : caseToUse === 'uppercase' || caseToUse === 'upper' ? value.toUpperCase() : value; } return value; }
[ "function", "toCase", "(", "value", ",", "asCase", ")", "{", "if", "(", "isNotBlank", "(", "value", ")", ")", "{", "const", "caseToUse", "=", "trimOrEmpty", "(", "asCase", "&&", "asCase", ".", "toLowerCase", "?", "asCase", ".", "toLowerCase", "(", ")", ":", "asCase", ")", ";", "return", "caseToUse", "===", "'lowercase'", "||", "caseToUse", "===", "'lower'", "?", "value", ".", "toLowerCase", "(", ")", ":", "caseToUse", "===", "'uppercase'", "||", "caseToUse", "===", "'upper'", "?", "value", ".", "toUpperCase", "(", ")", ":", "value", ";", "}", "return", "value", ";", "}" ]
Converts the given value to uppercase, lowercase or keeps it as is according to the given asCase argument. @param value - the value to convert or keep as is @param {string} asCase - specifies whether to convert the value to uppercase (if 'uppercase' or 'upper') or to lowercase (if 'lowercase' or 'lower') or to keep it as provided (if 'as_is' or anything else) @return {string} the converted or given value
[ "Converts", "the", "given", "value", "to", "uppercase", "lowercase", "or", "keeps", "it", "as", "is", "according", "to", "the", "given", "asCase", "argument", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stages.js#L877-L887
train
wwayne/mooseql
lib/utils.js
filterArgs
function filterArgs(defaultArgs, opt) { opt = opt || {}; const packValueToNonNull = value => (0, _assign2.default)({}, value, { type: new _graphql.GraphQLNonNull(value.type) }); return (0, _entries2.default)(defaultArgs).filter(_ref => { var _ref2 = (0, _slicedToArray3.default)(_ref, 2); let arg = _ref2[0]; let value = _ref2[1]; if (opt.onlyId && arg !== 'id' && arg !== 'ids') return false; if (opt.id && (arg === 'id' || arg === 'ids')) return false; if (opt.plural && !value.onlyPlural && _pluralize2.default.plural(arg) === arg) return false; return true; }).map(_ref3 => { var _ref4 = (0, _slicedToArray3.default)(_ref3, 2); let arg = _ref4[0]; let value = _ref4[1]; let newValue = (0, _assign2.default)({}, value); if ((arg === 'id' || arg === 'ids') && opt.idRequired) newValue = packValueToNonNull(newValue); if (!opt.required && newValue.required && !newValue.context) newValue = packValueToNonNull(newValue); return [arg, newValue]; }).reduce((args, _ref5) => { var _ref6 = (0, _slicedToArray3.default)(_ref5, 2); let arg = _ref6[0]; let value = _ref6[1]; return (0, _assign2.default)(args, { [arg]: value }); }, {}); }
javascript
function filterArgs(defaultArgs, opt) { opt = opt || {}; const packValueToNonNull = value => (0, _assign2.default)({}, value, { type: new _graphql.GraphQLNonNull(value.type) }); return (0, _entries2.default)(defaultArgs).filter(_ref => { var _ref2 = (0, _slicedToArray3.default)(_ref, 2); let arg = _ref2[0]; let value = _ref2[1]; if (opt.onlyId && arg !== 'id' && arg !== 'ids') return false; if (opt.id && (arg === 'id' || arg === 'ids')) return false; if (opt.plural && !value.onlyPlural && _pluralize2.default.plural(arg) === arg) return false; return true; }).map(_ref3 => { var _ref4 = (0, _slicedToArray3.default)(_ref3, 2); let arg = _ref4[0]; let value = _ref4[1]; let newValue = (0, _assign2.default)({}, value); if ((arg === 'id' || arg === 'ids') && opt.idRequired) newValue = packValueToNonNull(newValue); if (!opt.required && newValue.required && !newValue.context) newValue = packValueToNonNull(newValue); return [arg, newValue]; }).reduce((args, _ref5) => { var _ref6 = (0, _slicedToArray3.default)(_ref5, 2); let arg = _ref6[0]; let value = _ref6[1]; return (0, _assign2.default)(args, { [arg]: value }); }, {}); }
[ "function", "filterArgs", "(", "defaultArgs", ",", "opt", ")", "{", "opt", "=", "opt", "||", "{", "}", ";", "const", "packValueToNonNull", "=", "value", "=>", "(", "0", ",", "_assign2", ".", "default", ")", "(", "{", "}", ",", "value", ",", "{", "type", ":", "new", "_graphql", ".", "GraphQLNonNull", "(", "value", ".", "type", ")", "}", ")", ";", "return", "(", "0", ",", "_entries2", ".", "default", ")", "(", "defaultArgs", ")", ".", "filter", "(", "_ref", "=>", "{", "var", "_ref2", "=", "(", "0", ",", "_slicedToArray3", ".", "default", ")", "(", "_ref", ",", "2", ")", ";", "let", "arg", "=", "_ref2", "[", "0", "]", ";", "let", "value", "=", "_ref2", "[", "1", "]", ";", "if", "(", "opt", ".", "onlyId", "&&", "arg", "!==", "'id'", "&&", "arg", "!==", "'ids'", ")", "return", "false", ";", "if", "(", "opt", ".", "id", "&&", "(", "arg", "===", "'id'", "||", "arg", "===", "'ids'", ")", ")", "return", "false", ";", "if", "(", "opt", ".", "plural", "&&", "!", "value", ".", "onlyPlural", "&&", "_pluralize2", ".", "default", ".", "plural", "(", "arg", ")", "===", "arg", ")", "return", "false", ";", "return", "true", ";", "}", ")", ".", "map", "(", "_ref3", "=>", "{", "var", "_ref4", "=", "(", "0", ",", "_slicedToArray3", ".", "default", ")", "(", "_ref3", ",", "2", ")", ";", "let", "arg", "=", "_ref4", "[", "0", "]", ";", "let", "value", "=", "_ref4", "[", "1", "]", ";", "let", "newValue", "=", "(", "0", ",", "_assign2", ".", "default", ")", "(", "{", "}", ",", "value", ")", ";", "if", "(", "(", "arg", "===", "'id'", "||", "arg", "===", "'ids'", ")", "&&", "opt", ".", "idRequired", ")", "newValue", "=", "packValueToNonNull", "(", "newValue", ")", ";", "if", "(", "!", "opt", ".", "required", "&&", "newValue", ".", "required", "&&", "!", "newValue", ".", "context", ")", "newValue", "=", "packValueToNonNull", "(", "newValue", ")", ";", "return", "[", "arg", ",", "newValue", "]", ";", "}", ")", ".", "reduce", "(", "(", "args", ",", "_ref5", ")", "=>", "{", "var", "_ref6", "=", "(", "0", ",", "_slicedToArray3", ".", "default", ")", "(", "_ref5", ",", "2", ")", ";", "let", "arg", "=", "_ref6", "[", "0", "]", ";", "let", "value", "=", "_ref6", "[", "1", "]", ";", "return", "(", "0", ",", "_assign2", ".", "default", ")", "(", "args", ",", "{", "[", "arg", "]", ":", "value", "}", ")", ";", "}", ",", "{", "}", ")", ";", "}" ]
Filter arguments when doing CRUD @params - defaultArgs {Object} the result of buildArgs - opt {Object {filter: {Bool}} options: id, plural, required, idRequired, onlyId
[ "Filter", "arguments", "when", "doing", "CRUD" ]
4bd5f1e0e378fee59524d79c42154dbe9b07421b
https://github.com/wwayne/mooseql/blob/4bd5f1e0e378fee59524d79c42154dbe9b07421b/lib/utils.js#L37-L68
train
wwayne/mooseql
lib/utils.js
toMongooseArgs
function toMongooseArgs(args) { // Covert name_first to name: {first} let keyDepth = []; return (0, _entries2.default)(args).reduce((args, _ref7) => { var _ref8 = (0, _slicedToArray3.default)(_ref7, 2); let key = _ref8[0]; let value = _ref8[1]; keyDepth = key.split('_'); if (keyDepth.length === 1) return (0, _assign2.default)(args, { [key]: value }); keyDepth.reduce((args, depth, index) => { if (index === keyDepth.length - 1) { args[depth] = value; return; } args[depth] = args[depth] || {}; return args[depth]; }, args); return args; }, {}); }
javascript
function toMongooseArgs(args) { // Covert name_first to name: {first} let keyDepth = []; return (0, _entries2.default)(args).reduce((args, _ref7) => { var _ref8 = (0, _slicedToArray3.default)(_ref7, 2); let key = _ref8[0]; let value = _ref8[1]; keyDepth = key.split('_'); if (keyDepth.length === 1) return (0, _assign2.default)(args, { [key]: value }); keyDepth.reduce((args, depth, index) => { if (index === keyDepth.length - 1) { args[depth] = value; return; } args[depth] = args[depth] || {}; return args[depth]; }, args); return args; }, {}); }
[ "function", "toMongooseArgs", "(", "args", ")", "{", "let", "keyDepth", "=", "[", "]", ";", "return", "(", "0", ",", "_entries2", ".", "default", ")", "(", "args", ")", ".", "reduce", "(", "(", "args", ",", "_ref7", ")", "=>", "{", "var", "_ref8", "=", "(", "0", ",", "_slicedToArray3", ".", "default", ")", "(", "_ref7", ",", "2", ")", ";", "let", "key", "=", "_ref8", "[", "0", "]", ";", "let", "value", "=", "_ref8", "[", "1", "]", ";", "keyDepth", "=", "key", ".", "split", "(", "'_'", ")", ";", "if", "(", "keyDepth", ".", "length", "===", "1", ")", "return", "(", "0", ",", "_assign2", ".", "default", ")", "(", "args", ",", "{", "[", "key", "]", ":", "value", "}", ")", ";", "keyDepth", ".", "reduce", "(", "(", "args", ",", "depth", ",", "index", ")", "=>", "{", "if", "(", "index", "===", "keyDepth", ".", "length", "-", "1", ")", "{", "args", "[", "depth", "]", "=", "value", ";", "return", ";", "}", "args", "[", "depth", "]", "=", "args", "[", "depth", "]", "||", "{", "}", ";", "return", "args", "[", "depth", "]", ";", "}", ",", "args", ")", ";", "return", "args", ";", "}", ",", "{", "}", ")", ";", "}" ]
Convert args that graphql know to the args that mongoose know so that the args can be used by mongoose to find or create
[ "Convert", "args", "that", "graphql", "know", "to", "the", "args", "that", "mongoose", "know", "so", "that", "the", "args", "can", "be", "used", "by", "mongoose", "to", "find", "or", "create" ]
4bd5f1e0e378fee59524d79c42154dbe9b07421b
https://github.com/wwayne/mooseql/blob/4bd5f1e0e378fee59524d79c42154dbe9b07421b/lib/utils.js#L74-L95
train
elb-min-uhh/markdown-elearnjs
scripts/cleandocumentation.js
directoryCleanEverything
function directoryCleanEverything(dirPath, includeExtension, toRemove, replacement) { if(!fs.existsSync(dirPath)) return; let isDirectory = fs.statSync(dirPath).isDirectory(); // try cleaning package.json in current dir if(!isDirectory && dirPath.match(new RegExp(includeExtension + "$", "g"))) { let content = fs.readFileSync(dirPath).toString(); while(content.indexOf(toRemove) >= 0) { content = content.replace(toRemove, replacement || ""); } fs.writeFileSync(dirPath, content); } else if(isDirectory) { // check for subdirectories let list = fs.readdirSync(dirPath); for(let dir of list) { let subDirPath = dirPath + "/" + dir; directoryCleanEverything(subDirPath, includeExtension, toRemove, replacement); } } }
javascript
function directoryCleanEverything(dirPath, includeExtension, toRemove, replacement) { if(!fs.existsSync(dirPath)) return; let isDirectory = fs.statSync(dirPath).isDirectory(); // try cleaning package.json in current dir if(!isDirectory && dirPath.match(new RegExp(includeExtension + "$", "g"))) { let content = fs.readFileSync(dirPath).toString(); while(content.indexOf(toRemove) >= 0) { content = content.replace(toRemove, replacement || ""); } fs.writeFileSync(dirPath, content); } else if(isDirectory) { // check for subdirectories let list = fs.readdirSync(dirPath); for(let dir of list) { let subDirPath = dirPath + "/" + dir; directoryCleanEverything(subDirPath, includeExtension, toRemove, replacement); } } }
[ "function", "directoryCleanEverything", "(", "dirPath", ",", "includeExtension", ",", "toRemove", ",", "replacement", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "dirPath", ")", ")", "return", ";", "let", "isDirectory", "=", "fs", ".", "statSync", "(", "dirPath", ")", ".", "isDirectory", "(", ")", ";", "if", "(", "!", "isDirectory", "&&", "dirPath", ".", "match", "(", "new", "RegExp", "(", "includeExtension", "+", "\"$\"", ",", "\"g\"", ")", ")", ")", "{", "let", "content", "=", "fs", ".", "readFileSync", "(", "dirPath", ")", ".", "toString", "(", ")", ";", "while", "(", "content", ".", "indexOf", "(", "toRemove", ")", ">=", "0", ")", "{", "content", "=", "content", ".", "replace", "(", "toRemove", ",", "replacement", "||", "\"\"", ")", ";", "}", "fs", ".", "writeFileSync", "(", "dirPath", ",", "content", ")", ";", "}", "else", "if", "(", "isDirectory", ")", "{", "let", "list", "=", "fs", ".", "readdirSync", "(", "dirPath", ")", ";", "for", "(", "let", "dir", "of", "list", ")", "{", "let", "subDirPath", "=", "dirPath", "+", "\"/\"", "+", "dir", ";", "directoryCleanEverything", "(", "subDirPath", ",", "includeExtension", ",", "toRemove", ",", "replacement", ")", ";", "}", "}", "}" ]
Removes the `toRemove` string from every package.json found in the subtree @param {*} dirPath the parent dir
[ "Removes", "the", "toRemove", "string", "from", "every", "package", ".", "json", "found", "in", "the", "subtree" ]
a09bcc497c3c50dd565b7f440fa1f7b62074d679
https://github.com/elb-min-uhh/markdown-elearnjs/blob/a09bcc497c3c50dd565b7f440fa1f7b62074d679/scripts/cleandocumentation.js#L20-L39
train
XOP/sass-vars-to-js
src/_get-var-value.js
resolveVarValue
function resolveVarValue (name, values) { if (is.undef(values) || is.args.empty(arguments)) { message('Error: Missing arguments'); return undefined; } if (!is.string(name) || !is.object(values)) { message('Error: Check arguments type'); return undefined; } const varName = name.slice(1); return values[varName] || null; }
javascript
function resolveVarValue (name, values) { if (is.undef(values) || is.args.empty(arguments)) { message('Error: Missing arguments'); return undefined; } if (!is.string(name) || !is.object(values)) { message('Error: Check arguments type'); return undefined; } const varName = name.slice(1); return values[varName] || null; }
[ "function", "resolveVarValue", "(", "name", ",", "values", ")", "{", "if", "(", "is", ".", "undef", "(", "values", ")", "||", "is", ".", "args", ".", "empty", "(", "arguments", ")", ")", "{", "message", "(", "'Error: Missing arguments'", ")", ";", "return", "undefined", ";", "}", "if", "(", "!", "is", ".", "string", "(", "name", ")", "||", "!", "is", ".", "object", "(", "values", ")", ")", "{", "message", "(", "'Error: Check arguments type'", ")", ";", "return", "undefined", ";", "}", "const", "varName", "=", "name", ".", "slice", "(", "1", ")", ";", "return", "values", "[", "varName", "]", "||", "null", ";", "}" ]
Finds predefined variable value in variables object Returns variable value if any resolved @param name @param values @returns {*}
[ "Finds", "predefined", "variable", "value", "in", "variables", "object", "Returns", "variable", "value", "if", "any", "resolved" ]
87ad8588701a9c2e69ace75931947d11698f25f0
https://github.com/XOP/sass-vars-to-js/blob/87ad8588701a9c2e69ace75931947d11698f25f0/src/_get-var-value.js#L12-L26
train
XOP/sass-vars-to-js
src/utils/_message.js
message
function message (text) { const normalText = text.toLowerCase(); if (~normalText.indexOf('warning')) { log.warn(text) } else if (~normalText.indexOf('error')) { log.error(text); } else { log.debug(text); } }
javascript
function message (text) { const normalText = text.toLowerCase(); if (~normalText.indexOf('warning')) { log.warn(text) } else if (~normalText.indexOf('error')) { log.error(text); } else { log.debug(text); } }
[ "function", "message", "(", "text", ")", "{", "const", "normalText", "=", "text", ".", "toLowerCase", "(", ")", ";", "if", "(", "~", "normalText", ".", "indexOf", "(", "'warning'", ")", ")", "{", "log", ".", "warn", "(", "text", ")", "}", "else", "if", "(", "~", "normalText", ".", "indexOf", "(", "'error'", ")", ")", "{", "log", ".", "error", "(", "text", ")", ";", "}", "else", "{", "log", ".", "debug", "(", "text", ")", ";", "}", "}" ]
Pretty logger Returns beautified message @param text
[ "Pretty", "logger", "Returns", "beautified", "message" ]
87ad8588701a9c2e69ace75931947d11698f25f0
https://github.com/XOP/sass-vars-to-js/blob/87ad8588701a9c2e69ace75931947d11698f25f0/src/utils/_message.js#L8-L18
train
byron-dupreez/aws-core-utils
dynamodb-utils.js
toObjectFromDynamoDBMap
function toObjectFromDynamoDBMap(dynamoDBMap) { if (!dynamoDBMap || typeof dynamoDBMap !== 'object') { return dynamoDBMap; } const object = {}; const keys = Object.getOwnPropertyNames(dynamoDBMap); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; object[key] = toValueFromAttributeValue(dynamoDBMap[key]); } return object; }
javascript
function toObjectFromDynamoDBMap(dynamoDBMap) { if (!dynamoDBMap || typeof dynamoDBMap !== 'object') { return dynamoDBMap; } const object = {}; const keys = Object.getOwnPropertyNames(dynamoDBMap); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; object[key] = toValueFromAttributeValue(dynamoDBMap[key]); } return object; }
[ "function", "toObjectFromDynamoDBMap", "(", "dynamoDBMap", ")", "{", "if", "(", "!", "dynamoDBMap", "||", "typeof", "dynamoDBMap", "!==", "'object'", ")", "{", "return", "dynamoDBMap", ";", "}", "const", "object", "=", "{", "}", ";", "const", "keys", "=", "Object", ".", "getOwnPropertyNames", "(", "dynamoDBMap", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "{", "const", "key", "=", "keys", "[", "i", "]", ";", "object", "[", "key", "]", "=", "toValueFromAttributeValue", "(", "dynamoDBMap", "[", "key", "]", ")", ";", "}", "return", "object", ";", "}" ]
Attempts to convert the given DynamoDB map object containing keys and Attribute values into a JavaScript object. @param {Object} dynamoDBMap - a DynamoDB map object with keys and AttributeValue values @returns {Object} a JavaScript object
[ "Attempts", "to", "convert", "the", "given", "DynamoDB", "map", "object", "containing", "keys", "and", "Attribute", "values", "into", "a", "JavaScript", "object", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/dynamodb-utils.js#L38-L49
train
byron-dupreez/aws-core-utils
dynamodb-utils.js
toValueFromAttributeValue
function toValueFromAttributeValue(attributeValue) { if (!attributeValue || typeof attributeValue !== 'object') { return attributeValue; } const values = Object.getOwnPropertyNames(attributeValue).map(type => { return toValueFromAttributeTypeAndValue(type, attributeValue[type]) }); if (values.length !== 1) { throw new Error(`Found ${values.length} values on DynamoDB AttributeValue (${stringify(attributeValue)}), but expected only one!`); } return values[0]; }
javascript
function toValueFromAttributeValue(attributeValue) { if (!attributeValue || typeof attributeValue !== 'object') { return attributeValue; } const values = Object.getOwnPropertyNames(attributeValue).map(type => { return toValueFromAttributeTypeAndValue(type, attributeValue[type]) }); if (values.length !== 1) { throw new Error(`Found ${values.length} values on DynamoDB AttributeValue (${stringify(attributeValue)}), but expected only one!`); } return values[0]; }
[ "function", "toValueFromAttributeValue", "(", "attributeValue", ")", "{", "if", "(", "!", "attributeValue", "||", "typeof", "attributeValue", "!==", "'object'", ")", "{", "return", "attributeValue", ";", "}", "const", "values", "=", "Object", ".", "getOwnPropertyNames", "(", "attributeValue", ")", ".", "map", "(", "type", "=>", "{", "return", "toValueFromAttributeTypeAndValue", "(", "type", ",", "attributeValue", "[", "type", "]", ")", "}", ")", ";", "if", "(", "values", ".", "length", "!==", "1", ")", "{", "throw", "new", "Error", "(", "`", "${", "values", ".", "length", "}", "${", "stringify", "(", "attributeValue", ")", "}", "`", ")", ";", "}", "return", "values", "[", "0", "]", ";", "}" ]
Attempts to convert the given DynamoDB AttributeValue object into its equivalent JavaScript value. @param {Object} attributeValue - a DynamoDB AttributeValue object @returns {*} a JavaScript value
[ "Attempts", "to", "convert", "the", "given", "DynamoDB", "AttributeValue", "object", "into", "its", "equivalent", "JavaScript", "value", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/dynamodb-utils.js#L56-L67
train
byron-dupreez/aws-core-utils
dynamodb-utils.js
toValueFromAttributeTypeAndValue
function toValueFromAttributeTypeAndValue(attributeType, value) { switch (attributeType) { case 'S': return value; case 'N': return toNumberOrIntegerLike(value); case 'BOOL': return value === true || value === 'true'; case 'NULL': return null; case 'M': return toObjectFromDynamoDBMap(value); case 'L': return value.map(v => toValueFromAttributeValue(v)); case 'SS': return value; case 'NS': return value.map(v => toNumberOrIntegerLike(v)); case 'B': case 'BS': return value; default: throw new Error(`Unexpected DynamoDB attribute value type (${attributeType})`); } }
javascript
function toValueFromAttributeTypeAndValue(attributeType, value) { switch (attributeType) { case 'S': return value; case 'N': return toNumberOrIntegerLike(value); case 'BOOL': return value === true || value === 'true'; case 'NULL': return null; case 'M': return toObjectFromDynamoDBMap(value); case 'L': return value.map(v => toValueFromAttributeValue(v)); case 'SS': return value; case 'NS': return value.map(v => toNumberOrIntegerLike(v)); case 'B': case 'BS': return value; default: throw new Error(`Unexpected DynamoDB attribute value type (${attributeType})`); } }
[ "function", "toValueFromAttributeTypeAndValue", "(", "attributeType", ",", "value", ")", "{", "switch", "(", "attributeType", ")", "{", "case", "'S'", ":", "return", "value", ";", "case", "'N'", ":", "return", "toNumberOrIntegerLike", "(", "value", ")", ";", "case", "'BOOL'", ":", "return", "value", "===", "true", "||", "value", "===", "'true'", ";", "case", "'NULL'", ":", "return", "null", ";", "case", "'M'", ":", "return", "toObjectFromDynamoDBMap", "(", "value", ")", ";", "case", "'L'", ":", "return", "value", ".", "map", "(", "v", "=>", "toValueFromAttributeValue", "(", "v", ")", ")", ";", "case", "'SS'", ":", "return", "value", ";", "case", "'NS'", ":", "return", "value", ".", "map", "(", "v", "=>", "toNumberOrIntegerLike", "(", "v", ")", ")", ";", "case", "'B'", ":", "case", "'BS'", ":", "return", "value", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "attributeType", "}", "`", ")", ";", "}", "}" ]
Attempts to convert the given DynamoDB AttributeValue value into its original type based on the given DynamoDB AttributeValue type. @param {string} attributeType - a DynamoDB AttributeValue type @param {*} value - a DynamoDB AttributeValue value @returns {*} a JavaScript value
[ "Attempts", "to", "convert", "the", "given", "DynamoDB", "AttributeValue", "value", "into", "its", "original", "type", "based", "on", "the", "given", "DynamoDB", "AttributeValue", "type", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/dynamodb-utils.js#L76-L100
train
byron-dupreez/aws-core-utils
dynamodb-utils.js
toKeyValueStrings
function toKeyValueStrings(dynamoDBMap) { return dynamoDBMap && typeof dynamoDBMap === 'object' ? Object.getOwnPropertyNames(dynamoDBMap).map(key => `${key}:${stringify(toValueFromAttributeValue(dynamoDBMap[key]))}`) : []; }
javascript
function toKeyValueStrings(dynamoDBMap) { return dynamoDBMap && typeof dynamoDBMap === 'object' ? Object.getOwnPropertyNames(dynamoDBMap).map(key => `${key}:${stringify(toValueFromAttributeValue(dynamoDBMap[key]))}`) : []; }
[ "function", "toKeyValueStrings", "(", "dynamoDBMap", ")", "{", "return", "dynamoDBMap", "&&", "typeof", "dynamoDBMap", "===", "'object'", "?", "Object", ".", "getOwnPropertyNames", "(", "dynamoDBMap", ")", ".", "map", "(", "key", "=>", "`", "${", "key", "}", "${", "stringify", "(", "toValueFromAttributeValue", "(", "dynamoDBMap", "[", "key", "]", ")", ")", "}", "`", ")", ":", "[", "]", ";", "}" ]
Extracts an array of colon-separated key name and value strings from the given DynamoDB map object. @param {Object} dynamoDBMap - a DynamoDB map object @returns {string[]} an array of colon-separated key name and value strings
[ "Extracts", "an", "array", "of", "colon", "-", "separated", "key", "name", "and", "value", "strings", "from", "the", "given", "DynamoDB", "map", "object", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/dynamodb-utils.js#L107-L110
train
byron-dupreez/aws-core-utils
dynamodb-utils.js
toKeyValuePairs
function toKeyValuePairs(dynamoDBMap) { return dynamoDBMap && typeof dynamoDBMap === 'object' ? Object.getOwnPropertyNames(dynamoDBMap).map(key => [key, toValueFromAttributeValue(dynamoDBMap[key])]) : []; }
javascript
function toKeyValuePairs(dynamoDBMap) { return dynamoDBMap && typeof dynamoDBMap === 'object' ? Object.getOwnPropertyNames(dynamoDBMap).map(key => [key, toValueFromAttributeValue(dynamoDBMap[key])]) : []; }
[ "function", "toKeyValuePairs", "(", "dynamoDBMap", ")", "{", "return", "dynamoDBMap", "&&", "typeof", "dynamoDBMap", "===", "'object'", "?", "Object", ".", "getOwnPropertyNames", "(", "dynamoDBMap", ")", ".", "map", "(", "key", "=>", "[", "key", ",", "toValueFromAttributeValue", "(", "dynamoDBMap", "[", "key", "]", ")", "]", ")", ":", "[", "]", ";", "}" ]
Extracts an array of key value pairs from the given DynamoDB map object. Each key value pair is represented as an array containing a key property name followed by its associated value. @param {Object} dynamoDBMap - a DynamoDB map object @returns {KeyValuePair[]} an array of key value pairs
[ "Extracts", "an", "array", "of", "key", "value", "pairs", "from", "the", "given", "DynamoDB", "map", "object", ".", "Each", "key", "value", "pair", "is", "represented", "as", "an", "array", "containing", "a", "key", "property", "name", "followed", "by", "its", "associated", "value", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/dynamodb-utils.js#L118-L121
train
gegeyang0124/react-native-navigation-cus
src/views/CardStack/CardStackStyleInterpolator.js
forInitial
function forInitial(props) { const { navigation, scene } = props; const focused = navigation.state.index === scene.index; const opacity = focused ? 1 : 0; // If not focused, move the scene far away. const translate = focused ? 0 : 1000000; return { opacity, transform: [{ translateX: translate }, { translateY: translate }], }; }
javascript
function forInitial(props) { const { navigation, scene } = props; const focused = navigation.state.index === scene.index; const opacity = focused ? 1 : 0; // If not focused, move the scene far away. const translate = focused ? 0 : 1000000; return { opacity, transform: [{ translateX: translate }, { translateY: translate }], }; }
[ "function", "forInitial", "(", "props", ")", "{", "const", "{", "navigation", ",", "scene", "}", "=", "props", ";", "const", "focused", "=", "navigation", ".", "state", ".", "index", "===", "scene", ".", "index", ";", "const", "opacity", "=", "focused", "?", "1", ":", "0", ";", "const", "translate", "=", "focused", "?", "0", ":", "1000000", ";", "return", "{", "opacity", ",", "transform", ":", "[", "{", "translateX", ":", "translate", "}", ",", "{", "translateY", ":", "translate", "}", "]", ",", "}", ";", "}" ]
Utility that builds the style for the card in the cards stack. +------------+ +-+ | +-+ | | | | | | | | | Focused | | | | Card | | | | | +-+ | | +-+ | +------------+ Render the initial style when the initial layout isn't measured yet.
[ "Utility", "that", "builds", "the", "style", "for", "the", "card", "in", "the", "cards", "stack", "." ]
37bf130e0a459ed8f8671ebf87efcb425aaeb775
https://github.com/gegeyang0124/react-native-navigation-cus/blob/37bf130e0a459ed8f8671ebf87efcb425aaeb775/src/views/CardStack/CardStackStyleInterpolator.js#L22-L33
train
gegeyang0124/react-native-navigation-cus
src/views/CardStack/CardStackStyleInterpolator.js
forHorizontal
function forHorizontal(props) { const { layout, position, scene } = props; if (!layout.isMeasured) { return forInitial(props); } const interpolate = getSceneIndicesForInterpolationInputRange(props); if (!interpolate) return { opacity: 0 }; const { first, last } = interpolate; const index = scene.index; const opacity = position.interpolate({ inputRange: [first, first + 0.01, index, last - 0.01, last], outputRange: [0, 1, 1, 0.85, 0], }); const width = layout.initWidth; const translateX = position.interpolate({ inputRange: [first, index, last], outputRange: I18nManager.isRTL ? [-width, 0, width * 0.3] : [width, 0, width * -0.3], }); const translateY = 0; return { opacity, transform: [{ translateX }, { translateY }], }; }
javascript
function forHorizontal(props) { const { layout, position, scene } = props; if (!layout.isMeasured) { return forInitial(props); } const interpolate = getSceneIndicesForInterpolationInputRange(props); if (!interpolate) return { opacity: 0 }; const { first, last } = interpolate; const index = scene.index; const opacity = position.interpolate({ inputRange: [first, first + 0.01, index, last - 0.01, last], outputRange: [0, 1, 1, 0.85, 0], }); const width = layout.initWidth; const translateX = position.interpolate({ inputRange: [first, index, last], outputRange: I18nManager.isRTL ? [-width, 0, width * 0.3] : [width, 0, width * -0.3], }); const translateY = 0; return { opacity, transform: [{ translateX }, { translateY }], }; }
[ "function", "forHorizontal", "(", "props", ")", "{", "const", "{", "layout", ",", "position", ",", "scene", "}", "=", "props", ";", "if", "(", "!", "layout", ".", "isMeasured", ")", "{", "return", "forInitial", "(", "props", ")", ";", "}", "const", "interpolate", "=", "getSceneIndicesForInterpolationInputRange", "(", "props", ")", ";", "if", "(", "!", "interpolate", ")", "return", "{", "opacity", ":", "0", "}", ";", "const", "{", "first", ",", "last", "}", "=", "interpolate", ";", "const", "index", "=", "scene", ".", "index", ";", "const", "opacity", "=", "position", ".", "interpolate", "(", "{", "inputRange", ":", "[", "first", ",", "first", "+", "0.01", ",", "index", ",", "last", "-", "0.01", ",", "last", "]", ",", "outputRange", ":", "[", "0", ",", "1", ",", "1", ",", "0.85", ",", "0", "]", ",", "}", ")", ";", "const", "width", "=", "layout", ".", "initWidth", ";", "const", "translateX", "=", "position", ".", "interpolate", "(", "{", "inputRange", ":", "[", "first", ",", "index", ",", "last", "]", ",", "outputRange", ":", "I18nManager", ".", "isRTL", "?", "[", "-", "width", ",", "0", ",", "width", "*", "0.3", "]", ":", "[", "width", ",", "0", ",", "width", "*", "-", "0.3", "]", ",", "}", ")", ";", "const", "translateY", "=", "0", ";", "return", "{", "opacity", ",", "transform", ":", "[", "{", "translateX", "}", ",", "{", "translateY", "}", "]", ",", "}", ";", "}" ]
Standard iOS-style slide in from the right.
[ "Standard", "iOS", "-", "style", "slide", "in", "from", "the", "right", "." ]
37bf130e0a459ed8f8671ebf87efcb425aaeb775
https://github.com/gegeyang0124/react-native-navigation-cus/blob/37bf130e0a459ed8f8671ebf87efcb425aaeb775/src/views/CardStack/CardStackStyleInterpolator.js#L38-L68
train
gegeyang0124/react-native-navigation-cus
src/views/CardStack/CardStackStyleInterpolator.js
forFadeFromBottomAndroid
function forFadeFromBottomAndroid(props) { const { layout, position, scene } = props; if (!layout.isMeasured) { return forInitial(props); } const interpolate = getSceneIndicesForInterpolationInputRange(props); if (!interpolate) return { opacity: 0 }; const { first, last } = interpolate; const index = scene.index; const inputRange = [first, index, last - 0.01, last]; const opacity = position.interpolate({ inputRange, outputRange: [0, 1, 1, 0], }); const translateY = position.interpolate({ inputRange, outputRange: [50, 0, 0, 0], }); const translateX = 0; return { opacity, transform: [{ translateX }, { translateY }], }; }
javascript
function forFadeFromBottomAndroid(props) { const { layout, position, scene } = props; if (!layout.isMeasured) { return forInitial(props); } const interpolate = getSceneIndicesForInterpolationInputRange(props); if (!interpolate) return { opacity: 0 }; const { first, last } = interpolate; const index = scene.index; const inputRange = [first, index, last - 0.01, last]; const opacity = position.interpolate({ inputRange, outputRange: [0, 1, 1, 0], }); const translateY = position.interpolate({ inputRange, outputRange: [50, 0, 0, 0], }); const translateX = 0; return { opacity, transform: [{ translateX }, { translateY }], }; }
[ "function", "forFadeFromBottomAndroid", "(", "props", ")", "{", "const", "{", "layout", ",", "position", ",", "scene", "}", "=", "props", ";", "if", "(", "!", "layout", ".", "isMeasured", ")", "{", "return", "forInitial", "(", "props", ")", ";", "}", "const", "interpolate", "=", "getSceneIndicesForInterpolationInputRange", "(", "props", ")", ";", "if", "(", "!", "interpolate", ")", "return", "{", "opacity", ":", "0", "}", ";", "const", "{", "first", ",", "last", "}", "=", "interpolate", ";", "const", "index", "=", "scene", ".", "index", ";", "const", "inputRange", "=", "[", "first", ",", "index", ",", "last", "-", "0.01", ",", "last", "]", ";", "const", "opacity", "=", "position", ".", "interpolate", "(", "{", "inputRange", ",", "outputRange", ":", "[", "0", ",", "1", ",", "1", ",", "0", "]", ",", "}", ")", ";", "const", "translateY", "=", "position", ".", "interpolate", "(", "{", "inputRange", ",", "outputRange", ":", "[", "50", ",", "0", ",", "0", ",", "0", "]", ",", "}", ")", ";", "const", "translateX", "=", "0", ";", "return", "{", "opacity", ",", "transform", ":", "[", "{", "translateX", "}", ",", "{", "translateY", "}", "]", ",", "}", ";", "}" ]
Standard Android-style fade in from the bottom.
[ "Standard", "Android", "-", "style", "fade", "in", "from", "the", "bottom", "." ]
37bf130e0a459ed8f8671ebf87efcb425aaeb775
https://github.com/gegeyang0124/react-native-navigation-cus/blob/37bf130e0a459ed8f8671ebf87efcb425aaeb775/src/views/CardStack/CardStackStyleInterpolator.js#L106-L135
train
gegeyang0124/react-native-navigation-cus
src/views/CardStack/CardStackStyleInterpolator.js
forFade
function forFade(props) { const { layout, position, scene } = props; if (!layout.isMeasured) { return forInitial(props); } const interpolate = getSceneIndicesForInterpolationInputRange(props); if (!interpolate) return { opacity: 0 }; const { first, last } = interpolate; const index = scene.index; const opacity = position.interpolate({ inputRange: [first, index, last], outputRange: [0, 1, 1], }); return { opacity, }; }
javascript
function forFade(props) { const { layout, position, scene } = props; if (!layout.isMeasured) { return forInitial(props); } const interpolate = getSceneIndicesForInterpolationInputRange(props); if (!interpolate) return { opacity: 0 }; const { first, last } = interpolate; const index = scene.index; const opacity = position.interpolate({ inputRange: [first, index, last], outputRange: [0, 1, 1], }); return { opacity, }; }
[ "function", "forFade", "(", "props", ")", "{", "const", "{", "layout", ",", "position", ",", "scene", "}", "=", "props", ";", "if", "(", "!", "layout", ".", "isMeasured", ")", "{", "return", "forInitial", "(", "props", ")", ";", "}", "const", "interpolate", "=", "getSceneIndicesForInterpolationInputRange", "(", "props", ")", ";", "if", "(", "!", "interpolate", ")", "return", "{", "opacity", ":", "0", "}", ";", "const", "{", "first", ",", "last", "}", "=", "interpolate", ";", "const", "index", "=", "scene", ".", "index", ";", "const", "opacity", "=", "position", ".", "interpolate", "(", "{", "inputRange", ":", "[", "first", ",", "index", ",", "last", "]", ",", "outputRange", ":", "[", "0", ",", "1", ",", "1", "]", ",", "}", ")", ";", "return", "{", "opacity", ",", "}", ";", "}" ]
fadeIn and fadeOut
[ "fadeIn", "and", "fadeOut" ]
37bf130e0a459ed8f8671ebf87efcb425aaeb775
https://github.com/gegeyang0124/react-native-navigation-cus/blob/37bf130e0a459ed8f8671ebf87efcb425aaeb775/src/views/CardStack/CardStackStyleInterpolator.js#L140-L160
train
devfacet/iptocountry
app/index.js
loadAndServe
function loadAndServe() { ip2co.dbLoad(); ip2co.listenHTTP({hostname: appConfig.listenOpt.http.hostname, port: appConfig.listenOpt.http.port}); }
javascript
function loadAndServe() { ip2co.dbLoad(); ip2co.listenHTTP({hostname: appConfig.listenOpt.http.hostname, port: appConfig.listenOpt.http.port}); }
[ "function", "loadAndServe", "(", ")", "{", "ip2co", ".", "dbLoad", "(", ")", ";", "ip2co", ".", "listenHTTP", "(", "{", "hostname", ":", "appConfig", ".", "listenOpt", ".", "http", ".", "hostname", ",", "port", ":", "appConfig", ".", "listenOpt", ".", "http", ".", "port", "}", ")", ";", "}" ]
Loads the database and listen http requests.
[ "Loads", "the", "database", "and", "listen", "http", "requests", "." ]
e22081019cb579ddf1d200d857149374acabd01b
https://github.com/devfacet/iptocountry/blob/e22081019cb579ddf1d200d857149374acabd01b/app/index.js#L30-L33
train
amida-tech/blue-button-cms
lib/sections/claims.js
extrapolateDatesFromLines
function extrapolateDatesFromLines(claimLines, returnChildObj) { var lowTime; var highTime; var pointTime; if (returnChildObj.date_time) { if (returnChildObj.date_time.low) { lowTime = returnChildObj.date_time.low; } if (returnChildObj.date_time.high) { highTime = returnChildObj.date_time.high; } if (returnChildObj.date_time.point) { pointTime = returnChildObj.date_time.point; } } for (var x in claimLines) { if (typeof (claimLines[x]) === "function") { continue; } var claimLineObj = claimLines[x]; if (claimLineObj.date_time) { /*if the main claim body has undefined dates, populate it with claim lines date */ if (claimLineObj.date_time.low && lowTime === undefined) { lowTime = claimLineObj.date_time.low; } if (claimLineObj.date_time.high && highTime === undefined) { highTime = claimLineObj.date_time.high; } if (claimLineObj.date_time.point && pointTime === undefined) { pointTime = claimLineObj.date_time.point; } //if the claim lines are defined, then update them with better/more accurate information if (lowTime !== undefined && claimLineObj.date_time.low) { var lowDateTime = new Date(lowTime.date); var lineLowDateTime = new Date(claimLineObj.date_time.low.date); if (lineLowDateTime < lowDateTime) { lowTime = claimLineObj.date_time.low; } } if (highTime !== undefined && claimLineObj.date_time.high) { var highDateTime = new Date(highTime.date); var lineHighDateTime = new Date(claimLineObj.date_time.high.date); if (lineHighDateTime > highDateTime) { highTime = claimLineObj.date_time.high; } } //on the assumption that the most recent service date is most relevant if (pointTime !== undefined && claimLineObj.date_time.point) { var pointDateTime = new Date(pointTime.date); var linePointDateTime = new Date(claimLineObj.date_time.point.date); if (pointDateTime > pointDateTime) { pointTime = claimLineObj.date_time.point; } } } } //assign the newly discovered times to the main claims body object if (returnChildObj.date_time === undefined) { returnChildObj.date_time = {}; } if (lowTime) { returnChildObj.date_time.low = lowTime; } if (highTime) { returnChildObj.date_time.high = highTime; } if (pointTime) { returnChildObj.date_time.point = pointTime; } }
javascript
function extrapolateDatesFromLines(claimLines, returnChildObj) { var lowTime; var highTime; var pointTime; if (returnChildObj.date_time) { if (returnChildObj.date_time.low) { lowTime = returnChildObj.date_time.low; } if (returnChildObj.date_time.high) { highTime = returnChildObj.date_time.high; } if (returnChildObj.date_time.point) { pointTime = returnChildObj.date_time.point; } } for (var x in claimLines) { if (typeof (claimLines[x]) === "function") { continue; } var claimLineObj = claimLines[x]; if (claimLineObj.date_time) { /*if the main claim body has undefined dates, populate it with claim lines date */ if (claimLineObj.date_time.low && lowTime === undefined) { lowTime = claimLineObj.date_time.low; } if (claimLineObj.date_time.high && highTime === undefined) { highTime = claimLineObj.date_time.high; } if (claimLineObj.date_time.point && pointTime === undefined) { pointTime = claimLineObj.date_time.point; } //if the claim lines are defined, then update them with better/more accurate information if (lowTime !== undefined && claimLineObj.date_time.low) { var lowDateTime = new Date(lowTime.date); var lineLowDateTime = new Date(claimLineObj.date_time.low.date); if (lineLowDateTime < lowDateTime) { lowTime = claimLineObj.date_time.low; } } if (highTime !== undefined && claimLineObj.date_time.high) { var highDateTime = new Date(highTime.date); var lineHighDateTime = new Date(claimLineObj.date_time.high.date); if (lineHighDateTime > highDateTime) { highTime = claimLineObj.date_time.high; } } //on the assumption that the most recent service date is most relevant if (pointTime !== undefined && claimLineObj.date_time.point) { var pointDateTime = new Date(pointTime.date); var linePointDateTime = new Date(claimLineObj.date_time.point.date); if (pointDateTime > pointDateTime) { pointTime = claimLineObj.date_time.point; } } } } //assign the newly discovered times to the main claims body object if (returnChildObj.date_time === undefined) { returnChildObj.date_time = {}; } if (lowTime) { returnChildObj.date_time.low = lowTime; } if (highTime) { returnChildObj.date_time.high = highTime; } if (pointTime) { returnChildObj.date_time.point = pointTime; } }
[ "function", "extrapolateDatesFromLines", "(", "claimLines", ",", "returnChildObj", ")", "{", "var", "lowTime", ";", "var", "highTime", ";", "var", "pointTime", ";", "if", "(", "returnChildObj", ".", "date_time", ")", "{", "if", "(", "returnChildObj", ".", "date_time", ".", "low", ")", "{", "lowTime", "=", "returnChildObj", ".", "date_time", ".", "low", ";", "}", "if", "(", "returnChildObj", ".", "date_time", ".", "high", ")", "{", "highTime", "=", "returnChildObj", ".", "date_time", ".", "high", ";", "}", "if", "(", "returnChildObj", ".", "date_time", ".", "point", ")", "{", "pointTime", "=", "returnChildObj", ".", "date_time", ".", "point", ";", "}", "}", "for", "(", "var", "x", "in", "claimLines", ")", "{", "if", "(", "typeof", "(", "claimLines", "[", "x", "]", ")", "===", "\"function\"", ")", "{", "continue", ";", "}", "var", "claimLineObj", "=", "claimLines", "[", "x", "]", ";", "if", "(", "claimLineObj", ".", "date_time", ")", "{", "if", "(", "claimLineObj", ".", "date_time", ".", "low", "&&", "lowTime", "===", "undefined", ")", "{", "lowTime", "=", "claimLineObj", ".", "date_time", ".", "low", ";", "}", "if", "(", "claimLineObj", ".", "date_time", ".", "high", "&&", "highTime", "===", "undefined", ")", "{", "highTime", "=", "claimLineObj", ".", "date_time", ".", "high", ";", "}", "if", "(", "claimLineObj", ".", "date_time", ".", "point", "&&", "pointTime", "===", "undefined", ")", "{", "pointTime", "=", "claimLineObj", ".", "date_time", ".", "point", ";", "}", "if", "(", "lowTime", "!==", "undefined", "&&", "claimLineObj", ".", "date_time", ".", "low", ")", "{", "var", "lowDateTime", "=", "new", "Date", "(", "lowTime", ".", "date", ")", ";", "var", "lineLowDateTime", "=", "new", "Date", "(", "claimLineObj", ".", "date_time", ".", "low", ".", "date", ")", ";", "if", "(", "lineLowDateTime", "<", "lowDateTime", ")", "{", "lowTime", "=", "claimLineObj", ".", "date_time", ".", "low", ";", "}", "}", "if", "(", "highTime", "!==", "undefined", "&&", "claimLineObj", ".", "date_time", ".", "high", ")", "{", "var", "highDateTime", "=", "new", "Date", "(", "highTime", ".", "date", ")", ";", "var", "lineHighDateTime", "=", "new", "Date", "(", "claimLineObj", ".", "date_time", ".", "high", ".", "date", ")", ";", "if", "(", "lineHighDateTime", ">", "highDateTime", ")", "{", "highTime", "=", "claimLineObj", ".", "date_time", ".", "high", ";", "}", "}", "if", "(", "pointTime", "!==", "undefined", "&&", "claimLineObj", ".", "date_time", ".", "point", ")", "{", "var", "pointDateTime", "=", "new", "Date", "(", "pointTime", ".", "date", ")", ";", "var", "linePointDateTime", "=", "new", "Date", "(", "claimLineObj", ".", "date_time", ".", "point", ".", "date", ")", ";", "if", "(", "pointDateTime", ">", "pointDateTime", ")", "{", "pointTime", "=", "claimLineObj", ".", "date_time", ".", "point", ";", "}", "}", "}", "}", "if", "(", "returnChildObj", ".", "date_time", "===", "undefined", ")", "{", "returnChildObj", ".", "date_time", "=", "{", "}", ";", "}", "if", "(", "lowTime", ")", "{", "returnChildObj", ".", "date_time", ".", "low", "=", "lowTime", ";", "}", "if", "(", "highTime", ")", "{", "returnChildObj", ".", "date_time", ".", "high", "=", "highTime", ";", "}", "if", "(", "pointTime", ")", "{", "returnChildObj", ".", "date_time", ".", "point", "=", "pointTime", ";", "}", "}" ]
extrapolates main claim body dates from claim lines
[ "extrapolates", "main", "claim", "body", "dates", "from", "claim", "lines" ]
749b8cf071910b22f8176a9ed8fc3b05062e1aad
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/sections/claims.js#L25-L99
train
seancheung/kuconfig
lib/core.js
$var
function $var(params, fn, envs) { if (params == null) { return params; } if (typeof params === 'string') { if (envs && envs[params] !== undefined) { return envs[params]; } return; } if (Array.isArray(params) && params.length === 2) { const key = params[0]; if (typeof key === 'string') { const value = fn.$var(key, fn, envs); return value === undefined ? params[1] : value; } } throw new Error( '$var expects a string or an array with two elements of which the first one must be a string' ); }
javascript
function $var(params, fn, envs) { if (params == null) { return params; } if (typeof params === 'string') { if (envs && envs[params] !== undefined) { return envs[params]; } return; } if (Array.isArray(params) && params.length === 2) { const key = params[0]; if (typeof key === 'string') { const value = fn.$var(key, fn, envs); return value === undefined ? params[1] : value; } } throw new Error( '$var expects a string or an array with two elements of which the first one must be a string' ); }
[ "function", "$var", "(", "params", ",", "fn", ",", "envs", ")", "{", "if", "(", "params", "==", "null", ")", "{", "return", "params", ";", "}", "if", "(", "typeof", "params", "===", "'string'", ")", "{", "if", "(", "envs", "&&", "envs", "[", "params", "]", "!==", "undefined", ")", "{", "return", "envs", "[", "params", "]", ";", "}", "return", ";", "}", "if", "(", "Array", ".", "isArray", "(", "params", ")", "&&", "params", ".", "length", "===", "2", ")", "{", "const", "key", "=", "params", "[", "0", "]", ";", "if", "(", "typeof", "key", "===", "'string'", ")", "{", "const", "value", "=", "fn", ".", "$var", "(", "key", ",", "fn", ",", "envs", ")", ";", "return", "value", "===", "undefined", "?", "params", "[", "1", "]", ":", "value", ";", "}", "}", "throw", "new", "Error", "(", "'$var expects a string or an array with two elements of which the first one must be a string'", ")", ";", "}" ]
Get value from envs with an optional fallback value @param {string|[string, any]} params @returns {any}
[ "Get", "value", "from", "envs", "with", "an", "optional", "fallback", "value" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/core.js#L40-L62
train
seancheung/kuconfig
lib/core.js
$path
function $path(params) { if (params == null) { return params; } if (typeof params === 'string') { const path = require('path'); if (path.isAbsolute(params)) { return params; } return path.resolve(process.cwd(), params); } throw new Error('$path expects a string'); }
javascript
function $path(params) { if (params == null) { return params; } if (typeof params === 'string') { const path = require('path'); if (path.isAbsolute(params)) { return params; } return path.resolve(process.cwd(), params); } throw new Error('$path expects a string'); }
[ "function", "$path", "(", "params", ")", "{", "if", "(", "params", "==", "null", ")", "{", "return", "params", ";", "}", "if", "(", "typeof", "params", "===", "'string'", ")", "{", "const", "path", "=", "require", "(", "'path'", ")", ";", "if", "(", "path", ".", "isAbsolute", "(", "params", ")", ")", "{", "return", "params", ";", "}", "return", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "params", ")", ";", "}", "throw", "new", "Error", "(", "'$path expects a string'", ")", ";", "}" ]
Resolve the path to absolute from current working directory @param {string} params @returns {string}
[ "Resolve", "the", "path", "to", "absolute", "from", "current", "working", "directory" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/core.js#L70-L83
train
seancheung/kuconfig
lib/core.js
$file
function $file(params, fn) { if (params == null) { return params; } let file, encoding; if (typeof params === 'string') { file = params; } else if (Array.isArray(params) && params.length === 2) { file = params[0]; encoding = params[1]; } if ( typeof file === 'string' && (encoding === undefined || typeof encoding === 'string') ) { file = fn.$path(file); const fs = require('fs'); if (fs.existsSync(file) && fs.lstatSync(file).isFile()) { return fs.readFileSync(file, { encoding }); } } throw new Error( '$file expects a string or an array with two string elements' ); }
javascript
function $file(params, fn) { if (params == null) { return params; } let file, encoding; if (typeof params === 'string') { file = params; } else if (Array.isArray(params) && params.length === 2) { file = params[0]; encoding = params[1]; } if ( typeof file === 'string' && (encoding === undefined || typeof encoding === 'string') ) { file = fn.$path(file); const fs = require('fs'); if (fs.existsSync(file) && fs.lstatSync(file).isFile()) { return fs.readFileSync(file, { encoding }); } } throw new Error( '$file expects a string or an array with two string elements' ); }
[ "function", "$file", "(", "params", ",", "fn", ")", "{", "if", "(", "params", "==", "null", ")", "{", "return", "params", ";", "}", "let", "file", ",", "encoding", ";", "if", "(", "typeof", "params", "===", "'string'", ")", "{", "file", "=", "params", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "params", ")", "&&", "params", ".", "length", "===", "2", ")", "{", "file", "=", "params", "[", "0", "]", ";", "encoding", "=", "params", "[", "1", "]", ";", "}", "if", "(", "typeof", "file", "===", "'string'", "&&", "(", "encoding", "===", "undefined", "||", "typeof", "encoding", "===", "'string'", ")", ")", "{", "file", "=", "fn", ".", "$path", "(", "file", ")", ";", "const", "fs", "=", "require", "(", "'fs'", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "file", ")", "&&", "fs", ".", "lstatSync", "(", "file", ")", ".", "isFile", "(", ")", ")", "{", "return", "fs", ".", "readFileSync", "(", "file", ",", "{", "encoding", "}", ")", ";", "}", "}", "throw", "new", "Error", "(", "'$file expects a string or an array with two string elements'", ")", ";", "}" ]
Resolve the path and read the file with an optional encoding @param {string|[string, string]} params @returns {string|Buffer}
[ "Resolve", "the", "path", "and", "read", "the", "file", "with", "an", "optional", "encoding" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/core.js#L91-L115
train
seancheung/kuconfig
lib/core.js
$number
function $number(params) { if (params == null) { return params; } if (typeof params === 'number') { return params; } if (typeof params === 'string') { return Number(params); } throw new Error('$number expects a number or string'); }
javascript
function $number(params) { if (params == null) { return params; } if (typeof params === 'number') { return params; } if (typeof params === 'string') { return Number(params); } throw new Error('$number expects a number or string'); }
[ "function", "$number", "(", "params", ")", "{", "if", "(", "params", "==", "null", ")", "{", "return", "params", ";", "}", "if", "(", "typeof", "params", "===", "'number'", ")", "{", "return", "params", ";", "}", "if", "(", "typeof", "params", "===", "'string'", ")", "{", "return", "Number", "(", "params", ")", ";", "}", "throw", "new", "Error", "(", "'$number expects a number or string'", ")", ";", "}" ]
Parse the given string into a number @param {string} params @returns {number}
[ "Parse", "the", "given", "string", "into", "a", "number" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/core.js#L139-L150
train
mongodb-js/index-model
lib/collection.js
function(db, namespace) { var collection = this; collection.trigger('request', collection); fetch(db, namespace, function(err, res) { if (err) { throw err; } collection.reset(res, {parse: true}); collection.trigger('sync', collection); }); return collection; }
javascript
function(db, namespace) { var collection = this; collection.trigger('request', collection); fetch(db, namespace, function(err, res) { if (err) { throw err; } collection.reset(res, {parse: true}); collection.trigger('sync', collection); }); return collection; }
[ "function", "(", "db", ",", "namespace", ")", "{", "var", "collection", "=", "this", ";", "collection", ".", "trigger", "(", "'request'", ",", "collection", ")", ";", "fetch", "(", "db", ",", "namespace", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "collection", ".", "reset", "(", "res", ",", "{", "parse", ":", "true", "}", ")", ";", "collection", ".", "trigger", "(", "'sync'", ",", "collection", ")", ";", "}", ")", ";", "return", "collection", ";", "}" ]
queries a MongoDB instance for index details and populates IndexCollection with the indexes in `namespace`. @param {MongoClient} db MongoDB driver db handle @param {String} namespace namespace to get indexes from, e.g. `test.foo` @return {IndexCollection} collection of indexes on `namespace`
[ "queries", "a", "MongoDB", "instance", "for", "index", "details", "and", "populates", "IndexCollection", "with", "the", "indexes", "in", "namespace", "." ]
43c878440e79299ee104b36d55c06aff63d8cf63
https://github.com/mongodb-js/index-model/blob/43c878440e79299ee104b36d55c06aff63d8cf63/lib/collection.js#L17-L28
train
warehouseai/bffs
index.js
BFFS
function BFFS(options) { if (!this) return new BFFS(options); options = this.init(options); var store = options.store; var prefix = options.prefix; var env = options.env; var cdn = options.cdn; // // We keep the running status of builds in redis. // this.store = store; // // Everything else we store in Cassandra. // this.datastar = options.datastar; this.models = options.models; this.log = options.log; this.prefix = prefix; this.envs = env; this.cdns = this.cdnify(cdn); this.limit = options.limit; // // Always fetch by locale so we default our locale property if it does not // exist. // this.defaultLocale = 'en-US'; }
javascript
function BFFS(options) { if (!this) return new BFFS(options); options = this.init(options); var store = options.store; var prefix = options.prefix; var env = options.env; var cdn = options.cdn; // // We keep the running status of builds in redis. // this.store = store; // // Everything else we store in Cassandra. // this.datastar = options.datastar; this.models = options.models; this.log = options.log; this.prefix = prefix; this.envs = env; this.cdns = this.cdnify(cdn); this.limit = options.limit; // // Always fetch by locale so we default our locale property if it does not // exist. // this.defaultLocale = 'en-US'; }
[ "function", "BFFS", "(", "options", ")", "{", "if", "(", "!", "this", ")", "return", "new", "BFFS", "(", "options", ")", ";", "options", "=", "this", ".", "init", "(", "options", ")", ";", "var", "store", "=", "options", ".", "store", ";", "var", "prefix", "=", "options", ".", "prefix", ";", "var", "env", "=", "options", ".", "env", ";", "var", "cdn", "=", "options", ".", "cdn", ";", "this", ".", "store", "=", "store", ";", "this", ".", "datastar", "=", "options", ".", "datastar", ";", "this", ".", "models", "=", "options", ".", "models", ";", "this", ".", "log", "=", "options", ".", "log", ";", "this", ".", "prefix", "=", "prefix", ";", "this", ".", "envs", "=", "env", ";", "this", ".", "cdns", "=", "this", ".", "cdnify", "(", "cdn", ")", ";", "this", ".", "limit", "=", "options", ".", "limit", ";", "this", ".", "defaultLocale", "=", "'en-US'", ";", "}" ]
Build Files Finder, BFFS <3 Options: - store: Dynamis configuration. - env: Allowed environment variables. - cdn: Configuration for the CDN. @constructor @param {Object} options Configuration. @api private
[ "Build", "Files", "Finder", "BFFS", "<3" ]
ca66a82dbac05ba51338987cc90aa5b0bb49d188
https://github.com/warehouseai/bffs/blob/ca66a82dbac05ba51338987cc90aa5b0bb49d188/index.js#L31-L63
train