repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
b3nsn0w/murmur-random
index.js
subgen
function subgen (key, ...params) { return random(createSeed([...seed, keygen(key), ...params], seed.length)) }
javascript
function subgen (key, ...params) { return random(createSeed([...seed, keygen(key), ...params], seed.length)) }
[ "function", "subgen", "(", "key", ",", "...", "params", ")", "{", "return", "random", "(", "createSeed", "(", "[", "...", "seed", ",", "keygen", "(", "key", ")", ",", "...", "params", "]", ",", "seed", ".", "length", ")", ")", "}" ]
Creates a subgenerator from the current one @param {string} key Key of the subgenerator @param {...number} params Parameters affecting the subgenerator's seed
[ "Creates", "a", "subgenerator", "from", "the", "current", "one" ]
240977106f74fc20583ef0c4f95aaf862a8b3bdc
https://github.com/b3nsn0w/murmur-random/blob/240977106f74fc20583ef0c4f95aaf862a8b3bdc/index.js#L25-L27
train
Industryswarm/isnode-mod-data
lib/mongodb/mongodb/lib/operations/mongo_client_ops.js
logout
function logout(mongoClient, dbName, callback) { mongoClient.topology.logout(dbName, err => { if (err) return callback(err); callback(null, true); }); }
javascript
function logout(mongoClient, dbName, callback) { mongoClient.topology.logout(dbName, err => { if (err) return callback(err); callback(null, true); }); }
[ "function", "logout", "(", "mongoClient", ",", "dbName", ",", "callback", ")", "{", "mongoClient", ".", "topology", ".", "logout", "(", "dbName", ",", "err", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "callback", "(", "null", ",", "true", ")", ";", "}", ")", ";", "}" ]
Logout user from server, fire off on all connections and remove all auth info. @method @param {MongoClient} mongoClient The MongoClient instance on which to logout. @param {object} [options] Optional settings. See MongoClient.prototype.logout for a list of options. @param {Db~resultCallback} [callback] The command result callback
[ "Logout", "user", "from", "server", "fire", "off", "on", "all", "connections", "and", "remove", "all", "auth", "info", "." ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb/lib/operations/mongo_client_ops.js#L483-L488
train
Industryswarm/isnode-mod-data
lib/mongodb/mongodb/lib/operations/mongo_client_ops.js
validOptions
function validOptions(options) { const _validOptions = validOptionNames.concat(legacyOptionNames); for (const name in options) { if (ignoreOptionNames.indexOf(name) !== -1) { continue; } if (_validOptions.indexOf(name) === -1 && options.validateOptions) { return new MongoError(`option ${name} is not supported`); } else if (_validOptions.indexOf(name) === -1) { console.warn(`the options [${name}] is not supported`); } if (legacyOptionNames.indexOf(name) !== -1) { console.warn( `the server/replset/mongos/db options are deprecated, ` + `all their options are supported at the top level of the options object [${validOptionNames}]` ); } } }
javascript
function validOptions(options) { const _validOptions = validOptionNames.concat(legacyOptionNames); for (const name in options) { if (ignoreOptionNames.indexOf(name) !== -1) { continue; } if (_validOptions.indexOf(name) === -1 && options.validateOptions) { return new MongoError(`option ${name} is not supported`); } else if (_validOptions.indexOf(name) === -1) { console.warn(`the options [${name}] is not supported`); } if (legacyOptionNames.indexOf(name) !== -1) { console.warn( `the server/replset/mongos/db options are deprecated, ` + `all their options are supported at the top level of the options object [${validOptionNames}]` ); } } }
[ "function", "validOptions", "(", "options", ")", "{", "const", "_validOptions", "=", "validOptionNames", ".", "concat", "(", "legacyOptionNames", ")", ";", "for", "(", "const", "name", "in", "options", ")", "{", "if", "(", "ignoreOptionNames", ".", "indexOf", "(", "name", ")", "!==", "-", "1", ")", "{", "continue", ";", "}", "if", "(", "_validOptions", ".", "indexOf", "(", "name", ")", "===", "-", "1", "&&", "options", ".", "validateOptions", ")", "{", "return", "new", "MongoError", "(", "`", "${", "name", "}", "`", ")", ";", "}", "else", "if", "(", "_validOptions", ".", "indexOf", "(", "name", ")", "===", "-", "1", ")", "{", "console", ".", "warn", "(", "`", "${", "name", "}", "`", ")", ";", "}", "if", "(", "legacyOptionNames", ".", "indexOf", "(", "name", ")", "!==", "-", "1", ")", "{", "console", ".", "warn", "(", "`", "`", "+", "`", "${", "validOptionNames", "}", "`", ")", ";", "}", "}", "}" ]
Validate options object
[ "Validate", "options", "object" ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb/lib/operations/mongo_client_ops.js#L623-L644
train
boljen/node-buffer-to-messages
index.js
Converter
function Converter() { // Validate arguments if (arguments.length === 1) { this._bl = 2; if (typeof arguments[0] !== "function") throw new TypeError("Converter requires at least a callback function"); else this._fx = arguments[0]; } else if (arguments.length >= 2) { this._bl = arguments[0]; if (this._bl !== 1 && this._bl !== 2 && this._bl !== 4) throw new TypeError("Prefix length must be 1, 2 or 4"); if (typeof arguments[1] !== "function") throw new TypeError("Converter requires a callback function"); else this._fx = arguments[1]; } else { throw new Error("cannot construct a converter without a callback"); } this.flush(); }
javascript
function Converter() { // Validate arguments if (arguments.length === 1) { this._bl = 2; if (typeof arguments[0] !== "function") throw new TypeError("Converter requires at least a callback function"); else this._fx = arguments[0]; } else if (arguments.length >= 2) { this._bl = arguments[0]; if (this._bl !== 1 && this._bl !== 2 && this._bl !== 4) throw new TypeError("Prefix length must be 1, 2 or 4"); if (typeof arguments[1] !== "function") throw new TypeError("Converter requires a callback function"); else this._fx = arguments[1]; } else { throw new Error("cannot construct a converter without a callback"); } this.flush(); }
[ "function", "Converter", "(", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "this", ".", "_bl", "=", "2", ";", "if", "(", "typeof", "arguments", "[", "0", "]", "!==", "\"function\"", ")", "throw", "new", "TypeError", "(", "\"Converter requires at least a callback function\"", ")", ";", "else", "this", ".", "_fx", "=", "arguments", "[", "0", "]", ";", "}", "else", "if", "(", "arguments", ".", "length", ">=", "2", ")", "{", "this", ".", "_bl", "=", "arguments", "[", "0", "]", ";", "if", "(", "this", ".", "_bl", "!==", "1", "&&", "this", ".", "_bl", "!==", "2", "&&", "this", ".", "_bl", "!==", "4", ")", "throw", "new", "TypeError", "(", "\"Prefix length must be 1, 2 or 4\"", ")", ";", "if", "(", "typeof", "arguments", "[", "1", "]", "!==", "\"function\"", ")", "throw", "new", "TypeError", "(", "\"Converter requires a callback function\"", ")", ";", "else", "this", ".", "_fx", "=", "arguments", "[", "1", "]", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"cannot construct a converter without a callback\"", ")", ";", "}", "this", ".", "flush", "(", ")", ";", "}" ]
Takes in a series of Buffers and calls back whenever a fixed-length message has been completely processed. @param {Integer} [prefixLength] - The length in bytes of the size prefix. This argument is optional. The default length is 2 bytes, but can also be 1 or 4 bytes. @param {Function} callback - This will be called every time a new message has been completely processed.
[ "Takes", "in", "a", "series", "of", "Buffers", "and", "calls", "back", "whenever", "a", "fixed", "-", "length", "message", "has", "been", "completely", "processed", "." ]
9362c1677fd284d54040e56de99800a80494522e
https://github.com/boljen/node-buffer-to-messages/blob/9362c1677fd284d54040e56de99800a80494522e/index.js#L15-L43
train
open-nata/nata-device
src/actions/ActionFactory.js
getCommonActions
function getCommonActions(device) { const actions = [] actions.push(new BackAction(device)) actions.push(new HomeAction(device)) actions.push(new MenuAction(device)) actions.push() return actions }
javascript
function getCommonActions(device) { const actions = [] actions.push(new BackAction(device)) actions.push(new HomeAction(device)) actions.push(new MenuAction(device)) actions.push() return actions }
[ "function", "getCommonActions", "(", "device", ")", "{", "const", "actions", "=", "[", "]", "actions", ".", "push", "(", "new", "BackAction", "(", "device", ")", ")", "actions", ".", "push", "(", "new", "HomeAction", "(", "device", ")", ")", "actions", ".", "push", "(", "new", "MenuAction", "(", "device", ")", ")", "actions", ".", "push", "(", ")", "return", "actions", "}" ]
back, home, menu actions
[ "back", "home", "menu", "actions" ]
c2c1292fb0f634eab72e6770ee5b835b67186405
https://github.com/open-nata/nata-device/blob/c2c1292fb0f634eab72e6770ee5b835b67186405/src/actions/ActionFactory.js#L59-L67
train
richRemer/twixt-mutation
mutation.js
mutation
function mutation(target, handler) { target.addEventListener("mutation", function(evt) { handler.call(this, this, evt.mutations); }); }
javascript
function mutation(target, handler) { target.addEventListener("mutation", function(evt) { handler.call(this, this, evt.mutations); }); }
[ "function", "mutation", "(", "target", ",", "handler", ")", "{", "target", ".", "addEventListener", "(", "\"mutation\"", ",", "function", "(", "evt", ")", "{", "handler", ".", "call", "(", "this", ",", "this", ",", "evt", ".", "mutations", ")", ";", "}", ")", ";", "}" ]
Attach mutation event handler. @param {EventTarget} target @param {function} handler
[ "Attach", "mutation", "event", "handler", "." ]
e0b5f3883281888fa21a73a6d190e9d6dfef34e7
https://github.com/richRemer/twixt-mutation/blob/e0b5f3883281888fa21a73a6d190e9d6dfef34e7/mutation.js#L6-L10
train
dennismckinnon/tmsp-server
lib/tmspReader.js
Request
function Request(reqBytes){ var parsed; var err try { parsed = types.Request.decode(reqBytes); } catch (e) { err = e; } //Check for request errors here if(err){ this.BadRequest = true; this.errCode = types.CodeType.EncodingError; this.errMsg = "The request failed to be decoded" } else if(!types.methodLookup[parsed.type]){ //Request type not recognized //Make a request object for the error this.BadRequest = true; this.errCode = types.CodeType.UnknownRequest; this.errMsg = "The request type was not understood" } else { this.BadRequest = false; this.type = parsed.type; this.method = types.methodLookup[this.type]; this.data = parsed.data.buffer.slice(parsed.data.offset); this.dataLength = parsed.data.limit - parsed.data.offset; this.dataLittle = parsed.data.littleEndian; this.key = parsed.key; this.value = parsed.value; } }
javascript
function Request(reqBytes){ var parsed; var err try { parsed = types.Request.decode(reqBytes); } catch (e) { err = e; } //Check for request errors here if(err){ this.BadRequest = true; this.errCode = types.CodeType.EncodingError; this.errMsg = "The request failed to be decoded" } else if(!types.methodLookup[parsed.type]){ //Request type not recognized //Make a request object for the error this.BadRequest = true; this.errCode = types.CodeType.UnknownRequest; this.errMsg = "The request type was not understood" } else { this.BadRequest = false; this.type = parsed.type; this.method = types.methodLookup[this.type]; this.data = parsed.data.buffer.slice(parsed.data.offset); this.dataLength = parsed.data.limit - parsed.data.offset; this.dataLittle = parsed.data.littleEndian; this.key = parsed.key; this.value = parsed.value; } }
[ "function", "Request", "(", "reqBytes", ")", "{", "var", "parsed", ";", "var", "err", "try", "{", "parsed", "=", "types", ".", "Request", ".", "decode", "(", "reqBytes", ")", ";", "}", "catch", "(", "e", ")", "{", "err", "=", "e", ";", "}", "if", "(", "err", ")", "{", "this", ".", "BadRequest", "=", "true", ";", "this", ".", "errCode", "=", "types", ".", "CodeType", ".", "EncodingError", ";", "this", ".", "errMsg", "=", "\"The request failed to be decoded\"", "}", "else", "if", "(", "!", "types", ".", "methodLookup", "[", "parsed", ".", "type", "]", ")", "{", "this", ".", "BadRequest", "=", "true", ";", "this", ".", "errCode", "=", "types", ".", "CodeType", ".", "UnknownRequest", ";", "this", ".", "errMsg", "=", "\"The request type was not understood\"", "}", "else", "{", "this", ".", "BadRequest", "=", "false", ";", "this", ".", "type", "=", "parsed", ".", "type", ";", "this", ".", "method", "=", "types", ".", "methodLookup", "[", "this", ".", "type", "]", ";", "this", ".", "data", "=", "parsed", ".", "data", ".", "buffer", ".", "slice", "(", "parsed", ".", "data", ".", "offset", ")", ";", "this", ".", "dataLength", "=", "parsed", ".", "data", ".", "limit", "-", "parsed", ".", "data", ".", "offset", ";", "this", ".", "dataLittle", "=", "parsed", ".", "data", ".", "littleEndian", ";", "this", ".", "key", "=", "parsed", ".", "key", ";", "this", ".", "value", "=", "parsed", ".", "value", ";", "}", "}" ]
The Request object unlike in http requests is static So this stream is built to return it rather then the standard buffer. this means any consumer of this stream would need to take account of this fact
[ "The", "Request", "object", "unlike", "in", "http", "requests", "is", "static", "So", "this", "stream", "is", "built", "to", "return", "it", "rather", "then", "the", "standard", "buffer", ".", "this", "means", "any", "consumer", "of", "this", "stream", "would", "need", "to", "take", "account", "of", "this", "fact" ]
24d054c5a3eeacc6552645a2e3a7ed353112b171
https://github.com/dennismckinnon/tmsp-server/blob/24d054c5a3eeacc6552645a2e3a7ed353112b171/lib/tmspReader.js#L133-L166
train
jeremyckahn/bezierizer
dist/jquery.dragon.js
fire
function fire (event, $el, evt) { var handler = $el.data('dragon-opts')[event]; // Patch the proxied Event Object evt.target = $el[0]; if (handler) { handler(evt); } $el.trigger(event); }
javascript
function fire (event, $el, evt) { var handler = $el.data('dragon-opts')[event]; // Patch the proxied Event Object evt.target = $el[0]; if (handler) { handler(evt); } $el.trigger(event); }
[ "function", "fire", "(", "event", ",", "$el", ",", "evt", ")", "{", "var", "handler", "=", "$el", ".", "data", "(", "'dragon-opts'", ")", "[", "event", "]", ";", "evt", ".", "target", "=", "$el", "[", "0", "]", ";", "if", "(", "handler", ")", "{", "handler", "(", "evt", ")", ";", "}", "$el", ".", "trigger", "(", "event", ")", ";", "}" ]
Yep, you only get to bind one event handler. Much faster this way.
[ "Yep", "you", "only", "get", "to", "bind", "one", "event", "handler", ".", "Much", "faster", "this", "way", "." ]
f1886b556279875bbb0da5051f7b716727b28768
https://github.com/jeremyckahn/bezierizer/blob/f1886b556279875bbb0da5051f7b716727b28768/dist/jquery.dragon.js#L209-L218
train
mnichols/ankh
lib/component-model.js
ComponentModel
function ComponentModel(key, impl, cfg) { this.key = key /** * @property {Any} impl The implementation to use for `resolve` * */ this.impl =impl this._cfg = cfg || {} /** * @property {Array} inject The {String} dependencies array a service may declare * */ this.inject = (this.impl.inject || []) /** * @property {String} initializable The method to invoke on an resolved service just after resolution, but before returning * injecting any dependencies found on that method * */ this.initializable = (this.impl.initializable || false) /** * @property {String} startable The method to invoke on an resolved services when started. Usually during an app bootstrap. * */ this.startable = (this.impl.startable || false) }
javascript
function ComponentModel(key, impl, cfg) { this.key = key /** * @property {Any} impl The implementation to use for `resolve` * */ this.impl =impl this._cfg = cfg || {} /** * @property {Array} inject The {String} dependencies array a service may declare * */ this.inject = (this.impl.inject || []) /** * @property {String} initializable The method to invoke on an resolved service just after resolution, but before returning * injecting any dependencies found on that method * */ this.initializable = (this.impl.initializable || false) /** * @property {String} startable The method to invoke on an resolved services when started. Usually during an app bootstrap. * */ this.startable = (this.impl.startable || false) }
[ "function", "ComponentModel", "(", "key", ",", "impl", ",", "cfg", ")", "{", "this", ".", "key", "=", "key", "this", ".", "impl", "=", "impl", "this", ".", "_cfg", "=", "cfg", "||", "{", "}", "this", ".", "inject", "=", "(", "this", ".", "impl", ".", "inject", "||", "[", "]", ")", "this", ".", "initializable", "=", "(", "this", ".", "impl", ".", "initializable", "||", "false", ")", "this", ".", "startable", "=", "(", "this", ".", "impl", ".", "startable", "||", "false", ")", "}" ]
Describes the model for resolving a service @class ComponentModel
[ "Describes", "the", "model", "for", "resolving", "a", "service" ]
b5f6eae24b2dece4025b4f11cea7f1560d3b345f
https://github.com/mnichols/ankh/blob/b5f6eae24b2dece4025b4f11cea7f1560d3b345f/lib/component-model.js#L9-L29
train
JohnnieFucker/dreamix-admin
lib/modules/monitorLog.js
fetchLogs
function fetchLogs(root, msg, callback) { const number = msg.number; const logfile = msg.logfile; const serverId = msg.serverId; const filePath = path.join(root, getLogFileName(logfile, serverId)); const endLogs = []; exec(`tail -n ${number} ${filePath}`, (error, output) => { const endOut = []; output = output.replace(/^\s+|\s+$/g, '').split(/\s+/); for (let i = 5; i < output.length; i += 6) { endOut.push(output[i]); } const endLength = endOut.length; for (let j = 0; j < endLength; j++) { const map = {}; let json; try { json = JSON.parse(endOut[j]); } catch (e) { logger.error(`the log cannot parsed to json, ${e}`); continue; // eslint-disable-line } map.time = json.time; map.route = json.route || json.service; map.serverId = serverId; map.timeUsed = json.timeUsed; map.params = endOut[j]; endLogs.push(map); } callback({ logfile: logfile, dataArray: endLogs }); }); }
javascript
function fetchLogs(root, msg, callback) { const number = msg.number; const logfile = msg.logfile; const serverId = msg.serverId; const filePath = path.join(root, getLogFileName(logfile, serverId)); const endLogs = []; exec(`tail -n ${number} ${filePath}`, (error, output) => { const endOut = []; output = output.replace(/^\s+|\s+$/g, '').split(/\s+/); for (let i = 5; i < output.length; i += 6) { endOut.push(output[i]); } const endLength = endOut.length; for (let j = 0; j < endLength; j++) { const map = {}; let json; try { json = JSON.parse(endOut[j]); } catch (e) { logger.error(`the log cannot parsed to json, ${e}`); continue; // eslint-disable-line } map.time = json.time; map.route = json.route || json.service; map.serverId = serverId; map.timeUsed = json.timeUsed; map.params = endOut[j]; endLogs.push(map); } callback({ logfile: logfile, dataArray: endLogs }); }); }
[ "function", "fetchLogs", "(", "root", ",", "msg", ",", "callback", ")", "{", "const", "number", "=", "msg", ".", "number", ";", "const", "logfile", "=", "msg", ".", "logfile", ";", "const", "serverId", "=", "msg", ".", "serverId", ";", "const", "filePath", "=", "path", ".", "join", "(", "root", ",", "getLogFileName", "(", "logfile", ",", "serverId", ")", ")", ";", "const", "endLogs", "=", "[", "]", ";", "exec", "(", "`", "${", "number", "}", "${", "filePath", "}", "`", ",", "(", "error", ",", "output", ")", "=>", "{", "const", "endOut", "=", "[", "]", ";", "output", "=", "output", ".", "replace", "(", "/", "^\\s+|\\s+$", "/", "g", ",", "''", ")", ".", "split", "(", "/", "\\s+", "/", ")", ";", "for", "(", "let", "i", "=", "5", ";", "i", "<", "output", ".", "length", ";", "i", "+=", "6", ")", "{", "endOut", ".", "push", "(", "output", "[", "i", "]", ")", ";", "}", "const", "endLength", "=", "endOut", ".", "length", ";", "for", "(", "let", "j", "=", "0", ";", "j", "<", "endLength", ";", "j", "++", ")", "{", "const", "map", "=", "{", "}", ";", "let", "json", ";", "try", "{", "json", "=", "JSON", ".", "parse", "(", "endOut", "[", "j", "]", ")", ";", "}", "catch", "(", "e", ")", "{", "logger", ".", "error", "(", "`", "${", "e", "}", "`", ")", ";", "continue", ";", "}", "map", ".", "time", "=", "json", ".", "time", ";", "map", ".", "route", "=", "json", ".", "route", "||", "json", ".", "service", ";", "map", ".", "serverId", "=", "serverId", ";", "map", ".", "timeUsed", "=", "json", ".", "timeUsed", ";", "map", ".", "params", "=", "endOut", "[", "j", "]", ";", "endLogs", ".", "push", "(", "map", ")", ";", "}", "callback", "(", "{", "logfile", ":", "logfile", ",", "dataArray", ":", "endLogs", "}", ")", ";", "}", ")", ";", "}" ]
get the latest logs
[ "get", "the", "latest", "logs" ]
fc169e2481d5a7456725fb33f7a7907e0776ef79
https://github.com/JohnnieFucker/dreamix-admin/blob/fc169e2481d5a7456725fb33f7a7907e0776ef79/lib/modules/monitorLog.js#L13-L48
train
Wiredcraft/carcass-config
proto/config.js
function(parser) { return highland.map(function(item) { if (_.isFunction(parser)) { return parser(item); } if (_.isObject(parser) && (parser.parse != null)) { return parser.parse(item); } return item; }); }
javascript
function(parser) { return highland.map(function(item) { if (_.isFunction(parser)) { return parser(item); } if (_.isObject(parser) && (parser.parse != null)) { return parser.parse(item); } return item; }); }
[ "function", "(", "parser", ")", "{", "return", "highland", ".", "map", "(", "function", "(", "item", ")", "{", "if", "(", "_", ".", "isFunction", "(", "parser", ")", ")", "{", "return", "parser", "(", "item", ")", ";", "}", "if", "(", "_", ".", "isObject", "(", "parser", ")", "&&", "(", "parser", ".", "parse", "!=", "null", ")", ")", "{", "return", "parser", ".", "parse", "(", "item", ")", ";", "}", "return", "item", ";", "}", ")", ";", "}" ]
Builder; returns a function which can be used to map a stream with a given parser. @param {Function|Object} parser can be either a function or an object, in which case the parser.parse() will be used. @return {Function} curried map(). @private
[ "Builder", ";", "returns", "a", "function", "which", "can", "be", "used", "to", "map", "a", "stream", "with", "a", "given", "parser", "." ]
bb1dce284acfb40d2c23a989fe7b5ee4e2221bab
https://github.com/Wiredcraft/carcass-config/blob/bb1dce284acfb40d2c23a989fe7b5ee4e2221bab/proto/config.js#L45-L55
train
Wiredcraft/carcass-config
proto/config.js
function(done) { var p, parser, stream, _i, _len; parser = this.parser(); stream = highland(this.source()); if (_.isArray(parser)) { for (_i = 0, _len = parser.length; _i < _len; _i++) { p = parser[_i]; stream = this._mapWith(p)(stream).flatten().compact(); } } else { stream = this._mapWith(parser)(stream).flatten().compact(); } stream = stream.reduce({}, _.merge); if (done == null) { return stream; } stream.pull(done); return this; }
javascript
function(done) { var p, parser, stream, _i, _len; parser = this.parser(); stream = highland(this.source()); if (_.isArray(parser)) { for (_i = 0, _len = parser.length; _i < _len; _i++) { p = parser[_i]; stream = this._mapWith(p)(stream).flatten().compact(); } } else { stream = this._mapWith(parser)(stream).flatten().compact(); } stream = stream.reduce({}, _.merge); if (done == null) { return stream; } stream.pull(done); return this; }
[ "function", "(", "done", ")", "{", "var", "p", ",", "parser", ",", "stream", ",", "_i", ",", "_len", ";", "parser", "=", "this", ".", "parser", "(", ")", ";", "stream", "=", "highland", "(", "this", ".", "source", "(", ")", ")", ";", "if", "(", "_", ".", "isArray", "(", "parser", ")", ")", "{", "for", "(", "_i", "=", "0", ",", "_len", "=", "parser", ".", "length", ";", "_i", "<", "_len", ";", "_i", "++", ")", "{", "p", "=", "parser", "[", "_i", "]", ";", "stream", "=", "this", ".", "_mapWith", "(", "p", ")", "(", "stream", ")", ".", "flatten", "(", ")", ".", "compact", "(", ")", ";", "}", "}", "else", "{", "stream", "=", "this", ".", "_mapWith", "(", "parser", ")", "(", "stream", ")", ".", "flatten", "(", ")", ".", "compact", "(", ")", ";", "}", "stream", "=", "stream", ".", "reduce", "(", "{", "}", ",", "_", ".", "merge", ")", ";", "if", "(", "done", "==", "null", ")", "{", "return", "stream", ";", "}", "stream", ".", "pull", "(", "done", ")", ";", "return", "this", ";", "}" ]
Loads all the sources and parses with a given parser, and merges the results together. Bad results (false, null, undefined) are skipped. @param {Function|null} done the callback, if provided, will be called with the result, and if not provided, the stream will be returned. @return {this|stream} depends on whether a callback is provided. @private
[ "Loads", "all", "the", "sources", "and", "parses", "with", "a", "given", "parser", "and", "merges", "the", "results", "together", "." ]
bb1dce284acfb40d2c23a989fe7b5ee4e2221bab
https://github.com/Wiredcraft/carcass-config/blob/bb1dce284acfb40d2c23a989fe7b5ee4e2221bab/proto/config.js#L70-L88
train
LOKE/loke-config
lib/merge-into.js
mergeInto
function mergeInto(target, source) { var a = target; var b = source; if (a && b) { for (var key in b) { if (!(key in a)) { continue; } if (typeof b[key] === 'object' && !Array.isArray(b[key]) && b[key] !== null) { mergeInto(a[key], b[key]); } else { a[key] = b[key]; } } } return a; }
javascript
function mergeInto(target, source) { var a = target; var b = source; if (a && b) { for (var key in b) { if (!(key in a)) { continue; } if (typeof b[key] === 'object' && !Array.isArray(b[key]) && b[key] !== null) { mergeInto(a[key], b[key]); } else { a[key] = b[key]; } } } return a; }
[ "function", "mergeInto", "(", "target", ",", "source", ")", "{", "var", "a", "=", "target", ";", "var", "b", "=", "source", ";", "if", "(", "a", "&&", "b", ")", "{", "for", "(", "var", "key", "in", "b", ")", "{", "if", "(", "!", "(", "key", "in", "a", ")", ")", "{", "continue", ";", "}", "if", "(", "typeof", "b", "[", "key", "]", "===", "'object'", "&&", "!", "Array", ".", "isArray", "(", "b", "[", "key", "]", ")", "&&", "b", "[", "key", "]", "!==", "null", ")", "{", "mergeInto", "(", "a", "[", "key", "]", ",", "b", "[", "key", "]", ")", ";", "}", "else", "{", "a", "[", "key", "]", "=", "b", "[", "key", "]", ";", "}", "}", "}", "return", "a", ";", "}" ]
Merges properties from source into target. target will be modified as a result of this function. @param {Object} target The target object to merge the source into. Source values will override those in the target object. @param {Object} source The source object to get override values from. @return {Object} The target object (with source values merged into it)
[ "Merges", "properties", "from", "source", "into", "target", ".", "target", "will", "be", "modified", "as", "a", "result", "of", "this", "function", "." ]
84c207b2724c919bc6dde5efd7e7328591908cce
https://github.com/LOKE/loke-config/blob/84c207b2724c919bc6dde5efd7e7328591908cce/lib/merge-into.js#L12-L29
train
epii-io/epii-node-render
kernel/assist.js
tryWatch
function tryWatch(target, callback) { if (!target) { return logger.halt('invalid watch target') } if (!callback || typeof callback !== 'function') { return logger.halt('invalid watch callback') } return fs.watch( target, { persistent: true, recursive: true}, function (e, file) { // todo: exact watch callback(e, file) } ) }
javascript
function tryWatch(target, callback) { if (!target) { return logger.halt('invalid watch target') } if (!callback || typeof callback !== 'function') { return logger.halt('invalid watch callback') } return fs.watch( target, { persistent: true, recursive: true}, function (e, file) { // todo: exact watch callback(e, file) } ) }
[ "function", "tryWatch", "(", "target", ",", "callback", ")", "{", "if", "(", "!", "target", ")", "{", "return", "logger", ".", "halt", "(", "'invalid watch target'", ")", "}", "if", "(", "!", "callback", "||", "typeof", "callback", "!==", "'function'", ")", "{", "return", "logger", ".", "halt", "(", "'invalid watch callback'", ")", "}", "return", "fs", ".", "watch", "(", "target", ",", "{", "persistent", ":", "true", ",", "recursive", ":", "true", "}", ",", "function", "(", "e", ",", "file", ")", "{", "callback", "(", "e", ",", "file", ")", "}", ")", "}" ]
try to watch with custom callback @param {String} target @param {Function} callback @return {Object} fs.Watcher
[ "try", "to", "watch", "with", "custom", "callback" ]
e8afa57066251e173b3a6455d47218c95f30f563
https://github.com/epii-io/epii-node-render/blob/e8afa57066251e173b3a6455d47218c95f30f563/kernel/assist.js#L30-L45
train
epii-io/epii-node-render
kernel/assist.js
getBabelConfig
function getBabelConfig(env) { var babelrcPath = path.join(__dirname, '.babelrc') var babelrc = JSON.parse(fs.readFileSync(babelrcPath)) babelrc.presets = resolve( babelrc.presets.map(preset => 'babel-preset-' + preset) ) if (!babelrc.plugins) babelrc.plugins = [] return babelrc }
javascript
function getBabelConfig(env) { var babelrcPath = path.join(__dirname, '.babelrc') var babelrc = JSON.parse(fs.readFileSync(babelrcPath)) babelrc.presets = resolve( babelrc.presets.map(preset => 'babel-preset-' + preset) ) if (!babelrc.plugins) babelrc.plugins = [] return babelrc }
[ "function", "getBabelConfig", "(", "env", ")", "{", "var", "babelrcPath", "=", "path", ".", "join", "(", "__dirname", ",", "'.babelrc'", ")", "var", "babelrc", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "babelrcPath", ")", ")", "babelrc", ".", "presets", "=", "resolve", "(", "babelrc", ".", "presets", ".", "map", "(", "preset", "=>", "'babel-preset-'", "+", "preset", ")", ")", "if", "(", "!", "babelrc", ".", "plugins", ")", "babelrc", ".", "plugins", "=", "[", "]", "return", "babelrc", "}" ]
get babel config @param {String} env @return {Object} babel config
[ "get", "babel", "config" ]
e8afa57066251e173b3a6455d47218c95f30f563
https://github.com/epii-io/epii-node-render/blob/e8afa57066251e173b3a6455d47218c95f30f563/kernel/assist.js#L53-L61
train
tniedbala/jxh
lib/renderUtility.js
isNested
function isNested(obj) { if (getType(obj)==='object') { for (let tag in obj) { if (tag != TEXT && !ATTRTAG.test(tag)) { return true; } } } }
javascript
function isNested(obj) { if (getType(obj)==='object') { for (let tag in obj) { if (tag != TEXT && !ATTRTAG.test(tag)) { return true; } } } }
[ "function", "isNested", "(", "obj", ")", "{", "if", "(", "getType", "(", "obj", ")", "===", "'object'", ")", "{", "for", "(", "let", "tag", "in", "obj", ")", "{", "if", "(", "tag", "!=", "TEXT", "&&", "!", "ATTRTAG", ".", "test", "(", "tag", ")", ")", "{", "return", "true", ";", "}", "}", "}", "}" ]
test if object contains nested elements
[ "test", "if", "object", "contains", "nested", "elements" ]
83d699b126c5c7099ffea1f86ccacf5ec50ee6a9
https://github.com/tniedbala/jxh/blob/83d699b126c5c7099ffea1f86ccacf5ec50ee6a9/lib/renderUtility.js#L83-L91
train
tniedbala/jxh
lib/renderUtility.js
getAttributes
function getAttributes(obj) { let attrString = ''; let attrArray = Object.keys(obj); for (let tag of attrArray) { if (tag != ATTR && ATTRTAG.test(tag)) { attrString += ` ${tag.replace('_', '')}="${obj[tag]}"`; } } if (ATTR in obj) { attrString += ' ' + obj[ATTR]; } return attrString; }
javascript
function getAttributes(obj) { let attrString = ''; let attrArray = Object.keys(obj); for (let tag of attrArray) { if (tag != ATTR && ATTRTAG.test(tag)) { attrString += ` ${tag.replace('_', '')}="${obj[tag]}"`; } } if (ATTR in obj) { attrString += ' ' + obj[ATTR]; } return attrString; }
[ "function", "getAttributes", "(", "obj", ")", "{", "let", "attrString", "=", "''", ";", "let", "attrArray", "=", "Object", ".", "keys", "(", "obj", ")", ";", "for", "(", "let", "tag", "of", "attrArray", ")", "{", "if", "(", "tag", "!=", "ATTR", "&&", "ATTRTAG", ".", "test", "(", "tag", ")", ")", "{", "attrString", "+=", "`", "${", "tag", ".", "replace", "(", "'_'", ",", "''", ")", "}", "${", "obj", "[", "tag", "]", "}", "`", ";", "}", "}", "if", "(", "ATTR", "in", "obj", ")", "{", "attrString", "+=", "' '", "+", "obj", "[", "ATTR", "]", ";", "}", "return", "attrString", ";", "}" ]
return attribute string
[ "return", "attribute", "string" ]
83d699b126c5c7099ffea1f86ccacf5ec50ee6a9
https://github.com/tniedbala/jxh/blob/83d699b126c5c7099ffea1f86ccacf5ec50ee6a9/lib/renderUtility.js#L93-L105
train
tniedbala/jxh
lib/renderUtility.js
getType
function getType(obj) { let typeStr = typeof(obj); if (obj) { return Array.isArray(obj) ? 'array' : typeStr; } else { switch (typeStr) { case 'number': return obj === 0 ? 'number' : 'NaN'; case 'object': return 'null'; default: return typeStr; } } }
javascript
function getType(obj) { let typeStr = typeof(obj); if (obj) { return Array.isArray(obj) ? 'array' : typeStr; } else { switch (typeStr) { case 'number': return obj === 0 ? 'number' : 'NaN'; case 'object': return 'null'; default: return typeStr; } } }
[ "function", "getType", "(", "obj", ")", "{", "let", "typeStr", "=", "typeof", "(", "obj", ")", ";", "if", "(", "obj", ")", "{", "return", "Array", ".", "isArray", "(", "obj", ")", "?", "'array'", ":", "typeStr", ";", "}", "else", "{", "switch", "(", "typeStr", ")", "{", "case", "'number'", ":", "return", "obj", "===", "0", "?", "'number'", ":", "'NaN'", ";", "case", "'object'", ":", "return", "'null'", ";", "default", ":", "return", "typeStr", ";", "}", "}", "}" ]
returns type of obj, specifying array, NaN & null values
[ "returns", "type", "of", "obj", "specifying", "array", "NaN", "&", "null", "values" ]
83d699b126c5c7099ffea1f86ccacf5ec50ee6a9
https://github.com/tniedbala/jxh/blob/83d699b126c5c7099ffea1f86ccacf5ec50ee6a9/lib/renderUtility.js#L115-L129
train
henrytao-me/grunt-express-middleware
lib/util.js
injectWatcher
function injectWatcher(handler) { return function(module, filename) { fs.watchFile(filename, watcher); handler(module, filename); }; }
javascript
function injectWatcher(handler) { return function(module, filename) { fs.watchFile(filename, watcher); handler(module, filename); }; }
[ "function", "injectWatcher", "(", "handler", ")", "{", "return", "function", "(", "module", ",", "filename", ")", "{", "fs", ".", "watchFile", "(", "filename", ",", "watcher", ")", ";", "handler", "(", "module", ",", "filename", ")", ";", "}", ";", "}" ]
hijack each module extension handler, and watch the file
[ "hijack", "each", "module", "extension", "handler", "and", "watch", "the", "file" ]
26a902c60a4569dc65bf544ad91bd63d30f58c04
https://github.com/henrytao-me/grunt-express-middleware/blob/26a902c60a4569dc65bf544ad91bd63d30f58c04/lib/util.js#L26-L31
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/scriptloader.js
loadNext
function loadNext() { var script; if ( ( script = pending[ 0 ] ) ) this.load( script.scriptUrl, script.callback, CKEDITOR, 0 ); }
javascript
function loadNext() { var script; if ( ( script = pending[ 0 ] ) ) this.load( script.scriptUrl, script.callback, CKEDITOR, 0 ); }
[ "function", "loadNext", "(", ")", "{", "var", "script", ";", "if", "(", "(", "script", "=", "pending", "[", "0", "]", ")", ")", "this", ".", "load", "(", "script", ".", "scriptUrl", ",", "script", ".", "callback", ",", "CKEDITOR", ",", "0", ")", ";", "}" ]
Loads the very first script from queue and removes it.
[ "Loads", "the", "very", "first", "script", "from", "queue", "and", "removes", "it", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/scriptloader.js#L173-L178
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/scriptloader.js
callbackWrapper
function callbackWrapper() { callback && callback.apply( this, arguments ); // Removed the just loaded script from the queue. pending.shift(); loadNext.call( that ); }
javascript
function callbackWrapper() { callback && callback.apply( this, arguments ); // Removed the just loaded script from the queue. pending.shift(); loadNext.call( that ); }
[ "function", "callbackWrapper", "(", ")", "{", "callback", "&&", "callback", ".", "apply", "(", "this", ",", "arguments", ")", ";", "pending", ".", "shift", "(", ")", ";", "loadNext", ".", "call", "(", "that", ")", ";", "}" ]
This callback calls the standard callback for the script and loads the very next script from pending list.
[ "This", "callback", "calls", "the", "standard", "callback", "for", "the", "script", "and", "loads", "the", "very", "next", "script", "from", "pending", "list", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/scriptloader.js#L185-L192
train
darrencruse/sugarlisp-core
lexer.js
Lexer
function Lexer(sourcetext, filename, options) { options = options || {}; this.options = options || {}; this.dialects = []; // the "stack" dialects are pushed/popped from if(filename) { this.filename = filename; this.fileext = utils.getFileExt(filename, "sugar"); } this.set_source_text(sourcetext); }
javascript
function Lexer(sourcetext, filename, options) { options = options || {}; this.options = options || {}; this.dialects = []; // the "stack" dialects are pushed/popped from if(filename) { this.filename = filename; this.fileext = utils.getFileExt(filename, "sugar"); } this.set_source_text(sourcetext); }
[ "function", "Lexer", "(", "sourcetext", ",", "filename", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "dialects", "=", "[", "]", ";", "if", "(", "filename", ")", "{", "this", ".", "filename", "=", "filename", ";", "this", ".", "fileext", "=", "utils", ".", "getFileExt", "(", "filename", ",", "\"sugar\"", ")", ";", "}", "this", ".", "set_source_text", "(", "sourcetext", ")", ";", "}" ]
A Lexer for the source text we are scanning note: Lexer has been done as a javacript prototypal class with instances that hold all state for a given source file as it's being read and transpiled. This is in contrast to the other sugarlisp modules which are pretty much stateless collections of functions. The main exception to this is the "transpiler-context" which is the non-source-file related state of the transpiler (essentially a "singleton").
[ "A", "Lexer", "for", "the", "source", "text", "we", "are", "scanning" ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/lexer.js#L33-L42
train
darrencruse/sugarlisp-core
lexer.js
regexes_for_category
function regexes_for_category(lexer, category) { var REs = []; var done = false; for(var i = 0; !done && i < lexer.dialects.length; i++) { var dialect = lexer.dialects[i]; if(dialect.lextab) { var categoryentry = dialect.lextab.find(function(lextabentry) { return lextabentry.category == category; }); if(categoryentry) { REs.push(categoryentry.match); // if they've set entry.replace=true this dialect's // entry replaces other dialects' entries: done = categoryentry.replace; } } } return REs; }
javascript
function regexes_for_category(lexer, category) { var REs = []; var done = false; for(var i = 0; !done && i < lexer.dialects.length; i++) { var dialect = lexer.dialects[i]; if(dialect.lextab) { var categoryentry = dialect.lextab.find(function(lextabentry) { return lextabentry.category == category; }); if(categoryentry) { REs.push(categoryentry.match); // if they've set entry.replace=true this dialect's // entry replaces other dialects' entries: done = categoryentry.replace; } } } return REs; }
[ "function", "regexes_for_category", "(", "lexer", ",", "category", ")", "{", "var", "REs", "=", "[", "]", ";", "var", "done", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "!", "done", "&&", "i", "<", "lexer", ".", "dialects", ".", "length", ";", "i", "++", ")", "{", "var", "dialect", "=", "lexer", ".", "dialects", "[", "i", "]", ";", "if", "(", "dialect", ".", "lextab", ")", "{", "var", "categoryentry", "=", "dialect", ".", "lextab", ".", "find", "(", "function", "(", "lextabentry", ")", "{", "return", "lextabentry", ".", "category", "==", "category", ";", "}", ")", ";", "if", "(", "categoryentry", ")", "{", "REs", ".", "push", "(", "categoryentry", ".", "match", ")", ";", "done", "=", "categoryentry", ".", "replace", ";", "}", "}", "}", "return", "REs", ";", "}" ]
utility function accumulates all the regular expressions for a given token category and returns them in an array
[ "utility", "function", "accumulates", "all", "the", "regular", "expressions", "for", "a", "given", "token", "category", "and", "returns", "them", "in", "an", "array" ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/lexer.js#L585-L604
train
darrencruse/sugarlisp-core
lexer.js
oncharincategory
function oncharincategory(lexer, lookahead, categoryREs) { var c = lexer.peek_char(lookahead); return categoryREs.find(function(re) { // because we're matching a single char... re.lastIndex = 0; // make sure we start from the start return re.test(c); }); }
javascript
function oncharincategory(lexer, lookahead, categoryREs) { var c = lexer.peek_char(lookahead); return categoryREs.find(function(re) { // because we're matching a single char... re.lastIndex = 0; // make sure we start from the start return re.test(c); }); }
[ "function", "oncharincategory", "(", "lexer", ",", "lookahead", ",", "categoryREs", ")", "{", "var", "c", "=", "lexer", ".", "peek_char", "(", "lookahead", ")", ";", "return", "categoryREs", ".", "find", "(", "function", "(", "re", ")", "{", "re", ".", "lastIndex", "=", "0", ";", "return", "re", ".", "test", "(", "c", ")", ";", "}", ")", ";", "}" ]
is the source sitting on a char matching a specified token category?
[ "is", "the", "source", "sitting", "on", "a", "char", "matching", "a", "specified", "token", "category?" ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/lexer.js#L609-L616
train
darrencruse/sugarlisp-core
lexer.js
next_lextab_token
function next_lextab_token(lexer) { var token; if(lexer.eos()) { return undefined; } // skip leading whitespace or comments... lexer.skip_filler(); var previouslyPeeked = lexer.getPeekedToken(); if(previouslyPeeked) { return previouslyPeeked; } lexer.mark_token_start(); trace(lexer.message_src_loc("", lexer, {file:false})); // try and match all token categories except punctuation (and // the default handler). Note that single character punctuation // should take a back seat to longer symbols e.g. '...' should // match before '.'. token = match_in_lextabs(lexer, {omit: ['punctuation','default']}); if(!token) { // okay now try again matching punctuation characters. token = match_in_lextabs(lexer, {include: ['punctuation']}); } if(!token) { // ok go ahead and try any default handler(s) token = match_in_lextabs(lexer, {include: ['default']}); } // we expect they will use an explicit default lextab entry, but JIC: if(!token) { trace('their lextab has no default handler - defaulting to next word'); token = lexer.next_word_token(); if(token) { token.category = 'symbol'; } } return token; }
javascript
function next_lextab_token(lexer) { var token; if(lexer.eos()) { return undefined; } // skip leading whitespace or comments... lexer.skip_filler(); var previouslyPeeked = lexer.getPeekedToken(); if(previouslyPeeked) { return previouslyPeeked; } lexer.mark_token_start(); trace(lexer.message_src_loc("", lexer, {file:false})); // try and match all token categories except punctuation (and // the default handler). Note that single character punctuation // should take a back seat to longer symbols e.g. '...' should // match before '.'. token = match_in_lextabs(lexer, {omit: ['punctuation','default']}); if(!token) { // okay now try again matching punctuation characters. token = match_in_lextabs(lexer, {include: ['punctuation']}); } if(!token) { // ok go ahead and try any default handler(s) token = match_in_lextabs(lexer, {include: ['default']}); } // we expect they will use an explicit default lextab entry, but JIC: if(!token) { trace('their lextab has no default handler - defaulting to next word'); token = lexer.next_word_token(); if(token) { token.category = 'symbol'; } } return token; }
[ "function", "next_lextab_token", "(", "lexer", ")", "{", "var", "token", ";", "if", "(", "lexer", ".", "eos", "(", ")", ")", "{", "return", "undefined", ";", "}", "lexer", ".", "skip_filler", "(", ")", ";", "var", "previouslyPeeked", "=", "lexer", ".", "getPeekedToken", "(", ")", ";", "if", "(", "previouslyPeeked", ")", "{", "return", "previouslyPeeked", ";", "}", "lexer", ".", "mark_token_start", "(", ")", ";", "trace", "(", "lexer", ".", "message_src_loc", "(", "\"\"", ",", "lexer", ",", "{", "file", ":", "false", "}", ")", ")", ";", "token", "=", "match_in_lextabs", "(", "lexer", ",", "{", "omit", ":", "[", "'punctuation'", ",", "'default'", "]", "}", ")", ";", "if", "(", "!", "token", ")", "{", "token", "=", "match_in_lextabs", "(", "lexer", ",", "{", "include", ":", "[", "'punctuation'", "]", "}", ")", ";", "}", "if", "(", "!", "token", ")", "{", "token", "=", "match_in_lextabs", "(", "lexer", ",", "{", "include", ":", "[", "'default'", "]", "}", ")", ";", "}", "if", "(", "!", "token", ")", "{", "trace", "(", "'their lextab has no default handler - defaulting to next word'", ")", ";", "token", "=", "lexer", ".", "next_word_token", "(", ")", ";", "if", "(", "token", ")", "{", "token", ".", "category", "=", "'symbol'", ";", "}", "}", "return", "token", ";", "}" ]
Get the next token under the current source position according to the lextab entries of the current dialects.
[ "Get", "the", "next", "token", "under", "the", "current", "source", "position", "according", "to", "the", "lextab", "entries", "of", "the", "current", "dialects", "." ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/lexer.js#L830-L873
train
darrencruse/sugarlisp-core
lexer.js
match_in_lextabs
function match_in_lextabs(lexer, options) { options = options || {}; var token; var replaced = {}; // for each dialect's lextab... for(var d = 0; !token && d < lexer.dialects.length; d++) { var dialect = lexer.dialects[d]; if(!dialect.lextab) { continue; // no lextab for the dialect so move on } // check each entry in order... // NOTE I AM IGNORING THE 'PRIORITY' PROPERTY RIGHT NOW - MAYBE I CAN DELETE THEM!? debug('matching in ' + dialect.name + ' lextable'); for(var l = 0; !token && l < dialect.lextab.length; l++) { var entry = dialect.lextab[l]; // we don't match tokens against "replaced" categories if(!replaced[entry.category] && // and if they've specified categories to include... (!options.include || // only consider those (options.include.contains(entry.category) || (options.include.contains("default") && entry.default))) && // or if they've specified categories to omit... (!options.omit || // make sure we skip over those ((!options.omit.contains(entry.category) && !(options.omit.contains("default") && entry.default))))) { // most functions "match" (with a regex) // but they can also just "read" (with a function) if(typeof entry.read !== 'function') { // are we on a token matching this entry's pattern? //trace('matching ' + entry.category + ' pattern'); var matchedText = lexer.on(entry.match); if(matchedText) { trace('matched ' + entry.category + ' pattern'); // advance the current position lexer.next_char(matchedText.length); // create and return the token object (including line/col info) token = lexer.create_token(matchedText, entry.category); } } else { // note we use a "read" function for our default entry // used when nothing else matches. Such entries can // still set a token category, but they should set // "default: true" (so we know to consider them last). trace('invoking ' + entry.category + ' read function'); token = entry.read(lexer); if(token) { trace('read from ' + entry.category + ' read function'); token.category = entry.category; } } } if(entry.replace) { // remember that this category has been replaced replaced[entry.category] = true; } } } return token; }
javascript
function match_in_lextabs(lexer, options) { options = options || {}; var token; var replaced = {}; // for each dialect's lextab... for(var d = 0; !token && d < lexer.dialects.length; d++) { var dialect = lexer.dialects[d]; if(!dialect.lextab) { continue; // no lextab for the dialect so move on } // check each entry in order... // NOTE I AM IGNORING THE 'PRIORITY' PROPERTY RIGHT NOW - MAYBE I CAN DELETE THEM!? debug('matching in ' + dialect.name + ' lextable'); for(var l = 0; !token && l < dialect.lextab.length; l++) { var entry = dialect.lextab[l]; // we don't match tokens against "replaced" categories if(!replaced[entry.category] && // and if they've specified categories to include... (!options.include || // only consider those (options.include.contains(entry.category) || (options.include.contains("default") && entry.default))) && // or if they've specified categories to omit... (!options.omit || // make sure we skip over those ((!options.omit.contains(entry.category) && !(options.omit.contains("default") && entry.default))))) { // most functions "match" (with a regex) // but they can also just "read" (with a function) if(typeof entry.read !== 'function') { // are we on a token matching this entry's pattern? //trace('matching ' + entry.category + ' pattern'); var matchedText = lexer.on(entry.match); if(matchedText) { trace('matched ' + entry.category + ' pattern'); // advance the current position lexer.next_char(matchedText.length); // create and return the token object (including line/col info) token = lexer.create_token(matchedText, entry.category); } } else { // note we use a "read" function for our default entry // used when nothing else matches. Such entries can // still set a token category, but they should set // "default: true" (so we know to consider them last). trace('invoking ' + entry.category + ' read function'); token = entry.read(lexer); if(token) { trace('read from ' + entry.category + ' read function'); token.category = entry.category; } } } if(entry.replace) { // remember that this category has been replaced replaced[entry.category] = true; } } } return token; }
[ "function", "match_in_lextabs", "(", "lexer", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "token", ";", "var", "replaced", "=", "{", "}", ";", "for", "(", "var", "d", "=", "0", ";", "!", "token", "&&", "d", "<", "lexer", ".", "dialects", ".", "length", ";", "d", "++", ")", "{", "var", "dialect", "=", "lexer", ".", "dialects", "[", "d", "]", ";", "if", "(", "!", "dialect", ".", "lextab", ")", "{", "continue", ";", "}", "debug", "(", "'matching in '", "+", "dialect", ".", "name", "+", "' lextable'", ")", ";", "for", "(", "var", "l", "=", "0", ";", "!", "token", "&&", "l", "<", "dialect", ".", "lextab", ".", "length", ";", "l", "++", ")", "{", "var", "entry", "=", "dialect", ".", "lextab", "[", "l", "]", ";", "if", "(", "!", "replaced", "[", "entry", ".", "category", "]", "&&", "(", "!", "options", ".", "include", "||", "(", "options", ".", "include", ".", "contains", "(", "entry", ".", "category", ")", "||", "(", "options", ".", "include", ".", "contains", "(", "\"default\"", ")", "&&", "entry", ".", "default", ")", ")", ")", "&&", "(", "!", "options", ".", "omit", "||", "(", "(", "!", "options", ".", "omit", ".", "contains", "(", "entry", ".", "category", ")", "&&", "!", "(", "options", ".", "omit", ".", "contains", "(", "\"default\"", ")", "&&", "entry", ".", "default", ")", ")", ")", ")", ")", "{", "if", "(", "typeof", "entry", ".", "read", "!==", "'function'", ")", "{", "var", "matchedText", "=", "lexer", ".", "on", "(", "entry", ".", "match", ")", ";", "if", "(", "matchedText", ")", "{", "trace", "(", "'matched '", "+", "entry", ".", "category", "+", "' pattern'", ")", ";", "lexer", ".", "next_char", "(", "matchedText", ".", "length", ")", ";", "token", "=", "lexer", ".", "create_token", "(", "matchedText", ",", "entry", ".", "category", ")", ";", "}", "}", "else", "{", "trace", "(", "'invoking '", "+", "entry", ".", "category", "+", "' read function'", ")", ";", "token", "=", "entry", ".", "read", "(", "lexer", ")", ";", "if", "(", "token", ")", "{", "trace", "(", "'read from '", "+", "entry", ".", "category", "+", "' read function'", ")", ";", "token", ".", "category", "=", "entry", ".", "category", ";", "}", "}", "}", "if", "(", "entry", ".", "replace", ")", "{", "replaced", "[", "entry", ".", "category", "]", "=", "true", ";", "}", "}", "}", "return", "token", ";", "}" ]
Helper function returns a token for the source text under the current position based on the nearest match in the active dialect's lextabs. You can optionally omit specified token categories from consideration ("options.omit"), or include only specified token categories for consideration ("options.include"). You can also use the word "default" in options.omit/options.include to refer to default lextab entries indicated with "default: true"
[ "Helper", "function", "returns", "a", "token", "for", "the", "source", "text", "under", "the", "current", "position", "based", "on", "the", "nearest", "match", "in", "the", "active", "dialect", "s", "lextabs", "." ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/lexer.js#L887-L954
train
darrencruse/sugarlisp-core
lexer.js
formatTokenDump
function formatTokenDump(tokens, formatter, resultPrefix, resultSuffix) { var tokensSexpStr = ""; var currentLine = -999; tokens.forEach(function(token, index) { // skip the wrapping () it's annoying in the dump if(!((index === 0 && token.text === "(") || (index === tokens.length-1 && token.text === ")"))) { // add a return if this starts a different line: if(currentLine !== -999 && token.line !== currentLine) { tokensSexpStr += '\n'; } tokensSexpStr += formatter(token); currentLine = token.line; } }); return (resultPrefix ? resultPrefix : "") + tokensSexpStr + (resultSuffix ? resultSuffix : ""); }
javascript
function formatTokenDump(tokens, formatter, resultPrefix, resultSuffix) { var tokensSexpStr = ""; var currentLine = -999; tokens.forEach(function(token, index) { // skip the wrapping () it's annoying in the dump if(!((index === 0 && token.text === "(") || (index === tokens.length-1 && token.text === ")"))) { // add a return if this starts a different line: if(currentLine !== -999 && token.line !== currentLine) { tokensSexpStr += '\n'; } tokensSexpStr += formatter(token); currentLine = token.line; } }); return (resultPrefix ? resultPrefix : "") + tokensSexpStr + (resultSuffix ? resultSuffix : ""); }
[ "function", "formatTokenDump", "(", "tokens", ",", "formatter", ",", "resultPrefix", ",", "resultSuffix", ")", "{", "var", "tokensSexpStr", "=", "\"\"", ";", "var", "currentLine", "=", "-", "999", ";", "tokens", ".", "forEach", "(", "function", "(", "token", ",", "index", ")", "{", "if", "(", "!", "(", "(", "index", "===", "0", "&&", "token", ".", "text", "===", "\"(\"", ")", "||", "(", "index", "===", "tokens", ".", "length", "-", "1", "&&", "token", ".", "text", "===", "\")\"", ")", ")", ")", "{", "if", "(", "currentLine", "!==", "-", "999", "&&", "token", ".", "line", "!==", "currentLine", ")", "{", "tokensSexpStr", "+=", "'\\n'", ";", "}", "\\n", "tokensSexpStr", "+=", "formatter", "(", "token", ")", ";", "}", "}", ")", ";", "currentLine", "=", "token", ".", "line", ";", "}" ]
format the token dump into a string note: we put all the tokens from a line on a line to make this easier to match up with the original source when debugging problems. @tokens = an array of tokens @formatter = a function which takes a token and returns a string. @resultPrefix = optional string to prepend to the result @resultSuffix = optional string to append to the result @returns the formatted string.
[ "format", "the", "token", "dump", "into", "a", "string" ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/lexer.js#L1214-L1234
train
faiton/benchmark
lib/suite.js
Suite
function Suite(name, fn){ if (! (this instanceof Suite)) return new Suite(name, fn); return this.initialize(name, fn); }
javascript
function Suite(name, fn){ if (! (this instanceof Suite)) return new Suite(name, fn); return this.initialize(name, fn); }
[ "function", "Suite", "(", "name", ",", "fn", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Suite", ")", ")", "return", "new", "Suite", "(", "name", ",", "fn", ")", ";", "return", "this", ".", "initialize", "(", "name", ",", "fn", ")", ";", "}" ]
Suite constructor. @constructor @param {String} name @param {Function} fn @return {Suite} @api public
[ "Suite", "constructor", "." ]
678a10b69002c2b4a656527fbe457448ff402f40
https://github.com/faiton/benchmark/blob/678a10b69002c2b4a656527fbe457448ff402f40/lib/suite.js#L33-L38
train
ojj11/morphic
destructure.js
generateNamedFieldExtractors
function generateNamedFieldExtractors(input) { var names = input.filter(function(matcher, index, array) { // has a name? return matcher.name; }); // has duplicates? names.forEach(function(matcher, index, array) { var isDuplicate = array.slice(0, index).some(function(previousMatcher) { return previousMatcher.name == matcher.name; }); if (isDuplicate) { throw new Error("duplicate named field '" + matcher.name + "'"); } }); return names; }
javascript
function generateNamedFieldExtractors(input) { var names = input.filter(function(matcher, index, array) { // has a name? return matcher.name; }); // has duplicates? names.forEach(function(matcher, index, array) { var isDuplicate = array.slice(0, index).some(function(previousMatcher) { return previousMatcher.name == matcher.name; }); if (isDuplicate) { throw new Error("duplicate named field '" + matcher.name + "'"); } }); return names; }
[ "function", "generateNamedFieldExtractors", "(", "input", ")", "{", "var", "names", "=", "input", ".", "filter", "(", "function", "(", "matcher", ",", "index", ",", "array", ")", "{", "return", "matcher", ".", "name", ";", "}", ")", ";", "names", ".", "forEach", "(", "function", "(", "matcher", ",", "index", ",", "array", ")", "{", "var", "isDuplicate", "=", "array", ".", "slice", "(", "0", ",", "index", ")", ".", "some", "(", "function", "(", "previousMatcher", ")", "{", "return", "previousMatcher", ".", "name", "==", "matcher", ".", "name", ";", "}", ")", ";", "if", "(", "isDuplicate", ")", "{", "throw", "new", "Error", "(", "\"duplicate named field '\"", "+", "matcher", ".", "name", "+", "\"'\"", ")", ";", "}", "}", ")", ";", "return", "names", ";", "}" ]
this will flatten the input into a list of named field extractors, should be run over output of generateMatchers
[ "this", "will", "flatten", "the", "input", "into", "a", "list", "of", "named", "field", "extractors", "should", "be", "run", "over", "output", "of", "generateMatchers" ]
1ec6fd2f299e50866b9165c2545c430519f522ef
https://github.com/ojj11/morphic/blob/1ec6fd2f299e50866b9165c2545c430519f522ef/destructure.js#L44-L59
train
ojj11/morphic
destructure.js
extractNamedFields
function extractNamedFields(fields, input) { var output = Object.create(null); fields.forEach(function(field) { var subObject = input; for (var i = 0; i < field.path.length; i += 1) { if (subObject == undefined) { throw new Error("Unreachable: matched input will always have fields"); } subObject = subObject[field.path[i]]; } switch (field.typeShortcut) { // type matcher: case 1: subObject = global[field.type](subObject); break; // literal matcher: case 3: subObject = field.object; break; } output[field.name] = subObject; }); return output; }
javascript
function extractNamedFields(fields, input) { var output = Object.create(null); fields.forEach(function(field) { var subObject = input; for (var i = 0; i < field.path.length; i += 1) { if (subObject == undefined) { throw new Error("Unreachable: matched input will always have fields"); } subObject = subObject[field.path[i]]; } switch (field.typeShortcut) { // type matcher: case 1: subObject = global[field.type](subObject); break; // literal matcher: case 3: subObject = field.object; break; } output[field.name] = subObject; }); return output; }
[ "function", "extractNamedFields", "(", "fields", ",", "input", ")", "{", "var", "output", "=", "Object", ".", "create", "(", "null", ")", ";", "fields", ".", "forEach", "(", "function", "(", "field", ")", "{", "var", "subObject", "=", "input", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "field", ".", "path", ".", "length", ";", "i", "+=", "1", ")", "{", "if", "(", "subObject", "==", "undefined", ")", "{", "throw", "new", "Error", "(", "\"Unreachable: matched input will always have fields\"", ")", ";", "}", "subObject", "=", "subObject", "[", "field", ".", "path", "[", "i", "]", "]", ";", "}", "switch", "(", "field", ".", "typeShortcut", ")", "{", "case", "1", ":", "subObject", "=", "global", "[", "field", ".", "type", "]", "(", "subObject", ")", ";", "break", ";", "case", "3", ":", "subObject", "=", "field", ".", "object", ";", "break", ";", "}", "output", "[", "field", ".", "name", "]", "=", "subObject", ";", "}", ")", ";", "return", "output", ";", "}" ]
extract out the named fields from an input
[ "extract", "out", "the", "named", "fields", "from", "an", "input" ]
1ec6fd2f299e50866b9165c2545c430519f522ef
https://github.com/ojj11/morphic/blob/1ec6fd2f299e50866b9165c2545c430519f522ef/destructure.js#L62-L85
train
nomocas/yamvish
lib/parsers/html-to-template.js
rawContent
function rawContent(tagName, string, templ, innerTemplate) { var index = string.indexOf('</' + tagName + '>'), raw; if (index === -1) throw new Error(tagName + ' tag badly closed.'); if (index) { // more than 0 raw = string.substring(0, index); if (tagName === 'templ') // produce local api-like handler { innerTemplate.templFunc = new Function(raw); } else innerTemplate.raw(raw); } return string.substring(index + tagName.length + 3); }
javascript
function rawContent(tagName, string, templ, innerTemplate) { var index = string.indexOf('</' + tagName + '>'), raw; if (index === -1) throw new Error(tagName + ' tag badly closed.'); if (index) { // more than 0 raw = string.substring(0, index); if (tagName === 'templ') // produce local api-like handler { innerTemplate.templFunc = new Function(raw); } else innerTemplate.raw(raw); } return string.substring(index + tagName.length + 3); }
[ "function", "rawContent", "(", "tagName", ",", "string", ",", "templ", ",", "innerTemplate", ")", "{", "var", "index", "=", "string", ".", "indexOf", "(", "'</'", "+", "tagName", "+", "'>'", ")", ",", "raw", ";", "if", "(", "index", "===", "-", "1", ")", "throw", "new", "Error", "(", "tagName", "+", "' tag badly closed.'", ")", ";", "if", "(", "index", ")", "{", "raw", "=", "string", ".", "substring", "(", "0", ",", "index", ")", ";", "if", "(", "tagName", "===", "'templ'", ")", "{", "innerTemplate", ".", "templFunc", "=", "new", "Function", "(", "raw", ")", ";", "}", "else", "innerTemplate", ".", "raw", "(", "raw", ")", ";", "}", "return", "string", ".", "substring", "(", "index", "+", "tagName", ".", "length", "+", "3", ")", ";", "}" ]
raw inner content of tag
[ "raw", "inner", "content", "of", "tag" ]
017a536bb6bafddf1b31c0c7af6f723be58e9f0e
https://github.com/nomocas/yamvish/blob/017a536bb6bafddf1b31c0c7af6f723be58e9f0e/lib/parsers/html-to-template.js#L21-L35
train
srouse/cssmodeler
example/dist/csssystem/styleguide/cmod_styleguide.js
function(markupList) { ("production" !== "development" ? invariant( ExecutionEnvironment.canUseDOM, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'React.renderToString for server rendering.' ) : invariant(ExecutionEnvironment.canUseDOM)); var nodeName; var markupByNodeName = {}; // Group markup by `nodeName` if a wrap is necessary, else by '*'. for (var i = 0; i < markupList.length; i++) { ("production" !== "development" ? invariant( markupList[i], 'dangerouslyRenderMarkup(...): Missing markup.' ) : invariant(markupList[i])); nodeName = getNodeName(markupList[i]); nodeName = getMarkupWrap(nodeName) ? nodeName : '*'; markupByNodeName[nodeName] = markupByNodeName[nodeName] || []; markupByNodeName[nodeName][i] = markupList[i]; } var resultList = []; var resultListAssignmentCount = 0; for (nodeName in markupByNodeName) { if (!markupByNodeName.hasOwnProperty(nodeName)) { continue; } var markupListByNodeName = markupByNodeName[nodeName]; // This for-in loop skips the holes of the sparse array. The order of // iteration should follow the order of assignment, which happens to match // numerical index order, but we don't rely on that. var resultIndex; for (resultIndex in markupListByNodeName) { if (markupListByNodeName.hasOwnProperty(resultIndex)) { var markup = markupListByNodeName[resultIndex]; // Push the requested markup with an additional RESULT_INDEX_ATTR // attribute. If the markup does not start with a < character, it // will be discarded below (with an appropriate console.error). markupListByNodeName[resultIndex] = markup.replace( OPEN_TAG_NAME_EXP, // This index will be parsed back out below. '$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" ' ); } } // Render each group of markup with similar wrapping `nodeName`. var renderNodes = createNodesFromMarkup( markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags. ); for (var j = 0; j < renderNodes.length; ++j) { var renderNode = renderNodes[j]; if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) { resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR); renderNode.removeAttribute(RESULT_INDEX_ATTR); ("production" !== "development" ? invariant( !resultList.hasOwnProperty(resultIndex), 'Danger: Assigning to an already-occupied result index.' ) : invariant(!resultList.hasOwnProperty(resultIndex))); resultList[resultIndex] = renderNode; // This should match resultList.length and markupList.length when // we're done. resultListAssignmentCount += 1; } else if ("production" !== "development") { console.error( 'Danger: Discarding unexpected node:', renderNode ); } } } // Although resultList was populated out of order, it should now be a dense // array. ("production" !== "development" ? invariant( resultListAssignmentCount === resultList.length, 'Danger: Did not assign to every index of resultList.' ) : invariant(resultListAssignmentCount === resultList.length)); ("production" !== "development" ? invariant( resultList.length === markupList.length, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length ) : invariant(resultList.length === markupList.length)); return resultList; }
javascript
function(markupList) { ("production" !== "development" ? invariant( ExecutionEnvironment.canUseDOM, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'React.renderToString for server rendering.' ) : invariant(ExecutionEnvironment.canUseDOM)); var nodeName; var markupByNodeName = {}; // Group markup by `nodeName` if a wrap is necessary, else by '*'. for (var i = 0; i < markupList.length; i++) { ("production" !== "development" ? invariant( markupList[i], 'dangerouslyRenderMarkup(...): Missing markup.' ) : invariant(markupList[i])); nodeName = getNodeName(markupList[i]); nodeName = getMarkupWrap(nodeName) ? nodeName : '*'; markupByNodeName[nodeName] = markupByNodeName[nodeName] || []; markupByNodeName[nodeName][i] = markupList[i]; } var resultList = []; var resultListAssignmentCount = 0; for (nodeName in markupByNodeName) { if (!markupByNodeName.hasOwnProperty(nodeName)) { continue; } var markupListByNodeName = markupByNodeName[nodeName]; // This for-in loop skips the holes of the sparse array. The order of // iteration should follow the order of assignment, which happens to match // numerical index order, but we don't rely on that. var resultIndex; for (resultIndex in markupListByNodeName) { if (markupListByNodeName.hasOwnProperty(resultIndex)) { var markup = markupListByNodeName[resultIndex]; // Push the requested markup with an additional RESULT_INDEX_ATTR // attribute. If the markup does not start with a < character, it // will be discarded below (with an appropriate console.error). markupListByNodeName[resultIndex] = markup.replace( OPEN_TAG_NAME_EXP, // This index will be parsed back out below. '$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" ' ); } } // Render each group of markup with similar wrapping `nodeName`. var renderNodes = createNodesFromMarkup( markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags. ); for (var j = 0; j < renderNodes.length; ++j) { var renderNode = renderNodes[j]; if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) { resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR); renderNode.removeAttribute(RESULT_INDEX_ATTR); ("production" !== "development" ? invariant( !resultList.hasOwnProperty(resultIndex), 'Danger: Assigning to an already-occupied result index.' ) : invariant(!resultList.hasOwnProperty(resultIndex))); resultList[resultIndex] = renderNode; // This should match resultList.length and markupList.length when // we're done. resultListAssignmentCount += 1; } else if ("production" !== "development") { console.error( 'Danger: Discarding unexpected node:', renderNode ); } } } // Although resultList was populated out of order, it should now be a dense // array. ("production" !== "development" ? invariant( resultListAssignmentCount === resultList.length, 'Danger: Did not assign to every index of resultList.' ) : invariant(resultListAssignmentCount === resultList.length)); ("production" !== "development" ? invariant( resultList.length === markupList.length, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length ) : invariant(resultList.length === markupList.length)); return resultList; }
[ "function", "(", "markupList", ")", "{", "(", "\"production\"", "!==", "\"development\"", "?", "invariant", "(", "ExecutionEnvironment", ".", "canUseDOM", ",", "'dangerouslyRenderMarkup(...): Cannot render markup in a worker '", "+", "'thread. Make sure `window` and `document` are available globally '", "+", "'before requiring React when unit testing or use '", "+", "'React.renderToString for server rendering.'", ")", ":", "invariant", "(", "ExecutionEnvironment", ".", "canUseDOM", ")", ")", ";", "var", "nodeName", ";", "var", "markupByNodeName", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "markupList", ".", "length", ";", "i", "++", ")", "{", "(", "\"production\"", "!==", "\"development\"", "?", "invariant", "(", "markupList", "[", "i", "]", ",", "'dangerouslyRenderMarkup(...): Missing markup.'", ")", ":", "invariant", "(", "markupList", "[", "i", "]", ")", ")", ";", "nodeName", "=", "getNodeName", "(", "markupList", "[", "i", "]", ")", ";", "nodeName", "=", "getMarkupWrap", "(", "nodeName", ")", "?", "nodeName", ":", "'*'", ";", "markupByNodeName", "[", "nodeName", "]", "=", "markupByNodeName", "[", "nodeName", "]", "||", "[", "]", ";", "markupByNodeName", "[", "nodeName", "]", "[", "i", "]", "=", "markupList", "[", "i", "]", ";", "}", "var", "resultList", "=", "[", "]", ";", "var", "resultListAssignmentCount", "=", "0", ";", "for", "(", "nodeName", "in", "markupByNodeName", ")", "{", "if", "(", "!", "markupByNodeName", ".", "hasOwnProperty", "(", "nodeName", ")", ")", "{", "continue", ";", "}", "var", "markupListByNodeName", "=", "markupByNodeName", "[", "nodeName", "]", ";", "var", "resultIndex", ";", "for", "(", "resultIndex", "in", "markupListByNodeName", ")", "{", "if", "(", "markupListByNodeName", ".", "hasOwnProperty", "(", "resultIndex", ")", ")", "{", "var", "markup", "=", "markupListByNodeName", "[", "resultIndex", "]", ";", "markupListByNodeName", "[", "resultIndex", "]", "=", "markup", ".", "replace", "(", "OPEN_TAG_NAME_EXP", ",", "'$1 '", "+", "RESULT_INDEX_ATTR", "+", "'=\"'", "+", "resultIndex", "+", "'\" '", ")", ";", "}", "}", "var", "renderNodes", "=", "createNodesFromMarkup", "(", "markupListByNodeName", ".", "join", "(", "''", ")", ",", "emptyFunction", ")", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "renderNodes", ".", "length", ";", "++", "j", ")", "{", "var", "renderNode", "=", "renderNodes", "[", "j", "]", ";", "if", "(", "renderNode", ".", "hasAttribute", "&&", "renderNode", ".", "hasAttribute", "(", "RESULT_INDEX_ATTR", ")", ")", "{", "resultIndex", "=", "+", "renderNode", ".", "getAttribute", "(", "RESULT_INDEX_ATTR", ")", ";", "renderNode", ".", "removeAttribute", "(", "RESULT_INDEX_ATTR", ")", ";", "(", "\"production\"", "!==", "\"development\"", "?", "invariant", "(", "!", "resultList", ".", "hasOwnProperty", "(", "resultIndex", ")", ",", "'Danger: Assigning to an already-occupied result index.'", ")", ":", "invariant", "(", "!", "resultList", ".", "hasOwnProperty", "(", "resultIndex", ")", ")", ")", ";", "resultList", "[", "resultIndex", "]", "=", "renderNode", ";", "resultListAssignmentCount", "+=", "1", ";", "}", "else", "if", "(", "\"production\"", "!==", "\"development\"", ")", "{", "console", ".", "error", "(", "'Danger: Discarding unexpected node:'", ",", "renderNode", ")", ";", "}", "}", "}", "(", "\"production\"", "!==", "\"development\"", "?", "invariant", "(", "resultListAssignmentCount", "===", "resultList", ".", "length", ",", "'Danger: Did not assign to every index of resultList.'", ")", ":", "invariant", "(", "resultListAssignmentCount", "===", "resultList", ".", "length", ")", ")", ";", "(", "\"production\"", "!==", "\"development\"", "?", "invariant", "(", "resultList", ".", "length", "===", "markupList", ".", "length", ",", "'Danger: Expected markup to render %s nodes, but rendered %s.'", ",", "markupList", ".", "length", ",", "resultList", ".", "length", ")", ":", "invariant", "(", "resultList", ".", "length", "===", "markupList", ".", "length", ")", ")", ";", "return", "resultList", ";", "}" ]
Renders markup into an array of nodes. The markup is expected to render into a list of root nodes. Also, the length of `resultList` and `markupList` should be the same. @param {array<string>} markupList List of markup strings to render. @return {array<DOMElement>} List of rendered nodes. @internal
[ "Renders", "markup", "into", "an", "array", "of", "nodes", ".", "The", "markup", "is", "expected", "to", "render", "into", "a", "list", "of", "root", "nodes", ".", "Also", "the", "length", "of", "resultList", "and", "markupList", "should", "be", "the", "same", "." ]
8682a44736d21877a3237b222587acc2b43924c9
https://github.com/srouse/cssmodeler/blob/8682a44736d21877a3237b222587acc2b43924c9/example/dist/csssystem/styleguide/cmod_styleguide.js#L2168-L2265
train
srouse/cssmodeler
example/dist/csssystem/styleguide/cmod_styleguide.js
recomputePluginOrdering
function recomputePluginOrdering() { if (!EventPluginOrder) { // Wait until an `EventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var PluginModule = namesToPlugins[pluginName]; var pluginIndex = EventPluginOrder.indexOf(pluginName); ("production" !== "development" ? invariant( pluginIndex > -1, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName ) : invariant(pluginIndex > -1)); if (EventPluginRegistry.plugins[pluginIndex]) { continue; } ("production" !== "development" ? invariant( PluginModule.extractEvents, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName ) : invariant(PluginModule.extractEvents)); EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { ("production" !== "development" ? invariant( publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ), 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName ) : invariant(publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ))); } } }
javascript
function recomputePluginOrdering() { if (!EventPluginOrder) { // Wait until an `EventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var PluginModule = namesToPlugins[pluginName]; var pluginIndex = EventPluginOrder.indexOf(pluginName); ("production" !== "development" ? invariant( pluginIndex > -1, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName ) : invariant(pluginIndex > -1)); if (EventPluginRegistry.plugins[pluginIndex]) { continue; } ("production" !== "development" ? invariant( PluginModule.extractEvents, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName ) : invariant(PluginModule.extractEvents)); EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { ("production" !== "development" ? invariant( publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ), 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName ) : invariant(publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ))); } } }
[ "function", "recomputePluginOrdering", "(", ")", "{", "if", "(", "!", "EventPluginOrder", ")", "{", "return", ";", "}", "for", "(", "var", "pluginName", "in", "namesToPlugins", ")", "{", "var", "PluginModule", "=", "namesToPlugins", "[", "pluginName", "]", ";", "var", "pluginIndex", "=", "EventPluginOrder", ".", "indexOf", "(", "pluginName", ")", ";", "(", "\"production\"", "!==", "\"development\"", "?", "invariant", "(", "pluginIndex", ">", "-", "1", ",", "'EventPluginRegistry: Cannot inject event plugins that do not exist in '", "+", "'the plugin ordering, `%s`.'", ",", "pluginName", ")", ":", "invariant", "(", "pluginIndex", ">", "-", "1", ")", ")", ";", "if", "(", "EventPluginRegistry", ".", "plugins", "[", "pluginIndex", "]", ")", "{", "continue", ";", "}", "(", "\"production\"", "!==", "\"development\"", "?", "invariant", "(", "PluginModule", ".", "extractEvents", ",", "'EventPluginRegistry: Event plugins must implement an `extractEvents` '", "+", "'method, but `%s` does not.'", ",", "pluginName", ")", ":", "invariant", "(", "PluginModule", ".", "extractEvents", ")", ")", ";", "EventPluginRegistry", ".", "plugins", "[", "pluginIndex", "]", "=", "PluginModule", ";", "var", "publishedEvents", "=", "PluginModule", ".", "eventTypes", ";", "for", "(", "var", "eventName", "in", "publishedEvents", ")", "{", "(", "\"production\"", "!==", "\"development\"", "?", "invariant", "(", "publishEventForPlugin", "(", "publishedEvents", "[", "eventName", "]", ",", "PluginModule", ",", "eventName", ")", ",", "'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.'", ",", "eventName", ",", "pluginName", ")", ":", "invariant", "(", "publishEventForPlugin", "(", "publishedEvents", "[", "eventName", "]", ",", "PluginModule", ",", "eventName", ")", ")", ")", ";", "}", "}", "}" ]
Recomputes the plugin list using the injected plugins and plugin ordering. @private
[ "Recomputes", "the", "plugin", "list", "using", "the", "injected", "plugins", "and", "plugin", "ordering", "." ]
8682a44736d21877a3237b222587acc2b43924c9
https://github.com/srouse/cssmodeler/blob/8682a44736d21877a3237b222587acc2b43924c9/example/dist/csssystem/styleguide/cmod_styleguide.js#L2947-L2989
train
srouse/cssmodeler
example/dist/csssystem/styleguide/cmod_styleguide.js
publishEventForPlugin
function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { ("production" !== "development" ? invariant( !EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName ) : invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName))); EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName( phasedRegistrationName, PluginModule, eventName ); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName( dispatchConfig.registrationName, PluginModule, eventName ); return true; } return false; }
javascript
function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { ("production" !== "development" ? invariant( !EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName ) : invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName))); EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName( phasedRegistrationName, PluginModule, eventName ); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName( dispatchConfig.registrationName, PluginModule, eventName ); return true; } return false; }
[ "function", "publishEventForPlugin", "(", "dispatchConfig", ",", "PluginModule", ",", "eventName", ")", "{", "(", "\"production\"", "!==", "\"development\"", "?", "invariant", "(", "!", "EventPluginRegistry", ".", "eventNameDispatchConfigs", ".", "hasOwnProperty", "(", "eventName", ")", ",", "'EventPluginHub: More than one plugin attempted to publish the same '", "+", "'event name, `%s`.'", ",", "eventName", ")", ":", "invariant", "(", "!", "EventPluginRegistry", ".", "eventNameDispatchConfigs", ".", "hasOwnProperty", "(", "eventName", ")", ")", ")", ";", "EventPluginRegistry", ".", "eventNameDispatchConfigs", "[", "eventName", "]", "=", "dispatchConfig", ";", "var", "phasedRegistrationNames", "=", "dispatchConfig", ".", "phasedRegistrationNames", ";", "if", "(", "phasedRegistrationNames", ")", "{", "for", "(", "var", "phaseName", "in", "phasedRegistrationNames", ")", "{", "if", "(", "phasedRegistrationNames", ".", "hasOwnProperty", "(", "phaseName", ")", ")", "{", "var", "phasedRegistrationName", "=", "phasedRegistrationNames", "[", "phaseName", "]", ";", "publishRegistrationName", "(", "phasedRegistrationName", ",", "PluginModule", ",", "eventName", ")", ";", "}", "}", "return", "true", ";", "}", "else", "if", "(", "dispatchConfig", ".", "registrationName", ")", "{", "publishRegistrationName", "(", "dispatchConfig", ".", "registrationName", ",", "PluginModule", ",", "eventName", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Publishes an event so that it can be dispatched by the supplied plugin. @param {object} dispatchConfig Dispatch configuration for the event. @param {object} PluginModule Plugin publishing the event. @return {boolean} True if the event was successfully published. @private
[ "Publishes", "an", "event", "so", "that", "it", "can", "be", "dispatched", "by", "the", "supplied", "plugin", "." ]
8682a44736d21877a3237b222587acc2b43924c9
https://github.com/srouse/cssmodeler/blob/8682a44736d21877a3237b222587acc2b43924c9/example/dist/csssystem/styleguide/cmod_styleguide.js#L2999-L3030
train
srouse/cssmodeler
example/dist/csssystem/styleguide/cmod_styleguide.js
function(spec) { var Constructor = function(props, context) { // This constructor is overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if ("production" !== "development") { ("production" !== "development" ? warning( this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory' ) : null); } // Wire up auto-binding if (this.__reactAutoBindMap) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if ("production" !== "development") { // We allow auto-mocks to proceed as if they're returning null. if (typeof initialState === 'undefined' && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } ("production" !== "development" ? invariant( typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent' ) : invariant(typeof initialState === 'object' && !Array.isArray(initialState))); this.state = initialState; }; Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; injectedMixins.forEach( mixSpecIntoComponent.bind(null, Constructor) ); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if ("production" !== "development") { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } ("production" !== "development" ? invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.' ) : invariant(Constructor.prototype.render)); if ("production" !== "development") { ("production" !== "development" ? warning( !Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component' ) : null); } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } // Legacy hook Constructor.type = Constructor; if ("production" !== "development") { try { Object.defineProperty(Constructor, 'type', typeDeprecationDescriptor); } catch (x) { // IE will fail on defineProperty (es5-shim/sham too) } } return Constructor; }
javascript
function(spec) { var Constructor = function(props, context) { // This constructor is overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if ("production" !== "development") { ("production" !== "development" ? warning( this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory' ) : null); } // Wire up auto-binding if (this.__reactAutoBindMap) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if ("production" !== "development") { // We allow auto-mocks to proceed as if they're returning null. if (typeof initialState === 'undefined' && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } ("production" !== "development" ? invariant( typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent' ) : invariant(typeof initialState === 'object' && !Array.isArray(initialState))); this.state = initialState; }; Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; injectedMixins.forEach( mixSpecIntoComponent.bind(null, Constructor) ); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if ("production" !== "development") { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } ("production" !== "development" ? invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.' ) : invariant(Constructor.prototype.render)); if ("production" !== "development") { ("production" !== "development" ? warning( !Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component' ) : null); } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } // Legacy hook Constructor.type = Constructor; if ("production" !== "development") { try { Object.defineProperty(Constructor, 'type', typeDeprecationDescriptor); } catch (x) { // IE will fail on defineProperty (es5-shim/sham too) } } return Constructor; }
[ "function", "(", "spec", ")", "{", "var", "Constructor", "=", "function", "(", "props", ",", "context", ")", "{", "if", "(", "\"production\"", "!==", "\"development\"", ")", "{", "(", "\"production\"", "!==", "\"development\"", "?", "warning", "(", "this", "instanceof", "Constructor", ",", "'Something is calling a React component directly. Use a factory or '", "+", "'JSX instead. See: https://fb.me/react-legacyfactory'", ")", ":", "null", ")", ";", "}", "if", "(", "this", ".", "__reactAutoBindMap", ")", "{", "bindAutoBindMethods", "(", "this", ")", ";", "}", "this", ".", "props", "=", "props", ";", "this", ".", "context", "=", "context", ";", "this", ".", "state", "=", "null", ";", "var", "initialState", "=", "this", ".", "getInitialState", "?", "this", ".", "getInitialState", "(", ")", ":", "null", ";", "if", "(", "\"production\"", "!==", "\"development\"", ")", "{", "if", "(", "typeof", "initialState", "===", "'undefined'", "&&", "this", ".", "getInitialState", ".", "_isMockFunction", ")", "{", "initialState", "=", "null", ";", "}", "}", "(", "\"production\"", "!==", "\"development\"", "?", "invariant", "(", "typeof", "initialState", "===", "'object'", "&&", "!", "Array", ".", "isArray", "(", "initialState", ")", ",", "'%s.getInitialState(): must return an object or null'", ",", "Constructor", ".", "displayName", "||", "'ReactCompositeComponent'", ")", ":", "invariant", "(", "typeof", "initialState", "===", "'object'", "&&", "!", "Array", ".", "isArray", "(", "initialState", ")", ")", ")", ";", "this", ".", "state", "=", "initialState", ";", "}", ";", "Constructor", ".", "prototype", "=", "new", "ReactClassComponent", "(", ")", ";", "Constructor", ".", "prototype", ".", "constructor", "=", "Constructor", ";", "injectedMixins", ".", "forEach", "(", "mixSpecIntoComponent", ".", "bind", "(", "null", ",", "Constructor", ")", ")", ";", "mixSpecIntoComponent", "(", "Constructor", ",", "spec", ")", ";", "if", "(", "Constructor", ".", "getDefaultProps", ")", "{", "Constructor", ".", "defaultProps", "=", "Constructor", ".", "getDefaultProps", "(", ")", ";", "}", "if", "(", "\"production\"", "!==", "\"development\"", ")", "{", "if", "(", "Constructor", ".", "getDefaultProps", ")", "{", "Constructor", ".", "getDefaultProps", ".", "isReactClassApproved", "=", "{", "}", ";", "}", "if", "(", "Constructor", ".", "prototype", ".", "getInitialState", ")", "{", "Constructor", ".", "prototype", ".", "getInitialState", ".", "isReactClassApproved", "=", "{", "}", ";", "}", "}", "(", "\"production\"", "!==", "\"development\"", "?", "invariant", "(", "Constructor", ".", "prototype", ".", "render", ",", "'createClass(...): Class specification must implement a `render` method.'", ")", ":", "invariant", "(", "Constructor", ".", "prototype", ".", "render", ")", ")", ";", "if", "(", "\"production\"", "!==", "\"development\"", ")", "{", "(", "\"production\"", "!==", "\"development\"", "?", "warning", "(", "!", "Constructor", ".", "prototype", ".", "componentShouldUpdate", ",", "'%s has a method called '", "+", "'componentShouldUpdate(). Did you mean shouldComponentUpdate()? '", "+", "'The name is phrased as a question because the function is '", "+", "'expected to return a value.'", ",", "spec", ".", "displayName", "||", "'A component'", ")", ":", "null", ")", ";", "}", "for", "(", "var", "methodName", "in", "ReactClassInterface", ")", "{", "if", "(", "!", "Constructor", ".", "prototype", "[", "methodName", "]", ")", "{", "Constructor", ".", "prototype", "[", "methodName", "]", "=", "null", ";", "}", "}", "Constructor", ".", "type", "=", "Constructor", ";", "if", "(", "\"production\"", "!==", "\"development\"", ")", "{", "try", "{", "Object", ".", "defineProperty", "(", "Constructor", ",", "'type'", ",", "typeDeprecationDescriptor", ")", ";", "}", "catch", "(", "x", ")", "{", "}", "}", "return", "Constructor", ";", "}" ]
Creates a composite component class given a class specification. @param {object} spec Class specification (which must define `render`). @return {function} Component constructor function. @public
[ "Creates", "a", "composite", "component", "class", "given", "a", "class", "specification", "." ]
8682a44736d21877a3237b222587acc2b43924c9
https://github.com/srouse/cssmodeler/blob/8682a44736d21877a3237b222587acc2b43924c9/example/dist/csssystem/styleguide/cmod_styleguide.js#L5818-L5922
train
srouse/cssmodeler
example/dist/csssystem/styleguide/cmod_styleguide.js
function(propTypes, props, location) { // TODO: Stop validating prop types here and only use the element // validation. var componentName = this.getName(); for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. ("production" !== "development" ? invariant( typeof propTypes[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName ) : invariant(typeof propTypes[propName] === 'function')); error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } if (error instanceof Error) { // We may want to extend this logic for similar errors in // React.render calls, so I'm abstracting it away into // a function to minimize refactoring in the future var addendum = getDeclarationErrorAddendum(this); if (location === ReactPropTypeLocations.prop) { // Preface gives us something to blacklist in warning module ("production" !== "development" ? warning( false, 'Failed Composite propType: %s%s', error.message, addendum ) : null); } else { ("production" !== "development" ? warning( false, 'Failed Context Types: %s%s', error.message, addendum ) : null); } } } } }
javascript
function(propTypes, props, location) { // TODO: Stop validating prop types here and only use the element // validation. var componentName = this.getName(); for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. ("production" !== "development" ? invariant( typeof propTypes[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName ) : invariant(typeof propTypes[propName] === 'function')); error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } if (error instanceof Error) { // We may want to extend this logic for similar errors in // React.render calls, so I'm abstracting it away into // a function to minimize refactoring in the future var addendum = getDeclarationErrorAddendum(this); if (location === ReactPropTypeLocations.prop) { // Preface gives us something to blacklist in warning module ("production" !== "development" ? warning( false, 'Failed Composite propType: %s%s', error.message, addendum ) : null); } else { ("production" !== "development" ? warning( false, 'Failed Context Types: %s%s', error.message, addendum ) : null); } } } } }
[ "function", "(", "propTypes", ",", "props", ",", "location", ")", "{", "var", "componentName", "=", "this", ".", "getName", "(", ")", ";", "for", "(", "var", "propName", "in", "propTypes", ")", "{", "if", "(", "propTypes", ".", "hasOwnProperty", "(", "propName", ")", ")", "{", "var", "error", ";", "try", "{", "(", "\"production\"", "!==", "\"development\"", "?", "invariant", "(", "typeof", "propTypes", "[", "propName", "]", "===", "'function'", ",", "'%s: %s type `%s` is invalid; it must be a function, usually '", "+", "'from React.PropTypes.'", ",", "componentName", "||", "'React class'", ",", "ReactPropTypeLocationNames", "[", "location", "]", ",", "propName", ")", ":", "invariant", "(", "typeof", "propTypes", "[", "propName", "]", "===", "'function'", ")", ")", ";", "error", "=", "propTypes", "[", "propName", "]", "(", "props", ",", "propName", ",", "componentName", ",", "location", ")", ";", "}", "catch", "(", "ex", ")", "{", "error", "=", "ex", ";", "}", "if", "(", "error", "instanceof", "Error", ")", "{", "var", "addendum", "=", "getDeclarationErrorAddendum", "(", "this", ")", ";", "if", "(", "location", "===", "ReactPropTypeLocations", ".", "prop", ")", "{", "(", "\"production\"", "!==", "\"development\"", "?", "warning", "(", "false", ",", "'Failed Composite propType: %s%s'", ",", "error", ".", "message", ",", "addendum", ")", ":", "null", ")", ";", "}", "else", "{", "(", "\"production\"", "!==", "\"development\"", "?", "warning", "(", "false", ",", "'Failed Context Types: %s%s'", ",", "error", ".", "message", ",", "addendum", ")", ":", "null", ")", ";", "}", "}", "}", "}", "}" ]
Assert that the props are valid @param {object} propTypes Map of prop name to a ReactPropType @param {object} props @param {string} location e.g. "prop", "context", "child context" @private
[ "Assert", "that", "the", "props", "are", "valid" ]
8682a44736d21877a3237b222587acc2b43924c9
https://github.com/srouse/cssmodeler/blob/8682a44736d21877a3237b222587acc2b43924c9/example/dist/csssystem/styleguide/cmod_styleguide.js#L6643-L6690
train
srouse/cssmodeler
example/dist/csssystem/styleguide/cmod_styleguide.js
warnForPropsMutation
function warnForPropsMutation(propName, element) { var type = element.type; var elementName = typeof type === 'string' ? type : type.displayName; var ownerName = element._owner ? element._owner.getPublicInstance().constructor.displayName : null; var warningKey = propName + '|' + elementName + '|' + ownerName; if (warnedPropsMutations.hasOwnProperty(warningKey)) { return; } warnedPropsMutations[warningKey] = true; var elementInfo = ''; if (elementName) { elementInfo = ' <' + elementName + ' />'; } var ownerInfo = ''; if (ownerName) { ownerInfo = ' The element was created by ' + ownerName + '.'; } ("production" !== "development" ? warning( false, 'Don\'t set .props.%s of the React component%s. Instead, specify the ' + 'correct value when initially creating the element or use ' + 'React.cloneElement to make a new element with updated props.%s', propName, elementInfo, ownerInfo ) : null); }
javascript
function warnForPropsMutation(propName, element) { var type = element.type; var elementName = typeof type === 'string' ? type : type.displayName; var ownerName = element._owner ? element._owner.getPublicInstance().constructor.displayName : null; var warningKey = propName + '|' + elementName + '|' + ownerName; if (warnedPropsMutations.hasOwnProperty(warningKey)) { return; } warnedPropsMutations[warningKey] = true; var elementInfo = ''; if (elementName) { elementInfo = ' <' + elementName + ' />'; } var ownerInfo = ''; if (ownerName) { ownerInfo = ' The element was created by ' + ownerName + '.'; } ("production" !== "development" ? warning( false, 'Don\'t set .props.%s of the React component%s. Instead, specify the ' + 'correct value when initially creating the element or use ' + 'React.cloneElement to make a new element with updated props.%s', propName, elementInfo, ownerInfo ) : null); }
[ "function", "warnForPropsMutation", "(", "propName", ",", "element", ")", "{", "var", "type", "=", "element", ".", "type", ";", "var", "elementName", "=", "typeof", "type", "===", "'string'", "?", "type", ":", "type", ".", "displayName", ";", "var", "ownerName", "=", "element", ".", "_owner", "?", "element", ".", "_owner", ".", "getPublicInstance", "(", ")", ".", "constructor", ".", "displayName", ":", "null", ";", "var", "warningKey", "=", "propName", "+", "'|'", "+", "elementName", "+", "'|'", "+", "ownerName", ";", "if", "(", "warnedPropsMutations", ".", "hasOwnProperty", "(", "warningKey", ")", ")", "{", "return", ";", "}", "warnedPropsMutations", "[", "warningKey", "]", "=", "true", ";", "var", "elementInfo", "=", "''", ";", "if", "(", "elementName", ")", "{", "elementInfo", "=", "' <'", "+", "elementName", "+", "' />'", ";", "}", "var", "ownerInfo", "=", "''", ";", "if", "(", "ownerName", ")", "{", "ownerInfo", "=", "' The element was created by '", "+", "ownerName", "+", "'.'", ";", "}", "(", "\"production\"", "!==", "\"development\"", "?", "warning", "(", "false", ",", "'Don\\'t set .props.%s of the React component%s. Instead, specify the '", "+", "\\'", "+", "'correct value when initially creating the element or use '", ",", "'React.cloneElement to make a new element with updated props.%s'", ",", "propName", ",", "elementInfo", ")", ":", "null", ")", ";", "}" ]
Warn about mutating props when setting `propName` on `element`. @param {string} propName The string key within props that was set @param {ReactElement} element
[ "Warn", "about", "mutating", "props", "when", "setting", "propName", "on", "element", "." ]
8682a44736d21877a3237b222587acc2b43924c9
https://github.com/srouse/cssmodeler/blob/8682a44736d21877a3237b222587acc2b43924c9/example/dist/csssystem/styleguide/cmod_styleguide.js#L10417-L10447
train
srouse/cssmodeler
example/dist/csssystem/styleguide/cmod_styleguide.js
function(object) { if ("production" !== "development") { if (typeof object !== 'object' || !object || Array.isArray(object)) { ("production" !== "development" ? warning( false, 'React.addons.createFragment only accepts a single object.', object ) : null); return object; } if (ReactElement.isValidElement(object)) { ("production" !== "development" ? warning( false, 'React.addons.createFragment does not accept a ReactElement ' + 'without a wrapper object.' ) : null); return object; } if (canWarnForReactFragment) { var proxy = {}; Object.defineProperty(proxy, fragmentKey, { enumerable: false, value: object }); Object.defineProperty(proxy, didWarnKey, { writable: true, enumerable: false, value: false }); for (var key in object) { proxyPropertyAccessWithWarning(proxy, key); } Object.preventExtensions(proxy); return proxy; } } return object; }
javascript
function(object) { if ("production" !== "development") { if (typeof object !== 'object' || !object || Array.isArray(object)) { ("production" !== "development" ? warning( false, 'React.addons.createFragment only accepts a single object.', object ) : null); return object; } if (ReactElement.isValidElement(object)) { ("production" !== "development" ? warning( false, 'React.addons.createFragment does not accept a ReactElement ' + 'without a wrapper object.' ) : null); return object; } if (canWarnForReactFragment) { var proxy = {}; Object.defineProperty(proxy, fragmentKey, { enumerable: false, value: object }); Object.defineProperty(proxy, didWarnKey, { writable: true, enumerable: false, value: false }); for (var key in object) { proxyPropertyAccessWithWarning(proxy, key); } Object.preventExtensions(proxy); return proxy; } } return object; }
[ "function", "(", "object", ")", "{", "if", "(", "\"production\"", "!==", "\"development\"", ")", "{", "if", "(", "typeof", "object", "!==", "'object'", "||", "!", "object", "||", "Array", ".", "isArray", "(", "object", ")", ")", "{", "(", "\"production\"", "!==", "\"development\"", "?", "warning", "(", "false", ",", "'React.addons.createFragment only accepts a single object.'", ",", "object", ")", ":", "null", ")", ";", "return", "object", ";", "}", "if", "(", "ReactElement", ".", "isValidElement", "(", "object", ")", ")", "{", "(", "\"production\"", "!==", "\"development\"", "?", "warning", "(", "false", ",", "'React.addons.createFragment does not accept a ReactElement '", "+", "'without a wrapper object.'", ")", ":", "null", ")", ";", "return", "object", ";", "}", "if", "(", "canWarnForReactFragment", ")", "{", "var", "proxy", "=", "{", "}", ";", "Object", ".", "defineProperty", "(", "proxy", ",", "fragmentKey", ",", "{", "enumerable", ":", "false", ",", "value", ":", "object", "}", ")", ";", "Object", ".", "defineProperty", "(", "proxy", ",", "didWarnKey", ",", "{", "writable", ":", "true", ",", "enumerable", ":", "false", ",", "value", ":", "false", "}", ")", ";", "for", "(", "var", "key", "in", "object", ")", "{", "proxyPropertyAccessWithWarning", "(", "proxy", ",", "key", ")", ";", "}", "Object", ".", "preventExtensions", "(", "proxy", ")", ";", "return", "proxy", ";", "}", "}", "return", "object", ";", "}" ]
Wrap a keyed object in an opaque proxy that warns you if you access any of its properties.
[ "Wrap", "a", "keyed", "object", "in", "an", "opaque", "proxy", "that", "warns", "you", "if", "you", "access", "any", "of", "its", "properties", "." ]
8682a44736d21877a3237b222587acc2b43924c9
https://github.com/srouse/cssmodeler/blob/8682a44736d21877a3237b222587acc2b43924c9/example/dist/csssystem/styleguide/cmod_styleguide.js#L11065-L11102
train
srouse/cssmodeler
example/dist/csssystem/styleguide/cmod_styleguide.js
function(container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) ("production" !== "development" ? warning( ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function of ' + 'props and state; triggering nested component updates from render is ' + 'not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate.' ) : null); ("production" !== "development" ? invariant( container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ), 'unmountComponentAtNode(...): Target container is not a DOM element.' ) : invariant(container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ))); var reactRootID = getReactRootID(container); var component = instancesByReactRootID[reactRootID]; if (!component) { return false; } ReactMount.unmountComponentFromNode(component, container); delete instancesByReactRootID[reactRootID]; delete containersByReactRootID[reactRootID]; if ("production" !== "development") { delete rootElementsByReactRootID[reactRootID]; } return true; }
javascript
function(container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) ("production" !== "development" ? warning( ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function of ' + 'props and state; triggering nested component updates from render is ' + 'not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate.' ) : null); ("production" !== "development" ? invariant( container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ), 'unmountComponentAtNode(...): Target container is not a DOM element.' ) : invariant(container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ))); var reactRootID = getReactRootID(container); var component = instancesByReactRootID[reactRootID]; if (!component) { return false; } ReactMount.unmountComponentFromNode(component, container); delete instancesByReactRootID[reactRootID]; delete containersByReactRootID[reactRootID]; if ("production" !== "development") { delete rootElementsByReactRootID[reactRootID]; } return true; }
[ "function", "(", "container", ")", "{", "(", "\"production\"", "!==", "\"development\"", "?", "warning", "(", "ReactCurrentOwner", ".", "current", "==", "null", ",", "'unmountComponentAtNode(): Render methods should be a pure function of '", "+", "'props and state; triggering nested component updates from render is '", "+", "'not allowed. If necessary, trigger nested updates in '", "+", "'componentDidUpdate.'", ")", ":", "null", ")", ";", "(", "\"production\"", "!==", "\"development\"", "?", "invariant", "(", "container", "&&", "(", "(", "container", ".", "nodeType", "===", "ELEMENT_NODE_TYPE", "||", "container", ".", "nodeType", "===", "DOC_NODE_TYPE", ")", ")", ",", "'unmountComponentAtNode(...): Target container is not a DOM element.'", ")", ":", "invariant", "(", "container", "&&", "(", "(", "container", ".", "nodeType", "===", "ELEMENT_NODE_TYPE", "||", "container", ".", "nodeType", "===", "DOC_NODE_TYPE", ")", ")", ")", ")", ";", "var", "reactRootID", "=", "getReactRootID", "(", "container", ")", ";", "var", "component", "=", "instancesByReactRootID", "[", "reactRootID", "]", ";", "if", "(", "!", "component", ")", "{", "return", "false", ";", "}", "ReactMount", ".", "unmountComponentFromNode", "(", "component", ",", "container", ")", ";", "delete", "instancesByReactRootID", "[", "reactRootID", "]", ";", "delete", "containersByReactRootID", "[", "reactRootID", "]", ";", "if", "(", "\"production\"", "!==", "\"development\"", ")", "{", "delete", "rootElementsByReactRootID", "[", "reactRootID", "]", ";", "}", "return", "true", ";", "}" ]
Unmounts and destroys the React component rendered in the `container`. @param {DOMElement} container DOM element containing a React component. @return {boolean} True if a component was found in and unmounted from `container`
[ "Unmounts", "and", "destroys", "the", "React", "component", "rendered", "in", "the", "container", "." ]
8682a44736d21877a3237b222587acc2b43924c9
https://github.com/srouse/cssmodeler/blob/8682a44736d21877a3237b222587acc2b43924c9/example/dist/csssystem/styleguide/cmod_styleguide.js#L12362-L12396
train
srouse/cssmodeler
example/dist/csssystem/styleguide/cmod_styleguide.js
function(objName, fnName, func) { if ("production" !== "development") { var measuredFunc = null; var wrapper = function() { if (ReactPerf.enableMeasure) { if (!measuredFunc) { measuredFunc = ReactPerf.storedMeasure(objName, fnName, func); } return measuredFunc.apply(this, arguments); } return func.apply(this, arguments); }; wrapper.displayName = objName + '_' + fnName; return wrapper; } return func; }
javascript
function(objName, fnName, func) { if ("production" !== "development") { var measuredFunc = null; var wrapper = function() { if (ReactPerf.enableMeasure) { if (!measuredFunc) { measuredFunc = ReactPerf.storedMeasure(objName, fnName, func); } return measuredFunc.apply(this, arguments); } return func.apply(this, arguments); }; wrapper.displayName = objName + '_' + fnName; return wrapper; } return func; }
[ "function", "(", "objName", ",", "fnName", ",", "func", ")", "{", "if", "(", "\"production\"", "!==", "\"development\"", ")", "{", "var", "measuredFunc", "=", "null", ";", "var", "wrapper", "=", "function", "(", ")", "{", "if", "(", "ReactPerf", ".", "enableMeasure", ")", "{", "if", "(", "!", "measuredFunc", ")", "{", "measuredFunc", "=", "ReactPerf", ".", "storedMeasure", "(", "objName", ",", "fnName", ",", "func", ")", ";", "}", "return", "measuredFunc", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "return", "func", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "wrapper", ".", "displayName", "=", "objName", "+", "'_'", "+", "fnName", ";", "return", "wrapper", ";", "}", "return", "func", ";", "}" ]
Use this to wrap methods you want to measure. Zero overhead in production. @param {string} objName @param {string} fnName @param {function} func @return {function}
[ "Use", "this", "to", "wrap", "methods", "you", "want", "to", "measure", ".", "Zero", "overhead", "in", "production", "." ]
8682a44736d21877a3237b222587acc2b43924c9
https://github.com/srouse/cssmodeler/blob/8682a44736d21877a3237b222587acc2b43924c9/example/dist/csssystem/styleguide/cmod_styleguide.js#L13423-L13439
train
phated/grunt-enyo
tasks/init/enyo/root/enyo/source/kernel/Object.js
function() { var acc = arguments.callee.caller; var nom = ((acc ? acc.nom : "") || "(instance method)") + ":"; enyo.logging.log("log", [nom].concat(enyo.cloneArray(arguments))); }
javascript
function() { var acc = arguments.callee.caller; var nom = ((acc ? acc.nom : "") || "(instance method)") + ":"; enyo.logging.log("log", [nom].concat(enyo.cloneArray(arguments))); }
[ "function", "(", ")", "{", "var", "acc", "=", "arguments", ".", "callee", ".", "caller", ";", "var", "nom", "=", "(", "(", "acc", "?", "acc", ".", "nom", ":", "\"\"", ")", "||", "\"(instance method)\"", ")", "+", "\":\"", ";", "enyo", ".", "logging", ".", "log", "(", "\"log\"", ",", "[", "nom", "]", ".", "concat", "(", "enyo", ".", "cloneArray", "(", "arguments", ")", ")", ")", ";", "}" ]
Sends a log message to the console, prepended with the name of the kind and method from which _log_ was invoked. Multiple arguments are coerced to String and joined with spaces. enyo.kind({ name: "MyObject", kind: enyo.Object, hello: function() { this.log("says", "hi"); shows in the console: MyObject.hello: says hi } });
[ "Sends", "a", "log", "message", "to", "the", "console", "prepended", "with", "the", "name", "of", "the", "kind", "and", "method", "from", "which", "_log_", "was", "invoked", ".", "Multiple", "arguments", "are", "coerced", "to", "String", "and", "joined", "with", "spaces", "." ]
d2990ee4cd85eea8db4108c43086c6d8c3c90c30
https://github.com/phated/grunt-enyo/blob/d2990ee4cd85eea8db4108c43086c6d8c3c90c30/tasks/init/enyo/root/enyo/source/kernel/Object.js#L77-L81
train
melvincarvalho/rdf-shell
lib/mv.js
mv
function mv (sourceURI, destURI, callback) { if (!sourceURI) { callback(new Error('source URI is required')) } if (!destURI) { callback(new Error('dest URI is required')) } util.get(sourceURI, function (err, val, uri) { util.put(destURI, val, function (err, ret, uri) { if (!err) { util.rm(sourceURI, function(err, ret) { if (!err) { callback(null, ret, uri) } else { callback(err) } }) } else { callback(err) } }) }) }
javascript
function mv (sourceURI, destURI, callback) { if (!sourceURI) { callback(new Error('source URI is required')) } if (!destURI) { callback(new Error('dest URI is required')) } util.get(sourceURI, function (err, val, uri) { util.put(destURI, val, function (err, ret, uri) { if (!err) { util.rm(sourceURI, function(err, ret) { if (!err) { callback(null, ret, uri) } else { callback(err) } }) } else { callback(err) } }) }) }
[ "function", "mv", "(", "sourceURI", ",", "destURI", ",", "callback", ")", "{", "if", "(", "!", "sourceURI", ")", "{", "callback", "(", "new", "Error", "(", "'source URI is required'", ")", ")", "}", "if", "(", "!", "destURI", ")", "{", "callback", "(", "new", "Error", "(", "'dest URI is required'", ")", ")", "}", "util", ".", "get", "(", "sourceURI", ",", "function", "(", "err", ",", "val", ",", "uri", ")", "{", "util", ".", "put", "(", "destURI", ",", "val", ",", "function", "(", "err", ",", "ret", ",", "uri", ")", "{", "if", "(", "!", "err", ")", "{", "util", ".", "rm", "(", "sourceURI", ",", "function", "(", "err", ",", "ret", ")", "{", "if", "(", "!", "err", ")", "{", "callback", "(", "null", ",", "ret", ",", "uri", ")", "}", "else", "{", "callback", "(", "err", ")", "}", "}", ")", "}", "else", "{", "callback", "(", "err", ")", "}", "}", ")", "}", ")", "}" ]
Move rdf from a source to a destination. @param {string} sourceURI The source URI @param {string} destURI The dest URI @param {function} callback Callback with result
[ "Move", "rdf", "from", "a", "source", "to", "a", "destination", "." ]
bf2015f6f333855e69a18ce3ec9e917bbddfb425
https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/lib/mv.js#L11-L33
train
kaliumxyz/euphoria-connection
examples/userlist/index.js
update
function update() { connection = new Connection(room) // set our funcitonal code on the ready event, so we are sure that the socket has been created and is connected to the server connection.on('ready', _ => { connection.on('snapshot-event', event => { // get every listener including bots and lurkers userList = event.data.listing.sort() render(userList) connection.close() }) }) }
javascript
function update() { connection = new Connection(room) // set our funcitonal code on the ready event, so we are sure that the socket has been created and is connected to the server connection.on('ready', _ => { connection.on('snapshot-event', event => { // get every listener including bots and lurkers userList = event.data.listing.sort() render(userList) connection.close() }) }) }
[ "function", "update", "(", ")", "{", "connection", "=", "new", "Connection", "(", "room", ")", "connection", ".", "on", "(", "'ready'", ",", "_", "=>", "{", "connection", ".", "on", "(", "'snapshot-event'", ",", "event", "=>", "{", "userList", "=", "event", ".", "data", ".", "listing", ".", "sort", "(", ")", "render", "(", "userList", ")", "connection", ".", "close", "(", ")", "}", ")", "}", ")", "}" ]
Update the userList global with new data from the targeted euphoria room. We use the snapshot even send on a new connect to update the userlist.
[ "Update", "the", "userList", "global", "with", "new", "data", "from", "the", "targeted", "euphoria", "room", ".", "We", "use", "the", "snapshot", "even", "send", "on", "a", "new", "connect", "to", "update", "the", "userlist", "." ]
936cc92117f78d2c8f9560d80b1c416e672c8c42
https://github.com/kaliumxyz/euphoria-connection/blob/936cc92117f78d2c8f9560d80b1c416e672c8c42/examples/userlist/index.js#L25-L36
train
kaliumxyz/euphoria-connection
examples/userlist/index.js
render
function render(list) { const blank = new Array(process.stdout.rows).fill('\n') console.log(blank) readline.cursorTo(process.stdout, 0, 0) readline.clearScreenDown(process.stdout) list.forEach( user => { console.log(`${chalk.hsl(color(user.name),100,50)(user.name)}: ${user.id}`) }) }
javascript
function render(list) { const blank = new Array(process.stdout.rows).fill('\n') console.log(blank) readline.cursorTo(process.stdout, 0, 0) readline.clearScreenDown(process.stdout) list.forEach( user => { console.log(`${chalk.hsl(color(user.name),100,50)(user.name)}: ${user.id}`) }) }
[ "function", "render", "(", "list", ")", "{", "const", "blank", "=", "new", "Array", "(", "process", ".", "stdout", ".", "rows", ")", ".", "fill", "(", "'\\n'", ")", "\\n", "console", ".", "log", "(", "blank", ")", "readline", ".", "cursorTo", "(", "process", ".", "stdout", ",", "0", ",", "0", ")", "readline", ".", "clearScreenDown", "(", "process", ".", "stdout", ")", "}" ]
Render our list, replace the old console content with our newer content and place the relevant data in the relevant places. @param {Array} list
[ "Render", "our", "list", "replace", "the", "old", "console", "content", "with", "our", "newer", "content", "and", "place", "the", "relevant", "data", "in", "the", "relevant", "places", "." ]
936cc92117f78d2c8f9560d80b1c416e672c8c42
https://github.com/kaliumxyz/euphoria-connection/blob/936cc92117f78d2c8f9560d80b1c416e672c8c42/examples/userlist/index.js#L48-L58
train
oskarhagberg/gbgcity
lib/waterflow.js
getMeasureStations
function getMeasureStations(latitude, longitude, params, callback) { if(!latitude || !longitude) { callback(new Error("WaterFlow.getMeasureStations: latitude and longitude required")); return; } params = params || {}; params.latitude = latitude; params.longitude = longitude; core.callApi('/waterflowservice/GetMeasureStations', params, callback); }
javascript
function getMeasureStations(latitude, longitude, params, callback) { if(!latitude || !longitude) { callback(new Error("WaterFlow.getMeasureStations: latitude and longitude required")); return; } params = params || {}; params.latitude = latitude; params.longitude = longitude; core.callApi('/waterflowservice/GetMeasureStations', params, callback); }
[ "function", "getMeasureStations", "(", "latitude", ",", "longitude", ",", "params", ",", "callback", ")", "{", "if", "(", "!", "latitude", "||", "!", "longitude", ")", "{", "callback", "(", "new", "Error", "(", "\"WaterFlow.getMeasureStations: latitude and longitude required\"", ")", ")", ";", "return", ";", "}", "params", "=", "params", "||", "{", "}", ";", "params", ".", "latitude", "=", "latitude", ";", "params", ".", "longitude", "=", "longitude", ";", "core", ".", "callApi", "(", "'/waterflowservice/GetMeasureStations'", ",", "params", ",", "callback", ")", ";", "}" ]
Returns a list of all available measure stations producing water level data. @memberof module:gbgcity/WaterFlow @param {String|Number} latitude The latitude of the location around which to explore. @param {String|Number} longitude The longitude of the location around which to explore. @param {Object} [params] An object containing additional parameters. @param {Function} callback The function to call with results, function({Error} error, {Object} results)/ @see http://data.goteborg.se/WaterFlowService/help/operations/GetMeasureStations
[ "Returns", "a", "list", "of", "all", "available", "measure", "stations", "producing", "water", "level", "data", "." ]
d2de903b2fba83cc953ae218905380fef080cb2d
https://github.com/oskarhagberg/gbgcity/blob/d2de903b2fba83cc953ae218905380fef080cb2d/lib/waterflow.js#L24-L33
train
oskarhagberg/gbgcity
lib/waterflow.js
getWaterLevel
function getWaterLevel(stationId, startDate, endDate, params, callback) { if(!stationId) { callback(new Error("WaterFlow.getWaterLevel: stationId required")); return; } params = params || {}; params.stationid = stationId; if(!startDate && !endDate) { startDate = new Date(); startDate.setHours(startDate.getHours() - 4); startDate = formatDate(startDate); endDate = new Date(); endDate = formatDate(endDate); } params.startdate = startDate; params.endDate = endDate; core.callApi('/waterflowservice/GetWaterLevel', params, callback); }
javascript
function getWaterLevel(stationId, startDate, endDate, params, callback) { if(!stationId) { callback(new Error("WaterFlow.getWaterLevel: stationId required")); return; } params = params || {}; params.stationid = stationId; if(!startDate && !endDate) { startDate = new Date(); startDate.setHours(startDate.getHours() - 4); startDate = formatDate(startDate); endDate = new Date(); endDate = formatDate(endDate); } params.startdate = startDate; params.endDate = endDate; core.callApi('/waterflowservice/GetWaterLevel', params, callback); }
[ "function", "getWaterLevel", "(", "stationId", ",", "startDate", ",", "endDate", ",", "params", ",", "callback", ")", "{", "if", "(", "!", "stationId", ")", "{", "callback", "(", "new", "Error", "(", "\"WaterFlow.getWaterLevel: stationId required\"", ")", ")", ";", "return", ";", "}", "params", "=", "params", "||", "{", "}", ";", "params", ".", "stationid", "=", "stationId", ";", "if", "(", "!", "startDate", "&&", "!", "endDate", ")", "{", "startDate", "=", "new", "Date", "(", ")", ";", "startDate", ".", "setHours", "(", "startDate", ".", "getHours", "(", ")", "-", "4", ")", ";", "startDate", "=", "formatDate", "(", "startDate", ")", ";", "endDate", "=", "new", "Date", "(", ")", ";", "endDate", "=", "formatDate", "(", "endDate", ")", ";", "}", "params", ".", "startdate", "=", "startDate", ";", "params", ".", "endDate", "=", "endDate", ";", "core", ".", "callApi", "(", "'/waterflowservice/GetWaterLevel'", ",", "params", ",", "callback", ")", ";", "}" ]
Returns a list of water level measuring points given a sertain station and time interval. @memberof module:gbgcity/WaterFlow @param {String} stationId @param {String} [startDate] @param {String} [endData] @param {Function} callback The function to call with results, function({Error} error, {Object} results)/ @see http://data.goteborg.se/WaterFlowService/help/operations/GetWaterLevel
[ "Returns", "a", "list", "of", "water", "level", "measuring", "points", "given", "a", "sertain", "station", "and", "time", "interval", "." ]
d2de903b2fba83cc953ae218905380fef080cb2d
https://github.com/oskarhagberg/gbgcity/blob/d2de903b2fba83cc953ae218905380fef080cb2d/lib/waterflow.js#L45-L62
train
danielwerthen/funcis
lib/listener.js
matches
function matches(url, command) { var cap; if (cap = commandReg.exec(url)) return cap[1] === command; }
javascript
function matches(url, command) { var cap; if (cap = commandReg.exec(url)) return cap[1] === command; }
[ "function", "matches", "(", "url", ",", "command", ")", "{", "var", "cap", ";", "if", "(", "cap", "=", "commandReg", ".", "exec", "(", "url", ")", ")", "return", "cap", "[", "1", "]", "===", "command", ";", "}" ]
Ugliness to support escaped backslashes in windows
[ "Ugliness", "to", "support", "escaped", "backslashes", "in", "windows" ]
9482ea954e6684e6803c824b4105eac735d83812
https://github.com/danielwerthen/funcis/blob/9482ea954e6684e6803c824b4105eac735d83812/lib/listener.js#L13-L16
train
laconbass/mocha-pending
index.js
Pending
function Pending(runner) { runner.on('start', function(){ console.log('* ') console.log('*********************'); console.log('*** Pending tests ***'); console.log('*********************'); console.log('* ') }); var scope = []; runner.on('pending', function(test){ var current = [test] , parent = test.parent ; // stack suites while( !!parent ){ current.unshift(parent) parent = parent.parent; } // print titles current.forEach(function(val, key){ if( val != scope[key] ){ while( scope.length > key ){ scope.pop() } console.log( '* ' + Array(key).join(' ') + val.title ); scope.push(val); } }) }) }
javascript
function Pending(runner) { runner.on('start', function(){ console.log('* ') console.log('*********************'); console.log('*** Pending tests ***'); console.log('*********************'); console.log('* ') }); var scope = []; runner.on('pending', function(test){ var current = [test] , parent = test.parent ; // stack suites while( !!parent ){ current.unshift(parent) parent = parent.parent; } // print titles current.forEach(function(val, key){ if( val != scope[key] ){ while( scope.length > key ){ scope.pop() } console.log( '* ' + Array(key).join(' ') + val.title ); scope.push(val); } }) }) }
[ "function", "Pending", "(", "runner", ")", "{", "runner", ".", "on", "(", "'start'", ",", "function", "(", ")", "{", "console", ".", "log", "(", "'* '", ")", "console", ".", "log", "(", "'*********************'", ")", ";", "console", ".", "log", "(", "'*** Pending tests ***'", ")", ";", "console", ".", "log", "(", "'*********************'", ")", ";", "console", ".", "log", "(", "'* '", ")", "}", ")", ";", "var", "scope", "=", "[", "]", ";", "runner", ".", "on", "(", "'pending'", ",", "function", "(", "test", ")", "{", "var", "current", "=", "[", "test", "]", ",", "parent", "=", "test", ".", "parent", ";", "while", "(", "!", "!", "parent", ")", "{", "current", ".", "unshift", "(", "parent", ")", "parent", "=", "parent", ".", "parent", ";", "}", "current", ".", "forEach", "(", "function", "(", "val", ",", "key", ")", "{", "if", "(", "val", "!=", "scope", "[", "key", "]", ")", "{", "while", "(", "scope", ".", "length", ">", "key", ")", "{", "scope", ".", "pop", "(", ")", "}", "console", ".", "log", "(", "'* '", "+", "Array", "(", "key", ")", ".", "join", "(", "' '", ")", "+", "val", ".", "title", ")", ";", "scope", ".", "push", "(", "val", ")", ";", "}", "}", ")", "}", ")", "}" ]
Initialize a new `Pending` test reporter. @param {Runner} runner @api public
[ "Initialize", "a", "new", "Pending", "test", "reporter", "." ]
df0e5ee270cee86596a755ceb1900a83b2fa6e41
https://github.com/laconbass/mocha-pending/blob/df0e5ee270cee86596a755ceb1900a83b2fa6e41/index.js#L14-L46
train
rsdoiel/stn
stn.js
function (d, use_UTC) { if (typeof d === "string") { if (d.match(/[0-9][0-9][0-9][0-9][\s]*-[0-1][0-9]-[\s]*[0-3][0-9]/)) { return d.replace(/\s+/, ""); } d = new Date(d); } else if (typeof d === "number") { d = new Date(d); } else if (typeof d !== "object" && typeof d.getFullYear !== "function") { throw "Expecting type: " + String(d) + " --> " + typeof d; } if (!use_UTC) { return [ d.getFullYear(), String("0" + (d.getMonth() + 1)).substr(-2), String("0" + d.getDate()).substr(-2) ].join("-"); } return [ d.getUTCFullYear(), String("0" + (d.getUTCMonth() + 1)).substr(-2), String("0" + d.getUTCDate()).substr(-2) ].join("-"); }
javascript
function (d, use_UTC) { if (typeof d === "string") { if (d.match(/[0-9][0-9][0-9][0-9][\s]*-[0-1][0-9]-[\s]*[0-3][0-9]/)) { return d.replace(/\s+/, ""); } d = new Date(d); } else if (typeof d === "number") { d = new Date(d); } else if (typeof d !== "object" && typeof d.getFullYear !== "function") { throw "Expecting type: " + String(d) + " --> " + typeof d; } if (!use_UTC) { return [ d.getFullYear(), String("0" + (d.getMonth() + 1)).substr(-2), String("0" + d.getDate()).substr(-2) ].join("-"); } return [ d.getUTCFullYear(), String("0" + (d.getUTCMonth() + 1)).substr(-2), String("0" + d.getUTCDate()).substr(-2) ].join("-"); }
[ "function", "(", "d", ",", "use_UTC", ")", "{", "if", "(", "typeof", "d", "===", "\"string\"", ")", "{", "if", "(", "d", ".", "match", "(", "/", "[0-9][0-9][0-9][0-9][\\s]*-[0-1][0-9]-[\\s]*[0-3][0-9]", "/", ")", ")", "{", "return", "d", ".", "replace", "(", "/", "\\s+", "/", ",", "\"\"", ")", ";", "}", "d", "=", "new", "Date", "(", "d", ")", ";", "}", "else", "if", "(", "typeof", "d", "===", "\"number\"", ")", "{", "d", "=", "new", "Date", "(", "d", ")", ";", "}", "else", "if", "(", "typeof", "d", "!==", "\"object\"", "&&", "typeof", "d", ".", "getFullYear", "!==", "\"function\"", ")", "{", "throw", "\"Expecting type: \"", "+", "String", "(", "d", ")", "+", "\" ", "+", "typeof", "d", ";", "}", "if", "(", "!", "use_UTC", ")", "{", "return", "[", "d", ".", "getFullYear", "(", ")", ",", "String", "(", "\"0\"", "+", "(", "d", ".", "getMonth", "(", ")", "+", "1", ")", ")", ".", "substr", "(", "-", "2", ")", ",", "String", "(", "\"0\"", "+", "d", ".", "getDate", "(", ")", ")", ".", "substr", "(", "-", "2", ")", "]", ".", "join", "(", "\"-\"", ")", ";", "}", "return", "[", "d", ".", "getUTCFullYear", "(", ")", ",", "String", "(", "\"0\"", "+", "(", "d", ".", "getUTCMonth", "(", ")", "+", "1", ")", ")", ".", "substr", "(", "-", "2", ")", ",", "String", "(", "\"0\"", "+", "d", ".", "getUTCDate", "(", ")", ")", ".", "substr", "(", "-", "2", ")", "]", ".", "join", "(", "\"-\"", ")", ";", "}" ]
Format a date as YYYY-MM-DD @param Date object @return string in YYYY-MM-DD format
[ "Format", "a", "date", "as", "YYYY", "-", "MM", "-", "DD" ]
dffbe22a4a672f262e4c9151edf75fa7e077b8f4
https://github.com/rsdoiel/stn/blob/dffbe22a4a672f262e4c9151edf75fa7e077b8f4/stn.js#L17-L41
train
rsdoiel/stn
stn.js
function (options) { var ky, default_keys = [ "normalize_date", "hours", "save_parse", "tags", "map" ], defaults = {}, map = {}; default_keys.forEach(function (ky) { defaults[ky] = true; }); this.defaults = defaults; this.map = false; this.parse_tree = {}; this.msgs = []; if (options !== undefined) { for (ky in options) { if (options.hasOwnProperty(ky)) { if (default_keys.indexOf(ky) >= 0) { this.defaults[ky] = options[ky]; } else { map[ky] = options[ky]; } } } if (Object.keys(map).length > 0) { this.map = map; } } }
javascript
function (options) { var ky, default_keys = [ "normalize_date", "hours", "save_parse", "tags", "map" ], defaults = {}, map = {}; default_keys.forEach(function (ky) { defaults[ky] = true; }); this.defaults = defaults; this.map = false; this.parse_tree = {}; this.msgs = []; if (options !== undefined) { for (ky in options) { if (options.hasOwnProperty(ky)) { if (default_keys.indexOf(ky) >= 0) { this.defaults[ky] = options[ky]; } else { map[ky] = options[ky]; } } } if (Object.keys(map).length > 0) { this.map = map; } } }
[ "function", "(", "options", ")", "{", "var", "ky", ",", "default_keys", "=", "[", "\"normalize_date\"", ",", "\"hours\"", ",", "\"save_parse\"", ",", "\"tags\"", ",", "\"map\"", "]", ",", "defaults", "=", "{", "}", ",", "map", "=", "{", "}", ";", "default_keys", ".", "forEach", "(", "function", "(", "ky", ")", "{", "defaults", "[", "ky", "]", "=", "true", ";", "}", ")", ";", "this", ".", "defaults", "=", "defaults", ";", "this", ".", "map", "=", "false", ";", "this", ".", "parse_tree", "=", "{", "}", ";", "this", ".", "msgs", "=", "[", "]", ";", "if", "(", "options", "!==", "undefined", ")", "{", "for", "(", "ky", "in", "options", ")", "{", "if", "(", "options", ".", "hasOwnProperty", "(", "ky", ")", ")", "{", "if", "(", "default_keys", ".", "indexOf", "(", "ky", ")", ">=", "0", ")", "{", "this", ".", "defaults", "[", "ky", "]", "=", "options", "[", "ky", "]", ";", "}", "else", "{", "map", "[", "ky", "]", "=", "options", "[", "ky", "]", ";", "}", "}", "}", "if", "(", "Object", ".", "keys", "(", "map", ")", ".", "length", ">", "0", ")", "{", "this", ".", "map", "=", "map", ";", "}", "}", "}" ]
reset - clear the parse tree sets save_parse to true, sets normalize_date to true sets tags to true sets map ot false @param options - a set of options to override the defaults with on reset.
[ "reset", "-", "clear", "the", "parse", "tree", "sets", "save_parse", "to", "true", "sets", "normalize_date", "to", "true", "sets", "tags", "to", "true", "sets", "map", "ot", "false" ]
dffbe22a4a672f262e4c9151edf75fa7e077b8f4
https://github.com/rsdoiel/stn/blob/dffbe22a4a672f262e4c9151edf75fa7e077b8f4/stn.js#L66-L99
train
rsdoiel/stn
stn.js
function (msg) { var i = this.msgs.length; this.msgs.push('ERROR: ' + msg); if ((i + 1) !== this.msgs.length) { return false; } return true; }
javascript
function (msg) { var i = this.msgs.length; this.msgs.push('ERROR: ' + msg); if ((i + 1) !== this.msgs.length) { return false; } return true; }
[ "function", "(", "msg", ")", "{", "var", "i", "=", "this", ".", "msgs", ".", "length", ";", "this", ".", "msgs", ".", "push", "(", "'ERROR: '", "+", "msg", ")", ";", "if", "(", "(", "i", "+", "1", ")", "!==", "this", ".", "msgs", ".", "length", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
error - collect parse errors into the msgs array. @param msg - the message to the collection of messages. @return true on successful add, false otherwise
[ "error", "-", "collect", "parse", "errors", "into", "the", "msgs", "array", "." ]
dffbe22a4a672f262e4c9151edf75fa7e077b8f4
https://github.com/rsdoiel/stn/blob/dffbe22a4a672f262e4c9151edf75fa7e077b8f4/stn.js#L120-L128
train
rsdoiel/stn
stn.js
function (no_clear) { var result; if (this.msgs === undefined) { this.msgs = []; } result = this.msgs.join("\n"); // set optional default i needed if (no_clear !== undefined) { no_clear = false; } if (no_clear === true) { return result; } // Clear the messages this.msgs = []; return result; }
javascript
function (no_clear) { var result; if (this.msgs === undefined) { this.msgs = []; } result = this.msgs.join("\n"); // set optional default i needed if (no_clear !== undefined) { no_clear = false; } if (no_clear === true) { return result; } // Clear the messages this.msgs = []; return result; }
[ "function", "(", "no_clear", ")", "{", "var", "result", ";", "if", "(", "this", ".", "msgs", "===", "undefined", ")", "{", "this", ".", "msgs", "=", "[", "]", ";", "}", "result", "=", "this", ".", "msgs", ".", "join", "(", "\"\\n\"", ")", ";", "\\n", "if", "(", "no_clear", "!==", "undefined", ")", "{", "no_clear", "=", "false", ";", "}", "if", "(", "no_clear", "===", "true", ")", "{", "return", "result", ";", "}", "this", ".", "msgs", "=", "[", "]", ";", "}" ]
messages - return the msgs array as a single string delimited by new lines. @param no_clear (optional, defaults to false) @return string representing in messages
[ "messages", "-", "return", "the", "msgs", "array", "as", "a", "single", "string", "delimited", "by", "new", "lines", "." ]
dffbe22a4a672f262e4c9151edf75fa7e077b8f4
https://github.com/rsdoiel/stn/blob/dffbe22a4a672f262e4c9151edf75fa7e077b8f4/stn.js#L148-L168
train
rsdoiel/stn
stn.js
function () { var self = this, dates = Object.keys(this.parse_tree), lines = []; dates.sort(); dates.forEach(function (dy, i) { var times = Object.keys(self.parse_tree[dy]); lines.push(dy); times.sort(); times.forEach(function (tm) { var tags = "", maps = "", notes = "", rec; rec = self.parse_tree[dy][tm]; if (typeof rec === "string") { notes = rec; } else { if (typeof rec.map !== "undefined" && rec.map !== false) { maps = [ rec.map.project_name, rec.map.task ].join(", ") + "; "; } if (typeof rec.tags !== "undefined" && rec.tags !== false) { tags = rec.tags.join(", ") + "; "; } if (typeof rec.notes !== "undefined") { notes = rec.notes; } } lines.push([ tm, "; ", tags, maps, notes ].join("")); }); }); return lines.join("\n\n"); }
javascript
function () { var self = this, dates = Object.keys(this.parse_tree), lines = []; dates.sort(); dates.forEach(function (dy, i) { var times = Object.keys(self.parse_tree[dy]); lines.push(dy); times.sort(); times.forEach(function (tm) { var tags = "", maps = "", notes = "", rec; rec = self.parse_tree[dy][tm]; if (typeof rec === "string") { notes = rec; } else { if (typeof rec.map !== "undefined" && rec.map !== false) { maps = [ rec.map.project_name, rec.map.task ].join(", ") + "; "; } if (typeof rec.tags !== "undefined" && rec.tags !== false) { tags = rec.tags.join(", ") + "; "; } if (typeof rec.notes !== "undefined") { notes = rec.notes; } } lines.push([ tm, "; ", tags, maps, notes ].join("")); }); }); return lines.join("\n\n"); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "dates", "=", "Object", ".", "keys", "(", "this", ".", "parse_tree", ")", ",", "lines", "=", "[", "]", ";", "dates", ".", "sort", "(", ")", ";", "dates", ".", "forEach", "(", "function", "(", "dy", ",", "i", ")", "{", "var", "times", "=", "Object", ".", "keys", "(", "self", ".", "parse_tree", "[", "dy", "]", ")", ";", "lines", ".", "push", "(", "dy", ")", ";", "times", ".", "sort", "(", ")", ";", "times", ".", "forEach", "(", "function", "(", "tm", ")", "{", "var", "tags", "=", "\"\"", ",", "maps", "=", "\"\"", ",", "notes", "=", "\"\"", ",", "rec", ";", "rec", "=", "self", ".", "parse_tree", "[", "dy", "]", "[", "tm", "]", ";", "if", "(", "typeof", "rec", "===", "\"string\"", ")", "{", "notes", "=", "rec", ";", "}", "else", "{", "if", "(", "typeof", "rec", ".", "map", "!==", "\"undefined\"", "&&", "rec", ".", "map", "!==", "false", ")", "{", "maps", "=", "[", "rec", ".", "map", ".", "project_name", ",", "rec", ".", "map", ".", "task", "]", ".", "join", "(", "\", \"", ")", "+", "\"; \"", ";", "}", "if", "(", "typeof", "rec", ".", "tags", "!==", "\"undefined\"", "&&", "rec", ".", "tags", "!==", "false", ")", "{", "tags", "=", "rec", ".", "tags", ".", "join", "(", "\", \"", ")", "+", "\"; \"", ";", "}", "if", "(", "typeof", "rec", ".", "notes", "!==", "\"undefined\"", ")", "{", "notes", "=", "rec", ".", "notes", ";", "}", "}", "lines", ".", "push", "(", "[", "tm", ",", "\"; \"", ",", "tags", ",", "maps", ",", "notes", "]", ".", "join", "(", "\"\"", ")", ")", ";", "}", ")", ";", "}", ")", ";", "return", "lines", ".", "join", "(", "\"\\n\\n\"", ")", ";", "}" ]
Render parse tree as string.
[ "Render", "parse", "tree", "as", "string", "." ]
dffbe22a4a672f262e4c9151edf75fa7e077b8f4
https://github.com/rsdoiel/stn/blob/dffbe22a4a672f262e4c9151edf75fa7e077b8f4/stn.js#L365-L409
train
Aratramba/text-file-register
index.js
addFiles
function addFiles(pattern, cb){ glob(pattern, function(err, files){ if(err) throw err; async.each(files, readFile, function(err){ if(err) throw err; if(cb) cb(); }); }); }
javascript
function addFiles(pattern, cb){ glob(pattern, function(err, files){ if(err) throw err; async.each(files, readFile, function(err){ if(err) throw err; if(cb) cb(); }); }); }
[ "function", "addFiles", "(", "pattern", ",", "cb", ")", "{", "glob", "(", "pattern", ",", "function", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "throw", "err", ";", "async", ".", "each", "(", "files", ",", "readFile", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "throw", "err", ";", "if", "(", "cb", ")", "cb", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Add files to register
[ "Add", "files", "to", "register" ]
061249f90b08a300ec3647db167957d27a51ccdd
https://github.com/Aratramba/text-file-register/blob/061249f90b08a300ec3647db167957d27a51ccdd/index.js#L32-L41
train
camshaft/anvil-cli
lib/local.js
find
function find(source, fn) { glob('**', {cwd: source, dot: true}, function(err, files) { fn(err, files); }); }
javascript
function find(source, fn) { glob('**', {cwd: source, dot: true}, function(err, files) { fn(err, files); }); }
[ "function", "find", "(", "source", ",", "fn", ")", "{", "glob", "(", "'**'", ",", "{", "cwd", ":", "source", ",", "dot", ":", "true", "}", ",", "function", "(", "err", ",", "files", ")", "{", "fn", "(", "err", ",", "files", ")", ";", "}", ")", ";", "}" ]
Glob source dir @param {String} source @param {Function} fn
[ "Glob", "source", "dir" ]
5930e2165698c5577a0bcfa471dd521089acfb78
https://github.com/camshaft/anvil-cli/blob/5930e2165698c5577a0bcfa471dd521089acfb78/lib/local.js#L106-L110
train
camshaft/anvil-cli
lib/local.js
filterIgnored
function filterIgnored(files, ignore, fn) { fn(null, files.filter(function(file) { // TODO make more robust return !~ignore.indexOf(file) && !~ignore.indexOf(file + '/'); })); }
javascript
function filterIgnored(files, ignore, fn) { fn(null, files.filter(function(file) { // TODO make more robust return !~ignore.indexOf(file) && !~ignore.indexOf(file + '/'); })); }
[ "function", "filterIgnored", "(", "files", ",", "ignore", ",", "fn", ")", "{", "fn", "(", "null", ",", "files", ".", "filter", "(", "function", "(", "file", ")", "{", "return", "!", "~", "ignore", ".", "indexOf", "(", "file", ")", "&&", "!", "~", "ignore", ".", "indexOf", "(", "file", "+", "'/'", ")", ";", "}", ")", ")", ";", "}" ]
Filter ignored files @param {Array} files @param {Array} ignore
[ "Filter", "ignored", "files" ]
5930e2165698c5577a0bcfa471dd521089acfb78
https://github.com/camshaft/anvil-cli/blob/5930e2165698c5577a0bcfa471dd521089acfb78/lib/local.js#L132-L137
train
camshaft/anvil-cli
lib/local.js
statFiles
function statFiles(files, source, fn) { var batch = new Batch(); files.forEach(function(file) { batch.push(statFile(file, source)); }); batch.end(fn); }
javascript
function statFiles(files, source, fn) { var batch = new Batch(); files.forEach(function(file) { batch.push(statFile(file, source)); }); batch.end(fn); }
[ "function", "statFiles", "(", "files", ",", "source", ",", "fn", ")", "{", "var", "batch", "=", "new", "Batch", "(", ")", ";", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "batch", ".", "push", "(", "statFile", "(", "file", ",", "source", ")", ")", ";", "}", ")", ";", "batch", ".", "end", "(", "fn", ")", ";", "}" ]
Get files info @param {Array} files @param {String} source @param {Function} fn
[ "Get", "files", "info" ]
5930e2165698c5577a0bcfa471dd521089acfb78
https://github.com/camshaft/anvil-cli/blob/5930e2165698c5577a0bcfa471dd521089acfb78/lib/local.js#L147-L155
train
camshaft/anvil-cli
lib/local.js
statFile
function statFile(file, source) { return function(cb) { var abs = join(source, file); stat(abs, function(err, stats) { if (err) return cb(err); var manifest = { name: file, abs: abs, mtime: Math.floor(stats.mtime.getTime() / 1000), mode: '' + parseInt(stats.mode.toString(8), 10), size: '' + stats.size // do we need this? }; if (stats.isDirectory()) return cb(); if (stats.isSymbolicLink()) return fs.readlink(abs, finish('link')); calculateHash(abs, finish('hash')); function finish(key) { return function(err, val) { if (err) return cb(err); manifest[key] = val; cb(null, manifest); }; } }); }; }
javascript
function statFile(file, source) { return function(cb) { var abs = join(source, file); stat(abs, function(err, stats) { if (err) return cb(err); var manifest = { name: file, abs: abs, mtime: Math.floor(stats.mtime.getTime() / 1000), mode: '' + parseInt(stats.mode.toString(8), 10), size: '' + stats.size // do we need this? }; if (stats.isDirectory()) return cb(); if (stats.isSymbolicLink()) return fs.readlink(abs, finish('link')); calculateHash(abs, finish('hash')); function finish(key) { return function(err, val) { if (err) return cb(err); manifest[key] = val; cb(null, manifest); }; } }); }; }
[ "function", "statFile", "(", "file", ",", "source", ")", "{", "return", "function", "(", "cb", ")", "{", "var", "abs", "=", "join", "(", "source", ",", "file", ")", ";", "stat", "(", "abs", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "var", "manifest", "=", "{", "name", ":", "file", ",", "abs", ":", "abs", ",", "mtime", ":", "Math", ".", "floor", "(", "stats", ".", "mtime", ".", "getTime", "(", ")", "/", "1000", ")", ",", "mode", ":", "''", "+", "parseInt", "(", "stats", ".", "mode", ".", "toString", "(", "8", ")", ",", "10", ")", ",", "size", ":", "''", "+", "stats", ".", "size", "}", ";", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "return", "cb", "(", ")", ";", "if", "(", "stats", ".", "isSymbolicLink", "(", ")", ")", "return", "fs", ".", "readlink", "(", "abs", ",", "finish", "(", "'link'", ")", ")", ";", "calculateHash", "(", "abs", ",", "finish", "(", "'hash'", ")", ")", ";", "function", "finish", "(", "key", ")", "{", "return", "function", "(", "err", ",", "val", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "manifest", "[", "key", "]", "=", "val", ";", "cb", "(", "null", ",", "manifest", ")", ";", "}", ";", "}", "}", ")", ";", "}", ";", "}" ]
Get a file manifest @param {String} file @param {String} source @return {Function}
[ "Get", "a", "file", "manifest" ]
5930e2165698c5577a0bcfa471dd521089acfb78
https://github.com/camshaft/anvil-cli/blob/5930e2165698c5577a0bcfa471dd521089acfb78/lib/local.js#L165-L192
train
camshaft/anvil-cli
lib/local.js
calculateHash
function calculateHash(file, fn) { read(file, function(err, bin) { if (err) return fn(err); fn(null, hash('sha256').update(bin).digest('hex')); }); }
javascript
function calculateHash(file, fn) { read(file, function(err, bin) { if (err) return fn(err); fn(null, hash('sha256').update(bin).digest('hex')); }); }
[ "function", "calculateHash", "(", "file", ",", "fn", ")", "{", "read", "(", "file", ",", "function", "(", "err", ",", "bin", ")", "{", "if", "(", "err", ")", "return", "fn", "(", "err", ")", ";", "fn", "(", "null", ",", "hash", "(", "'sha256'", ")", ".", "update", "(", "bin", ")", ".", "digest", "(", "'hex'", ")", ")", ";", "}", ")", ";", "}" ]
Calculate hash for a file @param {String} file @param {Function} fn
[ "Calculate", "hash", "for", "a", "file" ]
5930e2165698c5577a0bcfa471dd521089acfb78
https://github.com/camshaft/anvil-cli/blob/5930e2165698c5577a0bcfa471dd521089acfb78/lib/local.js#L201-L206
train
camshaft/anvil-cli
lib/local.js
normalizeManifest
function normalizeManifest(manifest, fn) { var obj = {}; manifest.forEach(function(file) { if (!file) return; obj[file.name] = { mtime: file.mtime, mode: file.mode, size: file.size, hash: file.hash, link: file.link }; }); fn(null, obj); }
javascript
function normalizeManifest(manifest, fn) { var obj = {}; manifest.forEach(function(file) { if (!file) return; obj[file.name] = { mtime: file.mtime, mode: file.mode, size: file.size, hash: file.hash, link: file.link }; }); fn(null, obj); }
[ "function", "normalizeManifest", "(", "manifest", ",", "fn", ")", "{", "var", "obj", "=", "{", "}", ";", "manifest", ".", "forEach", "(", "function", "(", "file", ")", "{", "if", "(", "!", "file", ")", "return", ";", "obj", "[", "file", ".", "name", "]", "=", "{", "mtime", ":", "file", ".", "mtime", ",", "mode", ":", "file", ".", "mode", ",", "size", ":", "file", ".", "size", ",", "hash", ":", "file", ".", "hash", ",", "link", ":", "file", ".", "link", "}", ";", "}", ")", ";", "fn", "(", "null", ",", "obj", ")", ";", "}" ]
Normalize the manifest into the expected format @param {Object} manifest @param {Function} fn
[ "Normalize", "the", "manifest", "into", "the", "expected", "format" ]
5930e2165698c5577a0bcfa471dd521089acfb78
https://github.com/camshaft/anvil-cli/blob/5930e2165698c5577a0bcfa471dd521089acfb78/lib/local.js#L215-L228
train
camshaft/anvil-cli
lib/local.js
findMissing
function findMissing(manifest, request, host, fn) { request .post(host + '/manifest/diff') .send({manifest: JSON.stringify(manifest)}) .end(function(err, res) { if (err) return fn(err); if (res.error) return fn(res.error); fn(null, res.body); }); }
javascript
function findMissing(manifest, request, host, fn) { request .post(host + '/manifest/diff') .send({manifest: JSON.stringify(manifest)}) .end(function(err, res) { if (err) return fn(err); if (res.error) return fn(res.error); fn(null, res.body); }); }
[ "function", "findMissing", "(", "manifest", ",", "request", ",", "host", ",", "fn", ")", "{", "request", ".", "post", "(", "host", "+", "'/manifest/diff'", ")", ".", "send", "(", "{", "manifest", ":", "JSON", ".", "stringify", "(", "manifest", ")", "}", ")", ".", "end", "(", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "return", "fn", "(", "err", ")", ";", "if", "(", "res", ".", "error", ")", "return", "fn", "(", "res", ".", "error", ")", ";", "fn", "(", "null", ",", "res", ".", "body", ")", ";", "}", ")", ";", "}" ]
Find the missing files in the manifest @param {Object} manifest @param {Request} request @param {String} host @param {Function} fn
[ "Find", "the", "missing", "files", "in", "the", "manifest" ]
5930e2165698c5577a0bcfa471dd521089acfb78
https://github.com/camshaft/anvil-cli/blob/5930e2165698c5577a0bcfa471dd521089acfb78/lib/local.js#L239-L248
train
camshaft/anvil-cli
lib/local.js
selectMissing
function selectMissing(missing, manifest, fn) { fn(null, manifest.filter(function(file) { return file && ~missing.indexOf(file.hash); })); }
javascript
function selectMissing(missing, manifest, fn) { fn(null, manifest.filter(function(file) { return file && ~missing.indexOf(file.hash); })); }
[ "function", "selectMissing", "(", "missing", ",", "manifest", ",", "fn", ")", "{", "fn", "(", "null", ",", "manifest", ".", "filter", "(", "function", "(", "file", ")", "{", "return", "file", "&&", "~", "missing", ".", "indexOf", "(", "file", ".", "hash", ")", ";", "}", ")", ")", ";", "}" ]
Find the missing files from the manifest @param {Array} missing @param {Array} manifest @param {Function} fn
[ "Find", "the", "missing", "files", "from", "the", "manifest" ]
5930e2165698c5577a0bcfa471dd521089acfb78
https://github.com/camshaft/anvil-cli/blob/5930e2165698c5577a0bcfa471dd521089acfb78/lib/local.js#L258-L262
train
camshaft/anvil-cli
lib/local.js
uploadMissing
function uploadMissing(missing, request, host, log, fn) { var batch = new Batch(); missing.forEach(function(file) { batch.push(uploadFile(file, request, host)); }); batch.on('progress', function() { log('.'); }); batch.end(function(err, res) { log(' done\n'); fn(err, res); }); }
javascript
function uploadMissing(missing, request, host, log, fn) { var batch = new Batch(); missing.forEach(function(file) { batch.push(uploadFile(file, request, host)); }); batch.on('progress', function() { log('.'); }); batch.end(function(err, res) { log(' done\n'); fn(err, res); }); }
[ "function", "uploadMissing", "(", "missing", ",", "request", ",", "host", ",", "log", ",", "fn", ")", "{", "var", "batch", "=", "new", "Batch", "(", ")", ";", "missing", ".", "forEach", "(", "function", "(", "file", ")", "{", "batch", ".", "push", "(", "uploadFile", "(", "file", ",", "request", ",", "host", ")", ")", ";", "}", ")", ";", "batch", ".", "on", "(", "'progress'", ",", "function", "(", ")", "{", "log", "(", "'.'", ")", ";", "}", ")", ";", "batch", ".", "end", "(", "function", "(", "err", ",", "res", ")", "{", "log", "(", "' done\\n'", ")", ";", "\\n", "}", ")", ";", "}" ]
Upload the missing files to the build server @param {Array} missing @param {Request} request @param {String} host @param {Function} fn
[ "Upload", "the", "missing", "files", "to", "the", "build", "server" ]
5930e2165698c5577a0bcfa471dd521089acfb78
https://github.com/camshaft/anvil-cli/blob/5930e2165698c5577a0bcfa471dd521089acfb78/lib/local.js#L273-L288
train
camshaft/anvil-cli
lib/local.js
uploadFile
function uploadFile(file, request, host) { return function(cb) { request .post(host + '/file/' + file.hash) .attach('data', file.abs) .end(function(err, res) { if (err) return cb(err); if (res.error) return cb(res.error); return cb(); }); }; }
javascript
function uploadFile(file, request, host) { return function(cb) { request .post(host + '/file/' + file.hash) .attach('data', file.abs) .end(function(err, res) { if (err) return cb(err); if (res.error) return cb(res.error); return cb(); }); }; }
[ "function", "uploadFile", "(", "file", ",", "request", ",", "host", ")", "{", "return", "function", "(", "cb", ")", "{", "request", ".", "post", "(", "host", "+", "'/file/'", "+", "file", ".", "hash", ")", ".", "attach", "(", "'data'", ",", "file", ".", "abs", ")", ".", "end", "(", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "if", "(", "res", ".", "error", ")", "return", "cb", "(", "res", ".", "error", ")", ";", "return", "cb", "(", ")", ";", "}", ")", ";", "}", ";", "}" ]
Upload a single file to the build server @param {String} file @param {Request} request @param {String} host @return {Function}
[ "Upload", "a", "single", "file", "to", "the", "build", "server" ]
5930e2165698c5577a0bcfa471dd521089acfb78
https://github.com/camshaft/anvil-cli/blob/5930e2165698c5577a0bcfa471dd521089acfb78/lib/local.js#L299-L310
train
camshaft/anvil-cli
lib/local.js
saveManifest
function saveManifest(manifest, request, host, fn) { request .post(host + '/manifest') .send({manifest: JSON.stringify(manifest)}) .end(function(err, res) { if (err) return fn(err); if (res.error) return fn(res.error); fn(null, res.headers.location); }); }
javascript
function saveManifest(manifest, request, host, fn) { request .post(host + '/manifest') .send({manifest: JSON.stringify(manifest)}) .end(function(err, res) { if (err) return fn(err); if (res.error) return fn(res.error); fn(null, res.headers.location); }); }
[ "function", "saveManifest", "(", "manifest", ",", "request", ",", "host", ",", "fn", ")", "{", "request", ".", "post", "(", "host", "+", "'/manifest'", ")", ".", "send", "(", "{", "manifest", ":", "JSON", ".", "stringify", "(", "manifest", ")", "}", ")", ".", "end", "(", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "return", "fn", "(", "err", ")", ";", "if", "(", "res", ".", "error", ")", "return", "fn", "(", "res", ".", "error", ")", ";", "fn", "(", "null", ",", "res", ".", "headers", ".", "location", ")", ";", "}", ")", ";", "}" ]
Save the manifest file to the build server @param {Object} manifest @param {Request} request @param {String} host @param {Function} fn
[ "Save", "the", "manifest", "file", "to", "the", "build", "server" ]
5930e2165698c5577a0bcfa471dd521089acfb78
https://github.com/camshaft/anvil-cli/blob/5930e2165698c5577a0bcfa471dd521089acfb78/lib/local.js#L321-L330
train
yanhick/middlebot
lib/index.js
use
function use(type) { // Convert args to array. var args = Array.prototype.slice.call(arguments); // Check if type not provided. if ('string' !== typeof type && type instanceof Array === false) { type = []; } else { if ('string' === typeof type) { //wrap string in array to homogenize handling type = [type]; } args.shift(); } args.forEach(function(arg){ stack.push({type: type, cb: arg}); }); return middlebot; }
javascript
function use(type) { // Convert args to array. var args = Array.prototype.slice.call(arguments); // Check if type not provided. if ('string' !== typeof type && type instanceof Array === false) { type = []; } else { if ('string' === typeof type) { //wrap string in array to homogenize handling type = [type]; } args.shift(); } args.forEach(function(arg){ stack.push({type: type, cb: arg}); }); return middlebot; }
[ "function", "use", "(", "type", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "if", "(", "'string'", "!==", "typeof", "type", "&&", "type", "instanceof", "Array", "===", "false", ")", "{", "type", "=", "[", "]", ";", "}", "else", "{", "if", "(", "'string'", "===", "typeof", "type", ")", "{", "type", "=", "[", "type", "]", ";", "}", "args", ".", "shift", "(", ")", ";", "}", "args", ".", "forEach", "(", "function", "(", "arg", ")", "{", "stack", ".", "push", "(", "{", "type", ":", "type", ",", "cb", ":", "arg", "}", ")", ";", "}", ")", ";", "return", "middlebot", ";", "}" ]
Add a middleware in the stack for the given type. @param {*} type the handler type where to use the middleware. If not provided, middleware is always used. Can be either a string or an array of string @param {function} middlewares @returns the middlebot instance
[ "Add", "a", "middleware", "in", "the", "stack", "for", "the", "given", "type", "." ]
1920d56c0f4b162d892b8b7f70df575875bc943c
https://github.com/yanhick/middlebot/blob/1920d56c0f4b162d892b8b7f70df575875bc943c/lib/index.js#L29-L49
train
yanhick/middlebot
lib/index.js
handle
function handle(type, req, res, out) { var index = 0; var ended = false; // When called stop middlewares execution. res.end = end; // Handle next middleware in stack. function next(err) { var middleware = stack[index++]; // No more middlewares or early end. if (!middleware || ended) { if (out) out(err, req, res); return; } // Check if middleware type matches or if it has no type. if (middleware.type.indexOf(type) === -1 && middleware.type.length > 0) return next(err); try { var arity = middleware.cb.length; //if err, only execute error middlewares if (err) { //error middlewares have an arity of 4, the first //arg being the error if (arity === 4) { middleware.cb(err, req, res, next); } else { next(err); } } else if (arity < 4) { middleware.cb(req, res, next); } else { next(); } } catch (e) { next(e); } } // Stop middlewares execution. function end() { ended = true; } // Start handling. next(); }
javascript
function handle(type, req, res, out) { var index = 0; var ended = false; // When called stop middlewares execution. res.end = end; // Handle next middleware in stack. function next(err) { var middleware = stack[index++]; // No more middlewares or early end. if (!middleware || ended) { if (out) out(err, req, res); return; } // Check if middleware type matches or if it has no type. if (middleware.type.indexOf(type) === -1 && middleware.type.length > 0) return next(err); try { var arity = middleware.cb.length; //if err, only execute error middlewares if (err) { //error middlewares have an arity of 4, the first //arg being the error if (arity === 4) { middleware.cb(err, req, res, next); } else { next(err); } } else if (arity < 4) { middleware.cb(req, res, next); } else { next(); } } catch (e) { next(e); } } // Stop middlewares execution. function end() { ended = true; } // Start handling. next(); }
[ "function", "handle", "(", "type", ",", "req", ",", "res", ",", "out", ")", "{", "var", "index", "=", "0", ";", "var", "ended", "=", "false", ";", "res", ".", "end", "=", "end", ";", "function", "next", "(", "err", ")", "{", "var", "middleware", "=", "stack", "[", "index", "++", "]", ";", "if", "(", "!", "middleware", "||", "ended", ")", "{", "if", "(", "out", ")", "out", "(", "err", ",", "req", ",", "res", ")", ";", "return", ";", "}", "if", "(", "middleware", ".", "type", ".", "indexOf", "(", "type", ")", "===", "-", "1", "&&", "middleware", ".", "type", ".", "length", ">", "0", ")", "return", "next", "(", "err", ")", ";", "try", "{", "var", "arity", "=", "middleware", ".", "cb", ".", "length", ";", "if", "(", "err", ")", "{", "if", "(", "arity", "===", "4", ")", "{", "middleware", ".", "cb", "(", "err", ",", "req", ",", "res", ",", "next", ")", ";", "}", "else", "{", "next", "(", "err", ")", ";", "}", "}", "else", "if", "(", "arity", "<", "4", ")", "{", "middleware", ".", "cb", "(", "req", ",", "res", ",", "next", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "next", "(", "e", ")", ";", "}", "}", "function", "end", "(", ")", "{", "ended", "=", "true", ";", "}", "next", "(", ")", ";", "}" ]
Handle all middlewares of the provided type. @param {string} type the middleware type to handle @param {Object} req request object @param {Object} res response object @param {function} out optional function to be called once all middleware have been handled @returns the middlebot instance
[ "Handle", "all", "middlewares", "of", "the", "provided", "type", "." ]
1920d56c0f4b162d892b8b7f70df575875bc943c
https://github.com/yanhick/middlebot/blob/1920d56c0f4b162d892b8b7f70df575875bc943c/lib/index.js#L65-L115
train
readwritetools/rwserve-plugin-sdk
dist/expect.function.js
writeToConsoleOrStderr
function writeToConsoleOrStderr(message) { if (typeof console == 'object' && typeof console.warn == 'function') console.warn(message); else if (typeof process == 'object' && typeof process.stderr == 'object' && typeof process.stderr.write == 'function') process.stderr.write(message); else throw new Error(message); }
javascript
function writeToConsoleOrStderr(message) { if (typeof console == 'object' && typeof console.warn == 'function') console.warn(message); else if (typeof process == 'object' && typeof process.stderr == 'object' && typeof process.stderr.write == 'function') process.stderr.write(message); else throw new Error(message); }
[ "function", "writeToConsoleOrStderr", "(", "message", ")", "{", "if", "(", "typeof", "console", "==", "'object'", "&&", "typeof", "console", ".", "warn", "==", "'function'", ")", "console", ".", "warn", "(", "message", ")", ";", "else", "if", "(", "typeof", "process", "==", "'object'", "&&", "typeof", "process", ".", "stderr", "==", "'object'", "&&", "typeof", "process", ".", "stderr", ".", "write", "==", "'function'", ")", "process", ".", "stderr", ".", "write", "(", "message", ")", ";", "else", "throw", "new", "Error", "(", "message", ")", ";", "}" ]
^ Send message to browser console or CLI stderr
[ "^", "Send", "message", "to", "browser", "console", "or", "CLI", "stderr" ]
7f3b86b4d5279e26306225983c3d7f382f69dcce
https://github.com/readwritetools/rwserve-plugin-sdk/blob/7f3b86b4d5279e26306225983c3d7f382f69dcce/dist/expect.function.js#L90-L97
train
frisb/fdboost
lib/enhance/encoding/typecodes.js
function(value) { switch (typeof value) { case 'undefined': return this.undefined; case 'string': return this.string; case 'number': if (value % 1 === 0) { return this.integer; } else { return this.double; } break; case 'boolean': return this.boolean; case 'function': return this["function"]; default: if (value === null) { return this["null"]; } else if (value instanceof Date) { return this.datetime; } else if (value instanceof Array) { return this.array; } else if (Buffer.isBuffer(value)) { throw new TypeError("Value cannot be a buffer"); } else if (value instanceof Object) { return this.object; } else { throw new TypeError('Value must either be a string, integer, double, boolean, date, array, object or function'); } } }
javascript
function(value) { switch (typeof value) { case 'undefined': return this.undefined; case 'string': return this.string; case 'number': if (value % 1 === 0) { return this.integer; } else { return this.double; } break; case 'boolean': return this.boolean; case 'function': return this["function"]; default: if (value === null) { return this["null"]; } else if (value instanceof Date) { return this.datetime; } else if (value instanceof Array) { return this.array; } else if (Buffer.isBuffer(value)) { throw new TypeError("Value cannot be a buffer"); } else if (value instanceof Object) { return this.object; } else { throw new TypeError('Value must either be a string, integer, double, boolean, date, array, object or function'); } } }
[ "function", "(", "value", ")", "{", "switch", "(", "typeof", "value", ")", "{", "case", "'undefined'", ":", "return", "this", ".", "undefined", ";", "case", "'string'", ":", "return", "this", ".", "string", ";", "case", "'number'", ":", "if", "(", "value", "%", "1", "===", "0", ")", "{", "return", "this", ".", "integer", ";", "}", "else", "{", "return", "this", ".", "double", ";", "}", "break", ";", "case", "'boolean'", ":", "return", "this", ".", "boolean", ";", "case", "'function'", ":", "return", "this", "[", "\"function\"", "]", ";", "default", ":", "if", "(", "value", "===", "null", ")", "{", "return", "this", "[", "\"null\"", "]", ";", "}", "else", "if", "(", "value", "instanceof", "Date", ")", "{", "return", "this", ".", "datetime", ";", "}", "else", "if", "(", "value", "instanceof", "Array", ")", "{", "return", "this", ".", "array", ";", "}", "else", "if", "(", "Buffer", ".", "isBuffer", "(", "value", ")", ")", "{", "throw", "new", "TypeError", "(", "\"Value cannot be a buffer\"", ")", ";", "}", "else", "if", "(", "value", "instanceof", "Object", ")", "{", "return", "this", ".", "object", ";", "}", "else", "{", "throw", "new", "TypeError", "(", "'Value must either be a string, integer, double, boolean, date, array, object or function'", ")", ";", "}", "}", "}" ]
Gets type code value for name. @method @param {string} value Value to test type for. @return {integer} Type code value
[ "Gets", "type", "code", "value", "for", "name", "." ]
66cfb6552940aa92f35dbb1cf4d0695d842205c2
https://github.com/frisb/fdboost/blob/66cfb6552940aa92f35dbb1cf4d0695d842205c2/lib/enhance/encoding/typecodes.js#L36-L68
train
tmpfs/manual
index.js
preamble
function preamble(opts) { var str = ''; var index = opts.section || SECTION; var date = opts.date || new Date().toISOString(); var version = opts.version || '1.0'; // section name var sname = section(index); var title = opts.title || opts.name; if(!title) { throw new TypeError('manual preamble requires a name or title'); } // use comment if(opts.comment) { str += util.format(elements.comment, opts.comment); } //console.dir(title) str += util.format( elements.th, strip(title.toUpperCase()), index, date, (strip(opts.name || title)).replace(/\s+.*$/, '') + ' ' + version, sname); // add name section if(opts.name) { var name = strip(opts.name); str += util.format(elements.sh, header(constants.NAME)); if(opts.description) { str += util.format('%s \\- %s' + EOL, name, opts.description); }else{ str += util.format('%s' + EOL, name); } } return str; }
javascript
function preamble(opts) { var str = ''; var index = opts.section || SECTION; var date = opts.date || new Date().toISOString(); var version = opts.version || '1.0'; // section name var sname = section(index); var title = opts.title || opts.name; if(!title) { throw new TypeError('manual preamble requires a name or title'); } // use comment if(opts.comment) { str += util.format(elements.comment, opts.comment); } //console.dir(title) str += util.format( elements.th, strip(title.toUpperCase()), index, date, (strip(opts.name || title)).replace(/\s+.*$/, '') + ' ' + version, sname); // add name section if(opts.name) { var name = strip(opts.name); str += util.format(elements.sh, header(constants.NAME)); if(opts.description) { str += util.format('%s \\- %s' + EOL, name, opts.description); }else{ str += util.format('%s' + EOL, name); } } return str; }
[ "function", "preamble", "(", "opts", ")", "{", "var", "str", "=", "''", ";", "var", "index", "=", "opts", ".", "section", "||", "SECTION", ";", "var", "date", "=", "opts", ".", "date", "||", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ";", "var", "version", "=", "opts", ".", "version", "||", "'1.0'", ";", "var", "sname", "=", "section", "(", "index", ")", ";", "var", "title", "=", "opts", ".", "title", "||", "opts", ".", "name", ";", "if", "(", "!", "title", ")", "{", "throw", "new", "TypeError", "(", "'manual preamble requires a name or title'", ")", ";", "}", "if", "(", "opts", ".", "comment", ")", "{", "str", "+=", "util", ".", "format", "(", "elements", ".", "comment", ",", "opts", ".", "comment", ")", ";", "}", "str", "+=", "util", ".", "format", "(", "elements", ".", "th", ",", "strip", "(", "title", ".", "toUpperCase", "(", ")", ")", ",", "index", ",", "date", ",", "(", "strip", "(", "opts", ".", "name", "||", "title", ")", ")", ".", "replace", "(", "/", "\\s+.*$", "/", ",", "''", ")", "+", "' '", "+", "version", ",", "sname", ")", ";", "if", "(", "opts", ".", "name", ")", "{", "var", "name", "=", "strip", "(", "opts", ".", "name", ")", ";", "str", "+=", "util", ".", "format", "(", "elements", ".", "sh", ",", "header", "(", "constants", ".", "NAME", ")", ")", ";", "if", "(", "opts", ".", "description", ")", "{", "str", "+=", "util", ".", "format", "(", "'%s \\\\- %s'", "+", "\\\\", ",", "EOL", ",", "name", ")", ";", "}", "else", "opts", ".", "description", "}", "{", "str", "+=", "util", ".", "format", "(", "'%s'", "+", "EOL", ",", "name", ")", ";", "}", "}" ]
Gets the preamble for a man page. @param options The preamble options. @param options.title The document title. @param options.version A version number. @param options.date Document generation date. @param options.section The man section number (1-8). @param options.comment A comment string. @param options.name A name that indicates the name section should be added. @param options.description A short description to go aside the name.
[ "Gets", "the", "preamble", "for", "a", "man", "page", "." ]
5a869c4c49e18f7014969eec529ec9e9c9d7ba05
https://github.com/tmpfs/manual/blob/5a869c4c49e18f7014969eec529ec9e9c9d7ba05/index.js#L111-L147
train
CCISEL/connect-controller
lib/RouteInfo.js
splitActionName
function splitActionName(actionName) { if(actionName.indexOf('_') > 0) return actionName.split('_') else return actionName.split(/(?=[A-Z])/).map(p => p.toLowerCase()) }
javascript
function splitActionName(actionName) { if(actionName.indexOf('_') > 0) return actionName.split('_') else return actionName.split(/(?=[A-Z])/).map(p => p.toLowerCase()) }
[ "function", "splitActionName", "(", "actionName", ")", "{", "if", "(", "actionName", ".", "indexOf", "(", "'_'", ")", ">", "0", ")", "return", "actionName", ".", "split", "(", "'_'", ")", "else", "return", "actionName", ".", "split", "(", "/", "(?=[A-Z])", "/", ")", ".", "map", "(", "p", "=>", "p", ".", "toLowerCase", "(", ")", ")", "}" ]
Returns an array with the action's name split by underscores or lowerCamelCase.
[ "Returns", "an", "array", "with", "the", "action", "s", "name", "split", "by", "underscores", "or", "lowerCamelCase", "." ]
c8e2587c5a31e3cb54e3668c4b98b7b7526d69b4
https://github.com/CCISEL/connect-controller/blob/c8e2587c5a31e3cb54e3668c4b98b7b7526d69b4/lib/RouteInfo.js#L163-L166
train
CCISEL/connect-controller
lib/RouteInfo.js
parseMethodName
function parseMethodName(parts, argsNames) { /** * argsName could be in different case from that * of function's name. */ const argsNamesLower = argsNames.map(arg => arg.toLowerCase()) /** * Suppresses HTTP method if exists */ if(keysMethods.indexOf(parts[0].toLowerCase()) >= 0) parts = parts.slice(1) /** * Converts each method part into route path */ return parts.reduce((prev, curr) => { if(keywordsMaps[curr]) prev += keywordsMaps[curr] else { if(prev.slice(-1) != '/') prev += '/' const index = argsNamesLower.indexOf(curr.toLowerCase()) if(index >= 0) { prev += ':' prev += argsNames[index] // Preserve argument Case } else { prev += curr } } return prev }, '') }
javascript
function parseMethodName(parts, argsNames) { /** * argsName could be in different case from that * of function's name. */ const argsNamesLower = argsNames.map(arg => arg.toLowerCase()) /** * Suppresses HTTP method if exists */ if(keysMethods.indexOf(parts[0].toLowerCase()) >= 0) parts = parts.slice(1) /** * Converts each method part into route path */ return parts.reduce((prev, curr) => { if(keywordsMaps[curr]) prev += keywordsMaps[curr] else { if(prev.slice(-1) != '/') prev += '/' const index = argsNamesLower.indexOf(curr.toLowerCase()) if(index >= 0) { prev += ':' prev += argsNames[index] // Preserve argument Case } else { prev += curr } } return prev }, '') }
[ "function", "parseMethodName", "(", "parts", ",", "argsNames", ")", "{", "const", "argsNamesLower", "=", "argsNames", ".", "map", "(", "arg", "=>", "arg", ".", "toLowerCase", "(", ")", ")", "if", "(", "keysMethods", ".", "indexOf", "(", "parts", "[", "0", "]", ".", "toLowerCase", "(", ")", ")", ">=", "0", ")", "parts", "=", "parts", ".", "slice", "(", "1", ")", "return", "parts", ".", "reduce", "(", "(", "prev", ",", "curr", ")", "=>", "{", "if", "(", "keywordsMaps", "[", "curr", "]", ")", "prev", "+=", "keywordsMaps", "[", "curr", "]", "else", "{", "if", "(", "prev", ".", "slice", "(", "-", "1", ")", "!=", "'/'", ")", "prev", "+=", "'/'", "const", "index", "=", "argsNamesLower", ".", "indexOf", "(", "curr", ".", "toLowerCase", "(", ")", ")", "if", "(", "index", ">=", "0", ")", "{", "prev", "+=", "':'", "prev", "+=", "argsNames", "[", "index", "]", "}", "else", "{", "prev", "+=", "curr", "}", "}", "return", "prev", "}", ",", "''", ")", "}" ]
Returns the route path for the corresponding controller method name.
[ "Returns", "the", "route", "path", "for", "the", "corresponding", "controller", "method", "name", "." ]
c8e2587c5a31e3cb54e3668c4b98b7b7526d69b4
https://github.com/CCISEL/connect-controller/blob/c8e2587c5a31e3cb54e3668c4b98b7b7526d69b4/lib/RouteInfo.js#L172-L200
train
CCISEL/connect-controller
lib/RouteInfo.js
parseHttpMethod
function parseHttpMethod(parts) { const prefix = parts[0].toLowerCase() if(keysMethods.indexOf(prefix) >= 0) return prefix else return GET }
javascript
function parseHttpMethod(parts) { const prefix = parts[0].toLowerCase() if(keysMethods.indexOf(prefix) >= 0) return prefix else return GET }
[ "function", "parseHttpMethod", "(", "parts", ")", "{", "const", "prefix", "=", "parts", "[", "0", "]", ".", "toLowerCase", "(", ")", "if", "(", "keysMethods", ".", "indexOf", "(", "prefix", ")", ">=", "0", ")", "return", "prefix", "else", "return", "GET", "}" ]
Gets the HTTP method from the Controller method name. Otherwise returns 'get'.
[ "Gets", "the", "HTTP", "method", "from", "the", "Controller", "method", "name", ".", "Otherwise", "returns", "get", "." ]
c8e2587c5a31e3cb54e3668c4b98b7b7526d69b4
https://github.com/CCISEL/connect-controller/blob/c8e2587c5a31e3cb54e3668c4b98b7b7526d69b4/lib/RouteInfo.js#L206-L212
train
CCISEL/connect-controller
lib/RouteInfo.js
lookupParameterOnReq
function lookupParameterOnReq(name, index, length) { return (req, res) => { if(req[name]) return req[name] if(req.query && req.query[name]) return req.query[name] if(req.body && req.body[name]) return req.body[name] if(res.locals && res.locals[name]) return res.locals[name] if(req.app.locals && req.app.locals[name]) return req.app.locals[name] /** * In this case there is not a matching property in Request object for * the given parameter name. * We just accept it, if that is the last parameter of the method, in which * case it should correspond to a callback. */ if(index != (length - 1)) throw new Error('Parameter ' + name + ' not found in Request object!!!' ) return null } }
javascript
function lookupParameterOnReq(name, index, length) { return (req, res) => { if(req[name]) return req[name] if(req.query && req.query[name]) return req.query[name] if(req.body && req.body[name]) return req.body[name] if(res.locals && res.locals[name]) return res.locals[name] if(req.app.locals && req.app.locals[name]) return req.app.locals[name] /** * In this case there is not a matching property in Request object for * the given parameter name. * We just accept it, if that is the last parameter of the method, in which * case it should correspond to a callback. */ if(index != (length - 1)) throw new Error('Parameter ' + name + ' not found in Request object!!!' ) return null } }
[ "function", "lookupParameterOnReq", "(", "name", ",", "index", ",", "length", ")", "{", "return", "(", "req", ",", "res", ")", "=>", "{", "if", "(", "req", "[", "name", "]", ")", "return", "req", "[", "name", "]", "if", "(", "req", ".", "query", "&&", "req", ".", "query", "[", "name", "]", ")", "return", "req", ".", "query", "[", "name", "]", "if", "(", "req", ".", "body", "&&", "req", ".", "body", "[", "name", "]", ")", "return", "req", ".", "body", "[", "name", "]", "if", "(", "res", ".", "locals", "&&", "res", ".", "locals", "[", "name", "]", ")", "return", "res", ".", "locals", "[", "name", "]", "if", "(", "req", ".", "app", ".", "locals", "&&", "req", ".", "app", ".", "locals", "[", "name", "]", ")", "return", "req", ".", "app", ".", "locals", "[", "name", "]", "if", "(", "index", "!=", "(", "length", "-", "1", ")", ")", "throw", "new", "Error", "(", "'Parameter '", "+", "name", "+", "' not found in Request object!!!'", ")", "return", "null", "}", "}" ]
!!!!!DEPRECATED >= 2.0.1 Given the name of a parameter search for it in req, req.query, req.body, res.locals, app.locals.
[ "!!!!!DEPRECATED", ">", "=", "2", ".", "0", ".", "1", "Given", "the", "name", "of", "a", "parameter", "search", "for", "it", "in", "req", "req", ".", "query", "req", ".", "body", "res", ".", "locals", "app", ".", "locals", "." ]
c8e2587c5a31e3cb54e3668c4b98b7b7526d69b4
https://github.com/CCISEL/connect-controller/blob/c8e2587c5a31e3cb54e3668c4b98b7b7526d69b4/lib/RouteInfo.js#L245-L263
train
assemble/assemble-loader
index.js
appLoader
function appLoader(app, config) { app.define('load', load('view', config)); var fn = app.view; app.define('view', function() { var view = fn.apply(this, arguments); utils.contents.sync(view); return view; }); }
javascript
function appLoader(app, config) { app.define('load', load('view', config)); var fn = app.view; app.define('view', function() { var view = fn.apply(this, arguments); utils.contents.sync(view); return view; }); }
[ "function", "appLoader", "(", "app", ",", "config", ")", "{", "app", ".", "define", "(", "'load'", ",", "load", "(", "'view'", ",", "config", ")", ")", ";", "var", "fn", "=", "app", ".", "view", ";", "app", ".", "define", "(", "'view'", ",", "function", "(", ")", "{", "var", "view", "=", "fn", ".", "apply", "(", "this", ",", "arguments", ")", ";", "utils", ".", "contents", ".", "sync", "(", "view", ")", ";", "return", "view", ";", "}", ")", ";", "}" ]
Adds a `.load` method to the "app" instance for loading views that that don't belong to any particular collection. It just returns the object of views instead of caching them. ```js var loader = require('assemble-loader'); var assemble = require('assemble'); var app = assemble(); app.use(loader()); var views = app.load('foo/*.hbs'); console.log(views); ``` @param {Object} `app` application instance (e.g. assemble, verb, etc) @param {Object} `config` Settings to use when registering the plugin @return {Object} Returns an object of _un-cached_ views, from a glob, string, array of strings, or objects. @api public
[ "Adds", "a", ".", "load", "method", "to", "the", "app", "instance", "for", "loading", "views", "that", "that", "don", "t", "belong", "to", "any", "particular", "collection", ".", "It", "just", "returns", "the", "object", "of", "views", "instead", "of", "caching", "them", "." ]
6d6b001cfa43c0628098f1e77c4d74292b3dbb0d
https://github.com/assemble/assemble-loader/blob/6d6b001cfa43c0628098f1e77c4d74292b3dbb0d/index.js#L59-L68
train
assemble/assemble-loader
index.js
createLoader
function createLoader(options, fn) { var loader = new utils.Loader(options); return function() { if (!this.isApp) loader.cache = this.views; loader.options.loaderFn = fn.bind(this); loader.load.apply(loader, arguments); return loader.cache; }; }
javascript
function createLoader(options, fn) { var loader = new utils.Loader(options); return function() { if (!this.isApp) loader.cache = this.views; loader.options.loaderFn = fn.bind(this); loader.load.apply(loader, arguments); return loader.cache; }; }
[ "function", "createLoader", "(", "options", ",", "fn", ")", "{", "var", "loader", "=", "new", "utils", ".", "Loader", "(", "options", ")", ";", "return", "function", "(", ")", "{", "if", "(", "!", "this", ".", "isApp", ")", "loader", ".", "cache", "=", "this", ".", "views", ";", "loader", ".", "options", ".", "loaderFn", "=", "fn", ".", "bind", "(", "this", ")", ";", "loader", ".", "load", ".", "apply", "(", "loader", ",", "arguments", ")", ";", "return", "loader", ".", "cache", ";", "}", ";", "}" ]
Create a `Loader` instance with a `loaderfn` bound to the app or collection instance.
[ "Create", "a", "Loader", "instance", "with", "a", "loaderfn", "bound", "to", "the", "app", "or", "collection", "instance", "." ]
6d6b001cfa43c0628098f1e77c4d74292b3dbb0d
https://github.com/assemble/assemble-loader/blob/6d6b001cfa43c0628098f1e77c4d74292b3dbb0d/index.js#L143-L151
train
assemble/assemble-loader
index.js
load
function load(method, config) { return function(patterns, options) { var opts = mergeOptions(this, config, options); var loader = createLoader(opts, this[method]); return loader.apply(this, arguments); }; }
javascript
function load(method, config) { return function(patterns, options) { var opts = mergeOptions(this, config, options); var loader = createLoader(opts, this[method]); return loader.apply(this, arguments); }; }
[ "function", "load", "(", "method", ",", "config", ")", "{", "return", "function", "(", "patterns", ",", "options", ")", "{", "var", "opts", "=", "mergeOptions", "(", "this", ",", "config", ",", "options", ")", ";", "var", "loader", "=", "createLoader", "(", "opts", ",", "this", "[", "method", "]", ")", ";", "return", "loader", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "}" ]
Create a function for loading views using the given `method` on the collection or app.
[ "Create", "a", "function", "for", "loading", "views", "using", "the", "given", "method", "on", "the", "collection", "or", "app", "." ]
6d6b001cfa43c0628098f1e77c4d74292b3dbb0d
https://github.com/assemble/assemble-loader/blob/6d6b001cfa43c0628098f1e77c4d74292b3dbb0d/index.js#L158-L164
train
Nichejs/Seminarjs
private/lib/core/start.js
function () { waitForServers--; if (waitForServers) return; if (seminarjs.get('logger')) { console.log(dashes + startupMessages.join('\n') + dashes); } events.onStart && events.onStart(); }
javascript
function () { waitForServers--; if (waitForServers) return; if (seminarjs.get('logger')) { console.log(dashes + startupMessages.join('\n') + dashes); } events.onStart && events.onStart(); }
[ "function", "(", ")", "{", "waitForServers", "--", ";", "if", "(", "waitForServers", ")", "return", ";", "if", "(", "seminarjs", ".", "get", "(", "'logger'", ")", ")", "{", "console", ".", "log", "(", "dashes", "+", "startupMessages", ".", "join", "(", "'\\n'", ")", "+", "\\n", ")", ";", "}", "dashes", "}" ]
Log the startup messages and calls the onStart method
[ "Log", "the", "startup", "messages", "and", "calls", "the", "onStart", "method" ]
53c4c1d5c33ffbf6320b10f25679bf181cbf853e
https://github.com/Nichejs/Seminarjs/blob/53c4c1d5c33ffbf6320b10f25679bf181cbf853e/private/lib/core/start.js#L89-L96
train
thiagodp/better-randstr
index.js
randstr
function randstr(options) { var opt = _validateOptions(options); var from, to; if (Array.isArray(opt.length)) { _a = opt.length, from = _a[0], to = _a[1]; } else { from = to = opt.length; } var str = ''; if (0 === to) { return str; } var charsIsString = 'string' === typeof opt.chars; var charsLastIndex = charsIsString ? opt.chars.length - 1 : 0; var includeControlChars = true === opt.includeControlChars; var hasAcceptableFunc = 'function' === typeof opt.acceptable; var hasReplacer = 'function' === typeof opt.replacer; var max = _randomIntBetween(opt.random, from, to); // console.log( 'max', max, 'from', from, 'to', to ); for (var i = 0, len = 0, charCode = void 0, chr = void 0; i < max && len < max; ++i) { if (charsIsString) { var index = _randomIntBetween(opt.random, 0, charsLastIndex); charCode = opt.chars.charCodeAt(index); } else { charCode = _randomIntBetween(opt.random, opt.chars[0], opt.chars[1]); } // Non printable? if (!includeControlChars && _isControlChar(charCode)) { // console.log( 'NOT PRINTABLE!'); --i; // back to try again continue; } chr = String.fromCharCode(charCode); // console.log( 'charCode', charCode, 'char', chr ); if (hasAcceptableFunc && !opt.acceptable.call(null, chr)) { --i; // back to try again continue; } if (hasReplacer) { chr = opt.replacer.call(null, chr); // console.log( 'char after', chr ); // Their combined length pass the limit? if ((len + chr.length) > max) { // console.log( 'greater than max!', 'i', i, 'max', max, 'str', len, 'chr', chr.length ); --i; // back to try again continue; } } str += chr; len = str.length; } return str; var _a; }
javascript
function randstr(options) { var opt = _validateOptions(options); var from, to; if (Array.isArray(opt.length)) { _a = opt.length, from = _a[0], to = _a[1]; } else { from = to = opt.length; } var str = ''; if (0 === to) { return str; } var charsIsString = 'string' === typeof opt.chars; var charsLastIndex = charsIsString ? opt.chars.length - 1 : 0; var includeControlChars = true === opt.includeControlChars; var hasAcceptableFunc = 'function' === typeof opt.acceptable; var hasReplacer = 'function' === typeof opt.replacer; var max = _randomIntBetween(opt.random, from, to); // console.log( 'max', max, 'from', from, 'to', to ); for (var i = 0, len = 0, charCode = void 0, chr = void 0; i < max && len < max; ++i) { if (charsIsString) { var index = _randomIntBetween(opt.random, 0, charsLastIndex); charCode = opt.chars.charCodeAt(index); } else { charCode = _randomIntBetween(opt.random, opt.chars[0], opt.chars[1]); } // Non printable? if (!includeControlChars && _isControlChar(charCode)) { // console.log( 'NOT PRINTABLE!'); --i; // back to try again continue; } chr = String.fromCharCode(charCode); // console.log( 'charCode', charCode, 'char', chr ); if (hasAcceptableFunc && !opt.acceptable.call(null, chr)) { --i; // back to try again continue; } if (hasReplacer) { chr = opt.replacer.call(null, chr); // console.log( 'char after', chr ); // Their combined length pass the limit? if ((len + chr.length) > max) { // console.log( 'greater than max!', 'i', i, 'max', max, 'str', len, 'chr', chr.length ); --i; // back to try again continue; } } str += chr; len = str.length; } return str; var _a; }
[ "function", "randstr", "(", "options", ")", "{", "var", "opt", "=", "_validateOptions", "(", "options", ")", ";", "var", "from", ",", "to", ";", "if", "(", "Array", ".", "isArray", "(", "opt", ".", "length", ")", ")", "{", "_a", "=", "opt", ".", "length", ",", "from", "=", "_a", "[", "0", "]", ",", "to", "=", "_a", "[", "1", "]", ";", "}", "else", "{", "from", "=", "to", "=", "opt", ".", "length", ";", "}", "var", "str", "=", "''", ";", "if", "(", "0", "===", "to", ")", "{", "return", "str", ";", "}", "var", "charsIsString", "=", "'string'", "===", "typeof", "opt", ".", "chars", ";", "var", "charsLastIndex", "=", "charsIsString", "?", "opt", ".", "chars", ".", "length", "-", "1", ":", "0", ";", "var", "includeControlChars", "=", "true", "===", "opt", ".", "includeControlChars", ";", "var", "hasAcceptableFunc", "=", "'function'", "===", "typeof", "opt", ".", "acceptable", ";", "var", "hasReplacer", "=", "'function'", "===", "typeof", "opt", ".", "replacer", ";", "var", "max", "=", "_randomIntBetween", "(", "opt", ".", "random", ",", "from", ",", "to", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "0", ",", "charCode", "=", "void", "0", ",", "chr", "=", "void", "0", ";", "i", "<", "max", "&&", "len", "<", "max", ";", "++", "i", ")", "{", "if", "(", "charsIsString", ")", "{", "var", "index", "=", "_randomIntBetween", "(", "opt", ".", "random", ",", "0", ",", "charsLastIndex", ")", ";", "charCode", "=", "opt", ".", "chars", ".", "charCodeAt", "(", "index", ")", ";", "}", "else", "{", "charCode", "=", "_randomIntBetween", "(", "opt", ".", "random", ",", "opt", ".", "chars", "[", "0", "]", ",", "opt", ".", "chars", "[", "1", "]", ")", ";", "}", "if", "(", "!", "includeControlChars", "&&", "_isControlChar", "(", "charCode", ")", ")", "{", "--", "i", ";", "continue", ";", "}", "chr", "=", "String", ".", "fromCharCode", "(", "charCode", ")", ";", "if", "(", "hasAcceptableFunc", "&&", "!", "opt", ".", "acceptable", ".", "call", "(", "null", ",", "chr", ")", ")", "{", "--", "i", ";", "continue", ";", "}", "if", "(", "hasReplacer", ")", "{", "chr", "=", "opt", ".", "replacer", ".", "call", "(", "null", ",", "chr", ")", ";", "if", "(", "(", "len", "+", "chr", ".", "length", ")", ">", "max", ")", "{", "--", "i", ";", "continue", ";", "}", "}", "str", "+=", "chr", ";", "len", "=", "str", ".", "length", ";", "}", "return", "str", ";", "var", "_a", ";", "}" ]
Generates a random string according to the given options. @param options Options @returns a string
[ "Generates", "a", "random", "string", "according", "to", "the", "given", "options", "." ]
e63bc3085ad87e6f5ed1c59e5710e599127c3dce
https://github.com/thiagodp/better-randstr/blob/e63bc3085ad87e6f5ed1c59e5710e599127c3dce/index.js#L132-L187
train
niallo/deadlift
lib/deploy.js
updateStatus
function updateStatus(evType, opts) { var t2 = new Date() var elapsed = (t2.getTime() - t1.getTime()) / 1000 var msg = { timeElapsed:elapsed, stdout: opts.stdout || "", stderr: opts.stderr || "", stdmerged: opts.stdmerged || "", info: opts.info, step: opts.step, deployExitCode: null, url: null || opts.url, } if (opts.deployExitCode !== undefined) { msg.deployExitCode = opts.deployExitCode } emitter.emit(evType, msg) }
javascript
function updateStatus(evType, opts) { var t2 = new Date() var elapsed = (t2.getTime() - t1.getTime()) / 1000 var msg = { timeElapsed:elapsed, stdout: opts.stdout || "", stderr: opts.stderr || "", stdmerged: opts.stdmerged || "", info: opts.info, step: opts.step, deployExitCode: null, url: null || opts.url, } if (opts.deployExitCode !== undefined) { msg.deployExitCode = opts.deployExitCode } emitter.emit(evType, msg) }
[ "function", "updateStatus", "(", "evType", ",", "opts", ")", "{", "var", "t2", "=", "new", "Date", "(", ")", "var", "elapsed", "=", "(", "t2", ".", "getTime", "(", ")", "-", "t1", ".", "getTime", "(", ")", ")", "/", "1000", "var", "msg", "=", "{", "timeElapsed", ":", "elapsed", ",", "stdout", ":", "opts", ".", "stdout", "||", "\"\"", ",", "stderr", ":", "opts", ".", "stderr", "||", "\"\"", ",", "stdmerged", ":", "opts", ".", "stdmerged", "||", "\"\"", ",", "info", ":", "opts", ".", "info", ",", "step", ":", "opts", ".", "step", ",", "deployExitCode", ":", "null", ",", "url", ":", "null", "||", "opts", ".", "url", ",", "}", "if", "(", "opts", ".", "deployExitCode", "!==", "undefined", ")", "{", "msg", ".", "deployExitCode", "=", "opts", ".", "deployExitCode", "}", "emitter", ".", "emit", "(", "evType", ",", "msg", ")", "}" ]
Emit a status update event. This can result in data being sent to the user's browser in realtime via socket.io.
[ "Emit", "a", "status", "update", "event", ".", "This", "can", "result", "in", "data", "being", "sent", "to", "the", "user", "s", "browser", "in", "realtime", "via", "socket", ".", "io", "." ]
ff37d4eeccc326ec5e1390394585f6ac10bcc703
https://github.com/niallo/deadlift/blob/ff37d4eeccc326ec5e1390394585f6ac10bcc703/lib/deploy.js#L24-L42
train
blake-regalia/spaz.js
lib/main/js_sparql.js
function(s_thing) { if(H_SPARQL_CHARS[s_thing[0]]) return s_thing; else if(s_thing.indexOf(':') != -1) return s_thing; else if(s_thing == 'a') return s_thing; else return ':'+s_thing; }
javascript
function(s_thing) { if(H_SPARQL_CHARS[s_thing[0]]) return s_thing; else if(s_thing.indexOf(':') != -1) return s_thing; else if(s_thing == 'a') return s_thing; else return ':'+s_thing; }
[ "function", "(", "s_thing", ")", "{", "if", "(", "H_SPARQL_CHARS", "[", "s_thing", "[", "0", "]", "]", ")", "return", "s_thing", ";", "else", "if", "(", "s_thing", ".", "indexOf", "(", "':'", ")", "!=", "-", "1", ")", "return", "s_thing", ";", "else", "if", "(", "s_thing", "==", "'a'", ")", "return", "s_thing", ";", "else", "return", "':'", "+", "s_thing", ";", "}" ]
converts thing alias to proper identifier if not already specified
[ "converts", "thing", "alias", "to", "proper", "identifier", "if", "not", "already", "specified" ]
e0a04ab4783a0e386e245a3551e1a41bd746da35
https://github.com/blake-regalia/spaz.js/blob/e0a04ab4783a0e386e245a3551e1a41bd746da35/lib/main/js_sparql.js#L75-L80
train
blake-regalia/spaz.js
lib/main/js_sparql.js
function(s_str) { if(H_SPARQL_CHARS[s_str[0]]) return s_str; else if(s_str.indexOf(':') != -1) return s_str; else if(/^(?:[0-9]|(?:\-|\.|\-\.)[0-9])/.test(s_str)) return s_str; else return JSON.stringify(s_str); }
javascript
function(s_str) { if(H_SPARQL_CHARS[s_str[0]]) return s_str; else if(s_str.indexOf(':') != -1) return s_str; else if(/^(?:[0-9]|(?:\-|\.|\-\.)[0-9])/.test(s_str)) return s_str; else return JSON.stringify(s_str); }
[ "function", "(", "s_str", ")", "{", "if", "(", "H_SPARQL_CHARS", "[", "s_str", "[", "0", "]", "]", ")", "return", "s_str", ";", "else", "if", "(", "s_str", ".", "indexOf", "(", "':'", ")", "!=", "-", "1", ")", "return", "s_str", ";", "else", "if", "(", "/", "^(?:[0-9]|(?:\\-|\\.|\\-\\.)[0-9])", "/", ".", "test", "(", "s_str", ")", ")", "return", "s_str", ";", "else", "return", "JSON", ".", "stringify", "(", "s_str", ")", ";", "}" ]
converts string to proper identifier if not already specified
[ "converts", "string", "to", "proper", "identifier", "if", "not", "already", "specified" ]
e0a04ab4783a0e386e245a3551e1a41bd746da35
https://github.com/blake-regalia/spaz.js/blob/e0a04ab4783a0e386e245a3551e1a41bd746da35/lib/main/js_sparql.js#L90-L95
train
blake-regalia/spaz.js
lib/main/js_sparql.js
function(sq_prefixes) { var s_select = this.select || '*'; var sq_select = 'SELECT '+s_select+' WHERE {'; var sq_where = this.where; var sq_tail = this.tail; var sq_group = this.group? ' GROUP BY '+this.group: ''; var sq_order = this.order? ' ORDER BY '+this.order: ''; var sq_limit_offset = this.limit; var sq_close = '\n}'; return '' +sq_prefixes +sq_select +sq_where +sq_tail +sq_close +sq_group +sq_order +sq_limit_offset; }
javascript
function(sq_prefixes) { var s_select = this.select || '*'; var sq_select = 'SELECT '+s_select+' WHERE {'; var sq_where = this.where; var sq_tail = this.tail; var sq_group = this.group? ' GROUP BY '+this.group: ''; var sq_order = this.order? ' ORDER BY '+this.order: ''; var sq_limit_offset = this.limit; var sq_close = '\n}'; return '' +sq_prefixes +sq_select +sq_where +sq_tail +sq_close +sq_group +sq_order +sq_limit_offset; }
[ "function", "(", "sq_prefixes", ")", "{", "var", "s_select", "=", "this", ".", "select", "||", "'*'", ";", "var", "sq_select", "=", "'SELECT '", "+", "s_select", "+", "' WHERE {'", ";", "var", "sq_where", "=", "this", ".", "where", ";", "var", "sq_tail", "=", "this", ".", "tail", ";", "var", "sq_group", "=", "this", ".", "group", "?", "' GROUP BY '", "+", "this", ".", "group", ":", "''", ";", "var", "sq_order", "=", "this", ".", "order", "?", "' ORDER BY '", "+", "this", ".", "order", ":", "''", ";", "var", "sq_limit_offset", "=", "this", ".", "limit", ";", "var", "sq_close", "=", "'\\n}'", ";", "\\n", "}" ]
converts query hash to sparql string
[ "converts", "query", "hash", "to", "sparql", "string" ]
e0a04ab4783a0e386e245a3551e1a41bd746da35
https://github.com/blake-regalia/spaz.js/blob/e0a04ab4783a0e386e245a3551e1a41bd746da35/lib/main/js_sparql.js#L98-L116
train
blake-regalia/spaz.js
lib/main/js_sparql.js
function(s_query, f_okay) { $.ajax({ url: s_endpoint_url+'query', method: 'GET', data: { query: s_query, }, dataType: 'json', success: function(h_res) { f_okay && f_okay(h_res); }, }); }
javascript
function(s_query, f_okay) { $.ajax({ url: s_endpoint_url+'query', method: 'GET', data: { query: s_query, }, dataType: 'json', success: function(h_res) { f_okay && f_okay(h_res); }, }); }
[ "function", "(", "s_query", ",", "f_okay", ")", "{", "$", ".", "ajax", "(", "{", "url", ":", "s_endpoint_url", "+", "'query'", ",", "method", ":", "'GET'", ",", "data", ":", "{", "query", ":", "s_query", ",", "}", ",", "dataType", ":", "'json'", ",", "success", ":", "function", "(", "h_res", ")", "{", "f_okay", "&&", "f_okay", "(", "h_res", ")", ";", "}", ",", "}", ")", ";", "}" ]
submits a query
[ "submits", "a", "query" ]
e0a04ab4783a0e386e245a3551e1a41bd746da35
https://github.com/blake-regalia/spaz.js/blob/e0a04ab4783a0e386e245a3551e1a41bd746da35/lib/main/js_sparql.js#L131-L143
train
blake-regalia/spaz.js
lib/main/js_sparql.js
function(h_subjects, b_raw) { // initiliaze output var s_out = ''; // add slot for tail var s_tail = ''; // newline + indent var _ = '\n\t'+(b_raw? '\t':''); // root nodes must be subjects for(var s_rs in h_subjects) { // var z_predicates = h_subjects[s_rs]; // declaring optional block if(s_rs == '?') { // these are subjects actually var h_write = query_hash(z_predicates, true); s_out += _+'OPTIONAL {'+h_write.where+_+'}'; s_tail += h_write.tail; } // regular query hash else { var s_rsi = rdf_var(s_rs); // this is subject s_out += _+s_rsi; // predicates are in hash if(typeof z_predicates == 'object') { // recurse var a_write = build_from_ph(z_predicates, _); s_out += a_write[0]+' .'; s_tail += a_write[1]; } } } var h_raw = { treated_vars: {subs:{},lists:{}}, select: '', where: s_out, tail: s_tail, group: '', order: '', limit: '', }; return (b_raw? h_raw: qb(h_raw)); }
javascript
function(h_subjects, b_raw) { // initiliaze output var s_out = ''; // add slot for tail var s_tail = ''; // newline + indent var _ = '\n\t'+(b_raw? '\t':''); // root nodes must be subjects for(var s_rs in h_subjects) { // var z_predicates = h_subjects[s_rs]; // declaring optional block if(s_rs == '?') { // these are subjects actually var h_write = query_hash(z_predicates, true); s_out += _+'OPTIONAL {'+h_write.where+_+'}'; s_tail += h_write.tail; } // regular query hash else { var s_rsi = rdf_var(s_rs); // this is subject s_out += _+s_rsi; // predicates are in hash if(typeof z_predicates == 'object') { // recurse var a_write = build_from_ph(z_predicates, _); s_out += a_write[0]+' .'; s_tail += a_write[1]; } } } var h_raw = { treated_vars: {subs:{},lists:{}}, select: '', where: s_out, tail: s_tail, group: '', order: '', limit: '', }; return (b_raw? h_raw: qb(h_raw)); }
[ "function", "(", "h_subjects", ",", "b_raw", ")", "{", "var", "s_out", "=", "''", ";", "var", "s_tail", "=", "''", ";", "var", "_", "=", "'\\n\\t'", "+", "\\n", ";", "\\t", "(", "b_raw", "?", "'\\t'", ":", "\\t", ")", "''", "}" ]
constructs sparql query string from hash
[ "constructs", "sparql", "query", "string", "from", "hash" ]
e0a04ab4783a0e386e245a3551e1a41bd746da35
https://github.com/blake-regalia/spaz.js/blob/e0a04ab4783a0e386e245a3551e1a41bd746da35/lib/main/js_sparql.js#L415-L471
train
blake-regalia/spaz.js
lib/main/js_sparql.js
function(s_query) { // execute function var f_exec = function(f_okay) { submit_query(s_query, f_okay); }; var d_self = { exec: f_exec, results: function(f_okay) { f_exec(function(h_res) { f_okay && f_okay(h_res.results.bindings); }); }, each: function(f_each, f_okay) { f_exec(function(h_res) { if(!f_each) return; var a_rows = h_res.results.bindings; for(var i=0,l=a_rows.length; i<l; i++) { var h_row = a_rows[i]; var h_this = {}; for(var e in h_row) h_this[e] = h_row[e].value; f_each.apply(h_this, [i, h_row]); } f_okay && f_okay(); }); }, }; return d_self; }
javascript
function(s_query) { // execute function var f_exec = function(f_okay) { submit_query(s_query, f_okay); }; var d_self = { exec: f_exec, results: function(f_okay) { f_exec(function(h_res) { f_okay && f_okay(h_res.results.bindings); }); }, each: function(f_each, f_okay) { f_exec(function(h_res) { if(!f_each) return; var a_rows = h_res.results.bindings; for(var i=0,l=a_rows.length; i<l; i++) { var h_row = a_rows[i]; var h_this = {}; for(var e in h_row) h_this[e] = h_row[e].value; f_each.apply(h_this, [i, h_row]); } f_okay && f_okay(); }); }, }; return d_self; }
[ "function", "(", "s_query", ")", "{", "var", "f_exec", "=", "function", "(", "f_okay", ")", "{", "submit_query", "(", "s_query", ",", "f_okay", ")", ";", "}", ";", "var", "d_self", "=", "{", "exec", ":", "f_exec", ",", "results", ":", "function", "(", "f_okay", ")", "{", "f_exec", "(", "function", "(", "h_res", ")", "{", "f_okay", "&&", "f_okay", "(", "h_res", ".", "results", ".", "bindings", ")", ";", "}", ")", ";", "}", ",", "each", ":", "function", "(", "f_each", ",", "f_okay", ")", "{", "f_exec", "(", "function", "(", "h_res", ")", "{", "if", "(", "!", "f_each", ")", "return", ";", "var", "a_rows", "=", "h_res", ".", "results", ".", "bindings", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "a_rows", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "h_row", "=", "a_rows", "[", "i", "]", ";", "var", "h_this", "=", "{", "}", ";", "for", "(", "var", "e", "in", "h_row", ")", "h_this", "[", "e", "]", "=", "h_row", "[", "e", "]", ".", "value", ";", "f_each", ".", "apply", "(", "h_this", ",", "[", "i", ",", "h_row", "]", ")", ";", "}", "f_okay", "&&", "f_okay", "(", ")", ";", "}", ")", ";", "}", ",", "}", ";", "return", "d_self", ";", "}" ]
executes raw sparql query from string
[ "executes", "raw", "sparql", "query", "from", "string" ]
e0a04ab4783a0e386e245a3551e1a41bd746da35
https://github.com/blake-regalia/spaz.js/blob/e0a04ab4783a0e386e245a3551e1a41bd746da35/lib/main/js_sparql.js#L475-L505
train
blake-regalia/spaz.js
lib/main/js_sparql.js
function(channel) { return function() { var args = Array.prototype.slice.call(arguments); args.unshift(__class+':'); console[channel].apply(console, args); }; }
javascript
function(channel) { return function() { var args = Array.prototype.slice.call(arguments); args.unshift(__class+':'); console[channel].apply(console, args); }; }
[ "function", "(", "channel", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "args", ".", "unshift", "(", "__class", "+", "':'", ")", ";", "console", "[", "channel", "]", ".", "apply", "(", "console", ",", "args", ")", ";", "}", ";", "}" ]
output a message to the console prefixed with this class's tag
[ "output", "a", "message", "to", "the", "console", "prefixed", "with", "this", "class", "s", "tag" ]
e0a04ab4783a0e386e245a3551e1a41bd746da35
https://github.com/blake-regalia/spaz.js/blob/e0a04ab4783a0e386e245a3551e1a41bd746da35/lib/main/js_sparql.js#L599-L605
train
richRemer/twixt-select
select.js
into
function into(impl) { /** * @param {string} selector * @param {Document|Element} [context] */ return function(selector, context) { var callContext = this, extra; if (typeof selector === "string") { if (context && context.querySelector) { extra = Array.prototype.slice.call(arguments, 2); } else { extra = Array.prototype.slice.call(arguments, 1); context = document; } select(selector, context, function(elem) { impl.apply(callContext, [elem].concat(extra)); }); } else { impl.apply(callContext, arguments); } }; }
javascript
function into(impl) { /** * @param {string} selector * @param {Document|Element} [context] */ return function(selector, context) { var callContext = this, extra; if (typeof selector === "string") { if (context && context.querySelector) { extra = Array.prototype.slice.call(arguments, 2); } else { extra = Array.prototype.slice.call(arguments, 1); context = document; } select(selector, context, function(elem) { impl.apply(callContext, [elem].concat(extra)); }); } else { impl.apply(callContext, arguments); } }; }
[ "function", "into", "(", "impl", ")", "{", "return", "function", "(", "selector", ",", "context", ")", "{", "var", "callContext", "=", "this", ",", "extra", ";", "if", "(", "typeof", "selector", "===", "\"string\"", ")", "{", "if", "(", "context", "&&", "context", ".", "querySelector", ")", "{", "extra", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "2", ")", ";", "}", "else", "{", "extra", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "context", "=", "document", ";", "}", "select", "(", "selector", ",", "context", ",", "function", "(", "elem", ")", "{", "impl", ".", "apply", "(", "callContext", ",", "[", "elem", "]", ".", "concat", "(", "extra", ")", ")", ";", "}", ")", ";", "}", "else", "{", "impl", ".", "apply", "(", "callContext", ",", "arguments", ")", ";", "}", "}", ";", "}" ]
Create function composition which passes each selected element to a base function. @param {function} impl @returns {function}
[ "Create", "function", "composition", "which", "passes", "each", "selected", "element", "to", "a", "base", "function", "." ]
8f4cb70623f578d197a23a49e6dcd42a2bb772be
https://github.com/richRemer/twixt-select/blob/8f4cb70623f578d197a23a49e6dcd42a2bb772be/select.js#L7-L31
train
richRemer/twixt-select
select.js
select
function select(selector, context, fn) { var nodes; if (arguments.length === 2 && typeof context === "function") { fn = context; context = undefined; } nodes = (context || document).querySelectorAll(selector); nodes = Array.prototype.slice.call(nodes); if (fn) nodes.forEach(fn); else return nodes; }
javascript
function select(selector, context, fn) { var nodes; if (arguments.length === 2 && typeof context === "function") { fn = context; context = undefined; } nodes = (context || document).querySelectorAll(selector); nodes = Array.prototype.slice.call(nodes); if (fn) nodes.forEach(fn); else return nodes; }
[ "function", "select", "(", "selector", ",", "context", ",", "fn", ")", "{", "var", "nodes", ";", "if", "(", "arguments", ".", "length", "===", "2", "&&", "typeof", "context", "===", "\"function\"", ")", "{", "fn", "=", "context", ";", "context", "=", "undefined", ";", "}", "nodes", "=", "(", "context", "||", "document", ")", ".", "querySelectorAll", "(", "selector", ")", ";", "nodes", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "nodes", ")", ";", "if", "(", "fn", ")", "nodes", ".", "forEach", "(", "fn", ")", ";", "else", "return", "nodes", ";", "}" ]
Return selected elements or iterate and apply a function. @param {string} selector @param {Document|Element} [context] @param {function} [fn] @returns {Node[]}
[ "Return", "selected", "elements", "or", "iterate", "and", "apply", "a", "function", "." ]
8f4cb70623f578d197a23a49e6dcd42a2bb772be
https://github.com/richRemer/twixt-select/blob/8f4cb70623f578d197a23a49e6dcd42a2bb772be/select.js#L40-L53
train
brycebaril/node-loose-interval
index.js
LooseInterval
function LooseInterval(fn, interval, callback) { if (!(this instanceof LooseInterval)) return new LooseInterval(fn, interval, callback) if (typeof fn != "function") throw new Error("LooseInterval requires a function") if (typeof interval == "function") { callback = interval interval = null } this.fn = fn this.interval = interval this.callback = callback EventEmitter.call(this) this._running = false if (interval != null) this.start(interval) }
javascript
function LooseInterval(fn, interval, callback) { if (!(this instanceof LooseInterval)) return new LooseInterval(fn, interval, callback) if (typeof fn != "function") throw new Error("LooseInterval requires a function") if (typeof interval == "function") { callback = interval interval = null } this.fn = fn this.interval = interval this.callback = callback EventEmitter.call(this) this._running = false if (interval != null) this.start(interval) }
[ "function", "LooseInterval", "(", "fn", ",", "interval", ",", "callback", ")", "{", "if", "(", "!", "(", "this", "instanceof", "LooseInterval", ")", ")", "return", "new", "LooseInterval", "(", "fn", ",", "interval", ",", "callback", ")", "if", "(", "typeof", "fn", "!=", "\"function\"", ")", "throw", "new", "Error", "(", "\"LooseInterval requires a function\"", ")", "if", "(", "typeof", "interval", "==", "\"function\"", ")", "{", "callback", "=", "interval", "interval", "=", "null", "}", "this", ".", "fn", "=", "fn", "this", ".", "interval", "=", "interval", "this", ".", "callback", "=", "callback", "EventEmitter", ".", "call", "(", "this", ")", "this", ".", "_running", "=", "false", "if", "(", "interval", "!=", "null", ")", "this", ".", "start", "(", "interval", ")", "}" ]
Create a loose-interval repeated task. Like setInterval but will reschedule when the task finishes to avoid overlapping tasks. Your function must provide a callback to alert its completion. @param {Function} fn The function to repeatedly call. Must provide a callback. fn(cb) @param {Number} interval Millisecond interval to wait between the function's end next call. @param {Function} callback Callback to forward results to after each run.
[ "Create", "a", "loose", "-", "interval", "repeated", "task", ".", "Like", "setInterval", "but", "will", "reschedule", "when", "the", "task", "finishes", "to", "avoid", "overlapping", "tasks", ".", "Your", "function", "must", "provide", "a", "callback", "to", "alert", "its", "completion", "." ]
68d2880e2ab9b4978c488a3d55be491e0409ebd3
https://github.com/brycebaril/node-loose-interval/blob/68d2880e2ab9b4978c488a3d55be491e0409ebd3/index.js#L14-L30
train
Techniv/node-cmd-conf
libs/cmd-conf.js
process
function process(){ if (!conf.configured) that.configure(); var args = command.args.slice(0); for(var i in args){ var arg = args[i]; if(conf.regexp.test(arg)){ var catchWord = RegExp.$2; switch(RegExp.$1){ case '-': processShortKey(catchWord, i, args); break; case '--': processKey(catchWord, i, args); break; } } else { addArgument(arg); } } conf.processed = true }
javascript
function process(){ if (!conf.configured) that.configure(); var args = command.args.slice(0); for(var i in args){ var arg = args[i]; if(conf.regexp.test(arg)){ var catchWord = RegExp.$2; switch(RegExp.$1){ case '-': processShortKey(catchWord, i, args); break; case '--': processKey(catchWord, i, args); break; } } else { addArgument(arg); } } conf.processed = true }
[ "function", "process", "(", ")", "{", "if", "(", "!", "conf", ".", "configured", ")", "that", ".", "configure", "(", ")", ";", "var", "args", "=", "command", ".", "args", ".", "slice", "(", "0", ")", ";", "for", "(", "var", "i", "in", "args", ")", "{", "var", "arg", "=", "args", "[", "i", "]", ";", "if", "(", "conf", ".", "regexp", ".", "test", "(", "arg", ")", ")", "{", "var", "catchWord", "=", "RegExp", ".", "$2", ";", "switch", "(", "RegExp", ".", "$1", ")", "{", "case", "'-'", ":", "processShortKey", "(", "catchWord", ",", "i", ",", "args", ")", ";", "break", ";", "case", "'--'", ":", "processKey", "(", "catchWord", ",", "i", ",", "args", ")", ";", "break", ";", "}", "}", "else", "{", "addArgument", "(", "arg", ")", ";", "}", "}", "conf", ".", "processed", "=", "true", "}" ]
Fire the command line analyse
[ "Fire", "the", "command", "line", "analyse" ]
ecefaf9c1eb3a68a7ab4e5b9a0b71329a7d52646
https://github.com/Techniv/node-cmd-conf/blob/ecefaf9c1eb3a68a7ab4e5b9a0b71329a7d52646/libs/cmd-conf.js#L145-L165
train
ForbesLindesay-Unmaintained/sauce-test
lib/get-sauce-platforms.js
getPlatforms
function getPlatforms(options) { return request('GET', 'https://saucelabs.com/rest/v1/info/platforms/webdriver') .getBody('utf8').then(JSON.parse).then(function (platforms) { var obj = {}; platforms.map(function (platform) { return { browserName: platform.api_name, version: platform.short_version, platform: platform.os }; }).forEach(function (platform) { if (platform.browserName === 'lynx') return; if (!(options.filterPlatforms || defaultFilters.filterPlatforms)(platform, defaultFilters.filterPlatforms)) return; obj[platform.browserName] = obj[platform.browserName] || {}; obj[platform.browserName][platform.version] = obj[platform.browserName][platform.version] || []; obj[platform.browserName][platform.version].push(platform); }); var result = {}; Object.keys(obj).forEach(function (browser) { result[browser] = []; Object.keys(obj[browser]).sort(function (versionA, versionB) { if (isNaN(versionA) && isNaN(versionB)) return versionA < versionB ? -1 : 1; if (isNaN(versionA)) return -1; if (isNaN(versionB)) return 1; return (+versionB) - (+versionA); }).forEach(function (version, index) { var platforms = obj[browser][version]; result[browser] = result[browser].concat((options.choosePlatforms || defaultFilters.choosePlatforms)(platforms)); }); }); return result; }); }
javascript
function getPlatforms(options) { return request('GET', 'https://saucelabs.com/rest/v1/info/platforms/webdriver') .getBody('utf8').then(JSON.parse).then(function (platforms) { var obj = {}; platforms.map(function (platform) { return { browserName: platform.api_name, version: platform.short_version, platform: platform.os }; }).forEach(function (platform) { if (platform.browserName === 'lynx') return; if (!(options.filterPlatforms || defaultFilters.filterPlatforms)(platform, defaultFilters.filterPlatforms)) return; obj[platform.browserName] = obj[platform.browserName] || {}; obj[platform.browserName][platform.version] = obj[platform.browserName][platform.version] || []; obj[platform.browserName][platform.version].push(platform); }); var result = {}; Object.keys(obj).forEach(function (browser) { result[browser] = []; Object.keys(obj[browser]).sort(function (versionA, versionB) { if (isNaN(versionA) && isNaN(versionB)) return versionA < versionB ? -1 : 1; if (isNaN(versionA)) return -1; if (isNaN(versionB)) return 1; return (+versionB) - (+versionA); }).forEach(function (version, index) { var platforms = obj[browser][version]; result[browser] = result[browser].concat((options.choosePlatforms || defaultFilters.choosePlatforms)(platforms)); }); }); return result; }); }
[ "function", "getPlatforms", "(", "options", ")", "{", "return", "request", "(", "'GET'", ",", "'https://saucelabs.com/rest/v1/info/platforms/webdriver'", ")", ".", "getBody", "(", "'utf8'", ")", ".", "then", "(", "JSON", ".", "parse", ")", ".", "then", "(", "function", "(", "platforms", ")", "{", "var", "obj", "=", "{", "}", ";", "platforms", ".", "map", "(", "function", "(", "platform", ")", "{", "return", "{", "browserName", ":", "platform", ".", "api_name", ",", "version", ":", "platform", ".", "short_version", ",", "platform", ":", "platform", ".", "os", "}", ";", "}", ")", ".", "forEach", "(", "function", "(", "platform", ")", "{", "if", "(", "platform", ".", "browserName", "===", "'lynx'", ")", "return", ";", "if", "(", "!", "(", "options", ".", "filterPlatforms", "||", "defaultFilters", ".", "filterPlatforms", ")", "(", "platform", ",", "defaultFilters", ".", "filterPlatforms", ")", ")", "return", ";", "obj", "[", "platform", ".", "browserName", "]", "=", "obj", "[", "platform", ".", "browserName", "]", "||", "{", "}", ";", "obj", "[", "platform", ".", "browserName", "]", "[", "platform", ".", "version", "]", "=", "obj", "[", "platform", ".", "browserName", "]", "[", "platform", ".", "version", "]", "||", "[", "]", ";", "obj", "[", "platform", ".", "browserName", "]", "[", "platform", ".", "version", "]", ".", "push", "(", "platform", ")", ";", "}", ")", ";", "var", "result", "=", "{", "}", ";", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "function", "(", "browser", ")", "{", "result", "[", "browser", "]", "=", "[", "]", ";", "Object", ".", "keys", "(", "obj", "[", "browser", "]", ")", ".", "sort", "(", "function", "(", "versionA", ",", "versionB", ")", "{", "if", "(", "isNaN", "(", "versionA", ")", "&&", "isNaN", "(", "versionB", ")", ")", "return", "versionA", "<", "versionB", "?", "-", "1", ":", "1", ";", "if", "(", "isNaN", "(", "versionA", ")", ")", "return", "-", "1", ";", "if", "(", "isNaN", "(", "versionB", ")", ")", "return", "1", ";", "return", "(", "+", "versionB", ")", "-", "(", "+", "versionA", ")", ";", "}", ")", ".", "forEach", "(", "function", "(", "version", ",", "index", ")", "{", "var", "platforms", "=", "obj", "[", "browser", "]", "[", "version", "]", ";", "result", "[", "browser", "]", "=", "result", "[", "browser", "]", ".", "concat", "(", "(", "options", ".", "choosePlatforms", "||", "defaultFilters", ".", "choosePlatforms", ")", "(", "platforms", ")", ")", ";", "}", ")", ";", "}", ")", ";", "return", "result", ";", "}", ")", ";", "}" ]
Get an object containing the platforms supported by sauce labs Platforms: ```js { "chrome": [{"browserName": "chrome", "version": "34", platform:" Mac 10.9"}, ...] ... } ``` @option {Function.<Platform,Boolean>} filterPlatforms Return `true` to include the platform in the resulting set. @option {Function.<Array.<Platform>,Array.<Platform>>} choosePlatforms Return an array of platforms of a given version to include in the output. This lets you choose only one operating system for each browser version. @param {Options} options @returns {Promise.<Platforms>}
[ "Get", "an", "object", "containing", "the", "platforms", "supported", "by", "sauce", "labs" ]
7c671b3321dc63aefc00c1c8d49e943ead2e7f5e
https://github.com/ForbesLindesay-Unmaintained/sauce-test/blob/7c671b3321dc63aefc00c1c8d49e943ead2e7f5e/lib/get-sauce-platforms.js#L29-L61
train
rhyolight/github-data
lib/blob.js
Blob
function Blob(source, parent, githubClient) { this.gh = githubClient; this.parent = parent; this.sha = source.sha; this.rawContent = source.content; this.size = source.size; this.contents = new Buffer(this.rawContent, 'base64').toString('utf-8'); }
javascript
function Blob(source, parent, githubClient) { this.gh = githubClient; this.parent = parent; this.sha = source.sha; this.rawContent = source.content; this.size = source.size; this.contents = new Buffer(this.rawContent, 'base64').toString('utf-8'); }
[ "function", "Blob", "(", "source", ",", "parent", ",", "githubClient", ")", "{", "this", ".", "gh", "=", "githubClient", ";", "this", ".", "parent", "=", "parent", ";", "this", ".", "sha", "=", "source", ".", "sha", ";", "this", ".", "rawContent", "=", "source", ".", "content", ";", "this", ".", "size", "=", "source", ".", "size", ";", "this", ".", "contents", "=", "new", "Buffer", "(", "this", ".", "rawContent", ",", "'base64'", ")", ".", "toString", "(", "'utf-8'", ")", ";", "}" ]
A git blob object. @class Blob @param source {Object} JSON response from API, used to build. @param parent {Object} Expected to be {{#crossLink "Tree"}}{{/crossLink}}. @param githubClient {Object} GitHub API Client object. @constructor
[ "A", "git", "blob", "object", "." ]
5d6a3fc0e7ecfeaec03e4815b0940c2d9ce07d64
https://github.com/rhyolight/github-data/blob/5d6a3fc0e7ecfeaec03e4815b0940c2d9ce07d64/lib/blob.js#L9-L16
train
frankc60/jpretty
src/jPretty.js
pJson
function pJson(events, top = '') { Object.keys(events).forEach((i) => { if (typeof events[i] === 'object' && events[i] != null) { let rtn; if (Object.prototype.toString.call(events) === '[object Array]') { rtn = (`${top}[${i}]`); } else { rtn = (`${top}.${i}`); } pJson(events[i], rtn); } else if (Object.prototype.toString.call(events) === '[object Array]') { tmp += `{}${top}[${i}] = ${events[i]}\n`; } else { tmp += `{}${top}.${i} = ${events[i]}\n`; } }); }
javascript
function pJson(events, top = '') { Object.keys(events).forEach((i) => { if (typeof events[i] === 'object' && events[i] != null) { let rtn; if (Object.prototype.toString.call(events) === '[object Array]') { rtn = (`${top}[${i}]`); } else { rtn = (`${top}.${i}`); } pJson(events[i], rtn); } else if (Object.prototype.toString.call(events) === '[object Array]') { tmp += `{}${top}[${i}] = ${events[i]}\n`; } else { tmp += `{}${top}.${i} = ${events[i]}\n`; } }); }
[ "function", "pJson", "(", "events", ",", "top", "=", "''", ")", "{", "Object", ".", "keys", "(", "events", ")", ".", "forEach", "(", "(", "i", ")", "=>", "{", "if", "(", "typeof", "events", "[", "i", "]", "===", "'object'", "&&", "events", "[", "i", "]", "!=", "null", ")", "{", "let", "rtn", ";", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "events", ")", "===", "'[object Array]'", ")", "{", "rtn", "=", "(", "`", "${", "top", "}", "${", "i", "}", "`", ")", ";", "}", "else", "{", "rtn", "=", "(", "`", "${", "top", "}", "${", "i", "}", "`", ")", ";", "}", "pJson", "(", "events", "[", "i", "]", ",", "rtn", ")", ";", "}", "else", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "events", ")", "===", "'[object Array]'", ")", "{", "tmp", "+=", "`", "${", "top", "}", "${", "i", "}", "${", "events", "[", "i", "]", "}", "\\n", "`", ";", "}", "else", "{", "tmp", "+=", "`", "${", "top", "}", "${", "i", "}", "${", "events", "[", "i", "]", "}", "\\n", "`", ";", "}", "}", ")", ";", "}" ]
json needs to arrive stringified
[ "json", "needs", "to", "arrive", "stringified" ]
15c26bff27542c83ce28376b7065e09d2daa935a
https://github.com/frankc60/jpretty/blob/15c26bff27542c83ce28376b7065e09d2daa935a/src/jPretty.js#L11-L25
train
frankc60/jpretty
src/jPretty.js
jPretty
function jPretty(obj) { // make sure data is a json obj if(typeof obj === "string") { obj = obj.replace(/\s/g,""); obj = obj.replace(/'/g,'"'); } let gl; try { const p = JSON.parse(obj); gl = obj; // already stringified } catch (e) { // not stringified if(typeof obj === "string") { obj = obj.replace(/([,|{|\s|])([a-zA-Z0-9]*?)([\s|]*\:)/g,'$1"$2"$3'); } const s = JSON.stringify(obj); const k = JSON.parse(JSON.stringify(obj)); if (k && typeof k === 'object') { gl = s; } else { if(typeof obj === "string") { //console.log("ERROR: " + ); obj = obj.replace(/"/g,"'"); obj = obj.replace(/'/g,'"'); gl = ((obj)); } else { return new Error(`jpretty: input is not recognised json: ${typeof obj}- ${JSON.stringify(obj)}`); } } } return (() => { let jp = prettyJson(gl); if(typeof window !== 'undefined') { console.log("jPretty loaded in browser"); jp = jp.replace(/\{\}/g,"<br/>{}"); } return jp; })() }
javascript
function jPretty(obj) { // make sure data is a json obj if(typeof obj === "string") { obj = obj.replace(/\s/g,""); obj = obj.replace(/'/g,'"'); } let gl; try { const p = JSON.parse(obj); gl = obj; // already stringified } catch (e) { // not stringified if(typeof obj === "string") { obj = obj.replace(/([,|{|\s|])([a-zA-Z0-9]*?)([\s|]*\:)/g,'$1"$2"$3'); } const s = JSON.stringify(obj); const k = JSON.parse(JSON.stringify(obj)); if (k && typeof k === 'object') { gl = s; } else { if(typeof obj === "string") { //console.log("ERROR: " + ); obj = obj.replace(/"/g,"'"); obj = obj.replace(/'/g,'"'); gl = ((obj)); } else { return new Error(`jpretty: input is not recognised json: ${typeof obj}- ${JSON.stringify(obj)}`); } } } return (() => { let jp = prettyJson(gl); if(typeof window !== 'undefined') { console.log("jPretty loaded in browser"); jp = jp.replace(/\{\}/g,"<br/>{}"); } return jp; })() }
[ "function", "jPretty", "(", "obj", ")", "{", "if", "(", "typeof", "obj", "===", "\"string\"", ")", "{", "obj", "=", "obj", ".", "replace", "(", "/", "\\s", "/", "g", ",", "\"\"", ")", ";", "obj", "=", "obj", ".", "replace", "(", "/", "'", "/", "g", ",", "'\"'", ")", ";", "}", "let", "gl", ";", "try", "{", "const", "p", "=", "JSON", ".", "parse", "(", "obj", ")", ";", "gl", "=", "obj", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "typeof", "obj", "===", "\"string\"", ")", "{", "obj", "=", "obj", ".", "replace", "(", "/", "([,|{|\\s|])([a-zA-Z0-9]*?)([\\s|]*\\:)", "/", "g", ",", "'$1\"$2\"$3'", ")", ";", "}", "const", "s", "=", "JSON", ".", "stringify", "(", "obj", ")", ";", "const", "k", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "obj", ")", ")", ";", "if", "(", "k", "&&", "typeof", "k", "===", "'object'", ")", "{", "gl", "=", "s", ";", "}", "else", "{", "if", "(", "typeof", "obj", "===", "\"string\"", ")", "{", "obj", "=", "obj", ".", "replace", "(", "/", "\"", "/", "g", ",", "\"'\"", ")", ";", "obj", "=", "obj", ".", "replace", "(", "/", "'", "/", "g", ",", "'\"'", ")", ";", "gl", "=", "(", "(", "obj", ")", ")", ";", "}", "else", "{", "return", "new", "Error", "(", "`", "${", "typeof", "obj", "}", "${", "JSON", ".", "stringify", "(", "obj", ")", "}", "`", ")", ";", "}", "}", "}", "return", "(", "(", ")", "=>", "{", "let", "jp", "=", "prettyJson", "(", "gl", ")", ";", "if", "(", "typeof", "window", "!==", "'undefined'", ")", "{", "console", ".", "log", "(", "\"jPretty loaded in browser\"", ")", ";", "jp", "=", "jp", ".", "replace", "(", "/", "\\{\\}", "/", "g", ",", "\"<br/>{}\"", ")", ";", "}", "return", "jp", ";", "}", ")", "(", ")", "}" ]
Tidies up the json into a correct javascript object notation. @param {object} obj text or object. calls the main prettyJson module passing the json obj as argument.
[ "Tidies", "up", "the", "json", "into", "a", "correct", "javascript", "object", "notation", "." ]
15c26bff27542c83ce28376b7065e09d2daa935a
https://github.com/frankc60/jpretty/blob/15c26bff27542c83ce28376b7065e09d2daa935a/src/jPretty.js#L36-L77
train
Ma3Route/node-sdk
lib/client.js
Client
function Client(options) { options = options || { }; this._key = options.key || null; this._secret = options.secret || null; this._proxy = options.proxy || null; return this; }
javascript
function Client(options) { options = options || { }; this._key = options.key || null; this._secret = options.secret || null; this._proxy = options.proxy || null; return this; }
[ "function", "Client", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "_key", "=", "options", ".", "key", "||", "null", ";", "this", ".", "_secret", "=", "options", ".", "secret", "||", "null", ";", "this", ".", "_proxy", "=", "options", ".", "proxy", "||", "null", ";", "return", "this", ";", "}" ]
An API client. All the module functions can be accessed using a client @example // create a new client var client = new sdk.Client({ key: "SoM3C0mP1exKey", secret: "pSu3d0rAnD0mS3CrEt" }); // retrieive a single traffic update client.trafficUpdates.getOne(1, function(err, items) { console.log(err, items); }); @constructor @param {Object} [options] @param {String} options.key - API key @param {String} options.secret - API secret @param {String} options.proxy - a valid URL to use as proxy
[ "An", "API", "client", ".", "All", "the", "module", "functions", "can", "be", "accessed", "using", "a", "client" ]
a2769d97d77d6f762d23e743bf4c749e2bad0d8a
https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/client.js#L56-L62
train
AndiDittrich/Node.async-magic
lib/parallel.js
parallel
async function parallel(resolvers, limit=-1){ // set default limit if (limit < 1){ limit = 1000; } // buffer const results = []; // calculate chunk size // limit step size to input array size const chunkSize = Math.min(limit, resolvers.length); // process resolvers in chunks for (let i=0;i<resolvers.length;i=i+chunkSize){ // extract current chunk const chunk = resolvers.slice(i, Math.min(i+chunkSize, resolvers.length)); // resolve current chunk const intermediateResults = await Promise.all(chunk.map((r) => r.resolve())); // push results into buffer results.push(...intermediateResults); } // return results return results; }
javascript
async function parallel(resolvers, limit=-1){ // set default limit if (limit < 1){ limit = 1000; } // buffer const results = []; // calculate chunk size // limit step size to input array size const chunkSize = Math.min(limit, resolvers.length); // process resolvers in chunks for (let i=0;i<resolvers.length;i=i+chunkSize){ // extract current chunk const chunk = resolvers.slice(i, Math.min(i+chunkSize, resolvers.length)); // resolve current chunk const intermediateResults = await Promise.all(chunk.map((r) => r.resolve())); // push results into buffer results.push(...intermediateResults); } // return results return results; }
[ "async", "function", "parallel", "(", "resolvers", ",", "limit", "=", "-", "1", ")", "{", "if", "(", "limit", "<", "1", ")", "{", "limit", "=", "1000", ";", "}", "const", "results", "=", "[", "]", ";", "const", "chunkSize", "=", "Math", ".", "min", "(", "limit", ",", "resolvers", ".", "length", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "resolvers", ".", "length", ";", "i", "=", "i", "+", "chunkSize", ")", "{", "const", "chunk", "=", "resolvers", ".", "slice", "(", "i", ",", "Math", ".", "min", "(", "i", "+", "chunkSize", ",", "resolvers", ".", "length", ")", ")", ";", "const", "intermediateResults", "=", "await", "Promise", ".", "all", "(", "chunk", ".", "map", "(", "(", "r", ")", "=>", "r", ".", "resolve", "(", ")", ")", ")", ";", "results", ".", "push", "(", "...", "intermediateResults", ")", ";", "}", "return", "results", ";", "}" ]
resolves multiple promises in parallel
[ "resolves", "multiple", "promises", "in", "parallel" ]
0c41dd27d8f7539bb24034bc23ce870f5f8a10b3
https://github.com/AndiDittrich/Node.async-magic/blob/0c41dd27d8f7539bb24034bc23ce870f5f8a10b3/lib/parallel.js#L2-L30
train
eklem/search-index-indexer
index.js
function(error, newIndex) { if (error) { console.log('Data error for ' + dataurl + '\n' + error) } if (!error) { index = newIndex var timeStart = Date.now() request(dataurl) .pipe(JSONStream.parse()) .pipe(index.defaultPipeline()) .pipe(index.add()) .on('data', function(data) { //console.dir(data) // What's going on in the indexing process }) .on('end', () => { var timeEnd = Date.now() var timeUsed = Math.trunc((timeEnd - timeStart) / 1000) console.log('Indexed in ' + timeUsed + ' seconds') }) } }
javascript
function(error, newIndex) { if (error) { console.log('Data error for ' + dataurl + '\n' + error) } if (!error) { index = newIndex var timeStart = Date.now() request(dataurl) .pipe(JSONStream.parse()) .pipe(index.defaultPipeline()) .pipe(index.add()) .on('data', function(data) { //console.dir(data) // What's going on in the indexing process }) .on('end', () => { var timeEnd = Date.now() var timeUsed = Math.trunc((timeEnd - timeStart) / 1000) console.log('Indexed in ' + timeUsed + ' seconds') }) } }
[ "function", "(", "error", ",", "newIndex", ")", "{", "if", "(", "error", ")", "{", "console", ".", "log", "(", "'Data error for '", "+", "dataurl", "+", "'\\n'", "+", "\\n", ")", "}", "error", "}" ]
indexData const with pipeline pipeline
[ "indexData", "const", "with", "pipeline", "pipeline" ]
8be0dffad9f2babc486ad9f9de9918c4e976dcfa
https://github.com/eklem/search-index-indexer/blob/8be0dffad9f2babc486ad9f9de9918c4e976dcfa/index.js#L28-L48
train
greggman/hft-sample-ui
src/hft/scripts/misc/strings.js
function(str, len, padChar) { str = stringIt(str); if (str.length >= len) { return str; } var padStr = getPadding(padChar, len); return str + padStr.substr(str.length - len); }
javascript
function(str, len, padChar) { str = stringIt(str); if (str.length >= len) { return str; } var padStr = getPadding(padChar, len); return str + padStr.substr(str.length - len); }
[ "function", "(", "str", ",", "len", ",", "padChar", ")", "{", "str", "=", "stringIt", "(", "str", ")", ";", "if", "(", "str", ".", "length", ">=", "len", ")", "{", "return", "str", ";", "}", "var", "padStr", "=", "getPadding", "(", "padChar", ",", "len", ")", ";", "return", "str", "+", "padStr", ".", "substr", "(", "str", ".", "length", "-", "len", ")", ";", "}" ]
Pad string on right @param {string} str string to pad @param {number} len number of characters to pad to @param {string} padChar character to pad with @returns {string} padded string. @memberOf module:Strings
[ "Pad", "string", "on", "right" ]
b9e20afd5183db73522bcfae48225c87e01f68c0
https://github.com/greggman/hft-sample-ui/blob/b9e20afd5183db73522bcfae48225c87e01f68c0/src/hft/scripts/misc/strings.js#L75-L82
train
greggman/hft-sample-ui
src/hft/scripts/misc/strings.js
function(str, start) { return (str.length >= start.length && str.substr(0, start.length) === start); }
javascript
function(str, start) { return (str.length >= start.length && str.substr(0, start.length) === start); }
[ "function", "(", "str", ",", "start", ")", "{", "return", "(", "str", ".", "length", ">=", "start", ".", "length", "&&", "str", ".", "substr", "(", "0", ",", "start", ".", "length", ")", "===", "start", ")", ";", "}" ]
True if string starts with prefix @static @param {String} str string to check for start @param {String} prefix start value @returns {Boolean} true if str starts with prefix @memberOf module:Strings
[ "True", "if", "string", "starts", "with", "prefix" ]
b9e20afd5183db73522bcfae48225c87e01f68c0
https://github.com/greggman/hft-sample-ui/blob/b9e20afd5183db73522bcfae48225c87e01f68c0/src/hft/scripts/misc/strings.js#L151-L154
train