id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
53,200
origin1tech/stiks
dist/utils.js
copy
function copy(src, dest) { if (!src || !dest) return false; try { fs_extra_1.copySync(src, dest); logger_1.log.notify("copied " + src + " to " + dest + "."); return true; } catch (ex) { logger_1.log.warn("failed to copy " + src + " to " + dest + "."); return false; } }
javascript
function copy(src, dest) { if (!src || !dest) return false; try { fs_extra_1.copySync(src, dest); logger_1.log.notify("copied " + src + " to " + dest + "."); return true; } catch (ex) { logger_1.log.warn("failed to copy " + src + " to " + dest + "."); return false; } }
[ "function", "copy", "(", "src", ",", "dest", ")", "{", "if", "(", "!", "src", "||", "!", "dest", ")", "return", "false", ";", "try", "{", "fs_extra_1", ".", "copySync", "(", "src", ",", "dest", ")", ";", "logger_1", ".", "log", ".", "notify", "(", "\"copied \"", "+", "src", "+", "\" to \"", "+", "dest", "+", "\".\"", ")", ";", "return", "true", ";", "}", "catch", "(", "ex", ")", "{", "logger_1", ".", "log", ".", "warn", "(", "\"failed to copy \"", "+", "src", "+", "\" to \"", "+", "dest", "+", "\".\"", ")", ";", "return", "false", ";", "}", "}" ]
Copy Copies source to target. Does NOT support globs. @param src the source path to be copied. @param dest the destination path to copy to.
[ "Copy", "Copies", "source", "to", "target", ".", "Does", "NOT", "support", "globs", "." ]
dca9cd352bb914e53e64e791fc85985aef3d9fb7
https://github.com/origin1tech/stiks/blob/dca9cd352bb914e53e64e791fc85985aef3d9fb7/dist/utils.js#L62-L74
53,201
origin1tech/stiks
dist/utils.js
copyAll
function copyAll(copies) { var success = 0; var failed = 0; var result; function update(_result) { if (!_result) failed++; else success++; } function logResults() { // only log if something copied or failed. if (success || failed) { if (failed > success) { if (!success) logger_1.log.error(failed + " failed to copy with 0 succeeding."); else logger_1.log.warn(failed + " failed to copy " + success + " succeeded."); } else { logger_1.log.notify(success + " items copied " + failed + " failed."); } } } if (chek_1.isPlainObject(copies)) { chek_1.keys(copies).forEach(function (k) { var itm = copies[k]; // Check if src is glob. if (itm.src.indexOf('*') !== -1) { var arr = glob.sync(itm.src); arr.forEach(function (str) { result = copy(str, itm.dest); update(result); }); } else { result = copy(itm.src, itm.dest); update(result); } }); logResults(); } else if (chek_1.isArray(copies)) { // If not array of tuples convert. if (chek_1.isString(copies[0])) copies = copies.reduce(function (a, c) { var tuple = c.split('|'); return a.concat([tuple]); }, []); copies.forEach(function (c) { var tuple = c; if (tuple[0].indexOf('*') !== -1) { var arr = glob.sync(tuple[0]); arr.forEach(function (str) { result = copy(str, tuple[1]); update(result); }); } else { result = copy(tuple[0], tuple[1]); update(result); } }); logResults(); } else { logger_1.log.warn("copy failed using unknown configuration type."); } return { success: success, failed: failed }; }
javascript
function copyAll(copies) { var success = 0; var failed = 0; var result; function update(_result) { if (!_result) failed++; else success++; } function logResults() { // only log if something copied or failed. if (success || failed) { if (failed > success) { if (!success) logger_1.log.error(failed + " failed to copy with 0 succeeding."); else logger_1.log.warn(failed + " failed to copy " + success + " succeeded."); } else { logger_1.log.notify(success + " items copied " + failed + " failed."); } } } if (chek_1.isPlainObject(copies)) { chek_1.keys(copies).forEach(function (k) { var itm = copies[k]; // Check if src is glob. if (itm.src.indexOf('*') !== -1) { var arr = glob.sync(itm.src); arr.forEach(function (str) { result = copy(str, itm.dest); update(result); }); } else { result = copy(itm.src, itm.dest); update(result); } }); logResults(); } else if (chek_1.isArray(copies)) { // If not array of tuples convert. if (chek_1.isString(copies[0])) copies = copies.reduce(function (a, c) { var tuple = c.split('|'); return a.concat([tuple]); }, []); copies.forEach(function (c) { var tuple = c; if (tuple[0].indexOf('*') !== -1) { var arr = glob.sync(tuple[0]); arr.forEach(function (str) { result = copy(str, tuple[1]); update(result); }); } else { result = copy(tuple[0], tuple[1]); update(result); } }); logResults(); } else { logger_1.log.warn("copy failed using unknown configuration type."); } return { success: success, failed: failed }; }
[ "function", "copyAll", "(", "copies", ")", "{", "var", "success", "=", "0", ";", "var", "failed", "=", "0", ";", "var", "result", ";", "function", "update", "(", "_result", ")", "{", "if", "(", "!", "_result", ")", "failed", "++", ";", "else", "success", "++", ";", "}", "function", "logResults", "(", ")", "{", "// only log if something copied or failed.", "if", "(", "success", "||", "failed", ")", "{", "if", "(", "failed", ">", "success", ")", "{", "if", "(", "!", "success", ")", "logger_1", ".", "log", ".", "error", "(", "failed", "+", "\" failed to copy with 0 succeeding.\"", ")", ";", "else", "logger_1", ".", "log", ".", "warn", "(", "failed", "+", "\" failed to copy \"", "+", "success", "+", "\" succeeded.\"", ")", ";", "}", "else", "{", "logger_1", ".", "log", ".", "notify", "(", "success", "+", "\" items copied \"", "+", "failed", "+", "\" failed.\"", ")", ";", "}", "}", "}", "if", "(", "chek_1", ".", "isPlainObject", "(", "copies", ")", ")", "{", "chek_1", ".", "keys", "(", "copies", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "var", "itm", "=", "copies", "[", "k", "]", ";", "// Check if src is glob.", "if", "(", "itm", ".", "src", ".", "indexOf", "(", "'*'", ")", "!==", "-", "1", ")", "{", "var", "arr", "=", "glob", ".", "sync", "(", "itm", ".", "src", ")", ";", "arr", ".", "forEach", "(", "function", "(", "str", ")", "{", "result", "=", "copy", "(", "str", ",", "itm", ".", "dest", ")", ";", "update", "(", "result", ")", ";", "}", ")", ";", "}", "else", "{", "result", "=", "copy", "(", "itm", ".", "src", ",", "itm", ".", "dest", ")", ";", "update", "(", "result", ")", ";", "}", "}", ")", ";", "logResults", "(", ")", ";", "}", "else", "if", "(", "chek_1", ".", "isArray", "(", "copies", ")", ")", "{", "// If not array of tuples convert.", "if", "(", "chek_1", ".", "isString", "(", "copies", "[", "0", "]", ")", ")", "copies", "=", "copies", ".", "reduce", "(", "function", "(", "a", ",", "c", ")", "{", "var", "tuple", "=", "c", ".", "split", "(", "'|'", ")", ";", "return", "a", ".", "concat", "(", "[", "tuple", "]", ")", ";", "}", ",", "[", "]", ")", ";", "copies", ".", "forEach", "(", "function", "(", "c", ")", "{", "var", "tuple", "=", "c", ";", "if", "(", "tuple", "[", "0", "]", ".", "indexOf", "(", "'*'", ")", "!==", "-", "1", ")", "{", "var", "arr", "=", "glob", ".", "sync", "(", "tuple", "[", "0", "]", ")", ";", "arr", ".", "forEach", "(", "function", "(", "str", ")", "{", "result", "=", "copy", "(", "str", ",", "tuple", "[", "1", "]", ")", ";", "update", "(", "result", ")", ";", "}", ")", ";", "}", "else", "{", "result", "=", "copy", "(", "tuple", "[", "0", "]", ",", "tuple", "[", "1", "]", ")", ";", "update", "(", "result", ")", ";", "}", "}", ")", ";", "logResults", "(", ")", ";", "}", "else", "{", "logger_1", ".", "log", ".", "warn", "(", "\"copy failed using unknown configuration type.\"", ")", ";", "}", "return", "{", "success", ":", "success", ",", "failed", ":", "failed", "}", ";", "}" ]
Copy All Takes collection and copies to destination. @param copies collection of source and destination targets.
[ "Copy", "All", "Takes", "collection", "and", "copies", "to", "destination", "." ]
dca9cd352bb914e53e64e791fc85985aef3d9fb7
https://github.com/origin1tech/stiks/blob/dca9cd352bb914e53e64e791fc85985aef3d9fb7/dist/utils.js#L82-L154
53,202
origin1tech/stiks
dist/utils.js
pkg
function pkg(val) { var filename = path_1.resolve(exports.cwd, 'package.json'); if (!val) return _pkg || (_pkg = fs_extra_1.readJSONSync(filename)); fs_extra_1.writeJSONSync(filename, val, { spaces: 2 }); }
javascript
function pkg(val) { var filename = path_1.resolve(exports.cwd, 'package.json'); if (!val) return _pkg || (_pkg = fs_extra_1.readJSONSync(filename)); fs_extra_1.writeJSONSync(filename, val, { spaces: 2 }); }
[ "function", "pkg", "(", "val", ")", "{", "var", "filename", "=", "path_1", ".", "resolve", "(", "exports", ".", "cwd", ",", "'package.json'", ")", ";", "if", "(", "!", "val", ")", "return", "_pkg", "||", "(", "_pkg", "=", "fs_extra_1", ".", "readJSONSync", "(", "filename", ")", ")", ";", "fs_extra_1", ".", "writeJSONSync", "(", "filename", ",", "val", ",", "{", "spaces", ":", "2", "}", ")", ";", "}" ]
Pkg Loads the package.json file for project or saves package.json. @param val the package.json object to be written to file.
[ "Pkg", "Loads", "the", "package", ".", "json", "file", "for", "project", "or", "saves", "package", ".", "json", "." ]
dca9cd352bb914e53e64e791fc85985aef3d9fb7
https://github.com/origin1tech/stiks/blob/dca9cd352bb914e53e64e791fc85985aef3d9fb7/dist/utils.js#L162-L167
53,203
origin1tech/stiks
dist/utils.js
platform
function platform() { var cpus = os.cpus(); var cpu = cpus[0]; cpu.cores = cpus.length; var tmpPlatform = os.platform(); if (/^win/.test(tmpPlatform)) tmpPlatform = 'windows'; else if (tmpPlatform === 'darwin' || tmpPlatform === 'freebsd') tmpPlatform = 'mac'; else if (tmpPlatform === 'linux') tmpPlatform = 'linux'; return { platform: tmpPlatform, arch: os.arch(), release: os.release(), hostname: os.hostname(), homedir: os.homedir(), cpu: cpu }; }
javascript
function platform() { var cpus = os.cpus(); var cpu = cpus[0]; cpu.cores = cpus.length; var tmpPlatform = os.platform(); if (/^win/.test(tmpPlatform)) tmpPlatform = 'windows'; else if (tmpPlatform === 'darwin' || tmpPlatform === 'freebsd') tmpPlatform = 'mac'; else if (tmpPlatform === 'linux') tmpPlatform = 'linux'; return { platform: tmpPlatform, arch: os.arch(), release: os.release(), hostname: os.hostname(), homedir: os.homedir(), cpu: cpu }; }
[ "function", "platform", "(", ")", "{", "var", "cpus", "=", "os", ".", "cpus", "(", ")", ";", "var", "cpu", "=", "cpus", "[", "0", "]", ";", "cpu", ".", "cores", "=", "cpus", ".", "length", ";", "var", "tmpPlatform", "=", "os", ".", "platform", "(", ")", ";", "if", "(", "/", "^win", "/", ".", "test", "(", "tmpPlatform", ")", ")", "tmpPlatform", "=", "'windows'", ";", "else", "if", "(", "tmpPlatform", "===", "'darwin'", "||", "tmpPlatform", "===", "'freebsd'", ")", "tmpPlatform", "=", "'mac'", ";", "else", "if", "(", "tmpPlatform", "===", "'linux'", ")", "tmpPlatform", "=", "'linux'", ";", "return", "{", "platform", ":", "tmpPlatform", ",", "arch", ":", "os", ".", "arch", "(", ")", ",", "release", ":", "os", ".", "release", "(", ")", ",", "hostname", ":", "os", ".", "hostname", "(", ")", ",", "homedir", ":", "os", ".", "homedir", "(", ")", ",", "cpu", ":", "cpu", "}", ";", "}" ]
Platform Gets information and paths for the current platform.
[ "Platform", "Gets", "information", "and", "paths", "for", "the", "current", "platform", "." ]
dca9cd352bb914e53e64e791fc85985aef3d9fb7
https://github.com/origin1tech/stiks/blob/dca9cd352bb914e53e64e791fc85985aef3d9fb7/dist/utils.js#L235-L254
53,204
origin1tech/stiks
dist/utils.js
colorize
function colorize(val) { var styles = []; for (var _i = 1; _i < arguments.length; _i++) { styles[_i - 1] = arguments[_i]; } styles = chek_1.flatten(styles); if (chek_1.isObject(val)) return util_1.inspect(val, null, null, true); if (/\./.test(styles[0])) styles = styles[0].split('.'); return colurs.applyAnsi(val, styles); }
javascript
function colorize(val) { var styles = []; for (var _i = 1; _i < arguments.length; _i++) { styles[_i - 1] = arguments[_i]; } styles = chek_1.flatten(styles); if (chek_1.isObject(val)) return util_1.inspect(val, null, null, true); if (/\./.test(styles[0])) styles = styles[0].split('.'); return colurs.applyAnsi(val, styles); }
[ "function", "colorize", "(", "val", ")", "{", "var", "styles", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "1", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "styles", "[", "_i", "-", "1", "]", "=", "arguments", "[", "_i", "]", ";", "}", "styles", "=", "chek_1", ".", "flatten", "(", "styles", ")", ";", "if", "(", "chek_1", ".", "isObject", "(", "val", ")", ")", "return", "util_1", ".", "inspect", "(", "val", ",", "null", ",", "null", ",", "true", ")", ";", "if", "(", "/", "\\.", "/", ".", "test", "(", "styles", "[", "0", "]", ")", ")", "styles", "=", "styles", "[", "0", "]", ".", "split", "(", "'.'", ")", ";", "return", "colurs", ".", "applyAnsi", "(", "val", ",", "styles", ")", ";", "}" ]
Colorizes a value. @param val the value to colorize. @param styles the styles to be applied.
[ "Colorizes", "a", "value", "." ]
dca9cd352bb914e53e64e791fc85985aef3d9fb7
https://github.com/origin1tech/stiks/blob/dca9cd352bb914e53e64e791fc85985aef3d9fb7/dist/utils.js#L262-L273
53,205
origin1tech/pargv
dist/utils.js
findPackage
function findPackage(filename) { if (!ctr) return; filename = filename || require.main.filename; var parsed = path_1.parse(filename); var curPath = path_1.join(parsed.dir, 'package.json'); if (!fs_1.existsSync(curPath)) { ctr--; return findPackage(parsed.dir); } else { return chek_1.tryRequire(curPath, {}); } }
javascript
function findPackage(filename) { if (!ctr) return; filename = filename || require.main.filename; var parsed = path_1.parse(filename); var curPath = path_1.join(parsed.dir, 'package.json'); if (!fs_1.existsSync(curPath)) { ctr--; return findPackage(parsed.dir); } else { return chek_1.tryRequire(curPath, {}); } }
[ "function", "findPackage", "(", "filename", ")", "{", "if", "(", "!", "ctr", ")", "return", ";", "filename", "=", "filename", "||", "require", ".", "main", ".", "filename", ";", "var", "parsed", "=", "path_1", ".", "parse", "(", "filename", ")", ";", "var", "curPath", "=", "path_1", ".", "join", "(", "parsed", ".", "dir", ",", "'package.json'", ")", ";", "if", "(", "!", "fs_1", ".", "existsSync", "(", "curPath", ")", ")", "{", "ctr", "--", ";", "return", "findPackage", "(", "parsed", ".", "dir", ")", ";", "}", "else", "{", "return", "chek_1", ".", "tryRequire", "(", "curPath", ",", "{", "}", ")", ";", "}", "}" ]
limit recursion.
[ "limit", "recursion", "." ]
3dfe91190b843e9b0d84f9a65bcd45a86617cc05
https://github.com/origin1tech/pargv/blob/3dfe91190b843e9b0d84f9a65bcd45a86617cc05/dist/utils.js#L13-L26
53,206
redisjs/jsr-conf
lib/validator.js
save
function save(val) { if(Array.isArray(val)) { val.forEach(function(item) { var seconds = item[0] , changes = item[1]; if(seconds < 1 || changes < 0) { throw new Error('Invalid save parameters'); } }) } }
javascript
function save(val) { if(Array.isArray(val)) { val.forEach(function(item) { var seconds = item[0] , changes = item[1]; if(seconds < 1 || changes < 0) { throw new Error('Invalid save parameters'); } }) } }
[ "function", "save", "(", "val", ")", "{", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "{", "val", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "seconds", "=", "item", "[", "0", "]", ",", "changes", "=", "item", "[", "1", "]", ";", "if", "(", "seconds", "<", "1", "||", "changes", "<", "0", ")", "{", "throw", "new", "Error", "(", "'Invalid save parameters'", ")", ";", "}", "}", ")", "}", "}" ]
Validate a save value.
[ "Validate", "a", "save", "value", "." ]
97c5e2e77e1601c879a62dfc2d500df537eaaddd
https://github.com/redisjs/jsr-conf/blob/97c5e2e77e1601c879a62dfc2d500df537eaaddd/lib/validator.js#L71-L81
53,207
redisjs/jsr-conf
lib/validator.js
dir
function dir(val) { try { process.chdir(val); }catch(e) { throw new Error( util.format('Can\'t chdir to \'%s\': %s'), val, e.message); } }
javascript
function dir(val) { try { process.chdir(val); }catch(e) { throw new Error( util.format('Can\'t chdir to \'%s\': %s'), val, e.message); } }
[ "function", "dir", "(", "val", ")", "{", "try", "{", "process", ".", "chdir", "(", "val", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'Can\\'t chdir to \\'%s\\': %s'", ")", ",", "val", ",", "e", ".", "message", ")", ";", "}", "}" ]
Validate a dir value.
[ "Validate", "a", "dir", "value", "." ]
97c5e2e77e1601c879a62dfc2d500df537eaaddd
https://github.com/redisjs/jsr-conf/blob/97c5e2e77e1601c879a62dfc2d500df537eaaddd/lib/validator.js#L86-L93
53,208
redisjs/jsr-conf
lib/validator.js
logfile
function logfile(val) { var fd; // empty string disables use of log file if(val) { try { fd = fs.openSync(val, 'a'); fs.closeSync(fd); }catch(e) { throw new Error(util.format('Can\'t open the log file: %s', val)); } } }
javascript
function logfile(val) { var fd; // empty string disables use of log file if(val) { try { fd = fs.openSync(val, 'a'); fs.closeSync(fd); }catch(e) { throw new Error(util.format('Can\'t open the log file: %s', val)); } } }
[ "function", "logfile", "(", "val", ")", "{", "var", "fd", ";", "// empty string disables use of log file", "if", "(", "val", ")", "{", "try", "{", "fd", "=", "fs", ".", "openSync", "(", "val", ",", "'a'", ")", ";", "fs", ".", "closeSync", "(", "fd", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'Can\\'t open the log file: %s'", ",", "val", ")", ")", ";", "}", "}", "}" ]
Validate a logfile value.
[ "Validate", "a", "logfile", "value", "." ]
97c5e2e77e1601c879a62dfc2d500df537eaaddd
https://github.com/redisjs/jsr-conf/blob/97c5e2e77e1601c879a62dfc2d500df537eaaddd/lib/validator.js#L98-L109
53,209
redisjs/jsr-conf
lib/validator.js
include
function include(val) { var i, inc; // disallow the empty string if(Array.isArray(val)) { for(i = 0;i < val.length;i++) { inc = val[i]; if(!inc) throw new Error('Invalid include value'); } } }
javascript
function include(val) { var i, inc; // disallow the empty string if(Array.isArray(val)) { for(i = 0;i < val.length;i++) { inc = val[i]; if(!inc) throw new Error('Invalid include value'); } } }
[ "function", "include", "(", "val", ")", "{", "var", "i", ",", "inc", ";", "// disallow the empty string", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "val", ".", "length", ";", "i", "++", ")", "{", "inc", "=", "val", "[", "i", "]", ";", "if", "(", "!", "inc", ")", "throw", "new", "Error", "(", "'Invalid include value'", ")", ";", "}", "}", "}" ]
Validate an include value.
[ "Validate", "an", "include", "value", "." ]
97c5e2e77e1601c879a62dfc2d500df537eaaddd
https://github.com/redisjs/jsr-conf/blob/97c5e2e77e1601c879a62dfc2d500df537eaaddd/lib/validator.js#L133-L142
53,210
redisjs/jsr-conf
lib/validator.js
requirepass
function requirepass(val) { if(val && val.length > AUTHPASS_MAX_LEN) { throw new Error( util.format('Password is longer than %s', AUTHPASS_MAX_LEN)); } }
javascript
function requirepass(val) { if(val && val.length > AUTHPASS_MAX_LEN) { throw new Error( util.format('Password is longer than %s', AUTHPASS_MAX_LEN)); } }
[ "function", "requirepass", "(", "val", ")", "{", "if", "(", "val", "&&", "val", ".", "length", ">", "AUTHPASS_MAX_LEN", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'Password is longer than %s'", ",", "AUTHPASS_MAX_LEN", ")", ")", ";", "}", "}" ]
Validate a requirepass value.
[ "Validate", "a", "requirepass", "value", "." ]
97c5e2e77e1601c879a62dfc2d500df537eaaddd
https://github.com/redisjs/jsr-conf/blob/97c5e2e77e1601c879a62dfc2d500df537eaaddd/lib/validator.js#L204-L209
53,211
redisjs/jsr-conf
lib/validator.js
clientOutputBufferLimit
function clientOutputBufferLimit(val) { if(Array.isArray(val)) { val.forEach(function(limit) { var type = limit[0] , seconds = limit[3]; if(!~Constants.CLIENT_CLASS.indexOf(type)) { throw new Error('Unrecognized client limit class'); } if(seconds < 0) { throw new Error( 'Negative number of seconds in soft limit is invalid'); } }) } }
javascript
function clientOutputBufferLimit(val) { if(Array.isArray(val)) { val.forEach(function(limit) { var type = limit[0] , seconds = limit[3]; if(!~Constants.CLIENT_CLASS.indexOf(type)) { throw new Error('Unrecognized client limit class'); } if(seconds < 0) { throw new Error( 'Negative number of seconds in soft limit is invalid'); } }) } }
[ "function", "clientOutputBufferLimit", "(", "val", ")", "{", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "{", "val", ".", "forEach", "(", "function", "(", "limit", ")", "{", "var", "type", "=", "limit", "[", "0", "]", ",", "seconds", "=", "limit", "[", "3", "]", ";", "if", "(", "!", "~", "Constants", ".", "CLIENT_CLASS", ".", "indexOf", "(", "type", ")", ")", "{", "throw", "new", "Error", "(", "'Unrecognized client limit class'", ")", ";", "}", "if", "(", "seconds", "<", "0", ")", "{", "throw", "new", "Error", "(", "'Negative number of seconds in soft limit is invalid'", ")", ";", "}", "}", ")", "}", "}" ]
Validate a client-output-buffer-limit value.
[ "Validate", "a", "client", "-", "output", "-", "buffer", "-", "limit", "value", "." ]
97c5e2e77e1601c879a62dfc2d500df537eaaddd
https://github.com/redisjs/jsr-conf/blob/97c5e2e77e1601c879a62dfc2d500df537eaaddd/lib/validator.js#L214-L228
53,212
redisjs/jsr-conf
lib/validator.js
notifyKeyspaceEvents
function notifyKeyspaceEvents(val) { var i, c; if(val) { for(i = 0;i < val.length;i++) { c = val.charAt(i); if(!~KEYSPACES_EVENTS.indexOf(c)) { throw new Error('Invalid event class character. Use \'g$lshzxeA\'.'); } } } }
javascript
function notifyKeyspaceEvents(val) { var i, c; if(val) { for(i = 0;i < val.length;i++) { c = val.charAt(i); if(!~KEYSPACES_EVENTS.indexOf(c)) { throw new Error('Invalid event class character. Use \'g$lshzxeA\'.'); } } } }
[ "function", "notifyKeyspaceEvents", "(", "val", ")", "{", "var", "i", ",", "c", ";", "if", "(", "val", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "val", ".", "length", ";", "i", "++", ")", "{", "c", "=", "val", ".", "charAt", "(", "i", ")", ";", "if", "(", "!", "~", "KEYSPACES_EVENTS", ".", "indexOf", "(", "c", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid event class character. Use \\'g$lshzxeA\\'.'", ")", ";", "}", "}", "}", "}" ]
Validate a notify-keyspace-events value.
[ "Validate", "a", "notify", "-", "keyspace", "-", "events", "value", "." ]
97c5e2e77e1601c879a62dfc2d500df537eaaddd
https://github.com/redisjs/jsr-conf/blob/97c5e2e77e1601c879a62dfc2d500df537eaaddd/lib/validator.js#L233-L243
53,213
passcod/quenya
index.js
rawLineToText
function rawLineToText (line) { const cut = line.indexOf(' ') return cut === -1 ? '' : line.slice(cut + 1).trim() }
javascript
function rawLineToText (line) { const cut = line.indexOf(' ') return cut === -1 ? '' : line.slice(cut + 1).trim() }
[ "function", "rawLineToText", "(", "line", ")", "{", "const", "cut", "=", "line", ".", "indexOf", "(", "' '", ")", "return", "cut", "===", "-", "1", "?", "''", ":", "line", ".", "slice", "(", "cut", "+", "1", ")", ".", "trim", "(", ")", "}" ]
! Extracts the text out of a raw comment line
[ "!", "Extracts", "the", "text", "out", "of", "a", "raw", "comment", "line" ]
05ceedf58d3bd50b91698b4b15a98f9139ca1918
https://github.com/passcod/quenya/blob/05ceedf58d3bd50b91698b4b15a98f9139ca1918/index.js#L78-L83
53,214
jmike/naomi
src/datatypes/Float.js
calculateMaxValue
function calculateMaxValue(precision, scale) { const arr = _.fill(Array(precision), '9'); if (scale) { arr.splice(precision - scale, 0, '.'); } return parseFloat(arr.join('')); }
javascript
function calculateMaxValue(precision, scale) { const arr = _.fill(Array(precision), '9'); if (scale) { arr.splice(precision - scale, 0, '.'); } return parseFloat(arr.join('')); }
[ "function", "calculateMaxValue", "(", "precision", ",", "scale", ")", "{", "const", "arr", "=", "_", ".", "fill", "(", "Array", "(", "precision", ")", ",", "'9'", ")", ";", "if", "(", "scale", ")", "{", "arr", ".", "splice", "(", "precision", "-", "scale", ",", "0", ",", "'.'", ")", ";", "}", "return", "parseFloat", "(", "arr", ".", "join", "(", "''", ")", ")", ";", "}" ]
Calculates the max absolute value for the given precision and scale. @param {number} precision the number of total digits in value, including decimals. @param {number} [scale] the numver of decimal digits in value. @return {number} @private
[ "Calculates", "the", "max", "absolute", "value", "for", "the", "given", "precision", "and", "scale", "." ]
debf6d7a70e5968ff57ffabb803e0eaa5c065a93
https://github.com/jmike/naomi/blob/debf6d7a70e5968ff57ffabb803e0eaa5c065a93/src/datatypes/Float.js#L12-L20
53,215
create-conform/allume
bin/boot.js
open
function open(selector) { if (p["--debug"] && host.runtime == host.RUNTIME_NODEJS) { return debug(p); } if (p["--ui"] && !ui) { if (!nw) { allume.update(allume.STATUS_ERROR, MSG_UI_UNAVAILABLE); return; } // spawn nw.js process for allume with parameters var findpath = nw.findpath; childProcess = childProcess || require("child_process"); path = path || require("path"); var PATH_NW = findpath(); var PATH_APP = path.join(__dirname, ".."); var PATH_CWD = process.cwd(); var env = Object.create(process.env); env.PWD = process.cwd(); process.argv.splice(1, 1); process.argv[0] = PATH_APP; for (var a in process.argv) { process.argv[a] = process.argv[a].replace(/"/g, "\""); } var ls = childProcess.spawn(PATH_NW, process.argv, {"cwd": PATH_CWD, "env" : env}); ls.stdout.on("data", function(data) { console.log(data.toString().trim()); }); ls.stderr.on("data", function(data) { console.error(data.toString().trim()); }); return; } var requests = []; var request = selector; if (p["--config"]) { var json; try { json = JSON.parse(p["--config"].json); } catch(e) { var e = new Error("Make sure the data you pass to the --config switch is valid JSON data."); e.name = "error-invalid-configuration"; if (typeof document !== "undefined" && firstOpen) { allume.update(e); } else { console.error(e); } firstOpen = false; return; } request = { "package" : selector, "configuration" : json }; } requests.push(request); if (requests) { using.apply(using, requests).then(function () { if (firstOpen) { allume.hide(); firstOpen = false; } }, function (loader) { usingFailed(loader); var e = new Error(err); e.name = errName; if (typeof document !== "undefined" && firstOpen) { allume.update(e); firstOpen = false; } else { console.error(e); } }); } }
javascript
function open(selector) { if (p["--debug"] && host.runtime == host.RUNTIME_NODEJS) { return debug(p); } if (p["--ui"] && !ui) { if (!nw) { allume.update(allume.STATUS_ERROR, MSG_UI_UNAVAILABLE); return; } // spawn nw.js process for allume with parameters var findpath = nw.findpath; childProcess = childProcess || require("child_process"); path = path || require("path"); var PATH_NW = findpath(); var PATH_APP = path.join(__dirname, ".."); var PATH_CWD = process.cwd(); var env = Object.create(process.env); env.PWD = process.cwd(); process.argv.splice(1, 1); process.argv[0] = PATH_APP; for (var a in process.argv) { process.argv[a] = process.argv[a].replace(/"/g, "\""); } var ls = childProcess.spawn(PATH_NW, process.argv, {"cwd": PATH_CWD, "env" : env}); ls.stdout.on("data", function(data) { console.log(data.toString().trim()); }); ls.stderr.on("data", function(data) { console.error(data.toString().trim()); }); return; } var requests = []; var request = selector; if (p["--config"]) { var json; try { json = JSON.parse(p["--config"].json); } catch(e) { var e = new Error("Make sure the data you pass to the --config switch is valid JSON data."); e.name = "error-invalid-configuration"; if (typeof document !== "undefined" && firstOpen) { allume.update(e); } else { console.error(e); } firstOpen = false; return; } request = { "package" : selector, "configuration" : json }; } requests.push(request); if (requests) { using.apply(using, requests).then(function () { if (firstOpen) { allume.hide(); firstOpen = false; } }, function (loader) { usingFailed(loader); var e = new Error(err); e.name = errName; if (typeof document !== "undefined" && firstOpen) { allume.update(e); firstOpen = false; } else { console.error(e); } }); } }
[ "function", "open", "(", "selector", ")", "{", "if", "(", "p", "[", "\"--debug\"", "]", "&&", "host", ".", "runtime", "==", "host", ".", "RUNTIME_NODEJS", ")", "{", "return", "debug", "(", "p", ")", ";", "}", "if", "(", "p", "[", "\"--ui\"", "]", "&&", "!", "ui", ")", "{", "if", "(", "!", "nw", ")", "{", "allume", ".", "update", "(", "allume", ".", "STATUS_ERROR", ",", "MSG_UI_UNAVAILABLE", ")", ";", "return", ";", "}", "// spawn nw.js process for allume with parameters", "var", "findpath", "=", "nw", ".", "findpath", ";", "childProcess", "=", "childProcess", "||", "require", "(", "\"child_process\"", ")", ";", "path", "=", "path", "||", "require", "(", "\"path\"", ")", ";", "var", "PATH_NW", "=", "findpath", "(", ")", ";", "var", "PATH_APP", "=", "path", ".", "join", "(", "__dirname", ",", "\"..\"", ")", ";", "var", "PATH_CWD", "=", "process", ".", "cwd", "(", ")", ";", "var", "env", "=", "Object", ".", "create", "(", "process", ".", "env", ")", ";", "env", ".", "PWD", "=", "process", ".", "cwd", "(", ")", ";", "process", ".", "argv", ".", "splice", "(", "1", ",", "1", ")", ";", "process", ".", "argv", "[", "0", "]", "=", "PATH_APP", ";", "for", "(", "var", "a", "in", "process", ".", "argv", ")", "{", "process", ".", "argv", "[", "a", "]", "=", "process", ".", "argv", "[", "a", "]", ".", "replace", "(", "/", "\"", "/", "g", ",", "\"\\\"\"", ")", ";", "}", "var", "ls", "=", "childProcess", ".", "spawn", "(", "PATH_NW", ",", "process", ".", "argv", ",", "{", "\"cwd\"", ":", "PATH_CWD", ",", "\"env\"", ":", "env", "}", ")", ";", "ls", ".", "stdout", ".", "on", "(", "\"data\"", ",", "function", "(", "data", ")", "{", "console", ".", "log", "(", "data", ".", "toString", "(", ")", ".", "trim", "(", ")", ")", ";", "}", ")", ";", "ls", ".", "stderr", ".", "on", "(", "\"data\"", ",", "function", "(", "data", ")", "{", "console", ".", "error", "(", "data", ".", "toString", "(", ")", ".", "trim", "(", ")", ")", ";", "}", ")", ";", "return", ";", "}", "var", "requests", "=", "[", "]", ";", "var", "request", "=", "selector", ";", "if", "(", "p", "[", "\"--config\"", "]", ")", "{", "var", "json", ";", "try", "{", "json", "=", "JSON", ".", "parse", "(", "p", "[", "\"--config\"", "]", ".", "json", ")", ";", "}", "catch", "(", "e", ")", "{", "var", "e", "=", "new", "Error", "(", "\"Make sure the data you pass to the --config switch is valid JSON data.\"", ")", ";", "e", ".", "name", "=", "\"error-invalid-configuration\"", ";", "if", "(", "typeof", "document", "!==", "\"undefined\"", "&&", "firstOpen", ")", "{", "allume", ".", "update", "(", "e", ")", ";", "}", "else", "{", "console", ".", "error", "(", "e", ")", ";", "}", "firstOpen", "=", "false", ";", "return", ";", "}", "request", "=", "{", "\"package\"", ":", "selector", ",", "\"configuration\"", ":", "json", "}", ";", "}", "requests", ".", "push", "(", "request", ")", ";", "if", "(", "requests", ")", "{", "using", ".", "apply", "(", "using", ",", "requests", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "firstOpen", ")", "{", "allume", ".", "hide", "(", ")", ";", "firstOpen", "=", "false", ";", "}", "}", ",", "function", "(", "loader", ")", "{", "usingFailed", "(", "loader", ")", ";", "var", "e", "=", "new", "Error", "(", "err", ")", ";", "e", ".", "name", "=", "errName", ";", "if", "(", "typeof", "document", "!==", "\"undefined\"", "&&", "firstOpen", ")", "{", "allume", ".", "update", "(", "e", ")", ";", "firstOpen", "=", "false", ";", "}", "else", "{", "console", ".", "error", "(", "e", ")", ";", "}", "}", ")", ";", "}", "}" ]
start the loading process for the specified selector
[ "start", "the", "loading", "process", "for", "the", "specified", "selector" ]
5fdc87804f1e2309c155d001e64d23029c781491
https://github.com/create-conform/allume/blob/5fdc87804f1e2309c155d001e64d23029c781491/bin/boot.js#L310-L392
53,216
create-conform/allume
bin/boot.js
debug
function debug(cmd) { // start node in debug mode childProcess = childProcess || require("child_process"); var PATH_CWD = process.cwd(); // splice out allume command process.argv.splice(0, 1); // find debug argument var debugIdx = -1; for (var a in process.argv) { if (process.argv[a] == "--debug") { debugIdx = a; } process.argv[a] = process.argv[a].replace(/"/g, "\""); } if (debugIdx >= 0) { process.argv.splice(debugIdx, 1); } if (!cmd["--debug"].port) { process.argv.splice(0, 0, "--debug-brk"); //process.argv.splice(0, 0, "--inspect"); } else { if (debugIdx >= 0) { process.argv.splice(debugIdx, 1); } process.argv.splice(0, 0, "--debug-brk=" + cmd["--debug"].port); //process.argv.splice(0, 0, "--inspect=" + cmd["--debug"].port); } var ls = childProcess.spawn("node", process.argv, {"cwd": PATH_CWD}); ls.stdout.on("data", function(data) { console.log(data.toString().trim()); }); ls.stderr.on("data", function(data) { console.error(data.toString().trim()); }); return; }
javascript
function debug(cmd) { // start node in debug mode childProcess = childProcess || require("child_process"); var PATH_CWD = process.cwd(); // splice out allume command process.argv.splice(0, 1); // find debug argument var debugIdx = -1; for (var a in process.argv) { if (process.argv[a] == "--debug") { debugIdx = a; } process.argv[a] = process.argv[a].replace(/"/g, "\""); } if (debugIdx >= 0) { process.argv.splice(debugIdx, 1); } if (!cmd["--debug"].port) { process.argv.splice(0, 0, "--debug-brk"); //process.argv.splice(0, 0, "--inspect"); } else { if (debugIdx >= 0) { process.argv.splice(debugIdx, 1); } process.argv.splice(0, 0, "--debug-brk=" + cmd["--debug"].port); //process.argv.splice(0, 0, "--inspect=" + cmd["--debug"].port); } var ls = childProcess.spawn("node", process.argv, {"cwd": PATH_CWD}); ls.stdout.on("data", function(data) { console.log(data.toString().trim()); }); ls.stderr.on("data", function(data) { console.error(data.toString().trim()); }); return; }
[ "function", "debug", "(", "cmd", ")", "{", "// start node in debug mode", "childProcess", "=", "childProcess", "||", "require", "(", "\"child_process\"", ")", ";", "var", "PATH_CWD", "=", "process", ".", "cwd", "(", ")", ";", "// splice out allume command", "process", ".", "argv", ".", "splice", "(", "0", ",", "1", ")", ";", "// find debug argument", "var", "debugIdx", "=", "-", "1", ";", "for", "(", "var", "a", "in", "process", ".", "argv", ")", "{", "if", "(", "process", ".", "argv", "[", "a", "]", "==", "\"--debug\"", ")", "{", "debugIdx", "=", "a", ";", "}", "process", ".", "argv", "[", "a", "]", "=", "process", ".", "argv", "[", "a", "]", ".", "replace", "(", "/", "\"", "/", "g", ",", "\"\\\"\"", ")", ";", "}", "if", "(", "debugIdx", ">=", "0", ")", "{", "process", ".", "argv", ".", "splice", "(", "debugIdx", ",", "1", ")", ";", "}", "if", "(", "!", "cmd", "[", "\"--debug\"", "]", ".", "port", ")", "{", "process", ".", "argv", ".", "splice", "(", "0", ",", "0", ",", "\"--debug-brk\"", ")", ";", "//process.argv.splice(0, 0, \"--inspect\");", "}", "else", "{", "if", "(", "debugIdx", ">=", "0", ")", "{", "process", ".", "argv", ".", "splice", "(", "debugIdx", ",", "1", ")", ";", "}", "process", ".", "argv", ".", "splice", "(", "0", ",", "0", ",", "\"--debug-brk=\"", "+", "cmd", "[", "\"--debug\"", "]", ".", "port", ")", ";", "//process.argv.splice(0, 0, \"--inspect=\" + cmd[\"--debug\"].port);", "}", "var", "ls", "=", "childProcess", ".", "spawn", "(", "\"node\"", ",", "process", ".", "argv", ",", "{", "\"cwd\"", ":", "PATH_CWD", "}", ")", ";", "ls", ".", "stdout", ".", "on", "(", "\"data\"", ",", "function", "(", "data", ")", "{", "console", ".", "log", "(", "data", ".", "toString", "(", ")", ".", "trim", "(", ")", ")", ";", "}", ")", ";", "ls", ".", "stderr", ".", "on", "(", "\"data\"", ",", "function", "(", "data", ")", "{", "console", ".", "error", "(", "data", ".", "toString", "(", ")", ".", "trim", "(", ")", ")", ";", "}", ")", ";", "return", ";", "}" ]
CLI -> DEBUG COMMAND
[ "CLI", "-", ">", "DEBUG", "COMMAND" ]
5fdc87804f1e2309c155d001e64d23029c781491
https://github.com/create-conform/allume/blob/5fdc87804f1e2309c155d001e64d23029c781491/bin/boot.js#L489-L533
53,217
atd-schubert/node-stream-lib
lib/spawn.js
function (command, params, opts) { var self = this; this.cmd = spawn(command, params, opts); this.cmd.stdout.on('readable', function () { self.isSpawnReadable = true; privatePump.apply(self); }); this.cmd.stdout.on('end', function () { self.push(null); }); this.on('finish', function () { this.cmd.stdin.end(); }); }
javascript
function (command, params, opts) { var self = this; this.cmd = spawn(command, params, opts); this.cmd.stdout.on('readable', function () { self.isSpawnReadable = true; privatePump.apply(self); }); this.cmd.stdout.on('end', function () { self.push(null); }); this.on('finish', function () { this.cmd.stdin.end(); }); }
[ "function", "(", "command", ",", "params", ",", "opts", ")", "{", "var", "self", "=", "this", ";", "this", ".", "cmd", "=", "spawn", "(", "command", ",", "params", ",", "opts", ")", ";", "this", ".", "cmd", ".", "stdout", ".", "on", "(", "'readable'", ",", "function", "(", ")", "{", "self", ".", "isSpawnReadable", "=", "true", ";", "privatePump", ".", "apply", "(", "self", ")", ";", "}", ")", ";", "this", ".", "cmd", ".", "stdout", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "self", ".", "push", "(", "null", ")", ";", "}", ")", ";", "this", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "this", ".", "cmd", ".", "stdin", ".", "end", "(", ")", ";", "}", ")", ";", "}" ]
Spawn a process and set stdin to writable stream and stdout to readable stream. Please take a look at node.js-API for further information. @param {string} command - Command name that shoul be executed @param {string[]} [params] - Parameters to set in spawned process @param {{}} [opts] - Optional spawn settings
[ "Spawn", "a", "process", "and", "set", "stdin", "to", "writable", "stream", "and", "stdout", "to", "readable", "stream", "." ]
90f27042fae84d2fbdbf9d28149b0673997f151a
https://github.com/atd-schubert/node-stream-lib/blob/90f27042fae84d2fbdbf9d28149b0673997f151a/lib/spawn.js#L56-L71
53,218
gethuman/pancakes-angular
lib/ngapp/generic.directives.js
addDirective
function addDirective(directiveName, dashCase, attrName, filterType, isBind, isBindOnce, isFilter) { app.directive(directiveName, ['i18n', 'config', function (i18n, config) { function setValue(scope, element, attrs, value) { value = !isFilter ? value : filterType === 'file' ? (config.staticFileRoot + value) : i18n.translate(value, scope); attrName === 'text' ? element.text(value) : attrName === 'class' ? attrs.$addClass(value) : attrs.$set(attrName, value, scope); } return { priority: 101, link: function linkFn(scope, element, attrs) { var originalValue = attrs[directiveName]; // if we are binding to the attribute value if (isBind) { var unwatch = scope.$watch(originalValue, function (value) { if (value !== undefined && value !== null) { setValue(scope, element, attrs, value); if (isBindOnce && unwatch) { unwatch(); } } }); } // else we are not binding, but we want to do some filtering else if (!isBind && isFilter && filterType !== null) { var fTextVal = (element && element.length && element[0].attributes && element[0].attributes[dashCase] && element[0].attributes[dashCase].value) || ''; // if the value contains {{ it means there is interpolation if (fTextVal.indexOf('{{') >= 0) { var unobserve = attrs.$observe(directiveName, function (value) { setValue(scope, element, attrs, value); if (isBindOnce && unobserve) { unobserve(); } }); } // else we are very simply setting the value else { setValue(scope, element, attrs, originalValue); } } else { throw new Error('Not bind nor filter in generic addDirective for ' + originalValue); } } }; }]); }
javascript
function addDirective(directiveName, dashCase, attrName, filterType, isBind, isBindOnce, isFilter) { app.directive(directiveName, ['i18n', 'config', function (i18n, config) { function setValue(scope, element, attrs, value) { value = !isFilter ? value : filterType === 'file' ? (config.staticFileRoot + value) : i18n.translate(value, scope); attrName === 'text' ? element.text(value) : attrName === 'class' ? attrs.$addClass(value) : attrs.$set(attrName, value, scope); } return { priority: 101, link: function linkFn(scope, element, attrs) { var originalValue = attrs[directiveName]; // if we are binding to the attribute value if (isBind) { var unwatch = scope.$watch(originalValue, function (value) { if (value !== undefined && value !== null) { setValue(scope, element, attrs, value); if (isBindOnce && unwatch) { unwatch(); } } }); } // else we are not binding, but we want to do some filtering else if (!isBind && isFilter && filterType !== null) { var fTextVal = (element && element.length && element[0].attributes && element[0].attributes[dashCase] && element[0].attributes[dashCase].value) || ''; // if the value contains {{ it means there is interpolation if (fTextVal.indexOf('{{') >= 0) { var unobserve = attrs.$observe(directiveName, function (value) { setValue(scope, element, attrs, value); if (isBindOnce && unobserve) { unobserve(); } }); } // else we are very simply setting the value else { setValue(scope, element, attrs, originalValue); } } else { throw new Error('Not bind nor filter in generic addDirective for ' + originalValue); } } }; }]); }
[ "function", "addDirective", "(", "directiveName", ",", "dashCase", ",", "attrName", ",", "filterType", ",", "isBind", ",", "isBindOnce", ",", "isFilter", ")", "{", "app", ".", "directive", "(", "directiveName", ",", "[", "'i18n'", ",", "'config'", ",", "function", "(", "i18n", ",", "config", ")", "{", "function", "setValue", "(", "scope", ",", "element", ",", "attrs", ",", "value", ")", "{", "value", "=", "!", "isFilter", "?", "value", ":", "filterType", "===", "'file'", "?", "(", "config", ".", "staticFileRoot", "+", "value", ")", ":", "i18n", ".", "translate", "(", "value", ",", "scope", ")", ";", "attrName", "===", "'text'", "?", "element", ".", "text", "(", "value", ")", ":", "attrName", "===", "'class'", "?", "attrs", ".", "$addClass", "(", "value", ")", ":", "attrs", ".", "$set", "(", "attrName", ",", "value", ",", "scope", ")", ";", "}", "return", "{", "priority", ":", "101", ",", "link", ":", "function", "linkFn", "(", "scope", ",", "element", ",", "attrs", ")", "{", "var", "originalValue", "=", "attrs", "[", "directiveName", "]", ";", "// if we are binding to the attribute value", "if", "(", "isBind", ")", "{", "var", "unwatch", "=", "scope", ".", "$watch", "(", "originalValue", ",", "function", "(", "value", ")", "{", "if", "(", "value", "!==", "undefined", "&&", "value", "!==", "null", ")", "{", "setValue", "(", "scope", ",", "element", ",", "attrs", ",", "value", ")", ";", "if", "(", "isBindOnce", "&&", "unwatch", ")", "{", "unwatch", "(", ")", ";", "}", "}", "}", ")", ";", "}", "// else we are not binding, but we want to do some filtering", "else", "if", "(", "!", "isBind", "&&", "isFilter", "&&", "filterType", "!==", "null", ")", "{", "var", "fTextVal", "=", "(", "element", "&&", "element", ".", "length", "&&", "element", "[", "0", "]", ".", "attributes", "&&", "element", "[", "0", "]", ".", "attributes", "[", "dashCase", "]", "&&", "element", "[", "0", "]", ".", "attributes", "[", "dashCase", "]", ".", "value", ")", "||", "''", ";", "// if the value contains {{ it means there is interpolation", "if", "(", "fTextVal", ".", "indexOf", "(", "'{{'", ")", ">=", "0", ")", "{", "var", "unobserve", "=", "attrs", ".", "$observe", "(", "directiveName", ",", "function", "(", "value", ")", "{", "setValue", "(", "scope", ",", "element", ",", "attrs", ",", "value", ")", ";", "if", "(", "isBindOnce", "&&", "unobserve", ")", "{", "unobserve", "(", ")", ";", "}", "}", ")", ";", "}", "// else we are very simply setting the value", "else", "{", "setValue", "(", "scope", ",", "element", ",", "attrs", ",", "originalValue", ")", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "'Not bind nor filter in generic addDirective for '", "+", "originalValue", ")", ";", "}", "}", "}", ";", "}", "]", ")", ";", "}" ]
function used for each of the generic directives
[ "function", "used", "for", "each", "of", "the", "generic", "directives" ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/ngapp/generic.directives.js#L30-L84
53,219
boxxa/1broker-api
1broker.js
apiMethod
function apiMethod(path, params, callback) { var url = config.url + path + '?token=' + config.api_key; if(params) url = url+= '&'+params; return apiRequest(url, callback); }
javascript
function apiMethod(path, params, callback) { var url = config.url + path + '?token=' + config.api_key; if(params) url = url+= '&'+params; return apiRequest(url, callback); }
[ "function", "apiMethod", "(", "path", ",", "params", ",", "callback", ")", "{", "var", "url", "=", "config", ".", "url", "+", "path", "+", "'?token='", "+", "config", ".", "api_key", ";", "if", "(", "params", ")", "url", "=", "url", "+=", "'&'", "+", "params", ";", "return", "apiRequest", "(", "url", ",", "callback", ")", ";", "}" ]
This method makes a private API request. @param {String} path The path to the API method @param {Object} params String of arguments to pass to the api call @param {Function} callback A callback function to be executed when the request is complete @return {Object} The request object
[ "This", "method", "makes", "a", "private", "API", "request", "." ]
a32c8f6ba9fa744f4ff0c2dcbc616f37d3bebb43
https://github.com/boxxa/1broker-api/blob/a32c8f6ba9fa744f4ff0c2dcbc616f37d3bebb43/1broker.js#L69-L73
53,220
boxxa/1broker-api
1broker.js
apiRequest
function apiRequest(url, callback) { var options = { url: url, method: 'GET', timeout: config.timeoutMS, maxAttempts: 3, retryDelay: 2000, // (default) wait for 2s before trying again retryStrategy: request.RetryStrategies.HTTPOrNetworkError // (default) retry on 5xx or network errors }; var req = request(options, function(error, response, body) { if(typeof callback === 'function') { var data; if(error) { callback.call(self, new Error('Error in server response: ' + JSON.stringify(error)), null); return; } try { data = JSON.parse(body); if(data.error != false){ callback.call(self, new Error('API error.'), null); } else { // All good. callback.call(self,null,data.response); } } catch(e) { callback.call(self, new Error('Could unknown server response occured.'), null); return; } } }); return req; }
javascript
function apiRequest(url, callback) { var options = { url: url, method: 'GET', timeout: config.timeoutMS, maxAttempts: 3, retryDelay: 2000, // (default) wait for 2s before trying again retryStrategy: request.RetryStrategies.HTTPOrNetworkError // (default) retry on 5xx or network errors }; var req = request(options, function(error, response, body) { if(typeof callback === 'function') { var data; if(error) { callback.call(self, new Error('Error in server response: ' + JSON.stringify(error)), null); return; } try { data = JSON.parse(body); if(data.error != false){ callback.call(self, new Error('API error.'), null); } else { // All good. callback.call(self,null,data.response); } } catch(e) { callback.call(self, new Error('Could unknown server response occured.'), null); return; } } }); return req; }
[ "function", "apiRequest", "(", "url", ",", "callback", ")", "{", "var", "options", "=", "{", "url", ":", "url", ",", "method", ":", "'GET'", ",", "timeout", ":", "config", ".", "timeoutMS", ",", "maxAttempts", ":", "3", ",", "retryDelay", ":", "2000", ",", "// (default) wait for 2s before trying again\r", "retryStrategy", ":", "request", ".", "RetryStrategies", ".", "HTTPOrNetworkError", "// (default) retry on 5xx or network errors\r", "}", ";", "var", "req", "=", "request", "(", "options", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "if", "(", "typeof", "callback", "===", "'function'", ")", "{", "var", "data", ";", "if", "(", "error", ")", "{", "callback", ".", "call", "(", "self", ",", "new", "Error", "(", "'Error in server response: '", "+", "JSON", ".", "stringify", "(", "error", ")", ")", ",", "null", ")", ";", "return", ";", "}", "try", "{", "data", "=", "JSON", ".", "parse", "(", "body", ")", ";", "if", "(", "data", ".", "error", "!=", "false", ")", "{", "callback", ".", "call", "(", "self", ",", "new", "Error", "(", "'API error.'", ")", ",", "null", ")", ";", "}", "else", "{", "// All good.\r", "callback", ".", "call", "(", "self", ",", "null", ",", "data", ".", "response", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "callback", ".", "call", "(", "self", ",", "new", "Error", "(", "'Could unknown server response occured.'", ")", ",", "null", ")", ";", "return", ";", "}", "}", "}", ")", ";", "return", "req", ";", "}" ]
This method sends the actual HTTP request @param {String} url The URL to make the request @param {String} requestType POST or GET @param {Object} params POST or GET body @param {Function} callback A callback function to call when the request is complete @return {Object} The request object
[ "This", "method", "sends", "the", "actual", "HTTP", "request" ]
a32c8f6ba9fa744f4ff0c2dcbc616f37d3bebb43
https://github.com/boxxa/1broker-api/blob/a32c8f6ba9fa744f4ff0c2dcbc616f37d3bebb43/1broker.js#L82-L116
53,221
redisjs/jsr-conf
lib/resolve.js
resolve
function resolve(file) { // not too sure about windows, but put the \\ // just in case if(!/^(\\\\|\/)/.test(file)) { return path.normalize(path.join(process.cwd(), file)); } return file; }
javascript
function resolve(file) { // not too sure about windows, but put the \\ // just in case if(!/^(\\\\|\/)/.test(file)) { return path.normalize(path.join(process.cwd(), file)); } return file; }
[ "function", "resolve", "(", "file", ")", "{", "// not too sure about windows, but put the \\\\", "// just in case", "if", "(", "!", "/", "^(\\\\\\\\|\\/)", "/", ".", "test", "(", "file", ")", ")", "{", "return", "path", ".", "normalize", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "file", ")", ")", ";", "}", "return", "file", ";", "}" ]
Utility used to resolve relative paths so that circular references can be detected correctly.
[ "Utility", "used", "to", "resolve", "relative", "paths", "so", "that", "circular", "references", "can", "be", "detected", "correctly", "." ]
97c5e2e77e1601c879a62dfc2d500df537eaaddd
https://github.com/redisjs/jsr-conf/blob/97c5e2e77e1601c879a62dfc2d500df537eaaddd/lib/resolve.js#L7-L14
53,222
redisjs/jsr-persistence
lib/encoding.js
encoding
function encoding(rtype, value, conf) { var enc; //console.dir('rtype: ' + rtype); //console.dir(value); switch(rtype) { case RTYPE.STRING: enc = ENCODING.RAW; // integer encoding if(typeof value === 'number' && parseInt(value) === value || (typeof value === 'string' && /^-?\d+$/.test(value)) || (value instanceof Buffer) && isIntegerBuffer(value)) { enc = ENCODING.INT; } break; case RTYPE.LIST: // no ziplist support yet enc = ENCODING.LINKEDLIST; break; case RTYPE.SET: // no intset support yet enc = ENCODING.HASHTABLE; break; case RTYPE.HASH: // no zipmap support yet enc = ENCODING.HASHTABLE; break; case RTYPE.ZSET: // no ziplist support yet enc = ENCODING.SKIPLIST; break; } return enc; }
javascript
function encoding(rtype, value, conf) { var enc; //console.dir('rtype: ' + rtype); //console.dir(value); switch(rtype) { case RTYPE.STRING: enc = ENCODING.RAW; // integer encoding if(typeof value === 'number' && parseInt(value) === value || (typeof value === 'string' && /^-?\d+$/.test(value)) || (value instanceof Buffer) && isIntegerBuffer(value)) { enc = ENCODING.INT; } break; case RTYPE.LIST: // no ziplist support yet enc = ENCODING.LINKEDLIST; break; case RTYPE.SET: // no intset support yet enc = ENCODING.HASHTABLE; break; case RTYPE.HASH: // no zipmap support yet enc = ENCODING.HASHTABLE; break; case RTYPE.ZSET: // no ziplist support yet enc = ENCODING.SKIPLIST; break; } return enc; }
[ "function", "encoding", "(", "rtype", ",", "value", ",", "conf", ")", "{", "var", "enc", ";", "//console.dir('rtype: ' + rtype);", "//console.dir(value);", "switch", "(", "rtype", ")", "{", "case", "RTYPE", ".", "STRING", ":", "enc", "=", "ENCODING", ".", "RAW", ";", "// integer encoding", "if", "(", "typeof", "value", "===", "'number'", "&&", "parseInt", "(", "value", ")", "===", "value", "||", "(", "typeof", "value", "===", "'string'", "&&", "/", "^-?\\d+$", "/", ".", "test", "(", "value", ")", ")", "||", "(", "value", "instanceof", "Buffer", ")", "&&", "isIntegerBuffer", "(", "value", ")", ")", "{", "enc", "=", "ENCODING", ".", "INT", ";", "}", "break", ";", "case", "RTYPE", ".", "LIST", ":", "// no ziplist support yet", "enc", "=", "ENCODING", ".", "LINKEDLIST", ";", "break", ";", "case", "RTYPE", ".", "SET", ":", "// no intset support yet", "enc", "=", "ENCODING", ".", "HASHTABLE", ";", "break", ";", "case", "RTYPE", ".", "HASH", ":", "// no zipmap support yet", "enc", "=", "ENCODING", ".", "HASHTABLE", ";", "break", ";", "case", "RTYPE", ".", "ZSET", ":", "// no ziplist support yet", "enc", "=", "ENCODING", ".", "SKIPLIST", ";", "break", ";", "}", "return", "enc", ";", "}" ]
Determine the encoding of an object. @param rtype The redis type string. @param value The value of the object. @param conf Reference to the configuration.
[ "Determine", "the", "encoding", "of", "an", "object", "." ]
77f3fc84ea7cbdb9f41a4dfa7ee1d89be61f7510
https://github.com/redisjs/jsr-persistence/blob/77f3fc84ea7cbdb9f41a4dfa7ee1d89be61f7510/lib/encoding.js#L46-L83
53,223
pasquale-inc/dictmanager
src/dictmanager.js
clone
function clone(obj) { if (null == obj || "object" != typeof obj) return obj; if (obj instanceof Object) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); }
javascript
function clone(obj) { if (null == obj || "object" != typeof obj) return obj; if (obj instanceof Object) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); }
[ "function", "clone", "(", "obj", ")", "{", "if", "(", "null", "==", "obj", "||", "\"object\"", "!=", "typeof", "obj", ")", "return", "obj", ";", "if", "(", "obj", "instanceof", "Object", ")", "{", "var", "copy", "=", "{", "}", ";", "for", "(", "var", "attr", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "attr", ")", ")", "copy", "[", "attr", "]", "=", "clone", "(", "obj", "[", "attr", "]", ")", ";", "}", "return", "copy", ";", "}", "throw", "new", "Error", "(", "\"Unable to copy obj! Its type isn't supported.\"", ")", ";", "}" ]
Clones a given Object. This leads us to a more 'immutable' programming.
[ "Clones", "a", "given", "Object", ".", "This", "leads", "us", "to", "a", "more", "immutable", "programming", "." ]
b4d219c37132429a132e98f0270a11b8d1e9d286
https://github.com/pasquale-inc/dictmanager/blob/b4d219c37132429a132e98f0270a11b8d1e9d286/src/dictmanager.js#L19-L32
53,224
wunderbyte/grunt-spiritual-edbml
tasks/things/inliner.js
resolvehtml
function resolvehtml(html, holders) { Object.keys(holders).forEach(function(key) { html = html.replace(placeholder(key), holders[key]); }); return html; }
javascript
function resolvehtml(html, holders) { Object.keys(holders).forEach(function(key) { html = html.replace(placeholder(key), holders[key]); }); return html; }
[ "function", "resolvehtml", "(", "html", ",", "holders", ")", "{", "Object", ".", "keys", "(", "holders", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "html", "=", "html", ".", "replace", "(", "placeholder", "(", "key", ")", ",", "holders", "[", "key", "]", ")", ";", "}", ")", ";", "return", "html", ";", "}" ]
Bypass dysfunction in Cheerio that would HTML-encode the JS. @param {string} html @param {Map<string,string>} holders @returns {string}
[ "Bypass", "dysfunction", "in", "Cheerio", "that", "would", "HTML", "-", "encode", "the", "JS", "." ]
2ba0aa8042eceee917f1ee48c7881345df3bce46
https://github.com/wunderbyte/grunt-spiritual-edbml/blob/2ba0aa8042eceee917f1ee48c7881345df3bce46/tasks/things/inliner.js#L103-L108
53,225
wunderbyte/grunt-spiritual-edbml
tasks/things/inliner.js
rename
function rename(filepath, options) { var base = filepath.substr(0, filepath.lastIndexOf('.')); return base + (options.extname || '.html'); }
javascript
function rename(filepath, options) { var base = filepath.substr(0, filepath.lastIndexOf('.')); return base + (options.extname || '.html'); }
[ "function", "rename", "(", "filepath", ",", "options", ")", "{", "var", "base", "=", "filepath", ".", "substr", "(", "0", ",", "filepath", ".", "lastIndexOf", "(", "'.'", ")", ")", ";", "return", "base", "+", "(", "options", ".", "extname", "||", "'.html'", ")", ";", "}" ]
Change extension of file and return new path. @param {string} filepath @param {Map} options @returns {string}
[ "Change", "extension", "of", "file", "and", "return", "new", "path", "." ]
2ba0aa8042eceee917f1ee48c7881345df3bce46
https://github.com/wunderbyte/grunt-spiritual-edbml/blob/2ba0aa8042eceee917f1ee48c7881345df3bce46/tasks/things/inliner.js#L139-L142
53,226
wunderbyte/grunt-spiritual-edbml
tasks/things/inliner.js
tabbing
function tabbing(script) { var prev, data; script = script[0]; if ((prev = script.prev) && (data = prev.data)) { return data.replace(/\n/g, ''); } return ''; }
javascript
function tabbing(script) { var prev, data; script = script[0]; if ((prev = script.prev) && (data = prev.data)) { return data.replace(/\n/g, ''); } return ''; }
[ "function", "tabbing", "(", "script", ")", "{", "var", "prev", ",", "data", ";", "script", "=", "script", "[", "0", "]", ";", "if", "(", "(", "prev", "=", "script", ".", "prev", ")", "&&", "(", "data", "=", "prev", ".", "data", ")", ")", "{", "return", "data", ".", "replace", "(", "/", "\\n", "/", "g", ",", "''", ")", ";", "}", "return", "''", ";", "}" ]
Preserve some indentation in output. @TODO: double check whitespace only. @param {$} script @returns {string}
[ "Preserve", "some", "indentation", "in", "output", "." ]
2ba0aa8042eceee917f1ee48c7881345df3bce46
https://github.com/wunderbyte/grunt-spiritual-edbml/blob/2ba0aa8042eceee917f1ee48c7881345df3bce46/tasks/things/inliner.js#L159-L166
53,227
imyelo/template-cache
lib/cache.js
function (filename, ext) { if (!_.isString(filename) || !_.isString(ext)) { return false; } ext = ext.slice(0, 1) === '.' ? ext : ('.' + ext); return !!(filename && filename.split(ext).pop() === ''); }
javascript
function (filename, ext) { if (!_.isString(filename) || !_.isString(ext)) { return false; } ext = ext.slice(0, 1) === '.' ? ext : ('.' + ext); return !!(filename && filename.split(ext).pop() === ''); }
[ "function", "(", "filename", ",", "ext", ")", "{", "if", "(", "!", "_", ".", "isString", "(", "filename", ")", "||", "!", "_", ".", "isString", "(", "ext", ")", ")", "{", "return", "false", ";", "}", "ext", "=", "ext", ".", "slice", "(", "0", ",", "1", ")", "===", "'.'", "?", "ext", ":", "(", "'.'", "+", "ext", ")", ";", "return", "!", "!", "(", "filename", "&&", "filename", ".", "split", "(", "ext", ")", ".", "pop", "(", ")", "===", "''", ")", ";", "}" ]
return if the filename with the extension
[ "return", "if", "the", "filename", "with", "the", "extension" ]
32f801072d35b5e85115ba8df56fc9ee6c468dd3
https://github.com/imyelo/template-cache/blob/32f801072d35b5e85115ba8df56fc9ee6c468dd3/lib/cache.js#L73-L79
53,228
imyelo/template-cache
lib/cache.js
function (basepath, action, recursive) { var isDirectory = function (target) { return fs.statSync(target).isDirectory(); }; var nextLevel = function (subpath) { _.each(fs.readdirSync(path.join(basepath, subpath)), function (filename) { if (isDirectory(path.join(basepath, (filename = path.join(subpath, filename))))) { if (recursive) { nextLevel(filename); } } else { action(filename); } }); }; nextLevel('./'); }
javascript
function (basepath, action, recursive) { var isDirectory = function (target) { return fs.statSync(target).isDirectory(); }; var nextLevel = function (subpath) { _.each(fs.readdirSync(path.join(basepath, subpath)), function (filename) { if (isDirectory(path.join(basepath, (filename = path.join(subpath, filename))))) { if (recursive) { nextLevel(filename); } } else { action(filename); } }); }; nextLevel('./'); }
[ "function", "(", "basepath", ",", "action", ",", "recursive", ")", "{", "var", "isDirectory", "=", "function", "(", "target", ")", "{", "return", "fs", ".", "statSync", "(", "target", ")", ".", "isDirectory", "(", ")", ";", "}", ";", "var", "nextLevel", "=", "function", "(", "subpath", ")", "{", "_", ".", "each", "(", "fs", ".", "readdirSync", "(", "path", ".", "join", "(", "basepath", ",", "subpath", ")", ")", ",", "function", "(", "filename", ")", "{", "if", "(", "isDirectory", "(", "path", ".", "join", "(", "basepath", ",", "(", "filename", "=", "path", ".", "join", "(", "subpath", ",", "filename", ")", ")", ")", ")", ")", "{", "if", "(", "recursive", ")", "{", "nextLevel", "(", "filename", ")", ";", "}", "}", "else", "{", "action", "(", "filename", ")", ";", "}", "}", ")", ";", "}", ";", "nextLevel", "(", "'./'", ")", ";", "}" ]
recursive read each file in directories
[ "recursive", "read", "each", "file", "in", "directories" ]
32f801072d35b5e85115ba8df56fc9ee6c468dd3
https://github.com/imyelo/template-cache/blob/32f801072d35b5e85115ba8df56fc9ee6c468dd3/lib/cache.js#L107-L123
53,229
inviqa/deck-task-registry
src/scripts/buildScripts.js
buildScripts
function buildScripts(conf, undertaker) { const uglifyConf = { mangle: false }; const typeScriptConf = { target: 'es5', allowJs: true }; const jsSrc = path.join(conf.themeConfig.root, conf.themeConfig.js.src, '**', '*.[tj]s'); const jsDest = path.join(conf.themeConfig.root, conf.themeConfig.js.dest); const useTypescript = Boolean(conf.themeConfig.js.es2015); // Build the theme scripts. return undertaker.src(jsSrc) .pipe(gulpIf(!conf.productionMode, sourcemaps.init())) .pipe(gulpIf(useTypescript, ts(typeScriptConf))) .pipe(gulpIf(conf.productionMode, uglify(uglifyConf))) .pipe(gulpIf(!conf.productionMode, sourcemaps.write('.'))) .pipe(undertaker.dest(jsDest)); }
javascript
function buildScripts(conf, undertaker) { const uglifyConf = { mangle: false }; const typeScriptConf = { target: 'es5', allowJs: true }; const jsSrc = path.join(conf.themeConfig.root, conf.themeConfig.js.src, '**', '*.[tj]s'); const jsDest = path.join(conf.themeConfig.root, conf.themeConfig.js.dest); const useTypescript = Boolean(conf.themeConfig.js.es2015); // Build the theme scripts. return undertaker.src(jsSrc) .pipe(gulpIf(!conf.productionMode, sourcemaps.init())) .pipe(gulpIf(useTypescript, ts(typeScriptConf))) .pipe(gulpIf(conf.productionMode, uglify(uglifyConf))) .pipe(gulpIf(!conf.productionMode, sourcemaps.write('.'))) .pipe(undertaker.dest(jsDest)); }
[ "function", "buildScripts", "(", "conf", ",", "undertaker", ")", "{", "const", "uglifyConf", "=", "{", "mangle", ":", "false", "}", ";", "const", "typeScriptConf", "=", "{", "target", ":", "'es5'", ",", "allowJs", ":", "true", "}", ";", "const", "jsSrc", "=", "path", ".", "join", "(", "conf", ".", "themeConfig", ".", "root", ",", "conf", ".", "themeConfig", ".", "js", ".", "src", ",", "'**'", ",", "'*.[tj]s'", ")", ";", "const", "jsDest", "=", "path", ".", "join", "(", "conf", ".", "themeConfig", ".", "root", ",", "conf", ".", "themeConfig", ".", "js", ".", "dest", ")", ";", "const", "useTypescript", "=", "Boolean", "(", "conf", ".", "themeConfig", ".", "js", ".", "es2015", ")", ";", "// Build the theme scripts.", "return", "undertaker", ".", "src", "(", "jsSrc", ")", ".", "pipe", "(", "gulpIf", "(", "!", "conf", ".", "productionMode", ",", "sourcemaps", ".", "init", "(", ")", ")", ")", ".", "pipe", "(", "gulpIf", "(", "useTypescript", ",", "ts", "(", "typeScriptConf", ")", ")", ")", ".", "pipe", "(", "gulpIf", "(", "conf", ".", "productionMode", ",", "uglify", "(", "uglifyConf", ")", ")", ")", ".", "pipe", "(", "gulpIf", "(", "!", "conf", ".", "productionMode", ",", "sourcemaps", ".", "write", "(", "'.'", ")", ")", ")", ".", "pipe", "(", "undertaker", ".", "dest", "(", "jsDest", ")", ")", ";", "}" ]
Build project scripts. @param {ConfigParser} conf A configuration parser object. @param {Undertaker} undertaker An Undertaker instance. @returns {Stream} A stream of files.
[ "Build", "project", "scripts", "." ]
4c31787b978e9d99a47052e090d4589a50cd3015
https://github.com/inviqa/deck-task-registry/blob/4c31787b978e9d99a47052e090d4589a50cd3015/src/scripts/buildScripts.js#L17-L41
53,230
andrewscwei/requiem
src/dom/hasStyle.js
hasStyle
function hasStyle(element, key) { assertType(element, Node, false, 'Invalid element specified'); return element.style[key] !== ''; }
javascript
function hasStyle(element, key) { assertType(element, Node, false, 'Invalid element specified'); return element.style[key] !== ''; }
[ "function", "hasStyle", "(", "element", ",", "key", ")", "{", "assertType", "(", "element", ",", "Node", ",", "false", ",", "'Invalid element specified'", ")", ";", "return", "element", ".", "style", "[", "key", "]", "!==", "''", ";", "}" ]
Checks to see if a Node has the specified inline CSS rule. @param {Node} element - Target element. @param {string} key - Name of the style. @return {boolean} @alias module:requiem~dom.hasStyle
[ "Checks", "to", "see", "if", "a", "Node", "has", "the", "specified", "inline", "CSS", "rule", "." ]
c4182bfffc9841c6de5718f689ad3c2060511777
https://github.com/andrewscwei/requiem/blob/c4182bfffc9841c6de5718f689ad3c2060511777/src/dom/hasStyle.js#L17-L20
53,231
gethuman/jyt
lib/jyt.parser.js
convertDomToJyt
function convertDomToJyt(dom) { var i, elems, tempElem; // if just one element in the array, bump it up a level if (utils.isArray(dom) && dom.length === 1) { dom = dom[0]; } // if multiple, then we create a sibling array of elems and return it else if (utils.isArray(dom)) { elems = []; for (i = 0; i < dom.length; i++) { tempElem = convertDomToJyt(dom[i]); if (tempElem !== null) { elems.push(tempElem); } } return runtime.naked(elems, null); } // if type is string, then just return it if (dom.type === 'text') { return dom.data; } // if no dom name, then just return empty string since it is likely a comment if (!dom.name) { return null; } // if we get here then we have just one element var elem = runtime.elem(dom.name); var childCount = dom.children && dom.children.length; // attributes should be the same elem.attributes = dom.attribs; // recursively add children if (dom.children && dom.children.length) { elem.children = []; for (i = 0; i < childCount; i++) { tempElem = convertDomToJyt(dom.children[i]); if (tempElem !== null) { elem.children.push(tempElem); } } // if one child that is a string, bring it up a level if (elem.children.length === 1 && utils.isString(elem.children[0])) { elem.text = elem.children[0]; delete elem.children; } // if no children, remove it else if (elem.children.length === 0) { delete elem.children; } } return elem; }
javascript
function convertDomToJyt(dom) { var i, elems, tempElem; // if just one element in the array, bump it up a level if (utils.isArray(dom) && dom.length === 1) { dom = dom[0]; } // if multiple, then we create a sibling array of elems and return it else if (utils.isArray(dom)) { elems = []; for (i = 0; i < dom.length; i++) { tempElem = convertDomToJyt(dom[i]); if (tempElem !== null) { elems.push(tempElem); } } return runtime.naked(elems, null); } // if type is string, then just return it if (dom.type === 'text') { return dom.data; } // if no dom name, then just return empty string since it is likely a comment if (!dom.name) { return null; } // if we get here then we have just one element var elem = runtime.elem(dom.name); var childCount = dom.children && dom.children.length; // attributes should be the same elem.attributes = dom.attribs; // recursively add children if (dom.children && dom.children.length) { elem.children = []; for (i = 0; i < childCount; i++) { tempElem = convertDomToJyt(dom.children[i]); if (tempElem !== null) { elem.children.push(tempElem); } } // if one child that is a string, bring it up a level if (elem.children.length === 1 && utils.isString(elem.children[0])) { elem.text = elem.children[0]; delete elem.children; } // if no children, remove it else if (elem.children.length === 0) { delete elem.children; } } return elem; }
[ "function", "convertDomToJyt", "(", "dom", ")", "{", "var", "i", ",", "elems", ",", "tempElem", ";", "// if just one element in the array, bump it up a level", "if", "(", "utils", ".", "isArray", "(", "dom", ")", "&&", "dom", ".", "length", "===", "1", ")", "{", "dom", "=", "dom", "[", "0", "]", ";", "}", "// if multiple, then we create a sibling array of elems and return it", "else", "if", "(", "utils", ".", "isArray", "(", "dom", ")", ")", "{", "elems", "=", "[", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "dom", ".", "length", ";", "i", "++", ")", "{", "tempElem", "=", "convertDomToJyt", "(", "dom", "[", "i", "]", ")", ";", "if", "(", "tempElem", "!==", "null", ")", "{", "elems", ".", "push", "(", "tempElem", ")", ";", "}", "}", "return", "runtime", ".", "naked", "(", "elems", ",", "null", ")", ";", "}", "// if type is string, then just return it", "if", "(", "dom", ".", "type", "===", "'text'", ")", "{", "return", "dom", ".", "data", ";", "}", "// if no dom name, then just return empty string since it is likely a comment", "if", "(", "!", "dom", ".", "name", ")", "{", "return", "null", ";", "}", "// if we get here then we have just one element", "var", "elem", "=", "runtime", ".", "elem", "(", "dom", ".", "name", ")", ";", "var", "childCount", "=", "dom", ".", "children", "&&", "dom", ".", "children", ".", "length", ";", "// attributes should be the same", "elem", ".", "attributes", "=", "dom", ".", "attribs", ";", "// recursively add children", "if", "(", "dom", ".", "children", "&&", "dom", ".", "children", ".", "length", ")", "{", "elem", ".", "children", "=", "[", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "childCount", ";", "i", "++", ")", "{", "tempElem", "=", "convertDomToJyt", "(", "dom", ".", "children", "[", "i", "]", ")", ";", "if", "(", "tempElem", "!==", "null", ")", "{", "elem", ".", "children", ".", "push", "(", "tempElem", ")", ";", "}", "}", "// if one child that is a string, bring it up a level", "if", "(", "elem", ".", "children", ".", "length", "===", "1", "&&", "utils", ".", "isString", "(", "elem", ".", "children", "[", "0", "]", ")", ")", "{", "elem", ".", "text", "=", "elem", ".", "children", "[", "0", "]", ";", "delete", "elem", ".", "children", ";", "}", "// if no children, remove it", "else", "if", "(", "elem", ".", "children", ".", "length", "===", "0", ")", "{", "delete", "elem", ".", "children", ";", "}", "}", "return", "elem", ";", "}" ]
Convert the HTML parser DOM format to Jyt format @param dom
[ "Convert", "the", "HTML", "parser", "DOM", "format", "to", "Jyt", "format" ]
716be37e09217b4be917e179389f752212a428b3
https://github.com/gethuman/jyt/blob/716be37e09217b4be917e179389f752212a428b3/lib/jyt.parser.js#L15-L73
53,232
gethuman/jyt
lib/jyt.parser.js
parse
function parse(html, cb) { if (!cb) { throw new Error('Must pass in callback to parse() as 2nd param'); } var handler = new htmlparser.DefaultHandler(function (error, dom) { if (error) { cb('Error while parsing: ' + error); } else { var jytObj = convertDomToJyt(dom); cb(null, jytObj); } }, { ignoreWhitespace: true }); var parser = new htmlparser.Parser(handler); parser.parseComplete(html); }
javascript
function parse(html, cb) { if (!cb) { throw new Error('Must pass in callback to parse() as 2nd param'); } var handler = new htmlparser.DefaultHandler(function (error, dom) { if (error) { cb('Error while parsing: ' + error); } else { var jytObj = convertDomToJyt(dom); cb(null, jytObj); } }, { ignoreWhitespace: true }); var parser = new htmlparser.Parser(handler); parser.parseComplete(html); }
[ "function", "parse", "(", "html", ",", "cb", ")", "{", "if", "(", "!", "cb", ")", "{", "throw", "new", "Error", "(", "'Must pass in callback to parse() as 2nd param'", ")", ";", "}", "var", "handler", "=", "new", "htmlparser", ".", "DefaultHandler", "(", "function", "(", "error", ",", "dom", ")", "{", "if", "(", "error", ")", "{", "cb", "(", "'Error while parsing: '", "+", "error", ")", ";", "}", "else", "{", "var", "jytObj", "=", "convertDomToJyt", "(", "dom", ")", ";", "cb", "(", "null", ",", "jytObj", ")", ";", "}", "}", ",", "{", "ignoreWhitespace", ":", "true", "}", ")", ";", "var", "parser", "=", "new", "htmlparser", ".", "Parser", "(", "handler", ")", ";", "parser", ".", "parseComplete", "(", "html", ")", ";", "}" ]
Parse the HTML into Jyt format @param html @param cb @returns {*}
[ "Parse", "the", "HTML", "into", "Jyt", "format" ]
716be37e09217b4be917e179389f752212a428b3
https://github.com/gethuman/jyt/blob/716be37e09217b4be917e179389f752212a428b3/lib/jyt.parser.js#L81-L99
53,233
jsdevel/node-no-utils
index.js
transform
function transform(input, test) { var i, len, value, keys, key, newInput; if (Array.isArray(input)) { newInput = []; for (i = input.length - 1; i >= 0 ; i--) { value = input[i]; if (!test(value)) { newInput.unshift(value); } } input = newInput; } else if (input && input.constructor === Object) { keys = Object.keys(input); newInput = {}; for (i = 0, len = keys.length; i < len; i++) { key = keys[i]; value = input[keys[i]]; if (!test(value)) { newInput[key] = value; } } input = newInput; } else if (test(input)) { input = null; } return input; }
javascript
function transform(input, test) { var i, len, value, keys, key, newInput; if (Array.isArray(input)) { newInput = []; for (i = input.length - 1; i >= 0 ; i--) { value = input[i]; if (!test(value)) { newInput.unshift(value); } } input = newInput; } else if (input && input.constructor === Object) { keys = Object.keys(input); newInput = {}; for (i = 0, len = keys.length; i < len; i++) { key = keys[i]; value = input[keys[i]]; if (!test(value)) { newInput[key] = value; } } input = newInput; } else if (test(input)) { input = null; } return input; }
[ "function", "transform", "(", "input", ",", "test", ")", "{", "var", "i", ",", "len", ",", "value", ",", "keys", ",", "key", ",", "newInput", ";", "if", "(", "Array", ".", "isArray", "(", "input", ")", ")", "{", "newInput", "=", "[", "]", ";", "for", "(", "i", "=", "input", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "value", "=", "input", "[", "i", "]", ";", "if", "(", "!", "test", "(", "value", ")", ")", "{", "newInput", ".", "unshift", "(", "value", ")", ";", "}", "}", "input", "=", "newInput", ";", "}", "else", "if", "(", "input", "&&", "input", ".", "constructor", "===", "Object", ")", "{", "keys", "=", "Object", ".", "keys", "(", "input", ")", ";", "newInput", "=", "{", "}", ";", "for", "(", "i", "=", "0", ",", "len", "=", "keys", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "key", "=", "keys", "[", "i", "]", ";", "value", "=", "input", "[", "keys", "[", "i", "]", "]", ";", "if", "(", "!", "test", "(", "value", ")", ")", "{", "newInput", "[", "key", "]", "=", "value", ";", "}", "}", "input", "=", "newInput", ";", "}", "else", "if", "(", "test", "(", "input", ")", ")", "{", "input", "=", "null", ";", "}", "return", "input", ";", "}" ]
Transforms the input based on the result of test. Test is run against object values, array values, and anything else. If test returns true, object values are deleted, array items are removed, and null is returned for anything else. @param {?} input @param {Function} test @return {?}
[ "Transforms", "the", "input", "based", "on", "the", "result", "of", "test", ".", "Test", "is", "run", "against", "object", "values", "array", "values", "and", "anything", "else", ".", "If", "test", "returns", "true", "object", "values", "are", "deleted", "array", "items", "are", "removed", "and", "null", "is", "returned", "for", "anything", "else", "." ]
cbb79cff028c0e1dc7ce40b495a38a5cbb3dd412
https://github.com/jsdevel/node-no-utils/blob/cbb79cff028c0e1dc7ce40b495a38a5cbb3dd412/index.js#L16-L51
53,234
andrewscwei/requiem
src/helpers/checkType.js
checkType
function checkType(value, type) { if (typeof type === 'string') { switch (type) { case 'string': case 'object': case 'number': case 'boolean': case 'function': return typeof value === type; case 'class': return typeof value === 'function'; case 'array': return value.constructor === Array; default: return false; } } else { return value instanceof type; } }
javascript
function checkType(value, type) { if (typeof type === 'string') { switch (type) { case 'string': case 'object': case 'number': case 'boolean': case 'function': return typeof value === type; case 'class': return typeof value === 'function'; case 'array': return value.constructor === Array; default: return false; } } else { return value instanceof type; } }
[ "function", "checkType", "(", "value", ",", "type", ")", "{", "if", "(", "typeof", "type", "===", "'string'", ")", "{", "switch", "(", "type", ")", "{", "case", "'string'", ":", "case", "'object'", ":", "case", "'number'", ":", "case", "'boolean'", ":", "case", "'function'", ":", "return", "typeof", "value", "===", "type", ";", "case", "'class'", ":", "return", "typeof", "value", "===", "'function'", ";", "case", "'array'", ":", "return", "value", ".", "constructor", "===", "Array", ";", "default", ":", "return", "false", ";", "}", "}", "else", "{", "return", "value", "instanceof", "type", ";", "}", "}" ]
Verifies that a given is of the given type. @param {*} value - Any value. @param {*} type - Any class or string that describes a type. @return {boolean} True if validation passes, false otherwise. @alias module:requiem~helpers.checkType
[ "Verifies", "that", "a", "given", "is", "of", "the", "given", "type", "." ]
c4182bfffc9841c6de5718f689ad3c2060511777
https://github.com/andrewscwei/requiem/blob/c4182bfffc9841c6de5718f689ad3c2060511777/src/helpers/checkType.js#L15-L35
53,235
damsonjs/damson-driver-file
index.js
send
function send(object) { if (typeof object === 'object') { return write(this.filepath, JSON.stringify(object, null, ' ')); } else { return write(this.filepath, object.toString()); } }
javascript
function send(object) { if (typeof object === 'object') { return write(this.filepath, JSON.stringify(object, null, ' ')); } else { return write(this.filepath, object.toString()); } }
[ "function", "send", "(", "object", ")", "{", "if", "(", "typeof", "object", "===", "'object'", ")", "{", "return", "write", "(", "this", ".", "filepath", ",", "JSON", ".", "stringify", "(", "object", ",", "null", ",", "' '", ")", ")", ";", "}", "else", "{", "return", "write", "(", "this", ".", "filepath", ",", "object", ".", "toString", "(", ")", ")", ";", "}", "}" ]
Writes object to File @param {object} object Some output to File
[ "Writes", "object", "to", "File" ]
bc71c73dcfdc90b45a6a94a266e79ba7ea30da13
https://github.com/damsonjs/damson-driver-file/blob/bc71c73dcfdc90b45a6a94a266e79ba7ea30da13/index.js#L11-L17
53,236
belbis/dynamizer
src/dynamizer.js
Dynamizer
function Dynamizer(options) { // don"t enforce new if (!(this instanceof Dynamizer)) return new Dynamizer(options); if (options) { this.disableBoolean = options.disableBoolean || false; // maps boolean values to numeric this.enableSets = options.enableSets || false; // unsure about this option as yet this.disableLossyFloat = options.disableLossyFloat || false; } }
javascript
function Dynamizer(options) { // don"t enforce new if (!(this instanceof Dynamizer)) return new Dynamizer(options); if (options) { this.disableBoolean = options.disableBoolean || false; // maps boolean values to numeric this.enableSets = options.enableSets || false; // unsure about this option as yet this.disableLossyFloat = options.disableLossyFloat || false; } }
[ "function", "Dynamizer", "(", "options", ")", "{", "// don\"t enforce new", "if", "(", "!", "(", "this", "instanceof", "Dynamizer", ")", ")", "return", "new", "Dynamizer", "(", "options", ")", ";", "if", "(", "options", ")", "{", "this", ".", "disableBoolean", "=", "options", ".", "disableBoolean", "||", "false", ";", "// maps boolean values to numeric", "this", ".", "enableSets", "=", "options", ".", "enableSets", "||", "false", ";", "// unsure about this option as yet", "this", ".", "disableLossyFloat", "=", "options", ".", "disableLossyFloat", "||", "false", ";", "}", "}" ]
mirror of the boto Dynamizer class for node.js
[ "mirror", "of", "the", "boto", "Dynamizer", "class", "for", "node", ".", "js" ]
75e05e2d1c8ca6f05c09c9dac0bd70f8f82fbbda
https://github.com/belbis/dynamizer/blob/75e05e2d1c8ca6f05c09c9dac0bd70f8f82fbbda/src/dynamizer.js#L17-L27
53,237
integreat-io/great-uri-template
lib/filters/max.js
max
function max (value, length) { if (value === null || value === undefined || isNaN(length)) { return value } return String.prototype.substring.call(value, 0, length) }
javascript
function max (value, length) { if (value === null || value === undefined || isNaN(length)) { return value } return String.prototype.substring.call(value, 0, length) }
[ "function", "max", "(", "value", ",", "length", ")", "{", "if", "(", "value", "===", "null", "||", "value", "===", "undefined", "||", "isNaN", "(", "length", ")", ")", "{", "return", "value", "}", "return", "String", ".", "prototype", ".", "substring", ".", "call", "(", "value", ",", "0", ",", "length", ")", "}" ]
Return the `length` first characters of `value`. If `length` is higher than the number of characters in value, value is returned as is. @param {string} value - The value to shorten @param {integer} length - The max number of characers to return @returns {string} A string of maximum `length` characters
[ "Return", "the", "length", "first", "characters", "of", "value", ".", "If", "length", "is", "higher", "than", "the", "number", "of", "characters", "in", "value", "value", "is", "returned", "as", "is", "." ]
0e896ead0567737cf31a4a8b76a26cfa6ce60759
https://github.com/integreat-io/great-uri-template/blob/0e896ead0567737cf31a4a8b76a26cfa6ce60759/lib/filters/max.js#L8-L14
53,238
transomjs/transom-server-functions
lib/serverFxHandler.js
function (req, res, next) { // Delayed resolution of the isLoggedIn middleware. if (server.registry.has('localUserMiddleware')) { const middleware = server.registry.get('localUserMiddleware'); middleware.isLoggedInMiddleware()(req, res, next); } else { next(new restifyErrors.ForbiddenError(`Server configuration error, 'localUserMiddleware' not found.`)); } }
javascript
function (req, res, next) { // Delayed resolution of the isLoggedIn middleware. if (server.registry.has('localUserMiddleware')) { const middleware = server.registry.get('localUserMiddleware'); middleware.isLoggedInMiddleware()(req, res, next); } else { next(new restifyErrors.ForbiddenError(`Server configuration error, 'localUserMiddleware' not found.`)); } }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "// Delayed resolution of the isLoggedIn middleware.", "if", "(", "server", ".", "registry", ".", "has", "(", "'localUserMiddleware'", ")", ")", "{", "const", "middleware", "=", "server", ".", "registry", ".", "get", "(", "'localUserMiddleware'", ")", ";", "middleware", ".", "isLoggedInMiddleware", "(", ")", "(", "req", ",", "res", ",", "next", ")", ";", "}", "else", "{", "next", "(", "new", "restifyErrors", ".", "ForbiddenError", "(", "`", "`", ")", ")", ";", "}", "}" ]
Make sure User is authenticated
[ "Make", "sure", "User", "is", "authenticated" ]
68577950f5964031929f6b7360240bdcda65f004
https://github.com/transomjs/transom-server-functions/blob/68577950f5964031929f6b7360240bdcda65f004/lib/serverFxHandler.js#L15-L23
53,239
jmendiara/gitftw
examples/usage-async.js
doWork
function doWork(cb) { async.series([ async.apply(deleteTags), async.apply(createTag) ], cb); }
javascript
function doWork(cb) { async.series([ async.apply(deleteTags), async.apply(createTag) ], cb); }
[ "function", "doWork", "(", "cb", ")", "{", "async", ".", "series", "(", "[", "async", ".", "apply", "(", "deleteTags", ")", ",", "async", ".", "apply", "(", "createTag", ")", "]", ",", "cb", ")", ";", "}" ]
Creates and deletes tags
[ "Creates", "and", "deletes", "tags" ]
ba91b0d68b7791b5b557addc685737f6c912b4f3
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/examples/usage-async.js#L47-L52
53,240
openknowledge-archive/datapackage-init-js
demo/app.js
dictify
function dictify(serializedFormArray) { var o = {}; $.each(serializedFormArray, function() { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }
javascript
function dictify(serializedFormArray) { var o = {}; $.each(serializedFormArray, function() { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }
[ "function", "dictify", "(", "serializedFormArray", ")", "{", "var", "o", "=", "{", "}", ";", "$", ".", "each", "(", "serializedFormArray", ",", "function", "(", ")", "{", "if", "(", "o", "[", "this", ".", "name", "]", "!==", "undefined", ")", "{", "if", "(", "!", "o", "[", "this", ".", "name", "]", ".", "push", ")", "{", "o", "[", "this", ".", "name", "]", "=", "[", "o", "[", "this", ".", "name", "]", "]", ";", "}", "o", "[", "this", ".", "name", "]", ".", "push", "(", "this", ".", "value", "||", "''", ")", ";", "}", "else", "{", "o", "[", "this", ".", "name", "]", "=", "this", ".", "value", "||", "''", ";", "}", "}", ")", ";", "return", "o", ";", "}" ]
convert form array to dict
[ "convert", "form", "array", "to", "dict" ]
75d6c35f301e42c96dad345956cee5aeb0656d04
https://github.com/openknowledge-archive/datapackage-init-js/blob/75d6c35f301e42c96dad345956cee5aeb0656d04/demo/app.js#L39-L52
53,241
maxprogram/q-plus
index.js
eachSeries
function eachSeries(fn) { var i = 0; return this.then(function(object) { return reduce(object, function(newPromise, value, key) { // Allow value to be a promise if (Q.isPromise(value)) return newPromise.then(function() { return value; }).then(function(v) { return fn(v, key || i++); }); return newPromise.then(function() { return fn(value, key || i++);; }); }, Q()) .thenResolve(object) }); }
javascript
function eachSeries(fn) { var i = 0; return this.then(function(object) { return reduce(object, function(newPromise, value, key) { // Allow value to be a promise if (Q.isPromise(value)) return newPromise.then(function() { return value; }).then(function(v) { return fn(v, key || i++); }); return newPromise.then(function() { return fn(value, key || i++);; }); }, Q()) .thenResolve(object) }); }
[ "function", "eachSeries", "(", "fn", ")", "{", "var", "i", "=", "0", ";", "return", "this", ".", "then", "(", "function", "(", "object", ")", "{", "return", "reduce", "(", "object", ",", "function", "(", "newPromise", ",", "value", ",", "key", ")", "{", "// Allow value to be a promise", "if", "(", "Q", ".", "isPromise", "(", "value", ")", ")", "return", "newPromise", ".", "then", "(", "function", "(", ")", "{", "return", "value", ";", "}", ")", ".", "then", "(", "function", "(", "v", ")", "{", "return", "fn", "(", "v", ",", "key", "||", "i", "++", ")", ";", "}", ")", ";", "return", "newPromise", ".", "then", "(", "function", "(", ")", "{", "return", "fn", "(", "value", ",", "key", "||", "i", "++", ")", ";", ";", "}", ")", ";", "}", ",", "Q", "(", ")", ")", ".", "thenResolve", "(", "object", ")", "}", ")", ";", "}" ]
Executes function for each element of an array or object, running any promises in series only after the last has been completed. @promise {(array|object)} @param {function} fn : The function called per iteration @param value : Value of element @param key|index : Key if object, index if array @returns {object} Original object
[ "Executes", "function", "for", "each", "element", "of", "an", "array", "or", "object", "running", "any", "promises", "in", "series", "only", "after", "the", "last", "has", "been", "completed", "." ]
d3406f662a00172be39eebe0907db06e41db8307
https://github.com/maxprogram/q-plus/blob/d3406f662a00172be39eebe0907db06e41db8307/index.js#L142-L159
53,242
maxprogram/q-plus
index.js
mapSeries
function mapSeries(fn) { var newArray = []; // Allow iterator return to be a promise function push(value, key) { value = fn(value, key); if (Q.isPromise(value)) return value.then(function(v) { newArray.push(v); }); newArray.push(value); } return this.then(function(object) { return reduce(object, function(newPromise, value, key) { // Allow value to be a promise if (Q.isPromise(value)) return newPromise.then(function() { return value; }).then(function(v) { return push(v, key); }); return newPromise.then(function() { return push(value, key) }); }, Q()); }).thenResolve(newArray); }
javascript
function mapSeries(fn) { var newArray = []; // Allow iterator return to be a promise function push(value, key) { value = fn(value, key); if (Q.isPromise(value)) return value.then(function(v) { newArray.push(v); }); newArray.push(value); } return this.then(function(object) { return reduce(object, function(newPromise, value, key) { // Allow value to be a promise if (Q.isPromise(value)) return newPromise.then(function() { return value; }).then(function(v) { return push(v, key); }); return newPromise.then(function() { return push(value, key) }); }, Q()); }).thenResolve(newArray); }
[ "function", "mapSeries", "(", "fn", ")", "{", "var", "newArray", "=", "[", "]", ";", "// Allow iterator return to be a promise", "function", "push", "(", "value", ",", "key", ")", "{", "value", "=", "fn", "(", "value", ",", "key", ")", ";", "if", "(", "Q", ".", "isPromise", "(", "value", ")", ")", "return", "value", ".", "then", "(", "function", "(", "v", ")", "{", "newArray", ".", "push", "(", "v", ")", ";", "}", ")", ";", "newArray", ".", "push", "(", "value", ")", ";", "}", "return", "this", ".", "then", "(", "function", "(", "object", ")", "{", "return", "reduce", "(", "object", ",", "function", "(", "newPromise", ",", "value", ",", "key", ")", "{", "// Allow value to be a promise", "if", "(", "Q", ".", "isPromise", "(", "value", ")", ")", "return", "newPromise", ".", "then", "(", "function", "(", ")", "{", "return", "value", ";", "}", ")", ".", "then", "(", "function", "(", "v", ")", "{", "return", "push", "(", "v", ",", "key", ")", ";", "}", ")", ";", "return", "newPromise", ".", "then", "(", "function", "(", ")", "{", "return", "push", "(", "value", ",", "key", ")", "}", ")", ";", "}", ",", "Q", "(", ")", ")", ";", "}", ")", ".", "thenResolve", "(", "newArray", ")", ";", "}" ]
Transforms an array or object into a new array using the iterator function, running any promises in series only after the last has been completed. @promise {(array|object)} @param {function} fn : The function called per iteration @param value : Value of element @param [key] : Key of element @returns {array} Transformed array
[ "Transforms", "an", "array", "or", "object", "into", "a", "new", "array", "using", "the", "iterator", "function", "running", "any", "promises", "in", "series", "only", "after", "the", "last", "has", "been", "completed", "." ]
d3406f662a00172be39eebe0907db06e41db8307
https://github.com/maxprogram/q-plus/blob/d3406f662a00172be39eebe0907db06e41db8307/index.js#L170-L195
53,243
maxprogram/q-plus
index.js
push
function push(value, key) { value = fn(value, key); if (Q.isPromise(value)) return value.then(function(v) { newArray.push(v); }); newArray.push(value); }
javascript
function push(value, key) { value = fn(value, key); if (Q.isPromise(value)) return value.then(function(v) { newArray.push(v); }); newArray.push(value); }
[ "function", "push", "(", "value", ",", "key", ")", "{", "value", "=", "fn", "(", "value", ",", "key", ")", ";", "if", "(", "Q", ".", "isPromise", "(", "value", ")", ")", "return", "value", ".", "then", "(", "function", "(", "v", ")", "{", "newArray", ".", "push", "(", "v", ")", ";", "}", ")", ";", "newArray", ".", "push", "(", "value", ")", ";", "}" ]
Allow iterator return to be a promise
[ "Allow", "iterator", "return", "to", "be", "a", "promise" ]
d3406f662a00172be39eebe0907db06e41db8307
https://github.com/maxprogram/q-plus/blob/d3406f662a00172be39eebe0907db06e41db8307/index.js#L173-L179
53,244
maxprogram/q-plus
index.js
times
function times(n, fn) { var counter = []; return this.then(function(last) { for (var i = 0; i < n; i++) { counter.push(last || i); } return Q(counter).map(fn); }); }
javascript
function times(n, fn) { var counter = []; return this.then(function(last) { for (var i = 0; i < n; i++) { counter.push(last || i); } return Q(counter).map(fn); }); }
[ "function", "times", "(", "n", ",", "fn", ")", "{", "var", "counter", "=", "[", "]", ";", "return", "this", ".", "then", "(", "function", "(", "last", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "counter", ".", "push", "(", "last", "||", "i", ")", ";", "}", "return", "Q", "(", "counter", ")", ".", "map", "(", "fn", ")", ";", "}", ")", ";", "}" ]
Calls the callback function n times, and accumulates results in the same manner you would use with map. @promise {*} last @param {number} n : How many times to iterate @param {function} fn : The function called per iteration @param value : Last return value @returns {array} New array
[ "Calls", "the", "callback", "function", "n", "times", "and", "accumulates", "results", "in", "the", "same", "manner", "you", "would", "use", "with", "map", "." ]
d3406f662a00172be39eebe0907db06e41db8307
https://github.com/maxprogram/q-plus/blob/d3406f662a00172be39eebe0907db06e41db8307/index.js#L240-L248
53,245
origin1tech/chek
dist/modules/object.js
assign
function assign(obj) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } if (Object.assign) return Object.assign.apply(Object, [obj].concat(args)); return objAssign.apply(void 0, [obj].concat(args)); }
javascript
function assign(obj) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } if (Object.assign) return Object.assign.apply(Object, [obj].concat(args)); return objAssign.apply(void 0, [obj].concat(args)); }
[ "function", "assign", "(", "obj", ")", "{", "var", "args", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "1", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "args", "[", "_i", "-", "1", "]", "=", "arguments", "[", "_i", "]", ";", "}", "if", "(", "Object", ".", "assign", ")", "return", "Object", ".", "assign", ".", "apply", "(", "Object", ",", "[", "obj", "]", ".", "concat", "(", "args", ")", ")", ";", "return", "objAssign", ".", "apply", "(", "void", "0", ",", "[", "obj", "]", ".", "concat", "(", "args", ")", ")", ";", "}" ]
Uses Object.assign if available or falls back to polyfill. @param obj object to assign. @param args additional source object.
[ "Uses", "Object", ".", "assign", "if", "available", "or", "falls", "back", "to", "polyfill", "." ]
6bc3ab0ac36126cc7918a244a606009749897b2e
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/object.js#L127-L135
53,246
origin1tech/chek
dist/modules/object.js
del
function del(obj, key, immutable) { if (immutable) return _del(assign({}, obj), key); return _del(obj, key); }
javascript
function del(obj, key, immutable) { if (immutable) return _del(assign({}, obj), key); return _del(obj, key); }
[ "function", "del", "(", "obj", ",", "key", ",", "immutable", ")", "{", "if", "(", "immutable", ")", "return", "_del", "(", "assign", "(", "{", "}", ",", "obj", ")", ",", "key", ")", ";", "return", "_del", "(", "obj", ",", "key", ")", ";", "}" ]
Del Removes a property within the supplied object. @param obj the object to inspect. @param key the dot notated key or array of keys. @param immutable when true original object NOT mutated.
[ "Del", "Removes", "a", "property", "within", "the", "supplied", "object", "." ]
6bc3ab0ac36126cc7918a244a606009749897b2e
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/object.js#L145-L149
53,247
origin1tech/chek
dist/modules/object.js
get
function get(obj, key, def) { var result = _get(assign({}, obj), key); if (!is_1.isValue(result) && def) { _set(obj, key, def); result = def; } return result; }
javascript
function get(obj, key, def) { var result = _get(assign({}, obj), key); if (!is_1.isValue(result) && def) { _set(obj, key, def); result = def; } return result; }
[ "function", "get", "(", "obj", ",", "key", ",", "def", ")", "{", "var", "result", "=", "_get", "(", "assign", "(", "{", "}", ",", "obj", ")", ",", "key", ")", ";", "if", "(", "!", "is_1", ".", "isValue", "(", "result", ")", "&&", "def", ")", "{", "_set", "(", "obj", ",", "key", ",", "def", ")", ";", "result", "=", "def", ";", "}", "return", "result", ";", "}" ]
Get Gets a property within the supplied object. @param obj the object to inspect. @param key the dot notated key or array of keys. @param def a default value to set if not exists.
[ "Get", "Gets", "a", "property", "within", "the", "supplied", "object", "." ]
6bc3ab0ac36126cc7918a244a606009749897b2e
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/object.js#L159-L166
53,248
origin1tech/chek
dist/modules/object.js
has
function has(obj, key) { if (!is_1.isObject(obj) || (!is_1.isArray(key) && !is_1.isString(key))) return false; obj = assign({}, obj); var props = is_1.isArray(key) ? key : string_1.split(key); while (props.length && obj) { var prop = props.shift(), match = matchIndex(prop); if (!props.length) { // no more props chek path. var _keys = array_1.keys(obj); if (match) { return array_1.contains(_keys, match.name) && is_1.isValue(obj[match.name][match.index]); } else { return array_1.contains(_keys, prop); } } if (match) { /* istanbul ignore next */ if (!is_1.isUndefined(obj[match.name])) { obj = obj[match.name][match.index]; // iterate each indices and set obj to that index. match.indices.forEach(function (i) { return obj = obj[i]; }); } } else { obj = obj[prop]; } } }
javascript
function has(obj, key) { if (!is_1.isObject(obj) || (!is_1.isArray(key) && !is_1.isString(key))) return false; obj = assign({}, obj); var props = is_1.isArray(key) ? key : string_1.split(key); while (props.length && obj) { var prop = props.shift(), match = matchIndex(prop); if (!props.length) { // no more props chek path. var _keys = array_1.keys(obj); if (match) { return array_1.contains(_keys, match.name) && is_1.isValue(obj[match.name][match.index]); } else { return array_1.contains(_keys, prop); } } if (match) { /* istanbul ignore next */ if (!is_1.isUndefined(obj[match.name])) { obj = obj[match.name][match.index]; // iterate each indices and set obj to that index. match.indices.forEach(function (i) { return obj = obj[i]; }); } } else { obj = obj[prop]; } } }
[ "function", "has", "(", "obj", ",", "key", ")", "{", "if", "(", "!", "is_1", ".", "isObject", "(", "obj", ")", "||", "(", "!", "is_1", ".", "isArray", "(", "key", ")", "&&", "!", "is_1", ".", "isString", "(", "key", ")", ")", ")", "return", "false", ";", "obj", "=", "assign", "(", "{", "}", ",", "obj", ")", ";", "var", "props", "=", "is_1", ".", "isArray", "(", "key", ")", "?", "key", ":", "string_1", ".", "split", "(", "key", ")", ";", "while", "(", "props", ".", "length", "&&", "obj", ")", "{", "var", "prop", "=", "props", ".", "shift", "(", ")", ",", "match", "=", "matchIndex", "(", "prop", ")", ";", "if", "(", "!", "props", ".", "length", ")", "{", "// no more props chek path.", "var", "_keys", "=", "array_1", ".", "keys", "(", "obj", ")", ";", "if", "(", "match", ")", "{", "return", "array_1", ".", "contains", "(", "_keys", ",", "match", ".", "name", ")", "&&", "is_1", ".", "isValue", "(", "obj", "[", "match", ".", "name", "]", "[", "match", ".", "index", "]", ")", ";", "}", "else", "{", "return", "array_1", ".", "contains", "(", "_keys", ",", "prop", ")", ";", "}", "}", "if", "(", "match", ")", "{", "/* istanbul ignore next */", "if", "(", "!", "is_1", ".", "isUndefined", "(", "obj", "[", "match", ".", "name", "]", ")", ")", "{", "obj", "=", "obj", "[", "match", ".", "name", "]", "[", "match", ".", "index", "]", ";", "// iterate each indices and set obj to that index.", "match", ".", "indices", ".", "forEach", "(", "function", "(", "i", ")", "{", "return", "obj", "=", "obj", "[", "i", "]", ";", "}", ")", ";", "}", "}", "else", "{", "obj", "=", "obj", "[", "prop", "]", ";", "}", "}", "}" ]
Has Checks if property exists in object. @param obj the object to be inpsected. @param key the key to be found.
[ "Has", "Checks", "if", "property", "exists", "in", "object", "." ]
6bc3ab0ac36126cc7918a244a606009749897b2e
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/object.js#L175-L203
53,249
origin1tech/chek
dist/modules/object.js
clone
function clone(obj, json) { if (json) return JSON.parse(JSON.stringify(obj)); return _clone(obj); }
javascript
function clone(obj, json) { if (json) return JSON.parse(JSON.stringify(obj)); return _clone(obj); }
[ "function", "clone", "(", "obj", ",", "json", ")", "{", "if", "(", "json", ")", "return", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "obj", ")", ")", ";", "return", "_clone", "(", "obj", ")", ";", "}" ]
Clone Performs deep cloning of objects. @param obj object to be cloned. @param json performs quick shallow clone using JSON.
[ "Clone", "Performs", "deep", "cloning", "of", "objects", "." ]
6bc3ab0ac36126cc7918a244a606009749897b2e
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/object.js#L212-L216
53,250
origin1tech/chek
dist/modules/object.js
put
function put(obj, key, val, immutable) { if (immutable) return _put(assign({}, obj), key, val); return _put(obj, key, val); }
javascript
function put(obj, key, val, immutable) { if (immutable) return _put(assign({}, obj), key, val); return _put(obj, key, val); }
[ "function", "put", "(", "obj", ",", "key", ",", "val", ",", "immutable", ")", "{", "if", "(", "immutable", ")", "return", "_put", "(", "assign", "(", "{", "}", ",", "obj", ")", ",", "key", ",", "val", ")", ";", "return", "_put", "(", "obj", ",", "key", ",", "val", ")", ";", "}" ]
Put a value to key. If the value is not currently an array it converts. @param obj the object to push value to. @param key the key or array of keys to be joined as dot notation. @param val the value to be pushed. @param immutable when true update in immutable mode.
[ "Put", "a", "value", "to", "key", ".", "If", "the", "value", "is", "not", "currently", "an", "array", "it", "converts", "." ]
6bc3ab0ac36126cc7918a244a606009749897b2e
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/object.js#L285-L289
53,251
origin1tech/chek
dist/modules/object.js
reverse
function reverse(obj) { if (!is_1.isValue(obj)) return null; // Reverse an array. if (is_1.isArray(obj)) return obj.reverse(); // Reverse a string. if (is_1.isString(obj)) { var i = obj.toString().length; var tmpStr = ''; while (i--) tmpStr += obj[i]; return tmpStr; } // Reverse an object. var result = {}; for (var p in obj) { if (is_1.isObject(obj[p])) continue; result[obj[p]] = p; } return result; }
javascript
function reverse(obj) { if (!is_1.isValue(obj)) return null; // Reverse an array. if (is_1.isArray(obj)) return obj.reverse(); // Reverse a string. if (is_1.isString(obj)) { var i = obj.toString().length; var tmpStr = ''; while (i--) tmpStr += obj[i]; return tmpStr; } // Reverse an object. var result = {}; for (var p in obj) { if (is_1.isObject(obj[p])) continue; result[obj[p]] = p; } return result; }
[ "function", "reverse", "(", "obj", ")", "{", "if", "(", "!", "is_1", ".", "isValue", "(", "obj", ")", ")", "return", "null", ";", "// Reverse an array.", "if", "(", "is_1", ".", "isArray", "(", "obj", ")", ")", "return", "obj", ".", "reverse", "(", ")", ";", "// Reverse a string.", "if", "(", "is_1", ".", "isString", "(", "obj", ")", ")", "{", "var", "i", "=", "obj", ".", "toString", "(", ")", ".", "length", ";", "var", "tmpStr", "=", "''", ";", "while", "(", "i", "--", ")", "tmpStr", "+=", "obj", "[", "i", "]", ";", "return", "tmpStr", ";", "}", "// Reverse an object.", "var", "result", "=", "{", "}", ";", "for", "(", "var", "p", "in", "obj", ")", "{", "if", "(", "is_1", ".", "isObject", "(", "obj", "[", "p", "]", ")", ")", "continue", ";", "result", "[", "obj", "[", "p", "]", "]", "=", "p", ";", "}", "return", "result", ";", "}" ]
Reverse Reverses arrays, strings or objects. Only numbers, strings or booleans are supported when reverse mapping objects. @param obj the object to reverse.
[ "Reverse", "Reverses", "arrays", "strings", "or", "objects", ".", "Only", "numbers", "strings", "or", "booleans", "are", "supported", "when", "reverse", "mapping", "objects", "." ]
6bc3ab0ac36126cc7918a244a606009749897b2e
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/object.js#L299-L321
53,252
origin1tech/chek
dist/modules/object.js
set
function set(obj, key, val, immutable) { if (immutable) return _set(assign({}, obj), key, val); return _set(obj, key, val); }
javascript
function set(obj, key, val, immutable) { if (immutable) return _set(assign({}, obj), key, val); return _set(obj, key, val); }
[ "function", "set", "(", "obj", ",", "key", ",", "val", ",", "immutable", ")", "{", "if", "(", "immutable", ")", "return", "_set", "(", "assign", "(", "{", "}", ",", "obj", ")", ",", "key", ",", "val", ")", ";", "return", "_set", "(", "obj", ",", "key", ",", "val", ")", ";", "}" ]
Set Sets a value on an object using dot notation or url path. @todo need to refactor this method. @param obj the object to set the value on. @param key the property used for setting the value. @param value the value used for updating the property. @param immutable when true the original object is NOT mutated.
[ "Set", "Sets", "a", "value", "on", "an", "object", "using", "dot", "notation", "or", "url", "path", "." ]
6bc3ab0ac36126cc7918a244a606009749897b2e
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/object.js#L335-L339
53,253
origin1tech/chek
dist/modules/object.js
pick
function pick(obj, props) { props = to_1.toArray(props, []); if (!is_1.isValue(obj) || !is_1.isObject(obj) || !props || !props.length) return obj; return props.reduce(function (a, c) { var val = get(obj, c, undefined); if (is_1.isUndefined(val)) return a; return set(a, c, val); }, {}); }
javascript
function pick(obj, props) { props = to_1.toArray(props, []); if (!is_1.isValue(obj) || !is_1.isObject(obj) || !props || !props.length) return obj; return props.reduce(function (a, c) { var val = get(obj, c, undefined); if (is_1.isUndefined(val)) return a; return set(a, c, val); }, {}); }
[ "function", "pick", "(", "obj", ",", "props", ")", "{", "props", "=", "to_1", ".", "toArray", "(", "props", ",", "[", "]", ")", ";", "if", "(", "!", "is_1", ".", "isValue", "(", "obj", ")", "||", "!", "is_1", ".", "isObject", "(", "obj", ")", "||", "!", "props", "||", "!", "props", ".", "length", ")", "return", "obj", ";", "return", "props", ".", "reduce", "(", "function", "(", "a", ",", "c", ")", "{", "var", "val", "=", "get", "(", "obj", ",", "c", ",", "undefined", ")", ";", "if", "(", "is_1", ".", "isUndefined", "(", "val", ")", ")", "return", "a", ";", "return", "set", "(", "a", ",", "c", ",", "val", ")", ";", "}", ",", "{", "}", ")", ";", "}" ]
Picks values from object by property name. @param obj the object to pick from. @param props the properties to be picked.
[ "Picks", "values", "from", "object", "by", "property", "name", "." ]
6bc3ab0ac36126cc7918a244a606009749897b2e
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/object.js#L382-L392
53,254
bootprint/customize-watch
index.js
wrap
function wrap (fnName) { /* dynamic arguments */ return function () { var args = arguments return new Recustomize(function () { var customize = builder() return customize[fnName].apply(customize, args) }) } }
javascript
function wrap (fnName) { /* dynamic arguments */ return function () { var args = arguments return new Recustomize(function () { var customize = builder() return customize[fnName].apply(customize, args) }) } }
[ "function", "wrap", "(", "fnName", ")", "{", "/* dynamic arguments */", "return", "function", "(", ")", "{", "var", "args", "=", "arguments", "return", "new", "Recustomize", "(", "function", "(", ")", "{", "var", "customize", "=", "builder", "(", ")", "return", "customize", "[", "fnName", "]", ".", "apply", "(", "customize", ",", "args", ")", "}", ")", "}", "}" ]
Wrap the method of a Customize object such that instead of the new Customize object, new Recustomize object with the appropriate builder-function is returned @param fnName @returns {Function} @api private
[ "Wrap", "the", "method", "of", "a", "Customize", "object", "such", "that", "instead", "of", "the", "new", "Customize", "object", "new", "Recustomize", "object", "with", "the", "appropriate", "builder", "-", "function", "is", "returned" ]
61135b5f4d956d5a231551cc565d56da08ca7e3d
https://github.com/bootprint/customize-watch/blob/61135b5f4d956d5a231551cc565d56da08ca7e3d/index.js#L45-L54
53,255
MakerCollider/upm_mc
doxy/node/tolower.js
getHtmlFilenames
function getHtmlFilenames (directory) { return fs.readdirSync(directory).map(function (file) { return path.join(directory, file); }).filter(function (file) { return fs.statSync(file).isFile(); }).filter(function (file) { return path.extname(file).toLowerCase() == ".html"; }); }
javascript
function getHtmlFilenames (directory) { return fs.readdirSync(directory).map(function (file) { return path.join(directory, file); }).filter(function (file) { return fs.statSync(file).isFile(); }).filter(function (file) { return path.extname(file).toLowerCase() == ".html"; }); }
[ "function", "getHtmlFilenames", "(", "directory", ")", "{", "return", "fs", ".", "readdirSync", "(", "directory", ")", ".", "map", "(", "function", "(", "file", ")", "{", "return", "path", ".", "join", "(", "directory", ",", "file", ")", ";", "}", ")", ".", "filter", "(", "function", "(", "file", ")", "{", "return", "fs", ".", "statSync", "(", "file", ")", ".", "isFile", "(", ")", ";", "}", ")", ".", "filter", "(", "function", "(", "file", ")", "{", "return", "path", ".", "extname", "(", "file", ")", ".", "toLowerCase", "(", ")", "==", "\".html\"", ";", "}", ")", ";", "}" ]
Helper function that returns paths to the html files in the specified directory
[ "Helper", "function", "that", "returns", "paths", "to", "the", "html", "files", "in", "the", "specified", "directory" ]
525e775a17b85c30716c00435a2acb26bb198c12
https://github.com/MakerCollider/upm_mc/blob/525e775a17b85c30716c00435a2acb26bb198c12/doxy/node/tolower.js#L58-L67
53,256
nodejitsu/packages-pagelet
example/filecache.js
Filecache
function Filecache(options) { options = options || {}; this.directory = options.directory || path.join(__dirname, '/.cache'); this.fresh = +options.fresh || 500000; }
javascript
function Filecache(options) { options = options || {}; this.directory = options.directory || path.join(__dirname, '/.cache'); this.fresh = +options.fresh || 500000; }
[ "function", "Filecache", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "directory", "=", "options", ".", "directory", "||", "path", ".", "join", "(", "__dirname", ",", "'/.cache'", ")", ";", "this", ".", "fresh", "=", "+", "options", ".", "fresh", "||", "500000", ";", "}" ]
Really minimal implementation of a data cache sytem. This should not be used in production it merely serves as an example of caching the data to speedup the rendering of the pages. @constructor @param {Object} options Configuration. @api public
[ "Really", "minimal", "implementation", "of", "a", "data", "cache", "sytem", ".", "This", "should", "not", "be", "used", "in", "production", "it", "merely", "serves", "as", "an", "example", "of", "caching", "the", "data", "to", "speedup", "the", "rendering", "of", "the", "pages", "." ]
10c4bdb1a99a808b58e41d87c8e7ec8c9947a3d8
https://github.com/nodejitsu/packages-pagelet/blob/10c4bdb1a99a808b58e41d87c8e7ec8c9947a3d8/example/filecache.js#L15-L20
53,257
artdecocode/makepromise
build/index.js
makePromise
async function makePromise(fn, args, resolveValue) { const er = erotic(true) if (typeof fn !== 'function') { throw new Error('Function must be passed.') } const { length: fnLength } = fn if (!fnLength) { throw new Error('Function does not accept any arguments.') } const res = await new Promise((resolve, reject)=> { const cb = (err, res) => { if (err) { const error = er(err) return reject(error) } return resolve(resolveValue || res) } let allArgs = [cb] if (Array.isArray(args)) { args.forEach((arg, i) => { checkArgumentIndex(fnLength, i) }) allArgs = [...args, cb] } else if (Array.from(arguments).length > 1) { // args passed as a single argument, not array checkArgumentIndex(fnLength, 0) allArgs = [args, cb] } fn(...allArgs) }) return res }
javascript
async function makePromise(fn, args, resolveValue) { const er = erotic(true) if (typeof fn !== 'function') { throw new Error('Function must be passed.') } const { length: fnLength } = fn if (!fnLength) { throw new Error('Function does not accept any arguments.') } const res = await new Promise((resolve, reject)=> { const cb = (err, res) => { if (err) { const error = er(err) return reject(error) } return resolve(resolveValue || res) } let allArgs = [cb] if (Array.isArray(args)) { args.forEach((arg, i) => { checkArgumentIndex(fnLength, i) }) allArgs = [...args, cb] } else if (Array.from(arguments).length > 1) { // args passed as a single argument, not array checkArgumentIndex(fnLength, 0) allArgs = [args, cb] } fn(...allArgs) }) return res }
[ "async", "function", "makePromise", "(", "fn", ",", "args", ",", "resolveValue", ")", "{", "const", "er", "=", "erotic", "(", "true", ")", "if", "(", "typeof", "fn", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Function must be passed.'", ")", "}", "const", "{", "length", ":", "fnLength", "}", "=", "fn", "if", "(", "!", "fnLength", ")", "{", "throw", "new", "Error", "(", "'Function does not accept any arguments.'", ")", "}", "const", "res", "=", "await", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "cb", "=", "(", "err", ",", "res", ")", "=>", "{", "if", "(", "err", ")", "{", "const", "error", "=", "er", "(", "err", ")", "return", "reject", "(", "error", ")", "}", "return", "resolve", "(", "resolveValue", "||", "res", ")", "}", "let", "allArgs", "=", "[", "cb", "]", "if", "(", "Array", ".", "isArray", "(", "args", ")", ")", "{", "args", ".", "forEach", "(", "(", "arg", ",", "i", ")", "=>", "{", "checkArgumentIndex", "(", "fnLength", ",", "i", ")", "}", ")", "allArgs", "=", "[", "...", "args", ",", "cb", "]", "}", "else", "if", "(", "Array", ".", "from", "(", "arguments", ")", ".", "length", ">", "1", ")", "{", "// args passed as a single argument, not array", "checkArgumentIndex", "(", "fnLength", ",", "0", ")", "allArgs", "=", "[", "args", ",", "cb", "]", "}", "fn", "(", "...", "allArgs", ")", "}", ")", "return", "res", "}" ]
Get a promise from a function which otherwise accepts a callback. @param {Function} fn A function to promisify. @param {*|Array<*>} [args] An array of arguments to use in the call, or a single argument. @param {*} [resolveValue] A value to override the value with which the promise will be resolved. @returns {Promise<*>} A promise resolved on callback invocation without an error and rejected on callback called with an error.
[ "Get", "a", "promise", "from", "a", "function", "which", "otherwise", "accepts", "a", "callback", "." ]
2cea573b4c5379f05404632efef08a4235fb22a0
https://github.com/artdecocode/makepromise/blob/2cea573b4c5379f05404632efef08a4235fb22a0/build/index.js#L16-L49
53,258
on-point/thin-orm
drivers/pg.js
function(table, result) { if (result && result.rows && result.rows.length > 0) return result.rows[0][table.id]; return -1; }
javascript
function(table, result) { if (result && result.rows && result.rows.length > 0) return result.rows[0][table.id]; return -1; }
[ "function", "(", "table", ",", "result", ")", "{", "if", "(", "result", "&&", "result", ".", "rows", "&&", "result", ".", "rows", ".", "length", ">", "0", ")", "return", "result", ".", "rows", "[", "0", "]", "[", "table", ".", "id", "]", ";", "return", "-", "1", ";", "}" ]
gets the id of a new row from the result of an INSERT query
[ "gets", "the", "id", "of", "a", "new", "row", "from", "the", "result", "of", "an", "INSERT", "query" ]
761783a133ef6983f46060af68febc07e1f880e8
https://github.com/on-point/thin-orm/blob/761783a133ef6983f46060af68febc07e1f880e8/drivers/pg.js#L27-L31
53,259
averta-lab/touch-swipe
lib/touchSwipe.es.js
unbindEvents
function unbindEvents(target, events, listener) { events.split(' ').forEach(function (event) { return target.removeEventListener(event, listener, false); }); }
javascript
function unbindEvents(target, events, listener) { events.split(' ').forEach(function (event) { return target.removeEventListener(event, listener, false); }); }
[ "function", "unbindEvents", "(", "target", ",", "events", ",", "listener", ")", "{", "events", ".", "split", "(", "' '", ")", ".", "forEach", "(", "function", "(", "event", ")", "{", "return", "target", ".", "removeEventListener", "(", "event", ",", "listener", ",", "false", ")", ";", "}", ")", ";", "}" ]
Unbind multiple events on one element @param {Element} target Target element @param {String} events List of events separated by space @param {Function} listener Event listener
[ "Unbind", "multiple", "events", "on", "one", "element" ]
ffd3da21f8a0590a7a47603b32b1003fcfd330f8
https://github.com/averta-lab/touch-swipe/blob/ffd3da21f8a0590a7a47603b32b1003fcfd330f8/lib/touchSwipe.es.js#L55-L59
53,260
ibm-bluemix-mobile-services/bms-monitoring-sdk-node
bluemix.js
refreshProxyAccessToken
function refreshProxyAccessToken() { settings.AZTokenProvider().then(function(token) { proxyAccessToken = token; logger.log('Refreshed proxy access token: ' + proxyAccessToken); }, function(err) { logger.log(err); emitter.emit('error', 'Unable to refresh access token from AZTokenProvider'); return null; }); }
javascript
function refreshProxyAccessToken() { settings.AZTokenProvider().then(function(token) { proxyAccessToken = token; logger.log('Refreshed proxy access token: ' + proxyAccessToken); }, function(err) { logger.log(err); emitter.emit('error', 'Unable to refresh access token from AZTokenProvider'); return null; }); }
[ "function", "refreshProxyAccessToken", "(", ")", "{", "settings", ".", "AZTokenProvider", "(", ")", ".", "then", "(", "function", "(", "token", ")", "{", "proxyAccessToken", "=", "token", ";", "logger", ".", "log", "(", "'Refreshed proxy access token: '", "+", "proxyAccessToken", ")", ";", "}", ",", "function", "(", "err", ")", "{", "logger", ".", "log", "(", "err", ")", ";", "emitter", ".", "emit", "(", "'error'", ",", "'Unable to refresh access token from AZTokenProvider'", ")", ";", "return", "null", ";", "}", ")", ";", "}" ]
After invoking this function, one must invoke elasticsearchOptions again in order for new access token to be used.
[ "After", "invoking", "this", "function", "one", "must", "invoke", "elasticsearchOptions", "again", "in", "order", "for", "new", "access", "token", "to", "be", "used", "." ]
5b26fbd3b8adacb3fa9f4a0cbd60c8eae1a44df9
https://github.com/ibm-bluemix-mobile-services/bms-monitoring-sdk-node/blob/5b26fbd3b8adacb3fa9f4a0cbd60c8eae1a44df9/bluemix.js#L239-L248
53,261
dalekjs/dalek-driver-sauce
lib/commands/screenshot.js
function (path, pathname, hash, uuid) { this.actionQueue.push(this.webdriverClient.screenshot.bind(this.webdriverClient)); this.actionQueue.push(this._screenshotCb.bind(this, path, pathname, hash, uuid)); return this; }
javascript
function (path, pathname, hash, uuid) { this.actionQueue.push(this.webdriverClient.screenshot.bind(this.webdriverClient)); this.actionQueue.push(this._screenshotCb.bind(this, path, pathname, hash, uuid)); return this; }
[ "function", "(", "path", ",", "pathname", ",", "hash", ",", "uuid", ")", "{", "this", ".", "actionQueue", ".", "push", "(", "this", ".", "webdriverClient", ".", "screenshot", ".", "bind", "(", "this", ".", "webdriverClient", ")", ")", ";", "this", ".", "actionQueue", ".", "push", "(", "this", ".", "_screenshotCb", ".", "bind", "(", "this", ",", "path", ",", "pathname", ",", "hash", ",", "uuid", ")", ")", ";", "return", "this", ";", "}" ]
Makes an screenshot of the current page @method screenshot @param {string} path Root directory path @param {string} pathname Pathname of the screenshot path @param {string} hash Unique hash of that fn call @param {string} uuid Unique hash of that fn call @chainable
[ "Makes", "an", "screenshot", "of", "the", "current", "page" ]
4b3ef87a0c35a91db8456d074b0d47a3e0df58f7
https://github.com/dalekjs/dalek-driver-sauce/blob/4b3ef87a0c35a91db8456d074b0d47a3e0df58f7/lib/commands/screenshot.js#L52-L56
53,262
dalekjs/dalek-driver-sauce
lib/commands/screenshot.js
function (path, pathname, hash, uuid, result) { var deferred = Q.defer(); // replace base64 metadata var base64Data = JSON.parse(result).value.replace(/^data:image\/png;base64,/,''); // replace placeholders var realpath = this._replacePathPlaceholder(path + pathname); // check if we need to add a new directory this._recursiveMakeDirSync(realpath.substring(0, realpath.lastIndexOf('/'))); // write the screenshot fs.writeFileSync(realpath, base64Data, 'base64'); this.events.emit('driver:message', {key: 'screenshot', value: realpath, uuid: hash, hash: hash}); deferred.resolve(); return deferred.promise; }
javascript
function (path, pathname, hash, uuid, result) { var deferred = Q.defer(); // replace base64 metadata var base64Data = JSON.parse(result).value.replace(/^data:image\/png;base64,/,''); // replace placeholders var realpath = this._replacePathPlaceholder(path + pathname); // check if we need to add a new directory this._recursiveMakeDirSync(realpath.substring(0, realpath.lastIndexOf('/'))); // write the screenshot fs.writeFileSync(realpath, base64Data, 'base64'); this.events.emit('driver:message', {key: 'screenshot', value: realpath, uuid: hash, hash: hash}); deferred.resolve(); return deferred.promise; }
[ "function", "(", "path", ",", "pathname", ",", "hash", ",", "uuid", ",", "result", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "// replace base64 metadata", "var", "base64Data", "=", "JSON", ".", "parse", "(", "result", ")", ".", "value", ".", "replace", "(", "/", "^data:image\\/png;base64,", "/", ",", "''", ")", ";", "// replace placeholders", "var", "realpath", "=", "this", ".", "_replacePathPlaceholder", "(", "path", "+", "pathname", ")", ";", "// check if we need to add a new directory", "this", ".", "_recursiveMakeDirSync", "(", "realpath", ".", "substring", "(", "0", ",", "realpath", ".", "lastIndexOf", "(", "'/'", ")", ")", ")", ";", "// write the screenshot", "fs", ".", "writeFileSync", "(", "realpath", ",", "base64Data", ",", "'base64'", ")", ";", "this", ".", "events", ".", "emit", "(", "'driver:message'", ",", "{", "key", ":", "'screenshot'", ",", "value", ":", "realpath", ",", "uuid", ":", "hash", ",", "hash", ":", "hash", "}", ")", ";", "deferred", ".", "resolve", "(", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Sends out an event with the results of the `screenshot` call and stores the screenshot in the filesystem @method _screenshotCb @param {string} path Root directory path @param {string} pathname Pathname of the screenshot path @param {string} hash Unique hash of that fn call @param {string} uuid Unique hash of that fn call @param {string} result Serialized JSON result of the screenshot call @return {object} promise Screenshot promise @private
[ "Sends", "out", "an", "event", "with", "the", "results", "of", "the", "screenshot", "call", "and", "stores", "the", "screenshot", "in", "the", "filesystem" ]
4b3ef87a0c35a91db8456d074b0d47a3e0df58f7
https://github.com/dalekjs/dalek-driver-sauce/blob/4b3ef87a0c35a91db8456d074b0d47a3e0df58f7/lib/commands/screenshot.js#L72-L85
53,263
dalekjs/dalek-driver-sauce
lib/commands/screenshot.js
function (pathname) { pathname = pathname.replace(':browser', this.browserName); pathname = pathname.replace(':version', this._parseBrowserVersion(this.sessionStatus.version)); pathname = pathname.replace(':timestamp', Math.round(new Date().getTime() / 1000)); pathname = pathname.replace(':osVersion', this._parseOSVersion(this.driverStatus.os.version)); pathname = pathname.replace(':os', this._parseOS(this.driverStatus.os.name)); pathname = pathname.replace(':datetime', this._parseDatetime()); pathname = pathname.replace(':date', this._parseDate()); pathname = pathname.replace(':viewport', this._parseViewport()); return pathname; }
javascript
function (pathname) { pathname = pathname.replace(':browser', this.browserName); pathname = pathname.replace(':version', this._parseBrowserVersion(this.sessionStatus.version)); pathname = pathname.replace(':timestamp', Math.round(new Date().getTime() / 1000)); pathname = pathname.replace(':osVersion', this._parseOSVersion(this.driverStatus.os.version)); pathname = pathname.replace(':os', this._parseOS(this.driverStatus.os.name)); pathname = pathname.replace(':datetime', this._parseDatetime()); pathname = pathname.replace(':date', this._parseDate()); pathname = pathname.replace(':viewport', this._parseViewport()); return pathname; }
[ "function", "(", "pathname", ")", "{", "pathname", "=", "pathname", ".", "replace", "(", "':browser'", ",", "this", ".", "browserName", ")", ";", "pathname", "=", "pathname", ".", "replace", "(", "':version'", ",", "this", ".", "_parseBrowserVersion", "(", "this", ".", "sessionStatus", ".", "version", ")", ")", ";", "pathname", "=", "pathname", ".", "replace", "(", "':timestamp'", ",", "Math", ".", "round", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", "/", "1000", ")", ")", ";", "pathname", "=", "pathname", ".", "replace", "(", "':osVersion'", ",", "this", ".", "_parseOSVersion", "(", "this", ".", "driverStatus", ".", "os", ".", "version", ")", ")", ";", "pathname", "=", "pathname", ".", "replace", "(", "':os'", ",", "this", ".", "_parseOS", "(", "this", ".", "driverStatus", ".", "os", ".", "name", ")", ")", ";", "pathname", "=", "pathname", ".", "replace", "(", "':datetime'", ",", "this", ".", "_parseDatetime", "(", ")", ")", ";", "pathname", "=", "pathname", ".", "replace", "(", "':date'", ",", "this", ".", "_parseDate", "(", ")", ")", ";", "pathname", "=", "pathname", ".", "replace", "(", "':viewport'", ",", "this", ".", "_parseViewport", "(", ")", ")", ";", "return", "pathname", ";", "}" ]
Return the formatted os name @method _parseOS @param {string} Pathname @return {string} Formatted pathname @private
[ "Return", "the", "formatted", "os", "name" ]
4b3ef87a0c35a91db8456d074b0d47a3e0df58f7
https://github.com/dalekjs/dalek-driver-sauce/blob/4b3ef87a0c35a91db8456d074b0d47a3e0df58f7/lib/commands/screenshot.js#L121-L131
53,264
dalekjs/dalek-driver-sauce
lib/commands/screenshot.js
function (version) { var vs = version.replace(/[^0-9\\.]/g, ''); vs = vs.replace(/\./g, '_'); return vs; }
javascript
function (version) { var vs = version.replace(/[^0-9\\.]/g, ''); vs = vs.replace(/\./g, '_'); return vs; }
[ "function", "(", "version", ")", "{", "var", "vs", "=", "version", ".", "replace", "(", "/", "[^0-9\\\\.]", "/", "g", ",", "''", ")", ";", "vs", "=", "vs", ".", "replace", "(", "/", "\\.", "/", "g", ",", "'_'", ")", ";", "return", "vs", ";", "}" ]
Return the formatted os version @method _parseOSVersion @return {string} OS version @private
[ "Return", "the", "formatted", "os", "version" ]
4b3ef87a0c35a91db8456d074b0d47a3e0df58f7
https://github.com/dalekjs/dalek-driver-sauce/blob/4b3ef87a0c35a91db8456d074b0d47a3e0df58f7/lib/commands/screenshot.js#L157-L161
53,265
dalekjs/dalek-driver-sauce
lib/commands/screenshot.js
function () { var date = new Date(); var dateStr = ''; var day = date.getDate(); var month = date.getMonth(); month = (month+'').length === 1 ? '0' + month : month; day = (day+'').length === 1 ? '0' + day : day; dateStr += month + '_'; dateStr += day + '_'; dateStr += date.getFullYear(); return dateStr; }
javascript
function () { var date = new Date(); var dateStr = ''; var day = date.getDate(); var month = date.getMonth(); month = (month+'').length === 1 ? '0' + month : month; day = (day+'').length === 1 ? '0' + day : day; dateStr += month + '_'; dateStr += day + '_'; dateStr += date.getFullYear(); return dateStr; }
[ "function", "(", ")", "{", "var", "date", "=", "new", "Date", "(", ")", ";", "var", "dateStr", "=", "''", ";", "var", "day", "=", "date", ".", "getDate", "(", ")", ";", "var", "month", "=", "date", ".", "getMonth", "(", ")", ";", "month", "=", "(", "month", "+", "''", ")", ".", "length", "===", "1", "?", "'0'", "+", "month", ":", "month", ";", "day", "=", "(", "day", "+", "''", ")", ".", "length", "===", "1", "?", "'0'", "+", "day", ":", "day", ";", "dateStr", "+=", "month", "+", "'_'", ";", "dateStr", "+=", "day", "+", "'_'", ";", "dateStr", "+=", "date", ".", "getFullYear", "(", ")", ";", "return", "dateStr", ";", "}" ]
Return the formatted date @method _parseDate @return {string} Date @private
[ "Return", "the", "formatted", "date" ]
4b3ef87a0c35a91db8456d074b0d47a3e0df58f7
https://github.com/dalekjs/dalek-driver-sauce/blob/4b3ef87a0c35a91db8456d074b0d47a3e0df58f7/lib/commands/screenshot.js#L183-L197
53,266
dalekjs/dalek-driver-sauce
lib/commands/screenshot.js
function () { var date = new Date(); var dateStr = this._parseDate(); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); hours = (hours+'').length === 1 ? '0' + hours : hours; minutes = (minutes+'').length === 1 ? '0' + minutes : minutes; seconds = (seconds+'').length === 1 ? '0' + seconds : seconds; dateStr = dateStr + '_' + hours; dateStr = dateStr + '_' + minutes; dateStr = dateStr + '_' + seconds; return dateStr; }
javascript
function () { var date = new Date(); var dateStr = this._parseDate(); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); hours = (hours+'').length === 1 ? '0' + hours : hours; minutes = (minutes+'').length === 1 ? '0' + minutes : minutes; seconds = (seconds+'').length === 1 ? '0' + seconds : seconds; dateStr = dateStr + '_' + hours; dateStr = dateStr + '_' + minutes; dateStr = dateStr + '_' + seconds; return dateStr; }
[ "function", "(", ")", "{", "var", "date", "=", "new", "Date", "(", ")", ";", "var", "dateStr", "=", "this", ".", "_parseDate", "(", ")", ";", "var", "hours", "=", "date", ".", "getHours", "(", ")", ";", "var", "minutes", "=", "date", ".", "getMinutes", "(", ")", ";", "var", "seconds", "=", "date", ".", "getSeconds", "(", ")", ";", "hours", "=", "(", "hours", "+", "''", ")", ".", "length", "===", "1", "?", "'0'", "+", "hours", ":", "hours", ";", "minutes", "=", "(", "minutes", "+", "''", ")", ".", "length", "===", "1", "?", "'0'", "+", "minutes", ":", "minutes", ";", "seconds", "=", "(", "seconds", "+", "''", ")", ".", "length", "===", "1", "?", "'0'", "+", "seconds", ":", "seconds", ";", "dateStr", "=", "dateStr", "+", "'_'", "+", "hours", ";", "dateStr", "=", "dateStr", "+", "'_'", "+", "minutes", ";", "dateStr", "=", "dateStr", "+", "'_'", "+", "seconds", ";", "return", "dateStr", ";", "}" ]
Return the formatted datetime @method _parseDatetime @return {string} Datetime @private
[ "Return", "the", "formatted", "datetime" ]
4b3ef87a0c35a91db8456d074b0d47a3e0df58f7
https://github.com/dalekjs/dalek-driver-sauce/blob/4b3ef87a0c35a91db8456d074b0d47a3e0df58f7/lib/commands/screenshot.js#L207-L223
53,267
andrewscwei/requiem
src/dom/setDataRegistry.js
setDataRegistry
function setDataRegistry(data) { assertType(data, 'object', false, 'Invalid data specified'); if (!window.__private__) window.__private__ = {}; window.__private__.dataRegistry = data; }
javascript
function setDataRegistry(data) { assertType(data, 'object', false, 'Invalid data specified'); if (!window.__private__) window.__private__ = {}; window.__private__.dataRegistry = data; }
[ "function", "setDataRegistry", "(", "data", ")", "{", "assertType", "(", "data", ",", "'object'", ",", "false", ",", "'Invalid data specified'", ")", ";", "if", "(", "!", "window", ".", "__private__", ")", "window", ".", "__private__", "=", "{", "}", ";", "window", ".", "__private__", ".", "dataRegistry", "=", "data", ";", "}" ]
Sets the data registry. @param {Object} data - Sets the data registry. @alias module:requiem~dom.setDataRegistry
[ "Sets", "the", "data", "registry", "." ]
c4182bfffc9841c6de5718f689ad3c2060511777
https://github.com/andrewscwei/requiem/blob/c4182bfffc9841c6de5718f689ad3c2060511777/src/dom/setDataRegistry.js#L14-L18
53,268
mathieudutour/nplint
lib/config-initializer.js
writeFile
function writeFile(config, isJson, callback) { try { fs.writeFile('./.nplintrc', isJson ? JSON.stringify(config, null, 4) : yaml.safeDump(config), callback); } catch (e) { return callback(e); } }
javascript
function writeFile(config, isJson, callback) { try { fs.writeFile('./.nplintrc', isJson ? JSON.stringify(config, null, 4) : yaml.safeDump(config), callback); } catch (e) { return callback(e); } }
[ "function", "writeFile", "(", "config", ",", "isJson", ",", "callback", ")", "{", "try", "{", "fs", ".", "writeFile", "(", "'./.nplintrc'", ",", "isJson", "?", "JSON", ".", "stringify", "(", "config", ",", "null", ",", "4", ")", ":", "yaml", ".", "safeDump", "(", "config", ")", ",", "callback", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "callback", "(", "e", ")", ";", "}", "}" ]
Create .nplintrc file in the current working directory @param {object} config object that contains user's answers @param {bool} isJson should config file be json or yaml @param {function} callback function to call once the file is written. @returns {void}
[ "Create", ".", "nplintrc", "file", "in", "the", "current", "working", "directory" ]
ef444abcc6dd08fb61d5fc8ce618598d4455e08e
https://github.com/mathieudutour/nplint/blob/ef444abcc6dd08fb61d5fc8ce618598d4455e08e/lib/config-initializer.js#L14-L20
53,269
af83/nodetk
browser/static/yabble.js
function(moduleIds) { for (var i = moduleIds.length; i--;) { var moduleId = moduleIds[i], module = getModule(moduleId); if (module == null) { module = _modules[moduleId] = {}; _fetchFunc(moduleId); } } }
javascript
function(moduleIds) { for (var i = moduleIds.length; i--;) { var moduleId = moduleIds[i], module = getModule(moduleId); if (module == null) { module = _modules[moduleId] = {}; _fetchFunc(moduleId); } } }
[ "function", "(", "moduleIds", ")", "{", "for", "(", "var", "i", "=", "moduleIds", ".", "length", ";", "i", "--", ";", ")", "{", "var", "moduleId", "=", "moduleIds", "[", "i", "]", ",", "module", "=", "getModule", "(", "moduleId", ")", ";", "if", "(", "module", "==", "null", ")", "{", "module", "=", "_modules", "[", "moduleId", "]", "=", "{", "}", ";", "_fetchFunc", "(", "moduleId", ")", ";", "}", "}", "}" ]
Begins loading modules asynchronously
[ "Begins", "loading", "modules", "asynchronously" ]
bd44fcc331ed0857cc05ae3a2535a01c5e540c1e
https://github.com/af83/nodetk/blob/bd44fcc331ed0857cc05ae3a2535a01c5e540c1e/browser/static/yabble.js#L231-L241
53,270
af83/nodetk
browser/static/yabble.js
function() { var i = 0; while (i<_callbacks.length) { var deps = _callbacks[i][0], func = _callbacks[i][1], n = 0; while (n<deps.length) { if (areDeepDepsDefined(deps[n])) { deps.splice(n, 1); } else { n++; } } if (!deps.length) { _callbacks.splice(i, 1); if (func != null) { setTimeout(func, 0); } } else { i++; } } }
javascript
function() { var i = 0; while (i<_callbacks.length) { var deps = _callbacks[i][0], func = _callbacks[i][1], n = 0; while (n<deps.length) { if (areDeepDepsDefined(deps[n])) { deps.splice(n, 1); } else { n++; } } if (!deps.length) { _callbacks.splice(i, 1); if (func != null) { setTimeout(func, 0); } } else { i++; } } }
[ "function", "(", ")", "{", "var", "i", "=", "0", ";", "while", "(", "i", "<", "_callbacks", ".", "length", ")", "{", "var", "deps", "=", "_callbacks", "[", "i", "]", "[", "0", "]", ",", "func", "=", "_callbacks", "[", "i", "]", "[", "1", "]", ",", "n", "=", "0", ";", "while", "(", "n", "<", "deps", ".", "length", ")", "{", "if", "(", "areDeepDepsDefined", "(", "deps", "[", "n", "]", ")", ")", "{", "deps", ".", "splice", "(", "n", ",", "1", ")", ";", "}", "else", "{", "n", "++", ";", "}", "}", "if", "(", "!", "deps", ".", "length", ")", "{", "_callbacks", ".", "splice", "(", "i", ",", "1", ")", ";", "if", "(", "func", "!=", "null", ")", "{", "setTimeout", "(", "func", ",", "0", ")", ";", "}", "}", "else", "{", "i", "++", ";", "}", "}", "}" ]
Checks dependency callbacks and fires as necessary
[ "Checks", "dependency", "callbacks", "and", "fires", "as", "necessary" ]
bd44fcc331ed0857cc05ae3a2535a01c5e540c1e
https://github.com/af83/nodetk/blob/bd44fcc331ed0857cc05ae3a2535a01c5e540c1e/browser/static/yabble.js#L266-L290
53,271
af83/nodetk
browser/static/yabble.js
function(moduleId) { var scriptEl = document.createElement('script'); scriptEl.type = 'text/javascript'; scriptEl.src = resolveModuleUri(moduleId); var useStandard = !!scriptEl.addEventListener, timeoutHandle; var errorFunc = function() { postLoadFunc(false); }; var loadFunc = function() { if (useStandard || (scriptEl.readyState == 'complete' || scriptEl.readyState == 'loaded')) { postLoadFunc(getModule(moduleId).defined); } }; var postLoadFunc = function(loaded) { clearTimeout(timeoutHandle); if (useStandard) { scriptEl.removeEventListener('load', loadFunc, false); scriptEl.removeEventListener('error', errorFunc, false); } else { scriptEl.detachEvent('onreadystatechange', loadFunc); } if (!loaded) { var module = getModule(moduleId); if (!module.defined) { module.defined = module.error = true; fireCallbacks(); } } }; if (useStandard) { scriptEl.addEventListener('load', loadFunc, false); scriptEl.addEventListener('error', errorFunc, false); } else { scriptEl.attachEvent('onreadystatechange', loadFunc); } timeoutHandle = setTimeout(errorFunc, _timeoutLength); head.appendChild(scriptEl); }
javascript
function(moduleId) { var scriptEl = document.createElement('script'); scriptEl.type = 'text/javascript'; scriptEl.src = resolveModuleUri(moduleId); var useStandard = !!scriptEl.addEventListener, timeoutHandle; var errorFunc = function() { postLoadFunc(false); }; var loadFunc = function() { if (useStandard || (scriptEl.readyState == 'complete' || scriptEl.readyState == 'loaded')) { postLoadFunc(getModule(moduleId).defined); } }; var postLoadFunc = function(loaded) { clearTimeout(timeoutHandle); if (useStandard) { scriptEl.removeEventListener('load', loadFunc, false); scriptEl.removeEventListener('error', errorFunc, false); } else { scriptEl.detachEvent('onreadystatechange', loadFunc); } if (!loaded) { var module = getModule(moduleId); if (!module.defined) { module.defined = module.error = true; fireCallbacks(); } } }; if (useStandard) { scriptEl.addEventListener('load', loadFunc, false); scriptEl.addEventListener('error', errorFunc, false); } else { scriptEl.attachEvent('onreadystatechange', loadFunc); } timeoutHandle = setTimeout(errorFunc, _timeoutLength); head.appendChild(scriptEl); }
[ "function", "(", "moduleId", ")", "{", "var", "scriptEl", "=", "document", ".", "createElement", "(", "'script'", ")", ";", "scriptEl", ".", "type", "=", "'text/javascript'", ";", "scriptEl", ".", "src", "=", "resolveModuleUri", "(", "moduleId", ")", ";", "var", "useStandard", "=", "!", "!", "scriptEl", ".", "addEventListener", ",", "timeoutHandle", ";", "var", "errorFunc", "=", "function", "(", ")", "{", "postLoadFunc", "(", "false", ")", ";", "}", ";", "var", "loadFunc", "=", "function", "(", ")", "{", "if", "(", "useStandard", "||", "(", "scriptEl", ".", "readyState", "==", "'complete'", "||", "scriptEl", ".", "readyState", "==", "'loaded'", ")", ")", "{", "postLoadFunc", "(", "getModule", "(", "moduleId", ")", ".", "defined", ")", ";", "}", "}", ";", "var", "postLoadFunc", "=", "function", "(", "loaded", ")", "{", "clearTimeout", "(", "timeoutHandle", ")", ";", "if", "(", "useStandard", ")", "{", "scriptEl", ".", "removeEventListener", "(", "'load'", ",", "loadFunc", ",", "false", ")", ";", "scriptEl", ".", "removeEventListener", "(", "'error'", ",", "errorFunc", ",", "false", ")", ";", "}", "else", "{", "scriptEl", ".", "detachEvent", "(", "'onreadystatechange'", ",", "loadFunc", ")", ";", "}", "if", "(", "!", "loaded", ")", "{", "var", "module", "=", "getModule", "(", "moduleId", ")", ";", "if", "(", "!", "module", ".", "defined", ")", "{", "module", ".", "defined", "=", "module", ".", "error", "=", "true", ";", "fireCallbacks", "(", ")", ";", "}", "}", "}", ";", "if", "(", "useStandard", ")", "{", "scriptEl", ".", "addEventListener", "(", "'load'", ",", "loadFunc", ",", "false", ")", ";", "scriptEl", ".", "addEventListener", "(", "'error'", ",", "errorFunc", ",", "false", ")", ";", "}", "else", "{", "scriptEl", ".", "attachEvent", "(", "'onreadystatechange'", ",", "loadFunc", ")", ";", "}", "timeoutHandle", "=", "setTimeout", "(", "errorFunc", ",", "_timeoutLength", ")", ";", "head", ".", "appendChild", "(", "scriptEl", ")", ";", "}" ]
Load a wrapped module via script tags
[ "Load", "a", "wrapped", "module", "via", "script", "tags" ]
bd44fcc331ed0857cc05ae3a2535a01c5e540c1e
https://github.com/af83/nodetk/blob/bd44fcc331ed0857cc05ae3a2535a01c5e540c1e/browser/static/yabble.js#L365-L414
53,272
bholloway/browserify-anonymous-labeler
lib/adjust-source-map.js
copyAndOffsetMapping
function copyAndOffsetMapping(existingMapping) { var column = getColumnAfter(existingMapping.generatedLine - 1, existingMapping.generatedColumn); var newMapping = { generated: { line : existingMapping.generatedLine, column: column } }; if (existingMapping.source) { newMapping.source = existingMapping.source; newMapping.original = { line : existingMapping.originalLine, column: existingMapping.originalColumn }; if (existingMapping.name) { newMapping.name = existingMapping.name; } } generator.addMapping(newMapping); }
javascript
function copyAndOffsetMapping(existingMapping) { var column = getColumnAfter(existingMapping.generatedLine - 1, existingMapping.generatedColumn); var newMapping = { generated: { line : existingMapping.generatedLine, column: column } }; if (existingMapping.source) { newMapping.source = existingMapping.source; newMapping.original = { line : existingMapping.originalLine, column: existingMapping.originalColumn }; if (existingMapping.name) { newMapping.name = existingMapping.name; } } generator.addMapping(newMapping); }
[ "function", "copyAndOffsetMapping", "(", "existingMapping", ")", "{", "var", "column", "=", "getColumnAfter", "(", "existingMapping", ".", "generatedLine", "-", "1", ",", "existingMapping", ".", "generatedColumn", ")", ";", "var", "newMapping", "=", "{", "generated", ":", "{", "line", ":", "existingMapping", ".", "generatedLine", ",", "column", ":", "column", "}", "}", ";", "if", "(", "existingMapping", ".", "source", ")", "{", "newMapping", ".", "source", "=", "existingMapping", ".", "source", ";", "newMapping", ".", "original", "=", "{", "line", ":", "existingMapping", ".", "originalLine", ",", "column", ":", "existingMapping", ".", "originalColumn", "}", ";", "if", "(", "existingMapping", ".", "name", ")", "{", "newMapping", ".", "name", "=", "existingMapping", ".", "name", ";", "}", "}", "generator", ".", "addMapping", "(", "newMapping", ")", ";", "}" ]
Copy the given mapping but offset as indicated by the split source code. @param {object} existingMapping An existing source-map mapping from a source-map consumer
[ "Copy", "the", "given", "mapping", "but", "offset", "as", "indicated", "by", "the", "split", "source", "code", "." ]
651b124eefe8d1a567b2a03a0b8a3dfea87c2703
https://github.com/bholloway/browserify-anonymous-labeler/blob/651b124eefe8d1a567b2a03a0b8a3dfea87c2703/lib/adjust-source-map.js#L40-L59
53,273
jmarthernandez/chat-parser
src/mentions.js
mentionsPredicate
function mentionsPredicate(str) { // null/empty check if (!str) { return false; // has @ symbol } else if (str.indexOf('@') < 0) { return false; // has @ symbol as first char } else if (str[0] !== '@') { return false; // contains non-word chars } else if ((/[^\w\s]/).test(str.slice(1))) { return false; // if ends with @ } else if (str[str.length - 1] === '@') { return false; } return true; }
javascript
function mentionsPredicate(str) { // null/empty check if (!str) { return false; // has @ symbol } else if (str.indexOf('@') < 0) { return false; // has @ symbol as first char } else if (str[0] !== '@') { return false; // contains non-word chars } else if ((/[^\w\s]/).test(str.slice(1))) { return false; // if ends with @ } else if (str[str.length - 1] === '@') { return false; } return true; }
[ "function", "mentionsPredicate", "(", "str", ")", "{", "// null/empty check", "if", "(", "!", "str", ")", "{", "return", "false", ";", "// has @ symbol", "}", "else", "if", "(", "str", ".", "indexOf", "(", "'@'", ")", "<", "0", ")", "{", "return", "false", ";", "// has @ symbol as first char", "}", "else", "if", "(", "str", "[", "0", "]", "!==", "'@'", ")", "{", "return", "false", ";", "// contains non-word chars", "}", "else", "if", "(", "(", "/", "[^\\w\\s]", "/", ")", ".", "test", "(", "str", ".", "slice", "(", "1", ")", ")", ")", "{", "return", "false", ";", "// if ends with @", "}", "else", "if", "(", "str", "[", "str", ".", "length", "-", "1", "]", "===", "'@'", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Makes sure string matches the @mention convention @func @param {str}
[ "Makes", "sure", "string", "matches", "the" ]
62e7e28cca35318158e4a807b30dd8d5d88718ac
https://github.com/jmarthernandez/chat-parser/blob/62e7e28cca35318158e4a807b30dd8d5d88718ac/src/mentions.js#L6-L24
53,274
redisjs/jsr-server
lib/command/pubsub/publish.js
execute
function execute(req, res) { // must coerce channel to string var len = this.state.pubsub.publish( req.conn, '' + req.args[0], req.args[1]); res.send(null, len); }
javascript
function execute(req, res) { // must coerce channel to string var len = this.state.pubsub.publish( req.conn, '' + req.args[0], req.args[1]); res.send(null, len); }
[ "function", "execute", "(", "req", ",", "res", ")", "{", "// must coerce channel to string", "var", "len", "=", "this", ".", "state", ".", "pubsub", ".", "publish", "(", "req", ".", "conn", ",", "''", "+", "req", ".", "args", "[", "0", "]", ",", "req", ".", "args", "[", "1", "]", ")", ";", "res", ".", "send", "(", "null", ",", "len", ")", ";", "}" ]
Respond to the PUBLISH command.
[ "Respond", "to", "the", "PUBLISH", "command", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/pubsub/publish.js#L17-L22
53,275
luthraG/states-utils
index.js
_reverseAndPrecompute
function _reverseAndPrecompute () { STATE_NAME_STRICT = Object.keys(US_STATE_NAME_TO_CODE); var territoryKeys = Object.keys(US_INHABITED_TERRITORIES_NAME_TO_CODE); (STATE_NAME_STRICT || []).forEach(function(stateName) { US_STATE_CODE_TO_NAME[US_STATE_NAME_TO_CODE[stateName]] = stateName; US_CAPITAL_TO_STATE_NAME[US_STATE_NAME_TO_CAPITAL[stateName]] = stateName; }); (territoryKeys || []).forEach(function(territoryName) { US_INHABITED_TERRITORIES_CODE_TO_NAME[US_INHABITED_TERRITORIES_NAME_TO_CODE[territoryName]] = territoryName; US_CAPITAL_TO_INHABITED_TERRITORY_NAME[US_INHABITED_TERRITORIES_NAME_TO_CAPITAL[territoryName]] = territoryName; }); // Let us precompute now STATE_CODE_STRICT = Object.keys(US_STATE_CODE_TO_NAME); STATE_NAME_ALL = (STATE_NAME_STRICT || []).concat(territoryKeys); STATE_CODE_ALL = (STATE_CODE_STRICT || []).concat(Object.keys(US_INHABITED_TERRITORIES_CODE_TO_NAME)); }
javascript
function _reverseAndPrecompute () { STATE_NAME_STRICT = Object.keys(US_STATE_NAME_TO_CODE); var territoryKeys = Object.keys(US_INHABITED_TERRITORIES_NAME_TO_CODE); (STATE_NAME_STRICT || []).forEach(function(stateName) { US_STATE_CODE_TO_NAME[US_STATE_NAME_TO_CODE[stateName]] = stateName; US_CAPITAL_TO_STATE_NAME[US_STATE_NAME_TO_CAPITAL[stateName]] = stateName; }); (territoryKeys || []).forEach(function(territoryName) { US_INHABITED_TERRITORIES_CODE_TO_NAME[US_INHABITED_TERRITORIES_NAME_TO_CODE[territoryName]] = territoryName; US_CAPITAL_TO_INHABITED_TERRITORY_NAME[US_INHABITED_TERRITORIES_NAME_TO_CAPITAL[territoryName]] = territoryName; }); // Let us precompute now STATE_CODE_STRICT = Object.keys(US_STATE_CODE_TO_NAME); STATE_NAME_ALL = (STATE_NAME_STRICT || []).concat(territoryKeys); STATE_CODE_ALL = (STATE_CODE_STRICT || []).concat(Object.keys(US_INHABITED_TERRITORIES_CODE_TO_NAME)); }
[ "function", "_reverseAndPrecompute", "(", ")", "{", "STATE_NAME_STRICT", "=", "Object", ".", "keys", "(", "US_STATE_NAME_TO_CODE", ")", ";", "var", "territoryKeys", "=", "Object", ".", "keys", "(", "US_INHABITED_TERRITORIES_NAME_TO_CODE", ")", ";", "(", "STATE_NAME_STRICT", "||", "[", "]", ")", ".", "forEach", "(", "function", "(", "stateName", ")", "{", "US_STATE_CODE_TO_NAME", "[", "US_STATE_NAME_TO_CODE", "[", "stateName", "]", "]", "=", "stateName", ";", "US_CAPITAL_TO_STATE_NAME", "[", "US_STATE_NAME_TO_CAPITAL", "[", "stateName", "]", "]", "=", "stateName", ";", "}", ")", ";", "(", "territoryKeys", "||", "[", "]", ")", ".", "forEach", "(", "function", "(", "territoryName", ")", "{", "US_INHABITED_TERRITORIES_CODE_TO_NAME", "[", "US_INHABITED_TERRITORIES_NAME_TO_CODE", "[", "territoryName", "]", "]", "=", "territoryName", ";", "US_CAPITAL_TO_INHABITED_TERRITORY_NAME", "[", "US_INHABITED_TERRITORIES_NAME_TO_CAPITAL", "[", "territoryName", "]", "]", "=", "territoryName", ";", "}", ")", ";", "// Let us precompute now", "STATE_CODE_STRICT", "=", "Object", ".", "keys", "(", "US_STATE_CODE_TO_NAME", ")", ";", "STATE_NAME_ALL", "=", "(", "STATE_NAME_STRICT", "||", "[", "]", ")", ".", "concat", "(", "territoryKeys", ")", ";", "STATE_CODE_ALL", "=", "(", "STATE_CODE_STRICT", "||", "[", "]", ")", ".", "concat", "(", "Object", ".", "keys", "(", "US_INHABITED_TERRITORIES_CODE_TO_NAME", ")", ")", ";", "}" ]
Create reverse mapping
[ "Create", "reverse", "mapping" ]
d5c2534b0da5f316569591274704894e0527ca2f
https://github.com/luthraG/states-utils/blob/d5c2534b0da5f316569591274704894e0527ca2f/index.js#L24-L43
53,276
luthraG/states-utils
index.js
isUSAState
function isUSAState (state, strict) { state = state && NODE_RATIFY.isString(state) ? _toTitleCase(state) : null; var topLevel = (US_STATE_CODE_TO_NAME[state] || US_STATE_NAME_TO_CODE[state]); if(strict) { return topLevel ? true : false; } else { return (US_INHABITED_TERRITORIES_CODE_TO_NAME[state] || US_INHABITED_TERRITORIES_NAME_TO_CODE[state] || topLevel) ? true : false; } }
javascript
function isUSAState (state, strict) { state = state && NODE_RATIFY.isString(state) ? _toTitleCase(state) : null; var topLevel = (US_STATE_CODE_TO_NAME[state] || US_STATE_NAME_TO_CODE[state]); if(strict) { return topLevel ? true : false; } else { return (US_INHABITED_TERRITORIES_CODE_TO_NAME[state] || US_INHABITED_TERRITORIES_NAME_TO_CODE[state] || topLevel) ? true : false; } }
[ "function", "isUSAState", "(", "state", ",", "strict", ")", "{", "state", "=", "state", "&&", "NODE_RATIFY", ".", "isString", "(", "state", ")", "?", "_toTitleCase", "(", "state", ")", ":", "null", ";", "var", "topLevel", "=", "(", "US_STATE_CODE_TO_NAME", "[", "state", "]", "||", "US_STATE_NAME_TO_CODE", "[", "state", "]", ")", ";", "if", "(", "strict", ")", "{", "return", "topLevel", "?", "true", ":", "false", ";", "}", "else", "{", "return", "(", "US_INHABITED_TERRITORIES_CODE_TO_NAME", "[", "state", "]", "||", "US_INHABITED_TERRITORIES_NAME_TO_CODE", "[", "state", "]", "||", "topLevel", ")", "?", "true", ":", "false", ";", "}", "}" ]
Is given state code or state name is a valid state
[ "Is", "given", "state", "code", "or", "state", "name", "is", "a", "valid", "state" ]
d5c2534b0da5f316569591274704894e0527ca2f
https://github.com/luthraG/states-utils/blob/d5c2534b0da5f316569591274704894e0527ca2f/index.js#L62-L71
53,277
luthraG/states-utils
index.js
getStateName
function getStateName(searchKey, strict) { searchKey = searchKey && NODE_RATIFY.isString(searchKey) ? _toTitleCase(searchKey) : null; var topLevel = (US_STATE_CODE_TO_NAME[searchKey] || US_CAPITAL_TO_STATE_NAME[searchKey]); if(strict) { return topLevel; } else { return (US_INHABITED_TERRITORIES_CODE_TO_NAME[searchKey] || US_CAPITAL_TO_INHABITED_TERRITORY_NAME[searchKey] || topLevel); } }
javascript
function getStateName(searchKey, strict) { searchKey = searchKey && NODE_RATIFY.isString(searchKey) ? _toTitleCase(searchKey) : null; var topLevel = (US_STATE_CODE_TO_NAME[searchKey] || US_CAPITAL_TO_STATE_NAME[searchKey]); if(strict) { return topLevel; } else { return (US_INHABITED_TERRITORIES_CODE_TO_NAME[searchKey] || US_CAPITAL_TO_INHABITED_TERRITORY_NAME[searchKey] || topLevel); } }
[ "function", "getStateName", "(", "searchKey", ",", "strict", ")", "{", "searchKey", "=", "searchKey", "&&", "NODE_RATIFY", ".", "isString", "(", "searchKey", ")", "?", "_toTitleCase", "(", "searchKey", ")", ":", "null", ";", "var", "topLevel", "=", "(", "US_STATE_CODE_TO_NAME", "[", "searchKey", "]", "||", "US_CAPITAL_TO_STATE_NAME", "[", "searchKey", "]", ")", ";", "if", "(", "strict", ")", "{", "return", "topLevel", ";", "}", "else", "{", "return", "(", "US_INHABITED_TERRITORIES_CODE_TO_NAME", "[", "searchKey", "]", "||", "US_CAPITAL_TO_INHABITED_TERRITORY_NAME", "[", "searchKey", "]", "||", "topLevel", ")", ";", "}", "}" ]
Given a state USPS Code or state capital it finds the state name
[ "Given", "a", "state", "USPS", "Code", "or", "state", "capital", "it", "finds", "the", "state", "name" ]
d5c2534b0da5f316569591274704894e0527ca2f
https://github.com/luthraG/states-utils/blob/d5c2534b0da5f316569591274704894e0527ca2f/index.js#L90-L99
53,278
luthraG/states-utils
index.js
getUSPSCode
function getUSPSCode(searchKey, strict) { searchKey = searchKey && NODE_RATIFY.isString(searchKey) ? _toTitleCase(searchKey) : null; var topLevel = (US_STATE_NAME_TO_CODE[searchKey] || US_STATE_NAME_TO_CODE[US_CAPITAL_TO_STATE_NAME[searchKey]]); if(strict) { return topLevel; } else { searchKey = (searchKey === 'HagåTñA') ? 'Hagatna' : searchKey; return (US_INHABITED_TERRITORIES_NAME_TO_CODE[searchKey] || US_INHABITED_TERRITORIES_NAME_TO_CODE[US_CAPITAL_TO_INHABITED_TERRITORY_NAME[searchKey]] || topLevel); } }
javascript
function getUSPSCode(searchKey, strict) { searchKey = searchKey && NODE_RATIFY.isString(searchKey) ? _toTitleCase(searchKey) : null; var topLevel = (US_STATE_NAME_TO_CODE[searchKey] || US_STATE_NAME_TO_CODE[US_CAPITAL_TO_STATE_NAME[searchKey]]); if(strict) { return topLevel; } else { searchKey = (searchKey === 'HagåTñA') ? 'Hagatna' : searchKey; return (US_INHABITED_TERRITORIES_NAME_TO_CODE[searchKey] || US_INHABITED_TERRITORIES_NAME_TO_CODE[US_CAPITAL_TO_INHABITED_TERRITORY_NAME[searchKey]] || topLevel); } }
[ "function", "getUSPSCode", "(", "searchKey", ",", "strict", ")", "{", "searchKey", "=", "searchKey", "&&", "NODE_RATIFY", ".", "isString", "(", "searchKey", ")", "?", "_toTitleCase", "(", "searchKey", ")", ":", "null", ";", "var", "topLevel", "=", "(", "US_STATE_NAME_TO_CODE", "[", "searchKey", "]", "||", "US_STATE_NAME_TO_CODE", "[", "US_CAPITAL_TO_STATE_NAME", "[", "searchKey", "]", "]", ")", ";", "if", "(", "strict", ")", "{", "return", "topLevel", ";", "}", "else", "{", "searchKey", "=", "(", "searchKey", "===", "'HagåTñA') ", "?", "'", "agatna' :", "s", "archKey;", "", "return", "(", "US_INHABITED_TERRITORIES_NAME_TO_CODE", "[", "searchKey", "]", "||", "US_INHABITED_TERRITORIES_NAME_TO_CODE", "[", "US_CAPITAL_TO_INHABITED_TERRITORY_NAME", "[", "searchKey", "]", "]", "||", "topLevel", ")", ";", "}", "}" ]
Given a state name or state capital it finds the USPS Code
[ "Given", "a", "state", "name", "or", "state", "capital", "it", "finds", "the", "USPS", "Code" ]
d5c2534b0da5f316569591274704894e0527ca2f
https://github.com/luthraG/states-utils/blob/d5c2534b0da5f316569591274704894e0527ca2f/index.js#L104-L116
53,279
luthraG/states-utils
index.js
getStateCapital
function getStateCapital(searchKey, strict) { searchKey = searchKey && NODE_RATIFY.isString(searchKey) ? _toTitleCase(searchKey) : null; var topLevel = (US_STATE_NAME_TO_CAPITAL[searchKey] || US_STATE_NAME_TO_CAPITAL[US_STATE_CODE_TO_NAME[searchKey]]); if(strict) { return topLevel; } else { return (US_INHABITED_TERRITORIES_NAME_TO_CAPITAL[searchKey] || US_INHABITED_TERRITORIES_NAME_TO_CAPITAL[US_INHABITED_TERRITORIES_CODE_TO_NAME[searchKey]] || topLevel); } }
javascript
function getStateCapital(searchKey, strict) { searchKey = searchKey && NODE_RATIFY.isString(searchKey) ? _toTitleCase(searchKey) : null; var topLevel = (US_STATE_NAME_TO_CAPITAL[searchKey] || US_STATE_NAME_TO_CAPITAL[US_STATE_CODE_TO_NAME[searchKey]]); if(strict) { return topLevel; } else { return (US_INHABITED_TERRITORIES_NAME_TO_CAPITAL[searchKey] || US_INHABITED_TERRITORIES_NAME_TO_CAPITAL[US_INHABITED_TERRITORIES_CODE_TO_NAME[searchKey]] || topLevel); } }
[ "function", "getStateCapital", "(", "searchKey", ",", "strict", ")", "{", "searchKey", "=", "searchKey", "&&", "NODE_RATIFY", ".", "isString", "(", "searchKey", ")", "?", "_toTitleCase", "(", "searchKey", ")", ":", "null", ";", "var", "topLevel", "=", "(", "US_STATE_NAME_TO_CAPITAL", "[", "searchKey", "]", "||", "US_STATE_NAME_TO_CAPITAL", "[", "US_STATE_CODE_TO_NAME", "[", "searchKey", "]", "]", ")", ";", "if", "(", "strict", ")", "{", "return", "topLevel", ";", "}", "else", "{", "return", "(", "US_INHABITED_TERRITORIES_NAME_TO_CAPITAL", "[", "searchKey", "]", "||", "US_INHABITED_TERRITORIES_NAME_TO_CAPITAL", "[", "US_INHABITED_TERRITORIES_CODE_TO_NAME", "[", "searchKey", "]", "]", "||", "topLevel", ")", ";", "}", "}" ]
Given a state name or state USPS code it finds the state capital
[ "Given", "a", "state", "name", "or", "state", "USPS", "code", "it", "finds", "the", "state", "capital" ]
d5c2534b0da5f316569591274704894e0527ca2f
https://github.com/luthraG/states-utils/blob/d5c2534b0da5f316569591274704894e0527ca2f/index.js#L121-L132
53,280
superelement/log-saviour
index.js
log
function log() { var args = NS ? [chalk.bold.gray(NS)] : [] for(var i=0; i<arguments.length; i++) { var arg = arguments[i]; args.push(chalk.cyan( typeof arg === "object" ? JSON.stringify(arg) : arg )) // adds a separator if(i < arguments.length-1) args.push(chalk.gray("|")); } if(testLog) testLog(args); else console.log.apply(null, args) }
javascript
function log() { var args = NS ? [chalk.bold.gray(NS)] : [] for(var i=0; i<arguments.length; i++) { var arg = arguments[i]; args.push(chalk.cyan( typeof arg === "object" ? JSON.stringify(arg) : arg )) // adds a separator if(i < arguments.length-1) args.push(chalk.gray("|")); } if(testLog) testLog(args); else console.log.apply(null, args) }
[ "function", "log", "(", ")", "{", "var", "args", "=", "NS", "?", "[", "chalk", ".", "bold", ".", "gray", "(", "NS", ")", "]", ":", "[", "]", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "var", "arg", "=", "arguments", "[", "i", "]", ";", "args", ".", "push", "(", "chalk", ".", "cyan", "(", "typeof", "arg", "===", "\"object\"", "?", "JSON", ".", "stringify", "(", "arg", ")", ":", "arg", ")", ")", "// adds a separator", "if", "(", "i", "<", "arguments", ".", "length", "-", "1", ")", "args", ".", "push", "(", "chalk", ".", "gray", "(", "\"|\"", ")", ")", ";", "}", "if", "(", "testLog", ")", "testLog", "(", "args", ")", ";", "else", "console", ".", "log", ".", "apply", "(", "null", ",", "args", ")", "}" ]
coloured console log
[ "coloured", "console", "log" ]
a45c56d71b8af173e82f5dc12568f34eb380da51
https://github.com/superelement/log-saviour/blob/a45c56d71b8af173e82f5dc12568f34eb380da51/index.js#L11-L22
53,281
superelement/log-saviour
index.js
logArr
function logArr(arr) { if(arguments.length > 1) { if(!suppressWarnings) console.warn("'logArr' only supports 1 parameter. Converting to regular 'log'."); log(Array.prototype.slice.call(arguments)); return; } if(! _.isArray(arr)) { if(!suppressWarnings) console.warn("'logArr' used, but first argument was not an array. Converting to regular 'log'."); log(arr); return; } log.apply(null, arr) }
javascript
function logArr(arr) { if(arguments.length > 1) { if(!suppressWarnings) console.warn("'logArr' only supports 1 parameter. Converting to regular 'log'."); log(Array.prototype.slice.call(arguments)); return; } if(! _.isArray(arr)) { if(!suppressWarnings) console.warn("'logArr' used, but first argument was not an array. Converting to regular 'log'."); log(arr); return; } log.apply(null, arr) }
[ "function", "logArr", "(", "arr", ")", "{", "if", "(", "arguments", ".", "length", ">", "1", ")", "{", "if", "(", "!", "suppressWarnings", ")", "console", ".", "warn", "(", "\"'logArr' only supports 1 parameter. Converting to regular 'log'.\"", ")", ";", "log", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", ";", "return", ";", "}", "if", "(", "!", "_", ".", "isArray", "(", "arr", ")", ")", "{", "if", "(", "!", "suppressWarnings", ")", "console", ".", "warn", "(", "\"'logArr' used, but first argument was not an array. Converting to regular 'log'.\"", ")", ";", "log", "(", "arr", ")", ";", "return", ";", "}", "log", ".", "apply", "(", "null", ",", "arr", ")", "}" ]
coloured console log, using an array instead of parameters
[ "coloured", "console", "log", "using", "an", "array", "instead", "of", "parameters" ]
a45c56d71b8af173e82f5dc12568f34eb380da51
https://github.com/superelement/log-saviour/blob/a45c56d71b8af173e82f5dc12568f34eb380da51/index.js#L25-L39
53,282
superelement/log-saviour
index.js
warn
function warn() { if(suppressWarnings) return var args = NS ? [chalk.bold.gray(NS)] : [] for(var i=0; i<arguments.length; i++) { var arg = arguments[i]; args.push(chalk.bold.yellow.bgRed( typeof arg === "object" ? JSON.stringify(arg) : arg )) // adds a separator if(i < arguments.length-1) args.push(chalk.gray("|")); } if(testWarn) testWarn(args); else console.warn.apply(null, args) }
javascript
function warn() { if(suppressWarnings) return var args = NS ? [chalk.bold.gray(NS)] : [] for(var i=0; i<arguments.length; i++) { var arg = arguments[i]; args.push(chalk.bold.yellow.bgRed( typeof arg === "object" ? JSON.stringify(arg) : arg )) // adds a separator if(i < arguments.length-1) args.push(chalk.gray("|")); } if(testWarn) testWarn(args); else console.warn.apply(null, args) }
[ "function", "warn", "(", ")", "{", "if", "(", "suppressWarnings", ")", "return", "var", "args", "=", "NS", "?", "[", "chalk", ".", "bold", ".", "gray", "(", "NS", ")", "]", ":", "[", "]", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "var", "arg", "=", "arguments", "[", "i", "]", ";", "args", ".", "push", "(", "chalk", ".", "bold", ".", "yellow", ".", "bgRed", "(", "typeof", "arg", "===", "\"object\"", "?", "JSON", ".", "stringify", "(", "arg", ")", ":", "arg", ")", ")", "// adds a separator", "if", "(", "i", "<", "arguments", ".", "length", "-", "1", ")", "args", ".", "push", "(", "chalk", ".", "gray", "(", "\"|\"", ")", ")", ";", "}", "if", "(", "testWarn", ")", "testWarn", "(", "args", ")", ";", "else", "console", ".", "warn", ".", "apply", "(", "null", ",", "args", ")", "}" ]
coloured console warn
[ "coloured", "console", "warn" ]
a45c56d71b8af173e82f5dc12568f34eb380da51
https://github.com/superelement/log-saviour/blob/a45c56d71b8af173e82f5dc12568f34eb380da51/index.js#L42-L56
53,283
mvolkmann/node-token-auth
index.js
configure
function configure(alg, pswd, sto) { algorithm = alg; password = pswd; sessionTimeout = sto; }
javascript
function configure(alg, pswd, sto) { algorithm = alg; password = pswd; sessionTimeout = sto; }
[ "function", "configure", "(", "alg", ",", "pswd", ",", "sto", ")", "{", "algorithm", "=", "alg", ";", "password", "=", "pswd", ";", "sessionTimeout", "=", "sto", ";", "}" ]
Configures auth token encryption and the session timeout. @param alg the encryption algorithm name @param pswd the encryption password @param sto the session timeout duration in minutes
[ "Configures", "auth", "token", "encryption", "and", "the", "session", "timeout", "." ]
dfbccd0b58a02c02d96eccd14b2b96834eb024b0
https://github.com/mvolkmann/node-token-auth/blob/dfbccd0b58a02c02d96eccd14b2b96834eb024b0/index.js#L50-L54
53,284
bholloway/browserify-incremental-plugin
index.js
pluginFactory
function pluginFactory(cache) { // ensure cache var internalCache = cache || {}; // create an instance of cache populater var getCache = cacheFactory(internalCache); // return a closure with a pluginFactory() sidecar browserifyIncremental.pluginFactory = pluginFactory; return browserifyIncremental; /** * A browserify plugin that checks incoming file context and uses cached results. * @param {object} bundler The browserify bundler instance * @param {object} opt An options hash */ function browserifyIncremental(bundler, opt) { var isValid = bundler && (typeof bundler === 'object') && (typeof bundler.on === 'function') && (typeof bundler.pipeline === 'object'); if (isValid) { bundler.on('reset', setupPipeline); setupPipeline(); } else { throw new Error('Expected a browserify bundler instance') } /** * Apply an interceptor to the pipeline. */ function setupPipeline() { var deps = bundler.pipeline.get('deps'); deps.push(getCache(deps._streams[0].cache)); } } }
javascript
function pluginFactory(cache) { // ensure cache var internalCache = cache || {}; // create an instance of cache populater var getCache = cacheFactory(internalCache); // return a closure with a pluginFactory() sidecar browserifyIncremental.pluginFactory = pluginFactory; return browserifyIncremental; /** * A browserify plugin that checks incoming file context and uses cached results. * @param {object} bundler The browserify bundler instance * @param {object} opt An options hash */ function browserifyIncremental(bundler, opt) { var isValid = bundler && (typeof bundler === 'object') && (typeof bundler.on === 'function') && (typeof bundler.pipeline === 'object'); if (isValid) { bundler.on('reset', setupPipeline); setupPipeline(); } else { throw new Error('Expected a browserify bundler instance') } /** * Apply an interceptor to the pipeline. */ function setupPipeline() { var deps = bundler.pipeline.get('deps'); deps.push(getCache(deps._streams[0].cache)); } } }
[ "function", "pluginFactory", "(", "cache", ")", "{", "// ensure cache", "var", "internalCache", "=", "cache", "||", "{", "}", ";", "// create an instance of cache populater", "var", "getCache", "=", "cacheFactory", "(", "internalCache", ")", ";", "// return a closure with a pluginFactory() sidecar", "browserifyIncremental", ".", "pluginFactory", "=", "pluginFactory", ";", "return", "browserifyIncremental", ";", "/**\n * A browserify plugin that checks incoming file context and uses cached results.\n * @param {object} bundler The browserify bundler instance\n * @param {object} opt An options hash\n */", "function", "browserifyIncremental", "(", "bundler", ",", "opt", ")", "{", "var", "isValid", "=", "bundler", "&&", "(", "typeof", "bundler", "===", "'object'", ")", "&&", "(", "typeof", "bundler", ".", "on", "===", "'function'", ")", "&&", "(", "typeof", "bundler", ".", "pipeline", "===", "'object'", ")", ";", "if", "(", "isValid", ")", "{", "bundler", ".", "on", "(", "'reset'", ",", "setupPipeline", ")", ";", "setupPipeline", "(", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Expected a browserify bundler instance'", ")", "}", "/**\n * Apply an interceptor to the pipeline.\n */", "function", "setupPipeline", "(", ")", "{", "var", "deps", "=", "bundler", ".", "pipeline", ".", "get", "(", "'deps'", ")", ";", "deps", ".", "push", "(", "getCache", "(", "deps", ".", "_streams", "[", "0", "]", ".", "cache", ")", ")", ";", "}", "}", "}" ]
Create a context for which multiple instances of the plugin may operate with a shared cache. @param {object} [cache] Optional cache @returns {function} A browserify plugin
[ "Create", "a", "context", "for", "which", "multiple", "instances", "of", "the", "plugin", "may", "operate", "with", "a", "shared", "cache", "." ]
87656c217d6dd028f159122229f8fef412f42dd3
https://github.com/bholloway/browserify-incremental-plugin/blob/87656c217d6dd028f159122229f8fef412f42dd3/index.js#L13-L49
53,285
bholloway/browserify-incremental-plugin
index.js
setupPipeline
function setupPipeline() { var deps = bundler.pipeline.get('deps'); deps.push(getCache(deps._streams[0].cache)); }
javascript
function setupPipeline() { var deps = bundler.pipeline.get('deps'); deps.push(getCache(deps._streams[0].cache)); }
[ "function", "setupPipeline", "(", ")", "{", "var", "deps", "=", "bundler", ".", "pipeline", ".", "get", "(", "'deps'", ")", ";", "deps", ".", "push", "(", "getCache", "(", "deps", ".", "_streams", "[", "0", "]", ".", "cache", ")", ")", ";", "}" ]
Apply an interceptor to the pipeline.
[ "Apply", "an", "interceptor", "to", "the", "pipeline", "." ]
87656c217d6dd028f159122229f8fef412f42dd3
https://github.com/bholloway/browserify-incremental-plugin/blob/87656c217d6dd028f159122229f8fef412f42dd3/index.js#L44-L47
53,286
bholloway/browserify-incremental-plugin
index.js
cacheFactory
function cacheFactory(internalCache) { // comparison cache will be use by getters // since getters are persistent on the internal cache then the comparison cache also needs to be persistent var isTestedCache = {}; /** * Get a pipeline 'deps' stage that populates cache for incremental compile. * Called on fully transformed row but only when there is no cache hit. * @param {object} depsCache The cache used by module-deps * @returns {stream.Through} a through stream */ return function getCacheSession(depsCache) { // make getters for any existing values (cache is shared across instances) for (var key in internalCache) { defineGetterFor(depsCache, key); } // comparison cache needs to be reset every compile // setting value is quicker than delete operation by an order of magnitude for (var key in isTestedCache) { isTestedCache[key] = false; } // deps stage transform function transform(row, encoding, done) { /* jshint validthis:true */ var filename = row.file; var fileSource = null; try { fileSource = fs.readFileSync(filename).toString() } catch (e) {} if (fileSource !== null) { // populate the cache (overwrite) isTestedCache[filename] = false; internalCache[filename] = { input : fileSource, output: { id : filename, source: row.source, deps : merge({}, row.deps), file : filename } }; } // ensure a getter is present for this key defineGetterFor(depsCache, filename); // complete this.push(row); done(); } return through.obj(transform); }; /** * Create getter on first appearance of a given key and operate through the persistent cache objects. * However be careful not to use any closed over variables in the getter. * @param {object} depsCache The browserify cache shared across instances * @param {string} filename The key (file name) for the deps cache */ function defineGetterFor(depsCache, filename) { // instead of making the property re-definable we instead make assignment idempotent if (!depsCache.hasOwnProperty(filename)) { Object.defineProperty(depsCache, filename, {get: getter}); } // create a getter // we need to use a getter as it is the only hook at which we can perform comparison // the value is accessed multiple times each compile cycle but is only set at the end of the cycle // getters will persist for the life of the internal cache so the test cache also needs to persist function getter() { // not found var cached = internalCache[filename]; if (!cached) { return undefined; } // we have already tested whether the cached value is valid and deleted it if not else if (isTestedCache[filename]) { return cached.output; } // test the input else { var isMatch = cached.input && fs.existsSync(filename) && (cached.input === fs.readFileSync(filename).toString()); isTestedCache[filename] = true; internalCache[filename] = isMatch && cached; return getter(); } } } }
javascript
function cacheFactory(internalCache) { // comparison cache will be use by getters // since getters are persistent on the internal cache then the comparison cache also needs to be persistent var isTestedCache = {}; /** * Get a pipeline 'deps' stage that populates cache for incremental compile. * Called on fully transformed row but only when there is no cache hit. * @param {object} depsCache The cache used by module-deps * @returns {stream.Through} a through stream */ return function getCacheSession(depsCache) { // make getters for any existing values (cache is shared across instances) for (var key in internalCache) { defineGetterFor(depsCache, key); } // comparison cache needs to be reset every compile // setting value is quicker than delete operation by an order of magnitude for (var key in isTestedCache) { isTestedCache[key] = false; } // deps stage transform function transform(row, encoding, done) { /* jshint validthis:true */ var filename = row.file; var fileSource = null; try { fileSource = fs.readFileSync(filename).toString() } catch (e) {} if (fileSource !== null) { // populate the cache (overwrite) isTestedCache[filename] = false; internalCache[filename] = { input : fileSource, output: { id : filename, source: row.source, deps : merge({}, row.deps), file : filename } }; } // ensure a getter is present for this key defineGetterFor(depsCache, filename); // complete this.push(row); done(); } return through.obj(transform); }; /** * Create getter on first appearance of a given key and operate through the persistent cache objects. * However be careful not to use any closed over variables in the getter. * @param {object} depsCache The browserify cache shared across instances * @param {string} filename The key (file name) for the deps cache */ function defineGetterFor(depsCache, filename) { // instead of making the property re-definable we instead make assignment idempotent if (!depsCache.hasOwnProperty(filename)) { Object.defineProperty(depsCache, filename, {get: getter}); } // create a getter // we need to use a getter as it is the only hook at which we can perform comparison // the value is accessed multiple times each compile cycle but is only set at the end of the cycle // getters will persist for the life of the internal cache so the test cache also needs to persist function getter() { // not found var cached = internalCache[filename]; if (!cached) { return undefined; } // we have already tested whether the cached value is valid and deleted it if not else if (isTestedCache[filename]) { return cached.output; } // test the input else { var isMatch = cached.input && fs.existsSync(filename) && (cached.input === fs.readFileSync(filename).toString()); isTestedCache[filename] = true; internalCache[filename] = isMatch && cached; return getter(); } } } }
[ "function", "cacheFactory", "(", "internalCache", ")", "{", "// comparison cache will be use by getters", "// since getters are persistent on the internal cache then the comparison cache also needs to be persistent", "var", "isTestedCache", "=", "{", "}", ";", "/**\n * Get a pipeline 'deps' stage that populates cache for incremental compile.\n * Called on fully transformed row but only when there is no cache hit.\n * @param {object} depsCache The cache used by module-deps\n * @returns {stream.Through} a through stream\n */", "return", "function", "getCacheSession", "(", "depsCache", ")", "{", "// make getters for any existing values (cache is shared across instances)", "for", "(", "var", "key", "in", "internalCache", ")", "{", "defineGetterFor", "(", "depsCache", ",", "key", ")", ";", "}", "// comparison cache needs to be reset every compile", "// setting value is quicker than delete operation by an order of magnitude", "for", "(", "var", "key", "in", "isTestedCache", ")", "{", "isTestedCache", "[", "key", "]", "=", "false", ";", "}", "// deps stage transform", "function", "transform", "(", "row", ",", "encoding", ",", "done", ")", "{", "/* jshint validthis:true */", "var", "filename", "=", "row", ".", "file", ";", "var", "fileSource", "=", "null", ";", "try", "{", "fileSource", "=", "fs", ".", "readFileSync", "(", "filename", ")", ".", "toString", "(", ")", "}", "catch", "(", "e", ")", "{", "}", "if", "(", "fileSource", "!==", "null", ")", "{", "// populate the cache (overwrite)", "isTestedCache", "[", "filename", "]", "=", "false", ";", "internalCache", "[", "filename", "]", "=", "{", "input", ":", "fileSource", ",", "output", ":", "{", "id", ":", "filename", ",", "source", ":", "row", ".", "source", ",", "deps", ":", "merge", "(", "{", "}", ",", "row", ".", "deps", ")", ",", "file", ":", "filename", "}", "}", ";", "}", "// ensure a getter is present for this key", "defineGetterFor", "(", "depsCache", ",", "filename", ")", ";", "// complete", "this", ".", "push", "(", "row", ")", ";", "done", "(", ")", ";", "}", "return", "through", ".", "obj", "(", "transform", ")", ";", "}", ";", "/**\n * Create getter on first appearance of a given key and operate through the persistent cache objects.\n * However be careful not to use any closed over variables in the getter.\n * @param {object} depsCache The browserify cache shared across instances\n * @param {string} filename The key (file name) for the deps cache\n */", "function", "defineGetterFor", "(", "depsCache", ",", "filename", ")", "{", "// instead of making the property re-definable we instead make assignment idempotent", "if", "(", "!", "depsCache", ".", "hasOwnProperty", "(", "filename", ")", ")", "{", "Object", ".", "defineProperty", "(", "depsCache", ",", "filename", ",", "{", "get", ":", "getter", "}", ")", ";", "}", "// create a getter", "// we need to use a getter as it is the only hook at which we can perform comparison", "// the value is accessed multiple times each compile cycle but is only set at the end of the cycle", "// getters will persist for the life of the internal cache so the test cache also needs to persist", "function", "getter", "(", ")", "{", "// not found", "var", "cached", "=", "internalCache", "[", "filename", "]", ";", "if", "(", "!", "cached", ")", "{", "return", "undefined", ";", "}", "// we have already tested whether the cached value is valid and deleted it if not", "else", "if", "(", "isTestedCache", "[", "filename", "]", ")", "{", "return", "cached", ".", "output", ";", "}", "// test the input", "else", "{", "var", "isMatch", "=", "cached", ".", "input", "&&", "fs", ".", "existsSync", "(", "filename", ")", "&&", "(", "cached", ".", "input", "===", "fs", ".", "readFileSync", "(", "filename", ")", ".", "toString", "(", ")", ")", ";", "isTestedCache", "[", "filename", "]", "=", "true", ";", "internalCache", "[", "filename", "]", "=", "isMatch", "&&", "cached", ";", "return", "getter", "(", ")", ";", "}", "}", "}", "}" ]
A factory for a pipeline 'deps' stage. @param {object} internalCache Our internal cache @returns {function} a closure that will get an instance for a given depsCache
[ "A", "factory", "for", "a", "pipeline", "deps", "stage", "." ]
87656c217d6dd028f159122229f8fef412f42dd3
https://github.com/bholloway/browserify-incremental-plugin/blob/87656c217d6dd028f159122229f8fef412f42dd3/index.js#L58-L156
53,287
bholloway/browserify-incremental-plugin
index.js
defineGetterFor
function defineGetterFor(depsCache, filename) { // instead of making the property re-definable we instead make assignment idempotent if (!depsCache.hasOwnProperty(filename)) { Object.defineProperty(depsCache, filename, {get: getter}); } // create a getter // we need to use a getter as it is the only hook at which we can perform comparison // the value is accessed multiple times each compile cycle but is only set at the end of the cycle // getters will persist for the life of the internal cache so the test cache also needs to persist function getter() { // not found var cached = internalCache[filename]; if (!cached) { return undefined; } // we have already tested whether the cached value is valid and deleted it if not else if (isTestedCache[filename]) { return cached.output; } // test the input else { var isMatch = cached.input && fs.existsSync(filename) && (cached.input === fs.readFileSync(filename).toString()); isTestedCache[filename] = true; internalCache[filename] = isMatch && cached; return getter(); } } }
javascript
function defineGetterFor(depsCache, filename) { // instead of making the property re-definable we instead make assignment idempotent if (!depsCache.hasOwnProperty(filename)) { Object.defineProperty(depsCache, filename, {get: getter}); } // create a getter // we need to use a getter as it is the only hook at which we can perform comparison // the value is accessed multiple times each compile cycle but is only set at the end of the cycle // getters will persist for the life of the internal cache so the test cache also needs to persist function getter() { // not found var cached = internalCache[filename]; if (!cached) { return undefined; } // we have already tested whether the cached value is valid and deleted it if not else if (isTestedCache[filename]) { return cached.output; } // test the input else { var isMatch = cached.input && fs.existsSync(filename) && (cached.input === fs.readFileSync(filename).toString()); isTestedCache[filename] = true; internalCache[filename] = isMatch && cached; return getter(); } } }
[ "function", "defineGetterFor", "(", "depsCache", ",", "filename", ")", "{", "// instead of making the property re-definable we instead make assignment idempotent", "if", "(", "!", "depsCache", ".", "hasOwnProperty", "(", "filename", ")", ")", "{", "Object", ".", "defineProperty", "(", "depsCache", ",", "filename", ",", "{", "get", ":", "getter", "}", ")", ";", "}", "// create a getter", "// we need to use a getter as it is the only hook at which we can perform comparison", "// the value is accessed multiple times each compile cycle but is only set at the end of the cycle", "// getters will persist for the life of the internal cache so the test cache also needs to persist", "function", "getter", "(", ")", "{", "// not found", "var", "cached", "=", "internalCache", "[", "filename", "]", ";", "if", "(", "!", "cached", ")", "{", "return", "undefined", ";", "}", "// we have already tested whether the cached value is valid and deleted it if not", "else", "if", "(", "isTestedCache", "[", "filename", "]", ")", "{", "return", "cached", ".", "output", ";", "}", "// test the input", "else", "{", "var", "isMatch", "=", "cached", ".", "input", "&&", "fs", ".", "existsSync", "(", "filename", ")", "&&", "(", "cached", ".", "input", "===", "fs", ".", "readFileSync", "(", "filename", ")", ".", "toString", "(", ")", ")", ";", "isTestedCache", "[", "filename", "]", "=", "true", ";", "internalCache", "[", "filename", "]", "=", "isMatch", "&&", "cached", ";", "return", "getter", "(", ")", ";", "}", "}", "}" ]
Create getter on first appearance of a given key and operate through the persistent cache objects. However be careful not to use any closed over variables in the getter. @param {object} depsCache The browserify cache shared across instances @param {string} filename The key (file name) for the deps cache
[ "Create", "getter", "on", "first", "appearance", "of", "a", "given", "key", "and", "operate", "through", "the", "persistent", "cache", "objects", ".", "However", "be", "careful", "not", "to", "use", "any", "closed", "over", "variables", "in", "the", "getter", "." ]
87656c217d6dd028f159122229f8fef412f42dd3
https://github.com/bholloway/browserify-incremental-plugin/blob/87656c217d6dd028f159122229f8fef412f42dd3/index.js#L124-L155
53,288
bholloway/browserify-incremental-plugin
index.js
getter
function getter() { // not found var cached = internalCache[filename]; if (!cached) { return undefined; } // we have already tested whether the cached value is valid and deleted it if not else if (isTestedCache[filename]) { return cached.output; } // test the input else { var isMatch = cached.input && fs.existsSync(filename) && (cached.input === fs.readFileSync(filename).toString()); isTestedCache[filename] = true; internalCache[filename] = isMatch && cached; return getter(); } }
javascript
function getter() { // not found var cached = internalCache[filename]; if (!cached) { return undefined; } // we have already tested whether the cached value is valid and deleted it if not else if (isTestedCache[filename]) { return cached.output; } // test the input else { var isMatch = cached.input && fs.existsSync(filename) && (cached.input === fs.readFileSync(filename).toString()); isTestedCache[filename] = true; internalCache[filename] = isMatch && cached; return getter(); } }
[ "function", "getter", "(", ")", "{", "// not found", "var", "cached", "=", "internalCache", "[", "filename", "]", ";", "if", "(", "!", "cached", ")", "{", "return", "undefined", ";", "}", "// we have already tested whether the cached value is valid and deleted it if not", "else", "if", "(", "isTestedCache", "[", "filename", "]", ")", "{", "return", "cached", ".", "output", ";", "}", "// test the input", "else", "{", "var", "isMatch", "=", "cached", ".", "input", "&&", "fs", ".", "existsSync", "(", "filename", ")", "&&", "(", "cached", ".", "input", "===", "fs", ".", "readFileSync", "(", "filename", ")", ".", "toString", "(", ")", ")", ";", "isTestedCache", "[", "filename", "]", "=", "true", ";", "internalCache", "[", "filename", "]", "=", "isMatch", "&&", "cached", ";", "return", "getter", "(", ")", ";", "}", "}" ]
create a getter we need to use a getter as it is the only hook at which we can perform comparison the value is accessed multiple times each compile cycle but is only set at the end of the cycle getters will persist for the life of the internal cache so the test cache also needs to persist
[ "create", "a", "getter", "we", "need", "to", "use", "a", "getter", "as", "it", "is", "the", "only", "hook", "at", "which", "we", "can", "perform", "comparison", "the", "value", "is", "accessed", "multiple", "times", "each", "compile", "cycle", "but", "is", "only", "set", "at", "the", "end", "of", "the", "cycle", "getters", "will", "persist", "for", "the", "life", "of", "the", "internal", "cache", "so", "the", "test", "cache", "also", "needs", "to", "persist" ]
87656c217d6dd028f159122229f8fef412f42dd3
https://github.com/bholloway/browserify-incremental-plugin/blob/87656c217d6dd028f159122229f8fef412f42dd3/index.js#L135-L154
53,289
tx4x/git-module
lib/exe.js
getModuleConfig
function getModuleConfig(nameOrPath,modules) { for (var i = 0; i < modules.length; i++) { var config = modules[i]; if (config.options && (config.options.directory === nameOrPath || config.name === nameOrPath)) { return config; } } return null; }
javascript
function getModuleConfig(nameOrPath,modules) { for (var i = 0; i < modules.length; i++) { var config = modules[i]; if (config.options && (config.options.directory === nameOrPath || config.name === nameOrPath)) { return config; } } return null; }
[ "function", "getModuleConfig", "(", "nameOrPath", ",", "modules", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "modules", ".", "length", ";", "i", "++", ")", "{", "var", "config", "=", "modules", "[", "i", "]", ";", "if", "(", "config", ".", "options", "&&", "(", "config", ".", "options", ".", "directory", "===", "nameOrPath", "||", "config", ".", "name", "===", "nameOrPath", ")", ")", "{", "return", "config", ";", "}", "}", "return", "null", ";", "}" ]
Find a module config by path or name @param nameOrPath {string} @param modules {object[]} @returns {null|object}
[ "Find", "a", "module", "config", "by", "path", "or", "name" ]
93ff14eecb00c5c140f3e6413bd43404cc1dd021
https://github.com/tx4x/git-module/blob/93ff14eecb00c5c140f3e6413bd43404cc1dd021/lib/exe.js#L24-L32
53,290
tx4x/git-module
lib/exe.js
getModules
function getModules(argv,modules){ if(argv.module){ var which = getModuleConfig(argv.module,modules); if(which){ return [which]; }else{ return []; } } return modules; }
javascript
function getModules(argv,modules){ if(argv.module){ var which = getModuleConfig(argv.module,modules); if(which){ return [which]; }else{ return []; } } return modules; }
[ "function", "getModules", "(", "argv", ",", "modules", ")", "{", "if", "(", "argv", ".", "module", ")", "{", "var", "which", "=", "getModuleConfig", "(", "argv", ".", "module", ",", "modules", ")", ";", "if", "(", "which", ")", "{", "return", "[", "which", "]", ";", "}", "else", "{", "return", "[", "]", ";", "}", "}", "return", "modules", ";", "}" ]
Filter modules against cmd arg @param argv {object} @param modules {object[]} @returns {*}
[ "Filter", "modules", "against", "cmd", "arg" ]
93ff14eecb00c5c140f3e6413bd43404cc1dd021
https://github.com/tx4x/git-module/blob/93ff14eecb00c5c140f3e6413bd43404cc1dd021/lib/exe.js#L94-L104
53,291
faboweb/zliq
src/utils/vdom-diff.js
removeNotNeededNodes
function removeNotNeededNodes(parentElements, newChildren, oldChildren) { let remaining = parentElements.childNodes.length; if (oldChildren.length !== remaining) { console.warn( "ZLIQ: Something other then ZLIQ has manipulated the children of the element", parentElements, ". This can lead to sideffects. Consider using the 'isolated' attribute for this element to prevent updates." ); } for (; remaining > newChildren.length; remaining--) { let childToRemove = parentElements.childNodes[remaining - 1]; parentElements.removeChild(childToRemove); if (oldChildren.length < remaining) { continue; } else { let { cycle } = oldChildren[remaining - 1]; triggerLifecycle(childToRemove, { cycle }, "removed"); } } }
javascript
function removeNotNeededNodes(parentElements, newChildren, oldChildren) { let remaining = parentElements.childNodes.length; if (oldChildren.length !== remaining) { console.warn( "ZLIQ: Something other then ZLIQ has manipulated the children of the element", parentElements, ". This can lead to sideffects. Consider using the 'isolated' attribute for this element to prevent updates." ); } for (; remaining > newChildren.length; remaining--) { let childToRemove = parentElements.childNodes[remaining - 1]; parentElements.removeChild(childToRemove); if (oldChildren.length < remaining) { continue; } else { let { cycle } = oldChildren[remaining - 1]; triggerLifecycle(childToRemove, { cycle }, "removed"); } } }
[ "function", "removeNotNeededNodes", "(", "parentElements", ",", "newChildren", ",", "oldChildren", ")", "{", "let", "remaining", "=", "parentElements", ".", "childNodes", ".", "length", ";", "if", "(", "oldChildren", ".", "length", "!==", "remaining", ")", "{", "console", ".", "warn", "(", "\"ZLIQ: Something other then ZLIQ has manipulated the children of the element\"", ",", "parentElements", ",", "\". This can lead to sideffects. Consider using the 'isolated' attribute for this element to prevent updates.\"", ")", ";", "}", "for", "(", ";", "remaining", ">", "newChildren", ".", "length", ";", "remaining", "--", ")", "{", "let", "childToRemove", "=", "parentElements", ".", "childNodes", "[", "remaining", "-", "1", "]", ";", "parentElements", ".", "removeChild", "(", "childToRemove", ")", ";", "if", "(", "oldChildren", ".", "length", "<", "remaining", ")", "{", "continue", ";", "}", "else", "{", "let", "{", "cycle", "}", "=", "oldChildren", "[", "remaining", "-", "1", "]", ";", "triggerLifecycle", "(", "childToRemove", ",", "{", "cycle", "}", ",", "\"removed\"", ")", ";", "}", "}", "}" ]
this removes nodes at the end of the children, that are not needed anymore in the current state for recycling
[ "this", "removes", "nodes", "at", "the", "end", "of", "the", "children", "that", "are", "not", "needed", "anymore", "in", "the", "current", "state", "for", "recycling" ]
1d4d5ed9631c0c29b101bcf4817ad40624b6bbea
https://github.com/faboweb/zliq/blob/1d4d5ed9631c0c29b101bcf4817ad40624b6bbea/src/utils/vdom-diff.js#L156-L178
53,292
faboweb/zliq
src/utils/vdom-diff.js
shouldRecycleElement
function shouldRecycleElement(oldElement, props, tag) { return ( !isTextNode(oldElement) && oldElement.id === "" && !nodeTypeDiffers(oldElement, tag) ); }
javascript
function shouldRecycleElement(oldElement, props, tag) { return ( !isTextNode(oldElement) && oldElement.id === "" && !nodeTypeDiffers(oldElement, tag) ); }
[ "function", "shouldRecycleElement", "(", "oldElement", ",", "props", ",", "tag", ")", "{", "return", "(", "!", "isTextNode", "(", "oldElement", ")", "&&", "oldElement", ".", "id", "===", "\"\"", "&&", "!", "nodeTypeDiffers", "(", "oldElement", ",", "tag", ")", ")", ";", "}" ]
we want to recycle elements to save time on creating and inserting nodes into the dom we don't want to manipulate elements that go into the cache, because they would mutate in the cache as well
[ "we", "want", "to", "recycle", "elements", "to", "save", "time", "on", "creating", "and", "inserting", "nodes", "into", "the", "dom", "we", "don", "t", "want", "to", "manipulate", "elements", "that", "go", "into", "the", "cache", "because", "they", "would", "mutate", "in", "the", "cache", "as", "well" ]
1d4d5ed9631c0c29b101bcf4817ad40624b6bbea
https://github.com/faboweb/zliq/blob/1d4d5ed9631c0c29b101bcf4817ad40624b6bbea/src/utils/vdom-diff.js#L345-L351
53,293
gethuman/pancakes-recipe
middleware/mw.auth.social.js
getProvider
function getProvider(providerName, providerConfig) { return _.extend({}, providerConfig.opts, { profile: function profile(credentials, params, get, callback) { var proof = null; /* eslint camelcase:0 */ if (providerConfig.useProof) { proof = { appsecret_proof: crypto .createHmac('sha256', this.clientSecret) .update(credentials.token) .digest('hex') }; } get(providerConfig.url, proof, function (data) { credentials.profile = { authType: providerName, email: data.email, emailLower: data.email && data.email.toLowerCase(), emailConfirmed: data.verified, name: { firstName: data.given_name || '', lastName: data.family_name || '', displayName: data.name || '' } }; if (providerName === 'google') { credentials.profile.profileImg = data.picture; credentials.profile.googleAuthData = data; } else if (providerName === 'facebook') { credentials.profile.profileImg = 'https://graph.facebook.com/' + data.id + '/picture?width=80&height=80'; credentials.profile.fbAuthData = data; } return callback(); }); } }); }
javascript
function getProvider(providerName, providerConfig) { return _.extend({}, providerConfig.opts, { profile: function profile(credentials, params, get, callback) { var proof = null; /* eslint camelcase:0 */ if (providerConfig.useProof) { proof = { appsecret_proof: crypto .createHmac('sha256', this.clientSecret) .update(credentials.token) .digest('hex') }; } get(providerConfig.url, proof, function (data) { credentials.profile = { authType: providerName, email: data.email, emailLower: data.email && data.email.toLowerCase(), emailConfirmed: data.verified, name: { firstName: data.given_name || '', lastName: data.family_name || '', displayName: data.name || '' } }; if (providerName === 'google') { credentials.profile.profileImg = data.picture; credentials.profile.googleAuthData = data; } else if (providerName === 'facebook') { credentials.profile.profileImg = 'https://graph.facebook.com/' + data.id + '/picture?width=80&height=80'; credentials.profile.fbAuthData = data; } return callback(); }); } }); }
[ "function", "getProvider", "(", "providerName", ",", "providerConfig", ")", "{", "return", "_", ".", "extend", "(", "{", "}", ",", "providerConfig", ".", "opts", ",", "{", "profile", ":", "function", "profile", "(", "credentials", ",", "params", ",", "get", ",", "callback", ")", "{", "var", "proof", "=", "null", ";", "/* eslint camelcase:0 */", "if", "(", "providerConfig", ".", "useProof", ")", "{", "proof", "=", "{", "appsecret_proof", ":", "crypto", ".", "createHmac", "(", "'sha256'", ",", "this", ".", "clientSecret", ")", ".", "update", "(", "credentials", ".", "token", ")", ".", "digest", "(", "'hex'", ")", "}", ";", "}", "get", "(", "providerConfig", ".", "url", ",", "proof", ",", "function", "(", "data", ")", "{", "credentials", ".", "profile", "=", "{", "authType", ":", "providerName", ",", "email", ":", "data", ".", "email", ",", "emailLower", ":", "data", ".", "email", "&&", "data", ".", "email", ".", "toLowerCase", "(", ")", ",", "emailConfirmed", ":", "data", ".", "verified", ",", "name", ":", "{", "firstName", ":", "data", ".", "given_name", "||", "''", ",", "lastName", ":", "data", ".", "family_name", "||", "''", ",", "displayName", ":", "data", ".", "name", "||", "''", "}", "}", ";", "if", "(", "providerName", "===", "'google'", ")", "{", "credentials", ".", "profile", ".", "profileImg", "=", "data", ".", "picture", ";", "credentials", ".", "profile", ".", "googleAuthData", "=", "data", ";", "}", "else", "if", "(", "providerName", "===", "'facebook'", ")", "{", "credentials", ".", "profile", ".", "profileImg", "=", "'https://graph.facebook.com/'", "+", "data", ".", "id", "+", "'/picture?width=80&height=80'", ";", "credentials", ".", "profile", ".", "fbAuthData", "=", "data", ";", "}", "return", "callback", "(", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Get the provider info which is really opts from the config plus the profile function which sets the values which we will store in the user table in the database @param providerName @param providerConfig @returns {*}
[ "Get", "the", "provider", "info", "which", "is", "really", "opts", "from", "the", "config", "plus", "the", "profile", "function", "which", "sets", "the", "values", "which", "we", "will", "store", "in", "the", "user", "table", "in", "the", "database" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/middleware/mw.auth.social.js#L18-L60
53,294
gethuman/pancakes-recipe
middleware/mw.auth.social.js
init
function init(ctx) { var server = ctx.server; var deferred = Q.defer(); server.register({register: require('bell')}, function (err) { if (err) { deferred.reject(err); return; } _.each(config.security.social, function (providerConfig, providerName) { var opts = _.extend({}, config.security.cookie, { 'cookie': 'bell-' + providerName, 'clientId': providerConfig.appId, 'clientSecret': providerConfig.appSecret, 'isSecure': config.useSSL, 'forceHttps': config.useSSL, 'provider': getProvider(providerName, providerConfig) }); server.auth.strategy(providerName, 'bell', opts); }); deferred.resolve(); }); return deferred.promise.then(function () { return Q.when(ctx); }); }
javascript
function init(ctx) { var server = ctx.server; var deferred = Q.defer(); server.register({register: require('bell')}, function (err) { if (err) { deferred.reject(err); return; } _.each(config.security.social, function (providerConfig, providerName) { var opts = _.extend({}, config.security.cookie, { 'cookie': 'bell-' + providerName, 'clientId': providerConfig.appId, 'clientSecret': providerConfig.appSecret, 'isSecure': config.useSSL, 'forceHttps': config.useSSL, 'provider': getProvider(providerName, providerConfig) }); server.auth.strategy(providerName, 'bell', opts); }); deferred.resolve(); }); return deferred.promise.then(function () { return Q.when(ctx); }); }
[ "function", "init", "(", "ctx", ")", "{", "var", "server", "=", "ctx", ".", "server", ";", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "server", ".", "register", "(", "{", "register", ":", "require", "(", "'bell'", ")", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "deferred", ".", "reject", "(", "err", ")", ";", "return", ";", "}", "_", ".", "each", "(", "config", ".", "security", ".", "social", ",", "function", "(", "providerConfig", ",", "providerName", ")", "{", "var", "opts", "=", "_", ".", "extend", "(", "{", "}", ",", "config", ".", "security", ".", "cookie", ",", "{", "'cookie'", ":", "'bell-'", "+", "providerName", ",", "'clientId'", ":", "providerConfig", ".", "appId", ",", "'clientSecret'", ":", "providerConfig", ".", "appSecret", ",", "'isSecure'", ":", "config", ".", "useSSL", ",", "'forceHttps'", ":", "config", ".", "useSSL", ",", "'provider'", ":", "getProvider", "(", "providerName", ",", "providerConfig", ")", "}", ")", ";", "server", ".", "auth", ".", "strategy", "(", "providerName", ",", "'bell'", ",", "opts", ")", ";", "}", ")", ";", "deferred", ".", "resolve", "(", ")", ";", "}", ")", ";", "return", "deferred", ".", "promise", ".", "then", "(", "function", "(", ")", "{", "return", "Q", ".", "when", "(", "ctx", ")", ";", "}", ")", ";", "}" ]
Use the Hapi Bell plugin to register the social auth providers @param ctx
[ "Use", "the", "Hapi", "Bell", "plugin", "to", "register", "the", "social", "auth", "providers" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/middleware/mw.auth.social.js#L66-L96
53,295
tolokoban/ToloFrameWork
ker/mod/tfw.view.language.js
findLanguageNameFromCode
function findLanguageNameFromCode( languageCode ) { var a = 0; var b = LANGUAGES.length; var m = b; var item, code, name; languageCode = languageCode.toLowerCase(); while( b - a > 1 ) { m = Math.floor( (a + b) / 2 ); item = LANGUAGES[m]; code = item[0]; name = item[1]; if( code == languageCode ) return name; if( languageCode < code ) b = m; else a = m; } return null; }
javascript
function findLanguageNameFromCode( languageCode ) { var a = 0; var b = LANGUAGES.length; var m = b; var item, code, name; languageCode = languageCode.toLowerCase(); while( b - a > 1 ) { m = Math.floor( (a + b) / 2 ); item = LANGUAGES[m]; code = item[0]; name = item[1]; if( code == languageCode ) return name; if( languageCode < code ) b = m; else a = m; } return null; }
[ "function", "findLanguageNameFromCode", "(", "languageCode", ")", "{", "var", "a", "=", "0", ";", "var", "b", "=", "LANGUAGES", ".", "length", ";", "var", "m", "=", "b", ";", "var", "item", ",", "code", ",", "name", ";", "languageCode", "=", "languageCode", ".", "toLowerCase", "(", ")", ";", "while", "(", "b", "-", "a", ">", "1", ")", "{", "m", "=", "Math", ".", "floor", "(", "(", "a", "+", "b", ")", "/", "2", ")", ";", "item", "=", "LANGUAGES", "[", "m", "]", ";", "code", "=", "item", "[", "0", "]", ";", "name", "=", "item", "[", "1", "]", ";", "if", "(", "code", "==", "languageCode", ")", "return", "name", ";", "if", "(", "languageCode", "<", "code", ")", "b", "=", "m", ";", "else", "a", "=", "m", ";", "}", "return", "null", ";", "}" ]
Dichotomic search.
[ "Dichotomic", "search", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/tfw.view.language.js#L135-L153
53,296
hoodiehq-archive/hoodie-plugins-manager
lib/changes_pool.js
function (db, query, callback) { // query parameter is optional if (!callback) { callback = query query = {} } // create a new request object var req = { // db name db: db, // authenticated url to db db_url: url.resolve(couch_url, encodeURIComponent(db)), // used by the update queue workers callback: callback, // store the query parameters query: query } // make sure the request has a since parameter set exports.updateSince(req, function (err, req) { if (err) { return callback(err) } // add the changes request to the pool exports.addToPool(idle, req) // queue the new request for immediate update // exports.refreshDB(updated, idle, db) }) }
javascript
function (db, query, callback) { // query parameter is optional if (!callback) { callback = query query = {} } // create a new request object var req = { // db name db: db, // authenticated url to db db_url: url.resolve(couch_url, encodeURIComponent(db)), // used by the update queue workers callback: callback, // store the query parameters query: query } // make sure the request has a since parameter set exports.updateSince(req, function (err, req) { if (err) { return callback(err) } // add the changes request to the pool exports.addToPool(idle, req) // queue the new request for immediate update // exports.refreshDB(updated, idle, db) }) }
[ "function", "(", "db", ",", "query", ",", "callback", ")", "{", "// query parameter is optional", "if", "(", "!", "callback", ")", "{", "callback", "=", "query", "query", "=", "{", "}", "}", "// create a new request object", "var", "req", "=", "{", "// db name", "db", ":", "db", ",", "// authenticated url to db", "db_url", ":", "url", ".", "resolve", "(", "couch_url", ",", "encodeURIComponent", "(", "db", ")", ")", ",", "// used by the update queue workers", "callback", ":", "callback", ",", "// store the query parameters", "query", ":", "query", "}", "// make sure the request has a since parameter set", "exports", ".", "updateSince", "(", "req", ",", "function", "(", "err", ",", "req", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", "}", "// add the changes request to the pool", "exports", ".", "addToPool", "(", "idle", ",", "req", ")", "// queue the new request for immediate update", "// exports.refreshDB(updated, idle, db)", "}", ")", "}" ]
the public changes feed subscription function
[ "the", "public", "changes", "feed", "subscription", "function" ]
c2d752194b3780f5fa398cccfe0d0e35988f5a0b
https://github.com/hoodiehq-archive/hoodie-plugins-manager/blob/c2d752194b3780f5fa398cccfe0d0e35988f5a0b/lib/changes_pool.js#L80-L110
53,297
eanglay/bayon-core
lib/router.js
registerHandler
function registerHandler(routeItem, headler) { let method = routeItem.method.toLowerCase(); debug( 'Binding "%s" to path "%s" with method "%s"', routeItem.handler, routeItem.path, method.toUpperCase() ); headler.actionHandler = true; components.app[method](routeItem.path, headler); }
javascript
function registerHandler(routeItem, headler) { let method = routeItem.method.toLowerCase(); debug( 'Binding "%s" to path "%s" with method "%s"', routeItem.handler, routeItem.path, method.toUpperCase() ); headler.actionHandler = true; components.app[method](routeItem.path, headler); }
[ "function", "registerHandler", "(", "routeItem", ",", "headler", ")", "{", "let", "method", "=", "routeItem", ".", "method", ".", "toLowerCase", "(", ")", ";", "debug", "(", "'Binding \"%s\" to path \"%s\" with method \"%s\"'", ",", "routeItem", ".", "handler", ",", "routeItem", ".", "path", ",", "method", ".", "toUpperCase", "(", ")", ")", ";", "headler", ".", "actionHandler", "=", "true", ";", "components", ".", "app", "[", "method", "]", "(", "routeItem", ".", "path", ",", "headler", ")", ";", "}" ]
register route path with acually function
[ "register", "route", "path", "with", "acually", "function" ]
96e8ec296433bcf95aeb7d5b27d9fa275b049396
https://github.com/eanglay/bayon-core/blob/96e8ec296433bcf95aeb7d5b27d9fa275b049396/lib/router.js#L13-L21
53,298
eanglay/bayon-core
lib/router.js
routeSolver
function routeSolver(routeItem, handler, resolver) { switch (typeof handler) { case 'function': // solve as function handler registerHandler(routeItem, null, routeItem.handler); break; case 'string': // solve as controller - action handler resolver(routeItem, handler); break; default: throw new Error('unknow route type'); } }
javascript
function routeSolver(routeItem, handler, resolver) { switch (typeof handler) { case 'function': // solve as function handler registerHandler(routeItem, null, routeItem.handler); break; case 'string': // solve as controller - action handler resolver(routeItem, handler); break; default: throw new Error('unknow route type'); } }
[ "function", "routeSolver", "(", "routeItem", ",", "handler", ",", "resolver", ")", "{", "switch", "(", "typeof", "handler", ")", "{", "case", "'function'", ":", "// solve as function handler", "registerHandler", "(", "routeItem", ",", "null", ",", "routeItem", ".", "handler", ")", ";", "break", ";", "case", "'string'", ":", "// solve as controller - action handler", "resolver", "(", "routeItem", ",", "handler", ")", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "'unknow route type'", ")", ";", "}", "}" ]
determine route's type
[ "determine", "route", "s", "type" ]
96e8ec296433bcf95aeb7d5b27d9fa275b049396
https://github.com/eanglay/bayon-core/blob/96e8ec296433bcf95aeb7d5b27d9fa275b049396/lib/router.js#L66-L79
53,299
tolokoban/ToloFrameWork
lib/transpiler.js
transpile
function transpile( sourceCode, sourceName, minify ) { try { const sourceFileName = Path.basename( sourceName ), ast = parseToAST( sourceCode ), transfo = Babel.transformSync( sourceCode, buildOptions( sourceFileName, minify ) ), // transfo = Babel.transformFromAstSync( ast, OPTIONS ), transpiledCode = transfo.code; return { code: `${transpiledCode}\n//# sourceMappingURL=${sourceFileName}.map`, zip: transpiledCode, map: transfo.map, ast }; } catch ( ex ) { console.warn( "================================================================================" ); console.warn( sourceCode ); console.warn( "================================================================================" ); Fatal.fire( `Babel parsing error in ${sourceName}:\n${ex}`, sourceName ); } return null; }
javascript
function transpile( sourceCode, sourceName, minify ) { try { const sourceFileName = Path.basename( sourceName ), ast = parseToAST( sourceCode ), transfo = Babel.transformSync( sourceCode, buildOptions( sourceFileName, minify ) ), // transfo = Babel.transformFromAstSync( ast, OPTIONS ), transpiledCode = transfo.code; return { code: `${transpiledCode}\n//# sourceMappingURL=${sourceFileName}.map`, zip: transpiledCode, map: transfo.map, ast }; } catch ( ex ) { console.warn( "================================================================================" ); console.warn( sourceCode ); console.warn( "================================================================================" ); Fatal.fire( `Babel parsing error in ${sourceName}:\n${ex}`, sourceName ); } return null; }
[ "function", "transpile", "(", "sourceCode", ",", "sourceName", ",", "minify", ")", "{", "try", "{", "const", "sourceFileName", "=", "Path", ".", "basename", "(", "sourceName", ")", ",", "ast", "=", "parseToAST", "(", "sourceCode", ")", ",", "transfo", "=", "Babel", ".", "transformSync", "(", "sourceCode", ",", "buildOptions", "(", "sourceFileName", ",", "minify", ")", ")", ",", "// transfo = Babel.transformFromAstSync( ast, OPTIONS ),", "transpiledCode", "=", "transfo", ".", "code", ";", "return", "{", "code", ":", "`", "${", "transpiledCode", "}", "\\n", "${", "sourceFileName", "}", "`", ",", "zip", ":", "transpiledCode", ",", "map", ":", "transfo", ".", "map", ",", "ast", "}", ";", "}", "catch", "(", "ex", ")", "{", "console", ".", "warn", "(", "\"================================================================================\"", ")", ";", "console", ".", "warn", "(", "sourceCode", ")", ";", "console", ".", "warn", "(", "\"================================================================================\"", ")", ";", "Fatal", ".", "fire", "(", "`", "${", "sourceName", "}", "\\n", "${", "ex", "}", "`", ",", "sourceName", ")", ";", "}", "return", "null", ";", "}" ]
Transpile code into Javascript equivalent that can be read on currently supported browsers. @param {string} sourceCode - Code in cutting edge Javascript. @param {string} sourceName - Name of the file. @param {boolean} minify - Default `false`. @returns {object} The transpiled code and its source map. __code__: code compatible with currently supported browsers. __map__: source map.
[ "Transpile", "code", "into", "Javascript", "equivalent", "that", "can", "be", "read", "on", "currently", "supported", "browsers", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/lib/transpiler.js#L33-L55