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
warehouseai/bffs
index.js
compileEntity
function compileEntity() { var entity = extend({ buildId: bff.key(payload), extension: file.extension, filename: file.filename, fingerprint: print, url: file.url }, payload); return entity; }
javascript
function compileEntity() { var entity = extend({ buildId: bff.key(payload), extension: file.extension, filename: file.filename, fingerprint: print, url: file.url }, payload); return entity; }
[ "function", "compileEntity", "(", ")", "{", "var", "entity", "=", "extend", "(", "{", "buildId", ":", "bff", ".", "key", "(", "payload", ")", ",", "extension", ":", "file", ".", "extension", ",", "filename", ":", "file", ".", "filename", ",", "fingerprint", ":", "print", ",", "url", ":", "file", ".", "url", "}", ",", "payload", ")", ";", "return", "entity", ";", "}" ]
Compile the entity based on parameters
[ "Compile", "the", "entity", "based", "on", "parameters" ]
ca66a82dbac05ba51338987cc90aa5b0bb49d188
https://github.com/warehouseai/bffs/blob/ca66a82dbac05ba51338987cc90aa5b0bb49d188/index.js#L402-L412
train
JamesEggers1/node-ABAValidator
bin/client-install.js
function(){ _prompt.question("You entered '" + _destination + "'. Is this correct? (Y/N)\n", function(input){ var response = input.trim().toLowerCase(); evaluateConfirmation(response); }); }
javascript
function(){ _prompt.question("You entered '" + _destination + "'. Is this correct? (Y/N)\n", function(input){ var response = input.trim().toLowerCase(); evaluateConfirmation(response); }); }
[ "function", "(", ")", "{", "_prompt", ".", "question", "(", "\"You entered '\"", "+", "_destination", "+", "\"'. Is this correct? (Y/N)\\n\"", ",", "\\n", ")", ";", "}" ]
Prompts the user to confirm in a destination directory previously typed in. @private
[ "Prompts", "the", "user", "to", "confirm", "in", "a", "destination", "directory", "previously", "typed", "in", "." ]
13cfc08c7160b809799a187f3909768816b9c16c
https://github.com/JamesEggers1/node-ABAValidator/blob/13cfc08c7160b809799a187f3909768816b9c16c/bin/client-install.js#L28-L33
train
JamesEggers1/node-ABAValidator
bin/client-install.js
function(){ console.log("Unknown Response"); if (_pathConfirmationCounter < 3){ console.log("Please enter a 'Y' or an 'N' when answering.\n"); _pathConfirmationCounter++; confirmDestination(); } else { console.log("Unable to install at this time due to too many unknown responses.\n"); _prompt.close(); } }
javascript
function(){ console.log("Unknown Response"); if (_pathConfirmationCounter < 3){ console.log("Please enter a 'Y' or an 'N' when answering.\n"); _pathConfirmationCounter++; confirmDestination(); } else { console.log("Unable to install at this time due to too many unknown responses.\n"); _prompt.close(); } }
[ "function", "(", ")", "{", "console", ".", "log", "(", "\"Unknown Response\"", ")", ";", "if", "(", "_pathConfirmationCounter", "<", "3", ")", "{", "console", ".", "log", "(", "\"Please enter a 'Y' or an 'N' when answering.\\n\"", ")", ";", "\\n", "_pathConfirmationCounter", "++", ";", "}", "else", "confirmDestination", "(", ")", ";", "}" ]
Informs the user that their response was unknown and will reprompt if not encountered more than 3 times. @private
[ "Informs", "the", "user", "that", "their", "response", "was", "unknown", "and", "will", "reprompt", "if", "not", "encountered", "more", "than", "3", "times", "." ]
13cfc08c7160b809799a187f3909768816b9c16c
https://github.com/JamesEggers1/node-ABAValidator/blob/13cfc08c7160b809799a187f3909768816b9c16c/bin/client-install.js#L39-L50
train
JamesEggers1/node-ABAValidator
bin/client-install.js
function(){ if (destinationIsRelative){ _destination = _path.join(process.cwd(), "../..", _destination); } if(!_fs.existsSync(_destination)){ _fs.mkdirSync(_destination); } var destinationPath = _path.join(_destination, "/" + SCRIPT_NAME); var sourcePath = _path.resolve(_path.dirname(module.filename), "../src/" + SCRIPT_NAME); var source = _fs.createReadStream(sourcePath); var dest = _fs.createWriteStream(destinationPath); dest.pipe(source); console.log("Client Installation Complete!\n"); console.log(SCRIPT_NAME + " has been installed at: " + destinationPath); _prompt.close(); }
javascript
function(){ if (destinationIsRelative){ _destination = _path.join(process.cwd(), "../..", _destination); } if(!_fs.existsSync(_destination)){ _fs.mkdirSync(_destination); } var destinationPath = _path.join(_destination, "/" + SCRIPT_NAME); var sourcePath = _path.resolve(_path.dirname(module.filename), "../src/" + SCRIPT_NAME); var source = _fs.createReadStream(sourcePath); var dest = _fs.createWriteStream(destinationPath); dest.pipe(source); console.log("Client Installation Complete!\n"); console.log(SCRIPT_NAME + " has been installed at: " + destinationPath); _prompt.close(); }
[ "function", "(", ")", "{", "if", "(", "destinationIsRelative", ")", "{", "_destination", "=", "_path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "\"../..\"", ",", "_destination", ")", ";", "}", "if", "(", "!", "_fs", ".", "existsSync", "(", "_destination", ")", ")", "{", "_fs", ".", "mkdirSync", "(", "_destination", ")", ";", "}", "var", "destinationPath", "=", "_path", ".", "join", "(", "_destination", ",", "\"/\"", "+", "SCRIPT_NAME", ")", ";", "var", "sourcePath", "=", "_path", ".", "resolve", "(", "_path", ".", "dirname", "(", "module", ".", "filename", ")", ",", "\"../src/\"", "+", "SCRIPT_NAME", ")", ";", "var", "source", "=", "_fs", ".", "createReadStream", "(", "sourcePath", ")", ";", "var", "dest", "=", "_fs", ".", "createWriteStream", "(", "destinationPath", ")", ";", "dest", ".", "pipe", "(", "source", ")", ";", "console", ".", "log", "(", "\"Client Installation Complete!\\n\"", ")", ";", "\\n", "console", ".", "log", "(", "SCRIPT_NAME", "+", "\" has been installed at: \"", "+", "destinationPath", ")", ";", "}" ]
Copies the client-side script to the provided destination directory @private
[ "Copies", "the", "client", "-", "side", "script", "to", "the", "provided", "destination", "directory" ]
13cfc08c7160b809799a187f3909768816b9c16c
https://github.com/JamesEggers1/node-ABAValidator/blob/13cfc08c7160b809799a187f3909768816b9c16c/bin/client-install.js#L82-L100
train
ibm-watson-data-lab/--deprecated--pipes-sdk
lib/run/pipeRunStep.js
pipeRunStep
function pipeRunStep(){ //Public APIs /** * run: run this step * Should be implemented by subclasses */ this.run = function( callback ){ throw new Error("Called run method from abstract pipeRunStep class"); } this.getLabel = function(){ return this.label || "Unknown label"; } this.getPipe = function(){ return (this.pipeRunStats && this.pipeRunStats.getPipe()) || null; } this.getPipeRunner = function(){ return this.pipeRunner || null; } this.setStepMessage = function(message){ this.stats.message = message; this.pipeRunStats.broadcastRunEvent(); } this.setPercentCompletion = function( percent ){ this.stats.percent = percent; } this.beginStep = function( pipeRunner, pipeRunStats ){ pipeRunStats.logger.info( "Step %s started", this.getLabel() ); //Reference to the main stats object this.pipeRunStats = pipeRunStats; this.pipeRunner = pipeRunner; pipeRunStats.setMessage( this.label ); //Record the start time this.stats.startTime = moment(); this.stats.status = "RUNNING"; this.setPercentCompletion(0); this.pipeRunStats.save(); } this.endStep = function(callback, err){ //Set the end time and elapsed time this.stats.endTime = moment(); this.stats.elapsedTime = moment.duration( this.stats.endTime.diff( this.stats.startTime ) ).humanize(); this.stats.status = err ? "ERROR" : "FINISHED"; if ( err ){ this.setStepMessage( err ); } this.setPercentCompletion(100); this.pipeRunStats.save( callback, err ); this.pipeRunStats.logger.info({ message: require('util').format("Step %s completed", this.getLabel() ), stats: this.stats }); } /** * toJSON serialization function */ this.toJSON = function(){ return { label: this.getLabel() } } }
javascript
function pipeRunStep(){ //Public APIs /** * run: run this step * Should be implemented by subclasses */ this.run = function( callback ){ throw new Error("Called run method from abstract pipeRunStep class"); } this.getLabel = function(){ return this.label || "Unknown label"; } this.getPipe = function(){ return (this.pipeRunStats && this.pipeRunStats.getPipe()) || null; } this.getPipeRunner = function(){ return this.pipeRunner || null; } this.setStepMessage = function(message){ this.stats.message = message; this.pipeRunStats.broadcastRunEvent(); } this.setPercentCompletion = function( percent ){ this.stats.percent = percent; } this.beginStep = function( pipeRunner, pipeRunStats ){ pipeRunStats.logger.info( "Step %s started", this.getLabel() ); //Reference to the main stats object this.pipeRunStats = pipeRunStats; this.pipeRunner = pipeRunner; pipeRunStats.setMessage( this.label ); //Record the start time this.stats.startTime = moment(); this.stats.status = "RUNNING"; this.setPercentCompletion(0); this.pipeRunStats.save(); } this.endStep = function(callback, err){ //Set the end time and elapsed time this.stats.endTime = moment(); this.stats.elapsedTime = moment.duration( this.stats.endTime.diff( this.stats.startTime ) ).humanize(); this.stats.status = err ? "ERROR" : "FINISHED"; if ( err ){ this.setStepMessage( err ); } this.setPercentCompletion(100); this.pipeRunStats.save( callback, err ); this.pipeRunStats.logger.info({ message: require('util').format("Step %s completed", this.getLabel() ), stats: this.stats }); } /** * toJSON serialization function */ this.toJSON = function(){ return { label: this.getLabel() } } }
[ "function", "pipeRunStep", "(", ")", "{", "this", ".", "run", "=", "function", "(", "callback", ")", "{", "throw", "new", "Error", "(", "\"Called run method from abstract pipeRunStep class\"", ")", ";", "}", "this", ".", "getLabel", "=", "function", "(", ")", "{", "return", "this", ".", "label", "||", "\"Unknown label\"", ";", "}", "this", ".", "getPipe", "=", "function", "(", ")", "{", "return", "(", "this", ".", "pipeRunStats", "&&", "this", ".", "pipeRunStats", ".", "getPipe", "(", ")", ")", "||", "null", ";", "}", "this", ".", "getPipeRunner", "=", "function", "(", ")", "{", "return", "this", ".", "pipeRunner", "||", "null", ";", "}", "this", ".", "setStepMessage", "=", "function", "(", "message", ")", "{", "this", ".", "stats", ".", "message", "=", "message", ";", "this", ".", "pipeRunStats", ".", "broadcastRunEvent", "(", ")", ";", "}", "this", ".", "setPercentCompletion", "=", "function", "(", "percent", ")", "{", "this", ".", "stats", ".", "percent", "=", "percent", ";", "}", "this", ".", "beginStep", "=", "function", "(", "pipeRunner", ",", "pipeRunStats", ")", "{", "pipeRunStats", ".", "logger", ".", "info", "(", "\"Step %s started\"", ",", "this", ".", "getLabel", "(", ")", ")", ";", "this", ".", "pipeRunStats", "=", "pipeRunStats", ";", "this", ".", "pipeRunner", "=", "pipeRunner", ";", "pipeRunStats", ".", "setMessage", "(", "this", ".", "label", ")", ";", "this", ".", "stats", ".", "startTime", "=", "moment", "(", ")", ";", "this", ".", "stats", ".", "status", "=", "\"RUNNING\"", ";", "this", ".", "setPercentCompletion", "(", "0", ")", ";", "this", ".", "pipeRunStats", ".", "save", "(", ")", ";", "}", "this", ".", "endStep", "=", "function", "(", "callback", ",", "err", ")", "{", "this", ".", "stats", ".", "endTime", "=", "moment", "(", ")", ";", "this", ".", "stats", ".", "elapsedTime", "=", "moment", ".", "duration", "(", "this", ".", "stats", ".", "endTime", ".", "diff", "(", "this", ".", "stats", ".", "startTime", ")", ")", ".", "humanize", "(", ")", ";", "this", ".", "stats", ".", "status", "=", "err", "?", "\"ERROR\"", ":", "\"FINISHED\"", ";", "if", "(", "err", ")", "{", "this", ".", "setStepMessage", "(", "err", ")", ";", "}", "this", ".", "setPercentCompletion", "(", "100", ")", ";", "this", ".", "pipeRunStats", ".", "save", "(", "callback", ",", "err", ")", ";", "this", ".", "pipeRunStats", ".", "logger", ".", "info", "(", "{", "message", ":", "require", "(", "'util'", ")", ".", "format", "(", "\"Step %s completed\"", ",", "this", ".", "getLabel", "(", ")", ")", ",", "stats", ":", "this", ".", "stats", "}", ")", ";", "}", "this", ".", "toJSON", "=", "function", "(", ")", "{", "return", "{", "label", ":", "this", ".", "getLabel", "(", ")", "}", "}", "}" ]
PipeRunStep class Abstract Base class for all run steps
[ "PipeRunStep", "class", "Abstract", "Base", "class", "for", "all", "run", "steps" ]
b5cbf238d8d2c6a852f1712eed7dcfabeebfdb25
https://github.com/ibm-watson-data-lab/--deprecated--pipes-sdk/blob/b5cbf238d8d2c6a852f1712eed7dcfabeebfdb25/lib/run/pipeRunStep.js#L14-L88
train
node-modules/antpb
lib/converter.js
genValuePartial_fromObject
function genValuePartial_fromObject(gen, field, fieldIndex, prop) { if (field.resolvedType) { if (field.resolvedType instanceof Enum) { gen('switch(d%s){', prop); for (let values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) { if (field.repeated && values[keys[i]] === field.typeDefault) gen('default:'); gen('case%j:', keys[i])('case %i:', values[keys[i]])('m%s=%j', prop, values[keys[i]])('break'); } gen('}'); } else { gen('if(typeof d%s!=="object")', prop)('throw TypeError(%j)', field.fullName + ': object expected')('m%s=types[%i].fromObject(d%s)', prop, fieldIndex, prop); } } else { let isUnsigned = false; switch (field.type) { case 'double': case 'float': gen('m%s=Number(d%s)', prop, prop); // also catches "NaN", "Infinity" break; case 'uint32': case 'fixed32': gen('m%s=d%s>>>0', prop, prop); break; case 'int32': case 'sint32': case 'sfixed32': gen('m%s=d%s|0', prop, prop); break; case 'uint64': isUnsigned = true; // eslint-disable-line no-fallthrough case 'int64': case 'sint64': case 'fixed64': case 'sfixed64': gen('if(util.Long)')('(m%s=util.Long.fromValue(d%s)).unsigned=%j', prop, prop, isUnsigned)('else if(typeof d%s==="string")', prop)('m%s=parseInt(d%s,10)', prop, prop)('else if(typeof d%s==="number")', prop)('m%s=d%s', prop, prop)('else if(typeof d%s==="object")', prop)('m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)', prop, prop, prop, isUnsigned ? 'true' : ''); break; case 'bytes': gen('if(typeof d%s==="string")', prop)('util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)', prop, prop, prop)('else if(d%s.length)', prop)('m%s=d%s', prop, prop); break; case 'string': gen('m%s=String(d%s)', prop, prop); break; case 'bool': gen('m%s=Boolean(d%s)', prop, prop); break; default: break; /* default: gen ("m%s=d%s", prop, prop); break; */ } } return gen; }
javascript
function genValuePartial_fromObject(gen, field, fieldIndex, prop) { if (field.resolvedType) { if (field.resolvedType instanceof Enum) { gen('switch(d%s){', prop); for (let values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) { if (field.repeated && values[keys[i]] === field.typeDefault) gen('default:'); gen('case%j:', keys[i])('case %i:', values[keys[i]])('m%s=%j', prop, values[keys[i]])('break'); } gen('}'); } else { gen('if(typeof d%s!=="object")', prop)('throw TypeError(%j)', field.fullName + ': object expected')('m%s=types[%i].fromObject(d%s)', prop, fieldIndex, prop); } } else { let isUnsigned = false; switch (field.type) { case 'double': case 'float': gen('m%s=Number(d%s)', prop, prop); // also catches "NaN", "Infinity" break; case 'uint32': case 'fixed32': gen('m%s=d%s>>>0', prop, prop); break; case 'int32': case 'sint32': case 'sfixed32': gen('m%s=d%s|0', prop, prop); break; case 'uint64': isUnsigned = true; // eslint-disable-line no-fallthrough case 'int64': case 'sint64': case 'fixed64': case 'sfixed64': gen('if(util.Long)')('(m%s=util.Long.fromValue(d%s)).unsigned=%j', prop, prop, isUnsigned)('else if(typeof d%s==="string")', prop)('m%s=parseInt(d%s,10)', prop, prop)('else if(typeof d%s==="number")', prop)('m%s=d%s', prop, prop)('else if(typeof d%s==="object")', prop)('m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)', prop, prop, prop, isUnsigned ? 'true' : ''); break; case 'bytes': gen('if(typeof d%s==="string")', prop)('util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)', prop, prop, prop)('else if(d%s.length)', prop)('m%s=d%s', prop, prop); break; case 'string': gen('m%s=String(d%s)', prop, prop); break; case 'bool': gen('m%s=Boolean(d%s)', prop, prop); break; default: break; /* default: gen ("m%s=d%s", prop, prop); break; */ } } return gen; }
[ "function", "genValuePartial_fromObject", "(", "gen", ",", "field", ",", "fieldIndex", ",", "prop", ")", "{", "if", "(", "field", ".", "resolvedType", ")", "{", "if", "(", "field", ".", "resolvedType", "instanceof", "Enum", ")", "{", "gen", "(", "'switch(d%s){'", ",", "prop", ")", ";", "for", "(", "let", "values", "=", "field", ".", "resolvedType", ".", "values", ",", "keys", "=", "Object", ".", "keys", "(", "values", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "{", "if", "(", "field", ".", "repeated", "&&", "values", "[", "keys", "[", "i", "]", "]", "===", "field", ".", "typeDefault", ")", "gen", "(", "'default:'", ")", ";", "gen", "(", "'case%j:'", ",", "keys", "[", "i", "]", ")", "(", "'case %i:'", ",", "values", "[", "keys", "[", "i", "]", "]", ")", "(", "'m%s=%j'", ",", "prop", ",", "values", "[", "keys", "[", "i", "]", "]", ")", "(", "'break'", ")", ";", "}", "gen", "(", "'}'", ")", ";", "}", "else", "{", "gen", "(", "'if(typeof d%s!==\"object\")'", ",", "prop", ")", "(", "'throw TypeError(%j)'", ",", "field", ".", "fullName", "+", "': object expected'", ")", "(", "'m%s=types[%i].fromObject(d%s)'", ",", "prop", ",", "fieldIndex", ",", "prop", ")", ";", "}", "}", "else", "{", "let", "isUnsigned", "=", "false", ";", "switch", "(", "field", ".", "type", ")", "{", "case", "'double'", ":", "case", "'float'", ":", "gen", "(", "'m%s=Number(d%s)'", ",", "prop", ",", "prop", ")", ";", "break", ";", "case", "'uint32'", ":", "case", "'fixed32'", ":", "gen", "(", "'m%s=d%s>>>0'", ",", "prop", ",", "prop", ")", ";", "break", ";", "case", "'int32'", ":", "case", "'sint32'", ":", "case", "'sfixed32'", ":", "gen", "(", "'m%s=d%s|0'", ",", "prop", ",", "prop", ")", ";", "break", ";", "case", "'uint64'", ":", "isUnsigned", "=", "true", ";", "case", "'int64'", ":", "case", "'sint64'", ":", "case", "'fixed64'", ":", "case", "'sfixed64'", ":", "gen", "(", "'if(util.Long)'", ")", "(", "'(m%s=util.Long.fromValue(d%s)).unsigned=%j'", ",", "prop", ",", "prop", ",", "isUnsigned", ")", "(", "'else if(typeof d%s===\"string\")'", ",", "prop", ")", "(", "'m%s=parseInt(d%s,10)'", ",", "prop", ",", "prop", ")", "(", "'else if(typeof d%s===\"number\")'", ",", "prop", ")", "(", "'m%s=d%s'", ",", "prop", ",", "prop", ")", "(", "'else if(typeof d%s===\"object\")'", ",", "prop", ")", "(", "'m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)'", ",", "prop", ",", "prop", ",", "prop", ",", "isUnsigned", "?", "'true'", ":", "''", ")", ";", "break", ";", "case", "'bytes'", ":", "gen", "(", "'if(typeof d%s===\"string\")'", ",", "prop", ")", "(", "'util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)'", ",", "prop", ",", "prop", ",", "prop", ")", "(", "'else if(d%s.length)'", ",", "prop", ")", "(", "'m%s=d%s'", ",", "prop", ",", "prop", ")", ";", "break", ";", "case", "'string'", ":", "gen", "(", "'m%s=String(d%s)'", ",", "prop", ",", "prop", ")", ";", "break", ";", "case", "'bool'", ":", "gen", "(", "'m%s=Boolean(d%s)'", ",", "prop", ",", "prop", ")", ";", "break", ";", "default", ":", "break", ";", "}", "}", "return", "gen", ";", "}" ]
Generates a partial value fromObject conveter. @param {Codegen} gen Codegen instance @param {Field} field Reflected field @param {number} fieldIndex Field index @param {string} prop Property reference @return {Codegen} Codegen instance @ignore
[ "Generates", "a", "partial", "value", "fromObject", "conveter", "." ]
e6d74d4c372151fcb3880eb44a4e85907d99405c
https://github.com/node-modules/antpb/blob/e6d74d4c372151fcb3880eb44a4e85907d99405c/lib/converter.js#L17-L71
train
node-modules/antpb
lib/converter.js
genValuePartial_toObject
function genValuePartial_toObject(gen, field, fieldIndex, prop, map) { if (field.resolvedType) { if (field.resolvedType instanceof Enum) { if (map) { gen('d%s.set(k, o.enums===String?types[%i].values[m%s.get(k)]:m%s.get(k));', prop, fieldIndex, prop, prop); } else { gen('d%s=o.enums===String?types[%i].values[m%s]:m%s', prop, fieldIndex, prop, prop); } } else { if (map) { gen('d%s.set(k, types[%i].toObject(m%s.get(k),o));', prop, fieldIndex, prop); } else { gen('d%s=types[%i].toObject(m%s,o)', prop, fieldIndex, prop); } } } else { let isUnsigned = false; switch (field.type) { case 'double': case 'float': if (map) { gen('d%s.set(k, o.json&&!isFinite(m%s.get(k))?String(m%s.get(k)):m%s.get(k));', prop, prop, prop, prop); } else { gen('d%s=o.json&&!isFinite(m%s)?String(m%s):m%s;', prop, prop, prop, prop); } break; case 'uint64': isUnsigned = true; // eslint-disable-line no-fallthrough case 'int64': case 'sint64': case 'fixed64': case 'sfixed64': if (map) { gen('if(typeof m%s==="number"){', prop)('d%s.set(k, o.longs===String?String(m%s.get(k)):m%s.get(k));', prop, prop, prop)('} else {')('d%s.set(k, o.longs===String?util.Long.prototype.toString.call(m%s.get(k)):o.longs===Number?new util.LongBits(m%s.get(k).low>>>0,m%s.get(k).high>>>0).toNumber(%s):m%s.get(k));', prop, prop, prop, prop, isUnsigned ? 'true' : '', prop)('}'); } else { gen('if(typeof m%s==="number"){', prop)('d%s=o.longs===String?String(m%s):m%s;', prop, prop, prop)('} else {')('d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s', prop, prop, prop, prop, isUnsigned ? 'true' : '', prop)('}'); } break; case 'bytes': if (map) { gen('d%s.set(k, o.bytes===String?util.base64.encode(m%s.get(k),0,m%s.get(k).length):o.bytes===Array?Array.prototype.slice.call(m%s.get(k)):m%s.get(k));', prop, prop, prop, prop, prop); } else { gen('d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s', prop, prop, prop, prop, prop); } break; default: if (map) { gen('d%s.set(k, m%s.get(k));', prop, prop); } else { gen('d%s=m%s', prop, prop); } break; } } return gen; }
javascript
function genValuePartial_toObject(gen, field, fieldIndex, prop, map) { if (field.resolvedType) { if (field.resolvedType instanceof Enum) { if (map) { gen('d%s.set(k, o.enums===String?types[%i].values[m%s.get(k)]:m%s.get(k));', prop, fieldIndex, prop, prop); } else { gen('d%s=o.enums===String?types[%i].values[m%s]:m%s', prop, fieldIndex, prop, prop); } } else { if (map) { gen('d%s.set(k, types[%i].toObject(m%s.get(k),o));', prop, fieldIndex, prop); } else { gen('d%s=types[%i].toObject(m%s,o)', prop, fieldIndex, prop); } } } else { let isUnsigned = false; switch (field.type) { case 'double': case 'float': if (map) { gen('d%s.set(k, o.json&&!isFinite(m%s.get(k))?String(m%s.get(k)):m%s.get(k));', prop, prop, prop, prop); } else { gen('d%s=o.json&&!isFinite(m%s)?String(m%s):m%s;', prop, prop, prop, prop); } break; case 'uint64': isUnsigned = true; // eslint-disable-line no-fallthrough case 'int64': case 'sint64': case 'fixed64': case 'sfixed64': if (map) { gen('if(typeof m%s==="number"){', prop)('d%s.set(k, o.longs===String?String(m%s.get(k)):m%s.get(k));', prop, prop, prop)('} else {')('d%s.set(k, o.longs===String?util.Long.prototype.toString.call(m%s.get(k)):o.longs===Number?new util.LongBits(m%s.get(k).low>>>0,m%s.get(k).high>>>0).toNumber(%s):m%s.get(k));', prop, prop, prop, prop, isUnsigned ? 'true' : '', prop)('}'); } else { gen('if(typeof m%s==="number"){', prop)('d%s=o.longs===String?String(m%s):m%s;', prop, prop, prop)('} else {')('d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s', prop, prop, prop, prop, isUnsigned ? 'true' : '', prop)('}'); } break; case 'bytes': if (map) { gen('d%s.set(k, o.bytes===String?util.base64.encode(m%s.get(k),0,m%s.get(k).length):o.bytes===Array?Array.prototype.slice.call(m%s.get(k)):m%s.get(k));', prop, prop, prop, prop, prop); } else { gen('d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s', prop, prop, prop, prop, prop); } break; default: if (map) { gen('d%s.set(k, m%s.get(k));', prop, prop); } else { gen('d%s=m%s', prop, prop); } break; } } return gen; }
[ "function", "genValuePartial_toObject", "(", "gen", ",", "field", ",", "fieldIndex", ",", "prop", ",", "map", ")", "{", "if", "(", "field", ".", "resolvedType", ")", "{", "if", "(", "field", ".", "resolvedType", "instanceof", "Enum", ")", "{", "if", "(", "map", ")", "{", "gen", "(", "'d%s.set(k, o.enums===String?types[%i].values[m%s.get(k)]:m%s.get(k));'", ",", "prop", ",", "fieldIndex", ",", "prop", ",", "prop", ")", ";", "}", "else", "{", "gen", "(", "'d%s=o.enums===String?types[%i].values[m%s]:m%s'", ",", "prop", ",", "fieldIndex", ",", "prop", ",", "prop", ")", ";", "}", "}", "else", "{", "if", "(", "map", ")", "{", "gen", "(", "'d%s.set(k, types[%i].toObject(m%s.get(k),o));'", ",", "prop", ",", "fieldIndex", ",", "prop", ")", ";", "}", "else", "{", "gen", "(", "'d%s=types[%i].toObject(m%s,o)'", ",", "prop", ",", "fieldIndex", ",", "prop", ")", ";", "}", "}", "}", "else", "{", "let", "isUnsigned", "=", "false", ";", "switch", "(", "field", ".", "type", ")", "{", "case", "'double'", ":", "case", "'float'", ":", "if", "(", "map", ")", "{", "gen", "(", "'d%s.set(k, o.json&&!isFinite(m%s.get(k))?String(m%s.get(k)):m%s.get(k));'", ",", "prop", ",", "prop", ",", "prop", ",", "prop", ")", ";", "}", "else", "{", "gen", "(", "'d%s=o.json&&!isFinite(m%s)?String(m%s):m%s;'", ",", "prop", ",", "prop", ",", "prop", ",", "prop", ")", ";", "}", "break", ";", "case", "'uint64'", ":", "isUnsigned", "=", "true", ";", "case", "'int64'", ":", "case", "'sint64'", ":", "case", "'fixed64'", ":", "case", "'sfixed64'", ":", "if", "(", "map", ")", "{", "gen", "(", "'if(typeof m%s===\"number\"){'", ",", "prop", ")", "(", "'d%s.set(k, o.longs===String?String(m%s.get(k)):m%s.get(k));'", ",", "prop", ",", "prop", ",", "prop", ")", "(", "'} else {'", ")", "(", "'d%s.set(k, o.longs===String?util.Long.prototype.toString.call(m%s.get(k)):o.longs===Number?new util.LongBits(m%s.get(k).low>>>0,m%s.get(k).high>>>0).toNumber(%s):m%s.get(k));'", ",", "prop", ",", "prop", ",", "prop", ",", "prop", ",", "isUnsigned", "?", "'true'", ":", "''", ",", "prop", ")", "(", "'}'", ")", ";", "}", "else", "{", "gen", "(", "'if(typeof m%s===\"number\"){'", ",", "prop", ")", "(", "'d%s=o.longs===String?String(m%s):m%s;'", ",", "prop", ",", "prop", ",", "prop", ")", "(", "'} else {'", ")", "(", "'d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s'", ",", "prop", ",", "prop", ",", "prop", ",", "prop", ",", "isUnsigned", "?", "'true'", ":", "''", ",", "prop", ")", "(", "'}'", ")", ";", "}", "break", ";", "case", "'bytes'", ":", "if", "(", "map", ")", "{", "gen", "(", "'d%s.set(k, o.bytes===String?util.base64.encode(m%s.get(k),0,m%s.get(k).length):o.bytes===Array?Array.prototype.slice.call(m%s.get(k)):m%s.get(k));'", ",", "prop", ",", "prop", ",", "prop", ",", "prop", ",", "prop", ")", ";", "}", "else", "{", "gen", "(", "'d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s'", ",", "prop", ",", "prop", ",", "prop", ",", "prop", ",", "prop", ")", ";", "}", "break", ";", "default", ":", "if", "(", "map", ")", "{", "gen", "(", "'d%s.set(k, m%s.get(k));'", ",", "prop", ",", "prop", ")", ";", "}", "else", "{", "gen", "(", "'d%s=m%s'", ",", "prop", ",", "prop", ")", ";", "}", "break", ";", "}", "}", "return", "gen", ";", "}" ]
Generates a partial value toObject converter. @param {Codegen} gen Codegen instance @param {Field} field Reflected field @param {number} fieldIndex Field index @param {string} prop Property reference @param {bool} map whether is a map @return {Codegen} Codegen instance @ignore
[ "Generates", "a", "partial", "value", "toObject", "converter", "." ]
e6d74d4c372151fcb3880eb44a4e85907d99405c
https://github.com/node-modules/antpb/blob/e6d74d4c372151fcb3880eb44a4e85907d99405c/lib/converter.js#L175-L231
train
hachi-eiji/generate-serial-number
index.js
checkSum
function checkSum(num) { if (num == null) { return 0; } var doubled = _splitDigits(num).reverse().map(function(v, idx) { return idx % 2 === 0 ? v * 2 : v; }); var sum = doubled.reduce(function(tmp, v) { return tmp + _sum(v); }, 0); var check = 10 - (sum % 10); return check === 10 ? 0 : check; }
javascript
function checkSum(num) { if (num == null) { return 0; } var doubled = _splitDigits(num).reverse().map(function(v, idx) { return idx % 2 === 0 ? v * 2 : v; }); var sum = doubled.reduce(function(tmp, v) { return tmp + _sum(v); }, 0); var check = 10 - (sum % 10); return check === 10 ? 0 : check; }
[ "function", "checkSum", "(", "num", ")", "{", "if", "(", "num", "==", "null", ")", "{", "return", "0", ";", "}", "var", "doubled", "=", "_splitDigits", "(", "num", ")", ".", "reverse", "(", ")", ".", "map", "(", "function", "(", "v", ",", "idx", ")", "{", "return", "idx", "%", "2", "===", "0", "?", "v", "*", "2", ":", "v", ";", "}", ")", ";", "var", "sum", "=", "doubled", ".", "reduce", "(", "function", "(", "tmp", ",", "v", ")", "{", "return", "tmp", "+", "_sum", "(", "v", ")", ";", "}", ",", "0", ")", ";", "var", "check", "=", "10", "-", "(", "sum", "%", "10", ")", ";", "return", "check", "===", "10", "?", "0", ":", "check", ";", "}" ]
create check sum. @param {string|number} num @return {number} check sum value
[ "create", "check", "sum", "." ]
17bf97c86aa183690e9456cb5bf3619c964542d4
https://github.com/hachi-eiji/generate-serial-number/blob/17bf97c86aa183690e9456cb5bf3619c964542d4/index.js#L22-L34
train
hachi-eiji/generate-serial-number
index.js
isValid
function isValid(checkNumber) { if (checkNumber == null) { return false; } var numbers = _splitDigits(checkNumber); return numbers.pop() === checkSum(numbers.join('')); }
javascript
function isValid(checkNumber) { if (checkNumber == null) { return false; } var numbers = _splitDigits(checkNumber); return numbers.pop() === checkSum(numbers.join('')); }
[ "function", "isValid", "(", "checkNumber", ")", "{", "if", "(", "checkNumber", "==", "null", ")", "{", "return", "false", ";", "}", "var", "numbers", "=", "_splitDigits", "(", "checkNumber", ")", ";", "return", "numbers", ".", "pop", "(", ")", "===", "checkSum", "(", "numbers", ".", "join", "(", "''", ")", ")", ";", "}" ]
validate num. @param {string|number} checkNumber check number @return {boolean} true: checkNumber is valid
[ "validate", "num", "." ]
17bf97c86aa183690e9456cb5bf3619c964542d4
https://github.com/hachi-eiji/generate-serial-number/blob/17bf97c86aa183690e9456cb5bf3619c964542d4/index.js#L42-L48
train
hachi-eiji/generate-serial-number
index.js
generate
function generate(length) { var len = length - 1; var ary = new Array(len); for (var i = 0; i < len; i++) { ary.push(Math.floor(Math.random() * 10)); } var num = ary.join(''); return num + '' + checkSum(num); }
javascript
function generate(length) { var len = length - 1; var ary = new Array(len); for (var i = 0; i < len; i++) { ary.push(Math.floor(Math.random() * 10)); } var num = ary.join(''); return num + '' + checkSum(num); }
[ "function", "generate", "(", "length", ")", "{", "var", "len", "=", "length", "-", "1", ";", "var", "ary", "=", "new", "Array", "(", "len", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "ary", ".", "push", "(", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "10", ")", ")", ";", "}", "var", "num", "=", "ary", ".", "join", "(", "''", ")", ";", "return", "num", "+", "''", "+", "checkSum", "(", "num", ")", ";", "}" ]
create generate code @param {number} length generage @return {string} generaged digits value
[ "create", "generate", "code" ]
17bf97c86aa183690e9456cb5bf3619c964542d4
https://github.com/hachi-eiji/generate-serial-number/blob/17bf97c86aa183690e9456cb5bf3619c964542d4/index.js#L56-L64
train
tjmehta/buffer-splice
index.js
bufferSplice
function bufferSplice (buffer, start, count/*, [...items] */) { var args = assertArgs(arguments, { buffer: [Buffer, 'object'], '[start]': 'integer', '[count]': 'integer', '[...items]': [Buffer, 'string', 'array', 'object', 'number'] }) defaults(args, { start: buffer.length, count: buffer.length, items: [] }) buffer = args.buffer start = args.start count = args.count var opts if (!Buffer.isBuffer(buffer)) { opts = buffer buffer = opts.buffer } var items = args.items.map(castBuffer) var end = start + count var modified = Buffer.concat( [ buffer.slice(0, start) ] .concat(items) .concat(buffer.slice(end, buffer.length)) ) if (opts) { opts.buffer = modified // opts.buffer becomes modified buffer return buffer.slice(start, end) // removed buffer } return modified // modified buffer }
javascript
function bufferSplice (buffer, start, count/*, [...items] */) { var args = assertArgs(arguments, { buffer: [Buffer, 'object'], '[start]': 'integer', '[count]': 'integer', '[...items]': [Buffer, 'string', 'array', 'object', 'number'] }) defaults(args, { start: buffer.length, count: buffer.length, items: [] }) buffer = args.buffer start = args.start count = args.count var opts if (!Buffer.isBuffer(buffer)) { opts = buffer buffer = opts.buffer } var items = args.items.map(castBuffer) var end = start + count var modified = Buffer.concat( [ buffer.slice(0, start) ] .concat(items) .concat(buffer.slice(end, buffer.length)) ) if (opts) { opts.buffer = modified // opts.buffer becomes modified buffer return buffer.slice(start, end) // removed buffer } return modified // modified buffer }
[ "function", "bufferSplice", "(", "buffer", ",", "start", ",", "count", ")", "{", "var", "args", "=", "assertArgs", "(", "arguments", ",", "{", "buffer", ":", "[", "Buffer", ",", "'object'", "]", ",", "'[start]'", ":", "'integer'", ",", "'[count]'", ":", "'integer'", ",", "'[...items]'", ":", "[", "Buffer", ",", "'string'", ",", "'array'", ",", "'object'", ",", "'number'", "]", "}", ")", "defaults", "(", "args", ",", "{", "start", ":", "buffer", ".", "length", ",", "count", ":", "buffer", ".", "length", ",", "items", ":", "[", "]", "}", ")", "buffer", "=", "args", ".", "buffer", "start", "=", "args", ".", "start", "count", "=", "args", ".", "count", "var", "opts", "if", "(", "!", "Buffer", ".", "isBuffer", "(", "buffer", ")", ")", "{", "opts", "=", "buffer", "buffer", "=", "opts", ".", "buffer", "}", "var", "items", "=", "args", ".", "items", ".", "map", "(", "castBuffer", ")", "var", "end", "=", "start", "+", "count", "var", "modified", "=", "Buffer", ".", "concat", "(", "[", "buffer", ".", "slice", "(", "0", ",", "start", ")", "]", ".", "concat", "(", "items", ")", ".", "concat", "(", "buffer", ".", "slice", "(", "end", ",", "buffer", ".", "length", ")", ")", ")", "if", "(", "opts", ")", "{", "opts", ".", "buffer", "=", "modified", "return", "buffer", ".", "slice", "(", "start", ",", "end", ")", "}", "return", "modified", "}" ]
Splice a buffer @param {Buffer|Object} buffer input buffer or object w/ buffer { buffer: ... } @param {Integer} [start] default: buffer.length @param {Integer} [count] default: buffer.length @param {Buffer,String,Number,Object,Array} [...items] items to insert into buffer (will be casted to buffer before insertion) @return {Buffer} modified buffer
[ "Splice", "a", "buffer" ]
dbcfaaf881516b6b9cf4a6b2e144d8a55a4f03f5
https://github.com/tjmehta/buffer-splice/blob/dbcfaaf881516b6b9cf4a6b2e144d8a55a4f03f5/index.js#L14-L49
train
bodyno/nunjucks-volt
src/transformer.js
mapCOW
function mapCOW(arr, func) { var res = null; for(var i=0; i<arr.length; i++) { var item = func(arr[i]); if(item !== arr[i]) { if(!res) { res = arr.slice(); } res[i] = item; } } return res || arr; }
javascript
function mapCOW(arr, func) { var res = null; for(var i=0; i<arr.length; i++) { var item = func(arr[i]); if(item !== arr[i]) { if(!res) { res = arr.slice(); } res[i] = item; } } return res || arr; }
[ "function", "mapCOW", "(", "arr", ",", "func", ")", "{", "var", "res", "=", "null", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "var", "item", "=", "func", "(", "arr", "[", "i", "]", ")", ";", "if", "(", "item", "!==", "arr", "[", "i", "]", ")", "{", "if", "(", "!", "res", ")", "{", "res", "=", "arr", ".", "slice", "(", ")", ";", "}", "res", "[", "i", "]", "=", "item", ";", "}", "}", "return", "res", "||", "arr", ";", "}" ]
copy-on-write version of map
[ "copy", "-", "on", "-", "write", "version", "of", "map" ]
a7c0908bf98acc2af497069d7d2701bb880d3323
https://github.com/bodyno/nunjucks-volt/blob/a7c0908bf98acc2af497069d7d2701bb880d3323/src/transformer.js#L12-L28
train
adrai/devicestack
lib/framehandler.js
FrameHandler
function FrameHandler(deviceOrFrameHandler) { var self = this; // call super class EventEmitter2.call(this, { wildcard: true, delimiter: ':', maxListeners: 1000 // default would be 10! }); if (this.log) { this.log = _.wrap(this.log, function(func, msg) { func(self.constructor.name + ': ' + msg); }); } else if (FrameHandler.prototype.log) { FrameHandler.prototype.log = _.wrap(FrameHandler.prototype.log, function(func, msg) { func(self.constructor.name + ': ' + msg); }); this.log = FrameHandler.prototype.log; } else { var debug = require('debug')(this.constructor.name); this.log = function(msg) { debug(msg); }; } this.analyzeInterval = 20; if (deviceOrFrameHandler) { this.incomming = []; deviceOrFrameHandler.on('receive', function (frame) { var unwrappedFrame; if (self.analyzeNextFrame) { self.incomming = self.incomming.concat(Array.prototype.slice.call(frame, 0)); self.trigger(); } else { if (self.unwrapFrame) { unwrappedFrame = self.unwrapFrame(_.clone(frame)); if (self.log) self.log('receive unwrapped frame: ' + unwrappedFrame.toHexDebug()); self.emit('receive', unwrappedFrame); } else { if (self.log) self.log('receive frame: ' + frame.toHexDebug()); self.emit('receive', frame); } } }); deviceOrFrameHandler.on('close', function() { if (self.log) self.log('close'); self.emit('close'); self.removeAllListeners(); deviceOrFrameHandler.removeAllListeners(); deviceOrFrameHandler.removeAllListeners('receive'); self.incomming = []; }); } this.on('send', function(frame) { if (self.wrapFrame) { var wrappedFrame = self.wrapFrame(_.clone(frame)); if (self.log) self.log('send wrapped frame: ' + wrappedFrame.toHexDebug()); deviceOrFrameHandler.send(wrappedFrame); } else { if (self.log) self.log('send frame: ' + frame.toHexDebug()); deviceOrFrameHandler.send(frame); } }); }
javascript
function FrameHandler(deviceOrFrameHandler) { var self = this; // call super class EventEmitter2.call(this, { wildcard: true, delimiter: ':', maxListeners: 1000 // default would be 10! }); if (this.log) { this.log = _.wrap(this.log, function(func, msg) { func(self.constructor.name + ': ' + msg); }); } else if (FrameHandler.prototype.log) { FrameHandler.prototype.log = _.wrap(FrameHandler.prototype.log, function(func, msg) { func(self.constructor.name + ': ' + msg); }); this.log = FrameHandler.prototype.log; } else { var debug = require('debug')(this.constructor.name); this.log = function(msg) { debug(msg); }; } this.analyzeInterval = 20; if (deviceOrFrameHandler) { this.incomming = []; deviceOrFrameHandler.on('receive', function (frame) { var unwrappedFrame; if (self.analyzeNextFrame) { self.incomming = self.incomming.concat(Array.prototype.slice.call(frame, 0)); self.trigger(); } else { if (self.unwrapFrame) { unwrappedFrame = self.unwrapFrame(_.clone(frame)); if (self.log) self.log('receive unwrapped frame: ' + unwrappedFrame.toHexDebug()); self.emit('receive', unwrappedFrame); } else { if (self.log) self.log('receive frame: ' + frame.toHexDebug()); self.emit('receive', frame); } } }); deviceOrFrameHandler.on('close', function() { if (self.log) self.log('close'); self.emit('close'); self.removeAllListeners(); deviceOrFrameHandler.removeAllListeners(); deviceOrFrameHandler.removeAllListeners('receive'); self.incomming = []; }); } this.on('send', function(frame) { if (self.wrapFrame) { var wrappedFrame = self.wrapFrame(_.clone(frame)); if (self.log) self.log('send wrapped frame: ' + wrappedFrame.toHexDebug()); deviceOrFrameHandler.send(wrappedFrame); } else { if (self.log) self.log('send frame: ' + frame.toHexDebug()); deviceOrFrameHandler.send(frame); } }); }
[ "function", "FrameHandler", "(", "deviceOrFrameHandler", ")", "{", "var", "self", "=", "this", ";", "EventEmitter2", ".", "call", "(", "this", ",", "{", "wildcard", ":", "true", ",", "delimiter", ":", "':'", ",", "maxListeners", ":", "1000", "}", ")", ";", "if", "(", "this", ".", "log", ")", "{", "this", ".", "log", "=", "_", ".", "wrap", "(", "this", ".", "log", ",", "function", "(", "func", ",", "msg", ")", "{", "func", "(", "self", ".", "constructor", ".", "name", "+", "': '", "+", "msg", ")", ";", "}", ")", ";", "}", "else", "if", "(", "FrameHandler", ".", "prototype", ".", "log", ")", "{", "FrameHandler", ".", "prototype", ".", "log", "=", "_", ".", "wrap", "(", "FrameHandler", ".", "prototype", ".", "log", ",", "function", "(", "func", ",", "msg", ")", "{", "func", "(", "self", ".", "constructor", ".", "name", "+", "': '", "+", "msg", ")", ";", "}", ")", ";", "this", ".", "log", "=", "FrameHandler", ".", "prototype", ".", "log", ";", "}", "else", "{", "var", "debug", "=", "require", "(", "'debug'", ")", "(", "this", ".", "constructor", ".", "name", ")", ";", "this", ".", "log", "=", "function", "(", "msg", ")", "{", "debug", "(", "msg", ")", ";", "}", ";", "}", "this", ".", "analyzeInterval", "=", "20", ";", "if", "(", "deviceOrFrameHandler", ")", "{", "this", ".", "incomming", "=", "[", "]", ";", "deviceOrFrameHandler", ".", "on", "(", "'receive'", ",", "function", "(", "frame", ")", "{", "var", "unwrappedFrame", ";", "if", "(", "self", ".", "analyzeNextFrame", ")", "{", "self", ".", "incomming", "=", "self", ".", "incomming", ".", "concat", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "frame", ",", "0", ")", ")", ";", "self", ".", "trigger", "(", ")", ";", "}", "else", "{", "if", "(", "self", ".", "unwrapFrame", ")", "{", "unwrappedFrame", "=", "self", ".", "unwrapFrame", "(", "_", ".", "clone", "(", "frame", ")", ")", ";", "if", "(", "self", ".", "log", ")", "self", ".", "log", "(", "'receive unwrapped frame: '", "+", "unwrappedFrame", ".", "toHexDebug", "(", ")", ")", ";", "self", ".", "emit", "(", "'receive'", ",", "unwrappedFrame", ")", ";", "}", "else", "{", "if", "(", "self", ".", "log", ")", "self", ".", "log", "(", "'receive frame: '", "+", "frame", ".", "toHexDebug", "(", ")", ")", ";", "self", ".", "emit", "(", "'receive'", ",", "frame", ")", ";", "}", "}", "}", ")", ";", "deviceOrFrameHandler", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "if", "(", "self", ".", "log", ")", "self", ".", "log", "(", "'close'", ")", ";", "self", ".", "emit", "(", "'close'", ")", ";", "self", ".", "removeAllListeners", "(", ")", ";", "deviceOrFrameHandler", ".", "removeAllListeners", "(", ")", ";", "deviceOrFrameHandler", ".", "removeAllListeners", "(", "'receive'", ")", ";", "self", ".", "incomming", "=", "[", "]", ";", "}", ")", ";", "}", "this", ".", "on", "(", "'send'", ",", "function", "(", "frame", ")", "{", "if", "(", "self", ".", "wrapFrame", ")", "{", "var", "wrappedFrame", "=", "self", ".", "wrapFrame", "(", "_", ".", "clone", "(", "frame", ")", ")", ";", "if", "(", "self", ".", "log", ")", "self", ".", "log", "(", "'send wrapped frame: '", "+", "wrappedFrame", ".", "toHexDebug", "(", ")", ")", ";", "deviceOrFrameHandler", ".", "send", "(", "wrappedFrame", ")", ";", "}", "else", "{", "if", "(", "self", ".", "log", ")", "self", ".", "log", "(", "'send frame: '", "+", "frame", ".", "toHexDebug", "(", ")", ")", ";", "deviceOrFrameHandler", ".", "send", "(", "frame", ")", ";", "}", "}", ")", ";", "}" ]
You can have one or multiple framehandlers. A framhandler receives data from the upper layer and sends it to the lower layer by wrapping some header or footer information. A framehandler receives data from lower layer and sends it to the upper layer by unwrapping some header or footer information. The lowest layer for a framehandler is the device and the topmost ist the connection. - reacts on send of upper layer, calls wrapFrame function if exists and calls send function on lower layer - reacts on receive of lower layer, calls unwrapFrame function if exists and emits receive - automatically calls start function @param {Device || FrameHandler} deviceOrFrameHandler Device or framahandler object.
[ "You", "can", "have", "one", "or", "multiple", "framehandlers", ".", "A", "framhandler", "receives", "data", "from", "the", "upper", "layer", "and", "sends", "it", "to", "the", "lower", "layer", "by", "wrapping", "some", "header", "or", "footer", "information", ".", "A", "framehandler", "receives", "data", "from", "lower", "layer", "and", "sends", "it", "to", "the", "upper", "layer", "by", "unwrapping", "some", "header", "or", "footer", "information", ".", "The", "lowest", "layer", "for", "a", "framehandler", "is", "the", "device", "and", "the", "topmost", "ist", "the", "connection", ".", "-", "reacts", "on", "send", "of", "upper", "layer", "calls", "wrapFrame", "function", "if", "exists", "and", "calls", "send", "function", "on", "lower", "layer", "-", "reacts", "on", "receive", "of", "lower", "layer", "calls", "unwrapFrame", "function", "if", "exists", "and", "emits", "receive", "-", "automatically", "calls", "start", "function" ]
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/framehandler.js#L16-L83
train
edjafarov/PromisePipe
src/linkProcessors/nextEnvProcessor.js
isValidTransition
function isValidTransition (link, context) { var isValid = true; if (!(PromisePipe.envTransitions[context._env] && PromisePipe.envTransitions[context._env][link._env])) { if (!isSystemTransition(link._env)) { isValid = false; } } return isValid; }
javascript
function isValidTransition (link, context) { var isValid = true; if (!(PromisePipe.envTransitions[context._env] && PromisePipe.envTransitions[context._env][link._env])) { if (!isSystemTransition(link._env)) { isValid = false; } } return isValid; }
[ "function", "isValidTransition", "(", "link", ",", "context", ")", "{", "var", "isValid", "=", "true", ";", "if", "(", "!", "(", "PromisePipe", ".", "envTransitions", "[", "context", ".", "_env", "]", "&&", "PromisePipe", ".", "envTransitions", "[", "context", ".", "_env", "]", "[", "link", ".", "_env", "]", ")", ")", "{", "if", "(", "!", "isSystemTransition", "(", "link", ".", "_env", ")", ")", "{", "isValid", "=", "false", ";", "}", "}", "return", "isValid", ";", "}" ]
Check valid is transition
[ "Check", "valid", "is", "transition" ]
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/src/linkProcessors/nextEnvProcessor.js#L51-L60
train
edjafarov/PromisePipe
src/linkProcessors/nextEnvProcessor.js
passChains
function passChains (first, last, sequence) { return sequence.map(function (el) { return el._id; }).slice(first, last + 1); }
javascript
function passChains (first, last, sequence) { return sequence.map(function (el) { return el._id; }).slice(first, last + 1); }
[ "function", "passChains", "(", "first", ",", "last", ",", "sequence", ")", "{", "return", "sequence", ".", "map", "(", "function", "(", "el", ")", "{", "return", "el", ".", "_id", ";", "}", ")", ".", "slice", "(", "first", ",", "last", "+", "1", ")", ";", "}" ]
Return filtered list for passing functions @param {Number} first @param {Number} last @return {Array}
[ "Return", "filtered", "list", "for", "passing", "functions" ]
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/src/linkProcessors/nextEnvProcessor.js#L68-L72
train
edjafarov/PromisePipe
src/linkProcessors/nextEnvProcessor.js
lastChain
function lastChain (first, sequence) { var index = getIndexOfNextEnvAppearance(first, PromisePipe.env, sequence); return index === -1 ? (sequence.length - 1) : (index - 1); }
javascript
function lastChain (first, sequence) { var index = getIndexOfNextEnvAppearance(first, PromisePipe.env, sequence); return index === -1 ? (sequence.length - 1) : (index - 1); }
[ "function", "lastChain", "(", "first", ",", "sequence", ")", "{", "var", "index", "=", "getIndexOfNextEnvAppearance", "(", "first", ",", "PromisePipe", ".", "env", ",", "sequence", ")", ";", "return", "index", "===", "-", "1", "?", "(", "sequence", ".", "length", "-", "1", ")", ":", "(", "index", "-", "1", ")", ";", "}" ]
Return lastChain index @param {Number} first @return {Number}
[ "Return", "lastChain", "index" ]
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/src/linkProcessors/nextEnvProcessor.js#L79-L82
train
edjafarov/PromisePipe
src/linkProcessors/nextEnvProcessor.js
getChainIndexById
function getChainIndexById(id, sequence){ return sequence.map(function(el){ return el._id; }).indexOf(id); }
javascript
function getChainIndexById(id, sequence){ return sequence.map(function(el){ return el._id; }).indexOf(id); }
[ "function", "getChainIndexById", "(", "id", ",", "sequence", ")", "{", "return", "sequence", ".", "map", "(", "function", "(", "el", ")", "{", "return", "el", ".", "_id", ";", "}", ")", ".", "indexOf", "(", "id", ")", ";", "}" ]
Get chain by index @param {String} id @param {Array} sequence
[ "Get", "chain", "by", "index" ]
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/src/linkProcessors/nextEnvProcessor.js#L89-L93
train
edjafarov/PromisePipe
src/linkProcessors/nextEnvProcessor.js
getIndexOfNextEnvAppearance
function getIndexOfNextEnvAppearance(fromIndex, env, sequence){ return sequence.map(function(el){ return el._env; }).indexOf(env, fromIndex); }
javascript
function getIndexOfNextEnvAppearance(fromIndex, env, sequence){ return sequence.map(function(el){ return el._env; }).indexOf(env, fromIndex); }
[ "function", "getIndexOfNextEnvAppearance", "(", "fromIndex", ",", "env", ",", "sequence", ")", "{", "return", "sequence", ".", "map", "(", "function", "(", "el", ")", "{", "return", "el", ".", "_env", ";", "}", ")", ".", "indexOf", "(", "env", ",", "fromIndex", ")", ";", "}" ]
Get index of next env appearance @param {Number} fromIndex @param {String} env @return {Number}
[ "Get", "index", "of", "next", "env", "appearance" ]
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/src/linkProcessors/nextEnvProcessor.js#L101-L105
train
edjafarov/PromisePipe
src/linkProcessors/nextEnvProcessor.js
rangeChain
function rangeChain (id, sequence) { var first = getChainIndexById(id, sequence); return [first, lastChain(first, sequence)]; }
javascript
function rangeChain (id, sequence) { var first = getChainIndexById(id, sequence); return [first, lastChain(first, sequence)]; }
[ "function", "rangeChain", "(", "id", ",", "sequence", ")", "{", "var", "first", "=", "getChainIndexById", "(", "id", ",", "sequence", ")", ";", "return", "[", "first", ",", "lastChain", "(", "first", ",", "sequence", ")", "]", ";", "}" ]
Return tuple of chained indexes @param {Number} id @return {Tuple}
[ "Return", "tuple", "of", "chained", "indexes" ]
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/src/linkProcessors/nextEnvProcessor.js#L112-L115
train
sirap-group/connect-sequence
lib/errors/CustomError.js
setMessage
function setMessage (msg) { if (msg && typeof msg === 'string') { this.message = msg } else if (this.constructor.name !== 'CustomError') { this.message = this.constructor.DEFAULT_ERROR_MESSAGE } else { this.message = undefined } }
javascript
function setMessage (msg) { if (msg && typeof msg === 'string') { this.message = msg } else if (this.constructor.name !== 'CustomError') { this.message = this.constructor.DEFAULT_ERROR_MESSAGE } else { this.message = undefined } }
[ "function", "setMessage", "(", "msg", ")", "{", "if", "(", "msg", "&&", "typeof", "msg", "===", "'string'", ")", "{", "this", ".", "message", "=", "msg", "}", "else", "if", "(", "this", ".", "constructor", ".", "name", "!==", "'CustomError'", ")", "{", "this", ".", "message", "=", "this", ".", "constructor", ".", "DEFAULT_ERROR_MESSAGE", "}", "else", "{", "this", ".", "message", "=", "undefined", "}", "}" ]
Set the error message from the given argument or from the class property DEFAULT_ERROR_MESSAGE @method
[ "Set", "the", "error", "message", "from", "the", "given", "argument", "or", "from", "the", "class", "property", "DEFAULT_ERROR_MESSAGE" ]
8b0490d75596107b7c37e2c2cfa4d0486f3eda1a
https://github.com/sirap-group/connect-sequence/blob/8b0490d75596107b7c37e2c2cfa4d0486f3eda1a/lib/errors/CustomError.js#L33-L41
train
sirap-group/connect-sequence
lib/errors/CustomError.js
createStackTrace
function createStackTrace () { var stack = new Error().stack var splited = stack.split('\n') var modifiedStack = splited[0].concat('\n', splited.splice(3).join('\n')) this.stack = modifiedStack }
javascript
function createStackTrace () { var stack = new Error().stack var splited = stack.split('\n') var modifiedStack = splited[0].concat('\n', splited.splice(3).join('\n')) this.stack = modifiedStack }
[ "function", "createStackTrace", "(", ")", "{", "var", "stack", "=", "new", "Error", "(", ")", ".", "stack", "var", "splited", "=", "stack", ".", "split", "(", "'\\n'", ")", "\\n", "var", "modifiedStack", "=", "splited", "[", "0", "]", ".", "concat", "(", "'\\n'", ",", "\\n", ")", "}" ]
Set the the correct stack trace for this error @method @returns {undefined} @throws {PrivateMethodError}
[ "Set", "the", "the", "correct", "stack", "trace", "for", "this", "error" ]
8b0490d75596107b7c37e2c2cfa4d0486f3eda1a
https://github.com/sirap-group/connect-sequence/blob/8b0490d75596107b7c37e2c2cfa4d0486f3eda1a/lib/errors/CustomError.js#L49-L54
train
adrai/devicestack
lib/serial/eventeddeviceloader.js
EventedSerialDeviceLoader
function EventedSerialDeviceLoader(Device, vendorId, productId) { // call super class SerialDeviceLoader.call(this, Device, false); this.vidPidPairs = []; if (!productId && _.isArray(vendorId)) { this.vidPidPairs = vendorId; } else { this.vidPidPairs = [{vendorId: vendorId, productId: productId}]; } }
javascript
function EventedSerialDeviceLoader(Device, vendorId, productId) { // call super class SerialDeviceLoader.call(this, Device, false); this.vidPidPairs = []; if (!productId && _.isArray(vendorId)) { this.vidPidPairs = vendorId; } else { this.vidPidPairs = [{vendorId: vendorId, productId: productId}]; } }
[ "function", "EventedSerialDeviceLoader", "(", "Device", ",", "vendorId", ",", "productId", ")", "{", "SerialDeviceLoader", ".", "call", "(", "this", ",", "Device", ",", "false", ")", ";", "this", ".", "vidPidPairs", "=", "[", "]", ";", "if", "(", "!", "productId", "&&", "_", ".", "isArray", "(", "vendorId", ")", ")", "{", "this", ".", "vidPidPairs", "=", "vendorId", ";", "}", "else", "{", "this", ".", "vidPidPairs", "=", "[", "{", "vendorId", ":", "vendorId", ",", "productId", ":", "productId", "}", "]", ";", "}", "}" ]
An EventedSerialDeviceLoader can check if there are available some serial devices. @param {Object} Device Device The constructor function of the device. @param {Number || Array} vendorId The vendor id or an array of vid/pid pairs. @param {Number} productId The product id or optional.
[ "An", "EventedSerialDeviceLoader", "can", "check", "if", "there", "are", "available", "some", "serial", "devices", "." ]
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/serial/eventeddeviceloader.js#L12-L24
train
vygis/ng-clamp
ng-clamp.js
getMaxLines
function getMaxLines(height) { var availHeight = height || element.clientHeight, lineHeight = getLineHeight(element); return Math.max(Math.floor(availHeight / lineHeight), 0); }
javascript
function getMaxLines(height) { var availHeight = height || element.clientHeight, lineHeight = getLineHeight(element); return Math.max(Math.floor(availHeight / lineHeight), 0); }
[ "function", "getMaxLines", "(", "height", ")", "{", "var", "availHeight", "=", "height", "||", "element", ".", "clientHeight", ",", "lineHeight", "=", "getLineHeight", "(", "element", ")", ";", "return", "Math", ".", "max", "(", "Math", ".", "floor", "(", "availHeight", "/", "lineHeight", ")", ",", "0", ")", ";", "}" ]
Returns the maximum number of lines of text that should be rendered based on the current height of the element and the line-height of the text.
[ "Returns", "the", "maximum", "number", "of", "lines", "of", "text", "that", "should", "be", "rendered", "based", "on", "the", "current", "height", "of", "the", "element", "and", "the", "line", "-", "height", "of", "the", "text", "." ]
9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb
https://github.com/vygis/ng-clamp/blob/9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb/ng-clamp.js#L70-L75
train
vygis/ng-clamp
ng-clamp.js
getLineHeight
function getLineHeight(elem) { var lh = computeStyle(elem, 'line-height'); if (lh == 'normal') { // Normal line heights vary from browser to browser. The spec recommends // a value between 1.0 and 1.2 of the font size. Using 1.1 to split the diff. lh = parseInt(computeStyle(elem, 'font-size')) * 1.2; } return parseInt(lh); }
javascript
function getLineHeight(elem) { var lh = computeStyle(elem, 'line-height'); if (lh == 'normal') { // Normal line heights vary from browser to browser. The spec recommends // a value between 1.0 and 1.2 of the font size. Using 1.1 to split the diff. lh = parseInt(computeStyle(elem, 'font-size')) * 1.2; } return parseInt(lh); }
[ "function", "getLineHeight", "(", "elem", ")", "{", "var", "lh", "=", "computeStyle", "(", "elem", ",", "'line-height'", ")", ";", "if", "(", "lh", "==", "'normal'", ")", "{", "lh", "=", "parseInt", "(", "computeStyle", "(", "elem", ",", "'font-size'", ")", ")", "*", "1.2", ";", "}", "return", "parseInt", "(", "lh", ")", ";", "}" ]
Returns the line-height of an element as an integer.
[ "Returns", "the", "line", "-", "height", "of", "an", "element", "as", "an", "integer", "." ]
9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb
https://github.com/vygis/ng-clamp/blob/9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb/ng-clamp.js#L89-L97
train
vygis/ng-clamp
ng-clamp.js
getLastChild
function getLastChild(elem) { //Current element has children, need to go deeper and get last child as a text node if (elem.lastChild.children && elem.lastChild.children.length > 0) { return getLastChild(Array.prototype.slice.call(elem.children).pop()); } //This is the absolute last child, a text node, but something's wrong with it. Remove it and keep trying else if (!elem.lastChild || !elem.lastChild.nodeValue || elem.lastChild.nodeValue === '' || elem.lastChild.nodeValue == opt.truncationChar) { elem.lastChild.parentNode.removeChild(elem.lastChild); return getLastChild(element); } //This is the last child we want, return it else { return elem.lastChild; } }
javascript
function getLastChild(elem) { //Current element has children, need to go deeper and get last child as a text node if (elem.lastChild.children && elem.lastChild.children.length > 0) { return getLastChild(Array.prototype.slice.call(elem.children).pop()); } //This is the absolute last child, a text node, but something's wrong with it. Remove it and keep trying else if (!elem.lastChild || !elem.lastChild.nodeValue || elem.lastChild.nodeValue === '' || elem.lastChild.nodeValue == opt.truncationChar) { elem.lastChild.parentNode.removeChild(elem.lastChild); return getLastChild(element); } //This is the last child we want, return it else { return elem.lastChild; } }
[ "function", "getLastChild", "(", "elem", ")", "{", "if", "(", "elem", ".", "lastChild", ".", "children", "&&", "elem", ".", "lastChild", ".", "children", ".", "length", ">", "0", ")", "{", "return", "getLastChild", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "elem", ".", "children", ")", ".", "pop", "(", ")", ")", ";", "}", "else", "if", "(", "!", "elem", ".", "lastChild", "||", "!", "elem", ".", "lastChild", ".", "nodeValue", "||", "elem", ".", "lastChild", ".", "nodeValue", "===", "''", "||", "elem", ".", "lastChild", ".", "nodeValue", "==", "opt", ".", "truncationChar", ")", "{", "elem", ".", "lastChild", ".", "parentNode", ".", "removeChild", "(", "elem", ".", "lastChild", ")", ";", "return", "getLastChild", "(", "element", ")", ";", "}", "else", "{", "return", "elem", ".", "lastChild", ";", "}", "}" ]
Gets an element's last child. That may be another node or a node's contents.
[ "Gets", "an", "element", "s", "last", "child", ".", "That", "may", "be", "another", "node", "or", "a", "node", "s", "contents", "." ]
9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb
https://github.com/vygis/ng-clamp/blob/9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb/ng-clamp.js#L109-L123
train
vygis/ng-clamp
ng-clamp.js
truncate
function truncate(target, maxHeight) { if (!maxHeight) { return; } /** * Resets global variables. */ function reset() { splitOnChars = opt.splitOnChars.slice(0); splitChar = splitOnChars[0]; chunks = null; lastChunk = null; } var nodeValue = target.nodeValue.replace(opt.truncationChar, ''); //Grab the next chunks if (!chunks) { //If there are more characters to try, grab the next one if (splitOnChars.length > 0) { splitChar = splitOnChars.shift(); } //No characters to chunk by. Go character-by-character else { splitChar = ''; } chunks = nodeValue.split(splitChar); } //If there are chunks left to remove, remove the last one and see if // the nodeValue fits. if (chunks.length > 1) { // console.log('chunks', chunks); lastChunk = chunks.pop(); // console.log('lastChunk', lastChunk); applyEllipsis(target, chunks.join(splitChar)); } //No more chunks can be removed using this character else { chunks = null; } //Insert the custom HTML before the truncation character if (truncationHTMLContainer) { target.nodeValue = target.nodeValue.replace(opt.truncationChar, ''); element.innerHTML = target.nodeValue + ' ' + truncationHTMLContainer.innerHTML + opt.truncationChar; } //Search produced valid chunks if (chunks) { //It fits if (element.clientHeight <= maxHeight) { //There's still more characters to try splitting on, not quite done yet if (splitOnChars.length >= 0 && splitChar !== '') { applyEllipsis(target, chunks.join(splitChar) + splitChar + lastChunk); chunks = null; } //Finished! else { return element.innerHTML; } } } //No valid chunks produced else { //No valid chunks even when splitting by letter, time to move //on to the next node if (splitChar === '') { applyEllipsis(target, ''); target = getLastChild(element); reset(); } } //If you get here it means still too big, let's keep truncating if (opt.animate) { setTimeout(function() { truncate(target, maxHeight); }, opt.animate === true ? 10 : opt.animate); } else { return truncate(target, maxHeight); } }
javascript
function truncate(target, maxHeight) { if (!maxHeight) { return; } /** * Resets global variables. */ function reset() { splitOnChars = opt.splitOnChars.slice(0); splitChar = splitOnChars[0]; chunks = null; lastChunk = null; } var nodeValue = target.nodeValue.replace(opt.truncationChar, ''); //Grab the next chunks if (!chunks) { //If there are more characters to try, grab the next one if (splitOnChars.length > 0) { splitChar = splitOnChars.shift(); } //No characters to chunk by. Go character-by-character else { splitChar = ''; } chunks = nodeValue.split(splitChar); } //If there are chunks left to remove, remove the last one and see if // the nodeValue fits. if (chunks.length > 1) { // console.log('chunks', chunks); lastChunk = chunks.pop(); // console.log('lastChunk', lastChunk); applyEllipsis(target, chunks.join(splitChar)); } //No more chunks can be removed using this character else { chunks = null; } //Insert the custom HTML before the truncation character if (truncationHTMLContainer) { target.nodeValue = target.nodeValue.replace(opt.truncationChar, ''); element.innerHTML = target.nodeValue + ' ' + truncationHTMLContainer.innerHTML + opt.truncationChar; } //Search produced valid chunks if (chunks) { //It fits if (element.clientHeight <= maxHeight) { //There's still more characters to try splitting on, not quite done yet if (splitOnChars.length >= 0 && splitChar !== '') { applyEllipsis(target, chunks.join(splitChar) + splitChar + lastChunk); chunks = null; } //Finished! else { return element.innerHTML; } } } //No valid chunks produced else { //No valid chunks even when splitting by letter, time to move //on to the next node if (splitChar === '') { applyEllipsis(target, ''); target = getLastChild(element); reset(); } } //If you get here it means still too big, let's keep truncating if (opt.animate) { setTimeout(function() { truncate(target, maxHeight); }, opt.animate === true ? 10 : opt.animate); } else { return truncate(target, maxHeight); } }
[ "function", "truncate", "(", "target", ",", "maxHeight", ")", "{", "if", "(", "!", "maxHeight", ")", "{", "return", ";", "}", "function", "reset", "(", ")", "{", "splitOnChars", "=", "opt", ".", "splitOnChars", ".", "slice", "(", "0", ")", ";", "splitChar", "=", "splitOnChars", "[", "0", "]", ";", "chunks", "=", "null", ";", "lastChunk", "=", "null", ";", "}", "var", "nodeValue", "=", "target", ".", "nodeValue", ".", "replace", "(", "opt", ".", "truncationChar", ",", "''", ")", ";", "if", "(", "!", "chunks", ")", "{", "if", "(", "splitOnChars", ".", "length", ">", "0", ")", "{", "splitChar", "=", "splitOnChars", ".", "shift", "(", ")", ";", "}", "else", "{", "splitChar", "=", "''", ";", "}", "chunks", "=", "nodeValue", ".", "split", "(", "splitChar", ")", ";", "}", "if", "(", "chunks", ".", "length", ">", "1", ")", "{", "lastChunk", "=", "chunks", ".", "pop", "(", ")", ";", "applyEllipsis", "(", "target", ",", "chunks", ".", "join", "(", "splitChar", ")", ")", ";", "}", "else", "{", "chunks", "=", "null", ";", "}", "if", "(", "truncationHTMLContainer", ")", "{", "target", ".", "nodeValue", "=", "target", ".", "nodeValue", ".", "replace", "(", "opt", ".", "truncationChar", ",", "''", ")", ";", "element", ".", "innerHTML", "=", "target", ".", "nodeValue", "+", "' '", "+", "truncationHTMLContainer", ".", "innerHTML", "+", "opt", ".", "truncationChar", ";", "}", "if", "(", "chunks", ")", "{", "if", "(", "element", ".", "clientHeight", "<=", "maxHeight", ")", "{", "if", "(", "splitOnChars", ".", "length", ">=", "0", "&&", "splitChar", "!==", "''", ")", "{", "applyEllipsis", "(", "target", ",", "chunks", ".", "join", "(", "splitChar", ")", "+", "splitChar", "+", "lastChunk", ")", ";", "chunks", "=", "null", ";", "}", "else", "{", "return", "element", ".", "innerHTML", ";", "}", "}", "}", "else", "{", "if", "(", "splitChar", "===", "''", ")", "{", "applyEllipsis", "(", "target", ",", "''", ")", ";", "target", "=", "getLastChild", "(", "element", ")", ";", "reset", "(", ")", ";", "}", "}", "if", "(", "opt", ".", "animate", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "truncate", "(", "target", ",", "maxHeight", ")", ";", "}", ",", "opt", ".", "animate", "===", "true", "?", "10", ":", "opt", ".", "animate", ")", ";", "}", "else", "{", "return", "truncate", "(", "target", ",", "maxHeight", ")", ";", "}", "}" ]
Removes one character at a time from the text until its width or height is beneath the passed-in max param.
[ "Removes", "one", "character", "at", "a", "time", "from", "the", "text", "until", "its", "width", "or", "height", "is", "beneath", "the", "passed", "-", "in", "max", "param", "." ]
9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb
https://github.com/vygis/ng-clamp/blob/9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb/ng-clamp.js#L129-L214
train
vygis/ng-clamp
ng-clamp.js
reset
function reset() { splitOnChars = opt.splitOnChars.slice(0); splitChar = splitOnChars[0]; chunks = null; lastChunk = null; }
javascript
function reset() { splitOnChars = opt.splitOnChars.slice(0); splitChar = splitOnChars[0]; chunks = null; lastChunk = null; }
[ "function", "reset", "(", ")", "{", "splitOnChars", "=", "opt", ".", "splitOnChars", ".", "slice", "(", "0", ")", ";", "splitChar", "=", "splitOnChars", "[", "0", "]", ";", "chunks", "=", "null", ";", "lastChunk", "=", "null", ";", "}" ]
Resets global variables.
[ "Resets", "global", "variables", "." ]
9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb
https://github.com/vygis/ng-clamp/blob/9684b4422d07484a0dcecc0d7aec7ad5ba0ee0fb/ng-clamp.js#L137-L142
train
iranreyes/gsap-promisify
index.js
_animateFunc
function _animateFunc(func, element, duration, opts) { opts = Object.assign({}, opts); var tween; return new Promise(function(resolve, reject, onCancel) { opts.onComplete = resolve; tween = func(element, duration, opts); onCancel && onCancel(function() { tween.kill(); }); }); }
javascript
function _animateFunc(func, element, duration, opts) { opts = Object.assign({}, opts); var tween; return new Promise(function(resolve, reject, onCancel) { opts.onComplete = resolve; tween = func(element, duration, opts); onCancel && onCancel(function() { tween.kill(); }); }); }
[ "function", "_animateFunc", "(", "func", ",", "element", ",", "duration", ",", "opts", ")", "{", "opts", "=", "Object", ".", "assign", "(", "{", "}", ",", "opts", ")", ";", "var", "tween", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ",", "onCancel", ")", "{", "opts", ".", "onComplete", "=", "resolve", ";", "tween", "=", "func", "(", "element", ",", "duration", ",", "opts", ")", ";", "onCancel", "&&", "onCancel", "(", "function", "(", ")", "{", "tween", ".", "kill", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Animate specific functions inside the TweenModules, like TweenLite.to @param {Function} func - TweenModule.to @param {DOMElement} element - DOM Element @param {number} duration - Duration @param {Object} opts - Paramaters @returns
[ "Animate", "specific", "functions", "inside", "the", "TweenModules", "like", "TweenLite", ".", "to" ]
8f52438793f37678d257f1b68495961fb7ea4d92
https://github.com/iranreyes/gsap-promisify/blob/8f52438793f37678d257f1b68495961fb7ea4d92/index.js#L10-L21
train
iranreyes/gsap-promisify
index.js
animate
function animate(Promise, TweenModule) { var animateTo = _animateFunc.bind(null, TweenModule.to); var util = animateTo; util.to = animateTo; util.from = _animateFunc.bind(null, TweenModule.from); util.set = function animateSet(element, params) { params = Object.assign({}, params); return new Promise(function(resolve, reject) { params.onComplete = resolve; TweenModule.set(element, params); }); }; util.fromTo = function animateFromTo(element, duration, from, to) { to = Object.assign({}, to); var tween; return new Promise(function(resolve, reject, onCancel) { to.onComplete = resolve; tween = TweenModule.fromTo(element, duration, from, to); onCancel && onCancel(function() { tween.kill(); }); }); }; util.killTweensOf = TweenModule.killTweensOf.bind(TweenModule); util.all = Promise.all; return util; }
javascript
function animate(Promise, TweenModule) { var animateTo = _animateFunc.bind(null, TweenModule.to); var util = animateTo; util.to = animateTo; util.from = _animateFunc.bind(null, TweenModule.from); util.set = function animateSet(element, params) { params = Object.assign({}, params); return new Promise(function(resolve, reject) { params.onComplete = resolve; TweenModule.set(element, params); }); }; util.fromTo = function animateFromTo(element, duration, from, to) { to = Object.assign({}, to); var tween; return new Promise(function(resolve, reject, onCancel) { to.onComplete = resolve; tween = TweenModule.fromTo(element, duration, from, to); onCancel && onCancel(function() { tween.kill(); }); }); }; util.killTweensOf = TweenModule.killTweensOf.bind(TweenModule); util.all = Promise.all; return util; }
[ "function", "animate", "(", "Promise", ",", "TweenModule", ")", "{", "var", "animateTo", "=", "_animateFunc", ".", "bind", "(", "null", ",", "TweenModule", ".", "to", ")", ";", "var", "util", "=", "animateTo", ";", "util", ".", "to", "=", "animateTo", ";", "util", ".", "from", "=", "_animateFunc", ".", "bind", "(", "null", ",", "TweenModule", ".", "from", ")", ";", "util", ".", "set", "=", "function", "animateSet", "(", "element", ",", "params", ")", "{", "params", "=", "Object", ".", "assign", "(", "{", "}", ",", "params", ")", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "params", ".", "onComplete", "=", "resolve", ";", "TweenModule", ".", "set", "(", "element", ",", "params", ")", ";", "}", ")", ";", "}", ";", "util", ".", "fromTo", "=", "function", "animateFromTo", "(", "element", ",", "duration", ",", "from", ",", "to", ")", "{", "to", "=", "Object", ".", "assign", "(", "{", "}", ",", "to", ")", ";", "var", "tween", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ",", "onCancel", ")", "{", "to", ".", "onComplete", "=", "resolve", ";", "tween", "=", "TweenModule", ".", "fromTo", "(", "element", ",", "duration", ",", "from", ",", "to", ")", ";", "onCancel", "&&", "onCancel", "(", "function", "(", ")", "{", "tween", ".", "kill", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "util", ".", "killTweensOf", "=", "TweenModule", ".", "killTweensOf", ".", "bind", "(", "TweenModule", ")", ";", "util", ".", "all", "=", "Promise", ".", "all", ";", "return", "util", ";", "}" ]
Get a wrapper of GSAP Tween @param {Promise} Promise - Promise framework @param {TweenModule} TweenModule - TweenMax or TweenLite @returns {Object} GSAP Promisified
[ "Get", "a", "wrapper", "of", "GSAP", "Tween" ]
8f52438793f37678d257f1b68495961fb7ea4d92
https://github.com/iranreyes/gsap-promisify/blob/8f52438793f37678d257f1b68495961fb7ea4d92/index.js#L30-L61
train
bodyno/nunjucks-volt
src/compiler.js
binOpEmitter
function binOpEmitter(str) { return function(node, frame) { this.compile(node.left, frame); this.emit(str); this.compile(node.right, frame); }; }
javascript
function binOpEmitter(str) { return function(node, frame) { this.compile(node.left, frame); this.emit(str); this.compile(node.right, frame); }; }
[ "function", "binOpEmitter", "(", "str", ")", "{", "return", "function", "(", "node", ",", "frame", ")", "{", "this", ".", "compile", "(", "node", ".", "left", ",", "frame", ")", ";", "this", ".", "emit", "(", "str", ")", ";", "this", ".", "compile", "(", "node", ".", "right", ",", "frame", ")", ";", "}", ";", "}" ]
A common pattern is to emit binary operators
[ "A", "common", "pattern", "is", "to", "emit", "binary", "operators" ]
a7c0908bf98acc2af497069d7d2701bb880d3323
https://github.com/bodyno/nunjucks-volt/blob/a7c0908bf98acc2af497069d7d2701bb880d3323/src/compiler.js#L23-L29
train
mercmobily/simpleDeclare
declare.js
function( fn ){ // Get the object's base var objectBase = getObjectBase( this, fn ); // If the function is not found anywhere in the prototype chain // there is a pretty big problem if( ! objectBase.base ) throw new Error( "inherited coun't find method in chain (getInherited)" ); // At this point, I know the key. To look for the super method, I // only have to check if one of the parent __proto__ has a matching key `k` var p = Object.getPrototypeOf( objectBase.base ); return p[ objectBase.key ]; }
javascript
function( fn ){ // Get the object's base var objectBase = getObjectBase( this, fn ); // If the function is not found anywhere in the prototype chain // there is a pretty big problem if( ! objectBase.base ) throw new Error( "inherited coun't find method in chain (getInherited)" ); // At this point, I know the key. To look for the super method, I // only have to check if one of the parent __proto__ has a matching key `k` var p = Object.getPrototypeOf( objectBase.base ); return p[ objectBase.key ]; }
[ "function", "(", "fn", ")", "{", "var", "objectBase", "=", "getObjectBase", "(", "this", ",", "fn", ")", ";", "if", "(", "!", "objectBase", ".", "base", ")", "throw", "new", "Error", "(", "\"inherited coun't find method in chain (getInherited)\"", ")", ";", "var", "p", "=", "Object", ".", "getPrototypeOf", "(", "objectBase", ".", "base", ")", ";", "return", "p", "[", "objectBase", ".", "key", "]", ";", "}" ]
This will become a method call, so `this` is the object
[ "This", "will", "become", "a", "method", "call", "so", "this", "is", "the", "object" ]
1a8ed54f0e7eca6133c95e293e8770ef26382187
https://github.com/mercmobily/simpleDeclare/blob/1a8ed54f0e7eca6133c95e293e8770ef26382187/declare.js#L45-L58
train
mercmobily/simpleDeclare
declare.js
function(){ // These will be worked out from `arguments` var SuperCtorList, protoMixin; var MixedClass, ResultClass; var list = []; var i, l, ii, ll; var proto; var r = workoutDeclareArguments( arguments ); SuperCtorList = r.SuperCtorList; protoMixin = r.protoMixin; // No parameters: inheriting from Object directly, no multiple inheritance if( SuperCtorList.length === 0 ){ MixedClass = Object; } // Only one parameter: straght single inheritance. else if( SuperCtorList.length === 1 ){ MixedClass = SuperCtorList[ 0 ]; // More than one parameter: multiple inheritance at work // MixedClass will end up being an artificially made constructor // where the prototype chain is the sum of _every_ prototype in // every element of SuperCtorList (taking out duplicates) } else { MixedClass = Object; // NOW: // Go through every __proto__ of every derivative class, and augment // MixedClass by inheriting from A COPY OF each one of them. list = []; for( i = 0, l = SuperCtorList.length; i < l; i ++ ){ // Get the prototype list, in the right order // (the reversed discovery order) // The result will be placed in `subList` var subList = []; if( typeof SuperCtorList[ i ] === 'undefined' || typeof SuperCtorList[ i ].prototype === 'undefined'){ throw new Error("Invalid constructor!") } proto = SuperCtorList[ i ].prototype; while( proto ){ if( proto.constructor !== Object ) subList.push( proto ); proto = Object.getPrototypeOf( proto ); } subList = subList.reverse(); // Add each element of sublist as long as it's not already in the main `list` for( ii = 0, ll = subList.length; ii < ll; ii ++ ){ if( ! constructorAlreadyInList( subList[ ii ].constructor, list ) ) list.push( subList[ ii ] ); } } // For each element in the prototype list that isn't Object(), // augment MixedClass with a copy of the new prototype for( ii = 0, ll = list.length; ii < ll; ii ++ ){ proto = list[ ii ]; var M = MixedClass; if( proto.constructor !== Object ){ MixedClass = makeConstructor( MixedClass, proto, proto.constructor ); copyClassMethods( M, MixedClass ); // Methods previously inherited copyClassMethods( proto.constructor, MixedClass ); // Extra methods from the father constructor } } } // Finally, inherit from the MixedClass, and add // class methods over // MixedClass might be: // * Object (coming from no inheritance), // * SuperCtorList[0] (coming from single inheritance) // * A constructor with the appropriate prototype chain (multiple inheritance) ResultClass = makeConstructor( MixedClass, protoMixin ); copyClassMethods( MixedClass, ResultClass ); // Add getInherited, inherited() and inheritedAsync() to the prototype // (only if they are not already there) if( ! ResultClass.prototype.getInherited ) { ResultClass.prototype.getInherited = getInherited; } if( ! ResultClass.prototype.inherited ) { ResultClass.prototype.inherited = makeInheritedFunction( 'sync' ); } if( ! ResultClass.prototype.inheritedAsync ) { ResultClass.prototype.inheritedAsync = makeInheritedFunction( 'async' ); } // Add instanceOf if( ! ResultClass.prototype.instanceOf ) { ResultClass.prototype.instanceOf = instanceOf; } // Add class-wide method `extend` ResultClass.extend = function(){ return extend.apply( this, arguments ); }; // That's it! return ResultClass; }
javascript
function(){ // These will be worked out from `arguments` var SuperCtorList, protoMixin; var MixedClass, ResultClass; var list = []; var i, l, ii, ll; var proto; var r = workoutDeclareArguments( arguments ); SuperCtorList = r.SuperCtorList; protoMixin = r.protoMixin; // No parameters: inheriting from Object directly, no multiple inheritance if( SuperCtorList.length === 0 ){ MixedClass = Object; } // Only one parameter: straght single inheritance. else if( SuperCtorList.length === 1 ){ MixedClass = SuperCtorList[ 0 ]; // More than one parameter: multiple inheritance at work // MixedClass will end up being an artificially made constructor // where the prototype chain is the sum of _every_ prototype in // every element of SuperCtorList (taking out duplicates) } else { MixedClass = Object; // NOW: // Go through every __proto__ of every derivative class, and augment // MixedClass by inheriting from A COPY OF each one of them. list = []; for( i = 0, l = SuperCtorList.length; i < l; i ++ ){ // Get the prototype list, in the right order // (the reversed discovery order) // The result will be placed in `subList` var subList = []; if( typeof SuperCtorList[ i ] === 'undefined' || typeof SuperCtorList[ i ].prototype === 'undefined'){ throw new Error("Invalid constructor!") } proto = SuperCtorList[ i ].prototype; while( proto ){ if( proto.constructor !== Object ) subList.push( proto ); proto = Object.getPrototypeOf( proto ); } subList = subList.reverse(); // Add each element of sublist as long as it's not already in the main `list` for( ii = 0, ll = subList.length; ii < ll; ii ++ ){ if( ! constructorAlreadyInList( subList[ ii ].constructor, list ) ) list.push( subList[ ii ] ); } } // For each element in the prototype list that isn't Object(), // augment MixedClass with a copy of the new prototype for( ii = 0, ll = list.length; ii < ll; ii ++ ){ proto = list[ ii ]; var M = MixedClass; if( proto.constructor !== Object ){ MixedClass = makeConstructor( MixedClass, proto, proto.constructor ); copyClassMethods( M, MixedClass ); // Methods previously inherited copyClassMethods( proto.constructor, MixedClass ); // Extra methods from the father constructor } } } // Finally, inherit from the MixedClass, and add // class methods over // MixedClass might be: // * Object (coming from no inheritance), // * SuperCtorList[0] (coming from single inheritance) // * A constructor with the appropriate prototype chain (multiple inheritance) ResultClass = makeConstructor( MixedClass, protoMixin ); copyClassMethods( MixedClass, ResultClass ); // Add getInherited, inherited() and inheritedAsync() to the prototype // (only if they are not already there) if( ! ResultClass.prototype.getInherited ) { ResultClass.prototype.getInherited = getInherited; } if( ! ResultClass.prototype.inherited ) { ResultClass.prototype.inherited = makeInheritedFunction( 'sync' ); } if( ! ResultClass.prototype.inheritedAsync ) { ResultClass.prototype.inheritedAsync = makeInheritedFunction( 'async' ); } // Add instanceOf if( ! ResultClass.prototype.instanceOf ) { ResultClass.prototype.instanceOf = instanceOf; } // Add class-wide method `extend` ResultClass.extend = function(){ return extend.apply( this, arguments ); }; // That's it! return ResultClass; }
[ "function", "(", ")", "{", "var", "SuperCtorList", ",", "protoMixin", ";", "var", "MixedClass", ",", "ResultClass", ";", "var", "list", "=", "[", "]", ";", "var", "i", ",", "l", ",", "ii", ",", "ll", ";", "var", "proto", ";", "var", "r", "=", "workoutDeclareArguments", "(", "arguments", ")", ";", "SuperCtorList", "=", "r", ".", "SuperCtorList", ";", "protoMixin", "=", "r", ".", "protoMixin", ";", "if", "(", "SuperCtorList", ".", "length", "===", "0", ")", "{", "MixedClass", "=", "Object", ";", "}", "else", "if", "(", "SuperCtorList", ".", "length", "===", "1", ")", "{", "MixedClass", "=", "SuperCtorList", "[", "0", "]", ";", "}", "else", "{", "MixedClass", "=", "Object", ";", "list", "=", "[", "]", ";", "for", "(", "i", "=", "0", ",", "l", "=", "SuperCtorList", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "subList", "=", "[", "]", ";", "if", "(", "typeof", "SuperCtorList", "[", "i", "]", "===", "'undefined'", "||", "typeof", "SuperCtorList", "[", "i", "]", ".", "prototype", "===", "'undefined'", ")", "{", "throw", "new", "Error", "(", "\"Invalid constructor!\"", ")", "}", "proto", "=", "SuperCtorList", "[", "i", "]", ".", "prototype", ";", "while", "(", "proto", ")", "{", "if", "(", "proto", ".", "constructor", "!==", "Object", ")", "subList", ".", "push", "(", "proto", ")", ";", "proto", "=", "Object", ".", "getPrototypeOf", "(", "proto", ")", ";", "}", "subList", "=", "subList", ".", "reverse", "(", ")", ";", "for", "(", "ii", "=", "0", ",", "ll", "=", "subList", ".", "length", ";", "ii", "<", "ll", ";", "ii", "++", ")", "{", "if", "(", "!", "constructorAlreadyInList", "(", "subList", "[", "ii", "]", ".", "constructor", ",", "list", ")", ")", "list", ".", "push", "(", "subList", "[", "ii", "]", ")", ";", "}", "}", "for", "(", "ii", "=", "0", ",", "ll", "=", "list", ".", "length", ";", "ii", "<", "ll", ";", "ii", "++", ")", "{", "proto", "=", "list", "[", "ii", "]", ";", "var", "M", "=", "MixedClass", ";", "if", "(", "proto", ".", "constructor", "!==", "Object", ")", "{", "MixedClass", "=", "makeConstructor", "(", "MixedClass", ",", "proto", ",", "proto", ".", "constructor", ")", ";", "copyClassMethods", "(", "M", ",", "MixedClass", ")", ";", "copyClassMethods", "(", "proto", ".", "constructor", ",", "MixedClass", ")", ";", "}", "}", "}", "ResultClass", "=", "makeConstructor", "(", "MixedClass", ",", "protoMixin", ")", ";", "copyClassMethods", "(", "MixedClass", ",", "ResultClass", ")", ";", "if", "(", "!", "ResultClass", ".", "prototype", ".", "getInherited", ")", "{", "ResultClass", ".", "prototype", ".", "getInherited", "=", "getInherited", ";", "}", "if", "(", "!", "ResultClass", ".", "prototype", ".", "inherited", ")", "{", "ResultClass", ".", "prototype", ".", "inherited", "=", "makeInheritedFunction", "(", "'sync'", ")", ";", "}", "if", "(", "!", "ResultClass", ".", "prototype", ".", "inheritedAsync", ")", "{", "ResultClass", ".", "prototype", ".", "inheritedAsync", "=", "makeInheritedFunction", "(", "'async'", ")", ";", "}", "if", "(", "!", "ResultClass", ".", "prototype", ".", "instanceOf", ")", "{", "ResultClass", ".", "prototype", ".", "instanceOf", "=", "instanceOf", ";", "}", "ResultClass", ".", "extend", "=", "function", "(", ")", "{", "return", "extend", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "return", "ResultClass", ";", "}" ]
Parameters are very variable
[ "Parameters", "are", "very", "variable" ]
1a8ed54f0e7eca6133c95e293e8770ef26382187
https://github.com/mercmobily/simpleDeclare/blob/1a8ed54f0e7eca6133c95e293e8770ef26382187/declare.js#L328-L436
train
crysalead-js/dom-layer
examples/input/js/inputs.js
elementType
function elementType(element) { var name = element.nodeName.toLowerCase(); if (name !== "input") { if (name === "select" && element.multiple) { return "select-multiple"; } return name; } var type = element.getAttribute('type'); if (!type) { return "text"; } return type.toLowerCase(); }
javascript
function elementType(element) { var name = element.nodeName.toLowerCase(); if (name !== "input") { if (name === "select" && element.multiple) { return "select-multiple"; } return name; } var type = element.getAttribute('type'); if (!type) { return "text"; } return type.toLowerCase(); }
[ "function", "elementType", "(", "element", ")", "{", "var", "name", "=", "element", ".", "nodeName", ".", "toLowerCase", "(", ")", ";", "if", "(", "name", "!==", "\"input\"", ")", "{", "if", "(", "name", "===", "\"select\"", "&&", "element", ".", "multiple", ")", "{", "return", "\"select-multiple\"", ";", "}", "return", "name", ";", "}", "var", "type", "=", "element", ".", "getAttribute", "(", "'type'", ")", ";", "if", "(", "!", "type", ")", "{", "return", "\"text\"", ";", "}", "return", "type", ".", "toLowerCase", "(", ")", ";", "}" ]
Returns the type of a DOM element. @param Object element A DOM element. @return String The DOM element type.
[ "Returns", "the", "type", "of", "a", "DOM", "element", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/examples/input/js/inputs.js#L13-L26
train
crysalead-js/dom-layer
examples/input/js/inputs.js
getValue
function getValue(element) { var name = elementType(element); switch (name) { case "checkbox": case "radio": if (!element.checked) { return false; } var val = element.getAttribute('value'); return val == null ? true : val; case "select": case "select-multiple": var options = element.options; var values = []; for (var i = 0, len = options.length; i < len; i++) { if (options[i].selected) { values.push(options[i].value); } } return name === "select-multiple" ? values : values[0]; default: return element.value; } }
javascript
function getValue(element) { var name = elementType(element); switch (name) { case "checkbox": case "radio": if (!element.checked) { return false; } var val = element.getAttribute('value'); return val == null ? true : val; case "select": case "select-multiple": var options = element.options; var values = []; for (var i = 0, len = options.length; i < len; i++) { if (options[i].selected) { values.push(options[i].value); } } return name === "select-multiple" ? values : values[0]; default: return element.value; } }
[ "function", "getValue", "(", "element", ")", "{", "var", "name", "=", "elementType", "(", "element", ")", ";", "switch", "(", "name", ")", "{", "case", "\"checkbox\"", ":", "case", "\"radio\"", ":", "if", "(", "!", "element", ".", "checked", ")", "{", "return", "false", ";", "}", "var", "val", "=", "element", ".", "getAttribute", "(", "'value'", ")", ";", "return", "val", "==", "null", "?", "true", ":", "val", ";", "case", "\"select\"", ":", "case", "\"select-multiple\"", ":", "var", "options", "=", "element", ".", "options", ";", "var", "values", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "options", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "options", "[", "i", "]", ".", "selected", ")", "{", "values", ".", "push", "(", "options", "[", "i", "]", ".", "value", ")", ";", "}", "}", "return", "name", "===", "\"select-multiple\"", "?", "values", ":", "values", "[", "0", "]", ";", "default", ":", "return", "element", ".", "value", ";", "}", "}" ]
Gets DOM element value. @param Object element A DOM element @return mixed The DOM element value
[ "Gets", "DOM", "element", "value", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/examples/input/js/inputs.js#L34-L57
train
hswolff/activity-logger
index.js
getActivity
function getActivity(activityId) { var activity = activities[activityId]; if (activity === undefined) { throw new Error('activity with id "' + activityId + '" not found.'); } return activity; }
javascript
function getActivity(activityId) { var activity = activities[activityId]; if (activity === undefined) { throw new Error('activity with id "' + activityId + '" not found.'); } return activity; }
[ "function", "getActivity", "(", "activityId", ")", "{", "var", "activity", "=", "activities", "[", "activityId", "]", ";", "if", "(", "activity", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "'activity with id \"'", "+", "activityId", "+", "'\" not found.'", ")", ";", "}", "return", "activity", ";", "}" ]
The Activity object. @typedef {{ id: number, message: string, timestamps: Array.<number> }} Activity Get an Activity object if it exists. Throws if it doesn't exist. @param {number} activityId Activity id. @return {Activity}
[ "The", "Activity", "object", "." ]
e3997da2f8705aff488ac1be0b26a7fee7d4661f
https://github.com/hswolff/activity-logger/blob/e3997da2f8705aff488ac1be0b26a7fee7d4661f/index.js#L56-L64
train
hswolff/activity-logger
index.js
writeActivity
function writeActivity(template, activity) { if (!enabled) { return; } var handlers = outputHandlers.get(); if (handlers.length === 0) { throw new Error('No output handlers defined.'); } handlers.forEach(function(handler) { handler(template(activity)); }); }
javascript
function writeActivity(template, activity) { if (!enabled) { return; } var handlers = outputHandlers.get(); if (handlers.length === 0) { throw new Error('No output handlers defined.'); } handlers.forEach(function(handler) { handler(template(activity)); }); }
[ "function", "writeActivity", "(", "template", ",", "activity", ")", "{", "if", "(", "!", "enabled", ")", "{", "return", ";", "}", "var", "handlers", "=", "outputHandlers", ".", "get", "(", ")", ";", "if", "(", "handlers", ".", "length", "===", "0", ")", "{", "throw", "new", "Error", "(", "'No output handlers defined.'", ")", ";", "}", "handlers", ".", "forEach", "(", "function", "(", "handler", ")", "{", "handler", "(", "template", "(", "activity", ")", ")", ";", "}", ")", ";", "}" ]
Outputs the activity message to all defined handlers. @param {Function} template Template to use to format the message. @param {Activity} activity Activity object.
[ "Outputs", "the", "activity", "message", "to", "all", "defined", "handlers", "." ]
e3997da2f8705aff488ac1be0b26a7fee7d4661f
https://github.com/hswolff/activity-logger/blob/e3997da2f8705aff488ac1be0b26a7fee7d4661f/index.js#L71-L85
train
hswolff/activity-logger
index.js
createActivity
function createActivity(activityMessage) { if (activityMessage === undefined || activityMessage === undefined || typeof activityMessage !== 'string') { throw new Error('Creating a new activity requires an activity message.'); } var activityId = uuid++; var activity = { id: activityId, message: activityMessage, timestamps: [] }; activities[activityId] = activity; return activityId; }
javascript
function createActivity(activityMessage) { if (activityMessage === undefined || activityMessage === undefined || typeof activityMessage !== 'string') { throw new Error('Creating a new activity requires an activity message.'); } var activityId = uuid++; var activity = { id: activityId, message: activityMessage, timestamps: [] }; activities[activityId] = activity; return activityId; }
[ "function", "createActivity", "(", "activityMessage", ")", "{", "if", "(", "activityMessage", "===", "undefined", "||", "activityMessage", "===", "undefined", "||", "typeof", "activityMessage", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Creating a new activity requires an activity message.'", ")", ";", "}", "var", "activityId", "=", "uuid", "++", ";", "var", "activity", "=", "{", "id", ":", "activityId", ",", "message", ":", "activityMessage", ",", "timestamps", ":", "[", "]", "}", ";", "activities", "[", "activityId", "]", "=", "activity", ";", "return", "activityId", ";", "}" ]
Create a new Activity object with its own unique ID. Does not start the activity. @param {string} activityMessage The activity message to use. @return {number} Activity ID.
[ "Create", "a", "new", "Activity", "object", "with", "its", "own", "unique", "ID", ".", "Does", "not", "start", "the", "activity", "." ]
e3997da2f8705aff488ac1be0b26a7fee7d4661f
https://github.com/hswolff/activity-logger/blob/e3997da2f8705aff488ac1be0b26a7fee7d4661f/index.js#L93-L110
train
hswolff/activity-logger
index.js
markActivity
function markActivity(activityId) { var activity = getActivity(activityId); var timeNow = Date.now(); activity.timestamps.push(timeNow); return timeNow; }
javascript
function markActivity(activityId) { var activity = getActivity(activityId); var timeNow = Date.now(); activity.timestamps.push(timeNow); return timeNow; }
[ "function", "markActivity", "(", "activityId", ")", "{", "var", "activity", "=", "getActivity", "(", "activityId", ")", ";", "var", "timeNow", "=", "Date", ".", "now", "(", ")", ";", "activity", ".", "timestamps", ".", "push", "(", "timeNow", ")", ";", "return", "timeNow", ";", "}" ]
Mark a timestamp in an activity. Adds it to the array of timestamps. @param {number} activityId Activity ID. @return {number} The timestamp value added.
[ "Mark", "a", "timestamp", "in", "an", "activity", ".", "Adds", "it", "to", "the", "array", "of", "timestamps", "." ]
e3997da2f8705aff488ac1be0b26a7fee7d4661f
https://github.com/hswolff/activity-logger/blob/e3997da2f8705aff488ac1be0b26a7fee7d4661f/index.js#L118-L123
train
hswolff/activity-logger
index.js
startActivity
function startActivity(activityMessage) { var activityId = createActivity(activityMessage); markActivity(activityId); var activity = getActivity(activityId); writeActivity(activityEvents.start, activity); return activityId; }
javascript
function startActivity(activityMessage) { var activityId = createActivity(activityMessage); markActivity(activityId); var activity = getActivity(activityId); writeActivity(activityEvents.start, activity); return activityId; }
[ "function", "startActivity", "(", "activityMessage", ")", "{", "var", "activityId", "=", "createActivity", "(", "activityMessage", ")", ";", "markActivity", "(", "activityId", ")", ";", "var", "activity", "=", "getActivity", "(", "activityId", ")", ";", "writeActivity", "(", "activityEvents", ".", "start", ",", "activity", ")", ";", "return", "activityId", ";", "}" ]
Create and start a new activity. @param {string} activityMessage Message to use for activity. @return {number} Activity id.
[ "Create", "and", "start", "a", "new", "activity", "." ]
e3997da2f8705aff488ac1be0b26a7fee7d4661f
https://github.com/hswolff/activity-logger/blob/e3997da2f8705aff488ac1be0b26a7fee7d4661f/index.js#L143-L152
train
hswolff/activity-logger
index.js
endActivity
function endActivity(activityId) { markActivity(activityId); var activity = destroyActivity(activityId) writeActivity(activityEvents.end, activity); return activity; }
javascript
function endActivity(activityId) { markActivity(activityId); var activity = destroyActivity(activityId) writeActivity(activityEvents.end, activity); return activity; }
[ "function", "endActivity", "(", "activityId", ")", "{", "markActivity", "(", "activityId", ")", ";", "var", "activity", "=", "destroyActivity", "(", "activityId", ")", "writeActivity", "(", "activityEvents", ".", "end", ",", "activity", ")", ";", "return", "activity", ";", "}" ]
End an activity. Log the time, write output, and then delete activity. @param {number} activityId Activity ID. @return {Activity} Return the ended activity.
[ "End", "an", "activity", ".", "Log", "the", "time", "write", "output", "and", "then", "delete", "activity", "." ]
e3997da2f8705aff488ac1be0b26a7fee7d4661f
https://github.com/hswolff/activity-logger/blob/e3997da2f8705aff488ac1be0b26a7fee7d4661f/index.js#L160-L168
train
kmi/node-red-contrib-jsonpath
jsonpath/node-red-contrib-jsonpath.js
JSONPathNode
function JSONPathNode(n) { // Create a RED node RED.nodes.createNode(this,n); // Store local copies of the node configuration (as defined in the .html) this.expression = n.expression; this.split = n.split; var node = this; this.on("input", function(msg) { if ( msg.hasOwnProperty("payload") ) { var input = msg.payload; if (typeof msg.payload === "string") { // It's a string: parse it as JSON try { input = JSON.parse(msg.payload); } catch (e) { node.warn("The message received is not JSON. Ignoring it."); return; } } // Evalute the JSONPath expresssion var evalResult = jsonPath.eval(input, node.expression); if (!node.split) { // Batch it in one message. Carry pre-existing properties msg.payload = evalResult; node.send(msg); } else { // Send one message per match result var response = evalResult.map(function (value) { return {"payload": value}; }); node.send([response]); } } }); this.on("close", function() { // Called when the node is shutdown - eg on redeploy. // Allows ports to be closed, connections dropped etc. // eg: this.client.disconnect(); }); }
javascript
function JSONPathNode(n) { // Create a RED node RED.nodes.createNode(this,n); // Store local copies of the node configuration (as defined in the .html) this.expression = n.expression; this.split = n.split; var node = this; this.on("input", function(msg) { if ( msg.hasOwnProperty("payload") ) { var input = msg.payload; if (typeof msg.payload === "string") { // It's a string: parse it as JSON try { input = JSON.parse(msg.payload); } catch (e) { node.warn("The message received is not JSON. Ignoring it."); return; } } // Evalute the JSONPath expresssion var evalResult = jsonPath.eval(input, node.expression); if (!node.split) { // Batch it in one message. Carry pre-existing properties msg.payload = evalResult; node.send(msg); } else { // Send one message per match result var response = evalResult.map(function (value) { return {"payload": value}; }); node.send([response]); } } }); this.on("close", function() { // Called when the node is shutdown - eg on redeploy. // Allows ports to be closed, connections dropped etc. // eg: this.client.disconnect(); }); }
[ "function", "JSONPathNode", "(", "n", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "n", ")", ";", "this", ".", "expression", "=", "n", ".", "expression", ";", "this", ".", "split", "=", "n", ".", "split", ";", "var", "node", "=", "this", ";", "this", ".", "on", "(", "\"input\"", ",", "function", "(", "msg", ")", "{", "if", "(", "msg", ".", "hasOwnProperty", "(", "\"payload\"", ")", ")", "{", "var", "input", "=", "msg", ".", "payload", ";", "if", "(", "typeof", "msg", ".", "payload", "===", "\"string\"", ")", "{", "try", "{", "input", "=", "JSON", ".", "parse", "(", "msg", ".", "payload", ")", ";", "}", "catch", "(", "e", ")", "{", "node", ".", "warn", "(", "\"The message received is not JSON. Ignoring it.\"", ")", ";", "return", ";", "}", "}", "var", "evalResult", "=", "jsonPath", ".", "eval", "(", "input", ",", "node", ".", "expression", ")", ";", "if", "(", "!", "node", ".", "split", ")", "{", "msg", ".", "payload", "=", "evalResult", ";", "node", ".", "send", "(", "msg", ")", ";", "}", "else", "{", "var", "response", "=", "evalResult", ".", "map", "(", "function", "(", "value", ")", "{", "return", "{", "\"payload\"", ":", "value", "}", ";", "}", ")", ";", "node", ".", "send", "(", "[", "response", "]", ")", ";", "}", "}", "}", ")", ";", "this", ".", "on", "(", "\"close\"", ",", "function", "(", ")", "{", "}", ")", ";", "}" ]
The main node definition - most things happen in here
[ "The", "main", "node", "definition", "-", "most", "things", "happen", "in", "here" ]
6db0d1ffaa069e31b37b52fe8a4b420b5bdfe257
https://github.com/kmi/node-red-contrib-jsonpath/blob/6db0d1ffaa069e31b37b52fe8a4b420b5bdfe257/jsonpath/node-red-contrib-jsonpath.js#L28-L73
train
shakefu/template-js
index.js
Template
function Template (filename, context) { // Save the context for reuse in sub-templates this.context = context || {} this.context.include = this.render.bind(this) this.context.forEach = forEach // Save the filename for the initial render this.filename = filename // Create a cache so we only read files once this.cache = {} }
javascript
function Template (filename, context) { // Save the context for reuse in sub-templates this.context = context || {} this.context.include = this.render.bind(this) this.context.forEach = forEach // Save the filename for the initial render this.filename = filename // Create a cache so we only read files once this.cache = {} }
[ "function", "Template", "(", "filename", ",", "context", ")", "{", "this", ".", "context", "=", "context", "||", "{", "}", "this", ".", "context", ".", "include", "=", "this", ".", "render", ".", "bind", "(", "this", ")", "this", ".", "context", ".", "forEach", "=", "forEach", "this", ".", "filename", "=", "filename", "this", ".", "cache", "=", "{", "}", "}" ]
Template class for reusable contexts and cached files.
[ "Template", "class", "for", "reusable", "contexts", "and", "cached", "files", "." ]
9f336df6f88c5250bc5880d8dc45dac2f46fe2e0
https://github.com/shakefu/template-js/blob/9f336df6f88c5250bc5880d8dc45dac2f46fe2e0/index.js#L20-L31
train
adrai/devicestack
lib/serial/deviceguider.js
SerialDeviceGuider
function SerialDeviceGuider(deviceLoader) { var self = this; // call super class DeviceGuider.call(this, deviceLoader); this.currentState.getDeviceByPort = function(port) { return _.find(self.currentState.plugged, function(d) { return d.get('portName') && port && d.get('portName').toLowerCase() === port.toLowerCase(); }); }; this.currentState.getConnectedDeviceByPort = function(port) { return _.find(self.currentState.connected, function(d) { return d.get('portName') && port && d.get('portName').toLowerCase() === port.toLowerCase(); }); }; }
javascript
function SerialDeviceGuider(deviceLoader) { var self = this; // call super class DeviceGuider.call(this, deviceLoader); this.currentState.getDeviceByPort = function(port) { return _.find(self.currentState.plugged, function(d) { return d.get('portName') && port && d.get('portName').toLowerCase() === port.toLowerCase(); }); }; this.currentState.getConnectedDeviceByPort = function(port) { return _.find(self.currentState.connected, function(d) { return d.get('portName') && port && d.get('portName').toLowerCase() === port.toLowerCase(); }); }; }
[ "function", "SerialDeviceGuider", "(", "deviceLoader", ")", "{", "var", "self", "=", "this", ";", "DeviceGuider", ".", "call", "(", "this", ",", "deviceLoader", ")", ";", "this", ".", "currentState", ".", "getDeviceByPort", "=", "function", "(", "port", ")", "{", "return", "_", ".", "find", "(", "self", ".", "currentState", ".", "plugged", ",", "function", "(", "d", ")", "{", "return", "d", ".", "get", "(", "'portName'", ")", "&&", "port", "&&", "d", ".", "get", "(", "'portName'", ")", ".", "toLowerCase", "(", ")", "===", "port", ".", "toLowerCase", "(", ")", ";", "}", ")", ";", "}", ";", "this", ".", "currentState", ".", "getConnectedDeviceByPort", "=", "function", "(", "port", ")", "{", "return", "_", ".", "find", "(", "self", ".", "currentState", ".", "connected", ",", "function", "(", "d", ")", "{", "return", "d", ".", "get", "(", "'portName'", ")", "&&", "port", "&&", "d", ".", "get", "(", "'portName'", ")", ".", "toLowerCase", "(", ")", "===", "port", ".", "toLowerCase", "(", ")", ";", "}", ")", ";", "}", ";", "}" ]
A serialdeviceguider emits 'plug' for new attached serial devices, 'unplug' for removed serial devices, emits 'connect' for connected serial devices and emits 'disconnect' for disconnected serial devices. @param {SerialDeviceLoader} deviceLoader The deviceloader object.
[ "A", "serialdeviceguider", "emits", "plug", "for", "new", "attached", "serial", "devices", "unplug", "for", "removed", "serial", "devices", "emits", "connect", "for", "connected", "serial", "devices", "and", "emits", "disconnect", "for", "disconnected", "serial", "devices", "." ]
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/serial/deviceguider.js#L12-L29
train
NotNinja/nevis
src/hash-code/context.js
HashCodeContext
function HashCodeContext(value, hashCode, options) { if (options == null) { options = {}; } /** * A reference to {@link Nevis.hashCode} which can be called within a {@link HashCodeGenerator}. * * @private * @type {Function} */ this._hashCode = hashCode; /** * The options to be used to generate the hash code for the value. * * @public * @type {Nevis~HashCodeOptions} */ this.options = { allowCache: options.allowCache !== false, filterProperty: options.filterProperty != null ? options.filterProperty : function() { return true; }, ignoreHashCode: Boolean(options.ignoreHashCode), ignoreInherited: Boolean(options.ignoreInherited), ignoreMethods: Boolean(options.ignoreMethods) }; /** * The string representation of the value whose hash code is to be generated. * * This is generated using <code>Object.prototype.toString</code> and is intended to be primarily used for more * specific type-checking. * * @public * @type {string} */ this.string = Object.prototype.toString.call(value); /** * The type of the value whose hash code is to be generated. * * This is generated using <code>typeof</code> and is intended to be primarily used for simple type-checking. * * @public * @type {string} */ this.type = typeof value; /** * The value whose hash code is to be generated. * * @public * @type {*} */ this.value = value; }
javascript
function HashCodeContext(value, hashCode, options) { if (options == null) { options = {}; } /** * A reference to {@link Nevis.hashCode} which can be called within a {@link HashCodeGenerator}. * * @private * @type {Function} */ this._hashCode = hashCode; /** * The options to be used to generate the hash code for the value. * * @public * @type {Nevis~HashCodeOptions} */ this.options = { allowCache: options.allowCache !== false, filterProperty: options.filterProperty != null ? options.filterProperty : function() { return true; }, ignoreHashCode: Boolean(options.ignoreHashCode), ignoreInherited: Boolean(options.ignoreInherited), ignoreMethods: Boolean(options.ignoreMethods) }; /** * The string representation of the value whose hash code is to be generated. * * This is generated using <code>Object.prototype.toString</code> and is intended to be primarily used for more * specific type-checking. * * @public * @type {string} */ this.string = Object.prototype.toString.call(value); /** * The type of the value whose hash code is to be generated. * * This is generated using <code>typeof</code> and is intended to be primarily used for simple type-checking. * * @public * @type {string} */ this.type = typeof value; /** * The value whose hash code is to be generated. * * @public * @type {*} */ this.value = value; }
[ "function", "HashCodeContext", "(", "value", ",", "hashCode", ",", "options", ")", "{", "if", "(", "options", "==", "null", ")", "{", "options", "=", "{", "}", ";", "}", "this", ".", "_hashCode", "=", "hashCode", ";", "this", ".", "options", "=", "{", "allowCache", ":", "options", ".", "allowCache", "!==", "false", ",", "filterProperty", ":", "options", ".", "filterProperty", "!=", "null", "?", "options", ".", "filterProperty", ":", "function", "(", ")", "{", "return", "true", ";", "}", ",", "ignoreHashCode", ":", "Boolean", "(", "options", ".", "ignoreHashCode", ")", ",", "ignoreInherited", ":", "Boolean", "(", "options", ".", "ignoreInherited", ")", ",", "ignoreMethods", ":", "Boolean", "(", "options", ".", "ignoreMethods", ")", "}", ";", "this", ".", "string", "=", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "value", ")", ";", "this", ".", "type", "=", "typeof", "value", ";", "this", ".", "value", "=", "value", ";", "}" ]
Contains the value for which a hash code is to be generated as well string representation and type of the value which can be checked elsewhere for type-checking etc. @param {*} value - the value whose hash code is to be generated @param {Function} hashCode - a reference to {@link Nevis.hashCode} which can be called within a {@link HashCodeGenerator} @param {?Nevis~HashCodeOptions} options - the options to be used (may be <code>null</code>) @protected @constructor
[ "Contains", "the", "value", "for", "which", "a", "hash", "code", "is", "to", "be", "generated", "as", "well", "string", "representation", "and", "type", "of", "the", "value", "which", "can", "be", "checked", "elsewhere", "for", "type", "-", "checking", "etc", "." ]
1885e154e6e52d8d3eb307da9f27ed591bac455c
https://github.com/NotNinja/nevis/blob/1885e154e6e52d8d3eb307da9f27ed591bac455c/src/hash-code/context.js#L36-L93
train
nknapp/thought
lib/init.js
checkPackageJsonInGit
function checkPackageJsonInGit () { return exec('git', ['status', '--porcelain', 'package.json']) .then(function ([stdout, stderr]) { debug('git status --porcelain package.json', 'stdout', stdout, 'stderr', stderr) if (stdout.indexOf('package.json') >= 0) { throw new Error('package.json has changes!\n' + 'I would like to add scripts to your package.json, but ' + 'there are changes that have not been commited yet.\n' + 'I don\'t want to damage anything, so I\'m not doing anyhting right now. ' + 'Please commit your package.json') } }) }
javascript
function checkPackageJsonInGit () { return exec('git', ['status', '--porcelain', 'package.json']) .then(function ([stdout, stderr]) { debug('git status --porcelain package.json', 'stdout', stdout, 'stderr', stderr) if (stdout.indexOf('package.json') >= 0) { throw new Error('package.json has changes!\n' + 'I would like to add scripts to your package.json, but ' + 'there are changes that have not been commited yet.\n' + 'I don\'t want to damage anything, so I\'m not doing anyhting right now. ' + 'Please commit your package.json') } }) }
[ "function", "checkPackageJsonInGit", "(", ")", "{", "return", "exec", "(", "'git'", ",", "[", "'status'", ",", "'--porcelain'", ",", "'package.json'", "]", ")", ".", "then", "(", "function", "(", "[", "stdout", ",", "stderr", "]", ")", "{", "debug", "(", "'git status --porcelain package.json'", ",", "'stdout'", ",", "stdout", ",", "'stderr'", ",", "stderr", ")", "if", "(", "stdout", ".", "indexOf", "(", "'package.json'", ")", ">=", "0", ")", "{", "throw", "new", "Error", "(", "'package.json has changes!\\n'", "+", "\\n", "+", "'I would like to add scripts to your package.json, but '", "+", "'there are changes that have not been commited yet.\\n'", "+", "\\n", ")", "}", "}", ")", "}" ]
Ensure that package.json is checked in and unmodified @return {Promise<boolean>} true, if everything is fine
[ "Ensure", "that", "package", ".", "json", "is", "checked", "in", "and", "unmodified" ]
2ae991f2d3065ff4eae4df544d20787b07be5116
https://github.com/nknapp/thought/blob/2ae991f2d3065ff4eae4df544d20787b07be5116/lib/init.js#L49-L61
train
mongodb-js/index-model
lib/fetch.js
combineStatsAndIndexes
function combineStatsAndIndexes(done, results) { var indexes = results.getIndexes; var stats = results.getIndexStats; var sizes = results.getIndexSizes; _.each(indexes, function(idx, i) { _.assign(indexes[i], stats[idx.name]); _.assign(indexes[i], sizes[idx.name]); }); done(null, indexes); }
javascript
function combineStatsAndIndexes(done, results) { var indexes = results.getIndexes; var stats = results.getIndexStats; var sizes = results.getIndexSizes; _.each(indexes, function(idx, i) { _.assign(indexes[i], stats[idx.name]); _.assign(indexes[i], sizes[idx.name]); }); done(null, indexes); }
[ "function", "combineStatsAndIndexes", "(", "done", ",", "results", ")", "{", "var", "indexes", "=", "results", ".", "getIndexes", ";", "var", "stats", "=", "results", ".", "getIndexStats", ";", "var", "sizes", "=", "results", ".", "getIndexSizes", ";", "_", ".", "each", "(", "indexes", ",", "function", "(", "idx", ",", "i", ")", "{", "_", ".", "assign", "(", "indexes", "[", "i", "]", ",", "stats", "[", "idx", ".", "name", "]", ")", ";", "_", ".", "assign", "(", "indexes", "[", "i", "]", ",", "sizes", "[", "idx", ".", "name", "]", ")", ";", "}", ")", ";", "done", "(", "null", ",", "indexes", ")", ";", "}" ]
merge all information together for each index @param {Function} done callback @param {object} results results from async.auto
[ "merge", "all", "information", "together", "for", "each", "index" ]
43c878440e79299ee104b36d55c06aff63d8cf63
https://github.com/mongodb-js/index-model/blob/43c878440e79299ee104b36d55c06aff63d8cf63/lib/fetch.js#L125-L134
train
mlaanderson/database-js-postgres
index.js
OpenConnection
function OpenConnection(connection) { let base = new pg.Client({ host: connection.Hostname || 'localhost', port: parseInt(connection.Port) || 5432, user: connection.Username, password: connection.Password, database: connection.Database }); base.connect(); return new PostgreSQL(base); }
javascript
function OpenConnection(connection) { let base = new pg.Client({ host: connection.Hostname || 'localhost', port: parseInt(connection.Port) || 5432, user: connection.Username, password: connection.Password, database: connection.Database }); base.connect(); return new PostgreSQL(base); }
[ "function", "OpenConnection", "(", "connection", ")", "{", "let", "base", "=", "new", "pg", ".", "Client", "(", "{", "host", ":", "connection", ".", "Hostname", "||", "'localhost'", ",", "port", ":", "parseInt", "(", "connection", ".", "Port", ")", "||", "5432", ",", "user", ":", "connection", ".", "Username", ",", "password", ":", "connection", ".", "Password", ",", "database", ":", "connection", ".", "Database", "}", ")", ";", "base", ".", "connect", "(", ")", ";", "return", "new", "PostgreSQL", "(", "base", ")", ";", "}" ]
Opens a connection @param {{Hostname: string, Port: number, Username: string, Password: string, Database: string}} connection @returns {PostgreSQL}
[ "Opens", "a", "connection" ]
241d657f905f7f38113e230c84b4f7c14b234a65
https://github.com/mlaanderson/database-js-postgres/blob/241d657f905f7f38113e230c84b4f7c14b234a65/index.js#L123-L133
train
edjafarov/PromisePipe
example/PPRouter/adapters/ExpressAdapter.js
function(renderData){ var renderArr = Object.keys(renderData).map(function(mask){ return { mask: mask, context: renderData[mask].context, component: renderData[mask].component, params: renderData[mask].params, data: renderData[mask].data } }) function renderComp(renderArr){ var partial = renderArr.shift(); if(renderArr.length > 0) partial.params.children = [renderComp(renderArr)]; partial.params.mask = partial.mask; partial.params.data = partial.data; partial.params.context = partial.context; if(!partial.component) { var result = partial.data || ''; if(partial.params.children && partial.params.children[0]) result +=partial.params.children[0]; return result; } return partial.component(partial.params) } return renderComp(renderArr); }
javascript
function(renderData){ var renderArr = Object.keys(renderData).map(function(mask){ return { mask: mask, context: renderData[mask].context, component: renderData[mask].component, params: renderData[mask].params, data: renderData[mask].data } }) function renderComp(renderArr){ var partial = renderArr.shift(); if(renderArr.length > 0) partial.params.children = [renderComp(renderArr)]; partial.params.mask = partial.mask; partial.params.data = partial.data; partial.params.context = partial.context; if(!partial.component) { var result = partial.data || ''; if(partial.params.children && partial.params.children[0]) result +=partial.params.children[0]; return result; } return partial.component(partial.params) } return renderComp(renderArr); }
[ "function", "(", "renderData", ")", "{", "var", "renderArr", "=", "Object", ".", "keys", "(", "renderData", ")", ".", "map", "(", "function", "(", "mask", ")", "{", "return", "{", "mask", ":", "mask", ",", "context", ":", "renderData", "[", "mask", "]", ".", "context", ",", "component", ":", "renderData", "[", "mask", "]", ".", "component", ",", "params", ":", "renderData", "[", "mask", "]", ".", "params", ",", "data", ":", "renderData", "[", "mask", "]", ".", "data", "}", "}", ")", "function", "renderComp", "(", "renderArr", ")", "{", "var", "partial", "=", "renderArr", ".", "shift", "(", ")", ";", "if", "(", "renderArr", ".", "length", ">", "0", ")", "partial", ".", "params", ".", "children", "=", "[", "renderComp", "(", "renderArr", ")", "]", ";", "partial", ".", "params", ".", "mask", "=", "partial", ".", "mask", ";", "partial", ".", "params", ".", "data", "=", "partial", ".", "data", ";", "partial", ".", "params", ".", "context", "=", "partial", ".", "context", ";", "if", "(", "!", "partial", ".", "component", ")", "{", "var", "result", "=", "partial", ".", "data", "||", "''", ";", "if", "(", "partial", ".", "params", ".", "children", "&&", "partial", ".", "params", ".", "children", "[", "0", "]", ")", "result", "+=", "partial", ".", "params", ".", "children", "[", "0", "]", ";", "return", "result", ";", "}", "return", "partial", ".", "component", "(", "partial", ".", "params", ")", "}", "return", "renderComp", "(", "renderArr", ")", ";", "}" ]
renderData is a hash of data, params, and component per resolved part of url
[ "renderData", "is", "a", "hash", "of", "data", "params", "and", "component", "per", "resolved", "part", "of", "url" ]
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/example/PPRouter/adapters/ExpressAdapter.js#L6-L34
train
adrai/devicestack
lib/deviceloader.js
DeviceLoader
function DeviceLoader() { var self = this; // call super class EventEmitter2.call(this, { wildcard: true, delimiter: ':', maxListeners: 1000 // default would be 10! }); if (this.log) { this.log = _.wrap(this.log, function(func, msg) { func(self.constructor.name + ': ' + msg); }); } else if (DeviceLoader.prototype.log) { DeviceLoader.prototype.log = _.wrap(DeviceLoader.prototype.log, function(func, msg) { func(self.constructor.name + ': ' + msg); }); this.log = DeviceLoader.prototype.log; } else { var debug = require('debug')(this.constructor.name); this.log = function(msg) { debug(msg); }; } this.lookupIntervalId = null; this.oldDevices = []; this.isRunning = false; }
javascript
function DeviceLoader() { var self = this; // call super class EventEmitter2.call(this, { wildcard: true, delimiter: ':', maxListeners: 1000 // default would be 10! }); if (this.log) { this.log = _.wrap(this.log, function(func, msg) { func(self.constructor.name + ': ' + msg); }); } else if (DeviceLoader.prototype.log) { DeviceLoader.prototype.log = _.wrap(DeviceLoader.prototype.log, function(func, msg) { func(self.constructor.name + ': ' + msg); }); this.log = DeviceLoader.prototype.log; } else { var debug = require('debug')(this.constructor.name); this.log = function(msg) { debug(msg); }; } this.lookupIntervalId = null; this.oldDevices = []; this.isRunning = false; }
[ "function", "DeviceLoader", "(", ")", "{", "var", "self", "=", "this", ";", "EventEmitter2", ".", "call", "(", "this", ",", "{", "wildcard", ":", "true", ",", "delimiter", ":", "':'", ",", "maxListeners", ":", "1000", "}", ")", ";", "if", "(", "this", ".", "log", ")", "{", "this", ".", "log", "=", "_", ".", "wrap", "(", "this", ".", "log", ",", "function", "(", "func", ",", "msg", ")", "{", "func", "(", "self", ".", "constructor", ".", "name", "+", "': '", "+", "msg", ")", ";", "}", ")", ";", "}", "else", "if", "(", "DeviceLoader", ".", "prototype", ".", "log", ")", "{", "DeviceLoader", ".", "prototype", ".", "log", "=", "_", ".", "wrap", "(", "DeviceLoader", ".", "prototype", ".", "log", ",", "function", "(", "func", ",", "msg", ")", "{", "func", "(", "self", ".", "constructor", ".", "name", "+", "': '", "+", "msg", ")", ";", "}", ")", ";", "this", ".", "log", "=", "DeviceLoader", ".", "prototype", ".", "log", ";", "}", "else", "{", "var", "debug", "=", "require", "(", "'debug'", ")", "(", "this", ".", "constructor", ".", "name", ")", ";", "this", ".", "log", "=", "function", "(", "msg", ")", "{", "debug", "(", "msg", ")", ";", "}", ";", "}", "this", ".", "lookupIntervalId", "=", "null", ";", "this", ".", "oldDevices", "=", "[", "]", ";", "this", ".", "isRunning", "=", "false", ";", "}" ]
A deviceloader can check if there are available some devices.
[ "A", "deviceloader", "can", "check", "if", "there", "are", "available", "some", "devices", "." ]
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/deviceloader.js#L8-L38
train
koopjs/koop-logger
index.js
createLogger
function createLogger (config) { config = config || {} let level if (process.env.KOOP_LOG_LEVEL) { level = process.env.KOOP_LOG_LEVEL } else if (process.env.NODE_ENV === 'production') { level = 'info' } else { level = 'debug' } if (!config.logfile) { // no logfile defined, log to STDOUT an STDERRv const debugConsole = new winston.transports.Console({ colorize: process.env.NODE_ENV === 'production', level, stringify: true, json: true }) return new winston.Logger({ transports: [debugConsole] }) } // we need a dir to do log rotation so we get the dir from the file const logpath = path.dirname(config.logfile) const logAll = new winston.transports.File({ filename: config.logfile, name: 'log.all', dirname: logpath, colorize: true, json: false, level, formatter: formatter }) const logError = new winston.transports.File({ filename: config.logfile.replace('.log', '.error.log'), name: 'log.error', dirname: logpath, colorize: true, json: false, level: 'error', formatter: formatter }) // always log errors const transports = [logError] // only log everthing if debug mode is on if (process.env['LOG_LEVEL'] === 'debug') { transports.push(logAll) } return new winston.Logger({ transports }) }
javascript
function createLogger (config) { config = config || {} let level if (process.env.KOOP_LOG_LEVEL) { level = process.env.KOOP_LOG_LEVEL } else if (process.env.NODE_ENV === 'production') { level = 'info' } else { level = 'debug' } if (!config.logfile) { // no logfile defined, log to STDOUT an STDERRv const debugConsole = new winston.transports.Console({ colorize: process.env.NODE_ENV === 'production', level, stringify: true, json: true }) return new winston.Logger({ transports: [debugConsole] }) } // we need a dir to do log rotation so we get the dir from the file const logpath = path.dirname(config.logfile) const logAll = new winston.transports.File({ filename: config.logfile, name: 'log.all', dirname: logpath, colorize: true, json: false, level, formatter: formatter }) const logError = new winston.transports.File({ filename: config.logfile.replace('.log', '.error.log'), name: 'log.error', dirname: logpath, colorize: true, json: false, level: 'error', formatter: formatter }) // always log errors const transports = [logError] // only log everthing if debug mode is on if (process.env['LOG_LEVEL'] === 'debug') { transports.push(logAll) } return new winston.Logger({ transports }) }
[ "function", "createLogger", "(", "config", ")", "{", "config", "=", "config", "||", "{", "}", "let", "level", "if", "(", "process", ".", "env", ".", "KOOP_LOG_LEVEL", ")", "{", "level", "=", "process", ".", "env", ".", "KOOP_LOG_LEVEL", "}", "else", "if", "(", "process", ".", "env", ".", "NODE_ENV", "===", "'production'", ")", "{", "level", "=", "'info'", "}", "else", "{", "level", "=", "'debug'", "}", "if", "(", "!", "config", ".", "logfile", ")", "{", "const", "debugConsole", "=", "new", "winston", ".", "transports", ".", "Console", "(", "{", "colorize", ":", "process", ".", "env", ".", "NODE_ENV", "===", "'production'", ",", "level", ",", "stringify", ":", "true", ",", "json", ":", "true", "}", ")", "return", "new", "winston", ".", "Logger", "(", "{", "transports", ":", "[", "debugConsole", "]", "}", ")", "}", "const", "logpath", "=", "path", ".", "dirname", "(", "config", ".", "logfile", ")", "const", "logAll", "=", "new", "winston", ".", "transports", ".", "File", "(", "{", "filename", ":", "config", ".", "logfile", ",", "name", ":", "'log.all'", ",", "dirname", ":", "logpath", ",", "colorize", ":", "true", ",", "json", ":", "false", ",", "level", ",", "formatter", ":", "formatter", "}", ")", "const", "logError", "=", "new", "winston", ".", "transports", ".", "File", "(", "{", "filename", ":", "config", ".", "logfile", ".", "replace", "(", "'.log'", ",", "'.error.log'", ")", ",", "name", ":", "'log.error'", ",", "dirname", ":", "logpath", ",", "colorize", ":", "true", ",", "json", ":", "false", ",", "level", ":", "'error'", ",", "formatter", ":", "formatter", "}", ")", "const", "transports", "=", "[", "logError", "]", "if", "(", "process", ".", "env", "[", "'LOG_LEVEL'", "]", "===", "'debug'", ")", "{", "transports", ".", "push", "(", "logAll", ")", "}", "return", "new", "winston", ".", "Logger", "(", "{", "transports", "}", ")", "}" ]
creates new custom winston logger @param {object} config - koop configuration @return {Logger} custom logger instance
[ "creates", "new", "custom", "winston", "logger" ]
dce77f5ef23955b94514f97e9935f6011f035372
https://github.com/koopjs/koop-logger/blob/dce77f5ef23955b94514f97e9935f6011f035372/index.js#L11-L62
train
koopjs/koop-logger
index.js
formatter
function formatter (options) { const line = [ new Date().toISOString(), options.level ] if (options.message !== undefined) line.push(options.message) if (options.meta && Object.keys(options.meta).length) line.push(JSON.stringify(options.meta)) return line.join(' ') }
javascript
function formatter (options) { const line = [ new Date().toISOString(), options.level ] if (options.message !== undefined) line.push(options.message) if (options.meta && Object.keys(options.meta).length) line.push(JSON.stringify(options.meta)) return line.join(' ') }
[ "function", "formatter", "(", "options", ")", "{", "const", "line", "=", "[", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ",", "options", ".", "level", "]", "if", "(", "options", ".", "message", "!==", "undefined", ")", "line", ".", "push", "(", "options", ".", "message", ")", "if", "(", "options", ".", "meta", "&&", "Object", ".", "keys", "(", "options", ".", "meta", ")", ".", "length", ")", "line", ".", "push", "(", "JSON", ".", "stringify", "(", "options", ".", "meta", ")", ")", "return", "line", ".", "join", "(", "' '", ")", "}" ]
formats winston log lines @param {object} options - log info from winston @return {string} formatted log line
[ "formats", "winston", "log", "lines" ]
dce77f5ef23955b94514f97e9935f6011f035372
https://github.com/koopjs/koop-logger/blob/dce77f5ef23955b94514f97e9935f6011f035372/index.js#L69-L80
train
roboncode/tang
lib/helpers/difference.js
difference
function difference(object, base) { return transform(object, (result, value, key) => { if (!isEqual(value, base[key])) { result[key] = isObject(value) && isObject(base[key]) ? difference(value, base[key]) : value; } }); }
javascript
function difference(object, base) { return transform(object, (result, value, key) => { if (!isEqual(value, base[key])) { result[key] = isObject(value) && isObject(base[key]) ? difference(value, base[key]) : value; } }); }
[ "function", "difference", "(", "object", ",", "base", ")", "{", "return", "transform", "(", "object", ",", "(", "result", ",", "value", ",", "key", ")", "=>", "{", "if", "(", "!", "isEqual", "(", "value", ",", "base", "[", "key", "]", ")", ")", "{", "result", "[", "key", "]", "=", "isObject", "(", "value", ")", "&&", "isObject", "(", "base", "[", "key", "]", ")", "?", "difference", "(", "value", ",", "base", "[", "key", "]", ")", ":", "value", ";", "}", "}", ")", ";", "}" ]
Deep diff between two object, using lodash @param {Object} object Object compared @param {Object} base Object to compare with @return {Object} Return a new object who represent the diff
[ "Deep", "diff", "between", "two", "object", "using", "lodash" ]
3e3826be0e1a621faf3eeea8c769dd28343fb326
https://github.com/roboncode/tang/blob/3e3826be0e1a621faf3eeea8c769dd28343fb326/lib/helpers/difference.js#L16-L22
train
keyCat/node-steamspy
lib/steamspy.js
function ( method, params, cb ) { if ( typeof params === 'function' ) { cb = params; params = {}; } params = extend(params, {request: method}); this.__request({ method: 'get', url: this.options.api_url, qs: params }, function ( err, response, data ) { if ( err ) { cb(err, response, data); } else { try { data = JSON.parse(data); } catch ( parseError ) { cb(new Error('Status Code: ' + response.statusCode), response, data); } if ( response.statusCode === 200 ) { cb(null, response, data); } else { cb(new Error('Status Code: ' + response.statusCode), response, data); } } }); }
javascript
function ( method, params, cb ) { if ( typeof params === 'function' ) { cb = params; params = {}; } params = extend(params, {request: method}); this.__request({ method: 'get', url: this.options.api_url, qs: params }, function ( err, response, data ) { if ( err ) { cb(err, response, data); } else { try { data = JSON.parse(data); } catch ( parseError ) { cb(new Error('Status Code: ' + response.statusCode), response, data); } if ( response.statusCode === 200 ) { cb(null, response, data); } else { cb(new Error('Status Code: ' + response.statusCode), response, data); } } }); }
[ "function", "(", "method", ",", "params", ",", "cb", ")", "{", "if", "(", "typeof", "params", "===", "'function'", ")", "{", "cb", "=", "params", ";", "params", "=", "{", "}", ";", "}", "params", "=", "extend", "(", "params", ",", "{", "request", ":", "method", "}", ")", ";", "this", ".", "__request", "(", "{", "method", ":", "'get'", ",", "url", ":", "this", ".", "options", ".", "api_url", ",", "qs", ":", "params", "}", ",", "function", "(", "err", ",", "response", ",", "data", ")", "{", "if", "(", "err", ")", "{", "cb", "(", "err", ",", "response", ",", "data", ")", ";", "}", "else", "{", "try", "{", "data", "=", "JSON", ".", "parse", "(", "data", ")", ";", "}", "catch", "(", "parseError", ")", "{", "cb", "(", "new", "Error", "(", "'Status Code: '", "+", "response", ".", "statusCode", ")", ",", "response", ",", "data", ")", ";", "}", "if", "(", "response", ".", "statusCode", "===", "200", ")", "{", "cb", "(", "null", ",", "response", ",", "data", ")", ";", "}", "else", "{", "cb", "(", "new", "Error", "(", "'Status Code: '", "+", "response", ".", "statusCode", ")", ",", "response", ",", "data", ")", ";", "}", "}", "}", ")", ";", "}" ]
Makes a single request to SteamSpy API. Use this in case of absence of shorthands @param {String} method API request method (e.g 'appdetails', 'top100in2weeks') @param {Object} params API request parameters applied to URL querystring (e.g {appid: 730}) @param {SteamSpy~requestCallback} cb Callback executed after API response
[ "Makes", "a", "single", "request", "to", "SteamSpy", "API", ".", "Use", "this", "in", "case", "of", "absence", "of", "shorthands" ]
ee93def99fbfa842d3eef9580d80ab2d703105b3
https://github.com/keyCat/node-steamspy/blob/ee93def99fbfa842d3eef9580d80ab2d703105b3/lib/steamspy.js#L48-L75
train
ben-eb/biquad
index.js
_createBiquadFilter
function _createBiquadFilter (defaults) { return function (context, opts) { if (audioContext) { opts = context; context = audioContext; } opts = assign(opts, defaults); var filter = context.createBiquadFilter(); Object.keys(opts).forEach(function (option) { if (option !== 'type') { filter[option].value = opts[option]; } else { filter.type = opts[option]; } }); return filter; }; }
javascript
function _createBiquadFilter (defaults) { return function (context, opts) { if (audioContext) { opts = context; context = audioContext; } opts = assign(opts, defaults); var filter = context.createBiquadFilter(); Object.keys(opts).forEach(function (option) { if (option !== 'type') { filter[option].value = opts[option]; } else { filter.type = opts[option]; } }); return filter; }; }
[ "function", "_createBiquadFilter", "(", "defaults", ")", "{", "return", "function", "(", "context", ",", "opts", ")", "{", "if", "(", "audioContext", ")", "{", "opts", "=", "context", ";", "context", "=", "audioContext", ";", "}", "opts", "=", "assign", "(", "opts", ",", "defaults", ")", ";", "var", "filter", "=", "context", ".", "createBiquadFilter", "(", ")", ";", "Object", ".", "keys", "(", "opts", ")", ".", "forEach", "(", "function", "(", "option", ")", "{", "if", "(", "option", "!==", "'type'", ")", "{", "filter", "[", "option", "]", ".", "value", "=", "opts", "[", "option", "]", ";", "}", "else", "{", "filter", ".", "type", "=", "opts", "[", "option", "]", ";", "}", "}", ")", ";", "return", "filter", ";", "}", ";", "}" ]
Thin biquad filter creation wrapper. @param {Object} defaults Default options (usually just type) @api private
[ "Thin", "biquad", "filter", "creation", "wrapper", "." ]
a681aa5d4724e9fa716d0600b06d11ab7a8e1882
https://github.com/ben-eb/biquad/blob/a681aa5d4724e9fa716d0600b06d11ab7a8e1882/index.js#L11-L31
train
Losant/bravado-core
lib/collection.js
function(options, ...rest) { Entity.apply(this, [options, ...rest]); this.itemType = options.itemType; this.itemFactory = options.itemFactory; this.body = defaults(options.body, { count: 0, items: [] }); if (options.items) { this.body.items = options.items.map(function(item) { return this.createItemEntity(item); }); this.body.count = this.body.items.length; } }
javascript
function(options, ...rest) { Entity.apply(this, [options, ...rest]); this.itemType = options.itemType; this.itemFactory = options.itemFactory; this.body = defaults(options.body, { count: 0, items: [] }); if (options.items) { this.body.items = options.items.map(function(item) { return this.createItemEntity(item); }); this.body.count = this.body.items.length; } }
[ "function", "(", "options", ",", "...", "rest", ")", "{", "Entity", ".", "apply", "(", "this", ",", "[", "options", ",", "...", "rest", "]", ")", ";", "this", ".", "itemType", "=", "options", ".", "itemType", ";", "this", ".", "itemFactory", "=", "options", ".", "itemFactory", ";", "this", ".", "body", "=", "defaults", "(", "options", ".", "body", ",", "{", "count", ":", "0", ",", "items", ":", "[", "]", "}", ")", ";", "if", "(", "options", ".", "items", ")", "{", "this", ".", "body", ".", "items", "=", "options", ".", "items", ".", "map", "(", "function", "(", "item", ")", "{", "return", "this", ".", "createItemEntity", "(", "item", ")", ";", "}", ")", ";", "this", ".", "body", ".", "count", "=", "this", ".", "body", ".", "items", ".", "length", ";", "}", "}" ]
Object that represents a collection of entities returned by a resource's action
[ "Object", "that", "represents", "a", "collection", "of", "entities", "returned", "by", "a", "resource", "s", "action" ]
df152017e0aff9e575c1f7beaf4ddbb9cd346a7c
https://github.com/Losant/bravado-core/blob/df152017e0aff9e575c1f7beaf4ddbb9cd346a7c/lib/collection.js#L6-L20
train
curiousdannii/glkote-term
src/glkapi.js
set_references
function set_references( vm_options ) { if ( vm_options.Dialog ) { Dialog = vm_options.Dialog; } if ( !Dialog ) { if ( typeof window !== 'undefined' && window.Dialog ) { Dialog = window.Dialog; } else { throw new Error( 'No reference to Dialog' ); } } if ( vm_options.GiDispa ) { GiDispa = vm_options.GiDispa; } else if ( !GiDispa && typeof window !== 'undefined' && window.GiDispa ) { GiDispa = window.GiDispa; } if ( vm_options.GiLoad ) { GiLoad = vm_options.GiLoad; } else if ( !GiLoad && typeof window !== 'undefined' && window.GiLoad ) { GiLoad = window.GiLoad; } if ( vm_options.GlkOte ) { GlkOte = vm_options.GlkOte; } if ( !GlkOte ) { if ( typeof window !== 'undefined' && window.GlkOte ) { GlkOte = window.GlkOte; } else { throw new Error('No reference to GlkOte'); } } }
javascript
function set_references( vm_options ) { if ( vm_options.Dialog ) { Dialog = vm_options.Dialog; } if ( !Dialog ) { if ( typeof window !== 'undefined' && window.Dialog ) { Dialog = window.Dialog; } else { throw new Error( 'No reference to Dialog' ); } } if ( vm_options.GiDispa ) { GiDispa = vm_options.GiDispa; } else if ( !GiDispa && typeof window !== 'undefined' && window.GiDispa ) { GiDispa = window.GiDispa; } if ( vm_options.GiLoad ) { GiLoad = vm_options.GiLoad; } else if ( !GiLoad && typeof window !== 'undefined' && window.GiLoad ) { GiLoad = window.GiLoad; } if ( vm_options.GlkOte ) { GlkOte = vm_options.GlkOte; } if ( !GlkOte ) { if ( typeof window !== 'undefined' && window.GlkOte ) { GlkOte = window.GlkOte; } else { throw new Error('No reference to GlkOte'); } } }
[ "function", "set_references", "(", "vm_options", ")", "{", "if", "(", "vm_options", ".", "Dialog", ")", "{", "Dialog", "=", "vm_options", ".", "Dialog", ";", "}", "if", "(", "!", "Dialog", ")", "{", "if", "(", "typeof", "window", "!==", "'undefined'", "&&", "window", ".", "Dialog", ")", "{", "Dialog", "=", "window", ".", "Dialog", ";", "}", "else", "{", "throw", "new", "Error", "(", "'No reference to Dialog'", ")", ";", "}", "}", "if", "(", "vm_options", ".", "GiDispa", ")", "{", "GiDispa", "=", "vm_options", ".", "GiDispa", ";", "}", "else", "if", "(", "!", "GiDispa", "&&", "typeof", "window", "!==", "'undefined'", "&&", "window", ".", "GiDispa", ")", "{", "GiDispa", "=", "window", ".", "GiDispa", ";", "}", "if", "(", "vm_options", ".", "GiLoad", ")", "{", "GiLoad", "=", "vm_options", ".", "GiLoad", ";", "}", "else", "if", "(", "!", "GiLoad", "&&", "typeof", "window", "!==", "'undefined'", "&&", "window", ".", "GiLoad", ")", "{", "GiLoad", "=", "window", ".", "GiLoad", ";", "}", "if", "(", "vm_options", ".", "GlkOte", ")", "{", "GlkOte", "=", "vm_options", ".", "GlkOte", ";", "}", "if", "(", "!", "GlkOte", ")", "{", "if", "(", "typeof", "window", "!==", "'undefined'", "&&", "window", ".", "GlkOte", ")", "{", "GlkOte", "=", "window", ".", "GlkOte", ";", "}", "else", "{", "throw", "new", "Error", "(", "'No reference to GlkOte'", ")", ";", "}", "}", "}" ]
Set external variable references
[ "Set", "external", "variable", "references" ]
5eda3682a40609d624f4fd7405da58708a61d465
https://github.com/curiousdannii/glkote-term/blob/5eda3682a40609d624f4fd7405da58708a61d465/src/glkapi.js#L74-L125
train
crysalead-js/dom-layer
src/node/patcher/attrs-n-s.js
patch
function patch(element, previous, attrs) { if (!previous && !attrs) { return attrs; } var attrName, ns, name, value, split; previous = previous || {}; attrs = attrs || {}; for (attrName in previous) { if (previous[attrName] && !attrs[attrName]) { split = splitAttrName(attrName); ns = namespaces[split[0]]; name = split[1]; element.removeAttributeNS(ns, name); } } for (attrName in attrs) { value = attrs[attrName]; if (previous[attrName] === value) { continue; } if (value) { split = splitAttrName(attrName); ns = namespaces[split[0]]; name = split[1]; element.setAttributeNS(ns, name, value); } } return attrs; }
javascript
function patch(element, previous, attrs) { if (!previous && !attrs) { return attrs; } var attrName, ns, name, value, split; previous = previous || {}; attrs = attrs || {}; for (attrName in previous) { if (previous[attrName] && !attrs[attrName]) { split = splitAttrName(attrName); ns = namespaces[split[0]]; name = split[1]; element.removeAttributeNS(ns, name); } } for (attrName in attrs) { value = attrs[attrName]; if (previous[attrName] === value) { continue; } if (value) { split = splitAttrName(attrName); ns = namespaces[split[0]]; name = split[1]; element.setAttributeNS(ns, name, value); } } return attrs; }
[ "function", "patch", "(", "element", ",", "previous", ",", "attrs", ")", "{", "if", "(", "!", "previous", "&&", "!", "attrs", ")", "{", "return", "attrs", ";", "}", "var", "attrName", ",", "ns", ",", "name", ",", "value", ",", "split", ";", "previous", "=", "previous", "||", "{", "}", ";", "attrs", "=", "attrs", "||", "{", "}", ";", "for", "(", "attrName", "in", "previous", ")", "{", "if", "(", "previous", "[", "attrName", "]", "&&", "!", "attrs", "[", "attrName", "]", ")", "{", "split", "=", "splitAttrName", "(", "attrName", ")", ";", "ns", "=", "namespaces", "[", "split", "[", "0", "]", "]", ";", "name", "=", "split", "[", "1", "]", ";", "element", ".", "removeAttributeNS", "(", "ns", ",", "name", ")", ";", "}", "}", "for", "(", "attrName", "in", "attrs", ")", "{", "value", "=", "attrs", "[", "attrName", "]", ";", "if", "(", "previous", "[", "attrName", "]", "===", "value", ")", "{", "continue", ";", "}", "if", "(", "value", ")", "{", "split", "=", "splitAttrName", "(", "attrName", ")", ";", "ns", "=", "namespaces", "[", "split", "[", "0", "]", "]", ";", "name", "=", "split", "[", "1", "]", ";", "element", ".", "setAttributeNS", "(", "ns", ",", "name", ",", "value", ")", ";", "}", "}", "return", "attrs", ";", "}" ]
Maintains state of element namespaced attributes. @param Object element A DOM element. @param Object previous The previous state of attributes. @param Object attrs The attributes to match on. @return Object attrs The element attributes state.
[ "Maintains", "state", "of", "element", "namespaced", "attributes", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/patcher/attrs-n-s.js#L18-L47
train
etylsarin/gulp-ssi
lib/ssiparser.js
getFile
function getFile(filepath) { var fileObj = { path: filepath, content: null }; try { fs.accessSync(filepath, fs.F_OK); } catch(e) { console.log(e.message); return fileObj; } fileObj.content = fs.readFileSync(filepath, 'utf-8').trim(); return fileObj; }
javascript
function getFile(filepath) { var fileObj = { path: filepath, content: null }; try { fs.accessSync(filepath, fs.F_OK); } catch(e) { console.log(e.message); return fileObj; } fileObj.content = fs.readFileSync(filepath, 'utf-8').trim(); return fileObj; }
[ "function", "getFile", "(", "filepath", ")", "{", "var", "fileObj", "=", "{", "path", ":", "filepath", ",", "content", ":", "null", "}", ";", "try", "{", "fs", ".", "accessSync", "(", "filepath", ",", "fs", ".", "F_OK", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "e", ".", "message", ")", ";", "return", "fileObj", ";", "}", "fileObj", ".", "content", "=", "fs", ".", "readFileSync", "(", "filepath", ",", "'utf-8'", ")", ".", "trim", "(", ")", ";", "return", "fileObj", ";", "}" ]
Helper which gets a file content
[ "Helper", "which", "gets", "a", "file", "content" ]
d39e5caf21310d06c24302065520c9b52c3ebc56
https://github.com/etylsarin/gulp-ssi/blob/d39e5caf21310d06c24302065520c9b52c3ebc56/lib/ssiparser.js#L6-L19
train
bigpipe/floppy
index.js
Floppy
function Floppy(url, fn) { if (!(this instanceof Floppy)) return new Floppy(url, fn); this.readyState = Floppy.LOADING; this.start = +new Date(); this.callbacks = []; this.dependent = 0; this.cleanup = []; this.url = url; if ('function' === typeof fn) { this.add(fn); } }
javascript
function Floppy(url, fn) { if (!(this instanceof Floppy)) return new Floppy(url, fn); this.readyState = Floppy.LOADING; this.start = +new Date(); this.callbacks = []; this.dependent = 0; this.cleanup = []; this.url = url; if ('function' === typeof fn) { this.add(fn); } }
[ "function", "Floppy", "(", "url", ",", "fn", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Floppy", ")", ")", "return", "new", "Floppy", "(", "url", ",", "fn", ")", ";", "this", ".", "readyState", "=", "Floppy", ".", "LOADING", ";", "this", ".", "start", "=", "+", "new", "Date", "(", ")", ";", "this", ".", "callbacks", "=", "[", "]", ";", "this", ".", "dependent", "=", "0", ";", "this", ".", "cleanup", "=", "[", "]", ";", "this", ".", "url", "=", "url", ";", "if", "(", "'function'", "===", "typeof", "fn", ")", "{", "this", ".", "add", "(", "fn", ")", ";", "}", "}" ]
Representation of one single file that will be loaded. @constructor @param {String} url The file URL. @param {Function} fn Optional callback. @api private
[ "Representation", "of", "one", "single", "file", "that", "will", "be", "loaded", "." ]
907540a107c378ea14d9d40b05c625b43e151489
https://github.com/bigpipe/floppy/blob/907540a107c378ea14d9d40b05c625b43e151489/index.js#L11-L24
train
harmon25/msfrpc-client
lib/translate-response.js
translateResponse
function translateResponse(obj){ for(var k in obj){ if(obj[k] instanceof Array){ for(var i=0;i<obj[k].length;i++){ // just an array of strings if(obj[k][i] instanceof Buffer){ obj[k][i] = obj[k][i].toString() } else { // and array of objects.. for(var k1 in obj[k][i]){ if(obj[k][i][k1] instanceof Buffer){ obj[k][i][k1] = obj[k][i][k1].toString() } } } } } else if(obj[k] instanceof Buffer) { obj[k] = obj[k].toString() } else { for(var rk in obj[k]){ if(obj[k][rk] instanceof Buffer){ obj[k][rk] = obj[k][rk].toString() } else if(obj[k][rk] instanceof Array){ for(var i=0;i<obj[k][rk].length;i++){ if(obj[k][rk][i] instanceof Buffer){ obj[k][rk][i] = obj[k][rk][i].toString() } else { obj[k][rk][i] = obj[k][rk][i]; } } } } } } return obj }
javascript
function translateResponse(obj){ for(var k in obj){ if(obj[k] instanceof Array){ for(var i=0;i<obj[k].length;i++){ // just an array of strings if(obj[k][i] instanceof Buffer){ obj[k][i] = obj[k][i].toString() } else { // and array of objects.. for(var k1 in obj[k][i]){ if(obj[k][i][k1] instanceof Buffer){ obj[k][i][k1] = obj[k][i][k1].toString() } } } } } else if(obj[k] instanceof Buffer) { obj[k] = obj[k].toString() } else { for(var rk in obj[k]){ if(obj[k][rk] instanceof Buffer){ obj[k][rk] = obj[k][rk].toString() } else if(obj[k][rk] instanceof Array){ for(var i=0;i<obj[k][rk].length;i++){ if(obj[k][rk][i] instanceof Buffer){ obj[k][rk][i] = obj[k][rk][i].toString() } else { obj[k][rk][i] = obj[k][rk][i]; } } } } } } return obj }
[ "function", "translateResponse", "(", "obj", ")", "{", "for", "(", "var", "k", "in", "obj", ")", "{", "if", "(", "obj", "[", "k", "]", "instanceof", "Array", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "obj", "[", "k", "]", ".", "length", ";", "i", "++", ")", "{", "if", "(", "obj", "[", "k", "]", "[", "i", "]", "instanceof", "Buffer", ")", "{", "obj", "[", "k", "]", "[", "i", "]", "=", "obj", "[", "k", "]", "[", "i", "]", ".", "toString", "(", ")", "}", "else", "{", "for", "(", "var", "k1", "in", "obj", "[", "k", "]", "[", "i", "]", ")", "{", "if", "(", "obj", "[", "k", "]", "[", "i", "]", "[", "k1", "]", "instanceof", "Buffer", ")", "{", "obj", "[", "k", "]", "[", "i", "]", "[", "k1", "]", "=", "obj", "[", "k", "]", "[", "i", "]", "[", "k1", "]", ".", "toString", "(", ")", "}", "}", "}", "}", "}", "else", "if", "(", "obj", "[", "k", "]", "instanceof", "Buffer", ")", "{", "obj", "[", "k", "]", "=", "obj", "[", "k", "]", ".", "toString", "(", ")", "}", "else", "{", "for", "(", "var", "rk", "in", "obj", "[", "k", "]", ")", "{", "if", "(", "obj", "[", "k", "]", "[", "rk", "]", "instanceof", "Buffer", ")", "{", "obj", "[", "k", "]", "[", "rk", "]", "=", "obj", "[", "k", "]", "[", "rk", "]", ".", "toString", "(", ")", "}", "else", "if", "(", "obj", "[", "k", "]", "[", "rk", "]", "instanceof", "Array", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "obj", "[", "k", "]", "[", "rk", "]", ".", "length", ";", "i", "++", ")", "{", "if", "(", "obj", "[", "k", "]", "[", "rk", "]", "[", "i", "]", "instanceof", "Buffer", ")", "{", "obj", "[", "k", "]", "[", "rk", "]", "[", "i", "]", "=", "obj", "[", "k", "]", "[", "rk", "]", "[", "i", "]", ".", "toString", "(", ")", "}", "else", "{", "obj", "[", "k", "]", "[", "rk", "]", "[", "i", "]", "=", "obj", "[", "k", "]", "[", "rk", "]", "[", "i", "]", ";", "}", "}", "}", "}", "}", "}", "return", "obj", "}" ]
could probably do this with some kinda recursion, but whatever..cleaner than before...
[ "could", "probably", "do", "this", "with", "some", "kinda", "recursion", "but", "whatever", "..", "cleaner", "than", "before", "..." ]
9ea2385f73dd8d5225f553d0c27737b24a2ccec8
https://github.com/harmon25/msfrpc-client/blob/9ea2385f73dd8d5225f553d0c27737b24a2ccec8/lib/translate-response.js#L2-L37
train
henrytseng/hostr
lib/router.js
function(req) { if(!req || !req.url) return false; if(typeof(path) === 'string') { return (req.url).match(path) && ((req.url).match(path).index === 0); // RegExp } else { return (req.url).match(path) !== null; } }
javascript
function(req) { if(!req || !req.url) return false; if(typeof(path) === 'string') { return (req.url).match(path) && ((req.url).match(path).index === 0); // RegExp } else { return (req.url).match(path) !== null; } }
[ "function", "(", "req", ")", "{", "if", "(", "!", "req", "||", "!", "req", ".", "url", ")", "return", "false", ";", "if", "(", "typeof", "(", "path", ")", "===", "'string'", ")", "{", "return", "(", "req", ".", "url", ")", ".", "match", "(", "path", ")", "&&", "(", "(", "req", ".", "url", ")", ".", "match", "(", "path", ")", ".", "index", "===", "0", ")", ";", "}", "else", "{", "return", "(", "req", ".", "url", ")", ".", "match", "(", "path", ")", "!==", "null", ";", "}", "}" ]
Check if the route matches @return {Boolean} True if the URL matches and false otherwise
[ "Check", "if", "the", "route", "matches" ]
8ef1ec59d2acdd135eafb19d439519a8d87ff21a
https://github.com/henrytseng/hostr/blob/8ef1ec59d2acdd135eafb19d439519a8d87ff21a/lib/router.js#L24-L34
train
amida-tech/blue-button-cms
lib/sections/commonFunctions.js
ignoreValue
function ignoreValue(value) { if (value === null || value === undefined || value.length === 0) { return true; } if (value.length === 0) { return true; } if (typeof (value) === 'object') { return false; } value = value.toLowerCase(); var ignoreValues = ['not available', 'no information']; for (var x = 0; x < ignoreValues.length; x++) { if (value.indexOf(ignoreValues[x]) >= 0) { return true; } } return false; }
javascript
function ignoreValue(value) { if (value === null || value === undefined || value.length === 0) { return true; } if (value.length === 0) { return true; } if (typeof (value) === 'object') { return false; } value = value.toLowerCase(); var ignoreValues = ['not available', 'no information']; for (var x = 0; x < ignoreValues.length; x++) { if (value.indexOf(ignoreValues[x]) >= 0) { return true; } } return false; }
[ "function", "ignoreValue", "(", "value", ")", "{", "if", "(", "value", "===", "null", "||", "value", "===", "undefined", "||", "value", ".", "length", "===", "0", ")", "{", "return", "true", ";", "}", "if", "(", "value", ".", "length", "===", "0", ")", "{", "return", "true", ";", "}", "if", "(", "typeof", "(", "value", ")", "===", "'object'", ")", "{", "return", "false", ";", "}", "value", "=", "value", ".", "toLowerCase", "(", ")", ";", "var", "ignoreValues", "=", "[", "'not available'", ",", "'no information'", "]", ";", "for", "(", "var", "x", "=", "0", ";", "x", "<", "ignoreValues", ".", "length", ";", "x", "++", ")", "{", "if", "(", "value", ".", "indexOf", "(", "ignoreValues", "[", "x", "]", ")", ">=", "0", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
this function ignores all not avaliable value fields
[ "this", "function", "ignores", "all", "not", "avaliable", "value", "fields" ]
749b8cf071910b22f8176a9ed8fc3b05062e1aad
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/sections/commonFunctions.js#L418-L436
train
pwstegman/pw-lda
index.js
LDA
function LDA(...classes) { // Compute pairwise LDA classes (needed for multiclass LDA) if(classes.length < 2) { throw new Error('Please pass at least 2 classes'); } let numberOfPairs = classes.length * (classes.length - 1) / 2; let pair1 = 0; let pair2 = 1; let pairs = new Array(numberOfPairs); for(let i = 0; i < numberOfPairs; i++){ pairs[i] = computeLdaParams(classes[pair1], classes[pair2], pair1, pair2); pair2++; if(pair2 == classes.length) { pair1++; pair2 = pair1 + 1; } } this.pairs = pairs; this.numberOfClasses = classes.length; }
javascript
function LDA(...classes) { // Compute pairwise LDA classes (needed for multiclass LDA) if(classes.length < 2) { throw new Error('Please pass at least 2 classes'); } let numberOfPairs = classes.length * (classes.length - 1) / 2; let pair1 = 0; let pair2 = 1; let pairs = new Array(numberOfPairs); for(let i = 0; i < numberOfPairs; i++){ pairs[i] = computeLdaParams(classes[pair1], classes[pair2], pair1, pair2); pair2++; if(pair2 == classes.length) { pair1++; pair2 = pair1 + 1; } } this.pairs = pairs; this.numberOfClasses = classes.length; }
[ "function", "LDA", "(", "...", "classes", ")", "{", "if", "(", "classes", ".", "length", "<", "2", ")", "{", "throw", "new", "Error", "(", "'Please pass at least 2 classes'", ")", ";", "}", "let", "numberOfPairs", "=", "classes", ".", "length", "*", "(", "classes", ".", "length", "-", "1", ")", "/", "2", ";", "let", "pair1", "=", "0", ";", "let", "pair2", "=", "1", ";", "let", "pairs", "=", "new", "Array", "(", "numberOfPairs", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "numberOfPairs", ";", "i", "++", ")", "{", "pairs", "[", "i", "]", "=", "computeLdaParams", "(", "classes", "[", "pair1", "]", ",", "classes", "[", "pair2", "]", ",", "pair1", ",", "pair2", ")", ";", "pair2", "++", ";", "if", "(", "pair2", "==", "classes", ".", "length", ")", "{", "pair1", "++", ";", "pair2", "=", "pair1", "+", "1", ";", "}", "}", "this", ".", "pairs", "=", "pairs", ";", "this", ".", "numberOfClasses", "=", "classes", ".", "length", ";", "}" ]
An LDA object. @constructor @param {...number[][]} classes - Each parameter is a 2d class array. In each class array, rows are samples, columns are variables. @example let classifier = new LDA(class1, class2, class3);
[ "An", "LDA", "object", "." ]
4bd875cf746f98e2aa3f9c49cc426aad2980fb33
https://github.com/pwstegman/pw-lda/blob/4bd875cf746f98e2aa3f9c49cc426aad2980fb33/index.js#L15-L39
train
adrai/devicestack
lib/serial/globaldeviceloader.js
function(Device, filter) { var sub = new EventEmitter2({ wildcard: true, delimiter: ':', maxListeners: 1000 // default would be 10! }); sub.Device = Device; sub.filter = filter; sub.oldDevices = []; sub.newDevices = []; /** * Calls the callback with an array of devices. * @param {Array} ports When called within this file this are the listed system ports. [optional] * @param {Function} callback The function, that will be called when finished lookup. * `function(err, devices){}` devices is an array of Device objects. */ sub.lookup = function(ports, callback) { if (!callback) { callback = ports; ports = null; } if (this.newDevices.length > 0) { if (callback) { callback(null, this.newDevices); } return; } else { var self = this; globalSerialDeviceLoader.lookup(function(err) { if (err && !err.name) { err = new Error(err); } if (callback) { callback(err, self.newDevices); } }); } }; /** * Calls lookup function with optional callback * and emits 'plug' for new attached devices * and 'unplug' for removed devices. * @param {Function} callback The function, that will be called when finished triggering. [optional] * `function(err, devices){}` devices is an array of Device objects. */ sub.trigger = function(callback) { var self = this; globalSerialDeviceLoader.trigger(function(err) { if (err && !err.name) { err = new Error(err); } if (callback) { callback(err, self.newDevices); } }); }; /** * Starts to lookup. * @param {Number} interval The interval milliseconds. [optional] * @param {Function} callback The function, that will be called when trigger has started. [optional] * `function(err, devices){}` devices is an array of Device objects. */ sub.startLookup = function(interval, callback) { if (!callback && _.isFunction(interval)) { callback = interval; interval = null; } subscribers.push(this); var self = this; if (isRunning) { if (callback) { callback(null, self.newDevices); } return; } else { globalSerialDeviceLoader.startLookup(interval, function(err) { if (err && !err.name) { err = new Error(err); } if (callback) { callback(err, self.newDevices); } }); } }; /** * Removes itself as subscriber. * If last stops the interval that calls trigger function. */ sub.stopLookup = function() { var self = this; if (!isRunning) { return; } else { subscribers = _.reject(function(s) { return s === self; }); if (subscribers.length === 0) { globalSerialDeviceLoader.stopLookup(); } return; } }; return sub; }
javascript
function(Device, filter) { var sub = new EventEmitter2({ wildcard: true, delimiter: ':', maxListeners: 1000 // default would be 10! }); sub.Device = Device; sub.filter = filter; sub.oldDevices = []; sub.newDevices = []; /** * Calls the callback with an array of devices. * @param {Array} ports When called within this file this are the listed system ports. [optional] * @param {Function} callback The function, that will be called when finished lookup. * `function(err, devices){}` devices is an array of Device objects. */ sub.lookup = function(ports, callback) { if (!callback) { callback = ports; ports = null; } if (this.newDevices.length > 0) { if (callback) { callback(null, this.newDevices); } return; } else { var self = this; globalSerialDeviceLoader.lookup(function(err) { if (err && !err.name) { err = new Error(err); } if (callback) { callback(err, self.newDevices); } }); } }; /** * Calls lookup function with optional callback * and emits 'plug' for new attached devices * and 'unplug' for removed devices. * @param {Function} callback The function, that will be called when finished triggering. [optional] * `function(err, devices){}` devices is an array of Device objects. */ sub.trigger = function(callback) { var self = this; globalSerialDeviceLoader.trigger(function(err) { if (err && !err.name) { err = new Error(err); } if (callback) { callback(err, self.newDevices); } }); }; /** * Starts to lookup. * @param {Number} interval The interval milliseconds. [optional] * @param {Function} callback The function, that will be called when trigger has started. [optional] * `function(err, devices){}` devices is an array of Device objects. */ sub.startLookup = function(interval, callback) { if (!callback && _.isFunction(interval)) { callback = interval; interval = null; } subscribers.push(this); var self = this; if (isRunning) { if (callback) { callback(null, self.newDevices); } return; } else { globalSerialDeviceLoader.startLookup(interval, function(err) { if (err && !err.name) { err = new Error(err); } if (callback) { callback(err, self.newDevices); } }); } }; /** * Removes itself as subscriber. * If last stops the interval that calls trigger function. */ sub.stopLookup = function() { var self = this; if (!isRunning) { return; } else { subscribers = _.reject(function(s) { return s === self; }); if (subscribers.length === 0) { globalSerialDeviceLoader.stopLookup(); } return; } }; return sub; }
[ "function", "(", "Device", ",", "filter", ")", "{", "var", "sub", "=", "new", "EventEmitter2", "(", "{", "wildcard", ":", "true", ",", "delimiter", ":", "':'", ",", "maxListeners", ":", "1000", "}", ")", ";", "sub", ".", "Device", "=", "Device", ";", "sub", ".", "filter", "=", "filter", ";", "sub", ".", "oldDevices", "=", "[", "]", ";", "sub", ".", "newDevices", "=", "[", "]", ";", "sub", ".", "lookup", "=", "function", "(", "ports", ",", "callback", ")", "{", "if", "(", "!", "callback", ")", "{", "callback", "=", "ports", ";", "ports", "=", "null", ";", "}", "if", "(", "this", ".", "newDevices", ".", "length", ">", "0", ")", "{", "if", "(", "callback", ")", "{", "callback", "(", "null", ",", "this", ".", "newDevices", ")", ";", "}", "return", ";", "}", "else", "{", "var", "self", "=", "this", ";", "globalSerialDeviceLoader", ".", "lookup", "(", "function", "(", "err", ")", "{", "if", "(", "err", "&&", "!", "err", ".", "name", ")", "{", "err", "=", "new", "Error", "(", "err", ")", ";", "}", "if", "(", "callback", ")", "{", "callback", "(", "err", ",", "self", ".", "newDevices", ")", ";", "}", "}", ")", ";", "}", "}", ";", "sub", ".", "trigger", "=", "function", "(", "callback", ")", "{", "var", "self", "=", "this", ";", "globalSerialDeviceLoader", ".", "trigger", "(", "function", "(", "err", ")", "{", "if", "(", "err", "&&", "!", "err", ".", "name", ")", "{", "err", "=", "new", "Error", "(", "err", ")", ";", "}", "if", "(", "callback", ")", "{", "callback", "(", "err", ",", "self", ".", "newDevices", ")", ";", "}", "}", ")", ";", "}", ";", "sub", ".", "startLookup", "=", "function", "(", "interval", ",", "callback", ")", "{", "if", "(", "!", "callback", "&&", "_", ".", "isFunction", "(", "interval", ")", ")", "{", "callback", "=", "interval", ";", "interval", "=", "null", ";", "}", "subscribers", ".", "push", "(", "this", ")", ";", "var", "self", "=", "this", ";", "if", "(", "isRunning", ")", "{", "if", "(", "callback", ")", "{", "callback", "(", "null", ",", "self", ".", "newDevices", ")", ";", "}", "return", ";", "}", "else", "{", "globalSerialDeviceLoader", ".", "startLookup", "(", "interval", ",", "function", "(", "err", ")", "{", "if", "(", "err", "&&", "!", "err", ".", "name", ")", "{", "err", "=", "new", "Error", "(", "err", ")", ";", "}", "if", "(", "callback", ")", "{", "callback", "(", "err", ",", "self", ".", "newDevices", ")", ";", "}", "}", ")", ";", "}", "}", ";", "sub", ".", "stopLookup", "=", "function", "(", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "isRunning", ")", "{", "return", ";", "}", "else", "{", "subscribers", "=", "_", ".", "reject", "(", "function", "(", "s", ")", "{", "return", "s", "===", "self", ";", "}", ")", ";", "if", "(", "subscribers", ".", "length", "===", "0", ")", "{", "globalSerialDeviceLoader", ".", "stopLookup", "(", ")", ";", "}", "return", ";", "}", "}", ";", "return", "sub", ";", "}" ]
Creates a deviceloader. @param {Object} Device The constructor function of the device. @param {Function} filter The filter function that will filter the needed devices. @return {Object} Represents a SerialDeviceLoader.
[ "Creates", "a", "deviceloader", "." ]
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/serial/globaldeviceloader.js#L18-L120
train
adrai/devicestack
lib/serial/globaldeviceloader.js
function(callback) { sp.list(function(err, ports) { if (err && !err.name) { err = new Error(err); } if (err && callback) { return callback(err); } async.forEach(subscribers, function(s, callback) { if (s) { var resPorts = s.filter(ports); var devices = _.map(resPorts, function(p) { var found = _.find(s.oldDevices, function(dev) { return dev.get('portName') && p.comName && dev.get('portName').toLowerCase() === p.comName.toLowerCase(); }); if (found) { return found; } else { var newDev = new s.Device(p.comName); newDev.set(p); return newDev; } }) || []; s.newDevices = devices; } callback(null); }, function(err) { if (err && !err.name) { err = new Error(err); } if (callback) { return callback(err); } }); }); }
javascript
function(callback) { sp.list(function(err, ports) { if (err && !err.name) { err = new Error(err); } if (err && callback) { return callback(err); } async.forEach(subscribers, function(s, callback) { if (s) { var resPorts = s.filter(ports); var devices = _.map(resPorts, function(p) { var found = _.find(s.oldDevices, function(dev) { return dev.get('portName') && p.comName && dev.get('portName').toLowerCase() === p.comName.toLowerCase(); }); if (found) { return found; } else { var newDev = new s.Device(p.comName); newDev.set(p); return newDev; } }) || []; s.newDevices = devices; } callback(null); }, function(err) { if (err && !err.name) { err = new Error(err); } if (callback) { return callback(err); } }); }); }
[ "function", "(", "callback", ")", "{", "sp", ".", "list", "(", "function", "(", "err", ",", "ports", ")", "{", "if", "(", "err", "&&", "!", "err", ".", "name", ")", "{", "err", "=", "new", "Error", "(", "err", ")", ";", "}", "if", "(", "err", "&&", "callback", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "async", ".", "forEach", "(", "subscribers", ",", "function", "(", "s", ",", "callback", ")", "{", "if", "(", "s", ")", "{", "var", "resPorts", "=", "s", ".", "filter", "(", "ports", ")", ";", "var", "devices", "=", "_", ".", "map", "(", "resPorts", ",", "function", "(", "p", ")", "{", "var", "found", "=", "_", ".", "find", "(", "s", ".", "oldDevices", ",", "function", "(", "dev", ")", "{", "return", "dev", ".", "get", "(", "'portName'", ")", "&&", "p", ".", "comName", "&&", "dev", ".", "get", "(", "'portName'", ")", ".", "toLowerCase", "(", ")", "===", "p", ".", "comName", ".", "toLowerCase", "(", ")", ";", "}", ")", ";", "if", "(", "found", ")", "{", "return", "found", ";", "}", "else", "{", "var", "newDev", "=", "new", "s", ".", "Device", "(", "p", ".", "comName", ")", ";", "newDev", ".", "set", "(", "p", ")", ";", "return", "newDev", ";", "}", "}", ")", "||", "[", "]", ";", "s", ".", "newDevices", "=", "devices", ";", "}", "callback", "(", "null", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", "&&", "!", "err", ".", "name", ")", "{", "err", "=", "new", "Error", "(", "err", ")", ";", "}", "if", "(", "callback", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Calls the callback when finished. @param {Function} callback The function, that will be called when finished lookup. `function(err){}`
[ "Calls", "the", "callback", "when", "finished", "." ]
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/serial/globaldeviceloader.js#L127-L162
train
adrai/devicestack
lib/serial/globaldeviceloader.js
function(callback) { globalSerialDeviceLoader.lookup(function(err) { if (err && !err.name) { err = new Error(err); } if (err && callback) { return callback(err); } async.forEach(subscribers, function(s, callback) { if (s && s.oldDevices.length !== s.newDevices.length) { var devs = []; if (s.oldDevices.length > s.newDevices.length) { devs = _.difference(s.oldDevices, s.newDevices); _.each(devs, function(d) { if (s.log) s.log('unplug device with id ' + device.id); if (d.close) { d.close(); } s.emit('unplug', d); }); } else { devs = _.difference(s.newDevices, s.oldDevices); _.each(devs, function(d) { if (s.log) s.log('plug device with id ' + device.id); s.emit('plug', d); }); } s.oldDevices = s.newDevices; } callback(null); }, function(err) { if (err && !err.name) { err = new Error(err); } if (callback) { return callback(err); } }); }); }
javascript
function(callback) { globalSerialDeviceLoader.lookup(function(err) { if (err && !err.name) { err = new Error(err); } if (err && callback) { return callback(err); } async.forEach(subscribers, function(s, callback) { if (s && s.oldDevices.length !== s.newDevices.length) { var devs = []; if (s.oldDevices.length > s.newDevices.length) { devs = _.difference(s.oldDevices, s.newDevices); _.each(devs, function(d) { if (s.log) s.log('unplug device with id ' + device.id); if (d.close) { d.close(); } s.emit('unplug', d); }); } else { devs = _.difference(s.newDevices, s.oldDevices); _.each(devs, function(d) { if (s.log) s.log('plug device with id ' + device.id); s.emit('plug', d); }); } s.oldDevices = s.newDevices; } callback(null); }, function(err) { if (err && !err.name) { err = new Error(err); } if (callback) { return callback(err); } }); }); }
[ "function", "(", "callback", ")", "{", "globalSerialDeviceLoader", ".", "lookup", "(", "function", "(", "err", ")", "{", "if", "(", "err", "&&", "!", "err", ".", "name", ")", "{", "err", "=", "new", "Error", "(", "err", ")", ";", "}", "if", "(", "err", "&&", "callback", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "async", ".", "forEach", "(", "subscribers", ",", "function", "(", "s", ",", "callback", ")", "{", "if", "(", "s", "&&", "s", ".", "oldDevices", ".", "length", "!==", "s", ".", "newDevices", ".", "length", ")", "{", "var", "devs", "=", "[", "]", ";", "if", "(", "s", ".", "oldDevices", ".", "length", ">", "s", ".", "newDevices", ".", "length", ")", "{", "devs", "=", "_", ".", "difference", "(", "s", ".", "oldDevices", ",", "s", ".", "newDevices", ")", ";", "_", ".", "each", "(", "devs", ",", "function", "(", "d", ")", "{", "if", "(", "s", ".", "log", ")", "s", ".", "log", "(", "'unplug device with id '", "+", "device", ".", "id", ")", ";", "if", "(", "d", ".", "close", ")", "{", "d", ".", "close", "(", ")", ";", "}", "s", ".", "emit", "(", "'unplug'", ",", "d", ")", ";", "}", ")", ";", "}", "else", "{", "devs", "=", "_", ".", "difference", "(", "s", ".", "newDevices", ",", "s", ".", "oldDevices", ")", ";", "_", ".", "each", "(", "devs", ",", "function", "(", "d", ")", "{", "if", "(", "s", ".", "log", ")", "s", ".", "log", "(", "'plug device with id '", "+", "device", ".", "id", ")", ";", "s", ".", "emit", "(", "'plug'", ",", "d", ")", ";", "}", ")", ";", "}", "s", ".", "oldDevices", "=", "s", ".", "newDevices", ";", "}", "callback", "(", "null", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", "&&", "!", "err", ".", "name", ")", "{", "err", "=", "new", "Error", "(", "err", ")", ";", "}", "if", "(", "callback", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Calls lookup function with optional callback and emits 'plug' for new attached devices and 'unplug' for removed devices. @param {Function} callback The function, that will be called when finished triggering. [optional] `function(err){}`
[ "Calls", "lookup", "function", "with", "optional", "callback", "and", "emits", "plug", "for", "new", "attached", "devices", "and", "unplug", "for", "removed", "devices", "." ]
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/serial/globaldeviceloader.js#L171-L210
train
adrai/devicestack
lib/serial/globaldeviceloader.js
function(interval, callback) { if (lookupIntervalId) { return; } isRunning = true; if (!callback && _.isFunction(interval)) { callback = interval; interval = null; } interval = interval || 500; globalSerialDeviceLoader.trigger(function(err) { var triggering = false; lookupIntervalId = setInterval(function() { if (triggering) return; triggering = true; globalSerialDeviceLoader.trigger(function() { triggering = false; }); }, interval); if (err && !err.name) { err = new Error(err); } if (callback) { callback(err); } }); }
javascript
function(interval, callback) { if (lookupIntervalId) { return; } isRunning = true; if (!callback && _.isFunction(interval)) { callback = interval; interval = null; } interval = interval || 500; globalSerialDeviceLoader.trigger(function(err) { var triggering = false; lookupIntervalId = setInterval(function() { if (triggering) return; triggering = true; globalSerialDeviceLoader.trigger(function() { triggering = false; }); }, interval); if (err && !err.name) { err = new Error(err); } if (callback) { callback(err); } }); }
[ "function", "(", "interval", ",", "callback", ")", "{", "if", "(", "lookupIntervalId", ")", "{", "return", ";", "}", "isRunning", "=", "true", ";", "if", "(", "!", "callback", "&&", "_", ".", "isFunction", "(", "interval", ")", ")", "{", "callback", "=", "interval", ";", "interval", "=", "null", ";", "}", "interval", "=", "interval", "||", "500", ";", "globalSerialDeviceLoader", ".", "trigger", "(", "function", "(", "err", ")", "{", "var", "triggering", "=", "false", ";", "lookupIntervalId", "=", "setInterval", "(", "function", "(", ")", "{", "if", "(", "triggering", ")", "return", ";", "triggering", "=", "true", ";", "globalSerialDeviceLoader", ".", "trigger", "(", "function", "(", ")", "{", "triggering", "=", "false", ";", "}", ")", ";", "}", ",", "interval", ")", ";", "if", "(", "err", "&&", "!", "err", ".", "name", ")", "{", "err", "=", "new", "Error", "(", "err", ")", ";", "}", "if", "(", "callback", ")", "{", "callback", "(", "err", ")", ";", "}", "}", ")", ";", "}" ]
Starts to lookup. @param {Number} interval The interval milliseconds. [optional] @param {Function} callback The function, that will be called when trigger has started. [optional] `function(err){}`
[ "Starts", "to", "lookup", "." ]
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/serial/globaldeviceloader.js#L218-L247
train
Toxiapo/ardorjs
util/curve25519.js
cpy32
function cpy32 (d, s) { for (var i = 0; i < 32; i++) d[i] = s[i]; }
javascript
function cpy32 (d, s) { for (var i = 0; i < 32; i++) d[i] = s[i]; }
[ "function", "cpy32", "(", "d", ",", "s", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "32", ";", "i", "++", ")", "d", "[", "i", "]", "=", "s", "[", "i", "]", ";", "}" ]
endregion region radix 2^8 math
[ "endregion", "region", "radix", "2^8", "math" ]
0e312739b420476c4f9f6c072b84930401aa12a8
https://github.com/Toxiapo/ardorjs/blob/0e312739b420476c4f9f6c072b84930401aa12a8/util/curve25519.js#L87-L90
train
gegeyang0124/react-native-navigation-cus
src/views/Header/HeaderStyleInterpolator.js
forLeftButton
function forLeftButton(props) { const { position, scene, scenes } = props; const interpolate = getSceneIndicesForInterpolationInputRange(props); if (!interpolate) return { opacity: 0 }; const { first, last } = interpolate; const index = scene.index; return { opacity: position.interpolate({ inputRange: [ first, first + Math.abs(index - first) / 2, index, last - Math.abs(last - index) / 2, last, ], outputRange: [0, 0.5, 1, 0.5, 0], }), }; }
javascript
function forLeftButton(props) { const { position, scene, scenes } = props; const interpolate = getSceneIndicesForInterpolationInputRange(props); if (!interpolate) return { opacity: 0 }; const { first, last } = interpolate; const index = scene.index; return { opacity: position.interpolate({ inputRange: [ first, first + Math.abs(index - first) / 2, index, last - Math.abs(last - index) / 2, last, ], outputRange: [0, 0.5, 1, 0.5, 0], }), }; }
[ "function", "forLeftButton", "(", "props", ")", "{", "const", "{", "position", ",", "scene", ",", "scenes", "}", "=", "props", ";", "const", "interpolate", "=", "getSceneIndicesForInterpolationInputRange", "(", "props", ")", ";", "if", "(", "!", "interpolate", ")", "return", "{", "opacity", ":", "0", "}", ";", "const", "{", "first", ",", "last", "}", "=", "interpolate", ";", "const", "index", "=", "scene", ".", "index", ";", "return", "{", "opacity", ":", "position", ".", "interpolate", "(", "{", "inputRange", ":", "[", "first", ",", "first", "+", "Math", ".", "abs", "(", "index", "-", "first", ")", "/", "2", ",", "index", ",", "last", "-", "Math", ".", "abs", "(", "last", "-", "index", ")", "/", "2", ",", "last", ",", "]", ",", "outputRange", ":", "[", "0", ",", "0.5", ",", "1", ",", "0.5", ",", "0", "]", ",", "}", ")", ",", "}", ";", "}" ]
iOS UINavigationController style interpolators
[ "iOS", "UINavigationController", "style", "interpolators" ]
37bf130e0a459ed8f8671ebf87efcb425aaeb775
https://github.com/gegeyang0124/react-native-navigation-cus/blob/37bf130e0a459ed8f8671ebf87efcb425aaeb775/src/views/Header/HeaderStyleInterpolator.js#L65-L86
train
DenisCarriere/slippy-grid
index.js
all
function all (extent, minZoom, maxZoom) { const tiles = [] const grid = single(extent, minZoom, maxZoom) while (true) { const {value, done} = grid.next() if (done) break tiles.push(value) } return tiles }
javascript
function all (extent, minZoom, maxZoom) { const tiles = [] const grid = single(extent, minZoom, maxZoom) while (true) { const {value, done} = grid.next() if (done) break tiles.push(value) } return tiles }
[ "function", "all", "(", "extent", ",", "minZoom", ",", "maxZoom", ")", "{", "const", "tiles", "=", "[", "]", "const", "grid", "=", "single", "(", "extent", ",", "minZoom", ",", "maxZoom", ")", "while", "(", "true", ")", "{", "const", "{", "value", ",", "done", "}", "=", "grid", ".", "next", "(", ")", "if", "(", "done", ")", "break", "tiles", ".", "push", "(", "value", ")", "}", "return", "tiles", "}" ]
All Tiles from a given BBox @param {BBox|BBox[]|GeoJSON} extent BBox [west, south, east, north] order or GeoJSON Polygon @param {number} minZoom Minimum Zoom @param {number} maxZoom Maximum Zoom @returns {Array<Tile>} Tiles from extent @example const tiles = slippyGrid.all([-180.0, -90.0, 180, 90], 3, 8) //=tiles
[ "All", "Tiles", "from", "a", "given", "BBox" ]
6bc936925441598543eafbdd83076257fe3e712b
https://github.com/DenisCarriere/slippy-grid/blob/6bc936925441598543eafbdd83076257fe3e712b/index.js#L108-L117
train
DenisCarriere/slippy-grid
index.js
levels
function levels (extent, minZoom, maxZoom) { const extents = [] if (extent === undefined) throw new Error('extent is required') if (minZoom === undefined) throw new Error('minZoom is required') if (maxZoom === undefined) throw new Error('maxZoom is required') // Single Array if (extent.length === 4 && extent[0][0] === undefined) { extents.push({bbox: extent, minZoom, maxZoom}) } // Multiple Array if (extent.length && extent[0][0] !== undefined) { extent.map(inner => extents.push({bbox: inner, minZoom, maxZoom})) } // GeoJSON featureEach(extent, feature => { const bbox = turfBBox(feature) const featureMinZoom = feature.properties.minZoom || feature.properties.minzoom || minZoom const featureMaxZoom = feature.properties.maxZoom || feature.properties.maxzoom || maxZoom extents.push({bbox, minZoom: featureMinZoom, maxZoom: featureMaxZoom}) }) const levels = [] for (const {bbox, minZoom, maxZoom} of extents) { let [x1, y1, x2, y2] = bbox for (const zoom of range(minZoom, maxZoom + 1)) { if (y2 > 85) y2 = 85 if (y2 < -85) y2 = -85 const t1 = lngLatToTile([x1, y1], zoom) const t2 = lngLatToTile([x2, y2], zoom) // Columns let columns = [] // Fiji - World divided into two parts if (t1[0] > t2[0]) { // right world +180 degrees const maxtx = Math.pow(2, zoom) - 1 const rightColumns = range(t1[0], maxtx + 1) rightColumns.forEach(column => columns.push(column)) // left world -180 degrees const mintx = 0 const leftColumns = range(mintx, t2[0] + 1) leftColumns.forEach(column => columns.push(column)) } else { // Normal World const mintx = Math.min(t1[0], t2[0]) const maxtx = Math.max(t1[0], t2[0]) columns = range(mintx, maxtx + 1) } // Rows const minty = Math.min(t1[1], t2[1]) const maxty = Math.max(t1[1], t2[1]) const rows = range(minty, maxty + 1) levels.push([columns, rows, zoom]) } } return levels }
javascript
function levels (extent, minZoom, maxZoom) { const extents = [] if (extent === undefined) throw new Error('extent is required') if (minZoom === undefined) throw new Error('minZoom is required') if (maxZoom === undefined) throw new Error('maxZoom is required') // Single Array if (extent.length === 4 && extent[0][0] === undefined) { extents.push({bbox: extent, minZoom, maxZoom}) } // Multiple Array if (extent.length && extent[0][0] !== undefined) { extent.map(inner => extents.push({bbox: inner, minZoom, maxZoom})) } // GeoJSON featureEach(extent, feature => { const bbox = turfBBox(feature) const featureMinZoom = feature.properties.minZoom || feature.properties.minzoom || minZoom const featureMaxZoom = feature.properties.maxZoom || feature.properties.maxzoom || maxZoom extents.push({bbox, minZoom: featureMinZoom, maxZoom: featureMaxZoom}) }) const levels = [] for (const {bbox, minZoom, maxZoom} of extents) { let [x1, y1, x2, y2] = bbox for (const zoom of range(minZoom, maxZoom + 1)) { if (y2 > 85) y2 = 85 if (y2 < -85) y2 = -85 const t1 = lngLatToTile([x1, y1], zoom) const t2 = lngLatToTile([x2, y2], zoom) // Columns let columns = [] // Fiji - World divided into two parts if (t1[0] > t2[0]) { // right world +180 degrees const maxtx = Math.pow(2, zoom) - 1 const rightColumns = range(t1[0], maxtx + 1) rightColumns.forEach(column => columns.push(column)) // left world -180 degrees const mintx = 0 const leftColumns = range(mintx, t2[0] + 1) leftColumns.forEach(column => columns.push(column)) } else { // Normal World const mintx = Math.min(t1[0], t2[0]) const maxtx = Math.max(t1[0], t2[0]) columns = range(mintx, maxtx + 1) } // Rows const minty = Math.min(t1[1], t2[1]) const maxty = Math.max(t1[1], t2[1]) const rows = range(minty, maxty + 1) levels.push([columns, rows, zoom]) } } return levels }
[ "function", "levels", "(", "extent", ",", "minZoom", ",", "maxZoom", ")", "{", "const", "extents", "=", "[", "]", "if", "(", "extent", "===", "undefined", ")", "throw", "new", "Error", "(", "'extent is required'", ")", "if", "(", "minZoom", "===", "undefined", ")", "throw", "new", "Error", "(", "'minZoom is required'", ")", "if", "(", "maxZoom", "===", "undefined", ")", "throw", "new", "Error", "(", "'maxZoom is required'", ")", "if", "(", "extent", ".", "length", "===", "4", "&&", "extent", "[", "0", "]", "[", "0", "]", "===", "undefined", ")", "{", "extents", ".", "push", "(", "{", "bbox", ":", "extent", ",", "minZoom", ",", "maxZoom", "}", ")", "}", "if", "(", "extent", ".", "length", "&&", "extent", "[", "0", "]", "[", "0", "]", "!==", "undefined", ")", "{", "extent", ".", "map", "(", "inner", "=>", "extents", ".", "push", "(", "{", "bbox", ":", "inner", ",", "minZoom", ",", "maxZoom", "}", ")", ")", "}", "featureEach", "(", "extent", ",", "feature", "=>", "{", "const", "bbox", "=", "turfBBox", "(", "feature", ")", "const", "featureMinZoom", "=", "feature", ".", "properties", ".", "minZoom", "||", "feature", ".", "properties", ".", "minzoom", "||", "minZoom", "const", "featureMaxZoom", "=", "feature", ".", "properties", ".", "maxZoom", "||", "feature", ".", "properties", ".", "maxzoom", "||", "maxZoom", "extents", ".", "push", "(", "{", "bbox", ",", "minZoom", ":", "featureMinZoom", ",", "maxZoom", ":", "featureMaxZoom", "}", ")", "}", ")", "const", "levels", "=", "[", "]", "for", "(", "const", "{", "bbox", ",", "minZoom", ",", "maxZoom", "}", "of", "extents", ")", "{", "let", "[", "x1", ",", "y1", ",", "x2", ",", "y2", "]", "=", "bbox", "for", "(", "const", "zoom", "of", "range", "(", "minZoom", ",", "maxZoom", "+", "1", ")", ")", "{", "if", "(", "y2", ">", "85", ")", "y2", "=", "85", "if", "(", "y2", "<", "-", "85", ")", "y2", "=", "-", "85", "const", "t1", "=", "lngLatToTile", "(", "[", "x1", ",", "y1", "]", ",", "zoom", ")", "const", "t2", "=", "lngLatToTile", "(", "[", "x2", ",", "y2", "]", ",", "zoom", ")", "let", "columns", "=", "[", "]", "if", "(", "t1", "[", "0", "]", ">", "t2", "[", "0", "]", ")", "{", "const", "maxtx", "=", "Math", ".", "pow", "(", "2", ",", "zoom", ")", "-", "1", "const", "rightColumns", "=", "range", "(", "t1", "[", "0", "]", ",", "maxtx", "+", "1", ")", "rightColumns", ".", "forEach", "(", "column", "=>", "columns", ".", "push", "(", "column", ")", ")", "const", "mintx", "=", "0", "const", "leftColumns", "=", "range", "(", "mintx", ",", "t2", "[", "0", "]", "+", "1", ")", "leftColumns", ".", "forEach", "(", "column", "=>", "columns", ".", "push", "(", "column", ")", ")", "}", "else", "{", "const", "mintx", "=", "Math", ".", "min", "(", "t1", "[", "0", "]", ",", "t2", "[", "0", "]", ")", "const", "maxtx", "=", "Math", ".", "max", "(", "t1", "[", "0", "]", ",", "t2", "[", "0", "]", ")", "columns", "=", "range", "(", "mintx", ",", "maxtx", "+", "1", ")", "}", "const", "minty", "=", "Math", ".", "min", "(", "t1", "[", "1", "]", ",", "t2", "[", "1", "]", ")", "const", "maxty", "=", "Math", ".", "max", "(", "t1", "[", "1", "]", ",", "t2", "[", "1", "]", ")", "const", "rows", "=", "range", "(", "minty", ",", "maxty", "+", "1", ")", "levels", ".", "push", "(", "[", "columns", ",", "rows", ",", "zoom", "]", ")", "}", "}", "return", "levels", "}" ]
Creates a grid level pattern of arrays @param {BBox|BBox[]|GeoJSON} extent BBox [west, south, east, north] order or GeoJSON Polygon @param {number} minZoom Minimum Zoom @param {number} maxZoom Maximum Zoom @returns {GridLevel[]} Grid Level @example const levels = slippyGrid.levels([-180.0, -90.0, 180, 90], 3, 8) //=levels
[ "Creates", "a", "grid", "level", "pattern", "of", "arrays" ]
6bc936925441598543eafbdd83076257fe3e712b
https://github.com/DenisCarriere/slippy-grid/blob/6bc936925441598543eafbdd83076257fe3e712b/index.js#L165-L222
train
DenisCarriere/slippy-grid
index.js
count
function count (extent, minZoom, maxZoom, quick) { quick = quick || 1000 let count = 0 // Quick count if (quick !== -1) { for (const [columns, rows] of levels(extent, minZoom, maxZoom)) { count += rows.length * columns.length } if (count > quick) { return count } } // Accurate count count = 0 const grid = single(extent, minZoom, maxZoom) while (true) { const {done} = grid.next() if (done) { break } count++ } return count }
javascript
function count (extent, minZoom, maxZoom, quick) { quick = quick || 1000 let count = 0 // Quick count if (quick !== -1) { for (const [columns, rows] of levels(extent, minZoom, maxZoom)) { count += rows.length * columns.length } if (count > quick) { return count } } // Accurate count count = 0 const grid = single(extent, minZoom, maxZoom) while (true) { const {done} = grid.next() if (done) { break } count++ } return count }
[ "function", "count", "(", "extent", ",", "minZoom", ",", "maxZoom", ",", "quick", ")", "{", "quick", "=", "quick", "||", "1000", "let", "count", "=", "0", "if", "(", "quick", "!==", "-", "1", ")", "{", "for", "(", "const", "[", "columns", ",", "rows", "]", "of", "levels", "(", "extent", ",", "minZoom", ",", "maxZoom", ")", ")", "{", "count", "+=", "rows", ".", "length", "*", "columns", ".", "length", "}", "if", "(", "count", ">", "quick", ")", "{", "return", "count", "}", "}", "count", "=", "0", "const", "grid", "=", "single", "(", "extent", ",", "minZoom", ",", "maxZoom", ")", "while", "(", "true", ")", "{", "const", "{", "done", "}", "=", "grid", ".", "next", "(", ")", "if", "(", "done", ")", "{", "break", "}", "count", "++", "}", "return", "count", "}" ]
Counts the total amount of tiles from a given BBox @param {BBox|BBox[]|GeoJSON} extent BBox [west, south, east, north] order or GeoJSON Polygon @param {number} minZoom Minimum Zoom @param {number} maxZoom Maximum Zoom @param {number} [quick=1000] Enable quick count if greater than number @returns {number} Total tiles from BBox @example const count = slippyGrid.count([-180.0, -90.0, 180, 90], 3, 8) //=count 563136
[ "Counts", "the", "total", "amount", "of", "tiles", "from", "a", "given", "BBox" ]
6bc936925441598543eafbdd83076257fe3e712b
https://github.com/DenisCarriere/slippy-grid/blob/6bc936925441598543eafbdd83076257fe3e712b/index.js#L236-L257
train
base/base-env
lib/env.js
normalize
function normalize(file, fn) { var orig = utils.extend({}, file); // support paths if (typeof fn === 'string') { file.type = 'path'; file.path = fn; file.origPath = fn; file = resolve(file, file.options); // support functions } else if (typeof fn === 'function') { file.type = 'function'; file.path = file.name; file.fn = fn; // support instances } else if (utils.isAppArg(file.app)) { file.type = 'app'; file.path = file.name; file.app = fn; } else { throw new TypeError('expected env to be a string or function'); } if (file === null) { var name = typeof fn === 'string' ? fn : orig.key; throw new Error('cannot resolve: ' + util.inspect(name)); } return file; }
javascript
function normalize(file, fn) { var orig = utils.extend({}, file); // support paths if (typeof fn === 'string') { file.type = 'path'; file.path = fn; file.origPath = fn; file = resolve(file, file.options); // support functions } else if (typeof fn === 'function') { file.type = 'function'; file.path = file.name; file.fn = fn; // support instances } else if (utils.isAppArg(file.app)) { file.type = 'app'; file.path = file.name; file.app = fn; } else { throw new TypeError('expected env to be a string or function'); } if (file === null) { var name = typeof fn === 'string' ? fn : orig.key; throw new Error('cannot resolve: ' + util.inspect(name)); } return file; }
[ "function", "normalize", "(", "file", ",", "fn", ")", "{", "var", "orig", "=", "utils", ".", "extend", "(", "{", "}", ",", "file", ")", ";", "if", "(", "typeof", "fn", "===", "'string'", ")", "{", "file", ".", "type", "=", "'path'", ";", "file", ".", "path", "=", "fn", ";", "file", ".", "origPath", "=", "fn", ";", "file", "=", "resolve", "(", "file", ",", "file", ".", "options", ")", ";", "}", "else", "if", "(", "typeof", "fn", "===", "'function'", ")", "{", "file", ".", "type", "=", "'function'", ";", "file", ".", "path", "=", "file", ".", "name", ";", "file", ".", "fn", "=", "fn", ";", "}", "else", "if", "(", "utils", ".", "isAppArg", "(", "file", ".", "app", ")", ")", "{", "file", ".", "type", "=", "'app'", ";", "file", ".", "path", "=", "file", ".", "name", ";", "file", ".", "app", "=", "fn", ";", "}", "else", "{", "throw", "new", "TypeError", "(", "'expected env to be a string or function'", ")", ";", "}", "if", "(", "file", "===", "null", ")", "{", "var", "name", "=", "typeof", "fn", "===", "'string'", "?", "fn", ":", "orig", ".", "key", ";", "throw", "new", "Error", "(", "'cannot resolve: '", "+", "util", ".", "inspect", "(", "name", ")", ")", ";", "}", "return", "file", ";", "}" ]
Create a file object with normalized `fn`, `path` or `app` properties
[ "Create", "a", "file", "object", "with", "normalized", "fn", "path", "or", "app", "properties" ]
2140c8f12e3d21aba443666a481d71f15da900c2
https://github.com/base/base-env/blob/2140c8f12e3d21aba443666a481d71f15da900c2/lib/env.js#L196-L227
train
node-modules/antpb
lib/encoder.js
genTypePartial
function genTypePartial(gen, field, fieldIndex, ref) { return field.resolvedType.group ? gen('types[%i].encode(%s,w.uint32(%i)).uint32(%i)', fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0) : gen('types[%i].encode(%s,w.uint32(%i).fork()).ldelim()', fieldIndex, ref, (field.id << 3 | 2) >>> 0); }
javascript
function genTypePartial(gen, field, fieldIndex, ref) { return field.resolvedType.group ? gen('types[%i].encode(%s,w.uint32(%i)).uint32(%i)', fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0) : gen('types[%i].encode(%s,w.uint32(%i).fork()).ldelim()', fieldIndex, ref, (field.id << 3 | 2) >>> 0); }
[ "function", "genTypePartial", "(", "gen", ",", "field", ",", "fieldIndex", ",", "ref", ")", "{", "return", "field", ".", "resolvedType", ".", "group", "?", "gen", "(", "'types[%i].encode(%s,w.uint32(%i)).uint32(%i)'", ",", "fieldIndex", ",", "ref", ",", "(", "field", ".", "id", "<<", "3", "|", "3", ")", ">>>", "0", ",", "(", "field", ".", "id", "<<", "3", "|", "4", ")", ">>>", "0", ")", ":", "gen", "(", "'types[%i].encode(%s,w.uint32(%i).fork()).ldelim()'", ",", "fieldIndex", ",", "ref", ",", "(", "field", ".", "id", "<<", "3", "|", "2", ")", ">>>", "0", ")", ";", "}" ]
Generates a partial message type encoder. @param {Codegen} gen Codegen instance @param {Field} field Reflected field @param {number} fieldIndex Field index @param {string} ref Variable reference @return {Codegen} Codegen instance @ignore
[ "Generates", "a", "partial", "message", "type", "encoder", "." ]
e6d74d4c372151fcb3880eb44a4e85907d99405c
https://github.com/node-modules/antpb/blob/e6d74d4c372151fcb3880eb44a4e85907d99405c/lib/encoder.js#L17-L21
train
crysalead-js/dom-layer
src/node/patcher/attrs.js
patch
function patch(element, previous, attrs) { if (!previous && !attrs) { return attrs; } var name, value; previous = previous || {}; attrs = attrs || {}; for (name in previous) { if (previous[name] && !attrs[name]) { unset(name, element, previous); } } for (name in attrs) { if (previous[name] === attrs[name]) { continue; } if (attrs[name] || attrs[name] === '') { set(name, element, previous, attrs); } } return attrs; }
javascript
function patch(element, previous, attrs) { if (!previous && !attrs) { return attrs; } var name, value; previous = previous || {}; attrs = attrs || {}; for (name in previous) { if (previous[name] && !attrs[name]) { unset(name, element, previous); } } for (name in attrs) { if (previous[name] === attrs[name]) { continue; } if (attrs[name] || attrs[name] === '') { set(name, element, previous, attrs); } } return attrs; }
[ "function", "patch", "(", "element", ",", "previous", ",", "attrs", ")", "{", "if", "(", "!", "previous", "&&", "!", "attrs", ")", "{", "return", "attrs", ";", "}", "var", "name", ",", "value", ";", "previous", "=", "previous", "||", "{", "}", ";", "attrs", "=", "attrs", "||", "{", "}", ";", "for", "(", "name", "in", "previous", ")", "{", "if", "(", "previous", "[", "name", "]", "&&", "!", "attrs", "[", "name", "]", ")", "{", "unset", "(", "name", ",", "element", ",", "previous", ")", ";", "}", "}", "for", "(", "name", "in", "attrs", ")", "{", "if", "(", "previous", "[", "name", "]", "===", "attrs", "[", "name", "]", ")", "{", "continue", ";", "}", "if", "(", "attrs", "[", "name", "]", "||", "attrs", "[", "name", "]", "===", "''", ")", "{", "set", "(", "name", ",", "element", ",", "previous", ",", "attrs", ")", ";", "}", "}", "return", "attrs", ";", "}" ]
Maintains state of element attributes. @param Object element A DOM element. @param Object previous The previous state of attributes. @param Object attrs The attributes to match on. @return Object attrs The element attributes state.
[ "Maintains", "state", "of", "element", "attributes", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/patcher/attrs.js#L14-L36
train
crysalead-js/dom-layer
src/node/patcher/attrs.js
set
function set(name, element, previous, attrs) { if (set.handlers[name]) { set.handlers[name](name, element, previous, attrs); } else if (attrs[name] != null && previous[name] !== attrs[name]) { element.setAttribute(name, attrs[name]); } }
javascript
function set(name, element, previous, attrs) { if (set.handlers[name]) { set.handlers[name](name, element, previous, attrs); } else if (attrs[name] != null && previous[name] !== attrs[name]) { element.setAttribute(name, attrs[name]); } }
[ "function", "set", "(", "name", ",", "element", ",", "previous", ",", "attrs", ")", "{", "if", "(", "set", ".", "handlers", "[", "name", "]", ")", "{", "set", ".", "handlers", "[", "name", "]", "(", "name", ",", "element", ",", "previous", ",", "attrs", ")", ";", "}", "else", "if", "(", "attrs", "[", "name", "]", "!=", "null", "&&", "previous", "[", "name", "]", "!==", "attrs", "[", "name", "]", ")", "{", "element", ".", "setAttribute", "(", "name", ",", "attrs", "[", "name", "]", ")", ";", "}", "}" ]
Sets an attribute. @param String name The attribute name to set. @param Object element A DOM element. @param Object previous The previous state of attributes. @param Object attrs The attributes to match on.
[ "Sets", "an", "attribute", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/patcher/attrs.js#L46-L52
train
crysalead-js/dom-layer
src/node/patcher/attrs.js
unset
function unset(name, element, previous) { if (unset.handlers[name]) { unset.handlers[name](name, element, previous); } else { element.removeAttribute(name); } }
javascript
function unset(name, element, previous) { if (unset.handlers[name]) { unset.handlers[name](name, element, previous); } else { element.removeAttribute(name); } }
[ "function", "unset", "(", "name", ",", "element", ",", "previous", ")", "{", "if", "(", "unset", ".", "handlers", "[", "name", "]", ")", "{", "unset", ".", "handlers", "[", "name", "]", "(", "name", ",", "element", ",", "previous", ")", ";", "}", "else", "{", "element", ".", "removeAttribute", "(", "name", ")", ";", "}", "}" ]
Unsets an attribute. @param String name The attribute name to unset. @param Object element A DOM element. @param Object previous The previous state of attributes.
[ "Unsets", "an", "attribute", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/patcher/attrs.js#L62-L68
train
DenisCarriere/slippy-grid
dependencies/tilebelt.js
getParent
function getParent(tile) { // top left if (tile[0] % 2 === 0 && tile[1] % 2 === 0) { return [tile[0] / 2, tile[1] / 2, tile[2] - 1]; } // bottom left if ((tile[0] % 2 === 0) && (!tile[1] % 2 === 0)) { return [tile[0] / 2, (tile[1] - 1) / 2, tile[2] - 1]; } // top right if ((!tile[0] % 2 === 0) && (tile[1] % 2 === 0)) { return [(tile[0] - 1) / 2, (tile[1]) / 2, tile[2] - 1]; } // bottom right return [(tile[0] - 1) / 2, (tile[1] - 1) / 2, tile[2] - 1]; }
javascript
function getParent(tile) { // top left if (tile[0] % 2 === 0 && tile[1] % 2 === 0) { return [tile[0] / 2, tile[1] / 2, tile[2] - 1]; } // bottom left if ((tile[0] % 2 === 0) && (!tile[1] % 2 === 0)) { return [tile[0] / 2, (tile[1] - 1) / 2, tile[2] - 1]; } // top right if ((!tile[0] % 2 === 0) && (tile[1] % 2 === 0)) { return [(tile[0] - 1) / 2, (tile[1]) / 2, tile[2] - 1]; } // bottom right return [(tile[0] - 1) / 2, (tile[1] - 1) / 2, tile[2] - 1]; }
[ "function", "getParent", "(", "tile", ")", "{", "if", "(", "tile", "[", "0", "]", "%", "2", "===", "0", "&&", "tile", "[", "1", "]", "%", "2", "===", "0", ")", "{", "return", "[", "tile", "[", "0", "]", "/", "2", ",", "tile", "[", "1", "]", "/", "2", ",", "tile", "[", "2", "]", "-", "1", "]", ";", "}", "if", "(", "(", "tile", "[", "0", "]", "%", "2", "===", "0", ")", "&&", "(", "!", "tile", "[", "1", "]", "%", "2", "===", "0", ")", ")", "{", "return", "[", "tile", "[", "0", "]", "/", "2", ",", "(", "tile", "[", "1", "]", "-", "1", ")", "/", "2", ",", "tile", "[", "2", "]", "-", "1", "]", ";", "}", "if", "(", "(", "!", "tile", "[", "0", "]", "%", "2", "===", "0", ")", "&&", "(", "tile", "[", "1", "]", "%", "2", "===", "0", ")", ")", "{", "return", "[", "(", "tile", "[", "0", "]", "-", "1", ")", "/", "2", ",", "(", "tile", "[", "1", "]", ")", "/", "2", ",", "tile", "[", "2", "]", "-", "1", "]", ";", "}", "return", "[", "(", "tile", "[", "0", "]", "-", "1", ")", "/", "2", ",", "(", "tile", "[", "1", "]", "-", "1", ")", "/", "2", ",", "tile", "[", "2", "]", "-", "1", "]", ";", "}" ]
Get the tile one zoom level lower @name getParent @param {Array<number>} tile @returns {Array<number>} tile @example var tile = getParent([5, 10, 10]) //=tile
[ "Get", "the", "tile", "one", "zoom", "level", "lower" ]
6bc936925441598543eafbdd83076257fe3e712b
https://github.com/DenisCarriere/slippy-grid/blob/6bc936925441598543eafbdd83076257fe3e712b/dependencies/tilebelt.js#L106-L121
train
sakitam-fdd/rollup-plugin-copied
src/index.js
copyFile
function copyFile (src, dest) { return new Promise((resolve, reject) => { const read = fs.createReadStream(src); read.on('error', reject); const write = fs.createWriteStream(dest); write.on('error', reject); write.on('finish', resolve); read.pipe(write); }) }
javascript
function copyFile (src, dest) { return new Promise((resolve, reject) => { const read = fs.createReadStream(src); read.on('error', reject); const write = fs.createWriteStream(dest); write.on('error', reject); write.on('finish', resolve); read.pipe(write); }) }
[ "function", "copyFile", "(", "src", ",", "dest", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "read", "=", "fs", ".", "createReadStream", "(", "src", ")", ";", "read", ".", "on", "(", "'error'", ",", "reject", ")", ";", "const", "write", "=", "fs", ".", "createWriteStream", "(", "dest", ")", ";", "write", ".", "on", "(", "'error'", ",", "reject", ")", ";", "write", ".", "on", "(", "'finish'", ",", "resolve", ")", ";", "read", ".", "pipe", "(", "write", ")", ";", "}", ")", "}" ]
copy file to dir @param src @param dest @returns {Promise<any>}
[ "copy", "file", "to", "dir" ]
d9d16f90ea87b958d39ebba5824efce110e25468
https://github.com/sakitam-fdd/rollup-plugin-copied/blob/d9d16f90ea87b958d39ebba5824efce110e25468/src/index.js#L96-L105
train
amida-tech/blue-button-cms
lib/parser.js
parseCMS
function parseCMS(fileString) { var intObj = txtToIntObj(fileString); var result = cmsObjConverter.convertToBBModel(intObj); return result; }
javascript
function parseCMS(fileString) { var intObj = txtToIntObj(fileString); var result = cmsObjConverter.convertToBBModel(intObj); return result; }
[ "function", "parseCMS", "(", "fileString", ")", "{", "var", "intObj", "=", "txtToIntObj", "(", "fileString", ")", ";", "var", "result", "=", "cmsObjConverter", ".", "convertToBBModel", "(", "intObj", ")", ";", "return", "result", ";", "}" ]
parses CMS BB text format into BB JSON
[ "parses", "CMS", "BB", "text", "format", "into", "BB", "JSON" ]
749b8cf071910b22f8176a9ed8fc3b05062e1aad
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/parser.js#L8-L15
train
amida-tech/blue-button-cms
lib/cmsTxtToIntObj.js
clean
function clean(cmsString) { if (cmsString.indexOf('\r\n') >= 0) { cmsString = cmsString.replace(/\r\n/g, '\n'); cmsString = cmsString.replace(/\r/g, '\n'); } cmsString = cmsString.replace(/\n{5,}/g, '\n\n\n\n'); //more than 5 line breaks breaks the parser return cmsString; }
javascript
function clean(cmsString) { if (cmsString.indexOf('\r\n') >= 0) { cmsString = cmsString.replace(/\r\n/g, '\n'); cmsString = cmsString.replace(/\r/g, '\n'); } cmsString = cmsString.replace(/\n{5,}/g, '\n\n\n\n'); //more than 5 line breaks breaks the parser return cmsString; }
[ "function", "clean", "(", "cmsString", ")", "{", "if", "(", "cmsString", ".", "indexOf", "(", "'\\r\\n'", ")", ">=", "\\r", ")", "\\n", "0", "{", "cmsString", "=", "cmsString", ".", "replace", "(", "/", "\\r\\n", "/", "g", ",", "'\\n'", ")", ";", "\\n", "}", "}" ]
main function that will be used to getIntObj
[ "main", "function", "that", "will", "be", "used", "to", "getIntObj" ]
749b8cf071910b22f8176a9ed8fc3b05062e1aad
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/cmsTxtToIntObj.js#L68-L75
train
amida-tech/blue-button-cms
lib/cmsTxtToIntObj.js
separateSections
function separateSections(data) { //Separated regular expression into many distinct pieces //specical metaMatchCode goes first. // 1st regular expression for meta, need to do var metaMatchCode = '^(-).[\\S\\s]+?(\\n){2,}'; //this isn't used anywhere... /* 2nd regular expression for claims, because the structure of claims is unique */ var claimsHeaderMatchCode = '(-){4,}(\\n)*Claim Summary(\\n){2,}(-){4,}'; var claimsBodyMatchCode = '([\\S\\s]+Claim[\\S\\s]+)+'; var claimsEndMatchCode = '(?=((-){4,}))'; var claimsMatchCode = claimsHeaderMatchCode + claimsBodyMatchCode + claimsEndMatchCode; //this match code is for all other sections var headerMatchCode = '(-){4,}[\\S\\s]+?(\\n){2,}(-){4,}'; var bodyMatchCode = '[\\S\\s]+?'; var endMatchCode = '(?=((-){4,}))'; var sectionMatchCode = headerMatchCode + bodyMatchCode + endMatchCode; /* The regular expression for everything, search globally and ignore capitalization */ var totalMatchCode = claimsMatchCode + "|" + sectionMatchCode; var totalRegExp = new RegExp(totalMatchCode, 'gi'); var matchArray = data.match(totalRegExp); return matchArray; }
javascript
function separateSections(data) { //Separated regular expression into many distinct pieces //specical metaMatchCode goes first. // 1st regular expression for meta, need to do var metaMatchCode = '^(-).[\\S\\s]+?(\\n){2,}'; //this isn't used anywhere... /* 2nd regular expression for claims, because the structure of claims is unique */ var claimsHeaderMatchCode = '(-){4,}(\\n)*Claim Summary(\\n){2,}(-){4,}'; var claimsBodyMatchCode = '([\\S\\s]+Claim[\\S\\s]+)+'; var claimsEndMatchCode = '(?=((-){4,}))'; var claimsMatchCode = claimsHeaderMatchCode + claimsBodyMatchCode + claimsEndMatchCode; //this match code is for all other sections var headerMatchCode = '(-){4,}[\\S\\s]+?(\\n){2,}(-){4,}'; var bodyMatchCode = '[\\S\\s]+?'; var endMatchCode = '(?=((-){4,}))'; var sectionMatchCode = headerMatchCode + bodyMatchCode + endMatchCode; /* The regular expression for everything, search globally and ignore capitalization */ var totalMatchCode = claimsMatchCode + "|" + sectionMatchCode; var totalRegExp = new RegExp(totalMatchCode, 'gi'); var matchArray = data.match(totalRegExp); return matchArray; }
[ "function", "separateSections", "(", "data", ")", "{", "var", "metaMatchCode", "=", "'^(-).[\\\\S\\\\s]+?(\\\\n){2,}'", ";", "\\\\", "\\\\", "\\\\", "var", "claimsHeaderMatchCode", "=", "'(-){4,}(\\\\n)*Claim Summary(\\\\n){2,}(-){4,}'", ";", "\\\\", "\\\\", "var", "claimsBodyMatchCode", "=", "'([\\\\S\\\\s]+Claim[\\\\S\\\\s]+)+'", ";", "\\\\", "\\\\", "\\\\", "\\\\", "var", "claimsEndMatchCode", "=", "'(?=((-){4,}))'", ";", "}" ]
Parses string into sections, then returns the array of strings for each section
[ "Parses", "string", "into", "sections", "then", "returns", "the", "array", "of", "strings", "for", "each", "section" ]
749b8cf071910b22f8176a9ed8fc3b05062e1aad
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/cmsTxtToIntObj.js#L80-L108
train
amida-tech/blue-button-cms
lib/cmsTxtToIntObj.js
cleanUpTitle
function cleanUpTitle(rawTitleString) { /*dashChar is most commonly the dash of the title string, or a the first repeating character surrounding the title */ var dashChar = rawTitleString.charAt(0); //beginning and ending index of the dash var dashBegIndex = 0; var dashEndIndex = rawTitleString.lastIndexOf(dashChar); //loop through to find indicies without continous dashes while (rawTitleString.charAt(dashBegIndex) === (dashChar || '\n')) { dashBegIndex++; } while (rawTitleString.charAt(dashEndIndex) === (dashChar || '\n')) { dashEndIndex--; } var titleString = rawTitleString.slice(dashBegIndex + 1, dashEndIndex - 1); titleString = trimStringEnds(titleString, ['\n', '-']); return titleString; }
javascript
function cleanUpTitle(rawTitleString) { /*dashChar is most commonly the dash of the title string, or a the first repeating character surrounding the title */ var dashChar = rawTitleString.charAt(0); //beginning and ending index of the dash var dashBegIndex = 0; var dashEndIndex = rawTitleString.lastIndexOf(dashChar); //loop through to find indicies without continous dashes while (rawTitleString.charAt(dashBegIndex) === (dashChar || '\n')) { dashBegIndex++; } while (rawTitleString.charAt(dashEndIndex) === (dashChar || '\n')) { dashEndIndex--; } var titleString = rawTitleString.slice(dashBegIndex + 1, dashEndIndex - 1); titleString = trimStringEnds(titleString, ['\n', '-']); return titleString; }
[ "function", "cleanUpTitle", "(", "rawTitleString", ")", "{", "var", "dashChar", "=", "rawTitleString", ".", "charAt", "(", "0", ")", ";", "var", "dashBegIndex", "=", "0", ";", "var", "dashEndIndex", "=", "rawTitleString", ".", "lastIndexOf", "(", "dashChar", ")", ";", "while", "(", "rawTitleString", ".", "charAt", "(", "dashBegIndex", ")", "===", "(", "dashChar", "||", "'\\n'", ")", ")", "\\n", "{", "dashBegIndex", "++", ";", "}", "while", "(", "rawTitleString", ".", "charAt", "(", "dashEndIndex", ")", "===", "(", "dashChar", "||", "'\\n'", ")", ")", "\\n", "{", "dashEndIndex", "--", ";", "}", "var", "titleString", "=", "rawTitleString", ".", "slice", "(", "dashBegIndex", "+", "1", ",", "dashEndIndex", "-", "1", ")", ";", "}" ]
cleans up the title string obtained from the regular expression
[ "cleans", "up", "the", "title", "string", "obtained", "from", "the", "regular", "expression" ]
749b8cf071910b22f8176a9ed8fc3b05062e1aad
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/cmsTxtToIntObj.js#L112-L131
train
amida-tech/blue-button-cms
lib/cmsTxtToIntObj.js
processClaimsLineChild
function processClaimsLineChild(objectString) { var claimLineObj = {}; var obj = {}; var objArray = []; var keyValuePairRegExp = /(\n){1,}[\S\s,]+?(:)[\S\s]+?(?=((\n){1,})|$)/gi; var keyValuePairArray = objectString.match(keyValuePairRegExp); //unusual steps are required to parse meta data and claims summary for (var s = 0; s < keyValuePairArray.length; s++) { //clean up the key value pair var keyValuePairString = trimStringEnds(keyValuePairArray[s], ['\n']); //split each string by the :, the result is an array of size two var keyValuePair = keyValuePairString.split(/:(.*)/); var key = removeUnwantedCharacters(keyValuePair[0].trim(), ['\n', '-']); key = key.toLowerCase(); var value = keyValuePair[1].trim(); var claimLineCheckRegExp = /claim lines/i; if (claimLineCheckRegExp.test(key)) { claimLineObj.claimNumber = value; continue; } if (value.length === 0) { value = null; } //create a new object for line number if (key in obj) { objArray.push(obj); obj = {}; } obj[key] = value; } objArray.push(obj); claimLineObj.data = objArray; return claimLineObj; }
javascript
function processClaimsLineChild(objectString) { var claimLineObj = {}; var obj = {}; var objArray = []; var keyValuePairRegExp = /(\n){1,}[\S\s,]+?(:)[\S\s]+?(?=((\n){1,})|$)/gi; var keyValuePairArray = objectString.match(keyValuePairRegExp); //unusual steps are required to parse meta data and claims summary for (var s = 0; s < keyValuePairArray.length; s++) { //clean up the key value pair var keyValuePairString = trimStringEnds(keyValuePairArray[s], ['\n']); //split each string by the :, the result is an array of size two var keyValuePair = keyValuePairString.split(/:(.*)/); var key = removeUnwantedCharacters(keyValuePair[0].trim(), ['\n', '-']); key = key.toLowerCase(); var value = keyValuePair[1].trim(); var claimLineCheckRegExp = /claim lines/i; if (claimLineCheckRegExp.test(key)) { claimLineObj.claimNumber = value; continue; } if (value.length === 0) { value = null; } //create a new object for line number if (key in obj) { objArray.push(obj); obj = {}; } obj[key] = value; } objArray.push(obj); claimLineObj.data = objArray; return claimLineObj; }
[ "function", "processClaimsLineChild", "(", "objectString", ")", "{", "var", "claimLineObj", "=", "{", "}", ";", "var", "obj", "=", "{", "}", ";", "var", "objArray", "=", "[", "]", ";", "var", "keyValuePairRegExp", "=", "/", "(\\n){1,}[\\S\\s,]+?(:)[\\S\\s]+?(?=((\\n){1,})|$)", "/", "gi", ";", "var", "keyValuePairArray", "=", "objectString", ".", "match", "(", "keyValuePairRegExp", ")", ";", "for", "(", "var", "s", "=", "0", ";", "s", "<", "keyValuePairArray", ".", "length", ";", "s", "++", ")", "{", "var", "keyValuePairString", "=", "trimStringEnds", "(", "keyValuePairArray", "[", "s", "]", ",", "[", "'\\n'", "]", ")", ";", "\\n", "var", "keyValuePair", "=", "keyValuePairString", ".", "split", "(", "/", ":(.*)", "/", ")", ";", "var", "key", "=", "removeUnwantedCharacters", "(", "keyValuePair", "[", "0", "]", ".", "trim", "(", ")", ",", "[", "'\\n'", ",", "\\n", "]", ")", ";", "'-'", "key", "=", "key", ".", "toLowerCase", "(", ")", ";", "var", "value", "=", "keyValuePair", "[", "1", "]", ".", "trim", "(", ")", ";", "var", "claimLineCheckRegExp", "=", "/", "claim lines", "/", "i", ";", "if", "(", "claimLineCheckRegExp", ".", "test", "(", "key", ")", ")", "{", "claimLineObj", ".", "claimNumber", "=", "value", ";", "continue", ";", "}", "if", "(", "value", ".", "length", "===", "0", ")", "{", "value", "=", "null", ";", "}", "}", "if", "(", "key", "in", "obj", ")", "{", "objArray", ".", "push", "(", "obj", ")", ";", "obj", "=", "{", "}", ";", "}", "obj", "[", "key", "]", "=", "value", ";", "objArray", ".", "push", "(", "obj", ")", ";", "}" ]
function to process claim section of the document
[ "function", "to", "process", "claim", "section", "of", "the", "document" ]
749b8cf071910b22f8176a9ed8fc3b05062e1aad
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/cmsTxtToIntObj.js#L189-L225
train
amida-tech/blue-button-cms
lib/cmsTxtToIntObj.js
getSectionBody
function getSectionBody(sectionString) { /*first, use regular expressions to parse the section body into different objects */ var sectionBody = {}; var sectionBodyData = []; var objectFromBodyRegExp = /-*(\n){2,}(?!-{4,})[\S\s,]+?((?=((\n){3,}?))|\n\n$)/gi; //or go to the end of the string. var objectStrings = sectionString.match(objectFromBodyRegExp); //process each section object (from string to an actual object) for (var obj = 0; obj < objectStrings.length; obj++) { var sectionChild = processSectionChild(objectStrings[obj]); if (!isEmpty(sectionChild)) { if ('source' in sectionChild) { sectionBody.source = sectionChild.source; } else { sectionBodyData.push(sectionChild); } } } sectionBody.data = sectionBodyData; return sectionBody; }
javascript
function getSectionBody(sectionString) { /*first, use regular expressions to parse the section body into different objects */ var sectionBody = {}; var sectionBodyData = []; var objectFromBodyRegExp = /-*(\n){2,}(?!-{4,})[\S\s,]+?((?=((\n){3,}?))|\n\n$)/gi; //or go to the end of the string. var objectStrings = sectionString.match(objectFromBodyRegExp); //process each section object (from string to an actual object) for (var obj = 0; obj < objectStrings.length; obj++) { var sectionChild = processSectionChild(objectStrings[obj]); if (!isEmpty(sectionChild)) { if ('source' in sectionChild) { sectionBody.source = sectionChild.source; } else { sectionBodyData.push(sectionChild); } } } sectionBody.data = sectionBodyData; return sectionBody; }
[ "function", "getSectionBody", "(", "sectionString", ")", "{", "var", "sectionBody", "=", "{", "}", ";", "var", "sectionBodyData", "=", "[", "]", ";", "var", "objectFromBodyRegExp", "=", "/", "-*(\\n){2,}(?!-{4,})[\\S\\s,]+?((?=((\\n){3,}?))|\\n\\n$)", "/", "gi", ";", "var", "objectStrings", "=", "sectionString", ".", "match", "(", "objectFromBodyRegExp", ")", ";", "for", "(", "var", "obj", "=", "0", ";", "obj", "<", "objectStrings", ".", "length", ";", "obj", "++", ")", "{", "var", "sectionChild", "=", "processSectionChild", "(", "objectStrings", "[", "obj", "]", ")", ";", "if", "(", "!", "isEmpty", "(", "sectionChild", ")", ")", "{", "if", "(", "'source'", "in", "sectionChild", ")", "{", "sectionBody", ".", "source", "=", "sectionChild", ".", "source", ";", "}", "else", "{", "sectionBodyData", ".", "push", "(", "sectionChild", ")", ";", "}", "}", "}", "sectionBody", ".", "data", "=", "sectionBodyData", ";", "return", "sectionBody", ";", "}" ]
parses the section body into an object
[ "parses", "the", "section", "body", "into", "an", "object" ]
749b8cf071910b22f8176a9ed8fc3b05062e1aad
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/cmsTxtToIntObj.js#L266-L290
train
amida-tech/blue-button-cms
lib/cmsTxtToIntObj.js
getMetaBody
function getMetaBody(sectionString) { var sectionBody = {}; var sectionBodyObj = {}; var metaBodyCode = /-{2,}((\n*?\*{3,}[\S\s]+\*{3,})|(\n{2,}))[\S\s]+?\n{3,}/gi; var objectStrings = sectionString.match(metaBodyCode); for (var obj = 0; obj < objectStrings.length; obj++) { var sectionChild = processMetaChild(objectStrings[obj]); if (!isEmpty(sectionChild)) { sectionBodyObj.type = 'cms'; //get only the number from version var versionRegExp = /\(v[\S\s]+?\)/; var version = sectionChild[0].match(versionRegExp)[0]; version = trimStringEnds(version, ['(', ')', 'v']); sectionBodyObj.version = version; sectionBodyObj.timestamp = sectionChild[1]; } } sectionBody.data = [sectionBodyObj]; return sectionBody; }
javascript
function getMetaBody(sectionString) { var sectionBody = {}; var sectionBodyObj = {}; var metaBodyCode = /-{2,}((\n*?\*{3,}[\S\s]+\*{3,})|(\n{2,}))[\S\s]+?\n{3,}/gi; var objectStrings = sectionString.match(metaBodyCode); for (var obj = 0; obj < objectStrings.length; obj++) { var sectionChild = processMetaChild(objectStrings[obj]); if (!isEmpty(sectionChild)) { sectionBodyObj.type = 'cms'; //get only the number from version var versionRegExp = /\(v[\S\s]+?\)/; var version = sectionChild[0].match(versionRegExp)[0]; version = trimStringEnds(version, ['(', ')', 'v']); sectionBodyObj.version = version; sectionBodyObj.timestamp = sectionChild[1]; } } sectionBody.data = [sectionBodyObj]; return sectionBody; }
[ "function", "getMetaBody", "(", "sectionString", ")", "{", "var", "sectionBody", "=", "{", "}", ";", "var", "sectionBodyObj", "=", "{", "}", ";", "var", "metaBodyCode", "=", "/", "-{2,}((\\n*?\\*{3,}[\\S\\s]+\\*{3,})|(\\n{2,}))[\\S\\s]+?\\n{3,}", "/", "gi", ";", "var", "objectStrings", "=", "sectionString", ".", "match", "(", "metaBodyCode", ")", ";", "for", "(", "var", "obj", "=", "0", ";", "obj", "<", "objectStrings", ".", "length", ";", "obj", "++", ")", "{", "var", "sectionChild", "=", "processMetaChild", "(", "objectStrings", "[", "obj", "]", ")", ";", "if", "(", "!", "isEmpty", "(", "sectionChild", ")", ")", "{", "sectionBodyObj", ".", "type", "=", "'cms'", ";", "var", "versionRegExp", "=", "/", "\\(v[\\S\\s]+?\\)", "/", ";", "var", "version", "=", "sectionChild", "[", "0", "]", ".", "match", "(", "versionRegExp", ")", "[", "0", "]", ";", "version", "=", "trimStringEnds", "(", "version", ",", "[", "'('", ",", "')'", ",", "'v'", "]", ")", ";", "sectionBodyObj", ".", "version", "=", "version", ";", "sectionBodyObj", ".", "timestamp", "=", "sectionChild", "[", "1", "]", ";", "}", "}", "sectionBody", ".", "data", "=", "[", "sectionBodyObj", "]", ";", "return", "sectionBody", ";", "}" ]
functions for specific meta characters
[ "functions", "for", "specific", "meta", "characters" ]
749b8cf071910b22f8176a9ed8fc3b05062e1aad
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/cmsTxtToIntObj.js#L394-L414
train
amida-tech/blue-button-cms
lib/cmsTxtToIntObj.js
convertToObject
function convertToObject(sectionString) { var sectionObj = {}; //get the section title(get it raw, clean it) var sectionTitleRegExp = /(-){3,}([\S\s]+?)(-){3,}/; var sectionRawTitle = sectionString.match(sectionTitleRegExp)[0]; var sectionTitle = cleanUpTitle(sectionRawTitle).toLowerCase(); //get the section body var sectionBody; sectionObj.sectionTitle = sectionTitle; //these are very special "edge" cases //meta data/information about document in the beginning of the doc if (sectionTitle.toLowerCase().indexOf("personal health information") >= 0) { delete sectionObj.sectionTitle; sectionObj.sectionTitle = 'meta'; sectionBody = getMetaBody(sectionString); } else if (sectionTitle.toLowerCase().indexOf("claim") >= 0) { sectionBody = getClaimsBody(sectionString); } else { sectionBody = getSectionBody(sectionString); } sectionObj.sectionBody = sectionBody; return sectionObj; }
javascript
function convertToObject(sectionString) { var sectionObj = {}; //get the section title(get it raw, clean it) var sectionTitleRegExp = /(-){3,}([\S\s]+?)(-){3,}/; var sectionRawTitle = sectionString.match(sectionTitleRegExp)[0]; var sectionTitle = cleanUpTitle(sectionRawTitle).toLowerCase(); //get the section body var sectionBody; sectionObj.sectionTitle = sectionTitle; //these are very special "edge" cases //meta data/information about document in the beginning of the doc if (sectionTitle.toLowerCase().indexOf("personal health information") >= 0) { delete sectionObj.sectionTitle; sectionObj.sectionTitle = 'meta'; sectionBody = getMetaBody(sectionString); } else if (sectionTitle.toLowerCase().indexOf("claim") >= 0) { sectionBody = getClaimsBody(sectionString); } else { sectionBody = getSectionBody(sectionString); } sectionObj.sectionBody = sectionBody; return sectionObj; }
[ "function", "convertToObject", "(", "sectionString", ")", "{", "var", "sectionObj", "=", "{", "}", ";", "var", "sectionTitleRegExp", "=", "/", "(-){3,}([\\S\\s]+?)(-){3,}", "/", ";", "var", "sectionRawTitle", "=", "sectionString", ".", "match", "(", "sectionTitleRegExp", ")", "[", "0", "]", ";", "var", "sectionTitle", "=", "cleanUpTitle", "(", "sectionRawTitle", ")", ".", "toLowerCase", "(", ")", ";", "var", "sectionBody", ";", "sectionObj", ".", "sectionTitle", "=", "sectionTitle", ";", "if", "(", "sectionTitle", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "\"personal health information\"", ")", ">=", "0", ")", "{", "delete", "sectionObj", ".", "sectionTitle", ";", "sectionObj", ".", "sectionTitle", "=", "'meta'", ";", "sectionBody", "=", "getMetaBody", "(", "sectionString", ")", ";", "}", "else", "if", "(", "sectionTitle", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "\"claim\"", ")", ">=", "0", ")", "{", "sectionBody", "=", "getClaimsBody", "(", "sectionString", ")", ";", "}", "else", "{", "sectionBody", "=", "getSectionBody", "(", "sectionString", ")", ";", "}", "sectionObj", ".", "sectionBody", "=", "sectionBody", ";", "return", "sectionObj", ";", "}" ]
converts each section to an object representation
[ "converts", "each", "section", "to", "an", "object", "representation" ]
749b8cf071910b22f8176a9ed8fc3b05062e1aad
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/cmsTxtToIntObj.js#L418-L443
train
amida-tech/blue-button-cms
lib/cmsTxtToIntObj.js
getTitles
function getTitles(fileString) { var headerMatchCode = '(-){4,}[\\S\\s]+?(\\n){2,}(-){4,}'; var headerRegExp = new RegExp(headerMatchCode, 'gi'); var rawTitleArray = fileString.match(headerRegExp); var titleArray = []; if (rawTitleArray === null) { return null; } for (var i = 0, len = rawTitleArray.length; i < len; i++) { var tempTitle = cleanUpTitle(rawTitleArray[i]); //exception to the rule, claim lines if (tempTitle.toLowerCase().indexOf("claim lines for claim number") < 0 && tempTitle.length > 0) { titleArray[i] = tempTitle; } } return titleArray; }
javascript
function getTitles(fileString) { var headerMatchCode = '(-){4,}[\\S\\s]+?(\\n){2,}(-){4,}'; var headerRegExp = new RegExp(headerMatchCode, 'gi'); var rawTitleArray = fileString.match(headerRegExp); var titleArray = []; if (rawTitleArray === null) { return null; } for (var i = 0, len = rawTitleArray.length; i < len; i++) { var tempTitle = cleanUpTitle(rawTitleArray[i]); //exception to the rule, claim lines if (tempTitle.toLowerCase().indexOf("claim lines for claim number") < 0 && tempTitle.length > 0) { titleArray[i] = tempTitle; } } return titleArray; }
[ "function", "getTitles", "(", "fileString", ")", "{", "var", "headerMatchCode", "=", "'(-){4,}[\\\\S\\\\s]+?(\\\\n){2,}(-){4,}'", ";", "\\\\", "\\\\", "\\\\", "var", "headerRegExp", "=", "new", "RegExp", "(", "headerMatchCode", ",", "'gi'", ")", ";", "var", "rawTitleArray", "=", "fileString", ".", "match", "(", "headerRegExp", ")", ";", "var", "titleArray", "=", "[", "]", ";", "}" ]
Gets all section titles given the entire data file string
[ "Gets", "all", "section", "titles", "given", "the", "entire", "data", "file", "string" ]
749b8cf071910b22f8176a9ed8fc3b05062e1aad
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/cmsTxtToIntObj.js#L464-L481
train
akoenig/kast
lib/socket.js
Socket
function Socket (options) { this.$ipaddress = ip.address(); this.$port = options.port; this.$host = options.host || '224.1.1.1'; this.$ttl = options.ttl || 128; this.$dispatcher = options.dispatcher; // // The native socket implementation. // Will be filled on opening the socket. // this.$impl = null; }
javascript
function Socket (options) { this.$ipaddress = ip.address(); this.$port = options.port; this.$host = options.host || '224.1.1.1'; this.$ttl = options.ttl || 128; this.$dispatcher = options.dispatcher; // // The native socket implementation. // Will be filled on opening the socket. // this.$impl = null; }
[ "function", "Socket", "(", "options", ")", "{", "this", ".", "$ipaddress", "=", "ip", ".", "address", "(", ")", ";", "this", ".", "$port", "=", "options", ".", "port", ";", "this", ".", "$host", "=", "options", ".", "host", "||", "'224.1.1.1'", ";", "this", ".", "$ttl", "=", "options", ".", "ttl", "||", "128", ";", "this", ".", "$dispatcher", "=", "options", ".", "dispatcher", ";", "this", ".", "$impl", "=", "null", ";", "}" ]
Wrapper around the socket implementation of Node.js with some proxy functionality for incoming messages. @param {object} options A configuration object Should have the following structure: `port`: The respective port on which the multicast socket should be opened. `host`: The multicast ip address (optional; default: `224.1.1.1`). `dispatcher`: A function which will be executed on every request. Params that will be passed to this dispatcher: - `{Buffer} message` - the raw request string - `{object} rinfo` - client connection details `ttl`: The number of IP hops that a packet is allowed to go through (optional; default: 128).
[ "Wrapper", "around", "the", "socket", "implementation", "of", "Node", ".", "js", "with", "some", "proxy", "functionality", "for", "incoming", "messages", "." ]
c7be9d728ca499c728a4c7258fa7901ac7948831
https://github.com/akoenig/kast/blob/c7be9d728ca499c728a4c7258fa7901ac7948831/lib/socket.js#L48-L61
train
crysalead-js/dom-layer
src/node/patcher/style.js
patch
function patch(element, previous, style) { if (!previous && !style) { return style; } var rule; if (typeof style === 'object') { if (typeof previous === 'object') { for (rule in previous) { if (!style[rule]) { domElementCss(element, rule, null); } } domElementCss(element, style); } else { if (previous) { element.setAttribute('style', ''); } domElementCss(element, style); } } else { element.setAttribute('style', style || ''); } }
javascript
function patch(element, previous, style) { if (!previous && !style) { return style; } var rule; if (typeof style === 'object') { if (typeof previous === 'object') { for (rule in previous) { if (!style[rule]) { domElementCss(element, rule, null); } } domElementCss(element, style); } else { if (previous) { element.setAttribute('style', ''); } domElementCss(element, style); } } else { element.setAttribute('style', style || ''); } }
[ "function", "patch", "(", "element", ",", "previous", ",", "style", ")", "{", "if", "(", "!", "previous", "&&", "!", "style", ")", "{", "return", "style", ";", "}", "var", "rule", ";", "if", "(", "typeof", "style", "===", "'object'", ")", "{", "if", "(", "typeof", "previous", "===", "'object'", ")", "{", "for", "(", "rule", "in", "previous", ")", "{", "if", "(", "!", "style", "[", "rule", "]", ")", "{", "domElementCss", "(", "element", ",", "rule", ",", "null", ")", ";", "}", "}", "domElementCss", "(", "element", ",", "style", ")", ";", "}", "else", "{", "if", "(", "previous", ")", "{", "element", ".", "setAttribute", "(", "'style'", ",", "''", ")", ";", "}", "domElementCss", "(", "element", ",", "style", ")", ";", "}", "}", "else", "{", "element", ".", "setAttribute", "(", "'style'", ",", "style", "||", "''", ")", ";", "}", "}" ]
Maintains state of element style attribute. @param Object element A DOM element. @param Object previous The previous state of style attributes. @param Object style The style attributes to match on.
[ "Maintains", "state", "of", "element", "style", "attribute", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/patcher/style.js#L10-L32
train
crysalead-js/dom-layer
src/node/patcher/props.js
patch
function patch(element, previous, props) { if (!previous && !props) { return props; } var name, value; previous = previous || {}; props = props || {}; for (name in previous) { if (previous[name] === undefined || props[name] !== undefined) { continue; } unset(name, element, previous); } for (name in props) { set(name, element, previous, props); } return props; }
javascript
function patch(element, previous, props) { if (!previous && !props) { return props; } var name, value; previous = previous || {}; props = props || {}; for (name in previous) { if (previous[name] === undefined || props[name] !== undefined) { continue; } unset(name, element, previous); } for (name in props) { set(name, element, previous, props); } return props; }
[ "function", "patch", "(", "element", ",", "previous", ",", "props", ")", "{", "if", "(", "!", "previous", "&&", "!", "props", ")", "{", "return", "props", ";", "}", "var", "name", ",", "value", ";", "previous", "=", "previous", "||", "{", "}", ";", "props", "=", "props", "||", "{", "}", ";", "for", "(", "name", "in", "previous", ")", "{", "if", "(", "previous", "[", "name", "]", "===", "undefined", "||", "props", "[", "name", "]", "!==", "undefined", ")", "{", "continue", ";", "}", "unset", "(", "name", ",", "element", ",", "previous", ")", ";", "}", "for", "(", "name", "in", "props", ")", "{", "set", "(", "name", ",", "element", ",", "previous", ",", "props", ")", ";", "}", "return", "props", ";", "}" ]
Maintains state of element properties. @param Object element A DOM element. @param Object previous The previous state of properties. @param Object props The properties to match on. @return Object props The element properties state.
[ "Maintains", "state", "of", "element", "properties", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/patcher/props.js#L12-L30
train
crysalead-js/dom-layer
src/node/patcher/props.js
set
function set(name, element, previous, props) { if (set.handlers[name]) { set.handlers[name](name, element, previous, props); } else if (previous[name] !== props[name]) { element[name] = props[name]; } }
javascript
function set(name, element, previous, props) { if (set.handlers[name]) { set.handlers[name](name, element, previous, props); } else if (previous[name] !== props[name]) { element[name] = props[name]; } }
[ "function", "set", "(", "name", ",", "element", ",", "previous", ",", "props", ")", "{", "if", "(", "set", ".", "handlers", "[", "name", "]", ")", "{", "set", ".", "handlers", "[", "name", "]", "(", "name", ",", "element", ",", "previous", ",", "props", ")", ";", "}", "else", "if", "(", "previous", "[", "name", "]", "!==", "props", "[", "name", "]", ")", "{", "element", "[", "name", "]", "=", "props", "[", "name", "]", ";", "}", "}" ]
Sets a property. @param String name The property name to set. @param Object element A DOM element. @param Object previous The previous state of properties. @param Object props The properties to match on.
[ "Sets", "a", "property", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/patcher/props.js#L40-L46
train
crysalead-js/dom-layer
src/node/patcher/props.js
unset
function unset(name, element, previous) { if (unset.handlers[name]) { unset.handlers[name](name, element, previous); } else { element[name] = null; } }
javascript
function unset(name, element, previous) { if (unset.handlers[name]) { unset.handlers[name](name, element, previous); } else { element[name] = null; } }
[ "function", "unset", "(", "name", ",", "element", ",", "previous", ")", "{", "if", "(", "unset", ".", "handlers", "[", "name", "]", ")", "{", "unset", ".", "handlers", "[", "name", "]", "(", "name", ",", "element", ",", "previous", ")", ";", "}", "else", "{", "element", "[", "name", "]", "=", "null", ";", "}", "}" ]
Unsets a property. @param String name The property name to unset. @param Object element A DOM element. @param Object previous The previous state of properties.
[ "Unsets", "a", "property", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/patcher/props.js#L56-L62
train
seancheung/kuconfig
lib/conditional.js
$cond
function $cond(params) { if ( Array.isArray(params) && params.length === 3 && typeof params[0] === 'boolean' ) { return params[0] ? params[1] : params[2]; } throw new Error( '$cond expects an array of three elements of which the first must be a boolean' ); }
javascript
function $cond(params) { if ( Array.isArray(params) && params.length === 3 && typeof params[0] === 'boolean' ) { return params[0] ? params[1] : params[2]; } throw new Error( '$cond expects an array of three elements of which the first must be a boolean' ); }
[ "function", "$cond", "(", "params", ")", "{", "if", "(", "Array", ".", "isArray", "(", "params", ")", "&&", "params", ".", "length", "===", "3", "&&", "typeof", "params", "[", "0", "]", "===", "'boolean'", ")", "{", "return", "params", "[", "0", "]", "?", "params", "[", "1", "]", ":", "params", "[", "2", "]", ";", "}", "throw", "new", "Error", "(", "'$cond expects an array of three elements of which the first must be a boolean'", ")", ";", "}" ]
Return the second or third element based on the boolean value of the first element @param {[boolean, any, any]} params @returns {any}
[ "Return", "the", "second", "or", "third", "element", "based", "on", "the", "boolean", "value", "of", "the", "first", "element" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/conditional.js#L7-L18
train
crysalead-js/dom-layer
src/tree/tree.js
broadcastInserted
function broadcastInserted(node) { if (node.hooks && node.hooks.inserted) { return node.hooks.inserted(node, node.element); } if (node.children) { for (var i = 0, len = node.children.length; i < len; i++) { if (node.children[i]) { broadcastInserted(node.children[i]); } } } }
javascript
function broadcastInserted(node) { if (node.hooks && node.hooks.inserted) { return node.hooks.inserted(node, node.element); } if (node.children) { for (var i = 0, len = node.children.length; i < len; i++) { if (node.children[i]) { broadcastInserted(node.children[i]); } } } }
[ "function", "broadcastInserted", "(", "node", ")", "{", "if", "(", "node", ".", "hooks", "&&", "node", ".", "hooks", ".", "inserted", ")", "{", "return", "node", ".", "hooks", ".", "inserted", "(", "node", ",", "node", ".", "element", ")", ";", "}", "if", "(", "node", ".", "children", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "node", ".", "children", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "node", ".", "children", "[", "i", "]", ")", "{", "broadcastInserted", "(", "node", ".", "children", "[", "i", "]", ")", ";", "}", "}", "}", "}" ]
Broadcasts the inserted 'event'.
[ "Broadcasts", "the", "inserted", "event", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/tree/tree.js#L15-L26
train
charto/charto
bundler/publish.js
walk
function walk(dir, before, after, handler, name = null, depth = 0) { const listed = fs.readdirAsync( dir ).then((list) => Promise.map(list, (item) => { const child = path.resolve(dir, item); const result = fs.lstatAsync( child ).then((stat) => ({ path: child, name: item, isFile: stat.isFile(), enterDir: stat.isDirectory() })); return(result); })); const result = listed.then( (items) => before(items, depth) ).then((items) => Promise.map( items, (item) => item.enterDir && walk(item.path, before, after, handler, item.name, depth + 1) )).then( (children) => after(listed.value(), children) ).then((dependencyList) => { handler(dir, dependencyList, name, depth); return(dependencyList); }).catch((err) => {}); return(result); }
javascript
function walk(dir, before, after, handler, name = null, depth = 0) { const listed = fs.readdirAsync( dir ).then((list) => Promise.map(list, (item) => { const child = path.resolve(dir, item); const result = fs.lstatAsync( child ).then((stat) => ({ path: child, name: item, isFile: stat.isFile(), enterDir: stat.isDirectory() })); return(result); })); const result = listed.then( (items) => before(items, depth) ).then((items) => Promise.map( items, (item) => item.enterDir && walk(item.path, before, after, handler, item.name, depth + 1) )).then( (children) => after(listed.value(), children) ).then((dependencyList) => { handler(dir, dependencyList, name, depth); return(dependencyList); }).catch((err) => {}); return(result); }
[ "function", "walk", "(", "dir", ",", "before", ",", "after", ",", "handler", ",", "name", "=", "null", ",", "depth", "=", "0", ")", "{", "const", "listed", "=", "fs", ".", "readdirAsync", "(", "dir", ")", ".", "then", "(", "(", "list", ")", "=>", "Promise", ".", "map", "(", "list", ",", "(", "item", ")", "=>", "{", "const", "child", "=", "path", ".", "resolve", "(", "dir", ",", "item", ")", ";", "const", "result", "=", "fs", ".", "lstatAsync", "(", "child", ")", ".", "then", "(", "(", "stat", ")", "=>", "(", "{", "path", ":", "child", ",", "name", ":", "item", ",", "isFile", ":", "stat", ".", "isFile", "(", ")", ",", "enterDir", ":", "stat", ".", "isDirectory", "(", ")", "}", ")", ")", ";", "return", "(", "result", ")", ";", "}", ")", ")", ";", "const", "result", "=", "listed", ".", "then", "(", "(", "items", ")", "=>", "before", "(", "items", ",", "depth", ")", ")", ".", "then", "(", "(", "items", ")", "=>", "Promise", ".", "map", "(", "items", ",", "(", "item", ")", "=>", "item", ".", "enterDir", "&&", "walk", "(", "item", ".", "path", ",", "before", ",", "after", ",", "handler", ",", "item", ".", "name", ",", "depth", "+", "1", ")", ")", ")", ".", "then", "(", "(", "children", ")", "=>", "after", "(", "listed", ".", "value", "(", ")", ",", "children", ")", ")", ".", "then", "(", "(", "dependencyList", ")", "=>", "{", "handler", "(", "dir", ",", "dependencyList", ",", "name", ",", "depth", ")", ";", "return", "(", "dependencyList", ")", ";", "}", ")", ".", "catch", "(", "(", "err", ")", "=>", "{", "}", ")", ";", "return", "(", "result", ")", ";", "}" ]
Recursively walk a directory tree. @param dir Path to root of tree to explore. @param before Function called with contents of each directory, before entering subdirectories. Directories have an enterDir flag set and clearing it prevents recursing inside. @param after Function called for each directory after exploring subdirectories. Return value should contain a list of dependencies. @param name Name of the current npm package. @param depth Current recursion depth in directory tree. @return List of strings returned by the "after" callback, without any empty strings or name of the current NPM package.
[ "Recursively", "walk", "a", "directory", "tree", "." ]
bbdb49b8a5a3f5a7a715d2f7219df667e6062b39
https://github.com/charto/charto/blob/bbdb49b8a5a3f5a7a715d2f7219df667e6062b39/bundler/publish.js#L29-L60
train
charto/charto
bundler/publish.js
filterChildren
function filterChildren(children, depth) { if(depth == 1) { let found = false; for(let item of children) { if(item.name == 'package.json') found = true; if(item.name != 'src') item.enterDir = false; } if(!found) throw(new Error()); } return(children); }
javascript
function filterChildren(children, depth) { if(depth == 1) { let found = false; for(let item of children) { if(item.name == 'package.json') found = true; if(item.name != 'src') item.enterDir = false; } if(!found) throw(new Error()); } return(children); }
[ "function", "filterChildren", "(", "children", ",", "depth", ")", "{", "if", "(", "depth", "==", "1", ")", "{", "let", "found", "=", "false", ";", "for", "(", "let", "item", "of", "children", ")", "{", "if", "(", "item", ".", "name", "==", "'package.json'", ")", "found", "=", "true", ";", "if", "(", "item", ".", "name", "!=", "'src'", ")", "item", ".", "enterDir", "=", "false", ";", "}", "if", "(", "!", "found", ")", "throw", "(", "new", "Error", "(", ")", ")", ";", "}", "return", "(", "children", ")", ";", "}" ]
Detect NPM package root directories by presence of a package.json file. Only enter a subdirectory called "src". Usable as a "before" callback for the walk function. @return Filtered list of directory contents.
[ "Detect", "NPM", "package", "root", "directories", "by", "presence", "of", "a", "package", ".", "json", "file", ".", "Only", "enter", "a", "subdirectory", "called", "src", ".", "Usable", "as", "a", "before", "callback", "for", "the", "walk", "function", "." ]
bbdb49b8a5a3f5a7a715d2f7219df667e6062b39
https://github.com/charto/charto/blob/bbdb49b8a5a3f5a7a715d2f7219df667e6062b39/bundler/publish.js#L67-L80
train
maichong/number-random
index.js
random
function random(min, max, float) { if (min === undefined) { return Math.random(); } if (max === undefined) { max = min; min = 0; } if (max < min) { var tmp = max; max = min; min = tmp; } if (float) { var result = Math.random() * (max - min) + min; if (float === true) { return result; } else if (typeof float === 'number') { var str = result.toString(); var index = str.indexOf('.'); str = str.substr(0, index + 1 + float); if (str[str.length - 1] === '0') { str = str.substr(0, str.length - 1) + random(1, 9); } return parseFloat(str); } } return Math.floor(Math.random() * (max - min + 1) + min); }
javascript
function random(min, max, float) { if (min === undefined) { return Math.random(); } if (max === undefined) { max = min; min = 0; } if (max < min) { var tmp = max; max = min; min = tmp; } if (float) { var result = Math.random() * (max - min) + min; if (float === true) { return result; } else if (typeof float === 'number') { var str = result.toString(); var index = str.indexOf('.'); str = str.substr(0, index + 1 + float); if (str[str.length - 1] === '0') { str = str.substr(0, str.length - 1) + random(1, 9); } return parseFloat(str); } } return Math.floor(Math.random() * (max - min + 1) + min); }
[ "function", "random", "(", "min", ",", "max", ",", "float", ")", "{", "if", "(", "min", "===", "undefined", ")", "{", "return", "Math", ".", "random", "(", ")", ";", "}", "if", "(", "max", "===", "undefined", ")", "{", "max", "=", "min", ";", "min", "=", "0", ";", "}", "if", "(", "max", "<", "min", ")", "{", "var", "tmp", "=", "max", ";", "max", "=", "min", ";", "min", "=", "tmp", ";", "}", "if", "(", "float", ")", "{", "var", "result", "=", "Math", ".", "random", "(", ")", "*", "(", "max", "-", "min", ")", "+", "min", ";", "if", "(", "float", "===", "true", ")", "{", "return", "result", ";", "}", "else", "if", "(", "typeof", "float", "===", "'number'", ")", "{", "var", "str", "=", "result", ".", "toString", "(", ")", ";", "var", "index", "=", "str", ".", "indexOf", "(", "'.'", ")", ";", "str", "=", "str", ".", "substr", "(", "0", ",", "index", "+", "1", "+", "float", ")", ";", "if", "(", "str", "[", "str", ".", "length", "-", "1", "]", "===", "'0'", ")", "{", "str", "=", "str", ".", "substr", "(", "0", ",", "str", ".", "length", "-", "1", ")", "+", "random", "(", "1", ",", "9", ")", ";", "}", "return", "parseFloat", "(", "str", ")", ";", "}", "}", "return", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "(", "max", "-", "min", "+", "1", ")", "+", "min", ")", ";", "}" ]
Generate random number in a range @param {number} min @param {number} max [optional] @param {number|boolean} float [optional] default false @returns {number}
[ "Generate", "random", "number", "in", "a", "range" ]
246a9dc8d9d14263f9dda38e1a7227581ee24917
https://github.com/maichong/number-random/blob/246a9dc8d9d14263f9dda38e1a7227581ee24917/index.js#L8-L40
train
base/base-npm
index.js
checkName
function checkName(name, cb) { request(`https://registry.npmjs.org/${name}/latest`, {}, function(err, res, msg) { if (err) return cb(err); if (typeof msg === 'string' && msg === 'Package not found') { cb(null, false); return; } if (res && res.statusCode === 404) { return cb(null, false); } cb(null, true); }); }
javascript
function checkName(name, cb) { request(`https://registry.npmjs.org/${name}/latest`, {}, function(err, res, msg) { if (err) return cb(err); if (typeof msg === 'string' && msg === 'Package not found') { cb(null, false); return; } if (res && res.statusCode === 404) { return cb(null, false); } cb(null, true); }); }
[ "function", "checkName", "(", "name", ",", "cb", ")", "{", "request", "(", "`", "${", "name", "}", "`", ",", "{", "}", ",", "function", "(", "err", ",", "res", ",", "msg", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "if", "(", "typeof", "msg", "===", "'string'", "&&", "msg", "===", "'Package not found'", ")", "{", "cb", "(", "null", ",", "false", ")", ";", "return", ";", "}", "if", "(", "res", "&&", "res", ".", "statusCode", "===", "404", ")", "{", "return", "cb", "(", "null", ",", "false", ")", ";", "}", "cb", "(", "null", ",", "true", ")", ";", "}", ")", ";", "}" ]
Check if a name exists on npm. ```js checkName('foo', function(err, exists) { if (err) throw err; console.log(exists); }); //=> true ``` @param {String} `name` Name of module to check. @param {Function} `cb` Callback function
[ "Check", "if", "a", "name", "exists", "on", "npm", "." ]
c08b0760b40a1d2db05bef091e37ad1425933a91
https://github.com/base/base-npm/blob/c08b0760b40a1d2db05bef091e37ad1425933a91/index.js#L277-L292
train
edjafarov/PromisePipe
example/auction/src/client.js
upTo
function upTo(el, tagName) { tagName = tagName.toLowerCase(); while (el && el.parentNode) { el = el.parentNode; if (el.tagName && el.tagName.toLowerCase() == tagName) { return el; } } // Many DOM methods return null if they don't // find the element they are searching for // It would be OK to omit the following and just // return undefined return null; }
javascript
function upTo(el, tagName) { tagName = tagName.toLowerCase(); while (el && el.parentNode) { el = el.parentNode; if (el.tagName && el.tagName.toLowerCase() == tagName) { return el; } } // Many DOM methods return null if they don't // find the element they are searching for // It would be OK to omit the following and just // return undefined return null; }
[ "function", "upTo", "(", "el", ",", "tagName", ")", "{", "tagName", "=", "tagName", ".", "toLowerCase", "(", ")", ";", "while", "(", "el", "&&", "el", ".", "parentNode", ")", "{", "el", "=", "el", ".", "parentNode", ";", "if", "(", "el", ".", "tagName", "&&", "el", ".", "tagName", ".", "toLowerCase", "(", ")", "==", "tagName", ")", "{", "return", "el", ";", "}", "}", "return", "null", ";", "}" ]
Find first ancestor of el with tagName or undefined if not found
[ "Find", "first", "ancestor", "of", "el", "with", "tagName", "or", "undefined", "if", "not", "found" ]
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/example/auction/src/client.js#L55-L69
train