id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
49,700
nanowizard/vec23
src/Vec3.js
function(p){ return new Vec3(Math.pow(this.x, p), Math.pow(this.y, p), Math.pow(this.z, p)); }
javascript
function(p){ return new Vec3(Math.pow(this.x, p), Math.pow(this.y, p), Math.pow(this.z, p)); }
[ "function", "(", "p", ")", "{", "return", "new", "Vec3", "(", "Math", ".", "pow", "(", "this", ".", "x", ",", "p", ")", ",", "Math", ".", "pow", "(", "this", ".", "y", ",", "p", ")", ",", "Math", ".", "pow", "(", "this", ".", "z", ",", "p...
Raises each component of the vector to the power p and returns a new vector. @memberof Vec3# @returns {Vec3}
[ "Raises", "each", "component", "of", "the", "vector", "to", "the", "power", "p", "and", "returns", "a", "new", "vector", "." ]
e9ac7698d7cf96aeabd3d67cb48b8b1e5b6e8364
https://github.com/nanowizard/vec23/blob/e9ac7698d7cf96aeabd3d67cb48b8b1e5b6e8364/src/Vec3.js#L588-L590
49,701
vkiding/judpack-lib
src/cordova/info.js
execSpawn
function execSpawn(command, args, resultMsg, errorMsg) { return superspawn.spawn(command, args).then(function(result) { return resultMsg + result; }, function(error) { return errorMsg + error; }); }
javascript
function execSpawn(command, args, resultMsg, errorMsg) { return superspawn.spawn(command, args).then(function(result) { return resultMsg + result; }, function(error) { return errorMsg + error; }); }
[ "function", "execSpawn", "(", "command", ",", "args", ",", "resultMsg", ",", "errorMsg", ")", "{", "return", "superspawn", ".", "spawn", "(", "command", ",", "args", ")", ".", "then", "(", "function", "(", "result", ")", "{", "return", "resultMsg", "+", ...
Execute using a child_process exec, for any async command
[ "Execute", "using", "a", "child_process", "exec", "for", "any", "async", "command" ]
8657cecfec68221109279106adca8dbc81f430f4
https://github.com/vkiding/judpack-lib/blob/8657cecfec68221109279106adca8dbc81f430f4/src/cordova/info.js#L33-L39
49,702
stuartpb/aname-poll
index.js
finishQuerying
function finishQuerying(domain, err, records) { // Set time until our next query var expiration = Date.now() + ttl * 1000; // If there was an error querying the domain if (err) { // If the domain was not found if (err.code == 'ENOTFOUND') { // If we have a function to handle missing domains if (notfoundHandler) { // Call it with a callback that lets it decide how to proceed return notfoundHandler(domain, function(remove) { // Remove the domain from circulation if requested if (remove) return db.hdel('querying_domains', domain, next); // Otherwise, keep it in circulation else completeQuery(); }); // If there's no function to handle missing domains } else { // Just return the domain to the query queue return completeQuery(); } // If it was some other kind of error } else { // Spit it up return cb(err); } } // Set TTLs on the records records = records.map(function(record){record.ttl = ttl; return record}); // If we process new records if (process) { // Set the new records and get the old ones db.getset('records:' + domain, JSON.stringify(records), function(err, oldrecords) { if (err) return cb(err); // If the old ones aren't the same as the new ones if (!(oldrecords && equal(records, JSON.parse(oldrecords)))) { // Mark this domain as processing db.eval(hshd, 2, 'processing_domains', 'querying_domains', domain, expiration, function(err, res) { if (err) return cb(err); // Process the new records process(domain,records,finishProcessing); }); // If the old ones were the same, // just advance as if we weren't processing } else completeQuery(); }); } else { db.set('records:' + domain, JSON.stringify(records), completeQuery); } // Mark that we've set the records (if any) and finish function completeQuery(err) { if (err) return cb(err); db.eval(zahd, 2, 'expiring_domains', 'querying_domains', expiration, domain, next); } // Mark that we've finished processing records function finishProcessing(err) { if (err) return cb(err); db.eval(hmz, 2, 'processing_domains', 'expiring_domains', domain, next); } }
javascript
function finishQuerying(domain, err, records) { // Set time until our next query var expiration = Date.now() + ttl * 1000; // If there was an error querying the domain if (err) { // If the domain was not found if (err.code == 'ENOTFOUND') { // If we have a function to handle missing domains if (notfoundHandler) { // Call it with a callback that lets it decide how to proceed return notfoundHandler(domain, function(remove) { // Remove the domain from circulation if requested if (remove) return db.hdel('querying_domains', domain, next); // Otherwise, keep it in circulation else completeQuery(); }); // If there's no function to handle missing domains } else { // Just return the domain to the query queue return completeQuery(); } // If it was some other kind of error } else { // Spit it up return cb(err); } } // Set TTLs on the records records = records.map(function(record){record.ttl = ttl; return record}); // If we process new records if (process) { // Set the new records and get the old ones db.getset('records:' + domain, JSON.stringify(records), function(err, oldrecords) { if (err) return cb(err); // If the old ones aren't the same as the new ones if (!(oldrecords && equal(records, JSON.parse(oldrecords)))) { // Mark this domain as processing db.eval(hshd, 2, 'processing_domains', 'querying_domains', domain, expiration, function(err, res) { if (err) return cb(err); // Process the new records process(domain,records,finishProcessing); }); // If the old ones were the same, // just advance as if we weren't processing } else completeQuery(); }); } else { db.set('records:' + domain, JSON.stringify(records), completeQuery); } // Mark that we've set the records (if any) and finish function completeQuery(err) { if (err) return cb(err); db.eval(zahd, 2, 'expiring_domains', 'querying_domains', expiration, domain, next); } // Mark that we've finished processing records function finishProcessing(err) { if (err) return cb(err); db.eval(hmz, 2, 'processing_domains', 'expiring_domains', domain, next); } }
[ "function", "finishQuerying", "(", "domain", ",", "err", ",", "records", ")", "{", "// Set time until our next query", "var", "expiration", "=", "Date", ".", "now", "(", ")", "+", "ttl", "*", "1000", ";", "// If there was an error querying the domain", "if", "(", ...
Handle the record response from a query
[ "Handle", "the", "record", "response", "from", "a", "query" ]
c2efeef173ca1577922fb6c0a770fd169bfac058
https://github.com/stuartpb/aname-poll/blob/c2efeef173ca1577922fb6c0a770fd169bfac058/index.js#L26-L97
49,703
stuartpb/aname-poll
index.js
finishProcessing
function finishProcessing(err) { if (err) return cb(err); db.eval(hmz, 2, 'processing_domains', 'expiring_domains', domain, next); }
javascript
function finishProcessing(err) { if (err) return cb(err); db.eval(hmz, 2, 'processing_domains', 'expiring_domains', domain, next); }
[ "function", "finishProcessing", "(", "err", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "db", ".", "eval", "(", "hmz", ",", "2", ",", "'processing_domains'", ",", "'expiring_domains'", ",", "domain", ",", "next", ")", ";", ...
Mark that we've finished processing records
[ "Mark", "that", "we", "ve", "finished", "processing", "records" ]
c2efeef173ca1577922fb6c0a770fd169bfac058
https://github.com/stuartpb/aname-poll/blob/c2efeef173ca1577922fb6c0a770fd169bfac058/index.js#L92-L96
49,704
stuartpb/aname-poll
index.js
iface
function iface(end) { if (end) { return db.quit(next); } else { // Get all the domains whose records expired some time before now db.eval(scoreRange,2,'expiring_domains','querying_domains', '-inf', Date.now(), function (err, res) { if (err) return cb(err); // Query each of these domains for (var i = 0; i < res.length; i += 2) { queryDomain(res[i], finishQuerying.bind(null, res[i])); } }); return iface; } }
javascript
function iface(end) { if (end) { return db.quit(next); } else { // Get all the domains whose records expired some time before now db.eval(scoreRange,2,'expiring_domains','querying_domains', '-inf', Date.now(), function (err, res) { if (err) return cb(err); // Query each of these domains for (var i = 0; i < res.length; i += 2) { queryDomain(res[i], finishQuerying.bind(null, res[i])); } }); return iface; } }
[ "function", "iface", "(", "end", ")", "{", "if", "(", "end", ")", "{", "return", "db", ".", "quit", "(", "next", ")", ";", "}", "else", "{", "// Get all the domains whose records expired some time before now", "db", ".", "eval", "(", "scoreRange", ",", "2", ...
The interface interval function we return
[ "The", "interface", "interval", "function", "we", "return" ]
c2efeef173ca1577922fb6c0a770fd169bfac058
https://github.com/stuartpb/aname-poll/blob/c2efeef173ca1577922fb6c0a770fd169bfac058/index.js#L100-L115
49,705
nusmodifications/nusmoderator
lib/academicCalendar.js
getAcadSem
function getAcadSem(acadWeekNumber) { var earliestSupportedWeek = 1; var lastWeekofSem1 = 23; var lastWeekofSem2 = 40; var lastWeekofSpecialSem1 = 46; var lastWeekofSpecialSem2 = 52; if (acadWeekNumber >= earliestSupportedWeek && acadWeekNumber <= lastWeekofSem1) { return sem1; } else if (acadWeekNumber > lastWeekofSem1 && acadWeekNumber <= lastWeekofSem2) { return sem2; } else if (acadWeekNumber > lastWeekofSem2 && acadWeekNumber <= lastWeekofSpecialSem1) { return special1; } else if (acadWeekNumber > lastWeekofSpecialSem1 && acadWeekNumber <= lastWeekofSpecialSem2) { return special2; } console.warn('[nusmoderator] Unsupported acadWeekNumber as parameter: ' + acadWeekNumber); return null; }
javascript
function getAcadSem(acadWeekNumber) { var earliestSupportedWeek = 1; var lastWeekofSem1 = 23; var lastWeekofSem2 = 40; var lastWeekofSpecialSem1 = 46; var lastWeekofSpecialSem2 = 52; if (acadWeekNumber >= earliestSupportedWeek && acadWeekNumber <= lastWeekofSem1) { return sem1; } else if (acadWeekNumber > lastWeekofSem1 && acadWeekNumber <= lastWeekofSem2) { return sem2; } else if (acadWeekNumber > lastWeekofSem2 && acadWeekNumber <= lastWeekofSpecialSem1) { return special1; } else if (acadWeekNumber > lastWeekofSpecialSem1 && acadWeekNumber <= lastWeekofSpecialSem2) { return special2; } console.warn('[nusmoderator] Unsupported acadWeekNumber as parameter: ' + acadWeekNumber); return null; }
[ "function", "getAcadSem", "(", "acadWeekNumber", ")", "{", "var", "earliestSupportedWeek", "=", "1", ";", "var", "lastWeekofSem1", "=", "23", ";", "var", "lastWeekofSem2", "=", "40", ";", "var", "lastWeekofSpecialSem1", "=", "46", ";", "var", "lastWeekofSpecialS...
Computes the current academic semester. Expects a week number of a year. @param {Number} acadWeekNumber - 3 @return {String} semester - "Semester 1"
[ "Computes", "the", "current", "academic", "semester", ".", "Expects", "a", "week", "number", "of", "a", "year", "." ]
828d80ac47de090b0db3ab0b99cd68363f0fc263
https://github.com/nusmodifications/nusmoderator/blob/828d80ac47de090b0db3ab0b99cd68363f0fc263/lib/academicCalendar.js#L55-L74
49,706
nusmodifications/nusmoderator
lib/academicCalendar.js
getAcadWeekName
function getAcadWeekName(acadWeekNumber) { switch (acadWeekNumber) { case 7: return { weekType: 'Recess', weekNumber: null }; case 15: return { weekType: 'Reading', weekNumber: null }; case 16: case 17: return { weekType: 'Examination', weekNumber: acadWeekNumber - 15 }; default: { var weekNumber = acadWeekNumber; if (weekNumber >= 8) { // For weeks after recess week weekNumber -= 1; } if (acadWeekNumber < 1 || acadWeekNumber > 17) { console.warn('[nusmoderator] Unsupported acadWeekNumber as parameter: ' + acadWeekNumber); return null; } return { weekType: 'Instructional', weekNumber: weekNumber }; } } }
javascript
function getAcadWeekName(acadWeekNumber) { switch (acadWeekNumber) { case 7: return { weekType: 'Recess', weekNumber: null }; case 15: return { weekType: 'Reading', weekNumber: null }; case 16: case 17: return { weekType: 'Examination', weekNumber: acadWeekNumber - 15 }; default: { var weekNumber = acadWeekNumber; if (weekNumber >= 8) { // For weeks after recess week weekNumber -= 1; } if (acadWeekNumber < 1 || acadWeekNumber > 17) { console.warn('[nusmoderator] Unsupported acadWeekNumber as parameter: ' + acadWeekNumber); return null; } return { weekType: 'Instructional', weekNumber: weekNumber }; } } }
[ "function", "getAcadWeekName", "(", "acadWeekNumber", ")", "{", "switch", "(", "acadWeekNumber", ")", "{", "case", "7", ":", "return", "{", "weekType", ":", "'Recess'", ",", "weekNumber", ":", "null", "}", ";", "case", "15", ":", "return", "{", "weekType",...
Computes the current academic week of the semester Expects a week number of a semester. @param {Number} acadWeekNumber - 3 @return {String} semester - "Recess" | "Reading" | "Examination"
[ "Computes", "the", "current", "academic", "week", "of", "the", "semester", "Expects", "a", "week", "number", "of", "a", "semester", "." ]
828d80ac47de090b0db3ab0b99cd68363f0fc263
https://github.com/nusmodifications/nusmoderator/blob/828d80ac47de090b0db3ab0b99cd68363f0fc263/lib/academicCalendar.js#L82-L119
49,707
nusmodifications/nusmoderator
lib/academicCalendar.js
getAcadWeekInfo
function getAcadWeekInfo(date) { var currentAcad = getAcadYear(date); var acadYear = currentAcad.year; var acadYearStartDate = currentAcad.startDate; var acadWeekNumber = Math.ceil((date.getTime() - acadYearStartDate.getTime() + 1) / oneWeekDuration); var semester = getAcadSem(acadWeekNumber); var weekType = null; var weekNumber = null; switch (semester) { case sem2: // Semester 2 starts 22 weeks after Week 1 of semester 1 acadWeekNumber -= 22; case sem1: if (acadWeekNumber === 1) { weekType = 'Orientation'; break; } if (acadWeekNumber > 18) { weekType = 'Vacation'; weekNumber = acadWeekNumber - 18; break; } acadWeekNumber -= 1; { var week = getAcadWeekName(acadWeekNumber); weekType = week.weekType; weekNumber = week.weekNumber; } break; case special2: // Special Term II starts 6 weeks after Special Term I acadWeekNumber -= 6; case special1: // Special Term I starts on week 41 of the AY acadWeekNumber -= 40; weekType = 'Instructional'; weekNumber = acadWeekNumber; break; default: if (acadWeekNumber === 53) { // This means it is the 53th week of the AY, and this week is Vacation. // This happens 5 times every 28 years. weekType = 'Vacation'; weekNumber = null; } break; } return { year: acadYear, sem: semester, type: weekType, num: weekNumber }; }
javascript
function getAcadWeekInfo(date) { var currentAcad = getAcadYear(date); var acadYear = currentAcad.year; var acadYearStartDate = currentAcad.startDate; var acadWeekNumber = Math.ceil((date.getTime() - acadYearStartDate.getTime() + 1) / oneWeekDuration); var semester = getAcadSem(acadWeekNumber); var weekType = null; var weekNumber = null; switch (semester) { case sem2: // Semester 2 starts 22 weeks after Week 1 of semester 1 acadWeekNumber -= 22; case sem1: if (acadWeekNumber === 1) { weekType = 'Orientation'; break; } if (acadWeekNumber > 18) { weekType = 'Vacation'; weekNumber = acadWeekNumber - 18; break; } acadWeekNumber -= 1; { var week = getAcadWeekName(acadWeekNumber); weekType = week.weekType; weekNumber = week.weekNumber; } break; case special2: // Special Term II starts 6 weeks after Special Term I acadWeekNumber -= 6; case special1: // Special Term I starts on week 41 of the AY acadWeekNumber -= 40; weekType = 'Instructional'; weekNumber = acadWeekNumber; break; default: if (acadWeekNumber === 53) { // This means it is the 53th week of the AY, and this week is Vacation. // This happens 5 times every 28 years. weekType = 'Vacation'; weekNumber = null; } break; } return { year: acadYear, sem: semester, type: weekType, num: weekNumber }; }
[ "function", "getAcadWeekInfo", "(", "date", ")", "{", "var", "currentAcad", "=", "getAcadYear", "(", "date", ")", ";", "var", "acadYear", "=", "currentAcad", ".", "year", ";", "var", "acadYearStartDate", "=", "currentAcad", ".", "startDate", ";", "var", "aca...
Computes the current academic week and return in an object of acad date components @param {Date} date @return {Object} { year: "15/16", sem: 'Semester 1'|'Semester 2'|'Special Sem 1'|'Special Sem 2', type: 'Instructional'|'Reading'|'Examination'|'Recess'|'Vacation'|'Orientation', num: <weekNum> }
[ "Computes", "the", "current", "academic", "week", "and", "return", "in", "an", "object", "of", "acad", "date", "components" ]
828d80ac47de090b0db3ab0b99cd68363f0fc263
https://github.com/nusmodifications/nusmoderator/blob/828d80ac47de090b0db3ab0b99cd68363f0fc263/lib/academicCalendar.js#L131-L187
49,708
redisjs/jsr-server
lib/command/server/lastsave.js
execute
function execute(req, res) { // stored in milliseconds but this command returns seconds res.send(null, Math.round(this.state.lastsave / 1000)); }
javascript
function execute(req, res) { // stored in milliseconds but this command returns seconds res.send(null, Math.round(this.state.lastsave / 1000)); }
[ "function", "execute", "(", "req", ",", "res", ")", "{", "// stored in milliseconds but this command returns seconds", "res", ".", "send", "(", "null", ",", "Math", ".", "round", "(", "this", ".", "state", ".", "lastsave", "/", "1000", ")", ")", ";", "}" ]
Respond to the LASTSAVE command.
[ "Respond", "to", "the", "LASTSAVE", "command", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/server/lastsave.js#L17-L20
49,709
vkiding/judpack-lib
src/util/promise-util.js
Q_chainmap_graceful
function Q_chainmap_graceful(args, func, failureCallback) { return Q.when().then(function(inValue) { return args.reduce(function(soFar, arg) { return soFar.then(function(val) { return func(arg, val); }).fail(function(err) { if (failureCallback) { failureCallback(err); } }); }, Q(inValue)); }); }
javascript
function Q_chainmap_graceful(args, func, failureCallback) { return Q.when().then(function(inValue) { return args.reduce(function(soFar, arg) { return soFar.then(function(val) { return func(arg, val); }).fail(function(err) { if (failureCallback) { failureCallback(err); } }); }, Q(inValue)); }); }
[ "function", "Q_chainmap_graceful", "(", "args", ",", "func", ",", "failureCallback", ")", "{", "return", "Q", ".", "when", "(", ")", ".", "then", "(", "function", "(", "inValue", ")", "{", "return", "args", ".", "reduce", "(", "function", "(", "soFar", ...
Behaves similar to Q_chainmap but gracefully handles failures. When a promise in the chain is rejected, it will call the failureCallback and then continue the processing, instead of stopping
[ "Behaves", "similar", "to", "Q_chainmap", "but", "gracefully", "handles", "failures", ".", "When", "a", "promise", "in", "the", "chain", "is", "rejected", "it", "will", "call", "the", "failureCallback", "and", "then", "continue", "the", "processing", "instead", ...
8657cecfec68221109279106adca8dbc81f430f4
https://github.com/vkiding/judpack-lib/blob/8657cecfec68221109279106adca8dbc81f430f4/src/util/promise-util.js#L38-L50
49,710
aimingoo/redpoll
Distributed.js
isValueObject
function isValueObject(obj) { return (obj instanceof Number) || (obj instanceof String) || (obj instanceof Boolean) || (obj === null); }
javascript
function isValueObject(obj) { return (obj instanceof Number) || (obj instanceof String) || (obj instanceof Boolean) || (obj === null); }
[ "function", "isValueObject", "(", "obj", ")", "{", "return", "(", "obj", "instanceof", "Number", ")", "||", "(", "obj", "instanceof", "String", ")", "||", "(", "obj", "instanceof", "Boolean", ")", "||", "(", "obj", "===", "null", ")", ";", "}" ]
package classes of value types
[ "package", "classes", "of", "value", "types" ]
c14afc6792154374490d6753ba90fdd76cb6f5c3
https://github.com/aimingoo/redpoll/blob/c14afc6792154374490d6753ba90fdd76cb6f5c3/Distributed.js#L50-L52
49,711
aimingoo/redpoll
Distributed.js
enter
function enter(f, rejected) { return function() { try { return Promise.resolve(f.apply(this, arguments)).catch(rejected) } catch(e) { return rejected(e) } } }
javascript
function enter(f, rejected) { return function() { try { return Promise.resolve(f.apply(this, arguments)).catch(rejected) } catch(e) { return rejected(e) } } }
[ "function", "enter", "(", "f", ",", "rejected", ")", "{", "return", "function", "(", ")", "{", "try", "{", "return", "Promise", ".", "resolve", "(", "f", ".", "apply", "(", "this", ",", "arguments", ")", ")", ".", "catch", "(", "rejected", ")", "}"...
enter a sub-processes with privated rejected method
[ "enter", "a", "sub", "-", "processes", "with", "privated", "rejected", "method" ]
c14afc6792154374490d6753ba90fdd76cb6f5c3
https://github.com/aimingoo/redpoll/blob/c14afc6792154374490d6753ba90fdd76cb6f5c3/Distributed.js#L106-L113
49,712
aimingoo/redpoll
Distributed.js
internal_parse_scope
function internal_parse_scope(center, distributionScope) { // "?" or "*" is filted by this.require() if (distributionScope.length < 4) return this.require(":::"); // systemPart:pathPart:scopePart // - rx_tokens = /^([^:]+):(.*):([^:]+)$/ -> m[0],m[1],m[2] var rx_tokens = /^(.*):([^:]+)$/, m = distributionScope.match(rx_tokens); if (! m) return this.require(":::"); // TODO: dynamic scopePart parser, the <parts> is systemPart:pathPart // - var full = m[0], parts = m[1], scopePart = m[2]; return (m[2] == '?') ? this.require("::?") : (m[2] == '*') ? Promise.resolve(center.require(m[1])) : Promise.reject("dynamic scopePart is not support for '"+distributionScope+"'"); }
javascript
function internal_parse_scope(center, distributionScope) { // "?" or "*" is filted by this.require() if (distributionScope.length < 4) return this.require(":::"); // systemPart:pathPart:scopePart // - rx_tokens = /^([^:]+):(.*):([^:]+)$/ -> m[0],m[1],m[2] var rx_tokens = /^(.*):([^:]+)$/, m = distributionScope.match(rx_tokens); if (! m) return this.require(":::"); // TODO: dynamic scopePart parser, the <parts> is systemPart:pathPart // - var full = m[0], parts = m[1], scopePart = m[2]; return (m[2] == '?') ? this.require("::?") : (m[2] == '*') ? Promise.resolve(center.require(m[1])) : Promise.reject("dynamic scopePart is not support for '"+distributionScope+"'"); }
[ "function", "internal_parse_scope", "(", "center", ",", "distributionScope", ")", "{", "// \"?\" or \"*\" is filted by this.require()", "if", "(", "distributionScope", ".", "length", "<", "4", ")", "return", "this", ".", "require", "(", "\":::\"", ")", ";", "// syst...
internal distribution scope praser
[ "internal", "distribution", "scope", "praser" ]
c14afc6792154374490d6753ba90fdd76cb6f5c3
https://github.com/aimingoo/redpoll/blob/c14afc6792154374490d6753ba90fdd76cb6f5c3/Distributed.js#L367-L381
49,713
sendanor/nor-nopg
src/schema/v0011.js
function(db) { function check_javascript_function(js, plv8, ERROR) { var fun; try { // We'll check only positive input if(js) { fun = (new Function('return (' + js + ')'))(); if(! (fun && (fun instanceof Function)) ) { throw TypeError("Input is not valid JavaScript function: " + (typeof fun) + ": " + fun); } } } catch (e) { plv8.elog(ERROR, e); return false; } return true; } return db.query('CREATE OR REPLACE FUNCTION check_javascript_function(js text) RETURNS boolean LANGUAGE plv8 VOLATILE AS ' + NoPg._escapeFunction(check_javascript_function, ['js', 'plv8', 'ERROR'])); }
javascript
function(db) { function check_javascript_function(js, plv8, ERROR) { var fun; try { // We'll check only positive input if(js) { fun = (new Function('return (' + js + ')'))(); if(! (fun && (fun instanceof Function)) ) { throw TypeError("Input is not valid JavaScript function: " + (typeof fun) + ": " + fun); } } } catch (e) { plv8.elog(ERROR, e); return false; } return true; } return db.query('CREATE OR REPLACE FUNCTION check_javascript_function(js text) RETURNS boolean LANGUAGE plv8 VOLATILE AS ' + NoPg._escapeFunction(check_javascript_function, ['js', 'plv8', 'ERROR'])); }
[ "function", "(", "db", ")", "{", "function", "check_javascript_function", "(", "js", ",", "plv8", ",", "ERROR", ")", "{", "var", "fun", ";", "try", "{", "// We'll check only positive input", "if", "(", "js", ")", "{", "fun", "=", "(", "new", "Function", ...
Function for checking that only valid javascript goes into types.validator column
[ "Function", "for", "checking", "that", "only", "valid", "javascript", "goes", "into", "types", ".", "validator", "column" ]
0d99b86c1a1996b5828b56de8de23700df8bbc0c
https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/schema/v0011.js#L6-L24
49,714
transomjs/transom-server-functions
release.js
exec
function exec(cmd) { const ret = shell.exec(cmd, { silent: true }); if (ret.code != 0) { console.error("Error:", ret.stdout, ret.stderr); process.exit(1); } return ret; }
javascript
function exec(cmd) { const ret = shell.exec(cmd, { silent: true }); if (ret.code != 0) { console.error("Error:", ret.stdout, ret.stderr); process.exit(1); } return ret; }
[ "function", "exec", "(", "cmd", ")", "{", "const", "ret", "=", "shell", ".", "exec", "(", "cmd", ",", "{", "silent", ":", "true", "}", ")", ";", "if", "(", "ret", ".", "code", "!=", "0", ")", "{", "console", ".", "error", "(", "\"Error:\"", ","...
Run commands quietly, log output and exit only on errors.
[ "Run", "commands", "quietly", "log", "output", "and", "exit", "only", "on", "errors", "." ]
68577950f5964031929f6b7360240bdcda65f004
https://github.com/transomjs/transom-server-functions/blob/68577950f5964031929f6b7360240bdcda65f004/release.js#L29-L39
49,715
haraldrudell/apprunner
lib/rqs.js
shutdown
function shutdown() { var timer for (var id in requests) if (timer = requests[id].timer) { clearTimeout(timer) requests[id].timer = null } }
javascript
function shutdown() { var timer for (var id in requests) if (timer = requests[id].timer) { clearTimeout(timer) requests[id].timer = null } }
[ "function", "shutdown", "(", ")", "{", "var", "timer", "for", "(", "var", "id", "in", "requests", ")", "if", "(", "timer", "=", "requests", "[", "id", "]", ".", "timer", ")", "{", "clearTimeout", "(", "timer", ")", "requests", "[", "id", "]", ".", ...
clear all timers
[ "clear", "all", "timers" ]
8d7dead166c919d160b429e00c49a62027994c33
https://github.com/haraldrudell/apprunner/blob/8d7dead166c919d160b429e00c49a62027994c33/lib/rqs.js#L219-L227
49,716
nestorivan/flex-grill
gulpfile.js
sassTranspiler
function sassTranspiler(path) { return function () { return gulp.src(path) .pipe(sass({outputStyle: 'compressed'})) .pipe(autoprefixer({ browsers: ['last 2 versions'] })) .pipe(gulp.dest('dist')); } }
javascript
function sassTranspiler(path) { return function () { return gulp.src(path) .pipe(sass({outputStyle: 'compressed'})) .pipe(autoprefixer({ browsers: ['last 2 versions'] })) .pipe(gulp.dest('dist')); } }
[ "function", "sassTranspiler", "(", "path", ")", "{", "return", "function", "(", ")", "{", "return", "gulp", ".", "src", "(", "path", ")", ".", "pipe", "(", "sass", "(", "{", "outputStyle", ":", "'compressed'", "}", ")", ")", ".", "pipe", "(", "autopr...
Compiles the sass files to css. @param {Array} path array of file paths
[ "Compiles", "the", "sass", "files", "to", "css", "." ]
c4f1c5b085560b8cf1390eac8971d36f060580d1
https://github.com/nestorivan/flex-grill/blob/c4f1c5b085560b8cf1390eac8971d36f060580d1/gulpfile.js#L15-L24
49,717
alexpods/ClazzJS
src/components/meta/Property/Converters.js
function(object, converters, property) { var self = this; object.__addSetter(property, this.SETTER_NAME , this.SETTER_WEIGHT, function(value, fields) { return self.apply(value, converters, property, fields, this); }); }
javascript
function(object, converters, property) { var self = this; object.__addSetter(property, this.SETTER_NAME , this.SETTER_WEIGHT, function(value, fields) { return self.apply(value, converters, property, fields, this); }); }
[ "function", "(", "object", ",", "converters", ",", "property", ")", "{", "var", "self", "=", "this", ";", "object", ".", "__addSetter", "(", "property", ",", "this", ".", "SETTER_NAME", ",", "this", ".", "SETTER_WEIGHT", ",", "function", "(", "value", ",...
Add converters setter to object @param {object} object Object to which constraints will be applied @param {object} converters Hash of converters @param {string} property Property name @this {metaProcessor}
[ "Add", "converters", "setter", "to", "object" ]
2f94496019669813c8246d48fcceb12a3e68a870
https://github.com/alexpods/ClazzJS/blob/2f94496019669813c8246d48fcceb12a3e68a870/src/components/meta/Property/Converters.js#L19-L25
49,718
alexpods/ClazzJS
src/components/meta/Property/Converters.js
function(value, converters, property, fields, object) { _.each(converters, function(converter) { value = converter.call(object, value, fields, property); }); return value; }
javascript
function(value, converters, property, fields, object) { _.each(converters, function(converter) { value = converter.call(object, value, fields, property); }); return value; }
[ "function", "(", "value", ",", "converters", ",", "property", ",", "fields", ",", "object", ")", "{", "_", ".", "each", "(", "converters", ",", "function", "(", "converter", ")", "{", "value", "=", "converter", ".", "call", "(", "object", ",", "value",...
Applies property converters to object @param {*} value Property value @param {object} converters Hash of property converters @param {string} property Property name @param {array} fields Property fields @param {object} object Object @returns {*} value Converted property value @this {metaProcessor}
[ "Applies", "property", "converters", "to", "object" ]
2f94496019669813c8246d48fcceb12a3e68a870
https://github.com/alexpods/ClazzJS/blob/2f94496019669813c8246d48fcceb12a3e68a870/src/components/meta/Property/Converters.js#L40-L48
49,719
PanthR/panthrMath
panthrMath/distributions/f.js
rf
function rf(df1, df2) { var rchisqRatio; rchisqRatio = function(d) { return chisq.rchisq(d)() / d; }; if (df1 <= 0 || df2 <= 0) { return function() { return NaN; }; } return function() { return rchisqRatio(df1) / rchisqRatio(df2); }; }
javascript
function rf(df1, df2) { var rchisqRatio; rchisqRatio = function(d) { return chisq.rchisq(d)() / d; }; if (df1 <= 0 || df2 <= 0) { return function() { return NaN; }; } return function() { return rchisqRatio(df1) / rchisqRatio(df2); }; }
[ "function", "rf", "(", "df1", ",", "df2", ")", "{", "var", "rchisqRatio", ";", "rchisqRatio", "=", "function", "(", "d", ")", "{", "return", "chisq", ".", "rchisq", "(", "d", ")", "(", ")", "/", "d", ";", "}", ";", "if", "(", "df1", "<=", "0", ...
Returns a random variate from the F distribution, computed as a ratio of chi square variates. Expects `df1` and `df2` to be positive. @fullName rf(df1, df2)() @memberof f
[ "Returns", "a", "random", "variate", "from", "the", "F", "distribution", "computed", "as", "a", "ratio", "of", "chi", "square", "variates", "." ]
54d249ca9903a9535f963da711bd3a87fb229c0b
https://github.com/PanthR/panthrMath/blob/54d249ca9903a9535f963da711bd3a87fb229c0b/panthrMath/distributions/f.js#L186-L196
49,720
energimolnet/energimolnet-ng
src/models/subscribers.js
_subscribersDelete
function _subscribersDelete(id, revokeMeters) { return Api.request({ method: 'DELETE', url: makeUrl([this._config.default, id]), data: { revoke_meters: revokeMeters || false }, headers: { 'Content-Type': 'application/json;charset=UTF-8' } }); }
javascript
function _subscribersDelete(id, revokeMeters) { return Api.request({ method: 'DELETE', url: makeUrl([this._config.default, id]), data: { revoke_meters: revokeMeters || false }, headers: { 'Content-Type': 'application/json;charset=UTF-8' } }); }
[ "function", "_subscribersDelete", "(", "id", ",", "revokeMeters", ")", "{", "return", "Api", ".", "request", "(", "{", "method", ":", "'DELETE'", ",", "url", ":", "makeUrl", "(", "[", "this", ".", "_config", ".", "default", ",", "id", "]", ")", ",", ...
Revoke meters argument determines whether the meters shared through a subscription shouldshould be revoked. Default is false
[ "Revoke", "meters", "argument", "determines", "whether", "the", "meters", "shared", "through", "a", "subscription", "shouldshould", "be", "revoked", ".", "Default", "is", "false" ]
7249c7a52aa6878d462a429c3aacb33d43bf9484
https://github.com/energimolnet/energimolnet-ng/blob/7249c7a52aa6878d462a429c3aacb33d43bf9484/src/models/subscribers.js#L26-L37
49,721
johvin/adjust-md-for-publish
index.js
parseDocToTree
function parseDocToTree(doc, defaultTitle) { // save the parsed tree const tree = []; const lines = doc.split('\n'); let line, m; // 保存一个文档区域 let section = null; let parentSection = null; // if in a ``` block let inBlock = false; // little trick,如果第一行不是 #,则增加一个 # if (!/^#(?!#)/.test(lines[0])) { lines.unshift('# ' + defaultTitle); } while ((line = lines.shift()) !== undefined) { m = line && line.match(/^(#+)(?!#)(.*)$/); if (!inBlock && m && m.length == 3) { section = { title: m[2].trim(), level: m[1].length, parent: null, children: [] }; while (parentSection && parentSection.level >= section.level) { parentSection = parentSection.parent; } if (parentSection) { section.parent = parentSection; parentSection.children.push(section); parentSection = section; } else { tree.push(section); parentSection = section; } } else if (section) { if (line.indexOf('```') === 0) { inBlock = !inBlock; } section.children.push(line); } else { throw new Error(`NOT VALID LINE: ${line}`); } } return tree; }
javascript
function parseDocToTree(doc, defaultTitle) { // save the parsed tree const tree = []; const lines = doc.split('\n'); let line, m; // 保存一个文档区域 let section = null; let parentSection = null; // if in a ``` block let inBlock = false; // little trick,如果第一行不是 #,则增加一个 # if (!/^#(?!#)/.test(lines[0])) { lines.unshift('# ' + defaultTitle); } while ((line = lines.shift()) !== undefined) { m = line && line.match(/^(#+)(?!#)(.*)$/); if (!inBlock && m && m.length == 3) { section = { title: m[2].trim(), level: m[1].length, parent: null, children: [] }; while (parentSection && parentSection.level >= section.level) { parentSection = parentSection.parent; } if (parentSection) { section.parent = parentSection; parentSection.children.push(section); parentSection = section; } else { tree.push(section); parentSection = section; } } else if (section) { if (line.indexOf('```') === 0) { inBlock = !inBlock; } section.children.push(line); } else { throw new Error(`NOT VALID LINE: ${line}`); } } return tree; }
[ "function", "parseDocToTree", "(", "doc", ",", "defaultTitle", ")", "{", "// save the parsed tree", "const", "tree", "=", "[", "]", ";", "const", "lines", "=", "doc", ".", "split", "(", "'\\n'", ")", ";", "let", "line", ",", "m", ";", "// 保存一个文档区域", "let...
parse a md document to an abstract document tree
[ "parse", "a", "md", "document", "to", "an", "abstract", "document", "tree" ]
234026a000943f0f93e8df6b8d0e893addd91ddc
https://github.com/johvin/adjust-md-for-publish/blob/234026a000943f0f93e8df6b8d0e893addd91ddc/index.js#L44-L95
49,722
johvin/adjust-md-for-publish
index.js
treeDFS
function treeDFS(tree, callback) { for (let it of tree.slice()) { callback(it, tree); if (typeof it === 'object') { treeDFS(it.children, callback); } } }
javascript
function treeDFS(tree, callback) { for (let it of tree.slice()) { callback(it, tree); if (typeof it === 'object') { treeDFS(it.children, callback); } } }
[ "function", "treeDFS", "(", "tree", ",", "callback", ")", "{", "for", "(", "let", "it", "of", "tree", ".", "slice", "(", ")", ")", "{", "callback", "(", "it", ",", "tree", ")", ";", "if", "(", "typeof", "it", "===", "'object'", ")", "{", "treeDFS...
traverse tree with dfs
[ "traverse", "tree", "with", "dfs" ]
234026a000943f0f93e8df6b8d0e893addd91ddc
https://github.com/johvin/adjust-md-for-publish/blob/234026a000943f0f93e8df6b8d0e893addd91ddc/index.js#L98-L105
49,723
johvin/adjust-md-for-publish
index.js
treeToDoc
function treeToDoc(tree) { if (tree.length === 0) return ''; return tree.map((it) => { if (typeof it === 'object') { return `${'#'.repeat(it.level)} ${it.title}\n${treeToDoc(it.children)}`; } return it; }).join('\n'); }
javascript
function treeToDoc(tree) { if (tree.length === 0) return ''; return tree.map((it) => { if (typeof it === 'object') { return `${'#'.repeat(it.level)} ${it.title}\n${treeToDoc(it.children)}`; } return it; }).join('\n'); }
[ "function", "treeToDoc", "(", "tree", ")", "{", "if", "(", "tree", ".", "length", "===", "0", ")", "return", "''", ";", "return", "tree", ".", "map", "(", "(", "it", ")", "=>", "{", "if", "(", "typeof", "it", "===", "'object'", ")", "{", "return"...
convert an abstract md tree to document
[ "convert", "an", "abstract", "md", "tree", "to", "document" ]
234026a000943f0f93e8df6b8d0e893addd91ddc
https://github.com/johvin/adjust-md-for-publish/blob/234026a000943f0f93e8df6b8d0e893addd91ddc/index.js#L108-L117
49,724
vkiding/judpack-lib
src/plugman/install.js
callEngineScripts
function callEngineScripts(engines, project_dir) { return Q.all( engines.map(function(engine){ // CB-5192; on Windows scriptSrc doesn't have file extension so we shouldn't check whether the script exists var scriptPath = engine.scriptSrc ? '"' + engine.scriptSrc + '"' : null; if(scriptPath && (isWindows || fs.existsSync(engine.scriptSrc)) ) { var d = Q.defer(); if(!isWindows) { // not required on Windows fs.chmodSync(engine.scriptSrc, '755'); } child_process.exec(scriptPath, function(error, stdout, stderr) { if (error) { events.emit('warn', engine.name +' version check failed ('+ scriptPath +'), continuing anyways.'); engine.currentVersion = null; } else { engine.currentVersion = cleanVersionOutput(stdout, engine.name); if (engine.currentVersion === '') { events.emit('warn', engine.name +' version check returned nothing ('+ scriptPath +'), continuing anyways.'); engine.currentVersion = null; } } d.resolve(engine); }); return d.promise; } else { if(engine.currentVersion) { engine.currentVersion = cleanVersionOutput(engine.currentVersion, engine.name); } else { events.emit('warn', engine.name +' version not detected (lacks script '+ scriptPath +' ), continuing.'); } return Q(engine); } }) ); }
javascript
function callEngineScripts(engines, project_dir) { return Q.all( engines.map(function(engine){ // CB-5192; on Windows scriptSrc doesn't have file extension so we shouldn't check whether the script exists var scriptPath = engine.scriptSrc ? '"' + engine.scriptSrc + '"' : null; if(scriptPath && (isWindows || fs.existsSync(engine.scriptSrc)) ) { var d = Q.defer(); if(!isWindows) { // not required on Windows fs.chmodSync(engine.scriptSrc, '755'); } child_process.exec(scriptPath, function(error, stdout, stderr) { if (error) { events.emit('warn', engine.name +' version check failed ('+ scriptPath +'), continuing anyways.'); engine.currentVersion = null; } else { engine.currentVersion = cleanVersionOutput(stdout, engine.name); if (engine.currentVersion === '') { events.emit('warn', engine.name +' version check returned nothing ('+ scriptPath +'), continuing anyways.'); engine.currentVersion = null; } } d.resolve(engine); }); return d.promise; } else { if(engine.currentVersion) { engine.currentVersion = cleanVersionOutput(engine.currentVersion, engine.name); } else { events.emit('warn', engine.name +' version not detected (lacks script '+ scriptPath +' ), continuing.'); } return Q(engine); } }) ); }
[ "function", "callEngineScripts", "(", "engines", ",", "project_dir", ")", "{", "return", "Q", ".", "all", "(", "engines", ".", "map", "(", "function", "(", "engine", ")", "{", "// CB-5192; on Windows scriptSrc doesn't have file extension so we shouldn't check whether the ...
exec engine scripts in order to get the current engine version Returns a promise for the array of engines.
[ "exec", "engine", "scripts", "in", "order", "to", "get", "the", "current", "engine", "version", "Returns", "a", "promise", "for", "the", "array", "of", "engines", "." ]
8657cecfec68221109279106adca8dbc81f430f4
https://github.com/vkiding/judpack-lib/blob/8657cecfec68221109279106adca8dbc81f430f4/src/plugman/install.js#L194-L234
49,725
ChrisAckerman/needy
needy.js
defineProperties
function defineProperties(target, options/*, source, ...*/) { if (options == null) options = {}; var i = 2, max = arguments.length, source, prop; for (; i < max; ++i) { source = arguments[i]; if (!(source instanceof Object)) continue; for (prop in source) { if (source[prop] == null) continue; defineProperty(target, prop, { value: source[prop], enumerable: options.enumerable == null ? true : !!options.enumerable, writable: options.writable == null ? true : !!options.writable, configurable: options.configurable == null ? true : !!options.configurable }); } } return target; }
javascript
function defineProperties(target, options/*, source, ...*/) { if (options == null) options = {}; var i = 2, max = arguments.length, source, prop; for (; i < max; ++i) { source = arguments[i]; if (!(source instanceof Object)) continue; for (prop in source) { if (source[prop] == null) continue; defineProperty(target, prop, { value: source[prop], enumerable: options.enumerable == null ? true : !!options.enumerable, writable: options.writable == null ? true : !!options.writable, configurable: options.configurable == null ? true : !!options.configurable }); } } return target; }
[ "function", "defineProperties", "(", "target", ",", "options", "/*, source, ...*/", ")", "{", "if", "(", "options", "==", "null", ")", "options", "=", "{", "}", ";", "var", "i", "=", "2", ",", "max", "=", "arguments", ".", "length", ",", "source", ",",...
Define multiple properties with similar configuration values.
[ "Define", "multiple", "properties", "with", "similar", "configuration", "values", "." ]
44df50a3c41b65550e5dc90dc1f5fc73a36c5a51
https://github.com/ChrisAckerman/needy/blob/44df50a3c41b65550e5dc90dc1f5fc73a36c5a51/needy.js#L21-L51
49,726
ChrisAckerman/needy
needy.js
setProperties
function setProperties(target/*, source, ...*/) { var i = 1, max = arguments.length, source, prop; for (; i < max; ++i) { source = arguments[i]; if (!(source instanceof Object)) continue; for (prop in source) { if (source[prop] == null) continue; target[prop] = source[prop]; } } return target; }
javascript
function setProperties(target/*, source, ...*/) { var i = 1, max = arguments.length, source, prop; for (; i < max; ++i) { source = arguments[i]; if (!(source instanceof Object)) continue; for (prop in source) { if (source[prop] == null) continue; target[prop] = source[prop]; } } return target; }
[ "function", "setProperties", "(", "target", "/*, source, ...*/", ")", "{", "var", "i", "=", "1", ",", "max", "=", "arguments", ".", "length", ",", "source", ",", "prop", ";", "for", "(", ";", "i", "<", "max", ";", "++", "i", ")", "{", "source", "="...
Copy non-null properties from all sources, to the target
[ "Copy", "non", "-", "null", "properties", "from", "all", "sources", "to", "the", "target" ]
44df50a3c41b65550e5dc90dc1f5fc73a36c5a51
https://github.com/ChrisAckerman/needy/blob/44df50a3c41b65550e5dc90dc1f5fc73a36c5a51/needy.js#L54-L76
49,727
ChrisAckerman/needy
needy.js
extendClass
function extendClass(parent, constructor) { var anonymous = function() {}; anonymous.prototype = parent.prototype; constructor.prototype = new anonymous(); constructor.constructor = constructor; defineProperties.apply(null, [constructor.prototype, { configurable: false }].concat(Array.prototype.slice.call(arguments, 2))); defineProperties(constructor, { configurable: false }, { extend: partial(extendClass, constructor) }); return constructor; }
javascript
function extendClass(parent, constructor) { var anonymous = function() {}; anonymous.prototype = parent.prototype; constructor.prototype = new anonymous(); constructor.constructor = constructor; defineProperties.apply(null, [constructor.prototype, { configurable: false }].concat(Array.prototype.slice.call(arguments, 2))); defineProperties(constructor, { configurable: false }, { extend: partial(extendClass, constructor) }); return constructor; }
[ "function", "extendClass", "(", "parent", ",", "constructor", ")", "{", "var", "anonymous", "=", "function", "(", ")", "{", "}", ";", "anonymous", ".", "prototype", "=", "parent", ".", "prototype", ";", "constructor", ".", "prototype", "=", "new", "anonymo...
Simple JavaScript inheritance. Nothing fancy.
[ "Simple", "JavaScript", "inheritance", ".", "Nothing", "fancy", "." ]
44df50a3c41b65550e5dc90dc1f5fc73a36c5a51
https://github.com/ChrisAckerman/needy/blob/44df50a3c41b65550e5dc90dc1f5fc73a36c5a51/needy.js#L79-L93
49,728
ChrisAckerman/needy
needy.js
dethrow
function dethrow(fn) { try { /* jshint validthis: true */ return fn.apply(this, Array.prototype.slice.call(arguments, 1)); } catch (e) {} }
javascript
function dethrow(fn) { try { /* jshint validthis: true */ return fn.apply(this, Array.prototype.slice.call(arguments, 1)); } catch (e) {} }
[ "function", "dethrow", "(", "fn", ")", "{", "try", "{", "/* jshint validthis: true */", "return", "fn", ".", "apply", "(", "this", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "}", "catch", "(", ...
Call a function ignoring any exceptions that it throws.
[ "Call", "a", "function", "ignoring", "any", "exceptions", "that", "it", "throws", "." ]
44df50a3c41b65550e5dc90dc1f5fc73a36c5a51
https://github.com/ChrisAckerman/needy/blob/44df50a3c41b65550e5dc90dc1f5fc73a36c5a51/needy.js#L96-L104
49,729
ChrisAckerman/needy
needy.js
portable
function portable(obj, fn) { if (typeof fn === 'string') fn = obj[fn]; return function() { return fn.apply(obj, arguments); }; }
javascript
function portable(obj, fn) { if (typeof fn === 'string') fn = obj[fn]; return function() { return fn.apply(obj, arguments); }; }
[ "function", "portable", "(", "obj", ",", "fn", ")", "{", "if", "(", "typeof", "fn", "===", "'string'", ")", "fn", "=", "obj", "[", "fn", "]", ";", "return", "function", "(", ")", "{", "return", "fn", ".", "apply", "(", "obj", ",", "arguments", ")...
Permantently override the "this" value of a function.
[ "Permantently", "override", "the", "this", "value", "of", "a", "function", "." ]
44df50a3c41b65550e5dc90dc1f5fc73a36c5a51
https://github.com/ChrisAckerman/needy/blob/44df50a3c41b65550e5dc90dc1f5fc73a36c5a51/needy.js#L117-L126
49,730
ChrisAckerman/needy
needy.js
isValidPath
function isValidPath(path, allowDots) { if (typeof path !== 'string') return false; if (!path) return false; if (!/^([a-z]:[\/\\])?[a-z0-9_~\/\.\-]+$/i.test(path)) return false; if (!allowDots && /^\.{1,2}$/.test(path)) return false; return true; }
javascript
function isValidPath(path, allowDots) { if (typeof path !== 'string') return false; if (!path) return false; if (!/^([a-z]:[\/\\])?[a-z0-9_~\/\.\-]+$/i.test(path)) return false; if (!allowDots && /^\.{1,2}$/.test(path)) return false; return true; }
[ "function", "isValidPath", "(", "path", ",", "allowDots", ")", "{", "if", "(", "typeof", "path", "!==", "'string'", ")", "return", "false", ";", "if", "(", "!", "path", ")", "return", "false", ";", "if", "(", "!", "/", "^([a-z]:[\\/\\\\])?[a-z0-9_~\\/\\.\\...
Make sure a path is a string, isn't empty, contains valid characters, and optionally isn't a dot path.
[ "Make", "sure", "a", "path", "is", "a", "string", "isn", "t", "empty", "contains", "valid", "characters", "and", "optionally", "isn", "t", "a", "dot", "path", "." ]
44df50a3c41b65550e5dc90dc1f5fc73a36c5a51
https://github.com/ChrisAckerman/needy/blob/44df50a3c41b65550e5dc90dc1f5fc73a36c5a51/needy.js#L202-L214
49,731
ChrisAckerman/needy
needy.js
csv
function csv(array) { if (!(array instanceof Array) || array.length === 0) return ''; array = array.slice(0); var i = array.length; while (i--) array[i] = '"' + (''+array[i]).replace(/(\\|")/g, '\\$1') + '"'; return array.join(', '); }
javascript
function csv(array) { if (!(array instanceof Array) || array.length === 0) return ''; array = array.slice(0); var i = array.length; while (i--) array[i] = '"' + (''+array[i]).replace(/(\\|")/g, '\\$1') + '"'; return array.join(', '); }
[ "function", "csv", "(", "array", ")", "{", "if", "(", "!", "(", "array", "instanceof", "Array", ")", "||", "array", ".", "length", "===", "0", ")", "return", "''", ";", "array", "=", "array", ".", "slice", "(", "0", ")", ";", "var", "i", "=", "...
Return a quoted CSV string.
[ "Return", "a", "quoted", "CSV", "string", "." ]
44df50a3c41b65550e5dc90dc1f5fc73a36c5a51
https://github.com/ChrisAckerman/needy/blob/44df50a3c41b65550e5dc90dc1f5fc73a36c5a51/needy.js#L217-L229
49,732
chronicled/open-registry-utils
lib/urn.js
function(encoded) { if (encoded instanceof Array) { encoded = encoded.map(function(chunk) {return chunk.replace(/^0x/g, '')}).join(''); } // Each symbol is 4 bits var result = []; var nextIndex = 0; while (nextIndex < encoded.length) { var schemaLength = parseInt(encoded.slice(nextIndex, nextIndex + 1 * 2), 16); var idLength = parseInt(encoded.slice(nextIndex + (1 + schemaLength) * 2, nextIndex + (1 + schemaLength + 2) * 2), 16); var schema = encoded.slice(nextIndex + 1 * 2, nextIndex + (1 + schemaLength) * 2); // Convert to string schema = hexToString(schema); var idHex = encoded.slice(nextIndex + (1 + schemaLength + 2) * 2, nextIndex + (1 + schemaLength + 2 + idLength) * 2); var id = schema.match(allowedProtocolsRegExp) ? idHex : hexToString(idHex); result.push(schema + ':' + id); // Get full cells var cellsPerId = Math.ceil((1 + schemaLength + 2 + idLength) / 32); nextIndex += cellsPerId * 32 * 2; } return result; }
javascript
function(encoded) { if (encoded instanceof Array) { encoded = encoded.map(function(chunk) {return chunk.replace(/^0x/g, '')}).join(''); } // Each symbol is 4 bits var result = []; var nextIndex = 0; while (nextIndex < encoded.length) { var schemaLength = parseInt(encoded.slice(nextIndex, nextIndex + 1 * 2), 16); var idLength = parseInt(encoded.slice(nextIndex + (1 + schemaLength) * 2, nextIndex + (1 + schemaLength + 2) * 2), 16); var schema = encoded.slice(nextIndex + 1 * 2, nextIndex + (1 + schemaLength) * 2); // Convert to string schema = hexToString(schema); var idHex = encoded.slice(nextIndex + (1 + schemaLength + 2) * 2, nextIndex + (1 + schemaLength + 2 + idLength) * 2); var id = schema.match(allowedProtocolsRegExp) ? idHex : hexToString(idHex); result.push(schema + ':' + id); // Get full cells var cellsPerId = Math.ceil((1 + schemaLength + 2 + idLength) / 32); nextIndex += cellsPerId * 32 * 2; } return result; }
[ "function", "(", "encoded", ")", "{", "if", "(", "encoded", "instanceof", "Array", ")", "{", "encoded", "=", "encoded", ".", "map", "(", "function", "(", "chunk", ")", "{", "return", "chunk", ".", "replace", "(", "/", "^0x", "/", "g", ",", "''", ")...
Accepts both chunks array and hex string
[ "Accepts", "both", "chunks", "array", "and", "hex", "string" ]
b0a9a35a72f57c0280b78b6d2ef81582407632f1
https://github.com/chronicled/open-registry-utils/blob/b0a9a35a72f57c0280b78b6d2ef81582407632f1/lib/urn.js#L195-L220
49,733
BrightContext/node-sdk
bcc_socket.js
openSocket
function openSocket (sessionInfo, callback) { var socketUrl, socketInfo, socket_endpoint, new_socket; _log(sessionInfo); socketUrl = sessionInfo.endpoints.socket[0]; socketInfo = url.parse(socketUrl); _log(socketInfo); socket_endpoint = socketUrl + me.setting.apiroot + '/feed/ws?sid=' + sessionInfo.sid; _log('Connecting to ' + socket_endpoint); new_socket = new ws(socket_endpoint); new_socket.on('open', function () { _log('socket open'); callback(new_socket); }); }
javascript
function openSocket (sessionInfo, callback) { var socketUrl, socketInfo, socket_endpoint, new_socket; _log(sessionInfo); socketUrl = sessionInfo.endpoints.socket[0]; socketInfo = url.parse(socketUrl); _log(socketInfo); socket_endpoint = socketUrl + me.setting.apiroot + '/feed/ws?sid=' + sessionInfo.sid; _log('Connecting to ' + socket_endpoint); new_socket = new ws(socket_endpoint); new_socket.on('open', function () { _log('socket open'); callback(new_socket); }); }
[ "function", "openSocket", "(", "sessionInfo", ",", "callback", ")", "{", "var", "socketUrl", ",", "socketInfo", ",", "socket_endpoint", ",", "new_socket", ";", "_log", "(", "sessionInfo", ")", ";", "socketUrl", "=", "sessionInfo", ".", "endpoints", ".", "socke...
connect to first available socket endpoint
[ "connect", "to", "first", "available", "socket", "endpoint" ]
db9dfb4faa649236eee8c4099d79ecfc21ef9b19
https://github.com/BrightContext/node-sdk/blob/db9dfb4faa649236eee8c4099d79ecfc21ef9b19/bcc_socket.js#L147-L164
49,734
HelloCodeMing/spiderer
lib/index.js
initialize
function initialize(options) { // log config.logfile = options.logfile || 'logs/spider.log'; log4js.configure({ appenders: [ { type: 'console', category: 'console'}, { type: 'dateFile', filename: config.logfile, pattern: 'yyyy-MM-dd', category: 'default' } ], replaceConsole: true }); logger = log4js.getLogger('default'); if (!options.startURLs) { logger.error('At least one URL must be specified!'); return -1; } if (!options.filter) { logger.error('Filter must be specified!'); return -1; } config.filter = options.filter; config.startURLs = options.startURLs; config.domains = options.startURLs.map(function(url) { return URL.parse(url).host; }); config.interval = options.interval || 2 * 1000; config.domains.forEach(function(host) { taskQueues[host] = []; }); config.timeout = options.timeout || 10 * 1000; // push all URLs into taskQueues config.startURLs.forEach(function(url) { var urlObj = URL.parse(url); var queue = new TaskQueue(urlObj.host); queue.tasks.push(url); taskQueues.push(queue); }); }
javascript
function initialize(options) { // log config.logfile = options.logfile || 'logs/spider.log'; log4js.configure({ appenders: [ { type: 'console', category: 'console'}, { type: 'dateFile', filename: config.logfile, pattern: 'yyyy-MM-dd', category: 'default' } ], replaceConsole: true }); logger = log4js.getLogger('default'); if (!options.startURLs) { logger.error('At least one URL must be specified!'); return -1; } if (!options.filter) { logger.error('Filter must be specified!'); return -1; } config.filter = options.filter; config.startURLs = options.startURLs; config.domains = options.startURLs.map(function(url) { return URL.parse(url).host; }); config.interval = options.interval || 2 * 1000; config.domains.forEach(function(host) { taskQueues[host] = []; }); config.timeout = options.timeout || 10 * 1000; // push all URLs into taskQueues config.startURLs.forEach(function(url) { var urlObj = URL.parse(url); var queue = new TaskQueue(urlObj.host); queue.tasks.push(url); taskQueues.push(queue); }); }
[ "function", "initialize", "(", "options", ")", "{", "// log", "config", ".", "logfile", "=", "options", ".", "logfile", "||", "'logs/spider.log'", ";", "log4js", ".", "configure", "(", "{", "appenders", ":", "[", "{", "type", ":", "'console'", ",", "catego...
Initialize the spider, with some configurations. options.filter options.startURLS options.interval options.logfile options.timeout
[ "Initialize", "the", "spider", "with", "some", "configurations", ".", "options", ".", "filter", "options", ".", "startURLS", "options", ".", "interval", "options", ".", "logfile", "options", ".", "timeout" ]
6659a68f04c154f6d5b3edb46b6049ac7732964b
https://github.com/HelloCodeMing/spiderer/blob/6659a68f04c154f6d5b3edb46b6049ac7732964b/lib/index.js#L97-L139
49,735
gethuman/pancakes-recipe
middleware/mw.ssl.js
init
function init(ctx) { var server = ctx.server; server.ext('onRequest', checkIfSSL); return new Q(ctx); }
javascript
function init(ctx) { var server = ctx.server; server.ext('onRequest', checkIfSSL); return new Q(ctx); }
[ "function", "init", "(", "ctx", ")", "{", "var", "server", "=", "ctx", ".", "server", ";", "server", ".", "ext", "(", "'onRequest'", ",", "checkIfSSL", ")", ";", "return", "new", "Q", "(", "ctx", ")", ";", "}" ]
Add middleware for doing redirects
[ "Add", "middleware", "for", "doing", "redirects" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/middleware/mw.ssl.js#L46-L50
49,736
scrapjs/typling-core
lib/signature.js
parse
function parse (strip, associate) { var signature = strip.split('->') if (signature.length !== 2) return null // Param types: var params = signature[0].split(',') for (var i = params.length; i--;) { var p = params[i].trim() if (p === '*') params[i] = null else params[i] = p } // Return type: var returns = signature[1].trim() if (returns === '*') returns = null return associate ? [params, returns, associate] : [params, returns] }
javascript
function parse (strip, associate) { var signature = strip.split('->') if (signature.length !== 2) return null // Param types: var params = signature[0].split(',') for (var i = params.length; i--;) { var p = params[i].trim() if (p === '*') params[i] = null else params[i] = p } // Return type: var returns = signature[1].trim() if (returns === '*') returns = null return associate ? [params, returns, associate] : [params, returns] }
[ "function", "parse", "(", "strip", ",", "associate", ")", "{", "var", "signature", "=", "strip", ".", "split", "(", "'->'", ")", "if", "(", "signature", ".", "length", "!==", "2", ")", "return", "null", "// Param types:", "var", "params", "=", "signature...
exports.parse = parse exports.generate = generate Parse a signature strip into a signature object
[ "exports", ".", "parse", "=", "parse", "exports", ".", "generate", "=", "generate", "Parse", "a", "signature", "strip", "into", "a", "signature", "object" ]
89168c7a70835c86fd7c1e4ed138ec588323c79c
https://github.com/scrapjs/typling-core/blob/89168c7a70835c86fd7c1e4ed138ec588323c79c/lib/signature.js#L6-L25
49,737
msecret/perf-hunter
build/index.js
require
function require(name, jumped){ if (cache[name]) return cache[name].exports; if (modules[name]) return call(name, require); throw new Error('cannot find module "' + name + '"'); }
javascript
function require(name, jumped){ if (cache[name]) return cache[name].exports; if (modules[name]) return call(name, require); throw new Error('cannot find module "' + name + '"'); }
[ "function", "require", "(", "name", ",", "jumped", ")", "{", "if", "(", "cache", "[", "name", "]", ")", "return", "cache", "[", "name", "]", ".", "exports", ";", "if", "(", "modules", "[", "name", "]", ")", "return", "call", "(", "name", ",", "re...
Require `name`. @param {String} name @param {Boolean} jumped @api public
[ "Require", "name", "." ]
61ccd794e8744eb6438f7c08bf49dae5d90cc4f5
https://github.com/msecret/perf-hunter/blob/61ccd794e8744eb6438f7c08bf49dae5d90cc4f5/build/index.js#L17-L21
49,738
msecret/perf-hunter
build/index.js
call
function call(id, require){ var m = { exports: {} }; var mod = modules[id]; var name = mod[2]; var fn = mod[0]; fn.call(m.exports, function(req){ var dep = modules[id][1][req]; return require(dep || req); }, m, m.exports, outer, modules, cache, entries); // store to cache after successful resolve cache[id] = m; // expose as `name`. if (name) cache[name] = cache[id]; return cache[id].exports; }
javascript
function call(id, require){ var m = { exports: {} }; var mod = modules[id]; var name = mod[2]; var fn = mod[0]; fn.call(m.exports, function(req){ var dep = modules[id][1][req]; return require(dep || req); }, m, m.exports, outer, modules, cache, entries); // store to cache after successful resolve cache[id] = m; // expose as `name`. if (name) cache[name] = cache[id]; return cache[id].exports; }
[ "function", "call", "(", "id", ",", "require", ")", "{", "var", "m", "=", "{", "exports", ":", "{", "}", "}", ";", "var", "mod", "=", "modules", "[", "id", "]", ";", "var", "name", "=", "mod", "[", "2", "]", ";", "var", "fn", "=", "mod", "[...
Call module `id` and cache it. @param {Number} id @param {Function} require @return {Function} @api private
[ "Call", "module", "id", "and", "cache", "it", "." ]
61ccd794e8744eb6438f7c08bf49dae5d90cc4f5
https://github.com/msecret/perf-hunter/blob/61ccd794e8744eb6438f7c08bf49dae5d90cc4f5/build/index.js#L32-L50
49,739
msecret/perf-hunter
build/index.js
function() { // Walk all of the elements in the DOM (try to only do this once) var elements = doc.getElementsByTagName('*'); var re = /url\((http.*)\)/ig; for (var i = 0; i < elements.length; i++) { var el = elements[i]; var style = win.getComputedStyle(el); // check for Images if (el.tagName == 'IMG') { CheckElement(el, el.src); } // Check for background images if (style['background-image']) { re.lastIndex = 0; var matches = re.exec(style['background-image']); if (matches && matches.length > 1) CheckElement(el, matches[1]); } // recursively walk any iFrames if (el.tagName == 'IFRAME') { try { var rect = GetElementViewportRect(el); if (rect) { var tm = RUMSpeedIndex(el.contentWindow); if (tm) { rects.push({'tm': tm, 'area': rect.area, 'rect': rect}); } } } catch(e) { } } } }
javascript
function() { // Walk all of the elements in the DOM (try to only do this once) var elements = doc.getElementsByTagName('*'); var re = /url\((http.*)\)/ig; for (var i = 0; i < elements.length; i++) { var el = elements[i]; var style = win.getComputedStyle(el); // check for Images if (el.tagName == 'IMG') { CheckElement(el, el.src); } // Check for background images if (style['background-image']) { re.lastIndex = 0; var matches = re.exec(style['background-image']); if (matches && matches.length > 1) CheckElement(el, matches[1]); } // recursively walk any iFrames if (el.tagName == 'IFRAME') { try { var rect = GetElementViewportRect(el); if (rect) { var tm = RUMSpeedIndex(el.contentWindow); if (tm) { rects.push({'tm': tm, 'area': rect.area, 'rect': rect}); } } } catch(e) { } } } }
[ "function", "(", ")", "{", "// Walk all of the elements in the DOM (try to only do this once)", "var", "elements", "=", "doc", ".", "getElementsByTagName", "(", "'*'", ")", ";", "var", "re", "=", "/", "url\\((http.*)\\)", "/", "ig", ";", "for", "(", "var", "i", ...
Get the visible rectangles for elements that we care about
[ "Get", "the", "visible", "rectangles", "for", "elements", "that", "we", "care", "about" ]
61ccd794e8744eb6438f7c08bf49dae5d90cc4f5
https://github.com/msecret/perf-hunter/blob/61ccd794e8744eb6438f7c08bf49dae5d90cc4f5/build/index.js#L209-L244
49,740
vkiding/judpack-lib
src/hooks/Context.js
Context
function Context(hook, opts) { var prop; this.hook = hook; //create new object, to avoid affecting input opts in other places //For example context.opts.plugin = Object is done, then it affects by reference this.opts = {}; for (prop in opts) { if (opts.hasOwnProperty(prop)) { this.opts[prop] = opts[prop]; } } this.cmdLine = process.argv.join(' '); this.cordova = require('../cordova/cordova'); }
javascript
function Context(hook, opts) { var prop; this.hook = hook; //create new object, to avoid affecting input opts in other places //For example context.opts.plugin = Object is done, then it affects by reference this.opts = {}; for (prop in opts) { if (opts.hasOwnProperty(prop)) { this.opts[prop] = opts[prop]; } } this.cmdLine = process.argv.join(' '); this.cordova = require('../cordova/cordova'); }
[ "function", "Context", "(", "hook", ",", "opts", ")", "{", "var", "prop", ";", "this", ".", "hook", "=", "hook", ";", "//create new object, to avoid affecting input opts in other places", "//For example context.opts.plugin = Object is done, then it affects by reference", "this"...
Creates hook script context @constructor @param {String} hook The hook type @param {Object} opts Hook options @returns {Object}
[ "Creates", "hook", "script", "context" ]
8657cecfec68221109279106adca8dbc81f430f4
https://github.com/vkiding/judpack-lib/blob/8657cecfec68221109279106adca8dbc81f430f4/src/hooks/Context.js#L29-L43
49,741
tolokoban/ToloFrameWork
ker/mod/wdg.area.js
grow
function grow(area, min, max) { if( typeof min !== 'undefined' ) { min = parseInt( min ); if( isNaN( min ) ) min = 2; } if( typeof max !== 'undefined' ) { max = parseInt( max ); if( isNaN( max ) ) max = 8; } if( max < min ) max = min; var text = area.value; var lines = 1; var index = -1; for(;;) { index = text.indexOf( "\n", index + 1 ); if( index === -1 ) break; lines++; } index = Math.max( min, Math.min( max, index ) ); $.att( area, {rows: lines} ); }
javascript
function grow(area, min, max) { if( typeof min !== 'undefined' ) { min = parseInt( min ); if( isNaN( min ) ) min = 2; } if( typeof max !== 'undefined' ) { max = parseInt( max ); if( isNaN( max ) ) max = 8; } if( max < min ) max = min; var text = area.value; var lines = 1; var index = -1; for(;;) { index = text.indexOf( "\n", index + 1 ); if( index === -1 ) break; lines++; } index = Math.max( min, Math.min( max, index ) ); $.att( area, {rows: lines} ); }
[ "function", "grow", "(", "area", ",", "min", ",", "max", ")", "{", "if", "(", "typeof", "min", "!==", "'undefined'", ")", "{", "min", "=", "parseInt", "(", "min", ")", ";", "if", "(", "isNaN", "(", "min", ")", ")", "min", "=", "2", ";", "}", ...
Check the number of rows regarding the inner text.
[ "Check", "the", "number", "of", "rows", "regarding", "the", "inner", "text", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/wdg.area.js#L113-L134
49,742
jeswin-unmaintained/isotropy-koa-context-in-browser
lib/request.js
function(field){ var req = this.req; field = field.toLowerCase(); switch (field) { case 'referer': case 'referrer': return req.headers.referrer || req.headers.referer || ''; default: return req.headers[field] || ''; } }
javascript
function(field){ var req = this.req; field = field.toLowerCase(); switch (field) { case 'referer': case 'referrer': return req.headers.referrer || req.headers.referer || ''; default: return req.headers[field] || ''; } }
[ "function", "(", "field", ")", "{", "var", "req", "=", "this", ".", "req", ";", "field", "=", "field", ".", "toLowerCase", "(", ")", ";", "switch", "(", "field", ")", "{", "case", "'referer'", ":", "case", "'referrer'", ":", "return", "req", ".", "...
Return request header. The `Referrer` header field is special-cased, both `Referrer` and `Referer` are interchangeable. Examples: this.get('Content-Type'); // => "text/plain" this.get('content-type'); // => "text/plain" this.get('Something'); // => undefined @param {String} field @return {String} @api public
[ "Return", "request", "header", "." ]
033a3ac0fd65ba6ac2b4ce715b3da54f873eed6f
https://github.com/jeswin-unmaintained/isotropy-koa-context-in-browser/blob/033a3ac0fd65ba6ac2b4ce715b3da54f873eed6f/lib/request.js#L561-L571
49,743
bleupen/glib
lib/index.js
logToConsole
function logToConsole(tags, message) { if (enabled) { if (arguments.length < 2) { message = tags; tags = []; } if (!util.isArray(tags)) tags = []; var text = new Date().getTime() + ', '; if (tags.length > 0) { text = text + tags[0] + ', '; } text = text + message; console.log(text); } }
javascript
function logToConsole(tags, message) { if (enabled) { if (arguments.length < 2) { message = tags; tags = []; } if (!util.isArray(tags)) tags = []; var text = new Date().getTime() + ', '; if (tags.length > 0) { text = text + tags[0] + ', '; } text = text + message; console.log(text); } }
[ "function", "logToConsole", "(", "tags", ",", "message", ")", "{", "if", "(", "enabled", ")", "{", "if", "(", "arguments", ".", "length", "<", "2", ")", "{", "message", "=", "tags", ";", "tags", "=", "[", "]", ";", "}", "if", "(", "!", "util", ...
Default console logger for use outside of hapi container @param tags @param message
[ "Default", "console", "logger", "for", "use", "outside", "of", "hapi", "container" ]
f47c6694761821197d790f617127b47f4e3be60f
https://github.com/bleupen/glib/blob/f47c6694761821197d790f617127b47f4e3be60f/lib/index.js#L13-L29
49,744
bleupen/glib
lib/index.js
parseTags
function parseTags(tags) { if (tags.length > 0 && util.isArray(tags[0])) { tags = tags[0]; } return tags; }
javascript
function parseTags(tags) { if (tags.length > 0 && util.isArray(tags[0])) { tags = tags[0]; } return tags; }
[ "function", "parseTags", "(", "tags", ")", "{", "if", "(", "tags", ".", "length", ">", "0", "&&", "util", ".", "isArray", "(", "tags", "[", "0", "]", ")", ")", "{", "tags", "=", "tags", "[", "0", "]", ";", "}", "return", "tags", ";", "}" ]
Assists with parsing var-arg'ed tags @param tags @return {*}
[ "Assists", "with", "parsing", "var", "-", "arg", "ed", "tags" ]
f47c6694761821197d790f617127b47f4e3be60f
https://github.com/bleupen/glib/blob/f47c6694761821197d790f617127b47f4e3be60f/lib/index.js#L36-L42
49,745
bleupen/glib
lib/index.js
Logger
function Logger(tags) { tags = parseTags(Array.prototype.slice.call(arguments)); if (!(this instanceof Logger)) { return new Logger(tags); } this.tags = tags; }
javascript
function Logger(tags) { tags = parseTags(Array.prototype.slice.call(arguments)); if (!(this instanceof Logger)) { return new Logger(tags); } this.tags = tags; }
[ "function", "Logger", "(", "tags", ")", "{", "tags", "=", "parseTags", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", ";", "if", "(", "!", "(", "this", "instanceof", "Logger", ")", ")", "{", "return", "new", ...
Logger constructor. may be invoked directly or as a constructor @param {string[]=} tags an array of default tags to include with log messages @return {Logger} a new logger instance @constructor
[ "Logger", "constructor", ".", "may", "be", "invoked", "directly", "or", "as", "a", "constructor" ]
f47c6694761821197d790f617127b47f4e3be60f
https://github.com/bleupen/glib/blob/f47c6694761821197d790f617127b47f4e3be60f/lib/index.js#L50-L58
49,746
sbugert/dishwasher
lib/dishwasher.js
rinse
function rinse (pageobj, finalarray, maps) { // Map where data will be inserted var map = maps.pagemap(); // Render data in temp object // var ruffian = plates.bind(partials[pageobj.mastertemplate], pageobj, map); var ruffian = partials[pageobj.mastertemplate]; // Render plates' simple case scenario // Iterate over Array of Strings if (pageobj.pagesingleset && finalarray) { insertSingleFragment(); } if (pageobj.pagemultiset && finalarray) { pageobj.pagemultiset.forEach(insertMultiFragment); } // This filters and renders collections of data from the array of objects function insertMultiFragment (collection, index, array) { // Only get the objects with the correct collection value var filtered = finalarray.filter(function (element) { return element.collection === collection; }); // Map data with corresponding partials var map = maps.multimap(collection) , obj = {fragment : plates.bind(partials[collection], filtered, maps.collections())}; ruffian = plates.bind(ruffian, obj, map); } // This filters and renders objects which do not belong to a collection function insertSingleFragment () { for (var i = 0; i < finalarray.length; i++) { // Check whether the object belongs to a collection or not if (finalarray[i].collection === 'none') { var singlepartial = finalarray[i].partial , singledest = finalarray[i].destination , map = maps.singlemap(singledest) , obj = { 'fragment':plates.bind(partials[singlepartial], finalarray[i],maps.fragments())}; ruffian = plates.bind(ruffian, obj, map); } } } ruffian = plates.bind(ruffian, pageobj, map); // ruffian = plates.bind(ruffian, pageobj); return ruffian; }
javascript
function rinse (pageobj, finalarray, maps) { // Map where data will be inserted var map = maps.pagemap(); // Render data in temp object // var ruffian = plates.bind(partials[pageobj.mastertemplate], pageobj, map); var ruffian = partials[pageobj.mastertemplate]; // Render plates' simple case scenario // Iterate over Array of Strings if (pageobj.pagesingleset && finalarray) { insertSingleFragment(); } if (pageobj.pagemultiset && finalarray) { pageobj.pagemultiset.forEach(insertMultiFragment); } // This filters and renders collections of data from the array of objects function insertMultiFragment (collection, index, array) { // Only get the objects with the correct collection value var filtered = finalarray.filter(function (element) { return element.collection === collection; }); // Map data with corresponding partials var map = maps.multimap(collection) , obj = {fragment : plates.bind(partials[collection], filtered, maps.collections())}; ruffian = plates.bind(ruffian, obj, map); } // This filters and renders objects which do not belong to a collection function insertSingleFragment () { for (var i = 0; i < finalarray.length; i++) { // Check whether the object belongs to a collection or not if (finalarray[i].collection === 'none') { var singlepartial = finalarray[i].partial , singledest = finalarray[i].destination , map = maps.singlemap(singledest) , obj = { 'fragment':plates.bind(partials[singlepartial], finalarray[i],maps.fragments())}; ruffian = plates.bind(ruffian, obj, map); } } } ruffian = plates.bind(ruffian, pageobj, map); // ruffian = plates.bind(ruffian, pageobj); return ruffian; }
[ "function", "rinse", "(", "pageobj", ",", "finalarray", ",", "maps", ")", "{", "// Map where data will be inserted", "var", "map", "=", "maps", ".", "pagemap", "(", ")", ";", "// Render data in temp object", "// var ruffian = plates.bind(partials[pageobj.mastertemplate], pa...
This gets an object an an array of objects. The object defines how the data in the array is renderd
[ "This", "gets", "an", "object", "an", "an", "array", "of", "objects", ".", "The", "object", "defines", "how", "the", "data", "in", "the", "array", "is", "renderd" ]
5c8f5fb78977cc1ffd6f9b2884297d99490bbddf
https://github.com/sbugert/dishwasher/blob/5c8f5fb78977cc1ffd6f9b2884297d99490bbddf/lib/dishwasher.js#L10-L60
49,747
sbugert/dishwasher
lib/dishwasher.js
insertMultiFragment
function insertMultiFragment (collection, index, array) { // Only get the objects with the correct collection value var filtered = finalarray.filter(function (element) { return element.collection === collection; }); // Map data with corresponding partials var map = maps.multimap(collection) , obj = {fragment : plates.bind(partials[collection], filtered, maps.collections())}; ruffian = plates.bind(ruffian, obj, map); }
javascript
function insertMultiFragment (collection, index, array) { // Only get the objects with the correct collection value var filtered = finalarray.filter(function (element) { return element.collection === collection; }); // Map data with corresponding partials var map = maps.multimap(collection) , obj = {fragment : plates.bind(partials[collection], filtered, maps.collections())}; ruffian = plates.bind(ruffian, obj, map); }
[ "function", "insertMultiFragment", "(", "collection", ",", "index", ",", "array", ")", "{", "// Only get the objects with the correct collection value", "var", "filtered", "=", "finalarray", ".", "filter", "(", "function", "(", "element", ")", "{", "return", "element"...
This filters and renders collections of data from the array of objects
[ "This", "filters", "and", "renders", "collections", "of", "data", "from", "the", "array", "of", "objects" ]
5c8f5fb78977cc1ffd6f9b2884297d99490bbddf
https://github.com/sbugert/dishwasher/blob/5c8f5fb78977cc1ffd6f9b2884297d99490bbddf/lib/dishwasher.js#L29-L40
49,748
sbugert/dishwasher
lib/dishwasher.js
insertSingleFragment
function insertSingleFragment () { for (var i = 0; i < finalarray.length; i++) { // Check whether the object belongs to a collection or not if (finalarray[i].collection === 'none') { var singlepartial = finalarray[i].partial , singledest = finalarray[i].destination , map = maps.singlemap(singledest) , obj = { 'fragment':plates.bind(partials[singlepartial], finalarray[i],maps.fragments())}; ruffian = plates.bind(ruffian, obj, map); } } }
javascript
function insertSingleFragment () { for (var i = 0; i < finalarray.length; i++) { // Check whether the object belongs to a collection or not if (finalarray[i].collection === 'none') { var singlepartial = finalarray[i].partial , singledest = finalarray[i].destination , map = maps.singlemap(singledest) , obj = { 'fragment':plates.bind(partials[singlepartial], finalarray[i],maps.fragments())}; ruffian = plates.bind(ruffian, obj, map); } } }
[ "function", "insertSingleFragment", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "finalarray", ".", "length", ";", "i", "++", ")", "{", "// Check whether the object belongs to a collection or not", "if", "(", "finalarray", "[", "i", "]", "...
This filters and renders objects which do not belong to a collection
[ "This", "filters", "and", "renders", "objects", "which", "do", "not", "belong", "to", "a", "collection" ]
5c8f5fb78977cc1ffd6f9b2884297d99490bbddf
https://github.com/sbugert/dishwasher/blob/5c8f5fb78977cc1ffd6f9b2884297d99490bbddf/lib/dishwasher.js#L43-L56
49,749
sbugert/dishwasher
lib/dishwasher.js
readPartials
function readPartials(userDir, cwd) { if (cwd) { userDir = path.join(cwd, userDir); } // Use working directory of process if not specified else { userDir = path.join(path.dirname(process.argv[1]), userDir); } partials = {}; var filenames = fs.readdirSync(userDir); for (var i = 0; i < filenames.length; i++) { partials[filenames[i].slice(0, -5)] = fs.readFileSync( path.join(userDir, filenames[i]), 'utf8' ); } return partials; }
javascript
function readPartials(userDir, cwd) { if (cwd) { userDir = path.join(cwd, userDir); } // Use working directory of process if not specified else { userDir = path.join(path.dirname(process.argv[1]), userDir); } partials = {}; var filenames = fs.readdirSync(userDir); for (var i = 0; i < filenames.length; i++) { partials[filenames[i].slice(0, -5)] = fs.readFileSync( path.join(userDir, filenames[i]), 'utf8' ); } return partials; }
[ "function", "readPartials", "(", "userDir", ",", "cwd", ")", "{", "if", "(", "cwd", ")", "{", "userDir", "=", "path", ".", "join", "(", "cwd", ",", "userDir", ")", ";", "}", "// Use working directory of process if not specified", "else", "{", "userDir", "=",...
Read all partials from disk
[ "Read", "all", "partials", "from", "disk" ]
5c8f5fb78977cc1ffd6f9b2884297d99490bbddf
https://github.com/sbugert/dishwasher/blob/5c8f5fb78977cc1ffd6f9b2884297d99490bbddf/lib/dishwasher.js#L63-L79
49,750
alejonext/humanquery
lib/compile.js
compile
function compile(node) { switch (node.type) { case 'field': var obj = {}; obj[node.name] = node.value; return obj; case 'op': var obj = {}; var op = '$' + node.op; obj[op] = [ compile(node.left), compile(node.right) ]; return obj; } }
javascript
function compile(node) { switch (node.type) { case 'field': var obj = {}; obj[node.name] = node.value; return obj; case 'op': var obj = {}; var op = '$' + node.op; obj[op] = [ compile(node.left), compile(node.right) ]; return obj; } }
[ "function", "compile", "(", "node", ")", "{", "switch", "(", "node", ".", "type", ")", "{", "case", "'field'", ":", "var", "obj", "=", "{", "}", ";", "obj", "[", "node", ".", "name", "]", "=", "node", ".", "value", ";", "return", "obj", ";", "c...
Compile `node` to a mongo query. @param {Object} node @return {Object} @api public
[ "Compile", "node", "to", "a", "mongo", "query", "." ]
f3dbc46379122f40bf9336991e9856a82fc95310
https://github.com/alejonext/humanquery/blob/f3dbc46379122f40bf9336991e9856a82fc95310/lib/compile.js#L16-L34
49,751
MakerCollider/node-red-contrib-smartnode-hook
html/scripts/jquery.blockUI.js
remove
function remove(el, opts) { var count; var full = (el == window); var $el = $(el); var data = $el.data('blockUI.history'); var to = $el.data('blockUI.timeout'); if (to) { clearTimeout(to); $el.removeData('blockUI.timeout'); } opts = $.extend({}, $.blockUI.defaults, opts || {}); bind(0, el, opts); // unbind events if (opts.onUnblock === null) { opts.onUnblock = $el.data('blockUI.onUnblock'); $el.removeData('blockUI.onUnblock'); } var els; if (full) // crazy selector to handle odd field errors in ie6/7 els = $('body').children().filter('.blockUI').add('body > .blockUI'); else els = $el.find('>.blockUI'); // fix cursor issue if ( opts.cursorReset ) { if ( els.length > 1 ) els[1].style.cursor = opts.cursorReset; if ( els.length > 2 ) els[2].style.cursor = opts.cursorReset; } if (full) pageBlock = pageBlockEls = null; if (opts.fadeOut) { count = els.length; els.stop().fadeOut(opts.fadeOut, function() { if ( --count === 0) reset(els,data,opts,el); }); } else reset(els, data, opts, el); }
javascript
function remove(el, opts) { var count; var full = (el == window); var $el = $(el); var data = $el.data('blockUI.history'); var to = $el.data('blockUI.timeout'); if (to) { clearTimeout(to); $el.removeData('blockUI.timeout'); } opts = $.extend({}, $.blockUI.defaults, opts || {}); bind(0, el, opts); // unbind events if (opts.onUnblock === null) { opts.onUnblock = $el.data('blockUI.onUnblock'); $el.removeData('blockUI.onUnblock'); } var els; if (full) // crazy selector to handle odd field errors in ie6/7 els = $('body').children().filter('.blockUI').add('body > .blockUI'); else els = $el.find('>.blockUI'); // fix cursor issue if ( opts.cursorReset ) { if ( els.length > 1 ) els[1].style.cursor = opts.cursorReset; if ( els.length > 2 ) els[2].style.cursor = opts.cursorReset; } if (full) pageBlock = pageBlockEls = null; if (opts.fadeOut) { count = els.length; els.stop().fadeOut(opts.fadeOut, function() { if ( --count === 0) reset(els,data,opts,el); }); } else reset(els, data, opts, el); }
[ "function", "remove", "(", "el", ",", "opts", ")", "{", "var", "count", ";", "var", "full", "=", "(", "el", "==", "window", ")", ";", "var", "$el", "=", "$", "(", "el", ")", ";", "var", "data", "=", "$el", ".", "data", "(", "'blockUI.history'", ...
remove the block
[ "remove", "the", "block" ]
245c267e832968bad880ca009929043e82c7bc25
https://github.com/MakerCollider/node-red-contrib-smartnode-hook/blob/245c267e832968bad880ca009929043e82c7bc25/html/scripts/jquery.blockUI.js#L457-L501
49,752
MakerCollider/node-red-contrib-smartnode-hook
html/scripts/jquery.blockUI.js
reset
function reset(els,data,opts,el) { var $el = $(el); if ( $el.data('blockUI.isBlocked') ) return; els.each(function(i,o) { // remove via DOM calls so we don't lose event handlers if (this.parentNode) this.parentNode.removeChild(this); }); if (data && data.el) { data.el.style.display = data.display; data.el.style.position = data.position; data.el.style.cursor = 'default'; // #59 if (data.parent) data.parent.appendChild(data.el); $el.removeData('blockUI.history'); } if ($el.data('blockUI.static')) { $el.css('position', 'static'); // #22 } if (typeof opts.onUnblock == 'function') opts.onUnblock(el,opts); // fix issue in Safari 6 where block artifacts remain until reflow var body = $(document.body), w = body.width(), cssW = body[0].style.width; body.width(w-1).width(w); body[0].style.width = cssW; }
javascript
function reset(els,data,opts,el) { var $el = $(el); if ( $el.data('blockUI.isBlocked') ) return; els.each(function(i,o) { // remove via DOM calls so we don't lose event handlers if (this.parentNode) this.parentNode.removeChild(this); }); if (data && data.el) { data.el.style.display = data.display; data.el.style.position = data.position; data.el.style.cursor = 'default'; // #59 if (data.parent) data.parent.appendChild(data.el); $el.removeData('blockUI.history'); } if ($el.data('blockUI.static')) { $el.css('position', 'static'); // #22 } if (typeof opts.onUnblock == 'function') opts.onUnblock(el,opts); // fix issue in Safari 6 where block artifacts remain until reflow var body = $(document.body), w = body.width(), cssW = body[0].style.width; body.width(w-1).width(w); body[0].style.width = cssW; }
[ "function", "reset", "(", "els", ",", "data", ",", "opts", ",", "el", ")", "{", "var", "$el", "=", "$", "(", "el", ")", ";", "if", "(", "$el", ".", "data", "(", "'blockUI.isBlocked'", ")", ")", "return", ";", "els", ".", "each", "(", "function", ...
move blocking element back into the DOM where it started
[ "move", "blocking", "element", "back", "into", "the", "DOM", "where", "it", "started" ]
245c267e832968bad880ca009929043e82c7bc25
https://github.com/MakerCollider/node-red-contrib-smartnode-hook/blob/245c267e832968bad880ca009929043e82c7bc25/html/scripts/jquery.blockUI.js#L504-L535
49,753
kvonflotow/local-json
index.js
watchFile
function watchFile( file ) { // make sure file is at least something if ( !file || '' === file ) { return } // make sure it's a string file = file.toString() if ( watchers.hasOwnProperty( file ) ) { return // already exists } // watch it watchers[ file ] = chokidar.watch( file, { ignored: /[\/\\]\./, persistent: true } ) var that = this // setup event listeners watchers[ file ] // listener for when the file has been removed .on( 'unlink', function ( path ) { that.opts.storageMethod.remove( path, function ( err ) { if ( err ) { if ( that.opts.logging ) { console.log( err ) } return } // success } ) } ) // listener for when the file has been changed .on( 'change', function ( path ) { // add to main file processing queue mainQueue.add( function ( mainDone ) { // attempt to read the file fs.readFile( path, function ( err, fileContents ) { // notify nbqueue that the async function has finished, // regardless of success mainDone() // check for errors if ( err ) { // see if LocalJson instance logging is enabled if ( that.opts.logging ) { console.log( err ) } return } var parsed = LocalJson.TryParse.call( that, JSON.parse, fileContents ) // cache new json that.opts.storageMethod.set( path, parsed, function ( err ) { if ( err ) { if ( that.opts.logging ) { console.log( err ) } return } // success } ) } ) } ) } ) }
javascript
function watchFile( file ) { // make sure file is at least something if ( !file || '' === file ) { return } // make sure it's a string file = file.toString() if ( watchers.hasOwnProperty( file ) ) { return // already exists } // watch it watchers[ file ] = chokidar.watch( file, { ignored: /[\/\\]\./, persistent: true } ) var that = this // setup event listeners watchers[ file ] // listener for when the file has been removed .on( 'unlink', function ( path ) { that.opts.storageMethod.remove( path, function ( err ) { if ( err ) { if ( that.opts.logging ) { console.log( err ) } return } // success } ) } ) // listener for when the file has been changed .on( 'change', function ( path ) { // add to main file processing queue mainQueue.add( function ( mainDone ) { // attempt to read the file fs.readFile( path, function ( err, fileContents ) { // notify nbqueue that the async function has finished, // regardless of success mainDone() // check for errors if ( err ) { // see if LocalJson instance logging is enabled if ( that.opts.logging ) { console.log( err ) } return } var parsed = LocalJson.TryParse.call( that, JSON.parse, fileContents ) // cache new json that.opts.storageMethod.set( path, parsed, function ( err ) { if ( err ) { if ( that.opts.logging ) { console.log( err ) } return } // success } ) } ) } ) } ) }
[ "function", "watchFile", "(", "file", ")", "{", "// make sure file is at least something", "if", "(", "!", "file", "||", "''", "===", "file", ")", "{", "return", "}", "// make sure it's a string", "file", "=", "file", ".", "toString", "(", ")", "if", "(", "w...
pass the full path of the file
[ "pass", "the", "full", "path", "of", "the", "file" ]
e29e2e63c554b64fe911629b87ddb2c81a68e1ea
https://github.com/kvonflotow/local-json/blob/e29e2e63c554b64fe911629b87ddb2c81a68e1ea/index.js#L29-L124
49,754
IonicaBizau/name-it
lib/index.js
NameIt
function NameIt(input) { var res = { _: [] , } , foos = Object.keys(NameIt) , i = 0 ; for (; i < foos.length; ++i) { res._.push(res[foos[i]] = NameIt[foos[i]](input)); } return res; }
javascript
function NameIt(input) { var res = { _: [] , } , foos = Object.keys(NameIt) , i = 0 ; for (; i < foos.length; ++i) { res._.push(res[foos[i]] = NameIt[foos[i]](input)); } return res; }
[ "function", "NameIt", "(", "input", ")", "{", "var", "res", "=", "{", "_", ":", "[", "]", ",", "}", ",", "foos", "=", "Object", ".", "keys", "(", "NameIt", ")", ",", "i", "=", "0", ";", "for", "(", ";", "i", "<", "foos", ".", "length", ";",...
NameIt Generates names for input keywords. @name NameIt @function @param {String} input The keyword to generate names for. @return {Object} An object containing the name results: - `_` (Array): An array of strings containing all the name results. It also contains fields generated from method names (e.g. `y`, `er`, `ify` etc).
[ "NameIt", "Generates", "names", "for", "input", "keywords", "." ]
9276ac740707e6d6089c274651a465e7fff4e9d0
https://github.com/IonicaBizau/name-it/blob/9276ac740707e6d6089c274651a465e7fff4e9d0/lib/index.js#L29-L42
49,755
wordijp/flexi-require
lib/internal/module-utils.js
mergeIfNeed
function mergeIfNeed(rtarget, o) { for (var key in o) { if (!rtarget[key]) { rtarget[key] = o[key]; } } return rtarget; }
javascript
function mergeIfNeed(rtarget, o) { for (var key in o) { if (!rtarget[key]) { rtarget[key] = o[key]; } } return rtarget; }
[ "function", "mergeIfNeed", "(", "rtarget", ",", "o", ")", "{", "for", "(", "var", "key", "in", "o", ")", "{", "if", "(", "!", "rtarget", "[", "key", "]", ")", "{", "rtarget", "[", "key", "]", "=", "o", "[", "key", "]", ";", "}", "}", "return"...
merge this function's cache
[ "merge", "this", "function", "s", "cache" ]
f62a7141fd97f4a5b47c9808a5c4a3349aeccb43
https://github.com/wordijp/flexi-require/blob/f62a7141fd97f4a5b47c9808a5c4a3349aeccb43/lib/internal/module-utils.js#L34-L41
49,756
me-ventures/microservice-toolkit
src/logger.js
setHandlers
function setHandlers(enableException, enableUnhandled) { if(enableException === true) { process.on('uncaughtException', UncaughtExceptionHandler); } if(enableUnhandled === true) { process.on('unhandledRejection', unhandledRejectionHandler); } }
javascript
function setHandlers(enableException, enableUnhandled) { if(enableException === true) { process.on('uncaughtException', UncaughtExceptionHandler); } if(enableUnhandled === true) { process.on('unhandledRejection', unhandledRejectionHandler); } }
[ "function", "setHandlers", "(", "enableException", ",", "enableUnhandled", ")", "{", "if", "(", "enableException", "===", "true", ")", "{", "process", ".", "on", "(", "'uncaughtException'", ",", "UncaughtExceptionHandler", ")", ";", "}", "if", "(", "enableUnhand...
Set handlers for the uncaughtException and unhandledRejection events in nodejs. @param enableException boolean @param enableUnhandled boolean
[ "Set", "handlers", "for", "the", "uncaughtException", "and", "unhandledRejection", "events", "in", "nodejs", "." ]
9aedc9542dffdc274a5142515bd22e92833220d2
https://github.com/me-ventures/microservice-toolkit/blob/9aedc9542dffdc274a5142515bd22e92833220d2/src/logger.js#L79-L87
49,757
me-ventures/microservice-toolkit
src/logger.js
UncaughtExceptionHandler
function UncaughtExceptionHandler(error) { // Call module.exports.crit here so that we can intercept the call in the tests module.exports.crit(`Unhandled exception: ${error.message}`); module.exports.crit(error.stack.toString()); process.exit(1); }
javascript
function UncaughtExceptionHandler(error) { // Call module.exports.crit here so that we can intercept the call in the tests module.exports.crit(`Unhandled exception: ${error.message}`); module.exports.crit(error.stack.toString()); process.exit(1); }
[ "function", "UncaughtExceptionHandler", "(", "error", ")", "{", "// Call module.exports.crit here so that we can intercept the call in the tests", "module", ".", "exports", ".", "crit", "(", "`", "${", "error", ".", "message", "}", "`", ")", ";", "module", ".", "expor...
Handler for the uncaught exception event inside nodejs. It will print out a critical error message and will then exit the application.
[ "Handler", "for", "the", "uncaught", "exception", "event", "inside", "nodejs", ".", "It", "will", "print", "out", "a", "critical", "error", "message", "and", "will", "then", "exit", "the", "application", "." ]
9aedc9542dffdc274a5142515bd22e92833220d2
https://github.com/me-ventures/microservice-toolkit/blob/9aedc9542dffdc274a5142515bd22e92833220d2/src/logger.js#L93-L98
49,758
me-ventures/microservice-toolkit
src/logger.js
unhandledRejectionHandler
function unhandledRejectionHandler(error) { let reasonString = error.message || error.msg || JSON.stringify(error); module.exports.crit(`Unhandled Promise Rejection - reason: [${reasonString}]`); module.exports.crit(error.stack.toString()); }
javascript
function unhandledRejectionHandler(error) { let reasonString = error.message || error.msg || JSON.stringify(error); module.exports.crit(`Unhandled Promise Rejection - reason: [${reasonString}]`); module.exports.crit(error.stack.toString()); }
[ "function", "unhandledRejectionHandler", "(", "error", ")", "{", "let", "reasonString", "=", "error", ".", "message", "||", "error", ".", "msg", "||", "JSON", ".", "stringify", "(", "error", ")", ";", "module", ".", "exports", ".", "crit", "(", "`", "${"...
Handler for the unhandledRejection event. Will print out a warning message using the log system.
[ "Handler", "for", "the", "unhandledRejection", "event", ".", "Will", "print", "out", "a", "warning", "message", "using", "the", "log", "system", "." ]
9aedc9542dffdc274a5142515bd22e92833220d2
https://github.com/me-ventures/microservice-toolkit/blob/9aedc9542dffdc274a5142515bd22e92833220d2/src/logger.js#L103-L108
49,759
redisjs/jsr-error
lib/index.js
StoreError
function StoreError(type, message) { this.name = StoreError.name; Error.call(this); type = type || ERR; message = type + ' ' + (message || 'unknown internal error'); if(arguments.length > 2) { var args = [message].concat([].slice.call(arguments, 2)); message = util.format.apply(util, args); } this.message = message; }
javascript
function StoreError(type, message) { this.name = StoreError.name; Error.call(this); type = type || ERR; message = type + ' ' + (message || 'unknown internal error'); if(arguments.length > 2) { var args = [message].concat([].slice.call(arguments, 2)); message = util.format.apply(util, args); } this.message = message; }
[ "function", "StoreError", "(", "type", ",", "message", ")", "{", "this", ".", "name", "=", "StoreError", ".", "name", ";", "Error", ".", "call", "(", "this", ")", ";", "type", "=", "type", "||", "ERR", ";", "message", "=", "type", "+", "' '", "+", ...
Abstract error super class.
[ "Abstract", "error", "super", "class", "." ]
f27ff57f90683895643d0ecc44feaf9bf8a18ae3
https://github.com/redisjs/jsr-error/blob/f27ff57f90683895643d0ecc44feaf9bf8a18ae3/lib/index.js#L15-L25
49,760
redisjs/jsr-error
lib/index.js
CommandArgLength
function CommandArgLength(cmd) { this.name = CommandArgLength.name; if(arguments.length > 1) { cmd = slice.call(arguments, 0).join(' '); } StoreError.apply( this, [null, 'wrong number of arguments for \'%s\' command', cmd]); }
javascript
function CommandArgLength(cmd) { this.name = CommandArgLength.name; if(arguments.length > 1) { cmd = slice.call(arguments, 0).join(' '); } StoreError.apply( this, [null, 'wrong number of arguments for \'%s\' command', cmd]); }
[ "function", "CommandArgLength", "(", "cmd", ")", "{", "this", ".", "name", "=", "CommandArgLength", ".", "name", ";", "if", "(", "arguments", ".", "length", ">", "1", ")", "{", "cmd", "=", "slice", ".", "call", "(", "arguments", ",", "0", ")", ".", ...
Encapsulates an argument length error.
[ "Encapsulates", "an", "argument", "length", "error", "." ]
f27ff57f90683895643d0ecc44feaf9bf8a18ae3
https://github.com/redisjs/jsr-error/blob/f27ff57f90683895643d0ecc44feaf9bf8a18ae3/lib/index.js#L45-L52
49,761
redisjs/jsr-error
lib/index.js
ConfigValue
function ConfigValue(key, value) { this.name = ConfigValue.name; StoreError.apply( this, [null, 'invalid argument \'%s\' for CONFIG SET \'%s\'', value, key]); }
javascript
function ConfigValue(key, value) { this.name = ConfigValue.name; StoreError.apply( this, [null, 'invalid argument \'%s\' for CONFIG SET \'%s\'', value, key]); }
[ "function", "ConfigValue", "(", "key", ",", "value", ")", "{", "this", ".", "name", "=", "ConfigValue", ".", "name", ";", "StoreError", ".", "apply", "(", "this", ",", "[", "null", ",", "'invalid argument \\'%s\\' for CONFIG SET \\'%s\\''", ",", "value", ",", ...
Encapsulates a config value error.
[ "Encapsulates", "a", "config", "value", "error", "." ]
f27ff57f90683895643d0ecc44feaf9bf8a18ae3
https://github.com/redisjs/jsr-error/blob/f27ff57f90683895643d0ecc44feaf9bf8a18ae3/lib/index.js#L70-L74
49,762
DScheglov/merest-swagger
lib/model-api-app.js
exposeSwagger
function exposeSwagger(path, options) { if (typeof path !== 'string') { options = path; path = null; } path = path || '/swagger.json'; options = options || {}; var needCors = options.cors; delete options.cors; var beautify = options.beautify; delete options.beautify; beautify = beautify === true ? ' ' : beautify; this.__swaggerDocURL = path; this.__swaggerDocJSON = JSON.stringify( this.swaggerDoc(options), null, beautify ); if (needCors !== false) { this.get(path, cors(), swaggerJSON.bind(this)); } else { this.get(path, swaggerJSON.bind(this)); } return this; }
javascript
function exposeSwagger(path, options) { if (typeof path !== 'string') { options = path; path = null; } path = path || '/swagger.json'; options = options || {}; var needCors = options.cors; delete options.cors; var beautify = options.beautify; delete options.beautify; beautify = beautify === true ? ' ' : beautify; this.__swaggerDocURL = path; this.__swaggerDocJSON = JSON.stringify( this.swaggerDoc(options), null, beautify ); if (needCors !== false) { this.get(path, cors(), swaggerJSON.bind(this)); } else { this.get(path, swaggerJSON.bind(this)); } return this; }
[ "function", "exposeSwagger", "(", "path", ",", "options", ")", "{", "if", "(", "typeof", "path", "!==", "'string'", ")", "{", "options", "=", "path", ";", "path", "=", "null", ";", "}", "path", "=", "path", "||", "'/swagger.json'", ";", "options", "=",...
exposeSwagger exposes the swagger document. If document is not created the method forces model description; @param {String} [path='/swagger.json'] path to mount swagger document @param {Object} [options] options for swagger document exposition @param {boolean} [options.cors=true] should the swagger doc be exposed with CORS @param {String} [options.beautify] the separator for JSON beautifier @return {ModelAPIExpress} the API object
[ "exposeSwagger", "exposes", "the", "swagger", "document", ".", "If", "document", "is", "not", "created", "the", "method", "forces", "model", "description", ";" ]
764ef9464dcfe5bf3f355293c2a9cb45eb42e49e
https://github.com/DScheglov/merest-swagger/blob/764ef9464dcfe5bf3f355293c2a9cb45eb42e49e/lib/model-api-app.js#L37-L57
49,763
DScheglov/merest-swagger
lib/model-api-app.js
exposeSwaggerUi
function exposeSwaggerUi(path, options) { if (typeof path !== 'string') { options = path; path = null; } options = options || {}; var swaggerDoc = options.swaggerDoc; delete options.swaggerDoc; if (!this.__swaggerDocURL) { this.exposeSwagger(swaggerDoc || '', options); }; var uiPath = _path.join(__dirname, '../swagger-ui'); this.__swaggerUiStaticMiddleware = serveStatic(uiPath, {}); this.__swaggerUiPath = path || '/swagger-ui'; this.use(this.__swaggerUiPath, swaggerUi.bind(this)); return this; }
javascript
function exposeSwaggerUi(path, options) { if (typeof path !== 'string') { options = path; path = null; } options = options || {}; var swaggerDoc = options.swaggerDoc; delete options.swaggerDoc; if (!this.__swaggerDocURL) { this.exposeSwagger(swaggerDoc || '', options); }; var uiPath = _path.join(__dirname, '../swagger-ui'); this.__swaggerUiStaticMiddleware = serveStatic(uiPath, {}); this.__swaggerUiPath = path || '/swagger-ui'; this.use(this.__swaggerUiPath, swaggerUi.bind(this)); return this; }
[ "function", "exposeSwaggerUi", "(", "path", ",", "options", ")", "{", "if", "(", "typeof", "path", "!==", "'string'", ")", "{", "options", "=", "path", ";", "path", "=", "null", ";", "}", "options", "=", "options", "||", "{", "}", ";", "var", "swagge...
exposeSwaggerUi exposes swagger ui application @param {String} [path='/swagger-ui'] the path to mount swagger ui app @param {Object} [options] options to expose swagger ui @param {String} [options.swaggerDoc='/swagger.json'] the path to mount swagger document @param {boolean} [options.cors=true] should the swagger doc be exposed with CORS @param {String} [options.beautify] the separator for JSON beautifier for swagger document @param {String} [options.title] the title of API @param {String} [options.path] the path of the API @param {String} [options.version] the API version @param {String} [options.host] the host name of the API @return {ModelAPIExpress} the API object
[ "exposeSwaggerUi", "exposes", "swagger", "ui", "application" ]
764ef9464dcfe5bf3f355293c2a9cb45eb42e49e
https://github.com/DScheglov/merest-swagger/blob/764ef9464dcfe5bf3f355293c2a9cb45eb42e49e/lib/model-api-app.js#L75-L94
49,764
samplx/samplx-agentdb
prepublish.js
getJSON
function getJSON(jsonUrl, done) { var parsedUrl = url.parse(jsonUrl); var options = { "host" : parsedUrl.hostname, "hostname": parsedUrl.hostname, "port" : parsedUrl.port || 80, "path" : parsedUrl.pathname, "method" : "GET", // "agent" : false, }; debug && console.error("prepublish:getJSON('" + jsonUrl + "', done)"); debug && console.error("options=" + util.inspect(options)); var req = http.get(options, function (res) { debug && console.error("STATUS: " + res.statusCode); debug && console.error("HEADERS: " + JSON.stringify(res.headers)); res.setEncoding('utf8'); var data = ''; res.on('data', function (chunk) { debug && console.error('getJSON: chunk="' + chunk + '"'); data += chunk; }); res.on('end', function() { debug && console.error('getJSON: end of request.'); done(JSON.parse(data)); }); }); req.on('error', function(error) { console.error("ERROR: " + error.message); }); }
javascript
function getJSON(jsonUrl, done) { var parsedUrl = url.parse(jsonUrl); var options = { "host" : parsedUrl.hostname, "hostname": parsedUrl.hostname, "port" : parsedUrl.port || 80, "path" : parsedUrl.pathname, "method" : "GET", // "agent" : false, }; debug && console.error("prepublish:getJSON('" + jsonUrl + "', done)"); debug && console.error("options=" + util.inspect(options)); var req = http.get(options, function (res) { debug && console.error("STATUS: " + res.statusCode); debug && console.error("HEADERS: " + JSON.stringify(res.headers)); res.setEncoding('utf8'); var data = ''; res.on('data', function (chunk) { debug && console.error('getJSON: chunk="' + chunk + '"'); data += chunk; }); res.on('end', function() { debug && console.error('getJSON: end of request.'); done(JSON.parse(data)); }); }); req.on('error', function(error) { console.error("ERROR: " + error.message); }); }
[ "function", "getJSON", "(", "jsonUrl", ",", "done", ")", "{", "var", "parsedUrl", "=", "url", ".", "parse", "(", "jsonUrl", ")", ";", "var", "options", "=", "{", "\"host\"", ":", "parsedUrl", ".", "hostname", ",", "\"hostname\"", ":", "parsedUrl", ".", ...
Download JSON object from a remote URL. @param path to request. @param done callback.
[ "Download", "JSON", "object", "from", "a", "remote", "URL", "." ]
4ded3176c8a9dceb3f2017f66581929d3cfc1084
https://github.com/samplx/samplx-agentdb/blob/4ded3176c8a9dceb3f2017f66581929d3cfc1084/prepublish.js#L49-L81
49,765
samplx/samplx-agentdb
prepublish.js
main
function main() { var database = fs.createWriteStream('./lib/database-min.js', { flags: 'w', encoding: 'utf8' }); var testFile; fs.mkdir('./data', 493, function (error) { // 493 == 0755 (no octal in strict mode.) // ignore errors. }); database.write("// Do not edit this file, your changes will be lost.\n"); database.write("module.exports = { \n"); getJSON('http://alscan.info/agent_groups/groups.json', function (groups) { var s = JSON.stringify(groups); database.write("groups:" + s + ",\n"); testFile = fs.createWriteStream('./data/groups.json', { flags: 'w', encoding: 'utf8' }); testFile.write(s+"\n"); testFile.end(); getJSON('http://alscan.info/agent_sources/sources.json', function (sources) { var s = JSON.stringify(sources); database.write("sources:" + s + ",\n"); testFile = fs.createWriteStream('./data/sources.json', { flags: 'w', encoding: 'utf8' }); testFile.write(s+"\n"); testFile.end(); getJSON('http://alscan.info/patterns/patterns.json', function (patterns) { database.write("patterns:[\n"); patterns.forEach(function (pattern) { database.write("{p: new RegExp('" + pattern.pattern + "'), x:" + agentdb.getX(pattern.groupId, pattern.sourceId) + "},"); }); database.write("],\n"); testFile = fs.createWriteStream('./data/patterns.json', { flags: 'w', encoding: 'utf8' }); testFile.write(JSON.stringify(patterns)+"\n"); testFile.end(); getJSON('http://alscan.info/agents/agents.json', function (agents) { var hash = new HashTable(HASH_TABLE_SIZE, HASH_TABLE_SEED, HASH_TABLE_MULTIPLIER); agents.forEach(function (agent) { if (agent.status < 2) { var obj = { a: agent.agent, x: agentdb.getX(agent.groupId, agent.sourceId) }; hash.add('a', obj); } }); database.write("table:" + JSON.stringify(hash.table) + ",\n"); database.write("HASH_TABLE_SIZE:" + HASH_TABLE_SIZE + ",\n"); database.write("HASH_TABLE_SEED:" + HASH_TABLE_SEED + ",\n"); database.write("HASH_TABLE_MULTIPLIER:" + HASH_TABLE_MULTIPLIER + ",\n"); database.write("hash: undefined\n}\n"); testFile = fs.createWriteStream('./data/agents.json', { flags: 'w', encoding: 'utf8' }); testFile.write(JSON.stringify(agents)+"\n"); testFile.end(); if (debug) { var history = hash.getHistory(); console.log("Hash table history"); for (var n=0; n < history.length; n++) { console.log(" Depth=" + n + ", count=" + history[n] + ", percent=" + (history[n] / HASH_TABLE_SIZE)); } } }); }); }); }); }
javascript
function main() { var database = fs.createWriteStream('./lib/database-min.js', { flags: 'w', encoding: 'utf8' }); var testFile; fs.mkdir('./data', 493, function (error) { // 493 == 0755 (no octal in strict mode.) // ignore errors. }); database.write("// Do not edit this file, your changes will be lost.\n"); database.write("module.exports = { \n"); getJSON('http://alscan.info/agent_groups/groups.json', function (groups) { var s = JSON.stringify(groups); database.write("groups:" + s + ",\n"); testFile = fs.createWriteStream('./data/groups.json', { flags: 'w', encoding: 'utf8' }); testFile.write(s+"\n"); testFile.end(); getJSON('http://alscan.info/agent_sources/sources.json', function (sources) { var s = JSON.stringify(sources); database.write("sources:" + s + ",\n"); testFile = fs.createWriteStream('./data/sources.json', { flags: 'w', encoding: 'utf8' }); testFile.write(s+"\n"); testFile.end(); getJSON('http://alscan.info/patterns/patterns.json', function (patterns) { database.write("patterns:[\n"); patterns.forEach(function (pattern) { database.write("{p: new RegExp('" + pattern.pattern + "'), x:" + agentdb.getX(pattern.groupId, pattern.sourceId) + "},"); }); database.write("],\n"); testFile = fs.createWriteStream('./data/patterns.json', { flags: 'w', encoding: 'utf8' }); testFile.write(JSON.stringify(patterns)+"\n"); testFile.end(); getJSON('http://alscan.info/agents/agents.json', function (agents) { var hash = new HashTable(HASH_TABLE_SIZE, HASH_TABLE_SEED, HASH_TABLE_MULTIPLIER); agents.forEach(function (agent) { if (agent.status < 2) { var obj = { a: agent.agent, x: agentdb.getX(agent.groupId, agent.sourceId) }; hash.add('a', obj); } }); database.write("table:" + JSON.stringify(hash.table) + ",\n"); database.write("HASH_TABLE_SIZE:" + HASH_TABLE_SIZE + ",\n"); database.write("HASH_TABLE_SEED:" + HASH_TABLE_SEED + ",\n"); database.write("HASH_TABLE_MULTIPLIER:" + HASH_TABLE_MULTIPLIER + ",\n"); database.write("hash: undefined\n}\n"); testFile = fs.createWriteStream('./data/agents.json', { flags: 'w', encoding: 'utf8' }); testFile.write(JSON.stringify(agents)+"\n"); testFile.end(); if (debug) { var history = hash.getHistory(); console.log("Hash table history"); for (var n=0; n < history.length; n++) { console.log(" Depth=" + n + ", count=" + history[n] + ", percent=" + (history[n] / HASH_TABLE_SIZE)); } } }); }); }); }); }
[ "function", "main", "(", ")", "{", "var", "database", "=", "fs", ".", "createWriteStream", "(", "'./lib/database-min.js'", ",", "{", "flags", ":", "'w'", ",", "encoding", ":", "'utf8'", "}", ")", ";", "var", "testFile", ";", "fs", ".", "mkdir", "(", "'...
Main entry point for prepublish script.
[ "Main", "entry", "point", "for", "prepublish", "script", "." ]
4ded3176c8a9dceb3f2017f66581929d3cfc1084
https://github.com/samplx/samplx-agentdb/blob/4ded3176c8a9dceb3f2017f66581929d3cfc1084/prepublish.js#L86-L146
49,766
gethuman/pancakes-recipe
utils/date.utils.js
datePlusFrequency
function datePlusFrequency(date, frequency) { var minutes; date = date || new Date(); // default is today frequency = frequency || 'hourly'; // default is hourly switch (frequency) { case 'none': minutes = 525949; // set far in future break; case 'instant': minutes = 1; break; case 'hourly': minutes = 60; break; case 'daily': minutes = 1440; break; case 'weekly': minutes = 10080; break; default: minutes = 0; } return new Date(date.getTime() + (minutes * 60000)); }
javascript
function datePlusFrequency(date, frequency) { var minutes; date = date || new Date(); // default is today frequency = frequency || 'hourly'; // default is hourly switch (frequency) { case 'none': minutes = 525949; // set far in future break; case 'instant': minutes = 1; break; case 'hourly': minutes = 60; break; case 'daily': minutes = 1440; break; case 'weekly': minutes = 10080; break; default: minutes = 0; } return new Date(date.getTime() + (minutes * 60000)); }
[ "function", "datePlusFrequency", "(", "date", ",", "frequency", ")", "{", "var", "minutes", ";", "date", "=", "date", "||", "new", "Date", "(", ")", ";", "// default is today", "frequency", "=", "frequency", "||", "'hourly'", ";", "// default is hourly", "swit...
Get a date in the future based off the frequency @param date The starting date @param frequency [none, instant, hourly, daily, weekly]
[ "Get", "a", "date", "in", "the", "future", "based", "off", "the", "frequency" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/utils/date.utils.js#L15-L42
49,767
gethuman/pancakes-recipe
utils/date.utils.js
serializeAllDates
function serializeAllDates(obj) { // if it is a date, then return serialized version if (_.isDate(obj)) { return serializeDate(obj); } // if array or object, loop over it if (_.isArray(obj) || _.isObject(obj)) { _.forEach(obj, function (item, key) { obj[key] = serializeAllDates(item); }); } return obj; }
javascript
function serializeAllDates(obj) { // if it is a date, then return serialized version if (_.isDate(obj)) { return serializeDate(obj); } // if array or object, loop over it if (_.isArray(obj) || _.isObject(obj)) { _.forEach(obj, function (item, key) { obj[key] = serializeAllDates(item); }); } return obj; }
[ "function", "serializeAllDates", "(", "obj", ")", "{", "// if it is a date, then return serialized version", "if", "(", "_", ".", "isDate", "(", "obj", ")", ")", "{", "return", "serializeDate", "(", "obj", ")", ";", "}", "// if array or object, loop over it", "if", ...
Recursively go through object and convert dates @param obj
[ "Recursively", "go", "through", "object", "and", "convert", "dates" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/utils/date.utils.js#L62-L77
49,768
clear/mongojs-hooks
mongojs-hooks.js
function (object) { var result = { }; for (var i in object) { if (!object.hasOwnProperty(i)) continue; if (isObject(object[i])) { var flatObject = this.flatten(object[i]); for (var x in flatObject) { if (!flatObject.hasOwnProperty(x)) continue; result[i + '.' + x] = flatObject[x]; } } else { result[i] = object[i]; } } return result; }
javascript
function (object) { var result = { }; for (var i in object) { if (!object.hasOwnProperty(i)) continue; if (isObject(object[i])) { var flatObject = this.flatten(object[i]); for (var x in flatObject) { if (!flatObject.hasOwnProperty(x)) continue; result[i + '.' + x] = flatObject[x]; } } else { result[i] = object[i]; } } return result; }
[ "function", "(", "object", ")", "{", "var", "result", "=", "{", "}", ";", "for", "(", "var", "i", "in", "object", ")", "{", "if", "(", "!", "object", ".", "hasOwnProperty", "(", "i", ")", ")", "continue", ";", "if", "(", "isObject", "(", "object"...
Flattens an object into dot-notation
[ "Flattens", "an", "object", "into", "dot", "-", "notation" ]
858b36cb49788f4c89478e2a4c400c652053171a
https://github.com/clear/mongojs-hooks/blob/858b36cb49788f4c89478e2a4c400c652053171a/mongojs-hooks.js#L123-L142
49,769
tea-noma/tea-macro
lib/tea-macro/tea-macro.js
readFileSync_
function readFileSync_(path){ if(file_values_[path]){ return file_values_[path]; } try { file_values_[path]=fs.readFileSync(path,'utf-8'); return file_values_[path]; }catch(e){ return null; } }
javascript
function readFileSync_(path){ if(file_values_[path]){ return file_values_[path]; } try { file_values_[path]=fs.readFileSync(path,'utf-8'); return file_values_[path]; }catch(e){ return null; } }
[ "function", "readFileSync_", "(", "path", ")", "{", "if", "(", "file_values_", "[", "path", "]", ")", "{", "return", "file_values_", "[", "path", "]", ";", "}", "try", "{", "file_values_", "[", "path", "]", "=", "fs", ".", "readFileSync", "(", "path", ...
read file with cache @param path file path @return file buffer
[ "read", "file", "with", "cache" ]
44fb3d48bc4044ae04ad13fc390ab468094be199
https://github.com/tea-noma/tea-macro/blob/44fb3d48bc4044ae04ad13fc390ab468094be199/lib/tea-macro/tea-macro.js#L61-L71
49,770
tea-noma/tea-macro
lib/tea-macro/tea-macro.js
function(doc){ var vs=doc.split("\r\n"); if(vs.length==1){ vs=doc.split("\n"); } if(vs[vs.length-1]==''){ vs.pop(); } return vs; }
javascript
function(doc){ var vs=doc.split("\r\n"); if(vs.length==1){ vs=doc.split("\n"); } if(vs[vs.length-1]==''){ vs.pop(); } return vs; }
[ "function", "(", "doc", ")", "{", "var", "vs", "=", "doc", ".", "split", "(", "\"\\r\\n\"", ")", ";", "if", "(", "vs", ".", "length", "==", "1", ")", "{", "vs", "=", "doc", ".", "split", "(", "\"\\n\"", ")", ";", "}", "if", "(", "vs", "[", ...
split string by line terminator @param doc target document @return splited document
[ "split", "string", "by", "line", "terminator" ]
44fb3d48bc4044ae04ad13fc390ab468094be199
https://github.com/tea-noma/tea-macro/blob/44fb3d48bc4044ae04ad13fc390ab468094be199/lib/tea-macro/tea-macro.js#L77-L86
49,771
tea-noma/tea-macro
lib/tea-macro/tea-macro.js
toExpr
function toExpr(value,line){ var token=[]; var ctoken=token; var newToken; var stacks=[]; var c; var ss=''; for(var i=0;i<value.length;i++){ c=value[i]; switch(c){ case ' ': case "\t": case ",": if(ss!=""){ ctoken.push(ss); ss=""; } break; case '(': if(ss!=""){ console.log("warning: no space before '(' in line "+line+" at "+(i+1)); ctoken.push(ss); ss=""; } stacks.push(ctoken); newToken=[]; ctoken.push(newToken); ctoken=newToken; break; case ')': if(ss!=""){ ctoken.push(ss); ss=""; } if(stacks.length>0){ ctoken=stacks.pop(); }else{ console.log("error: unmatched ')' in line "+line+" at "+(i+1)); return null; } break; default: ss+=c; break; } } if(ss!=''){ ctoken.push(ss); } // remove last '*/', '###' var ltoken=null; if(token&&(token.length>0)){ ltoken=token[token.length-1]; if((typeof ltoken=='string')&&((ltoken=='*/')||(ltoken=='###'))){ ltoken.pop(); } } return token; }
javascript
function toExpr(value,line){ var token=[]; var ctoken=token; var newToken; var stacks=[]; var c; var ss=''; for(var i=0;i<value.length;i++){ c=value[i]; switch(c){ case ' ': case "\t": case ",": if(ss!=""){ ctoken.push(ss); ss=""; } break; case '(': if(ss!=""){ console.log("warning: no space before '(' in line "+line+" at "+(i+1)); ctoken.push(ss); ss=""; } stacks.push(ctoken); newToken=[]; ctoken.push(newToken); ctoken=newToken; break; case ')': if(ss!=""){ ctoken.push(ss); ss=""; } if(stacks.length>0){ ctoken=stacks.pop(); }else{ console.log("error: unmatched ')' in line "+line+" at "+(i+1)); return null; } break; default: ss+=c; break; } } if(ss!=''){ ctoken.push(ss); } // remove last '*/', '###' var ltoken=null; if(token&&(token.length>0)){ ltoken=token[token.length-1]; if((typeof ltoken=='string')&&((ltoken=='*/')||(ltoken=='###'))){ ltoken.pop(); } } return token; }
[ "function", "toExpr", "(", "value", ",", "line", ")", "{", "var", "token", "=", "[", "]", ";", "var", "ctoken", "=", "token", ";", "var", "newToken", ";", "var", "stacks", "=", "[", "]", ";", "var", "c", ";", "var", "ss", "=", "''", ";", "for",...
convert expression string to expression object @param value (LISP style) expression string @param line line number @return expression object
[ "convert", "expression", "string", "to", "expression", "object" ]
44fb3d48bc4044ae04ad13fc390ab468094be199
https://github.com/tea-noma/tea-macro/blob/44fb3d48bc4044ae04ad13fc390ab468094be199/lib/tea-macro/tea-macro.js#L123-L183
49,772
tea-noma/tea-macro
lib/tea-macro/tea-macro.js
makeFromFile
function makeFromFile(makefile,target){ var read; var basedir='.'; if(makefile){ read = fs.createReadStream(makefile, {encoding: 'utf8'}); basedir=mpath.dirname(makefile); }else{ process.stdin.resume(); process.stdin.setEncoding('utf8'); read = process.stdin; } read.on('data', function (data){ try { var o=JSON.parse(data); make(basedir, o, target); }catch(e){ console.log(e); } }); }
javascript
function makeFromFile(makefile,target){ var read; var basedir='.'; if(makefile){ read = fs.createReadStream(makefile, {encoding: 'utf8'}); basedir=mpath.dirname(makefile); }else{ process.stdin.resume(); process.stdin.setEncoding('utf8'); read = process.stdin; } read.on('data', function (data){ try { var o=JSON.parse(data); make(basedir, o, target); }catch(e){ console.log(e); } }); }
[ "function", "makeFromFile", "(", "makefile", ",", "target", ")", "{", "var", "read", ";", "var", "basedir", "=", "'.'", ";", "if", "(", "makefile", ")", "{", "read", "=", "fs", ".", "createReadStream", "(", "makefile", ",", "{", "encoding", ":", "'utf8...
make from file @param makefile path of make file @param target make target. if null, all targets are compiled.
[ "make", "from", "file" ]
44fb3d48bc4044ae04ad13fc390ab468094be199
https://github.com/tea-noma/tea-macro/blob/44fb3d48bc4044ae04ad13fc390ab468094be199/lib/tea-macro/tea-macro.js#L706-L725
49,773
aureooms/js-grammar
lib/ll1/_parse_lazy.js
_parse_lazy
function _parse_lazy(eof, productions, table, rule, tape, nonterminal, production) { var shallow_materialize = /*#__PURE__*/ function () { var _ref = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee(expected) { return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _children_next_lazy2.default)(eof, productions, table, tape, expected); case 2: return _context.abrupt("return", _context.sent); case 3: case "end": return _context.stop(); } } }, _callee, this); })); return function shallow_materialize(_x) { return _ref.apply(this, arguments); }; }(); var iterator = (0, _ast.rmap)(shallow_materialize, rule)[Symbol.asyncIterator](); return { 'type': 'node', nonterminal: nonterminal, production: production, children: new _ast.Children(iterator, rule.length) }; }
javascript
function _parse_lazy(eof, productions, table, rule, tape, nonterminal, production) { var shallow_materialize = /*#__PURE__*/ function () { var _ref = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee(expected) { return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _children_next_lazy2.default)(eof, productions, table, tape, expected); case 2: return _context.abrupt("return", _context.sent); case 3: case "end": return _context.stop(); } } }, _callee, this); })); return function shallow_materialize(_x) { return _ref.apply(this, arguments); }; }(); var iterator = (0, _ast.rmap)(shallow_materialize, rule)[Symbol.asyncIterator](); return { 'type': 'node', nonterminal: nonterminal, production: production, children: new _ast.Children(iterator, rule.length) }; }
[ "function", "_parse_lazy", "(", "eof", ",", "productions", ",", "table", ",", "rule", ",", "tape", ",", "nonterminal", ",", "production", ")", "{", "var", "shallow_materialize", "=", "/*#__PURE__*/", "function", "(", ")", "{", "var", "_ref", "=", "_asyncToGe...
Table-driven predictive lazy parsing. @param {Object} eof - The end-of-file symbol. @param {Map} productions - The ll1 productions. @param {Map} table - The symbol table. @param {Array} rule - The production rule in use. @param {Tape} tape - The tape from which to read the symbols from. @param {String} nonterminal - The nonterminal that produced `rule`. @param {String} production - The production that corresponds to `rule`. @returns {Object} The root node of the parsed tree.
[ "Table", "-", "driven", "predictive", "lazy", "parsing", "." ]
28c4d1a3175327b33766c34539eab317303e26c5
https://github.com/aureooms/js-grammar/blob/28c4d1a3175327b33766c34539eab317303e26c5/lib/ll1/_parse_lazy.js#L30-L67
49,774
unclechu/node-njst
lib/parser.js
complexReturn
function complexReturn(result, data) { var complex = new String(result); for (var key in data) { complex[key] = data[key]; } return complex; }
javascript
function complexReturn(result, data) { var complex = new String(result); for (var key in data) { complex[key] = data[key]; } return complex; }
[ "function", "complexReturn", "(", "result", ",", "data", ")", "{", "var", "complex", "=", "new", "String", "(", "result", ")", ";", "for", "(", "var", "key", "in", "data", ")", "{", "complex", "[", "key", "]", "=", "data", "[", "key", "]", ";", "...
Merge and returns result parsed string as object with additional properties. @property {string} result.status is "success" or "error" @returns {string} String-object with additional properties
[ "Merge", "and", "returns", "result", "parsed", "string", "as", "object", "with", "additional", "properties", "." ]
b934b24a70b134eff49cf0db991e4d404695067e
https://github.com/unclechu/node-njst/blob/b934b24a70b134eff49cf0db991e4d404695067e/lib/parser.js#L147-L153
49,775
Wizcorp/panopticon
lib/Sample.js
Sample
function Sample(val, timeStamp, persistObj) { this.min = val; this.max = val; this.sigma = new StandardDeviation(val); this.average = new Average(val); this.timeStamp = timeStamp; if (persistObj) { var that = this; persistObj.on('reset', function (timeStamp) { that.reset(timeStamp); }); } }
javascript
function Sample(val, timeStamp, persistObj) { this.min = val; this.max = val; this.sigma = new StandardDeviation(val); this.average = new Average(val); this.timeStamp = timeStamp; if (persistObj) { var that = this; persistObj.on('reset', function (timeStamp) { that.reset(timeStamp); }); } }
[ "function", "Sample", "(", "val", ",", "timeStamp", ",", "persistObj", ")", "{", "this", ".", "min", "=", "val", ";", "this", ".", "max", "=", "val", ";", "this", ".", "sigma", "=", "new", "StandardDeviation", "(", "val", ")", ";", "this", ".", "av...
Sample taker object constructor. @param {Number} val This first value is used to initialise the sample. @param {Number} timeStamp A unix time stamp (in ms). @param {Object} persistObj If we are persisting then we don't initialise. @constructor @alias module:Sample
[ "Sample", "taker", "object", "constructor", "." ]
e0d660cd5287b45aafdb5a91e54affa7364b14e0
https://github.com/Wizcorp/panopticon/blob/e0d660cd5287b45aafdb5a91e54affa7364b14e0/lib/Sample.js#L15-L29
49,776
tolokoban/ToloFrameWork
lib/compiler-com.js
isHtmlFileUptodate
function isHtmlFileUptodate(source) { var dependencies = source.tag("dependencies") || []; var i, dep, file, prj = source.prj(), stat, mtime = source.modificationTime(); for (i = 0 ; i < dependencies.length ; i++) { dep = dependencies[i]; file = prj.srcOrLibPath(dep); if (file) { stat = FS.statSync(file); if (stat.mtime > mtime) return false; } } return source.isUptodate(); }
javascript
function isHtmlFileUptodate(source) { var dependencies = source.tag("dependencies") || []; var i, dep, file, prj = source.prj(), stat, mtime = source.modificationTime(); for (i = 0 ; i < dependencies.length ; i++) { dep = dependencies[i]; file = prj.srcOrLibPath(dep); if (file) { stat = FS.statSync(file); if (stat.mtime > mtime) return false; } } return source.isUptodate(); }
[ "function", "isHtmlFileUptodate", "(", "source", ")", "{", "var", "dependencies", "=", "source", ".", "tag", "(", "\"dependencies\"", ")", "||", "[", "]", ";", "var", "i", ",", "dep", ",", "file", ",", "prj", "=", "source", ".", "prj", "(", ")", ",",...
To be uptodate, an HTML page must be more recent that all its dependencies.
[ "To", "be", "uptodate", "an", "HTML", "page", "must", "be", "more", "recent", "that", "all", "its", "dependencies", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/lib/compiler-com.js#L138-L152
49,777
tjmehta/mongooseware
lib/middleware-class-factories/collection.js
function (item, req, eachReq, res, next) { eachReq.item = item; eachReq[indexKey] = index; index++; next(); }
javascript
function (item, req, eachReq, res, next) { eachReq.item = item; eachReq[indexKey] = index; index++; next(); }
[ "function", "(", "item", ",", "req", ",", "eachReq", ",", "res", ",", "next", ")", "{", "eachReq", ".", "item", "=", "item", ";", "eachReq", "[", "indexKey", "]", "=", "index", ";", "index", "++", ";", "next", "(", ")", ";", "}" ]
self.collectionKey is correct here
[ "self", ".", "collectionKey", "is", "correct", "here" ]
c62ce0bac82880826b3528231e08f5e5b3efdb83
https://github.com/tjmehta/mongooseware/blob/c62ce0bac82880826b3528231e08f5e5b3efdb83/lib/middleware-class-factories/collection.js#L45-L50
49,778
gethuman/pancakes-hapi
lib/pancakes.hapi.plugin.js
PancakesHapiPlugin
function PancakesHapiPlugin(opts) { this.pancakes = opts.pluginOptions.pancakes; this.jangular = opts.pluginOptions.jangular; }
javascript
function PancakesHapiPlugin(opts) { this.pancakes = opts.pluginOptions.pancakes; this.jangular = opts.pluginOptions.jangular; }
[ "function", "PancakesHapiPlugin", "(", "opts", ")", "{", "this", ".", "pancakes", "=", "opts", ".", "pluginOptions", ".", "pancakes", ";", "this", ".", "jangular", "=", "opts", ".", "pluginOptions", ".", "jangular", ";", "}" ]
Constructor sets up the plugin @param opts @constructor
[ "Constructor", "sets", "up", "the", "plugin" ]
1167cd7564cd8949c446c6fd8d95185f52b14492
https://github.com/gethuman/pancakes-hapi/blob/1167cd7564cd8949c446c6fd8d95185f52b14492/lib/pancakes.hapi.plugin.js#L16-L19
49,779
mdasberg/angular-test-setup
app/todo/todo.controller.js
_fetch
function _fetch() { vm.error = undefined; service.get({}, function (todos) { vm.todos = todos; }, function () { vm.todos = []; vm.error = 'An error occurred when fetching available todos'; }); }
javascript
function _fetch() { vm.error = undefined; service.get({}, function (todos) { vm.todos = todos; }, function () { vm.todos = []; vm.error = 'An error occurred when fetching available todos'; }); }
[ "function", "_fetch", "(", ")", "{", "vm", ".", "error", "=", "undefined", ";", "service", ".", "get", "(", "{", "}", ",", "function", "(", "todos", ")", "{", "vm", ".", "todos", "=", "todos", ";", "}", ",", "function", "(", ")", "{", "vm", "."...
Fetch the todo's @private
[ "Fetch", "the", "todo", "s" ]
4a1ef0742bac233b94e7c3682e8158c00aa87552
https://github.com/mdasberg/angular-test-setup/blob/4a1ef0742bac233b94e7c3682e8158c00aa87552/app/todo/todo.controller.js#L25-L33
49,780
mdasberg/angular-test-setup
app/todo/todo.controller.js
add
function add() { vm.error = undefined; service.add({ description: vm.description }, function() { _fetch(); }, function() { vm.error = 'An error occurred when adding a todo'; }); vm.description = ''; }
javascript
function add() { vm.error = undefined; service.add({ description: vm.description }, function() { _fetch(); }, function() { vm.error = 'An error occurred when adding a todo'; }); vm.description = ''; }
[ "function", "add", "(", ")", "{", "vm", ".", "error", "=", "undefined", ";", "service", ".", "add", "(", "{", "description", ":", "vm", ".", "description", "}", ",", "function", "(", ")", "{", "_fetch", "(", ")", ";", "}", ",", "function", "(", "...
Add the given todo. @param todo The todo
[ "Add", "the", "given", "todo", "." ]
4a1ef0742bac233b94e7c3682e8158c00aa87552
https://github.com/mdasberg/angular-test-setup/blob/4a1ef0742bac233b94e7c3682e8158c00aa87552/app/todo/todo.controller.js#L39-L49
49,781
mdasberg/angular-test-setup
app/todo/todo.controller.js
complete
function complete(todo) { vm.error = undefined; service.complete(todo, function() { _fetch(); }, function() { vm.error = 'An error occurred when completing a todo'; }); }
javascript
function complete(todo) { vm.error = undefined; service.complete(todo, function() { _fetch(); }, function() { vm.error = 'An error occurred when completing a todo'; }); }
[ "function", "complete", "(", "todo", ")", "{", "vm", ".", "error", "=", "undefined", ";", "service", ".", "complete", "(", "todo", ",", "function", "(", ")", "{", "_fetch", "(", ")", ";", "}", ",", "function", "(", ")", "{", "vm", ".", "error", "...
Complete the given todo. @param todo The todo
[ "Complete", "the", "given", "todo", "." ]
4a1ef0742bac233b94e7c3682e8158c00aa87552
https://github.com/mdasberg/angular-test-setup/blob/4a1ef0742bac233b94e7c3682e8158c00aa87552/app/todo/todo.controller.js#L55-L62
49,782
mdasberg/angular-test-setup
app/todo/todo.controller.js
archive
function archive() { vm.error = undefined; var promises = []; vm.todos.filter(function (todo) { return todo.completed; }).forEach(function (todo) { promises.push(_archive(todo)); }); $q.all(promises).then(function () { _fetch(); }).catch(function () { vm.error = 'An error occurred when archiving completed todos'; }); }
javascript
function archive() { vm.error = undefined; var promises = []; vm.todos.filter(function (todo) { return todo.completed; }).forEach(function (todo) { promises.push(_archive(todo)); }); $q.all(promises).then(function () { _fetch(); }).catch(function () { vm.error = 'An error occurred when archiving completed todos'; }); }
[ "function", "archive", "(", ")", "{", "vm", ".", "error", "=", "undefined", ";", "var", "promises", "=", "[", "]", ";", "vm", ".", "todos", ".", "filter", "(", "function", "(", "todo", ")", "{", "return", "todo", ".", "completed", ";", "}", ")", ...
Archive the completed todo's.
[ "Archive", "the", "completed", "todo", "s", "." ]
4a1ef0742bac233b94e7c3682e8158c00aa87552
https://github.com/mdasberg/angular-test-setup/blob/4a1ef0742bac233b94e7c3682e8158c00aa87552/app/todo/todo.controller.js#L65-L79
49,783
mdasberg/angular-test-setup
app/todo/todo.controller.js
_archive
function _archive(todo) { var deferred = $q.defer(); service.archive(todo, function () { return deferred.resolve(); }, function () { return deferred.reject(); }); return deferred.promise; }
javascript
function _archive(todo) { var deferred = $q.defer(); service.archive(todo, function () { return deferred.resolve(); }, function () { return deferred.reject(); }); return deferred.promise; }
[ "function", "_archive", "(", "todo", ")", "{", "var", "deferred", "=", "$q", ".", "defer", "(", ")", ";", "service", ".", "archive", "(", "todo", ",", "function", "(", ")", "{", "return", "deferred", ".", "resolve", "(", ")", ";", "}", ",", "functi...
Archive the given todo. @param todo The todo. @private
[ "Archive", "the", "given", "todo", "." ]
4a1ef0742bac233b94e7c3682e8158c00aa87552
https://github.com/mdasberg/angular-test-setup/blob/4a1ef0742bac233b94e7c3682e8158c00aa87552/app/todo/todo.controller.js#L96-L104
49,784
tgi-io/tgi-interface-bootstrap
dist/tgi-interface-bootstrap.js
function (args) { if (false === (this instanceof Session)) throw new Error('new operator required'); args = args || {}; if (!args.attributes) { args.attributes = []; } var userModelID = new Attribute.ModelID(new User()); args.attributes.push(new Attribute({name: 'userID', type: 'Model', value: userModelID})); args.attributes.push(new Attribute({name: 'dateStarted', type: 'Date', value: new Date()})); args.attributes.push(new Attribute({name: 'passCode', type: 'String(20)'})); args.attributes.push(new Attribute({name: 'active', type: 'Boolean'})); args.attributes.push(new Attribute({name: 'ipAddress', type: 'String'})); Model.call(this, args); this.modelType = "Session"; this.set('active', false); }
javascript
function (args) { if (false === (this instanceof Session)) throw new Error('new operator required'); args = args || {}; if (!args.attributes) { args.attributes = []; } var userModelID = new Attribute.ModelID(new User()); args.attributes.push(new Attribute({name: 'userID', type: 'Model', value: userModelID})); args.attributes.push(new Attribute({name: 'dateStarted', type: 'Date', value: new Date()})); args.attributes.push(new Attribute({name: 'passCode', type: 'String(20)'})); args.attributes.push(new Attribute({name: 'active', type: 'Boolean'})); args.attributes.push(new Attribute({name: 'ipAddress', type: 'String'})); Model.call(this, args); this.modelType = "Session"; this.set('active', false); }
[ "function", "(", "args", ")", "{", "if", "(", "false", "===", "(", "this", "instanceof", "Session", ")", ")", "throw", "new", "Error", "(", "'new operator required'", ")", ";", "args", "=", "args", "||", "{", "}", ";", "if", "(", "!", "args", ".", ...
tequila session-model Model Constructor
[ "tequila", "session", "-", "model", "Model", "Constructor" ]
5681a8806cb855d3e2035b95e22502ae581bfd18
https://github.com/tgi-io/tgi-interface-bootstrap/blob/5681a8806cb855d3e2035b95e22502ae581bfd18/dist/tgi-interface-bootstrap.js#L2525-L2541
49,785
tgi-io/tgi-interface-bootstrap
dist/tgi-interface-bootstrap.js
function (args) { if (false === (this instanceof User)) throw new Error('new operator required'); args = args || {}; if (!args.attributes) { args.attributes = []; } args.attributes.push(new Attribute({name: 'name', type: 'String(20)'})); args.attributes.push(new Attribute({name: 'active', type: 'Boolean'})); args.attributes.push(new Attribute({name: 'password', type: 'String(20)'})); args.attributes.push(new Attribute({name: 'firstName', type: 'String(35)'})); args.attributes.push(new Attribute({name: 'lastName', type: 'String(35)'})); args.attributes.push(new Attribute({name: 'email', type: 'String(20)'})); Model.call(this, args); this.modelType = "User"; this.set('active', false); }
javascript
function (args) { if (false === (this instanceof User)) throw new Error('new operator required'); args = args || {}; if (!args.attributes) { args.attributes = []; } args.attributes.push(new Attribute({name: 'name', type: 'String(20)'})); args.attributes.push(new Attribute({name: 'active', type: 'Boolean'})); args.attributes.push(new Attribute({name: 'password', type: 'String(20)'})); args.attributes.push(new Attribute({name: 'firstName', type: 'String(35)'})); args.attributes.push(new Attribute({name: 'lastName', type: 'String(35)'})); args.attributes.push(new Attribute({name: 'email', type: 'String(20)'})); Model.call(this, args); this.modelType = "User"; this.set('active', false); }
[ "function", "(", "args", ")", "{", "if", "(", "false", "===", "(", "this", "instanceof", "User", ")", ")", "throw", "new", "Error", "(", "'new operator required'", ")", ";", "args", "=", "args", "||", "{", "}", ";", "if", "(", "!", "args", ".", "at...
tequila user-core-model Model Constructor
[ "tequila", "user", "-", "core", "-", "model", "Model", "Constructor" ]
5681a8806cb855d3e2035b95e22502ae581bfd18
https://github.com/tgi-io/tgi-interface-bootstrap/blob/5681a8806cb855d3e2035b95e22502ae581bfd18/dist/tgi-interface-bootstrap.js#L2636-L2651
49,786
tgi-io/tgi-interface-bootstrap
dist/tgi-interface-bootstrap.js
Workspace
function Workspace(args) { if (false === (this instanceof Workspace)) throw new Error('new operator required'); args = args || {}; if (!args.attributes) { args.attributes = []; } var userModelID = new Attribute.ModelID(new User()); args.attributes.push(new Attribute({name: 'user', type: 'Model', value: userModelID})); args.attributes.push(new Attribute({name: 'deltas', type: 'Object', value: {}})); // var delta // this.deltas = []; Model.call(this, args); this.modelType = "Workspace"; }
javascript
function Workspace(args) { if (false === (this instanceof Workspace)) throw new Error('new operator required'); args = args || {}; if (!args.attributes) { args.attributes = []; } var userModelID = new Attribute.ModelID(new User()); args.attributes.push(new Attribute({name: 'user', type: 'Model', value: userModelID})); args.attributes.push(new Attribute({name: 'deltas', type: 'Object', value: {}})); // var delta // this.deltas = []; Model.call(this, args); this.modelType = "Workspace"; }
[ "function", "Workspace", "(", "args", ")", "{", "if", "(", "false", "===", "(", "this", "instanceof", "Workspace", ")", ")", "throw", "new", "Error", "(", "'new operator required'", ")", ";", "args", "=", "args", "||", "{", "}", ";", "if", "(", "!", ...
tequila workspace-class
[ "tequila", "workspace", "-", "class" ]
5681a8806cb855d3e2035b95e22502ae581bfd18
https://github.com/tgi-io/tgi-interface-bootstrap/blob/5681a8806cb855d3e2035b95e22502ae581bfd18/dist/tgi-interface-bootstrap.js#L2658-L2673
49,787
tgi-io/tgi-interface-bootstrap
dist/tgi-interface-bootstrap.js
function (args) { if (false === (this instanceof MemoryStore)) throw new Error('new operator required'); args = args || {}; this.storeType = args.storeType || "MemoryStore"; this.name = args.name || 'a ' + this.storeType; this.storeProperty = { isReady: true, canGetModel: true, canPutModel: true, canDeleteModel: true, canGetList: true }; this.data = [];// Each ele is an array of model types and contents (which is an array of IDs and Model Value Store) this.idCounter = 0; var unusedProperties = getInvalidProperties(args, ['name', 'storeType']); var errorList = []; for (var i = 0; i < unusedProperties.length; i++) errorList.push('invalid property: ' + unusedProperties[i]); if (errorList.length > 1) throw new Error('error creating Store: multiple errors'); if (errorList.length) throw new Error('error creating Store: ' + errorList[0]); }
javascript
function (args) { if (false === (this instanceof MemoryStore)) throw new Error('new operator required'); args = args || {}; this.storeType = args.storeType || "MemoryStore"; this.name = args.name || 'a ' + this.storeType; this.storeProperty = { isReady: true, canGetModel: true, canPutModel: true, canDeleteModel: true, canGetList: true }; this.data = [];// Each ele is an array of model types and contents (which is an array of IDs and Model Value Store) this.idCounter = 0; var unusedProperties = getInvalidProperties(args, ['name', 'storeType']); var errorList = []; for (var i = 0; i < unusedProperties.length; i++) errorList.push('invalid property: ' + unusedProperties[i]); if (errorList.length > 1) throw new Error('error creating Store: multiple errors'); if (errorList.length) throw new Error('error creating Store: ' + errorList[0]); }
[ "function", "(", "args", ")", "{", "if", "(", "false", "===", "(", "this", "instanceof", "MemoryStore", ")", ")", "throw", "new", "Error", "(", "'new operator required'", ")", ";", "args", "=", "args", "||", "{", "}", ";", "this", ".", "storeType", "="...
tequila memory-store Constructor
[ "tequila", "memory", "-", "store", "Constructor" ]
5681a8806cb855d3e2035b95e22502ae581bfd18
https://github.com/tgi-io/tgi-interface-bootstrap/blob/5681a8806cb855d3e2035b95e22502ae581bfd18/dist/tgi-interface-bootstrap.js#L2686-L2705
49,788
tgi-io/tgi-interface-bootstrap
dist/tgi-interface-bootstrap.js
renderText
function renderText(text) { var textDiv = addEle(panel.panelForm, 'div', indent ? 'col-sm-offset-3' : ''); textDiv.innerHTML = marked(text.get()); text.onEvent('StateChange', function () { textDiv.innerHTML = marked(text.get()); }); panel.textListeners.push(text); // so we can avoid leakage on deleting panel }
javascript
function renderText(text) { var textDiv = addEle(panel.panelForm, 'div', indent ? 'col-sm-offset-3' : ''); textDiv.innerHTML = marked(text.get()); text.onEvent('StateChange', function () { textDiv.innerHTML = marked(text.get()); }); panel.textListeners.push(text); // so we can avoid leakage on deleting panel }
[ "function", "renderText", "(", "text", ")", "{", "var", "textDiv", "=", "addEle", "(", "panel", ".", "panelForm", ",", "'div'", ",", "indent", "?", "'col-sm-offset-3'", ":", "''", ")", ";", "textDiv", ".", "innerHTML", "=", "marked", "(", "text", ".", ...
function to render Attribute
[ "function", "to", "render", "Attribute" ]
5681a8806cb855d3e2035b95e22502ae581bfd18
https://github.com/tgi-io/tgi-interface-bootstrap/blob/5681a8806cb855d3e2035b95e22502ae581bfd18/dist/tgi-interface-bootstrap.js#L3473-L3480
49,789
tgi-io/tgi-interface-bootstrap
dist/tgi-interface-bootstrap.js
function (event) { switch (attribute.type) { case 'Date': attribute.value = (input.value === '') ? null : attribute.coerce(input.value); if (attribute.value != null) { var mm = attribute.value.getMonth() + 1; var dd = attribute.value.getDate(); var yyyy = attribute.value.getFullYear(); if (mm < 10) mm = '0' + mm; if (dd < 10) dd = '0' + dd; input.value = mm + '/' + dd + '/' + yyyy; } else { input.value = ''; } break; default: attribute.value = (input.value === '') ? null : attribute.coerce(input.value); if (attribute.value != null) input.value = attribute.value; break; } attribute.validate(function () { }); }
javascript
function (event) { switch (attribute.type) { case 'Date': attribute.value = (input.value === '') ? null : attribute.coerce(input.value); if (attribute.value != null) { var mm = attribute.value.getMonth() + 1; var dd = attribute.value.getDate(); var yyyy = attribute.value.getFullYear(); if (mm < 10) mm = '0' + mm; if (dd < 10) dd = '0' + dd; input.value = mm + '/' + dd + '/' + yyyy; } else { input.value = ''; } break; default: attribute.value = (input.value === '') ? null : attribute.coerce(input.value); if (attribute.value != null) input.value = attribute.value; break; } attribute.validate(function () { }); }
[ "function", "(", "event", ")", "{", "switch", "(", "attribute", ".", "type", ")", "{", "case", "'Date'", ":", "attribute", ".", "value", "=", "(", "input", ".", "value", "===", "''", ")", "?", "null", ":", "attribute", ".", "coerce", "(", "input", ...
When focus lost on attribute - validate it
[ "When", "focus", "lost", "on", "attribute", "-", "validate", "it" ]
5681a8806cb855d3e2035b95e22502ae581bfd18
https://github.com/tgi-io/tgi-interface-bootstrap/blob/5681a8806cb855d3e2035b95e22502ae581bfd18/dist/tgi-interface-bootstrap.js#L3657-L3680
49,790
tgi-io/tgi-interface-bootstrap
dist/tgi-interface-bootstrap.js
renderHelpText
function renderHelpText(text) { if (text) { if (!helpTextDiv) { helpTextDiv = document.createElement("div"); helpTextDiv.className = 'col-sm-9 col-sm-offset-3 has-error'; formGroup.appendChild(helpTextDiv); } helpTextDiv.innerHTML = '<span style="display: block;" class="help-block">' + text + '</span>'; $(formGroup).addClass('has-error'); if (inputGroupButton) $(inputGroupButton).addClass('btn-danger'); } else { setTimeout(function () { if (helpTextDiv) { $(helpTextDiv).remove(); helpTextDiv = null; } }, 250); $(formGroup).removeClass('has-error'); if (inputGroupButton) $(inputGroupButton).removeClass('btn-danger'); } }
javascript
function renderHelpText(text) { if (text) { if (!helpTextDiv) { helpTextDiv = document.createElement("div"); helpTextDiv.className = 'col-sm-9 col-sm-offset-3 has-error'; formGroup.appendChild(helpTextDiv); } helpTextDiv.innerHTML = '<span style="display: block;" class="help-block">' + text + '</span>'; $(formGroup).addClass('has-error'); if (inputGroupButton) $(inputGroupButton).addClass('btn-danger'); } else { setTimeout(function () { if (helpTextDiv) { $(helpTextDiv).remove(); helpTextDiv = null; } }, 250); $(formGroup).removeClass('has-error'); if (inputGroupButton) $(inputGroupButton).removeClass('btn-danger'); } }
[ "function", "renderHelpText", "(", "text", ")", "{", "if", "(", "text", ")", "{", "if", "(", "!", "helpTextDiv", ")", "{", "helpTextDiv", "=", "document", ".", "createElement", "(", "\"div\"", ")", ";", "helpTextDiv", ".", "className", "=", "'col-sm-9 col-...
so we can avoid leakage on deleting panel For attribute error display
[ "so", "we", "can", "avoid", "leakage", "on", "deleting", "panel", "For", "attribute", "error", "display" ]
5681a8806cb855d3e2035b95e22502ae581bfd18
https://github.com/tgi-io/tgi-interface-bootstrap/blob/5681a8806cb855d3e2035b95e22502ae581bfd18/dist/tgi-interface-bootstrap.js#L3723-L3745
49,791
tgi-io/tgi-interface-bootstrap
dist/tgi-interface-bootstrap.js
renderList
function renderList(list, theme) { var txtDiv = document.createElement("table"); txtDiv.className = 'table table-condensed table-bordered table-hover-' + theme; //bootstrapInterface.info(txtDiv.className); /** * Header */ var tHead = addEle(txtDiv, 'thead'); var tHeadRow = addEle(tHead, 'tr'); for (j = 1; j < list.model.attributes.length; j++) { // skip id (0)) var hAttribute = list.model.attributes[j]; if (hAttribute.hidden == undefined) addEle(tHeadRow, 'th').innerHTML = hAttribute.label; } /** * Now each row in list */ var gotData = list.moveFirst(); var tBody = addEle(txtDiv, 'tbody'); while (gotData) { var tBodyRow = addEle(tBody, 'tr'); var idAttribute = list.model.attributes[0]; $(tBodyRow).data("id", list.get(idAttribute.name)); $(tBodyRow).click(function (e) { // bootstrapInterface.dispatch(new Request({type: 'Command', command: action})); // bootstrapInterface.info('you picked #' + $(e.currentTarget).data("id")); if (list.pickKludge) list.pickKludge($(e.currentTarget).data("id")); // too shitty balls e.preventDefault(); }); for (j = 1; j < list.model.attributes.length; j++) { // skip id (0)) var dAttribute = list.model.attributes[j]; if (dAttribute.hidden == undefined) { var dValue = list.get(dAttribute.name); switch (dAttribute.type) { case 'Date': //console.log('dValue=' + dValue); // addEle(tBodyRow, 'td').innerHTML = left(dValue.toISOString(), 10); // addEle(tBodyRow, 'td').innerHTML = dValue.toString(); // todo use moment.js if (dValue) addEle(tBodyRow, 'td').innerHTML = left(dValue.toISOString(), 10); else addEle(tBodyRow, 'td').innerHTML = '&nbsp;'; break; case 'Boolean': if (dValue) addEle(tBodyRow, 'td').innerHTML = '<i class="fa fa-check-square-o"></i>'; else addEle(tBodyRow, 'td').innerHTML = '<i class="fa fa-square-o"></i>'; break; default: if (dValue && dValue.name) // todo instanceof Attribute.ModelID did not work so kludge here addEle(tBodyRow, 'td').innerHTML = dValue.name; else addEle(tBodyRow, 'td').innerHTML = dValue; } } } gotData = list.moveNext(); } panel.panelForm.appendChild(txtDiv); }
javascript
function renderList(list, theme) { var txtDiv = document.createElement("table"); txtDiv.className = 'table table-condensed table-bordered table-hover-' + theme; //bootstrapInterface.info(txtDiv.className); /** * Header */ var tHead = addEle(txtDiv, 'thead'); var tHeadRow = addEle(tHead, 'tr'); for (j = 1; j < list.model.attributes.length; j++) { // skip id (0)) var hAttribute = list.model.attributes[j]; if (hAttribute.hidden == undefined) addEle(tHeadRow, 'th').innerHTML = hAttribute.label; } /** * Now each row in list */ var gotData = list.moveFirst(); var tBody = addEle(txtDiv, 'tbody'); while (gotData) { var tBodyRow = addEle(tBody, 'tr'); var idAttribute = list.model.attributes[0]; $(tBodyRow).data("id", list.get(idAttribute.name)); $(tBodyRow).click(function (e) { // bootstrapInterface.dispatch(new Request({type: 'Command', command: action})); // bootstrapInterface.info('you picked #' + $(e.currentTarget).data("id")); if (list.pickKludge) list.pickKludge($(e.currentTarget).data("id")); // too shitty balls e.preventDefault(); }); for (j = 1; j < list.model.attributes.length; j++) { // skip id (0)) var dAttribute = list.model.attributes[j]; if (dAttribute.hidden == undefined) { var dValue = list.get(dAttribute.name); switch (dAttribute.type) { case 'Date': //console.log('dValue=' + dValue); // addEle(tBodyRow, 'td').innerHTML = left(dValue.toISOString(), 10); // addEle(tBodyRow, 'td').innerHTML = dValue.toString(); // todo use moment.js if (dValue) addEle(tBodyRow, 'td').innerHTML = left(dValue.toISOString(), 10); else addEle(tBodyRow, 'td').innerHTML = '&nbsp;'; break; case 'Boolean': if (dValue) addEle(tBodyRow, 'td').innerHTML = '<i class="fa fa-check-square-o"></i>'; else addEle(tBodyRow, 'td').innerHTML = '<i class="fa fa-square-o"></i>'; break; default: if (dValue && dValue.name) // todo instanceof Attribute.ModelID did not work so kludge here addEle(tBodyRow, 'td').innerHTML = dValue.name; else addEle(tBodyRow, 'td').innerHTML = dValue; } } } gotData = list.moveNext(); } panel.panelForm.appendChild(txtDiv); }
[ "function", "renderList", "(", "list", ",", "theme", ")", "{", "var", "txtDiv", "=", "document", ".", "createElement", "(", "\"table\"", ")", ";", "txtDiv", ".", "className", "=", "'table table-condensed table-bordered table-hover-'", "+", "theme", ";", "//bootstr...
function to render List
[ "function", "to", "render", "List" ]
5681a8806cb855d3e2035b95e22502ae581bfd18
https://github.com/tgi-io/tgi-interface-bootstrap/blob/5681a8806cb855d3e2035b95e22502ae581bfd18/dist/tgi-interface-bootstrap.js#L3751-L3818
49,792
tgi-io/tgi-interface-bootstrap
dist/tgi-interface-bootstrap.js
renderCommand
function renderCommand(command) { if (!panel.buttonDiv) { var formGroup = addEle(panel.panelForm, 'div', 'form-group'); panel.buttonDiv = addEle(formGroup, 'div', indent ? 'col-sm-offset-3 col-sm-9' : 'col-sm-9'); } var cmdTheme = command.theme || 'default'; var button = addEle(panel.buttonDiv, 'button', 'btn btn-' + cmdTheme + ' btn-presentation', {type: 'button'}); var icon = command.icon; if (icon) { if (left(icon, 2) == 'fa') icon = '<i class="fa ' + icon + '"></i>&nbsp;'; else icon = '<span class="glyphicon ' + icon + '"></span>&nbsp;'; button.innerHTML = icon + command.name; } else { button.innerHTML = command.name; } $(button).on('click', function (event) { event.preventDefault(); bootstrapInterface.dispatch(new Request({type: 'Command', command: command})); }); panel.listeners.push(button); // so we can avoid leakage on deleting panel }
javascript
function renderCommand(command) { if (!panel.buttonDiv) { var formGroup = addEle(panel.panelForm, 'div', 'form-group'); panel.buttonDiv = addEle(formGroup, 'div', indent ? 'col-sm-offset-3 col-sm-9' : 'col-sm-9'); } var cmdTheme = command.theme || 'default'; var button = addEle(panel.buttonDiv, 'button', 'btn btn-' + cmdTheme + ' btn-presentation', {type: 'button'}); var icon = command.icon; if (icon) { if (left(icon, 2) == 'fa') icon = '<i class="fa ' + icon + '"></i>&nbsp;'; else icon = '<span class="glyphicon ' + icon + '"></span>&nbsp;'; button.innerHTML = icon + command.name; } else { button.innerHTML = command.name; } $(button).on('click', function (event) { event.preventDefault(); bootstrapInterface.dispatch(new Request({type: 'Command', command: command})); }); panel.listeners.push(button); // so we can avoid leakage on deleting panel }
[ "function", "renderCommand", "(", "command", ")", "{", "if", "(", "!", "panel", ".", "buttonDiv", ")", "{", "var", "formGroup", "=", "addEle", "(", "panel", ".", "panelForm", ",", "'div'", ",", "'form-group'", ")", ";", "panel", ".", "buttonDiv", "=", ...
function to render Command
[ "function", "to", "render", "Command" ]
5681a8806cb855d3e2035b95e22502ae581bfd18
https://github.com/tgi-io/tgi-interface-bootstrap/blob/5681a8806cb855d3e2035b95e22502ae581bfd18/dist/tgi-interface-bootstrap.js#L3823-L3848
49,793
byron-dupreez/aws-stream-consumer-core
tracking.js
setUnusableRecord
function setUnusableRecord(state, unusableRecord) { Object.defineProperty(state, 'unusableRecord', {value: unusableRecord, writable: true, configurable: true, enumerable: false}); }
javascript
function setUnusableRecord(state, unusableRecord) { Object.defineProperty(state, 'unusableRecord', {value: unusableRecord, writable: true, configurable: true, enumerable: false}); }
[ "function", "setUnusableRecord", "(", "state", ",", "unusableRecord", ")", "{", "Object", ".", "defineProperty", "(", "state", ",", "'unusableRecord'", ",", "{", "value", ":", "unusableRecord", ",", "writable", ":", "true", ",", "configurable", ":", "true", ",...
Sets the given unusable record on its given state that is being tracked for the unusable record. @param {UnusableRecordState} state - the tracked state to be updated @param {UnusableRecord} unusableRecord - the unusable record to which this state belongs
[ "Sets", "the", "given", "unusable", "record", "on", "its", "given", "state", "that", "is", "being", "tracked", "for", "the", "unusable", "record", "." ]
9b256084297f80d373bcf483aaf68a9da176b3d7
https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/tracking.js#L76-L79
49,794
byron-dupreez/aws-stream-consumer-core
tracking.js
setUserRecord
function setUserRecord(state, userRecord) { Object.defineProperty(state, 'userRecord', {value: userRecord, writable: true, configurable: true, enumerable: false}); }
javascript
function setUserRecord(state, userRecord) { Object.defineProperty(state, 'userRecord', {value: userRecord, writable: true, configurable: true, enumerable: false}); }
[ "function", "setUserRecord", "(", "state", ",", "userRecord", ")", "{", "Object", ".", "defineProperty", "(", "state", ",", "'userRecord'", ",", "{", "value", ":", "userRecord", ",", "writable", ":", "true", ",", "configurable", ":", "true", ",", "enumerable...
Sets the given user record on the given state that is being tracked for a message. @param {MessageState} state - the tracked state to be updated @param {UserRecord} userRecord - the user record to link to the state
[ "Sets", "the", "given", "user", "record", "on", "the", "given", "state", "that", "is", "being", "tracked", "for", "a", "message", "." ]
9b256084297f80d373bcf483aaf68a9da176b3d7
https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/tracking.js#L86-L89
49,795
byron-dupreez/aws-stream-consumer-core
tracking.js
setRecord
function setRecord(state, record) { Object.defineProperty(state, 'record', {value: record, writable: true, configurable: true, enumerable: false}); }
javascript
function setRecord(state, record) { Object.defineProperty(state, 'record', {value: record, writable: true, configurable: true, enumerable: false}); }
[ "function", "setRecord", "(", "state", ",", "record", ")", "{", "Object", ".", "defineProperty", "(", "state", ",", "'record'", ",", "{", "value", ":", "record", ",", "writable", ":", "true", ",", "configurable", ":", "true", ",", "enumerable", ":", "fal...
Sets the given record on the given state that is being tracked for a message or unusable record. @param {MessageState|UnusableRecordState} state - the tracked state to be updated @param {Record} record - the record to link to the state
[ "Sets", "the", "given", "record", "on", "the", "given", "state", "that", "is", "being", "tracked", "for", "a", "message", "or", "unusable", "record", "." ]
9b256084297f80d373bcf483aaf68a9da176b3d7
https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/tracking.js#L96-L98
49,796
byron-dupreez/aws-stream-consumer-core
tracking.js
deleteLegacyState
function deleteLegacyState(trackedItem, context) { const taskTrackingName = Settings.getLegacyTaskTrackingName(context); return taskTrackingName && trackedItem ? delete trackedItem[taskTrackingName] : true; }
javascript
function deleteLegacyState(trackedItem, context) { const taskTrackingName = Settings.getLegacyTaskTrackingName(context); return taskTrackingName && trackedItem ? delete trackedItem[taskTrackingName] : true; }
[ "function", "deleteLegacyState", "(", "trackedItem", ",", "context", ")", "{", "const", "taskTrackingName", "=", "Settings", ".", "getLegacyTaskTrackingName", "(", "context", ")", ";", "return", "taskTrackingName", "&&", "trackedItem", "?", "delete", "trackedItem", ...
Deletes any legacy task tracking state attached directly to the tracked item from previous runs of older versions of aws-stream-consumer. @param {TrackedItem} trackedItem - the tracked item from which to remove its legacy tracked state @param {StreamConsumerContext} context - the context to use to resolve the name of the legacy task tracking state property @return {boolean} whether the task tracking state property was deleted or not
[ "Deletes", "any", "legacy", "task", "tracking", "state", "attached", "directly", "to", "the", "tracked", "item", "from", "previous", "runs", "of", "older", "versions", "of", "aws", "-", "stream", "-", "consumer", "." ]
9b256084297f80d373bcf483aaf68a9da176b3d7
https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/tracking.js#L154-L157
49,797
jonschlinkert/lint-templates
index.js
data
function data(app, file, key) { var o = has(app.options, key); var c = has(app.cache.data, key); var d = has(file.data, key); if (!c && !d && !o) { set(file.data, key, comment(key, 'property')); console.log(warning(' missing variable:')); } }
javascript
function data(app, file, key) { var o = has(app.options, key); var c = has(app.cache.data, key); var d = has(file.data, key); if (!c && !d && !o) { set(file.data, key, comment(key, 'property')); console.log(warning(' missing variable:')); } }
[ "function", "data", "(", "app", ",", "file", ",", "key", ")", "{", "var", "o", "=", "has", "(", "app", ".", "options", ",", "key", ")", ";", "var", "c", "=", "has", "(", "app", ".", "cache", ".", "data", ",", "key", ")", ";", "var", "d", "=...
Find missing data. @param {Object} `app` @param {Object} `file` @param {String} `key` @return {Object}
[ "Find", "missing", "data", "." ]
a84aaaae1d7218c1a7671071c3264ef53bbb0732
https://github.com/jonschlinkert/lint-templates/blob/a84aaaae1d7218c1a7671071c3264ef53bbb0732/index.js#L48-L56
49,798
jonschlinkert/lint-templates
index.js
helper
function helper(app, file, key, re) { var h = get(app._.asyncHelpers, key); var a = get(app._.helpers, key); if (!h && !a) { set(file.data, key, function () { return comment(key, 'helper'); }); if (re.test(file.content)) { var message = 'MISSING helper: "' + key + '".\n'; // rethrow (or actually throw) the error var err = new SyntaxError(message); if (app.disabled('silent')) { rethrow(err, file.path, file.content, re); } } } }
javascript
function helper(app, file, key, re) { var h = get(app._.asyncHelpers, key); var a = get(app._.helpers, key); if (!h && !a) { set(file.data, key, function () { return comment(key, 'helper'); }); if (re.test(file.content)) { var message = 'MISSING helper: "' + key + '".\n'; // rethrow (or actually throw) the error var err = new SyntaxError(message); if (app.disabled('silent')) { rethrow(err, file.path, file.content, re); } } } }
[ "function", "helper", "(", "app", ",", "file", ",", "key", ",", "re", ")", "{", "var", "h", "=", "get", "(", "app", ".", "_", ".", "asyncHelpers", ",", "key", ")", ";", "var", "a", "=", "get", "(", "app", ".", "_", ".", "helpers", ",", "key",...
Find missing helpers. @param {Object} `app` @param {Object} `file` @param {String} `key` @return {Object}
[ "Find", "missing", "helpers", "." ]
a84aaaae1d7218c1a7671071c3264ef53bbb0732
https://github.com/jonschlinkert/lint-templates/blob/a84aaaae1d7218c1a7671071c3264ef53bbb0732/index.js#L67-L85
49,799
jonschlinkert/lint-templates
index.js
rethrow
function rethrow(err, fp, str, re) { var lines = str.split('\n'); var len = lines.length, i = 0; var res = ''; while (len--) { var line = lines[i++]; if (re.test(line)) { error(err, fp, i, str); break; } } }
javascript
function rethrow(err, fp, str, re) { var lines = str.split('\n'); var len = lines.length, i = 0; var res = ''; while (len--) { var line = lines[i++]; if (re.test(line)) { error(err, fp, i, str); break; } } }
[ "function", "rethrow", "(", "err", ",", "fp", ",", "str", ",", "re", ")", "{", "var", "lines", "=", "str", ".", "split", "(", "'\\n'", ")", ";", "var", "len", "=", "lines", ".", "length", ",", "i", "=", "0", ";", "var", "res", "=", "''", ";",...
Re-throw an error to get the line number and postion to help with debuging. @param {Error} `err` Pass an `Error` object @param {Object} `fp` Pass `file.path` @param {Object} `str` The content string @param {Object} `re` RegExp to use for matching the template delimiters @return {Object}
[ "Re", "-", "throw", "an", "error", "to", "get", "the", "line", "number", "and", "postion", "to", "help", "with", "debuging", "." ]
a84aaaae1d7218c1a7671071c3264ef53bbb0732
https://github.com/jonschlinkert/lint-templates/blob/a84aaaae1d7218c1a7671071c3264ef53bbb0732/index.js#L115-L127