id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
48,400
smartface/sf-component-calendar
lib/services/StyleContext.js
createStyleContext
function createStyleContext(actors, hooks) { var context; /** * Composes a context. * * @param {function) styling - Styling function from styler. * @param {function} reducer - Reducer function to run actions */ return function composeContext(styling, reducer) { var latestState = context ? context.getState() : {}; context && context.dispose(); context = (0, _Context2.default)(actors, function contextUpdater(context, action, target) { var state = context.getState(), newState = state; if (target || action.type == _Context.INIT_CONTEXT_ACTION_TYPE) { newState = reducer(state, context.actors, action, target); // state is not changed if (newState === state) { // return current state instance return state; } } Object.keys(context.actors).forEach(function setInitialStyles(name) { var comp = context.actors[name]; if (comp.isUgly === true || action.type === _Context.INIT_CONTEXT_ACTION_TYPE) { var className = context.actors[name].getClassName(); var beforeHook = hooks("beforeAssignComponentStyles"); beforeHook && (className = beforeHook(name, className)); var styles = styling(className + " #" + name)(); context.actors[name].setStyles(styles); comp.isUgly = false; } }); latestState = newState; return newState; }, latestState); Object.keys(context.actors).forEach(function assignContext(name) { context.actors[name].isUgly = true; context.actors[name].setContext(context); }); return context; }; }
javascript
function createStyleContext(actors, hooks) { var context; /** * Composes a context. * * @param {function) styling - Styling function from styler. * @param {function} reducer - Reducer function to run actions */ return function composeContext(styling, reducer) { var latestState = context ? context.getState() : {}; context && context.dispose(); context = (0, _Context2.default)(actors, function contextUpdater(context, action, target) { var state = context.getState(), newState = state; if (target || action.type == _Context.INIT_CONTEXT_ACTION_TYPE) { newState = reducer(state, context.actors, action, target); // state is not changed if (newState === state) { // return current state instance return state; } } Object.keys(context.actors).forEach(function setInitialStyles(name) { var comp = context.actors[name]; if (comp.isUgly === true || action.type === _Context.INIT_CONTEXT_ACTION_TYPE) { var className = context.actors[name].getClassName(); var beforeHook = hooks("beforeAssignComponentStyles"); beforeHook && (className = beforeHook(name, className)); var styles = styling(className + " #" + name)(); context.actors[name].setStyles(styles); comp.isUgly = false; } }); latestState = newState; return newState; }, latestState); Object.keys(context.actors).forEach(function assignContext(name) { context.actors[name].isUgly = true; context.actors[name].setContext(context); }); return context; }; }
[ "function", "createStyleContext", "(", "actors", ",", "hooks", ")", "{", "var", "context", ";", "/**\n * Composes a context.\n * \n * @param {function) styling - Styling function from styler.\n * @param {function} reducer - Reducer function to run actions\n */", "return",...
Style Context. Returns context composer @param {Array.<Object>} actors - Actors List @param {function} hooks - Hooks callback @returns {function} - Context Composer Function
[ "Style", "Context", ".", "Returns", "context", "composer" ]
d6c8310564ff551b9424ac6955efa5e8cf5f8dff
https://github.com/smartface/sf-component-calendar/blob/d6c8310564ff551b9424ac6955efa5e8cf5f8dff/lib/services/StyleContext.js#L256-L309
48,401
baijijs/baiji
lib/Controller.js
configure
function configure(proto, nameOrConfigs, actionConfig) { if (!proto.__configs) proto.__configs = {}; if (typeof nameOrConfigs === 'string') { // Set new configs if (typeof actionConfig === 'object') { proto.__configs = _.assign( proto.__configs, { [nameOrConfigs]: actionConfig } ); } // Get config else { return proto.__configs[nameOrConfigs]; } } // Overwrite all configs else if (typeof nameOrConfigs === 'object') { proto.__configs = nameOrConfigs; } }
javascript
function configure(proto, nameOrConfigs, actionConfig) { if (!proto.__configs) proto.__configs = {}; if (typeof nameOrConfigs === 'string') { // Set new configs if (typeof actionConfig === 'object') { proto.__configs = _.assign( proto.__configs, { [nameOrConfigs]: actionConfig } ); } // Get config else { return proto.__configs[nameOrConfigs]; } } // Overwrite all configs else if (typeof nameOrConfigs === 'object') { proto.__configs = nameOrConfigs; } }
[ "function", "configure", "(", "proto", ",", "nameOrConfigs", ",", "actionConfig", ")", "{", "if", "(", "!", "proto", ".", "__configs", ")", "proto", ".", "__configs", "=", "{", "}", ";", "if", "(", "typeof", "nameOrConfigs", "===", "'string'", ")", "{", ...
Route action for adding routes config for both Controller and its instance
[ "Route", "action", "for", "adding", "routes", "config", "for", "both", "Controller", "and", "its", "instance" ]
9e5938d5ce4991d0f9d12dbb4f50b3f30adbe601
https://github.com/baijijs/baiji/blob/9e5938d5ce4991d0f9d12dbb4f50b3f30adbe601/lib/Controller.js#L13-L34
48,402
baijijs/baiji
lib/Controller.js
detectConflictActions
function detectConflictActions(instance) { // Get all props and check reserved words let propNames = Object.getOwnPropertyNames(instance.__proto__); // Check internal action conflicts _.each(propNames, function(name) { assert( !~RESERVED_METHODS.indexOf(name), `Action: \`${name}\` is reserved by baiji.Controller, please rename it` ); }); }
javascript
function detectConflictActions(instance) { // Get all props and check reserved words let propNames = Object.getOwnPropertyNames(instance.__proto__); // Check internal action conflicts _.each(propNames, function(name) { assert( !~RESERVED_METHODS.indexOf(name), `Action: \`${name}\` is reserved by baiji.Controller, please rename it` ); }); }
[ "function", "detectConflictActions", "(", "instance", ")", "{", "// Get all props and check reserved words", "let", "propNames", "=", "Object", ".", "getOwnPropertyNames", "(", "instance", ".", "__proto__", ")", ";", "// Check internal action conflicts", "_", ".", "each",...
Detect whether user defined actions unexpectedly overwritten reserved actions Error will be throwed out if any confliction found
[ "Detect", "whether", "user", "defined", "actions", "unexpectedly", "overwritten", "reserved", "actions", "Error", "will", "be", "throwed", "out", "if", "any", "confliction", "found" ]
9e5938d5ce4991d0f9d12dbb4f50b3f30adbe601
https://github.com/baijijs/baiji/blob/9e5938d5ce4991d0f9d12dbb4f50b3f30adbe601/lib/Controller.js#L40-L51
48,403
lukewestby/class-name-builder
src/class-name-builder.js
unique
function unique(value) { return value.reduce((memo, current) => { return memo.indexOf(current) !== -1 ? memo : memo.concat(current); }, []); }
javascript
function unique(value) { return value.reduce((memo, current) => { return memo.indexOf(current) !== -1 ? memo : memo.concat(current); }, []); }
[ "function", "unique", "(", "value", ")", "{", "return", "value", ".", "reduce", "(", "(", "memo", ",", "current", ")", "=>", "{", "return", "memo", ".", "indexOf", "(", "current", ")", "!==", "-", "1", "?", "memo", ":", "memo", ".", "concat", "(", ...
Performaces a uniqueness reduction on an array @param {Array} value - the array to reduce @returns {Array} an array with unique values
[ "Performaces", "a", "uniqueness", "reduction", "on", "an", "array" ]
2e252f0ef0ff0fa08ef1a7eda82bdd2be3a50e41
https://github.com/lukewestby/class-name-builder/blob/2e252f0ef0ff0fa08ef1a7eda82bdd2be3a50e41/src/class-name-builder.js#L124-L128
48,404
lukewestby/class-name-builder
src/class-name-builder.js
cleanClassNames
function cleanClassNames(value) { const classNamesArray = isString(value) ? splitString(value) : value; const trimmedNamesArray = trimClassNames(classNamesArray); const uniqueNamesArray = unique(trimmedNamesArray); return uniqueNamesArray; }
javascript
function cleanClassNames(value) { const classNamesArray = isString(value) ? splitString(value) : value; const trimmedNamesArray = trimClassNames(classNamesArray); const uniqueNamesArray = unique(trimmedNamesArray); return uniqueNamesArray; }
[ "function", "cleanClassNames", "(", "value", ")", "{", "const", "classNamesArray", "=", "isString", "(", "value", ")", "?", "splitString", "(", "value", ")", ":", "value", ";", "const", "trimmedNamesArray", "=", "trimClassNames", "(", "classNamesArray", ")", "...
Converts class name input into an array of strings with space trimmed off @param {string | Array<string>} value - the value to convert @returns {Array<string>} the split and trimmed values
[ "Converts", "class", "name", "input", "into", "an", "array", "of", "strings", "with", "space", "trimmed", "off" ]
2e252f0ef0ff0fa08ef1a7eda82bdd2be3a50e41
https://github.com/lukewestby/class-name-builder/blob/2e252f0ef0ff0fa08ef1a7eda82bdd2be3a50e41/src/class-name-builder.js#L144-L149
48,405
reelyactive/chickadee
lib/server.js
ChickadeeServer
function ChickadeeServer(options) { options = options || {}; var specifiedHttpPort = options.httpPort || HTTP_PORT; var httpPort = process.env.PORT || specifiedHttpPort; var app = express(); app.use(bodyParser.json()); var instance = new Chickadee(options); options.app = app; instance.configureRoutes(options); app.listen(httpPort, function() { console.log('chickadee is listening on port', httpPort); }); return instance; }
javascript
function ChickadeeServer(options) { options = options || {}; var specifiedHttpPort = options.httpPort || HTTP_PORT; var httpPort = process.env.PORT || specifiedHttpPort; var app = express(); app.use(bodyParser.json()); var instance = new Chickadee(options); options.app = app; instance.configureRoutes(options); app.listen(httpPort, function() { console.log('chickadee is listening on port', httpPort); }); return instance; }
[ "function", "ChickadeeServer", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "specifiedHttpPort", "=", "options", ".", "httpPort", "||", "HTTP_PORT", ";", "var", "httpPort", "=", "process", ".", "env", ".", "PORT", "||", ...
ChickadeeServer Class Server for chickadee, returns an instance of chickadee with its own Express server listening on the given port. @param {Object} options The options as a JSON object. @constructor
[ "ChickadeeServer", "Class", "Server", "for", "chickadee", "returns", "an", "instance", "of", "chickadee", "with", "its", "own", "Express", "server", "listening", "on", "the", "given", "port", "." ]
1f65c2d369694d93796aae63318fa76326275120
https://github.com/reelyactive/chickadee/blob/1f65c2d369694d93796aae63318fa76326275120/lib/server.js#L23-L40
48,406
rtm/upward
src/Obs.js
getTypesFromHandlers
function getTypesFromHandlers(handlers) { var types = keys(handlers); types = types.map(k => k.replace(/_.*/, '')); if (types.indexOf('end') !== -1) { types.push('add', 'update', 'delete'); } return types; }
javascript
function getTypesFromHandlers(handlers) { var types = keys(handlers); types = types.map(k => k.replace(/_.*/, '')); if (types.indexOf('end') !== -1) { types.push('add', 'update', 'delete'); } return types; }
[ "function", "getTypesFromHandlers", "(", "handlers", ")", "{", "var", "types", "=", "keys", "(", "handlers", ")", ";", "types", "=", "types", ".", "map", "(", "k", "=>", "k", ".", "replace", "(", "/", "_.*", "/", ",", "''", ")", ")", ";", "if", "...
Prepare the list of `type`s to pass to O.o, based on handler methods. Even if only `end` is present, we need to add `add` etc. If handler named `type_name` is there, register `type` as handled.
[ "Prepare", "the", "list", "of", "type", "s", "to", "pass", "to", "O", ".", "o", "based", "on", "handler", "methods", ".", "Even", "if", "only", "end", "is", "present", "we", "need", "to", "add", "add", "etc", ".", "If", "handler", "named", "type_name...
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Obs.js#L49-L56
48,407
rtm/upward
src/Obs.js
makeObserver
function makeObserver(handlers) { console.assert(handlers && typeof handlers === 'object', "Argument to makeObserver must be hash."); var handler = assign(create(observerPrototype), handlers); var observer = handler.handle.bind(handler); observer.keys = getTypesFromHandlers(handlers); return observer; }
javascript
function makeObserver(handlers) { console.assert(handlers && typeof handlers === 'object', "Argument to makeObserver must be hash."); var handler = assign(create(observerPrototype), handlers); var observer = handler.handle.bind(handler); observer.keys = getTypesFromHandlers(handlers); return observer; }
[ "function", "makeObserver", "(", "handlers", ")", "{", "console", ".", "assert", "(", "handlers", "&&", "typeof", "handlers", "===", "'object'", ",", "\"Argument to makeObserver must be hash.\"", ")", ";", "var", "handler", "=", "assign", "(", "create", "(", "ob...
Make an observer from a hash of handlers for observation types. This observer can be passed to `observeObject`.
[ "Make", "an", "observer", "from", "a", "hash", "of", "handlers", "for", "observation", "types", ".", "This", "observer", "can", "be", "passed", "to", "observeObject", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Obs.js#L60-L66
48,408
rtm/upward
src/Obs.js
observeObject
function observeObject(o, observer) { return o && typeof o === 'object' && observe(o, observer, observer.keys); }
javascript
function observeObject(o, observer) { return o && typeof o === 'object' && observe(o, observer, observer.keys); }
[ "function", "observeObject", "(", "o", ",", "observer", ")", "{", "return", "o", "&&", "typeof", "o", "===", "'object'", "&&", "observe", "(", "o", ",", "observer", ",", "observer", ".", "keys", ")", ";", "}" ]
Invoke Object.observe with only the types available to be handled.
[ "Invoke", "Object", ".", "observe", "with", "only", "the", "types", "available", "to", "be", "handled", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Obs.js#L69-L71
48,409
rtm/upward
src/Obs.js
notifyRetroactively
function notifyRetroactively(object) { if (object && typeof object === 'object') { const type = 'add'; var notifier = Object.getNotifier(object); keys(object).forEach(name => notifier.notify({type, name, object})); } return object; }
javascript
function notifyRetroactively(object) { if (object && typeof object === 'object') { const type = 'add'; var notifier = Object.getNotifier(object); keys(object).forEach(name => notifier.notify({type, name, object})); } return object; }
[ "function", "notifyRetroactively", "(", "object", ")", "{", "if", "(", "object", "&&", "typeof", "object", "===", "'object'", ")", "{", "const", "type", "=", "'add'", ";", "var", "notifier", "=", "Object", ".", "getNotifier", "(", "object", ")", ";", "ke...
Retroactively notify 'add' to all properties in an object.
[ "Retroactively", "notify", "add", "to", "all", "properties", "in", "an", "object", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Obs.js#L85-L92
48,410
rtm/upward
src/Obs.js
observeOnce
function observeOnce(object, observer, types) { function _observer(changes) { observer(changes); unobserve(object, _observer); } observe(object, _observer, types); }
javascript
function observeOnce(object, observer, types) { function _observer(changes) { observer(changes); unobserve(object, _observer); } observe(object, _observer, types); }
[ "function", "observeOnce", "(", "object", ",", "observer", ",", "types", ")", "{", "function", "_observer", "(", "changes", ")", "{", "observer", "(", "changes", ")", ";", "unobserve", "(", "object", ",", "_observer", ")", ";", "}", "observe", "(", "obje...
Set up an observer and tear it down after the first report
[ "Set", "up", "an", "observer", "and", "tear", "it", "down", "after", "the", "first", "report" ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Obs.js#L95-L101
48,411
rtm/upward
src/Obs.js
mirrorProperties
function mirrorProperties(src, dest = {}) { function set(name) { dest[name] = src[name]; } function _delete(name) { delete dest[name]; } var handlers = { add: set, update: set, delete: _delete}; assign(dest, src); observe(src, makeObserver(handlers)); return dest; }
javascript
function mirrorProperties(src, dest = {}) { function set(name) { dest[name] = src[name]; } function _delete(name) { delete dest[name]; } var handlers = { add: set, update: set, delete: _delete}; assign(dest, src); observe(src, makeObserver(handlers)); return dest; }
[ "function", "mirrorProperties", "(", "src", ",", "dest", "=", "{", "}", ")", "{", "function", "set", "(", "name", ")", "{", "dest", "[", "name", "]", "=", "src", "[", "name", "]", ";", "}", "function", "_delete", "(", "name", ")", "{", "delete", ...
Keep an object in sync with another.
[ "Keep", "an", "object", "in", "sync", "with", "another", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Obs.js#L104-L113
48,412
rtm/upward
src/Obs.js
Observer
function Observer(object, observer, types) { return { observe(_types) { types = _types || types; if (isObject(object)) observe(object, observer, types); return this; }, unobserve() { if (isObject(object)) unobserve(object, observer); return this; }, reobserve(_object) { this.unobserve(); object = _object; return this.observe(); } }; }
javascript
function Observer(object, observer, types) { return { observe(_types) { types = _types || types; if (isObject(object)) observe(object, observer, types); return this; }, unobserve() { if (isObject(object)) unobserve(object, observer); return this; }, reobserve(_object) { this.unobserve(); object = _object; return this.observe(); } }; }
[ "function", "Observer", "(", "object", ",", "observer", ",", "types", ")", "{", "return", "{", "observe", "(", "_types", ")", "{", "types", "=", "_types", "||", "types", ";", "if", "(", "isObject", "(", "object", ")", ")", "observe", "(", "object", "...
Make an Observer object, which allows easy unobserving and resobserving.
[ "Make", "an", "Observer", "object", "which", "allows", "easy", "unobserving", "and", "resobserving", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Obs.js#L116-L133
48,413
node-tastypie/tastypie
lib/class/parent.js
function(method){ var parent, result; parent = this._parent || this.constructor.parent; this._parent = parent.constructor.parent; result = attempt(parent[method], slice(arguments, 1) , this ); this._parent = parent; if( result[0] ){ throw result[0]; } return result[1]; }
javascript
function(method){ var parent, result; parent = this._parent || this.constructor.parent; this._parent = parent.constructor.parent; result = attempt(parent[method], slice(arguments, 1) , this ); this._parent = parent; if( result[0] ){ throw result[0]; } return result[1]; }
[ "function", "(", "method", ")", "{", "var", "parent", ",", "result", ";", "parent", "=", "this", ".", "_parent", "||", "this", ".", "constructor", ".", "parent", ";", "this", ".", "_parent", "=", "parent", ".", "constructor", ".", "parent", ";", "resul...
Calls a function on the parent class in the scope of the child class @method module:tastypie/lib/class/parent#parent @param {TYPE} name DESCRIPTION @param {...Mixed} argument arguments to pass to the function @return {?Object} returns the result of the parent function call
[ "Calls", "a", "function", "on", "the", "parent", "class", "in", "the", "scope", "of", "the", "child", "class" ]
bf42227975704ac19cce2c5f62427a205cadafdb
https://github.com/node-tastypie/tastypie/blob/bf42227975704ac19cce2c5f62427a205cadafdb/lib/class/parent.js#L35-L48
48,414
defunctzombie/ratelimit-middleware
index.js
throttle
function throttle(options) { assert.object(options, 'options'); assert.number(options.burst, 'options.burst'); assert.number(options.rate, 'options.rate'); if (!xor(options.ip, options.xff, options.username)) { throw new Error('(ip ^ username ^ xff)'); } for (key in options.overrides) { var override = options.overrides[key]; try { var block = new Netmask(key); // Non-/32 blocks only if (block.first !== block.last) { override.block = block; } } catch(err) { // The key may be a username, which would raise but should // be ignored } } var message = options.message || 'You have exceeded your request rate of %s r/s.'; var table = options.tokensTable || new TokenTable({size: options.maxKeys}); function rateLimit(req, res, next) { var attr; var burst = options.burst; var rate = options.rate; if (options.ip) { attr = req.connection.remoteAddress; } else if (options.xff) { attr = req.headers['x-forwarded-for']; } else if (options.username) { attr = req.username; } // Before bothering with overrides, see if this request // even matches if (!attr) { return next(new Error('Invalid throttle configuration')); } // If the attr is a comma-delimited list of IPs, get the first attr = attr.split(',')[0]; // Check the overrides if (options.overrides) { var override = options.overrides[attr]; // If the rate limit attribute matches an override key, apply it if (override) { if (override.burst !== undefined && override.rate !== undefined) { burst = override.burst; rate = override.rate; } } // Otherwise, see if the rate limit attribute matches any CIDR // block overrides else { for (key in options.overrides) { override = options.overrides[key]; var contained = false; try { contained = override.block && override.block.contains(attr); } catch(err) { // attr may be a username, which would raise but should // be ignored } if (contained) { burst = override.burst; rate = override.rate; break; } } } } if (!rate || !burst) { return next(); } var bucket = table.get(attr); if (!bucket) { bucket = new TokenBucket({ capacity: burst, fillRate: rate }); table.put(attr, bucket); } if (!bucket.consume(1)) { var msg = sprintf(message, rate); var err = new Error(msg); err.status = 429; // Too Many Requests return next(err); } return next(); } return rateLimit; }
javascript
function throttle(options) { assert.object(options, 'options'); assert.number(options.burst, 'options.burst'); assert.number(options.rate, 'options.rate'); if (!xor(options.ip, options.xff, options.username)) { throw new Error('(ip ^ username ^ xff)'); } for (key in options.overrides) { var override = options.overrides[key]; try { var block = new Netmask(key); // Non-/32 blocks only if (block.first !== block.last) { override.block = block; } } catch(err) { // The key may be a username, which would raise but should // be ignored } } var message = options.message || 'You have exceeded your request rate of %s r/s.'; var table = options.tokensTable || new TokenTable({size: options.maxKeys}); function rateLimit(req, res, next) { var attr; var burst = options.burst; var rate = options.rate; if (options.ip) { attr = req.connection.remoteAddress; } else if (options.xff) { attr = req.headers['x-forwarded-for']; } else if (options.username) { attr = req.username; } // Before bothering with overrides, see if this request // even matches if (!attr) { return next(new Error('Invalid throttle configuration')); } // If the attr is a comma-delimited list of IPs, get the first attr = attr.split(',')[0]; // Check the overrides if (options.overrides) { var override = options.overrides[attr]; // If the rate limit attribute matches an override key, apply it if (override) { if (override.burst !== undefined && override.rate !== undefined) { burst = override.burst; rate = override.rate; } } // Otherwise, see if the rate limit attribute matches any CIDR // block overrides else { for (key in options.overrides) { override = options.overrides[key]; var contained = false; try { contained = override.block && override.block.contains(attr); } catch(err) { // attr may be a username, which would raise but should // be ignored } if (contained) { burst = override.burst; rate = override.rate; break; } } } } if (!rate || !burst) { return next(); } var bucket = table.get(attr); if (!bucket) { bucket = new TokenBucket({ capacity: burst, fillRate: rate }); table.put(attr, bucket); } if (!bucket.consume(1)) { var msg = sprintf(message, rate); var err = new Error(msg); err.status = 429; // Too Many Requests return next(err); } return next(); } return rateLimit; }
[ "function", "throttle", "(", "options", ")", "{", "assert", ".", "object", "(", "options", ",", "'options'", ")", ";", "assert", ".", "number", "(", "options", ".", "burst", ",", "'options.burst'", ")", ";", "assert", ".", "number", "(", "options", ".", ...
Creates an API rate limiter that can be plugged into the standard restify request handling pipeline. This throttle gives you three options on which to throttle: username, IP address and 'X-Forwarded-For'. IP/XFF is a /32 match, so keep that in mind if using it. Username takes the user specified on req.username (which gets automagically set for supported Authorization types; otherwise set it yourself with a filter that runs before this). In both cases, you can set a `burst` and a `rate` (in requests/seconds), as an integer/float. Those really translate to the `TokenBucket` algorithm, so read up on that (or see the comments above...). In either case, the top level options burst/rate set a blanket throttling rate, and then you can pass in an `overrides` object with rates for specific users/IPs. You should use overrides sparingly, as we make a new TokenBucket to track each. On the `options` object ip and username are treated as an XOR. An example options object with overrides: { burst: 10, // Max 10 concurrent requests (if tokens) rate: 0.5, // Steady state: 1 request / 2 seconds ip: true, // throttle per IP overrides: { '192.168.1.1': { burst: 0, rate: 0 // unlimited } } @param {Object} options required options with: - {Number} burst (required). - {Number} rate (required). - {Boolean} ip (optional). - {Boolean} username (optional). - {Boolean} xff (optional). - {Object} overrides (optional). - {Object} tokensTable: a storage engine this plugin will use to store throttling keys -> bucket mappings. If you don't specify this, the default is to use an in-memory O(1) LRU, with 10k distinct keys. Any implementation just needs to support put/get. - {Number} maxKeys: If using the default implementation, you can specify how large you want the table to be. Default is 10000. @return {Function} of type f(req, res, next) to be plugged into a route. @throws {TypeError} on bad input.
[ "Creates", "an", "API", "rate", "limiter", "that", "can", "be", "plugged", "into", "the", "standard", "restify", "request", "handling", "pipeline", "." ]
b5dc549e5498c6c4e50ec3daca4491f129536e6e
https://github.com/defunctzombie/ratelimit-middleware/blob/b5dc549e5498c6c4e50ec3daca4491f129536e6e/index.js#L63-L173
48,415
defunctzombie/node-influx-collector
index.js
Collector
function Collector(series, uri) { if (!(this instanceof Collector)) { return new Collector(series, uri); } var self = this; if (!uri) { return; } if (!series) { throw new Error('series name must be specified'); } var parsed = url.parse(uri, true /* parse query args */); var username = undefined; var password = undefined; if (parsed.auth) { var parts = parsed.auth.split(':'); username = parts.shift(); password = parts.shift(); } self._client = influx({ host : parsed.hostname, port : parsed.port, protocol : parsed.protocol, username : username, password : password, database : parsed.pathname.slice(1) // remove leading '/' }) self._points = []; var opt = parsed.query || {}; self._series_name = series; self._instant_flush = opt.instantFlush == 'yes'; self._time_precision = opt.time_precision; // no automatic flush if (opt.autoFlush == 'no' || self._instant_flush) { return; } var flush_interval = opt.flushInterval || 5000; // flush on an interval // or option to auto_flush=false setInterval(function() { self.flush(); }, flush_interval).unref(); }
javascript
function Collector(series, uri) { if (!(this instanceof Collector)) { return new Collector(series, uri); } var self = this; if (!uri) { return; } if (!series) { throw new Error('series name must be specified'); } var parsed = url.parse(uri, true /* parse query args */); var username = undefined; var password = undefined; if (parsed.auth) { var parts = parsed.auth.split(':'); username = parts.shift(); password = parts.shift(); } self._client = influx({ host : parsed.hostname, port : parsed.port, protocol : parsed.protocol, username : username, password : password, database : parsed.pathname.slice(1) // remove leading '/' }) self._points = []; var opt = parsed.query || {}; self._series_name = series; self._instant_flush = opt.instantFlush == 'yes'; self._time_precision = opt.time_precision; // no automatic flush if (opt.autoFlush == 'no' || self._instant_flush) { return; } var flush_interval = opt.flushInterval || 5000; // flush on an interval // or option to auto_flush=false setInterval(function() { self.flush(); }, flush_interval).unref(); }
[ "function", "Collector", "(", "series", ",", "uri", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Collector", ")", ")", "{", "return", "new", "Collector", "(", "series", ",", "uri", ")", ";", "}", "var", "self", "=", "this", ";", "if", "(",...
create a collector for the given series
[ "create", "a", "collector", "for", "the", "given", "series" ]
4a6701bf6f7d6489fe25dc55e6eaa24c15ae5a50
https://github.com/defunctzombie/node-influx-collector/blob/4a6701bf6f7d6489fe25dc55e6eaa24c15ae5a50/index.js#L6-L61
48,416
flyvictor/fortune-client
lib/resource-linker.js
fetchAncestor
function fetchAncestor(type, ids, includePath, req) { return router.actions["get" + util.toCapitalisedCamelCase(type)](ids, {include: includePath, parentRequest: req}); }
javascript
function fetchAncestor(type, ids, includePath, req) { return router.actions["get" + util.toCapitalisedCamelCase(type)](ids, {include: includePath, parentRequest: req}); }
[ "function", "fetchAncestor", "(", "type", ",", "ids", ",", "includePath", ",", "req", ")", "{", "return", "router", ".", "actions", "[", "\"get\"", "+", "util", ".", "toCapitalisedCamelCase", "(", "type", ")", "]", "(", "ids", ",", "{", "include", ":", ...
Returns the resource data for the external resource. @param {String} The type of resource to lookup. @param {Array} The link id(s) of the resource to be looked up. @param {Object} The http request object. @param {Array} The include url params. @api private
[ "Returns", "the", "resource", "data", "for", "the", "external", "resource", "." ]
1d1eaccbe0cf5293201736d6563ff4cd70881542
https://github.com/flyvictor/fortune-client/blob/1d1eaccbe0cf5293201736d6563ff4cd70881542/lib/resource-linker.js#L63-L65
48,417
flyvictor/fortune-client
lib/resource-linker.js
mergeLinked
function mergeLinked(source, target, pathArr, ancestorType) { var linked, type, res; if (pathArr.length) { // the external is referenced by the ancestor if (source.links && source.linked && source.links[ancestorType + "." + pathArr.join(".")]) { type = source.links[ancestorType + "." + pathArr.join(".")].type; linked = source.linked[type]; } } else { // ancestor is the sought external type = ancestorType; linked = source[ancestorType] || []; } target.linked[type] = _.isArray(res = target.linked[type]) ? _.uniq(res.concat(linked), function(i){ return i.id}) : linked; }
javascript
function mergeLinked(source, target, pathArr, ancestorType) { var linked, type, res; if (pathArr.length) { // the external is referenced by the ancestor if (source.links && source.linked && source.links[ancestorType + "." + pathArr.join(".")]) { type = source.links[ancestorType + "." + pathArr.join(".")].type; linked = source.linked[type]; } } else { // ancestor is the sought external type = ancestorType; linked = source[ancestorType] || []; } target.linked[type] = _.isArray(res = target.linked[type]) ? _.uniq(res.concat(linked), function(i){ return i.id}) : linked; }
[ "function", "mergeLinked", "(", "source", ",", "target", ",", "pathArr", ",", "ancestorType", ")", "{", "var", "linked", ",", "type", ",", "res", ";", "if", "(", "pathArr", ".", "length", ")", "{", "// the external is referenced by the ancestor", "if", "(", ...
Replaces the target linked property with the external data. @param {Object} The source from the external lookup. @param {Object} The target resource. @param {Object} The include properties. @param {Object} The lookup resource type. @api private
[ "Replaces", "the", "target", "linked", "property", "with", "the", "external", "data", "." ]
1d1eaccbe0cf5293201736d6563ff4cd70881542
https://github.com/flyvictor/fortune-client/blob/1d1eaccbe0cf5293201736d6563ff4cd70881542/lib/resource-linker.js#L76-L92
48,418
flyvictor/fortune-client
lib/resource-linker.js
mergeLinks
function mergeLinks(source, target, pathArr, ancestorType) { var refType = ancestorType + ((pathArr.length > 1) ? "." + _.rest(pathArr).join(".") : ""); var link = source.links && source.links[refType]; if (link) target.links[rootName(target) + "." + pathArr.join(".")] = link; }
javascript
function mergeLinks(source, target, pathArr, ancestorType) { var refType = ancestorType + ((pathArr.length > 1) ? "." + _.rest(pathArr).join(".") : ""); var link = source.links && source.links[refType]; if (link) target.links[rootName(target) + "." + pathArr.join(".")] = link; }
[ "function", "mergeLinks", "(", "source", ",", "target", ",", "pathArr", ",", "ancestorType", ")", "{", "var", "refType", "=", "ancestorType", "+", "(", "(", "pathArr", ".", "length", ">", "1", ")", "?", "\".\"", "+", "_", ".", "rest", "(", "pathArr", ...
Append meta data of included type to the links section of root resource. @param {Object} The source from the external lookup. @param {Object} The target resource. @param {Object} The include properties. @param {Object} The lookup resource type. @api private
[ "Append", "meta", "data", "of", "included", "type", "to", "the", "links", "section", "of", "root", "resource", "." ]
1d1eaccbe0cf5293201736d6563ff4cd70881542
https://github.com/flyvictor/fortune-client/blob/1d1eaccbe0cf5293201736d6563ff4cd70881542/lib/resource-linker.js#L103-L109
48,419
flyvictor/fortune-client
lib/resource-linker.js
mergeAncestorData
function mergeAncestorData(target, pathArr, type, source) { mergeLinked(source, target, _.rest(pathArr), type); mergeLinks(source, target , pathArr, type); }
javascript
function mergeAncestorData(target, pathArr, type, source) { mergeLinked(source, target, _.rest(pathArr), type); mergeLinks(source, target , pathArr, type); }
[ "function", "mergeAncestorData", "(", "target", ",", "pathArr", ",", "type", ",", "source", ")", "{", "mergeLinked", "(", "source", ",", "target", ",", "_", ".", "rest", "(", "pathArr", ")", ",", "type", ")", ";", "mergeLinks", "(", "source", ",", "tar...
Combines the original target resource with the external resource data. @param {Object} The target resource. @param {Object} The include properties. @param {Object} The lookup resource type. @param {Object} The source from the external lookup. @api private
[ "Combines", "the", "original", "target", "resource", "with", "the", "external", "resource", "data", "." ]
1d1eaccbe0cf5293201736d6563ff4cd70881542
https://github.com/flyvictor/fortune-client/blob/1d1eaccbe0cf5293201736d6563ff4cd70881542/lib/resource-linker.js#L120-L123
48,420
flyvictor/fortune-client
lib/resource-linker.js
groupIncludes
function groupIncludes(includes, body) { var root = rootName(body); var requestsByType = {}; _.each(includes, function(include) { var type = ((body.links && body.links[root + "." + include]) || {}).type, split = include.split("."); if (_.isUndefined(body.links) || _.isUndefined(body.links[root + "." + split[0]])) { return; } if (type && body.linked[type] && body.linked[type] !== "external") { // The type exists but is not an external reference exit. return; } var ancestorType = body.links[root + "." + split[0]].type; var ids = linkedIds(body[root], split[0]); if (ids.length) { var requestData = requestsByType[ancestorType] || {ids: [], includes: []}; requestData.ids = requestData.ids.concat(ids); requestData.includes.push(split); requestsByType[ancestorType] = requestData; } }); return requestsByType; }
javascript
function groupIncludes(includes, body) { var root = rootName(body); var requestsByType = {}; _.each(includes, function(include) { var type = ((body.links && body.links[root + "." + include]) || {}).type, split = include.split("."); if (_.isUndefined(body.links) || _.isUndefined(body.links[root + "." + split[0]])) { return; } if (type && body.linked[type] && body.linked[type] !== "external") { // The type exists but is not an external reference exit. return; } var ancestorType = body.links[root + "." + split[0]].type; var ids = linkedIds(body[root], split[0]); if (ids.length) { var requestData = requestsByType[ancestorType] || {ids: [], includes: []}; requestData.ids = requestData.ids.concat(ids); requestData.includes.push(split); requestsByType[ancestorType] = requestData; } }); return requestsByType; }
[ "function", "groupIncludes", "(", "includes", ",", "body", ")", "{", "var", "root", "=", "rootName", "(", "body", ")", ";", "var", "requestsByType", "=", "{", "}", ";", "_", ".", "each", "(", "includes", ",", "function", "(", "include", ")", "{", "va...
Batches together the includes by type, as to avoid multiple requests. @param {Object} The resource body. @api private
[ "Batches", "together", "the", "includes", "by", "type", "as", "to", "avoid", "multiple", "requests", "." ]
1d1eaccbe0cf5293201736d6563ff4cd70881542
https://github.com/flyvictor/fortune-client/blob/1d1eaccbe0cf5293201736d6563ff4cd70881542/lib/resource-linker.js#L134-L162
48,421
flyvictor/fortune-client
lib/resource-linker.js
fetchExternals
function fetchExternals(request, body) { var includes = parseIncludes(request); var user = request.user; var requestsByType = groupIncludes(includes, body); return when.all(_.map(requestsByType, function(requestData, ancestorType) { var ids = _.uniq(requestData.ids); return fetchAncestor(ancestorType, ids, _.compact(_.map(requestData.includes, function(i) { return _.rest(i).join("."); })).join(","), request) .then(function(response){ return response; }) .then(function(data) { _.each(requestData.includes, function(split) { mergeAncestorData(body, split, ancestorType, data); }); }) .catch(function(err) { console.trace(err.stack || err); }); })).then(function() { return body; }); }
javascript
function fetchExternals(request, body) { var includes = parseIncludes(request); var user = request.user; var requestsByType = groupIncludes(includes, body); return when.all(_.map(requestsByType, function(requestData, ancestorType) { var ids = _.uniq(requestData.ids); return fetchAncestor(ancestorType, ids, _.compact(_.map(requestData.includes, function(i) { return _.rest(i).join("."); })).join(","), request) .then(function(response){ return response; }) .then(function(data) { _.each(requestData.includes, function(split) { mergeAncestorData(body, split, ancestorType, data); }); }) .catch(function(err) { console.trace(err.stack || err); }); })).then(function() { return body; }); }
[ "function", "fetchExternals", "(", "request", ",", "body", ")", "{", "var", "includes", "=", "parseIncludes", "(", "request", ")", ";", "var", "user", "=", "request", ".", "user", ";", "var", "requestsByType", "=", "groupIncludes", "(", "includes", ",", "b...
Reads the resource object and attaches data via external http calls the properties marked as "external". @param {Object} The http request object. @param {Object} The body data from the response. @api private
[ "Reads", "the", "resource", "object", "and", "attaches", "data", "via", "external", "http", "calls", "the", "properties", "marked", "as", "external", "." ]
1d1eaccbe0cf5293201736d6563ff4cd70881542
https://github.com/flyvictor/fortune-client/blob/1d1eaccbe0cf5293201736d6563ff4cd70881542/lib/resource-linker.js#L173-L194
48,422
smartface/sf-component-calendar
src/services/CalendarService.js
getMonth
function getMonth(moment, service, dt) { const dateService = new service(moment, dt); return { longName: dateService.monthLong(), shortName: dateService.monthShort(), daysCount: dateService.daysCount(), startDayOfMonth: dateService.startDayOfMonth(), }; }
javascript
function getMonth(moment, service, dt) { const dateService = new service(moment, dt); return { longName: dateService.monthLong(), shortName: dateService.monthShort(), daysCount: dateService.daysCount(), startDayOfMonth: dateService.startDayOfMonth(), }; }
[ "function", "getMonth", "(", "moment", ",", "service", ",", "dt", ")", "{", "const", "dateService", "=", "new", "service", "(", "moment", ",", "dt", ")", ";", "return", "{", "longName", ":", "dateService", ".", "monthLong", "(", ")", ",", "shortName", ...
Returns current month data @private @returns {Object}
[ "Returns", "current", "month", "data" ]
d6c8310564ff551b9424ac6955efa5e8cf5f8dff
https://github.com/smartface/sf-component-calendar/blob/d6c8310564ff551b9424ac6955efa5e8cf5f8dff/src/services/CalendarService.js#L75-L85
48,423
koliseoapi/alt-ng
Alt.js
generateActions
function generateActions({ generate, ...actions }) { return !generate ? actions : Object.assign( generate.reduce((obj, name) => { obj[name] = forwardValue; return obj; }, {}), actions ); }
javascript
function generateActions({ generate, ...actions }) { return !generate ? actions : Object.assign( generate.reduce((obj, name) => { obj[name] = forwardValue; return obj; }, {}), actions ); }
[ "function", "generateActions", "(", "{", "generate", ",", "...", "actions", "}", ")", "{", "return", "!", "generate", "?", "actions", ":", "Object", ".", "assign", "(", "generate", ".", "reduce", "(", "(", "obj", ",", "name", ")", "=>", "{", "obj", "...
process the "generate" field of an Actions object. Adds a new pass-through method with each name from the generated values
[ "process", "the", "generate", "field", "of", "an", "Actions", "object", ".", "Adds", "a", "new", "pass", "-", "through", "method", "with", "each", "name", "from", "the", "generated", "values" ]
cfb4cbfb15f5a286d24fc18fa3e49d7dc58549b4
https://github.com/koliseoapi/alt-ng/blob/cfb4cbfb15f5a286d24fc18fa3e49d7dc58549b4/Alt.js#L14-L24
48,424
DeviaVir/node-transip
transip.js
TransIP
function TransIP(login, privateKey) { this.version = 5.1; this.mode = 'readwrite'; this.endpoint = 'api.transip.nl'; this.login = (login ? login : config.transip.login); this.privateKey = (privateKey ? privateKey : config.transip.privateKey); this.domainService = new domainService(this); }
javascript
function TransIP(login, privateKey) { this.version = 5.1; this.mode = 'readwrite'; this.endpoint = 'api.transip.nl'; this.login = (login ? login : config.transip.login); this.privateKey = (privateKey ? privateKey : config.transip.privateKey); this.domainService = new domainService(this); }
[ "function", "TransIP", "(", "login", ",", "privateKey", ")", "{", "this", ".", "version", "=", "5.1", ";", "this", ".", "mode", "=", "'readwrite'", ";", "this", ".", "endpoint", "=", "'api.transip.nl'", ";", "this", ".", "login", "=", "(", "login", "?"...
TransIP instance constructor @prototype @class TransIP
[ "TransIP", "instance", "constructor" ]
8bc5283a0bf2c6a21455f9f4629872cd08b65ac0
https://github.com/DeviaVir/node-transip/blob/8bc5283a0bf2c6a21455f9f4629872cd08b65ac0/transip.js#L21-L29
48,425
mattdot/passport-mspassport
lib/strategy.js
function(defaults, options) { options = options || {}; for (var option in defaults) { if (defaults.hasOwnProperty(option) && !options.hasOwnProperty(option)) { options[option] = defaults[option]; } } return options; }
javascript
function(defaults, options) { options = options || {}; for (var option in defaults) { if (defaults.hasOwnProperty(option) && !options.hasOwnProperty(option)) { options[option] = defaults[option]; } } return options; }
[ "function", "(", "defaults", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "for", "(", "var", "option", "in", "defaults", ")", "{", "if", "(", "defaults", ".", "hasOwnProperty", "(", "option", ")", "&&", "!", "options", "....
Merges default options with actual options @param {Object} defaults The default options @param {Object} options The set options @api private
[ "Merges", "default", "options", "with", "actual", "options" ]
0a89357e58d77db219beef0cd994ad8d6f8e53b2
https://github.com/mattdot/passport-mspassport/blob/0a89357e58d77db219beef0cd994ad8d6f8e53b2/lib/strategy.js#L13-L22
48,426
mattdot/passport-mspassport
lib/strategy.js
MSPassportStrategy
function MSPassportStrategy(options) { Strategy.call(this); this.name = "mspassport"; var default_options = { protocol : "querystring", protocolHandler : function() { self.fail("protocolHandler must be implemented if protocol === 'custom'") } }; this.options = _defaults(default_options, options); }
javascript
function MSPassportStrategy(options) { Strategy.call(this); this.name = "mspassport"; var default_options = { protocol : "querystring", protocolHandler : function() { self.fail("protocolHandler must be implemented if protocol === 'custom'") } }; this.options = _defaults(default_options, options); }
[ "function", "MSPassportStrategy", "(", "options", ")", "{", "Strategy", ".", "call", "(", "this", ")", ";", "this", ".", "name", "=", "\"mspassport\"", ";", "var", "default_options", "=", "{", "protocol", ":", "\"querystring\"", ",", "protocolHandler", ":", ...
Creates an instance of `MSPassportStrategy`. @constructor @api public
[ "Creates", "an", "instance", "of", "MSPassportStrategy", "." ]
0a89357e58d77db219beef0cd994ad8d6f8e53b2
https://github.com/mattdot/passport-mspassport/blob/0a89357e58d77db219beef0cd994ad8d6f8e53b2/lib/strategy.js#L104-L114
48,427
rodmcnew/tabular-sarsa-js
example/index.js
runGame
function runGame() { var totalReward = 0; var environment = new exampleWorld.Environment(); var lastReward = null; function tick() { //Tell the agent about the current environment state and have it choose an action to take var action = sarsaAgent.decide(lastReward, environment.getCurrentState()); //Tell the environment the agent's action and have it calculate a reward lastReward = environment.takeAction(action); //Log the total reward totalReward += lastReward; } for (var i = 0; i < 100; i++) { tick(); } return totalReward; }
javascript
function runGame() { var totalReward = 0; var environment = new exampleWorld.Environment(); var lastReward = null; function tick() { //Tell the agent about the current environment state and have it choose an action to take var action = sarsaAgent.decide(lastReward, environment.getCurrentState()); //Tell the environment the agent's action and have it calculate a reward lastReward = environment.takeAction(action); //Log the total reward totalReward += lastReward; } for (var i = 0; i < 100; i++) { tick(); } return totalReward; }
[ "function", "runGame", "(", ")", "{", "var", "totalReward", "=", "0", ";", "var", "environment", "=", "new", "exampleWorld", ".", "Environment", "(", ")", ";", "var", "lastReward", "=", "null", ";", "function", "tick", "(", ")", "{", "//Tell the agent abou...
Run a game where we see how high of a total reward we can get in 100 actions @returns {number} Total reward for this game
[ "Run", "a", "game", "where", "we", "see", "how", "high", "of", "a", "total", "reward", "we", "can", "get", "in", "100", "actions" ]
5058e788a6c87742ccd2ad9d579378233d999156
https://github.com/rodmcnew/tabular-sarsa-js/blob/5058e788a6c87742ccd2ad9d579378233d999156/example/index.js#L14-L35
48,428
rtm/upward
src/Out.js
objectToString
function objectToString(o) { return '{' + keys(o).map(k => `${k}: ${o[k]}`).join(', ') + '}'; }
javascript
function objectToString(o) { return '{' + keys(o).map(k => `${k}: ${o[k]}`).join(', ') + '}'; }
[ "function", "objectToString", "(", "o", ")", "{", "return", "'{'", "+", "keys", "(", "o", ")", ".", "map", "(", "k", "=>", "`", "${", "k", "}", "${", "o", "[", "k", "]", "}", "`", ")", ".", "join", "(", "', '", ")", "+", "'}'", ";", "}" ]
User-friendly representation of an object.
[ "User", "-", "friendly", "representation", "of", "an", "object", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Out.js#L15-L17
48,429
rtm/upward
src/Out.js
mapObjectInPlace
function mapObjectInPlace(o, fn, ctxt) { for (let key in o) { if (o.hasOwnProperty(key)) { o[key] = fn.call(ctxt, o[key], key, o); } } return o; }
javascript
function mapObjectInPlace(o, fn, ctxt) { for (let key in o) { if (o.hasOwnProperty(key)) { o[key] = fn.call(ctxt, o[key], key, o); } } return o; }
[ "function", "mapObjectInPlace", "(", "o", ",", "fn", ",", "ctxt", ")", "{", "for", "(", "let", "key", "in", "o", ")", "{", "if", "(", "o", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "o", "[", "key", "]", "=", "fn", ".", "call", "(", "c...
Map an object's values, replacing existing ones.
[ "Map", "an", "object", "s", "values", "replacing", "existing", "ones", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Out.js#L37-L44
48,430
rtm/upward
src/Out.js
copyOf
function copyOf(o) { if (Array.isArray(o)) return o.slice(); if (isObject(o)) return assign({}, o); return o; }
javascript
function copyOf(o) { if (Array.isArray(o)) return o.slice(); if (isObject(o)) return assign({}, o); return o; }
[ "function", "copyOf", "(", "o", ")", "{", "if", "(", "Array", ".", "isArray", "(", "o", ")", ")", "return", "o", ".", "slice", "(", ")", ";", "if", "(", "isObject", "(", "o", ")", ")", "return", "assign", "(", "{", "}", ",", "o", ")", ";", ...
Make a copy of something.
[ "Make", "a", "copy", "of", "something", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Out.js#L47-L51
48,431
rtm/upward
src/Out.js
copyOntoArray
function copyOntoArray(a1, a2) { for (let i = 0; i < a2.length; i++) { a1[i] = a2[i]; } a1.length = a2.length; return a1; }
javascript
function copyOntoArray(a1, a2) { for (let i = 0; i < a2.length; i++) { a1[i] = a2[i]; } a1.length = a2.length; return a1; }
[ "function", "copyOntoArray", "(", "a1", ",", "a2", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "a2", ".", "length", ";", "i", "++", ")", "{", "a1", "[", "i", "]", "=", "a2", "[", "i", "]", ";", "}", "a1", ".", "length", "="...
Copy a second array onto a first one destructively.
[ "Copy", "a", "second", "array", "onto", "a", "first", "one", "destructively", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Out.js#L54-L60
48,432
rtm/upward
src/Out.js
copyOntoObject
function copyOntoObject(o1, o2) { assign(o1, o2); keys(o1) .filter(key => !(key in o2)) .forEach(key => (delete o1[key])); return o1; }
javascript
function copyOntoObject(o1, o2) { assign(o1, o2); keys(o1) .filter(key => !(key in o2)) .forEach(key => (delete o1[key])); return o1; }
[ "function", "copyOntoObject", "(", "o1", ",", "o2", ")", "{", "assign", "(", "o1", ",", "o2", ")", ";", "keys", "(", "o1", ")", ".", "filter", "(", "key", "=>", "!", "(", "key", "in", "o2", ")", ")", ".", "forEach", "(", "key", "=>", "(", "de...
Overwrite a first object entirely with a second one.
[ "Overwrite", "a", "first", "object", "entirely", "with", "a", "second", "one", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Out.js#L63-L69
48,433
rtm/upward
src/Out.js
copyOnto
function copyOnto(a1, a2) { if (Array.isArray(a1) && Array.isArray(a2)) return copyOntoArray (a1, a2); if (isObject (a1) && isObject (a2)) return copyOntoObject(a1, a2); return (a1 = a2); }
javascript
function copyOnto(a1, a2) { if (Array.isArray(a1) && Array.isArray(a2)) return copyOntoArray (a1, a2); if (isObject (a1) && isObject (a2)) return copyOntoObject(a1, a2); return (a1 = a2); }
[ "function", "copyOnto", "(", "a1", ",", "a2", ")", "{", "if", "(", "Array", ".", "isArray", "(", "a1", ")", "&&", "Array", ".", "isArray", "(", "a2", ")", ")", "return", "copyOntoArray", "(", "a1", ",", "a2", ")", ";", "if", "(", "isObject", "(",...
Copy a second object or array destructively onto a first one.
[ "Copy", "a", "second", "object", "or", "array", "destructively", "onto", "a", "first", "one", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Out.js#L72-L76
48,434
rtm/upward
src/Out.js
invertObject
function invertObject(o) { var result = {}; for (let pair of objectPairs(o)) { let [key, val] = pair; result[val] = key; } return result; }
javascript
function invertObject(o) { var result = {}; for (let pair of objectPairs(o)) { let [key, val] = pair; result[val] = key; } return result; }
[ "function", "invertObject", "(", "o", ")", "{", "var", "result", "=", "{", "}", ";", "for", "(", "let", "pair", "of", "objectPairs", "(", "o", ")", ")", "{", "let", "[", "key", ",", "val", "]", "=", "pair", ";", "result", "[", "val", "]", "=", ...
"Invert" an object, swapping keys and values.
[ "Invert", "an", "object", "swapping", "keys", "and", "values", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Out.js#L79-L86
48,435
rtm/upward
src/Out.js
objectFromLists
function objectFromLists(keys, vals) { var result = {}; for (let i = 0, len = keys.length; i < len; i++) { result[keys[i]] = vals[i]; } return result; }
javascript
function objectFromLists(keys, vals) { var result = {}; for (let i = 0, len = keys.length; i < len; i++) { result[keys[i]] = vals[i]; } return result; }
[ "function", "objectFromLists", "(", "keys", ",", "vals", ")", "{", "var", "result", "=", "{", "}", ";", "for", "(", "let", "i", "=", "0", ",", "len", "=", "keys", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "result", "[", "...
Create an object from two arrays of keys and values.
[ "Create", "an", "object", "from", "two", "arrays", "of", "keys", "and", "values", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Out.js#L98-L104
48,436
twolfson/doubleshot
lib/renderBatch.js
addHooks
function addHooks(fn, value) { // Upcast val to an array var values = value; if (!Array.isArray(values)) { values = [value]; } // Call each of the functions with hook values.forEach(fn); }
javascript
function addHooks(fn, value) { // Upcast val to an array var values = value; if (!Array.isArray(values)) { values = [value]; } // Call each of the functions with hook values.forEach(fn); }
[ "function", "addHooks", "(", "fn", ",", "value", ")", "{", "// Upcast val to an array", "var", "values", "=", "value", ";", "if", "(", "!", "Array", ".", "isArray", "(", "values", ")", ")", "{", "values", "=", "[", "value", "]", ";", "}", "// Call each...
Helper function to add hooks
[ "Helper", "function", "to", "add", "hooks" ]
3523177d7bcaeeb8c5198d154da0b5fdaba8d7fe
https://github.com/twolfson/doubleshot/blob/3523177d7bcaeeb8c5198d154da0b5fdaba8d7fe/lib/renderBatch.js#L5-L14
48,437
baijijs/baiji
lib/utils/addHookByType.js
addHookByType
function addHookByType(ctx, type, methodNames, fn) { let i = methodNames.length; // If no hook specified, add wildcard if (i === 0) { methodNames = ['*']; i = 1; } let hookType = `${type}Hooks`; if (!ctx[hookType]) ctx[hookType] = {}; while (i--) { let methodName = methodNames[i]; // for array method names if (Array.isArray(methodName)) { addHookByType(ctx, type, methodName, fn); } else { if (!ctx[hookType][methodName]) { ctx[hookType][methodName] = [fn]; } else { ctx[hookType][methodName].push(fn); } } } }
javascript
function addHookByType(ctx, type, methodNames, fn) { let i = methodNames.length; // If no hook specified, add wildcard if (i === 0) { methodNames = ['*']; i = 1; } let hookType = `${type}Hooks`; if (!ctx[hookType]) ctx[hookType] = {}; while (i--) { let methodName = methodNames[i]; // for array method names if (Array.isArray(methodName)) { addHookByType(ctx, type, methodName, fn); } else { if (!ctx[hookType][methodName]) { ctx[hookType][methodName] = [fn]; } else { ctx[hookType][methodName].push(fn); } } } }
[ "function", "addHookByType", "(", "ctx", ",", "type", ",", "methodNames", ",", "fn", ")", "{", "let", "i", "=", "methodNames", ".", "length", ";", "// If no hook specified, add wildcard", "if", "(", "i", "===", "0", ")", "{", "methodNames", "=", "[", "'*'"...
Add hook by method names, nested method names will be flattened
[ "Add", "hook", "by", "method", "names", "nested", "method", "names", "will", "be", "flattened" ]
9e5938d5ce4991d0f9d12dbb4f50b3f30adbe601
https://github.com/baijijs/baiji/blob/9e5938d5ce4991d0f9d12dbb4f50b3f30adbe601/lib/utils/addHookByType.js#L6-L32
48,438
assemble/assemble-streams
index.js
viewStream
function viewStream(view) { return function() { var stream = utils.through.obj(); stream.setMaxListeners(0); setImmediate(function(item) { stream.write(item); stream.end(); }, this); return outStream(stream, view); }; }
javascript
function viewStream(view) { return function() { var stream = utils.through.obj(); stream.setMaxListeners(0); setImmediate(function(item) { stream.write(item); stream.end(); }, this); return outStream(stream, view); }; }
[ "function", "viewStream", "(", "view", ")", "{", "return", "function", "(", ")", "{", "var", "stream", "=", "utils", ".", "through", ".", "obj", "(", ")", ";", "stream", ".", "setMaxListeners", "(", "0", ")", ";", "setImmediate", "(", "function", "(", ...
Push the current view into a vinyl stream. ```js app.pages.getView('a.html').toStream() .on('data', function(file) { console.log(file); //=> <Page "a.html" <Buffer 2e 2e 2e>> }); ``` @name view.toStream @return {Stream} @api public
[ "Push", "the", "current", "view", "into", "a", "vinyl", "stream", "." ]
674e81cd523d50dce96455bea18f1b271bb4870a
https://github.com/assemble/assemble-streams/blob/674e81cd523d50dce96455bea18f1b271bb4870a/index.js#L145-L155
48,439
eblanshey/safenet
src/utils.js
parseJson
function parseJson(text) { try { var o = JSON.parse(text); if (o && typeof o === "object" && o !== null) return o; } catch (e) {} return text; }
javascript
function parseJson(text) { try { var o = JSON.parse(text); if (o && typeof o === "object" && o !== null) return o; } catch (e) {} return text; }
[ "function", "parseJson", "(", "text", ")", "{", "try", "{", "var", "o", "=", "JSON", ".", "parse", "(", "text", ")", ";", "if", "(", "o", "&&", "typeof", "o", "===", "\"object\"", "&&", "o", "!==", "null", ")", "return", "o", ";", "}", "catch", ...
Return parsed JSON if needed, otherwise returns text as is. @source http://stackoverflow.com/a/20392392/371699 @param text
[ "Return", "parsed", "JSON", "if", "needed", "otherwise", "returns", "text", "as", "is", "." ]
8438251bf0999b43f39c231df299b05d01dd4618
https://github.com/eblanshey/safenet/blob/8438251bf0999b43f39c231df299b05d01dd4618/src/utils.js#L38-L47
48,440
gardenhq/o
examples/b/bundled.js
substiteVariable
function substiteVariable(variable, options, cb) { var value; var err = null; var s = variable.split(':', 2); if (s.length == 2) { value = options.env[s[0]]; if (typeof value == 'function') { value = value(); } if (s[1][0] == '+') { // Substitute replacement, but only if variable is defined and nonempty. Otherwise, substitute nothing value = value ? s[1].substring(1) : ''; } else if (s[1][0] == '-') { // Substitute the value of variable, but if that is empty or undefined, use default instead value = value || s[1].substring(1); } else if (s[1][0] == '#') { // Substitute with the length of the value of the variable value = value !== undefined ? String(value).length : 0; } else if (s[1][0] == '=') { // Substitute the value of variable, but if that is empty or undefined, use default instead and set the variable to default if (!value) { value = s[1].substring(1); options.env[s[0]] = value; } } else if (s[1][0] == '?') { // If variable is defined and not empty, substitute its value. Otherwise, print message as an error message. if (!value) { if (s[1].length > 1) { throw new Error(); // return cb(s[0] + ': ' + s[1].substring(1)); } else { throw new Error(); // return cb(s[0] + ': parameter null or not set'); } } } } else { value = options.env[variable]; if (typeof value == 'function') { value = value(); } } return value; }
javascript
function substiteVariable(variable, options, cb) { var value; var err = null; var s = variable.split(':', 2); if (s.length == 2) { value = options.env[s[0]]; if (typeof value == 'function') { value = value(); } if (s[1][0] == '+') { // Substitute replacement, but only if variable is defined and nonempty. Otherwise, substitute nothing value = value ? s[1].substring(1) : ''; } else if (s[1][0] == '-') { // Substitute the value of variable, but if that is empty or undefined, use default instead value = value || s[1].substring(1); } else if (s[1][0] == '#') { // Substitute with the length of the value of the variable value = value !== undefined ? String(value).length : 0; } else if (s[1][0] == '=') { // Substitute the value of variable, but if that is empty or undefined, use default instead and set the variable to default if (!value) { value = s[1].substring(1); options.env[s[0]] = value; } } else if (s[1][0] == '?') { // If variable is defined and not empty, substitute its value. Otherwise, print message as an error message. if (!value) { if (s[1].length > 1) { throw new Error(); // return cb(s[0] + ': ' + s[1].substring(1)); } else { throw new Error(); // return cb(s[0] + ': parameter null or not set'); } } } } else { value = options.env[variable]; if (typeof value == 'function') { value = value(); } } return value; }
[ "function", "substiteVariable", "(", "variable", ",", "options", ",", "cb", ")", "{", "var", "value", ";", "var", "err", "=", "null", ";", "var", "s", "=", "variable", ".", "split", "(", "':'", ",", "2", ")", ";", "if", "(", "s", ".", "length", "...
Shell variable substitution code taken from 'somewhere'? Not sure who :( This will be cleaned up at some point anyway
[ "Shell", "variable", "substitution", "code", "taken", "from", "somewhere", "?" ]
cbca7760987d628de0b0d0647c95936f24577b00
https://github.com/gardenhq/o/blob/cbca7760987d628de0b0d0647c95936f24577b00/examples/b/bundled.js#L1054-L1097
48,441
mjtb/unidata
unidata.js
UnidataHeaders
function UnidataHeaders(d,m,e) { if(!d) { d = new Date(); } if(!m) { m = d; } if(!e) { const year = 1000 * 60 * 60 * 24 * 365; e = new Date(m.valueOf() + year); } else if(typeof(e) === 'number') { e = new Date(m.valueOf() + e); } /** * Date the database was downloaded. * * @type {Date} */ this.date = d; /** * Date the database was last updated on the server. * * @type {Date} */ this.modified = m; /** * Date the cached copy of the database is presumed to expire. * * @type {Date} */ this.expires = e; }
javascript
function UnidataHeaders(d,m,e) { if(!d) { d = new Date(); } if(!m) { m = d; } if(!e) { const year = 1000 * 60 * 60 * 24 * 365; e = new Date(m.valueOf() + year); } else if(typeof(e) === 'number') { e = new Date(m.valueOf() + e); } /** * Date the database was downloaded. * * @type {Date} */ this.date = d; /** * Date the database was last updated on the server. * * @type {Date} */ this.modified = m; /** * Date the cached copy of the database is presumed to expire. * * @type {Date} */ this.expires = e; }
[ "function", "UnidataHeaders", "(", "d", ",", "m", ",", "e", ")", "{", "if", "(", "!", "d", ")", "{", "d", "=", "new", "Date", "(", ")", ";", "}", "if", "(", "!", "m", ")", "{", "m", "=", "d", ";", "}", "if", "(", "!", "e", ")", "{", "...
Provides date information about the Unicode character database. <p>If the date of last modification is not provided, the download date is used. <p>Database expiration can be specified as a date or as a time period (in milliseconds) that is added to the last modification date. If not provided, an expiration period of one year is chosen. @class @constructor @param d {Date} date the database was downloaded @param m {Date} date of database last modification (optional) @param e {Date} expiration date or period (optional)
[ "Provides", "date", "information", "about", "the", "Unicode", "character", "database", "." ]
0d4de343c51dbf882161aea7ee50ffd93aa3a9c3
https://github.com/mjtb/unidata/blob/0d4de343c51dbf882161aea7ee50ffd93aa3a9c3/unidata.js#L1071-L1102
48,442
mjtb/unidata
unidata.js
Fraction
function Fraction(n, d) { if(typeof(d) === "number") { this.denominator = d; } else { this.denominator = 1; } if(typeof(n) === "number") { this.numerator = n; } else if(typeof(n) === "string") { let slash = n.indexOf('/'); if(slash > 0) { /** * The numerator of the fraction. * * @type {number} */ this.numerator = Number.parseInt(n.substring(0, slash)); /** * The denominator of the fraction. * * @type {number} * @defaultvalue 1 */ this.denominator = Number.parseInt(n.substring(slash + 1)); } else { this.numerator = Number.parseFloat(n); } } else if((typeof(n) === "object") && (n instanceof Fraction)) { this.numerator = n.numerator; this.denominator = n.denominator; } else { throw new TypeError(`${n} must be a number or a string`); } /** * The numeric value of the fraction i.e., numerator divided by denominator. * * @type {number} */ this.value = this.numerator / this.denominator; }
javascript
function Fraction(n, d) { if(typeof(d) === "number") { this.denominator = d; } else { this.denominator = 1; } if(typeof(n) === "number") { this.numerator = n; } else if(typeof(n) === "string") { let slash = n.indexOf('/'); if(slash > 0) { /** * The numerator of the fraction. * * @type {number} */ this.numerator = Number.parseInt(n.substring(0, slash)); /** * The denominator of the fraction. * * @type {number} * @defaultvalue 1 */ this.denominator = Number.parseInt(n.substring(slash + 1)); } else { this.numerator = Number.parseFloat(n); } } else if((typeof(n) === "object") && (n instanceof Fraction)) { this.numerator = n.numerator; this.denominator = n.denominator; } else { throw new TypeError(`${n} must be a number or a string`); } /** * The numeric value of the fraction i.e., numerator divided by denominator. * * @type {number} */ this.value = this.numerator / this.denominator; }
[ "function", "Fraction", "(", "n", ",", "d", ")", "{", "if", "(", "typeof", "(", "d", ")", "===", "\"number\"", ")", "{", "this", ".", "denominator", "=", "d", ";", "}", "else", "{", "this", ".", "denominator", "=", "1", ";", "}", "if", "(", "ty...
Represents a fraction i.e., a numerator and a denominator. @class @constructor @param n {number|string} numerator or string representation of the fraction @param d {number} (optional) denominator of the fraction
[ "Represents", "a", "fraction", "i", ".", "e", ".", "a", "numerator", "and", "a", "denominator", "." ]
0d4de343c51dbf882161aea7ee50ffd93aa3a9c3
https://github.com/mjtb/unidata/blob/0d4de343c51dbf882161aea7ee50ffd93aa3a9c3/unidata.js#L1528-L1567
48,443
nknapp/tree-from-paths
src/index.js
render
function render (files, baseDir, renderLabelFn, options = {}) { baseDir = baseDir.replace(/\/$/, '/') const strippedFiles = files.map(file => { /* istanbul ignore else: Else-case should never happen */ if (file.lastIndexOf(baseDir, 0) === 0) { return file.substr(baseDir.length) } /* istanbul ignore next: Should never happen */ throw new Error('Basedir ' + baseDir + ' must be a prefix of ' + file) }) const rootNode = treeFromPaths(strippedFiles, baseDir, renderLabelFn, options) const condensed = condense(rootNode) return archy(condensed) }
javascript
function render (files, baseDir, renderLabelFn, options = {}) { baseDir = baseDir.replace(/\/$/, '/') const strippedFiles = files.map(file => { /* istanbul ignore else: Else-case should never happen */ if (file.lastIndexOf(baseDir, 0) === 0) { return file.substr(baseDir.length) } /* istanbul ignore next: Should never happen */ throw new Error('Basedir ' + baseDir + ' must be a prefix of ' + file) }) const rootNode = treeFromPaths(strippedFiles, baseDir, renderLabelFn, options) const condensed = condense(rootNode) return archy(condensed) }
[ "function", "render", "(", "files", ",", "baseDir", ",", "renderLabelFn", ",", "options", "=", "{", "}", ")", "{", "baseDir", "=", "baseDir", ".", "replace", "(", "/", "\\/$", "/", ",", "'/'", ")", "const", "strippedFiles", "=", "files", ".", "map", ...
Renders a list of files like ``` ['abc/cde/efg/', 'abc/cde/abc', 'abc/zyx'] ``` as ascii-art tree (using [archy](https://www.npmjs.com/package/archy)) @param {string[]} files an array of sorted file paths relative to `parent` @param {string} baseDir the root path of the tree. @param {function({parent:string, file:string, explicit: boolean}):string} renderLabelFn function that renders the label of a node. It receives the parent and a filenpath as parameters. @param {object=} options optional parameters @param {string=} options.label the label of the root node (default: '') @returns {string} am ascii-art tree @access public
[ "Renders", "a", "list", "of", "files", "like" ]
0eabbbd96f33e7367c3f5292cb1a0a38b1975dfc
https://github.com/nknapp/tree-from-paths/blob/0eabbbd96f33e7367c3f5292cb1a0a38b1975dfc/src/index.js#L31-L44
48,444
nknapp/tree-from-paths
src/index.js
childNodesFromPaths
function childNodesFromPaths (files, parent, renderLabelFn, originalFiles, baseDir) { // Group by first path element var groups = _.groupBy(files, file => file.match(/^[^/]*\/?/)) return Object.keys(groups).map(function (groupKey) { const group = groups[groupKey] // Is this group explicitly part of the result, or // just implicit through its children const explicit = group.indexOf(groupKey) >= 0 let index = -1 if (explicit) { index = originalFiles.indexOf(parent.replace(baseDir, '') + groupKey) } return { label: renderLabelFn(parent, groupKey, explicit, explicit ? index : -1), nodes: childNodesFromPaths( // Remove parent directory from file paths group .map(node => node.substr(groupKey.length)) // Skip the empty path .filter(node => node), // New parent..., normalize to one trailing slash parent + groupKey, renderLabelFn, originalFiles, baseDir ) } }) }
javascript
function childNodesFromPaths (files, parent, renderLabelFn, originalFiles, baseDir) { // Group by first path element var groups = _.groupBy(files, file => file.match(/^[^/]*\/?/)) return Object.keys(groups).map(function (groupKey) { const group = groups[groupKey] // Is this group explicitly part of the result, or // just implicit through its children const explicit = group.indexOf(groupKey) >= 0 let index = -1 if (explicit) { index = originalFiles.indexOf(parent.replace(baseDir, '') + groupKey) } return { label: renderLabelFn(parent, groupKey, explicit, explicit ? index : -1), nodes: childNodesFromPaths( // Remove parent directory from file paths group .map(node => node.substr(groupKey.length)) // Skip the empty path .filter(node => node), // New parent..., normalize to one trailing slash parent + groupKey, renderLabelFn, originalFiles, baseDir ) } }) }
[ "function", "childNodesFromPaths", "(", "files", ",", "parent", ",", "renderLabelFn", ",", "originalFiles", ",", "baseDir", ")", "{", "// Group by first path element", "var", "groups", "=", "_", ".", "groupBy", "(", "files", ",", "file", "=>", "file", ".", "ma...
Compute the child nodes of a node, given a list of paths @param files @param parent @param renderLabelFn @returns {Array}
[ "Compute", "the", "child", "nodes", "of", "a", "node", "given", "a", "list", "of", "paths" ]
0eabbbd96f33e7367c3f5292cb1a0a38b1975dfc
https://github.com/nknapp/tree-from-paths/blob/0eabbbd96f33e7367c3f5292cb1a0a38b1975dfc/src/index.js#L85-L114
48,445
joneit/filter-tree
build/demo.js
msgBox
function msgBox(messageHTML) { var msgEl = document.querySelector('.msg-box'), rect = this.getBoundingClientRect(); msgEl.style.top = window.scrollY + rect.bottom + 8 + 'px'; msgEl.style.left = window.scrollX + rect.left + 8 + 'px'; msgEl.style.display = 'block'; msgEl.querySelector('.msg-box-close').addEventListener('click', closeMsgBox); msgEl.querySelector('.msg-box-content').innerHTML = messageHTML; this.classList.add('filter-box-warn'); }
javascript
function msgBox(messageHTML) { var msgEl = document.querySelector('.msg-box'), rect = this.getBoundingClientRect(); msgEl.style.top = window.scrollY + rect.bottom + 8 + 'px'; msgEl.style.left = window.scrollX + rect.left + 8 + 'px'; msgEl.style.display = 'block'; msgEl.querySelector('.msg-box-close').addEventListener('click', closeMsgBox); msgEl.querySelector('.msg-box-content').innerHTML = messageHTML; this.classList.add('filter-box-warn'); }
[ "function", "msgBox", "(", "messageHTML", ")", "{", "var", "msgEl", "=", "document", ".", "querySelector", "(", "'.msg-box'", ")", ",", "rect", "=", "this", ".", "getBoundingClientRect", "(", ")", ";", "msgEl", ".", "style", ".", "top", "=", "window", "....
Display an error message box. @this {Element} The offending input field. @param {string} messageHTML
[ "Display", "an", "error", "message", "box", "." ]
c070a4045fced3e4ab20ed2e0c706c9a5fd07d1e
https://github.com/joneit/filter-tree/blob/c070a4045fced3e4ab20ed2e0c706c9a5fd07d1e/build/demo.js#L131-L144
48,446
joneit/filter-tree
build/demo.js
captureExpressions
function captureExpressions(expressionChain, booleans) { var expressions, re; if (booleans) { re = new RegExp(PREFIX + booleans.join(INFIX) + POSTFIX, 'i'); expressions = expressionChain.match(re); expressions.shift(); // discard [0] (input) } else { expressions = [expressionChain]; } return expressions; }
javascript
function captureExpressions(expressionChain, booleans) { var expressions, re; if (booleans) { re = new RegExp(PREFIX + booleans.join(INFIX) + POSTFIX, 'i'); expressions = expressionChain.match(re); expressions.shift(); // discard [0] (input) } else { expressions = [expressionChain]; } return expressions; }
[ "function", "captureExpressions", "(", "expressionChain", ",", "booleans", ")", "{", "var", "expressions", ",", "re", ";", "if", "(", "booleans", ")", "{", "re", "=", "new", "RegExp", "(", "PREFIX", "+", "booleans", ".", "join", "(", "INFIX", ")", "+", ...
Break an expression chain into a list of expressions. @param {string} expressionChain @returns {string[]}
[ "Break", "an", "expression", "chain", "into", "a", "list", "of", "expressions", "." ]
c070a4045fced3e4ab20ed2e0c706c9a5fd07d1e
https://github.com/joneit/filter-tree/blob/c070a4045fced3e4ab20ed2e0c706c9a5fd07d1e/build/demo.js#L253-L265
48,447
rtm/upward
src/Fun.js
observeArgs
function observeArgs(args, run) { function observeArg(arg, i, args) { var observer = Observer( arg, function argObserver(changes) { changes.forEach(({type, newValue}) => { if (type === 'upward') { args[i] = newValue; observer.reobserve(newValue); } }); run(); }, // @TODO: consider whether to check for D/A/U here, or use 'modify' change type ['upward', 'delete', 'add', 'update'] // @TODO: check all these are necessary ); observer.observe(); } args.forEach(observeArg); }
javascript
function observeArgs(args, run) { function observeArg(arg, i, args) { var observer = Observer( arg, function argObserver(changes) { changes.forEach(({type, newValue}) => { if (type === 'upward') { args[i] = newValue; observer.reobserve(newValue); } }); run(); }, // @TODO: consider whether to check for D/A/U here, or use 'modify' change type ['upward', 'delete', 'add', 'update'] // @TODO: check all these are necessary ); observer.observe(); } args.forEach(observeArg); }
[ "function", "observeArgs", "(", "args", ",", "run", ")", "{", "function", "observeArg", "(", "arg", ",", "i", ",", "args", ")", "{", "var", "observer", "=", "Observer", "(", "arg", ",", "function", "argObserver", "(", "changes", ")", "{", "changes", "....
Observe changes to arguments. This will handle 'compute' changes, and trigger recomputation of function. When args changes, the new value is reobserved.
[ "Observe", "changes", "to", "arguments", ".", "This", "will", "handle", "compute", "changes", "and", "trigger", "recomputation", "of", "function", ".", "When", "args", "changes", "the", "new", "value", "is", "reobserved", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Fun.js#L99-L121
48,448
lrlna/olivaw
index.js
_setState
function _setState (lattice, size) { for (var num = 0; num < size; num++) { var cell = {} cell.state = getRandomState() lattice.push(cell) } return lattice }
javascript
function _setState (lattice, size) { for (var num = 0; num < size; num++) { var cell = {} cell.state = getRandomState() lattice.push(cell) } return lattice }
[ "function", "_setState", "(", "lattice", ",", "size", ")", "{", "for", "(", "var", "num", "=", "0", ";", "num", "<", "size", ";", "num", "++", ")", "{", "var", "cell", "=", "{", "}", "cell", ".", "state", "=", "getRandomState", "(", ")", "lattice...
get a random state and create all cells
[ "get", "a", "random", "state", "and", "create", "all", "cells" ]
2e195a4a79f8cf15389942973bd00f09461e7da6
https://github.com/lrlna/olivaw/blob/2e195a4a79f8cf15389942973bd00f09461e7da6/index.js#L41-L49
48,449
lrlna/olivaw
index.js
_getRule
function _getRule (neighbourhood) { var currentState = null var currentRule = [...rule] neighbourhoods.forEach(function (hood, index) { if (hood === neighbourhood) { currentState = currentRule[index] } }) return currentState }
javascript
function _getRule (neighbourhood) { var currentState = null var currentRule = [...rule] neighbourhoods.forEach(function (hood, index) { if (hood === neighbourhood) { currentState = currentRule[index] } }) return currentState }
[ "function", "_getRule", "(", "neighbourhood", ")", "{", "var", "currentState", "=", "null", "var", "currentRule", "=", "[", "...", "rule", "]", "neighbourhoods", ".", "forEach", "(", "function", "(", "hood", ",", "index", ")", "{", "if", "(", "hood", "==...
let's see which rule we are currently looking at
[ "let", "s", "see", "which", "rule", "we", "are", "currently", "looking", "at" ]
2e195a4a79f8cf15389942973bd00f09461e7da6
https://github.com/lrlna/olivaw/blob/2e195a4a79f8cf15389942973bd00f09461e7da6/index.js#L107-L117
48,450
nicktindall/cyclon.p2p-rtc-client
lib/PeerConnection.js
addLocalIceCandidate
function addLocalIceCandidate(event) { if (event && event.candidate) { // Add the ICE candidate only if we haven't already seen it var serializedCandidate = JSON.stringify(event.candidate); if (!storedIceCandidates.hasOwnProperty(serializedCandidate)) { storedIceCandidates[serializedCandidate] = true; localIceCandidates.push(event.candidate); } } // Emit an iceCandidates event containing all the candidates // gathered since the last event if we are emitting if (emittingIceCandidates && localIceCandidates.length > 0) { self.emit("iceCandidates", localIceCandidates); localIceCandidates = []; } }
javascript
function addLocalIceCandidate(event) { if (event && event.candidate) { // Add the ICE candidate only if we haven't already seen it var serializedCandidate = JSON.stringify(event.candidate); if (!storedIceCandidates.hasOwnProperty(serializedCandidate)) { storedIceCandidates[serializedCandidate] = true; localIceCandidates.push(event.candidate); } } // Emit an iceCandidates event containing all the candidates // gathered since the last event if we are emitting if (emittingIceCandidates && localIceCandidates.length > 0) { self.emit("iceCandidates", localIceCandidates); localIceCandidates = []; } }
[ "function", "addLocalIceCandidate", "(", "event", ")", "{", "if", "(", "event", "&&", "event", ".", "candidate", ")", "{", "// Add the ICE candidate only if we haven't already seen it", "var", "serializedCandidate", "=", "JSON", ".", "stringify", "(", "event", ".", ...
An ICE candidate was received @param event
[ "An", "ICE", "candidate", "was", "received" ]
eb586ce288a6ad7e1b221280825037e855b03904
https://github.com/nicktindall/cyclon.p2p-rtc-client/blob/eb586ce288a6ad7e1b221280825037e855b03904/lib/PeerConnection.js#L248-L264
48,451
reelyactive/chickadee
web/js/bubble.js
function() { var self = this; if (typeof CompilerInitialized !== "undefined") return true; oldPrepend = $.fn.prepend; $.fn.prepend = function() { var isFragment = arguments[0][0] && arguments[0][0].parentNode && arguments[0][0].parentNode.nodeName == "#document-fragment"; var result = oldPrepend.apply(this, arguments); if (isFragment) AngularCompile(arguments[0]); return result; }; oldAppend = $.fn.append; $.fn.append = function() { var isFragment = arguments[0][0] && arguments[0][0].parentNode && arguments[0][0].parentNode.nodeName == "#document-fragment"; var result = oldAppend.apply(this, arguments); if (isFragment) AngularCompile(arguments[0]); return result; }; AngularCompile = function(root) { var injector = angular.element($('[ng-app]')[0]).injector(); var $compile = injector.get('$compile'); var $rootScope = injector.get('$rootScope'); var result = $compile(root)($rootScope); $rootScope.$digest(); return result; } CompilerInitialized = true; }
javascript
function() { var self = this; if (typeof CompilerInitialized !== "undefined") return true; oldPrepend = $.fn.prepend; $.fn.prepend = function() { var isFragment = arguments[0][0] && arguments[0][0].parentNode && arguments[0][0].parentNode.nodeName == "#document-fragment"; var result = oldPrepend.apply(this, arguments); if (isFragment) AngularCompile(arguments[0]); return result; }; oldAppend = $.fn.append; $.fn.append = function() { var isFragment = arguments[0][0] && arguments[0][0].parentNode && arguments[0][0].parentNode.nodeName == "#document-fragment"; var result = oldAppend.apply(this, arguments); if (isFragment) AngularCompile(arguments[0]); return result; }; AngularCompile = function(root) { var injector = angular.element($('[ng-app]')[0]).injector(); var $compile = injector.get('$compile'); var $rootScope = injector.get('$rootScope'); var result = $compile(root)($rootScope); $rootScope.$digest(); return result; } CompilerInitialized = true; }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "if", "(", "typeof", "CompilerInitialized", "!==", "\"undefined\"", ")", "return", "true", ";", "oldPrepend", "=", "$", ".", "fn", ".", "prepend", ";", "$", ".", "fn", ".", "prepend", "=", "...
need Angular to recompile new elements after DOM manipulation
[ "need", "Angular", "to", "recompile", "new", "elements", "after", "DOM", "manipulation" ]
1f65c2d369694d93796aae63318fa76326275120
https://github.com/reelyactive/chickadee/blob/1f65c2d369694d93796aae63318fa76326275120/web/js/bubble.js#L356-L396
48,452
adplabs/PigeonKeeper
lib/vertex.js
Vertex
function Vertex(pkGloballyUniqueId, id, state, data) { var self = this; var pkGuid = pkGloballyUniqueId; var serviceStartMethod; if(VALID_STATES.indexOf(state) > -1) { this.id = id; this.state = state; this.data = data; } else { throw new Error("Invalid State", "Invalid initial state: " + state); } /** * Set state of the vertex * * @param {VALID_STATES} newState - The new state */ this.setState = function (newState) { if(VALID_STATES.indexOf(newState) > -1) { this.state = newState; if(newState == "IN_PROGRESS") { if(self.parent.parent.isRunning()) { self.emit(pkGuid + ":" + "start"); } else { // Ignore state changes when PK has stopped running } } } else { throw new Error("Invalid State", "Invalid state: " + newState); } }; /** * Method that PK calls when associated service is to be started * * @param {Function} serviceStart - Method that PK will call */ this.setServiceStartMethod = function (serviceStart) { serviceStartMethod = serviceStart; }; /** * Called by PK when associated process is successful * * @param {*} data - Data returned by process */ this.processSuccessful = function (data) { this.data = data; self.parent.parent.setState(id, "SUCCESS"); }; /** * Called by PK when process fails * * @param {*} err - Error object */ this.processFailed = function (err) { self.parent.parent.setState(id, "FAIL"); }; }
javascript
function Vertex(pkGloballyUniqueId, id, state, data) { var self = this; var pkGuid = pkGloballyUniqueId; var serviceStartMethod; if(VALID_STATES.indexOf(state) > -1) { this.id = id; this.state = state; this.data = data; } else { throw new Error("Invalid State", "Invalid initial state: " + state); } /** * Set state of the vertex * * @param {VALID_STATES} newState - The new state */ this.setState = function (newState) { if(VALID_STATES.indexOf(newState) > -1) { this.state = newState; if(newState == "IN_PROGRESS") { if(self.parent.parent.isRunning()) { self.emit(pkGuid + ":" + "start"); } else { // Ignore state changes when PK has stopped running } } } else { throw new Error("Invalid State", "Invalid state: " + newState); } }; /** * Method that PK calls when associated service is to be started * * @param {Function} serviceStart - Method that PK will call */ this.setServiceStartMethod = function (serviceStart) { serviceStartMethod = serviceStart; }; /** * Called by PK when associated process is successful * * @param {*} data - Data returned by process */ this.processSuccessful = function (data) { this.data = data; self.parent.parent.setState(id, "SUCCESS"); }; /** * Called by PK when process fails * * @param {*} err - Error object */ this.processFailed = function (err) { self.parent.parent.setState(id, "FAIL"); }; }
[ "function", "Vertex", "(", "pkGloballyUniqueId", ",", "id", ",", "state", ",", "data", ")", "{", "var", "self", "=", "this", ";", "var", "pkGuid", "=", "pkGloballyUniqueId", ";", "var", "serviceStartMethod", ";", "if", "(", "VALID_STATES", ".", "indexOf", ...
Creates a vertex for use in a digraph @constructor @param {string} pkGloballyUniqueId - ID of the associated PigeonKeeper, usually passed-in from digraph @param {string} id - The ID of this vertex @param {VALID_STATES} state - The initial state of this vertex @param {Object} data - Optional data object associated with this vertex
[ "Creates", "a", "vertex", "for", "use", "in", "a", "digraph" ]
c0a92d2032415617c2b6f6bd49d00a2c59bfaa41
https://github.com/adplabs/PigeonKeeper/blob/c0a92d2032415617c2b6f6bd49d00a2c59bfaa41/lib/vertex.js#L18-L94
48,453
building5/sails-hook-bunyan
index.js
function () { var config = sails.config[this.configKey]; // the ship drawing looks pretty silly in JSON sails.config.log.noShip = true; // as do color codes sails.config.log.colors = false; // setup some defaults config.logger.name = config.logger.name || 'sails'; config.logger.serializers = config.logger.serializers || bunyan.stdSerializers; this.reqSerializer = config.logger.serializers.req || function (x) { return x; }; this.logger = bunyan.createLogger(config.logger); }
javascript
function () { var config = sails.config[this.configKey]; // the ship drawing looks pretty silly in JSON sails.config.log.noShip = true; // as do color codes sails.config.log.colors = false; // setup some defaults config.logger.name = config.logger.name || 'sails'; config.logger.serializers = config.logger.serializers || bunyan.stdSerializers; this.reqSerializer = config.logger.serializers.req || function (x) { return x; }; this.logger = bunyan.createLogger(config.logger); }
[ "function", "(", ")", "{", "var", "config", "=", "sails", ".", "config", "[", "this", ".", "configKey", "]", ";", "// the ship drawing looks pretty silly in JSON", "sails", ".", "config", ".", "log", ".", "noShip", "=", "true", ";", "// as do color codes", "sa...
Hook configuration function.
[ "Hook", "configuration", "function", "." ]
0c46395198a0ad1105a7bc1946f5015bf4c7a185
https://github.com/building5/sails-hook-bunyan/blob/0c46395198a0ad1105a7bc1946f5015bf4c7a185/index.js#L97-L115
48,454
building5/sails-hook-bunyan
index.js
function (done) { var config = sails.config[this.configKey]; _this = this; // If a rotationSignal is given, listen for it if (config.rotationSignal) { process.on(config.rotationSignal, function () { _this.logger.reopenFileStreams(); }); } // If logUncaughtException is set, log those, too if (config.logUncaughtException) { process.on('uncaughtException', function (err) { _this.logger.fatal({ err: err }, 'Uncaught exception'); process.exit(1); }); } // save off injectRequestLogger for middleware route injectRequestLogger = sails.config[this.configKey].injectRequestLogger; // Inject log methods var log = sails.log = this.logger.debug.bind(this.logger); Object.keys(logLevels).forEach(function (sailsLevel) { var bunyanLevel = logLevels[sailsLevel]; if (bunyanLevel) { log[sailsLevel] = function () { var logger = config.getLogger(); logger[bunyanLevel].apply(logger, arguments); }; } else { // no-op log[sailsLevel] = function () {}; } }); done(); }
javascript
function (done) { var config = sails.config[this.configKey]; _this = this; // If a rotationSignal is given, listen for it if (config.rotationSignal) { process.on(config.rotationSignal, function () { _this.logger.reopenFileStreams(); }); } // If logUncaughtException is set, log those, too if (config.logUncaughtException) { process.on('uncaughtException', function (err) { _this.logger.fatal({ err: err }, 'Uncaught exception'); process.exit(1); }); } // save off injectRequestLogger for middleware route injectRequestLogger = sails.config[this.configKey].injectRequestLogger; // Inject log methods var log = sails.log = this.logger.debug.bind(this.logger); Object.keys(logLevels).forEach(function (sailsLevel) { var bunyanLevel = logLevels[sailsLevel]; if (bunyanLevel) { log[sailsLevel] = function () { var logger = config.getLogger(); logger[bunyanLevel].apply(logger, arguments); }; } else { // no-op log[sailsLevel] = function () {}; } }); done(); }
[ "function", "(", "done", ")", "{", "var", "config", "=", "sails", ".", "config", "[", "this", ".", "configKey", "]", ";", "_this", "=", "this", ";", "// If a rotationSignal is given, listen for it", "if", "(", "config", ".", "rotationSignal", ")", "{", "proc...
Hook initialization function.
[ "Hook", "initialization", "function", "." ]
0c46395198a0ad1105a7bc1946f5015bf4c7a185
https://github.com/building5/sails-hook-bunyan/blob/0c46395198a0ad1105a7bc1946f5015bf4c7a185/index.js#L120-L160
48,455
dogada/wpml
lib/compiler.js
urlize
function urlize(worker, text) { if (!linkify.test(text)) return escape(text) var matches = linkify.match(text) var lastIndex = 0; var buf = [] for (var i = 0, match; (match = matches[i++]); ) { buf.push(escape(text.slice(lastIndex, match.index))) var link = {tag: true, name: 'a', attrs: {href: match.url}, value: escape(match.type === 'hashtag' ? match.text : truncateUrl(match.text))} if (match.type === 'hashtag') { link.attrs['class'] = 'p-category' } else { link.attrs.rel = 'nofollow' link.attrs.target = '_blank' } buf = buf.concat(tagBuffer(worker, link, true)) lastIndex = match.lastIndex } buf.push(escape(text.slice(lastIndex))) debug('urlize', matches, buf) return buf.join('') }
javascript
function urlize(worker, text) { if (!linkify.test(text)) return escape(text) var matches = linkify.match(text) var lastIndex = 0; var buf = [] for (var i = 0, match; (match = matches[i++]); ) { buf.push(escape(text.slice(lastIndex, match.index))) var link = {tag: true, name: 'a', attrs: {href: match.url}, value: escape(match.type === 'hashtag' ? match.text : truncateUrl(match.text))} if (match.type === 'hashtag') { link.attrs['class'] = 'p-category' } else { link.attrs.rel = 'nofollow' link.attrs.target = '_blank' } buf = buf.concat(tagBuffer(worker, link, true)) lastIndex = match.lastIndex } buf.push(escape(text.slice(lastIndex))) debug('urlize', matches, buf) return buf.join('') }
[ "function", "urlize", "(", "worker", ",", "text", ")", "{", "if", "(", "!", "linkify", ".", "test", "(", "text", ")", ")", "return", "escape", "(", "text", ")", "var", "matches", "=", "linkify", ".", "match", "(", "text", ")", "var", "lastIndex", "...
Escape and urlize text.
[ "Escape", "and", "urlize", "text", "." ]
283e72a530151c4086afb4f78c0d97af6d213405
https://github.com/dogada/wpml/blob/283e72a530151c4086afb4f78c0d97af6d213405/lib/compiler.js#L65-L88
48,456
dogada/wpml
lib/compiler.js
compile
function compile(ast, opts) { opts = assign({}, config.defaultOpts, opts) debug('compile', opts, ast) var worker = makeWorker(opts) for (var i = 0, text = ast.value, len = text.length; i < len; i++) { compileLine(text[i], worker) } return worker.buf.join('') }
javascript
function compile(ast, opts) { opts = assign({}, config.defaultOpts, opts) debug('compile', opts, ast) var worker = makeWorker(opts) for (var i = 0, text = ast.value, len = text.length; i < len; i++) { compileLine(text[i], worker) } return worker.buf.join('') }
[ "function", "compile", "(", "ast", ",", "opts", ")", "{", "opts", "=", "assign", "(", "{", "}", ",", "config", ".", "defaultOpts", ",", "opts", ")", "debug", "(", "'compile'", ",", "opts", ",", "ast", ")", "var", "worker", "=", "makeWorker", "(", "...
Compile parsed MML-document into HTML. @param {object} ast Parsed WPML document @param {object} opts Same as opts in mml.doc @return{ string} Generated html string.
[ "Compile", "parsed", "MML", "-", "document", "into", "HTML", "." ]
283e72a530151c4086afb4f78c0d97af6d213405
https://github.com/dogada/wpml/blob/283e72a530151c4086afb4f78c0d97af6d213405/lib/compiler.js#L196-L204
48,457
brindille/brindille-component
lib/index.js
findComponents
function findComponents(nodes, callback) { nodes = toArray(nodes); nodes = [].slice.call(nodes); var node; for (var i = 0, l = nodes.length; i < l; i++) { node = nodes[i]; if (node && node.hasAttribute && node.hasAttribute('data-component')) { callback(node); } else if (node.childNodes && node.childNodes.length) { findComponents([].slice.call(node.childNodes), callback); } } }
javascript
function findComponents(nodes, callback) { nodes = toArray(nodes); nodes = [].slice.call(nodes); var node; for (var i = 0, l = nodes.length; i < l; i++) { node = nodes[i]; if (node && node.hasAttribute && node.hasAttribute('data-component')) { callback(node); } else if (node.childNodes && node.childNodes.length) { findComponents([].slice.call(node.childNodes), callback); } } }
[ "function", "findComponents", "(", "nodes", ",", "callback", ")", "{", "nodes", "=", "toArray", "(", "nodes", ")", ";", "nodes", "=", "[", "]", ".", "slice", ".", "call", "(", "nodes", ")", ";", "var", "node", ";", "for", "(", "var", "i", "=", "0...
Recursively Applies a callback on each Node that is found to be a Component @param {Array} nodes an array of Node @param {*} callback function to call on each Node that has data-component
[ "Recursively", "Applies", "a", "callback", "on", "each", "Node", "that", "is", "found", "to", "be", "a", "Component" ]
a53b4a568ff93c76d7f73d8b401c0d57cc9d1685
https://github.com/brindille/brindille-component/blob/a53b4a568ff93c76d7f73d8b401c0d57cc9d1685/lib/index.js#L250-L264
48,458
darul75/ng-audio
src/public/bower_components/ngprogress/src/provider.js
function () { count = 100; this.updateCount(count); var self = this; $timeout(function () { self.hide(); $timeout(function () { count = 0; self.updateCount(count); }, 500); }, 1000); return count; }
javascript
function () { count = 100; this.updateCount(count); var self = this; $timeout(function () { self.hide(); $timeout(function () { count = 0; self.updateCount(count); }, 500); }, 1000); return count; }
[ "function", "(", ")", "{", "count", "=", "100", ";", "this", ".", "updateCount", "(", "count", ")", ";", "var", "self", "=", "this", ";", "$timeout", "(", "function", "(", ")", "{", "self", ".", "hide", "(", ")", ";", "$timeout", "(", "function", ...
Jumps to 100% progress and fades away progressbar.
[ "Jumps", "to", "100%", "progress", "and", "fades", "away", "progressbar", "." ]
602f9fe92134955dc16d725732f508a4ebc4fb75
https://github.com/darul75/ng-audio/blob/602f9fe92134955dc16d725732f508a4ebc4fb75/src/public/bower_components/ngprogress/src/provider.js#L133-L145
48,459
rtm/upward
src/Asy.js
promisify
function promisify(f) { // given an underlying function, return function _promisify(...args) { // return a function which return new Promise( // returns a promise resolve => Promise.all([this, ...args]) // which, when all args are resolved, .then( parms => resolve(f.call(...parms)) // resolves to the function result ) ); }; }
javascript
function promisify(f) { // given an underlying function, return function _promisify(...args) { // return a function which return new Promise( // returns a promise resolve => Promise.all([this, ...args]) // which, when all args are resolved, .then( parms => resolve(f.call(...parms)) // resolves to the function result ) ); }; }
[ "function", "promisify", "(", "f", ")", "{", "// given an underlying function,", "return", "function", "_promisify", "(", "...", "args", ")", "{", "// return a function which", "return", "new", "Promise", "(", "// returns a promise", "resolve", "=>", "Promise", ".", ...
"Promisify" a function, meaning to create a function which returns a promise for the value of the function once `this` and all arguments have been fulfilled.
[ "Promisify", "a", "function", "meaning", "to", "create", "a", "function", "which", "returns", "a", "promise", "for", "the", "value", "of", "the", "function", "once", "this", "and", "all", "arguments", "have", "been", "fulfilled", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Asy.js#L82-L91
48,460
baijijs/baiji
lib/utils/compose.js
handleError
function handleError(promise) { if (canHandleError) { return promise.catch(function(err) { if (ctx) { ctx.error = err; if (ctx.emit) ctx.emit('error', ctx); } else { ctx = { error: err }; } return onError(ctx, next).catch(function(err) { // Log catched error in onError logError(`[${new Date()}] ${err.name || err.message} \n ${err.stack}`); }); }); } else { return promise; } }
javascript
function handleError(promise) { if (canHandleError) { return promise.catch(function(err) { if (ctx) { ctx.error = err; if (ctx.emit) ctx.emit('error', ctx); } else { ctx = { error: err }; } return onError(ctx, next).catch(function(err) { // Log catched error in onError logError(`[${new Date()}] ${err.name || err.message} \n ${err.stack}`); }); }); } else { return promise; } }
[ "function", "handleError", "(", "promise", ")", "{", "if", "(", "canHandleError", ")", "{", "return", "promise", ".", "catch", "(", "function", "(", "err", ")", "{", "if", "(", "ctx", ")", "{", "ctx", ".", "error", "=", "err", ";", "if", "(", "ctx"...
Handle possible error for each promise
[ "Handle", "possible", "error", "for", "each", "promise" ]
9e5938d5ce4991d0f9d12dbb4f50b3f30adbe601
https://github.com/baijijs/baiji/blob/9e5938d5ce4991d0f9d12dbb4f50b3f30adbe601/lib/utils/compose.js#L50-L67
48,461
khalyomede/aegean
dist/main.js
aegean
function aegean(path) { if (path === null || path === undefined || path.constructor !== String) { throw new Error("aegean expects parameter 1 to be a string"); } if (fs_1.existsSync(path) === false) { throw new Error("file \"" + path + "\" does not exist"); } var stat = fs_1.lstatSync(path); if (stat.isFile() === false) { throw new Error("path \"" + path + "\" should target a file"); } var content = fs_1.readFileSync(path).toString(); var result = inline(content, path); return result; }
javascript
function aegean(path) { if (path === null || path === undefined || path.constructor !== String) { throw new Error("aegean expects parameter 1 to be a string"); } if (fs_1.existsSync(path) === false) { throw new Error("file \"" + path + "\" does not exist"); } var stat = fs_1.lstatSync(path); if (stat.isFile() === false) { throw new Error("path \"" + path + "\" should target a file"); } var content = fs_1.readFileSync(path).toString(); var result = inline(content, path); return result; }
[ "function", "aegean", "(", "path", ")", "{", "if", "(", "path", "===", "null", "||", "path", "===", "undefined", "||", "path", ".", "constructor", "!==", "String", ")", "{", "throw", "new", "Error", "(", "\"aegean expects parameter 1 to be a string\"", ")", ...
Include imports statements down to the importing file. @param {String} path The path to the file to inline. @return {String} The inlined content. @throws {Error} If the first parameter is not a string. @throws {Error} If the path target a non existing file. @throws {Error} If the path does not target a file.
[ "Include", "imports", "statements", "down", "to", "the", "importing", "file", "." ]
99957eb9df483bb8b9e864af848af2371a6efa96
https://github.com/khalyomede/aegean/blob/99957eb9df483bb8b9e864af848af2371a6efa96/dist/main.js#L14-L28
48,462
khalyomede/aegean
dist/main.js
inline
function inline(content, path) { var result = content; var ast = babylon.parse(content, { allowImportExportEverywhere: true }); var statements = ast.program.body; var gap = 0; for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { var statement = statements_1[_i]; if (statement.type === "ImportDeclaration") { if (statement.specifiers.length === 0) { var regexpLocalFile = /^\.\//; var subPath = ""; if (regexpLocalFile.test(statement.source.value)) { subPath = path_1.dirname(path) + "/" + statement.source.value + (statement.source.value.endsWith(".js") ? "" : ".js"); } else { subPath = require.resolve(statement.source.value); } if (fs_1.existsSync(subPath) === false) { throw new Error("file \"" + path_1.resolve(__dirname, subPath) + "\" does not exist"); } var stat = fs_1.lstatSync(subPath); if (stat.isFile() === false) { throw new Error("path \"" + subPath + "\" should target a file"); } var subContent = fs_1.readFileSync(subPath).toString(); var subResult = inline(subContent, subPath); result = result.substring(0, statement.start + gap) + subResult + result.substring(statement.end + gap); gap += subResult.length - (statement.end - statement.start); } } } return result; }
javascript
function inline(content, path) { var result = content; var ast = babylon.parse(content, { allowImportExportEverywhere: true }); var statements = ast.program.body; var gap = 0; for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { var statement = statements_1[_i]; if (statement.type === "ImportDeclaration") { if (statement.specifiers.length === 0) { var regexpLocalFile = /^\.\//; var subPath = ""; if (regexpLocalFile.test(statement.source.value)) { subPath = path_1.dirname(path) + "/" + statement.source.value + (statement.source.value.endsWith(".js") ? "" : ".js"); } else { subPath = require.resolve(statement.source.value); } if (fs_1.existsSync(subPath) === false) { throw new Error("file \"" + path_1.resolve(__dirname, subPath) + "\" does not exist"); } var stat = fs_1.lstatSync(subPath); if (stat.isFile() === false) { throw new Error("path \"" + subPath + "\" should target a file"); } var subContent = fs_1.readFileSync(subPath).toString(); var subResult = inline(subContent, subPath); result = result.substring(0, statement.start + gap) + subResult + result.substring(statement.end + gap); gap += subResult.length - (statement.end - statement.start); } } } return result; }
[ "function", "inline", "(", "content", ",", "path", ")", "{", "var", "result", "=", "content", ";", "var", "ast", "=", "babylon", ".", "parse", "(", "content", ",", "{", "allowImportExportEverywhere", ":", "true", "}", ")", ";", "var", "statements", "=", ...
Traverse a content and import recursively all the import statement contents into the content. @param {String} content The file that could contain import statement. @param {String} path The path to the file. @return {String} The content with potential inlined import statements. @throws {Error} If one of the sub import files target a non existing file in their imports. @throws {Error} If one of the sub import files does not target a file.
[ "Traverse", "a", "content", "and", "import", "recursively", "all", "the", "import", "statement", "contents", "into", "the", "content", "." ]
99957eb9df483bb8b9e864af848af2371a6efa96
https://github.com/khalyomede/aegean/blob/99957eb9df483bb8b9e864af848af2371a6efa96/dist/main.js#L38-L79
48,463
mattma/ngd3
build.js
spawnObservable
function spawnObservable(command, args) { return Observable.create(observer => { const cmd = spawn(command, args); observer.next(''); // hack to kick things off, not every command will have a stdout cmd.stdout.on('data', (data) => { observer.next(data.toString('utf8')); }); cmd.stderr.on('data', (data) => { observer.error(data.toString('utf8')); }); cmd.on('close', (data) => { observer.complete(); }); }); }
javascript
function spawnObservable(command, args) { return Observable.create(observer => { const cmd = spawn(command, args); observer.next(''); // hack to kick things off, not every command will have a stdout cmd.stdout.on('data', (data) => { observer.next(data.toString('utf8')); }); cmd.stderr.on('data', (data) => { observer.error(data.toString('utf8')); }); cmd.on('close', (data) => { observer.complete(); }); }); }
[ "function", "spawnObservable", "(", "command", ",", "args", ")", "{", "return", "Observable", ".", "create", "(", "observer", "=>", "{", "const", "cmd", "=", "spawn", "(", "command", ",", "args", ")", ";", "observer", ".", "next", "(", "''", ")", ";", ...
Create an Observable of a spawned child process. @param {string} command @param {string[]} args
[ "Create", "an", "Observable", "of", "a", "spawned", "child", "process", "." ]
bdc5bf20e51c1a5f64f54ea1c083316d540560b1
https://github.com/mattma/ngd3/blob/bdc5bf20e51c1a5f64f54ea1c083316d540560b1/build.js#L32-L40
48,464
mattma/ngd3
build.js
createUmd
function createUmd(name, globals) { // core module is ngd3 the rest are ngd3.feature const MODULE_NAMES = { ngd3: 'ngd3', }; const ENTRIES = { ngd3: `${process.cwd()}/dist/index.js`, }; const moduleName = MODULE_NAMES[name]; const entry = ENTRIES[name]; return generateBundle(entry, { dest: `${process.cwd()}/dist/bundles/${name}.umd.js`, globals, moduleName }); }
javascript
function createUmd(name, globals) { // core module is ngd3 the rest are ngd3.feature const MODULE_NAMES = { ngd3: 'ngd3', }; const ENTRIES = { ngd3: `${process.cwd()}/dist/index.js`, }; const moduleName = MODULE_NAMES[name]; const entry = ENTRIES[name]; return generateBundle(entry, { dest: `${process.cwd()}/dist/bundles/${name}.umd.js`, globals, moduleName }); }
[ "function", "createUmd", "(", "name", ",", "globals", ")", "{", "// core module is ngd3 the rest are ngd3.feature", "const", "MODULE_NAMES", "=", "{", "ngd3", ":", "'ngd3'", ",", "}", ";", "const", "ENTRIES", "=", "{", "ngd3", ":", "`", "${", "process", ".", ...
Create a UMD bundle given a module name. @param {string} name @param {Object} globals
[ "Create", "a", "UMD", "bundle", "given", "a", "module", "name", "." ]
bdc5bf20e51c1a5f64f54ea1c083316d540560b1
https://github.com/mattma/ngd3/blob/bdc5bf20e51c1a5f64f54ea1c083316d540560b1/build.js#L60-L76
48,465
mattma/ngd3
build.js
replaceVersionsObservable
function replaceVersionsObservable(name, versions) { return Observable.create((observer) => { const package = getSrcPackageFile(name); let pkg = readFileSync(package, 'utf8'); const regexs = Object.keys(versions).map(key => ({ expr: new RegExp(key, 'g'), key, val: versions[key] })); regexs.forEach(reg => { pkg = pkg.replace(reg.expr, reg.val); }); const outPath = getDestPackageFile(name); writeFile(outPath, pkg, err => { if (err) { observer.error(err); } else { observer.next(pkg); observer.complete(); } }); }); }
javascript
function replaceVersionsObservable(name, versions) { return Observable.create((observer) => { const package = getSrcPackageFile(name); let pkg = readFileSync(package, 'utf8'); const regexs = Object.keys(versions).map(key => ({ expr: new RegExp(key, 'g'), key, val: versions[key] })); regexs.forEach(reg => { pkg = pkg.replace(reg.expr, reg.val); }); const outPath = getDestPackageFile(name); writeFile(outPath, pkg, err => { if (err) { observer.error(err); } else { observer.next(pkg); observer.complete(); } }); }); }
[ "function", "replaceVersionsObservable", "(", "name", ",", "versions", ")", "{", "return", "Observable", ".", "create", "(", "(", "observer", ")", "=>", "{", "const", "package", "=", "getSrcPackageFile", "(", "name", ")", ";", "let", "pkg", "=", "readFileSyn...
Create an observable of package.json dependency version replacements. This keeps the dependency versions across each package in sync. @param {string} name @param {Object} versions
[ "Create", "an", "observable", "of", "package", ".", "json", "dependency", "version", "replacements", ".", "This", "keeps", "the", "dependency", "versions", "across", "each", "package", "in", "sync", "." ]
bdc5bf20e51c1a5f64f54ea1c083316d540560b1
https://github.com/mattma/ngd3/blob/bdc5bf20e51c1a5f64f54ea1c083316d540560b1/build.js#L106-L125
48,466
mattma/ngd3
build.js
getVersions
function getVersions() { const paths = [ getDestPackageFile('ngd3'), ]; return paths .map(path => require(path)) .map(pkgs => pkgs.version); }
javascript
function getVersions() { const paths = [ getDestPackageFile('ngd3'), ]; return paths .map(path => require(path)) .map(pkgs => pkgs.version); }
[ "function", "getVersions", "(", ")", "{", "const", "paths", "=", "[", "getDestPackageFile", "(", "'ngd3'", ")", ",", "]", ";", "return", "paths", ".", "map", "(", "path", "=>", "require", "(", "path", ")", ")", ".", "map", "(", "pkgs", "=>", "pkgs", ...
Returns each version of each NgD3 module. This is used to help ensure each package has the same version.
[ "Returns", "each", "version", "of", "each", "NgD3", "module", ".", "This", "is", "used", "to", "help", "ensure", "each", "package", "has", "the", "same", "version", "." ]
bdc5bf20e51c1a5f64f54ea1c083316d540560b1
https://github.com/mattma/ngd3/blob/bdc5bf20e51c1a5f64f54ea1c083316d540560b1/build.js#L151-L159
48,467
erossignon/redmine-api
lib/redmine_web_server.js
fixUnicode
function fixUnicode(txt) { txt = txt.replace(/\003/g, ' '); txt = txt.replace(/\004/g, ' '); txt = txt.replace(/(\r|\n)/g, ' '); txt = txt.replace(/[\u007f-\uffff]/g, function (c) { return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4); }); return txt; }
javascript
function fixUnicode(txt) { txt = txt.replace(/\003/g, ' '); txt = txt.replace(/\004/g, ' '); txt = txt.replace(/(\r|\n)/g, ' '); txt = txt.replace(/[\u007f-\uffff]/g, function (c) { return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4); }); return txt; }
[ "function", "fixUnicode", "(", "txt", ")", "{", "txt", "=", "txt", ".", "replace", "(", "/", "\\003", "/", "g", ",", "' '", ")", ";", "txt", "=", "txt", ".", "replace", "(", "/", "\\004", "/", "g", ",", "' '", ")", ";", "txt", "=", "txt", "."...
Fix Unicode String that would cause JSON.parse to fail
[ "Fix", "Unicode", "String", "that", "would", "cause", "JSON", ".", "parse", "to", "fail" ]
8850f38c10fedf1d891cf3670863aed08c70745a
https://github.com/erossignon/redmine-api/blob/8850f38c10fedf1d891cf3670863aed08c70745a/lib/redmine_web_server.js#L41-L49
48,468
erossignon/redmine-api
lib/redmine_web_server.js
__fetchTicketInfo
function __fetchTicketInfo(server, ticketid, callback) { assert(server.cache_folder); var filename = server._ticket_cache_file(ticketid); //xx console.log("filename " , filename.red); assert(_.isFunction(callback)); var command = 'issues/' + ticketid.toString() + '.json?include=relations,journals'; perform_http_get_transaction(server,command, function (err, txt) { txt = fixUnicode(txt); var ticket = null; try { var o = JSON.parse(txt); fs.writeFileSync(filename, JSON.stringify(o, null, " ")); console.warn(" writing ", filename); ticket= o.issue; } catch (err) { console.log("error !".red, err.message); fs.writeFileSync("toto.txt", txt); callback(err); return; // the ticket may have been deleted } callback(null,ticket); }); }
javascript
function __fetchTicketInfo(server, ticketid, callback) { assert(server.cache_folder); var filename = server._ticket_cache_file(ticketid); //xx console.log("filename " , filename.red); assert(_.isFunction(callback)); var command = 'issues/' + ticketid.toString() + '.json?include=relations,journals'; perform_http_get_transaction(server,command, function (err, txt) { txt = fixUnicode(txt); var ticket = null; try { var o = JSON.parse(txt); fs.writeFileSync(filename, JSON.stringify(o, null, " ")); console.warn(" writing ", filename); ticket= o.issue; } catch (err) { console.log("error !".red, err.message); fs.writeFileSync("toto.txt", txt); callback(err); return; // the ticket may have been deleted } callback(null,ticket); }); }
[ "function", "__fetchTicketInfo", "(", "server", ",", "ticketid", ",", "callback", ")", "{", "assert", "(", "server", ".", "cache_folder", ")", ";", "var", "filename", "=", "server", ".", "_ticket_cache_file", "(", "ticketid", ")", ";", "//xx console.log(\"filena...
\brief extract the full raw information for a given ticket out of redmine and store it to a json file in the cache. any old version of the ticket json file will be overwritten
[ "\\", "brief", "extract", "the", "full", "raw", "information", "for", "a", "given", "ticket", "out", "of", "redmine", "and", "store", "it", "to", "a", "json", "file", "in", "the", "cache", ".", "any", "old", "version", "of", "the", "ticket", "json", "f...
8850f38c10fedf1d891cf3670863aed08c70745a
https://github.com/erossignon/redmine-api/blob/8850f38c10fedf1d891cf3670863aed08c70745a/lib/redmine_web_server.js#L327-L360
48,469
Kurento/kurento-module-crowddetector-js
lib/complexTypes/RelativePoint.js
RelativePoint
function RelativePoint(relativePointDict){ if(!(this instanceof RelativePoint)) return new RelativePoint(relativePointDict) relativePointDict = relativePointDict || {} // Check relativePointDict has the required fields // // checkType('float', 'relativePointDict.x', relativePointDict.x, {required: true}); // // checkType('float', 'relativePointDict.y', relativePointDict.y, {required: true}); // // Init parent class RelativePoint.super_.call(this, relativePointDict) // Set object properties Object.defineProperties(this, { x: { writable: true, enumerable: true, value: relativePointDict.x }, y: { writable: true, enumerable: true, value: relativePointDict.y } }) }
javascript
function RelativePoint(relativePointDict){ if(!(this instanceof RelativePoint)) return new RelativePoint(relativePointDict) relativePointDict = relativePointDict || {} // Check relativePointDict has the required fields // // checkType('float', 'relativePointDict.x', relativePointDict.x, {required: true}); // // checkType('float', 'relativePointDict.y', relativePointDict.y, {required: true}); // // Init parent class RelativePoint.super_.call(this, relativePointDict) // Set object properties Object.defineProperties(this, { x: { writable: true, enumerable: true, value: relativePointDict.x }, y: { writable: true, enumerable: true, value: relativePointDict.y } }) }
[ "function", "RelativePoint", "(", "relativePointDict", ")", "{", "if", "(", "!", "(", "this", "instanceof", "RelativePoint", ")", ")", "return", "new", "RelativePoint", "(", "relativePointDict", ")", "relativePointDict", "=", "relativePointDict", "||", "{", "}", ...
Relative points in a physical screen, values are a percentage relative to the @constructor module:crowddetector/complexTypes.RelativePoint @property {external:Number} x Percentage relative to the image width to calculate the X coordinate of the point [0..1] @property {external:Number} y Percentage relative to the image height to calculate the Y coordinate of the
[ "Relative", "points", "in", "a", "physical", "screen", "values", "are", "a", "percentage", "relative", "to", "the" ]
ae0a03c5d6bbc07a23d083fe8916017cb4a63855
https://github.com/Kurento/kurento-module-crowddetector-js/blob/ae0a03c5d6bbc07a23d083fe8916017cb4a63855/lib/complexTypes/RelativePoint.js#L40-L69
48,470
adplabs/PigeonKeeper
lib/pigeonkeeper.js
initializeStates
function initializeStates() { // Set all states to NOT_READY var numVertices = graph.vertexCount(); var vertexIds = graph.getVertexIds(); for(var i = 0; i < numVertices; i++) { graph.getVertex(vertexIds[i]).setState("NOT_READY"); } }
javascript
function initializeStates() { // Set all states to NOT_READY var numVertices = graph.vertexCount(); var vertexIds = graph.getVertexIds(); for(var i = 0; i < numVertices; i++) { graph.getVertex(vertexIds[i]).setState("NOT_READY"); } }
[ "function", "initializeStates", "(", ")", "{", "// Set all states to NOT_READY", "var", "numVertices", "=", "graph", ".", "vertexCount", "(", ")", ";", "var", "vertexIds", "=", "graph", ".", "getVertexIds", "(", ")", ";", "for", "(", "var", "i", "=", "0", ...
Sets states of all vertices to be NOT_READY @private
[ "Sets", "states", "of", "all", "vertices", "to", "be", "NOT_READY" ]
c0a92d2032415617c2b6f6bd49d00a2c59bfaa41
https://github.com/adplabs/PigeonKeeper/blob/c0a92d2032415617c2b6f6bd49d00a2c59bfaa41/lib/pigeonkeeper.js#L404-L414
48,471
adplabs/PigeonKeeper
lib/pigeonkeeper.js
startReadyProcesses
function startReadyProcesses() { // Start as many processes as we can! //writeToLog("INFO", "***** maxNumberOfRunningProcesses = " + maxNumberOfRunningProcesses + "; numberOfRunningProcesses = " + numberOfRunningProcesses); var numVertices = graph.vertexCount(); var vertexIds = graph.getVertexIds(); for(var i = 0; i < numVertices; i++) { if(graph.getVertex(vertexIds[i]).state == "READY") { if(maxNumberOfRunningProcesses > 0 && numberOfRunningProcesses < maxNumberOfRunningProcesses) { numberOfRunningProcesses++; graph.getVertex(vertexIds[i]).setState("IN_PROGRESS"); } else if(maxNumberOfRunningProcesses <= 0) { numberOfRunningProcesses++; graph.getVertex(vertexIds[i]).setState("IN_PROGRESS"); } } } }
javascript
function startReadyProcesses() { // Start as many processes as we can! //writeToLog("INFO", "***** maxNumberOfRunningProcesses = " + maxNumberOfRunningProcesses + "; numberOfRunningProcesses = " + numberOfRunningProcesses); var numVertices = graph.vertexCount(); var vertexIds = graph.getVertexIds(); for(var i = 0; i < numVertices; i++) { if(graph.getVertex(vertexIds[i]).state == "READY") { if(maxNumberOfRunningProcesses > 0 && numberOfRunningProcesses < maxNumberOfRunningProcesses) { numberOfRunningProcesses++; graph.getVertex(vertexIds[i]).setState("IN_PROGRESS"); } else if(maxNumberOfRunningProcesses <= 0) { numberOfRunningProcesses++; graph.getVertex(vertexIds[i]).setState("IN_PROGRESS"); } } } }
[ "function", "startReadyProcesses", "(", ")", "{", "// Start as many processes as we can!", "//writeToLog(\"INFO\", \"***** maxNumberOfRunningProcesses = \" + maxNumberOfRunningProcesses + \"; numberOfRunningProcesses = \" + numberOfRunningProcesses);", "var", "numVertices", "=", "graph", ".", ...
Starts all processes where associated vertices are READY @private
[ "Starts", "all", "processes", "where", "associated", "vertices", "are", "READY" ]
c0a92d2032415617c2b6f6bd49d00a2c59bfaa41
https://github.com/adplabs/PigeonKeeper/blob/c0a92d2032415617c2b6f6bd49d00a2c59bfaa41/lib/pigeonkeeper.js#L484-L507
48,472
adplabs/PigeonKeeper
lib/pigeonkeeper.js
vertexIdsFromArray
function vertexIdsFromArray(arr) { var numVertices = arr.length; var vertexIds = []; for(var i = 0; i < numVertices; i++) { vertexIds.push(arr[i].id); } return vertexIds; }
javascript
function vertexIdsFromArray(arr) { var numVertices = arr.length; var vertexIds = []; for(var i = 0; i < numVertices; i++) { vertexIds.push(arr[i].id); } return vertexIds; }
[ "function", "vertexIdsFromArray", "(", "arr", ")", "{", "var", "numVertices", "=", "arr", ".", "length", ";", "var", "vertexIds", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numVertices", ";", "i", "++", ")", "{", "vertexI...
Extracts the vertexIDs from a given array of vertices @private @param {Array} arr - Array of vertices @returns {Array}
[ "Extracts", "the", "vertexIDs", "from", "a", "given", "array", "of", "vertices" ]
c0a92d2032415617c2b6f6bd49d00a2c59bfaa41
https://github.com/adplabs/PigeonKeeper/blob/c0a92d2032415617c2b6f6bd49d00a2c59bfaa41/lib/pigeonkeeper.js#L516-L527
48,473
adplabs/PigeonKeeper
lib/pigeonkeeper.js
writeToLog
function writeToLog(level, msg) { var displayPrefix = "PK-" + pkGuid + ": "; if(loggingMechanism && logUserObject) { loggingMechanism.addLog(level, displayPrefix + msg, logUserObject); } else { console.log(displayPrefix + msg); } }
javascript
function writeToLog(level, msg) { var displayPrefix = "PK-" + pkGuid + ": "; if(loggingMechanism && logUserObject) { loggingMechanism.addLog(level, displayPrefix + msg, logUserObject); } else { console.log(displayPrefix + msg); } }
[ "function", "writeToLog", "(", "level", ",", "msg", ")", "{", "var", "displayPrefix", "=", "\"PK-\"", "+", "pkGuid", "+", "\": \"", ";", "if", "(", "loggingMechanism", "&&", "logUserObject", ")", "{", "loggingMechanism", ".", "addLog", "(", "level", ",", "...
Wrapper around logging mechanism's addLog method @private @param level @param {string} msg
[ "Wrapper", "around", "logging", "mechanism", "s", "addLog", "method" ]
c0a92d2032415617c2b6f6bd49d00a2c59bfaa41
https://github.com/adplabs/PigeonKeeper/blob/c0a92d2032415617c2b6f6bd49d00a2c59bfaa41/lib/pigeonkeeper.js#L536-L547
48,474
ebrelsford/cartocss2json
index.js
zoomCondition
function zoomCondition(zoom) { var zooms = []; for (var i = 0; i <= _carto2['default'].tree.Zoom.maxZoom; i++) { if (zoom & 1 << i) { zooms.push(i); } } var zoomRanges = detectZoomRanges(zooms), value, operator; if (zoomRanges.length > 1) { operator = 'IN'; value = zooms; } else { var range = zoomRanges[0]; if (range[0] === 0) { operator = '<='; value = range[1]; } else if (range[1] === _carto2['default'].tree.Zoom.maxZoom) { operator = '>='; value = range[0]; } else { // We're only handling >=, <= and IN right now operator = 'IN'; value = zooms; } } if (value.length === 0) { return null; } return [{ operator: operator, type: 'zoom', value: value }]; }
javascript
function zoomCondition(zoom) { var zooms = []; for (var i = 0; i <= _carto2['default'].tree.Zoom.maxZoom; i++) { if (zoom & 1 << i) { zooms.push(i); } } var zoomRanges = detectZoomRanges(zooms), value, operator; if (zoomRanges.length > 1) { operator = 'IN'; value = zooms; } else { var range = zoomRanges[0]; if (range[0] === 0) { operator = '<='; value = range[1]; } else if (range[1] === _carto2['default'].tree.Zoom.maxZoom) { operator = '>='; value = range[0]; } else { // We're only handling >=, <= and IN right now operator = 'IN'; value = zooms; } } if (value.length === 0) { return null; } return [{ operator: operator, type: 'zoom', value: value }]; }
[ "function", "zoomCondition", "(", "zoom", ")", "{", "var", "zooms", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<=", "_carto2", "[", "'default'", "]", ".", "tree", ".", "Zoom", ".", "maxZoom", ";", "i", "++", ")", "{", "if"...
Create a zoom condition given a zoom integer
[ "Create", "a", "zoom", "condition", "given", "a", "zoom", "integer" ]
4c1d47ce55da7cac97666439579781dd4d21b802
https://github.com/ebrelsford/cartocss2json/blob/4c1d47ce55da7cac97666439579781dd4d21b802/index.js#L169-L206
48,475
ebrelsford/cartocss2json
index.js
detectZoomRanges
function detectZoomRanges(zooms) { var ranges = []; var currentRange = []; for (var i = 0, z = zooms[0]; i <= zooms.length; i++, z = zooms[i]) { if (currentRange.length < 2) { currentRange.push(z); continue; } if (currentRange.length === 2) { if (z === currentRange[1] + 1) { currentRange[1] = z; } else { ranges.push(currentRange); currentRange = []; } } } if (currentRange.length > 0) { ranges.push(currentRange); } return ranges; }
javascript
function detectZoomRanges(zooms) { var ranges = []; var currentRange = []; for (var i = 0, z = zooms[0]; i <= zooms.length; i++, z = zooms[i]) { if (currentRange.length < 2) { currentRange.push(z); continue; } if (currentRange.length === 2) { if (z === currentRange[1] + 1) { currentRange[1] = z; } else { ranges.push(currentRange); currentRange = []; } } } if (currentRange.length > 0) { ranges.push(currentRange); } return ranges; }
[ "function", "detectZoomRanges", "(", "zooms", ")", "{", "var", "ranges", "=", "[", "]", ";", "var", "currentRange", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "z", "=", "zooms", "[", "0", "]", ";", "i", "<=", "zooms", ".", "leng...
Find zoom ranges in a set of zooms
[ "Find", "zoom", "ranges", "in", "a", "set", "of", "zooms" ]
4c1d47ce55da7cac97666439579781dd4d21b802
https://github.com/ebrelsford/cartocss2json/blob/4c1d47ce55da7cac97666439579781dd4d21b802/index.js#L211-L232
48,476
joneit/filter-tree
js/FilterTree.js
onchange
function onchange(evt) { // called in context var ctrl = evt.target; if (ctrl.parentElement === this.el) { if (ctrl.value === 'subexp') { this.children.push(new FilterTree({ parent: this })); } else { this.add({ state: { editor: ctrl.value }, focus: true }); } ctrl.selectedIndex = 0; } }
javascript
function onchange(evt) { // called in context var ctrl = evt.target; if (ctrl.parentElement === this.el) { if (ctrl.value === 'subexp') { this.children.push(new FilterTree({ parent: this })); } else { this.add({ state: { editor: ctrl.value }, focus: true }); } ctrl.selectedIndex = 0; } }
[ "function", "onchange", "(", "evt", ")", "{", "// called in context", "var", "ctrl", "=", "evt", ".", "target", ";", "if", "(", "ctrl", ".", "parentElement", "===", "this", ".", "el", ")", "{", "if", "(", "ctrl", ".", "value", "===", "'subexp'", ")", ...
Some event handlers bound to FilterTree object
[ "Some", "event", "handlers", "bound", "to", "FilterTree", "object" ]
c070a4045fced3e4ab20ed2e0c706c9a5fd07d1e
https://github.com/joneit/filter-tree/blob/c070a4045fced3e4ab20ed2e0c706c9a5fd07d1e/js/FilterTree.js#L463-L478
48,477
ev3-js/ev3-client
lib/move.js
move
function move (leftPort, rightPort) { leftPort = leftPort || 'b' rightPort = rightPort || 'c' var write = writeAction('motors_write', [leftPort, rightPort]) /** * Run motors forever * @param {Number} speed speed of motor * @param {Object} opts object of optional params */ function * forever (speed, turn, opts) { speed = speed || motorDefaults.speed var speeds = turnToSpeeds(turn, speed) yield write('run-forever', { left: { 'speed_sp': speeds.left.toString() }, right: { 'speed_sp': speeds.right.toString() } }) } /** * Run drive motors for a number of degrees * @param {Number} degrees degrees to turn motor * @param {Number} speed speed at which to turn motors * @param {Number} turn turn direction */ function * degrees (deg, speed, turn) { speed = speed || motorDefaults.speed var opts = turnToDegrees(turn, speed, deg) yield * writeAndWait('run-to-rel-pos', { left: { 'position_sp': opts.left.degrees.toString(), 'speed_sp': opts.left.speed.toString() }, right: { 'position_sp': opts.right.degrees.toString(), 'speed_sp': opts.right.speed.toString() } }) } /** * Run drive motors for a number of rotations * @param {Number} rotations number of rotations to turn the motor * @param {Number} speed speed at which to turn motors * @param {Number} turn turn direction */ function * rotations (rots, speed, turn) { speed = speed || motorDefaults.speed yield * this.degrees(Math.round(rots * 360), speed, turn) } /** * Run drive motors for a specified amount of time * @param {Number} time time to run the motors for (in milliseconds) * @param {Number} speed speed at which to turn motors * @param {Number} turn turn direction */ function * timed (time, speed, turn) { speed = speed || motorDefaults.speed var speeds = turnToSpeeds(turn, speed) yield * writeAndWait('run-timed', { left: { 'time_sp': time.toString(), 'speed_sp': speeds.left.toString() }, right: { 'time_sp': time.toString(), 'speed_sp': speeds.right.toString() } }) } /** * Stops motors */ function * stop () { yield write('stop', {left: {}, right: {}}) } /** * Write and hold execution until the motors are done moving * @param {string} command move command * @param {object} opts move options */ function * writeAndWait (command, opts) { var ran = false yield write(command, opts) while (true) { var devices = yield * read() if (devices.motor(leftPort) === 'running' || devices.motor(rightPort) === 'running') { ran = true } if (devices.motor(leftPort) === '' && devices.motor(rightPort) === '' && ran) { break } } } return { forever: forever, degrees: degrees, rotations: rotations, timed: timed, stop: stop } }
javascript
function move (leftPort, rightPort) { leftPort = leftPort || 'b' rightPort = rightPort || 'c' var write = writeAction('motors_write', [leftPort, rightPort]) /** * Run motors forever * @param {Number} speed speed of motor * @param {Object} opts object of optional params */ function * forever (speed, turn, opts) { speed = speed || motorDefaults.speed var speeds = turnToSpeeds(turn, speed) yield write('run-forever', { left: { 'speed_sp': speeds.left.toString() }, right: { 'speed_sp': speeds.right.toString() } }) } /** * Run drive motors for a number of degrees * @param {Number} degrees degrees to turn motor * @param {Number} speed speed at which to turn motors * @param {Number} turn turn direction */ function * degrees (deg, speed, turn) { speed = speed || motorDefaults.speed var opts = turnToDegrees(turn, speed, deg) yield * writeAndWait('run-to-rel-pos', { left: { 'position_sp': opts.left.degrees.toString(), 'speed_sp': opts.left.speed.toString() }, right: { 'position_sp': opts.right.degrees.toString(), 'speed_sp': opts.right.speed.toString() } }) } /** * Run drive motors for a number of rotations * @param {Number} rotations number of rotations to turn the motor * @param {Number} speed speed at which to turn motors * @param {Number} turn turn direction */ function * rotations (rots, speed, turn) { speed = speed || motorDefaults.speed yield * this.degrees(Math.round(rots * 360), speed, turn) } /** * Run drive motors for a specified amount of time * @param {Number} time time to run the motors for (in milliseconds) * @param {Number} speed speed at which to turn motors * @param {Number} turn turn direction */ function * timed (time, speed, turn) { speed = speed || motorDefaults.speed var speeds = turnToSpeeds(turn, speed) yield * writeAndWait('run-timed', { left: { 'time_sp': time.toString(), 'speed_sp': speeds.left.toString() }, right: { 'time_sp': time.toString(), 'speed_sp': speeds.right.toString() } }) } /** * Stops motors */ function * stop () { yield write('stop', {left: {}, right: {}}) } /** * Write and hold execution until the motors are done moving * @param {string} command move command * @param {object} opts move options */ function * writeAndWait (command, opts) { var ran = false yield write(command, opts) while (true) { var devices = yield * read() if (devices.motor(leftPort) === 'running' || devices.motor(rightPort) === 'running') { ran = true } if (devices.motor(leftPort) === '' && devices.motor(rightPort) === '' && ran) { break } } } return { forever: forever, degrees: degrees, rotations: rotations, timed: timed, stop: stop } }
[ "function", "move", "(", "leftPort", ",", "rightPort", ")", "{", "leftPort", "=", "leftPort", "||", "'b'", "rightPort", "=", "rightPort", "||", "'c'", "var", "write", "=", "writeAction", "(", "'motors_write'", ",", "[", "leftPort", ",", "rightPort", "]", "...
Set up drive motors and returns functions to control them. @param {string} leftPort port that the left motor is connected to @param {string} rightPort port that the right motor is connected to @return {object} steering functions
[ "Set", "up", "drive", "motors", "and", "returns", "functions", "to", "control", "them", "." ]
e63dad977a77b6d2ecc7b81ebf288cc595d76771
https://github.com/ev3-js/ev3-client/blob/e63dad977a77b6d2ecc7b81ebf288cc595d76771/lib/move.js#L32-L142
48,478
ev3-js/ev3-client
lib/move.js
turnToSpeeds
function turnToSpeeds (turn, speed) { turn = Math.max(Math.min(turn, 100), -100) var reducedSpeed = otherSpeed(turn, speed) reducedSpeed = percentToSpeed(reducedSpeed) speed = percentToSpeed(speed) return { left: turn < 0 ? reducedSpeed : speed, right: turn > 0 ? reducedSpeed : speed } }
javascript
function turnToSpeeds (turn, speed) { turn = Math.max(Math.min(turn, 100), -100) var reducedSpeed = otherSpeed(turn, speed) reducedSpeed = percentToSpeed(reducedSpeed) speed = percentToSpeed(speed) return { left: turn < 0 ? reducedSpeed : speed, right: turn > 0 ? reducedSpeed : speed } }
[ "function", "turnToSpeeds", "(", "turn", ",", "speed", ")", "{", "turn", "=", "Math", ".", "max", "(", "Math", ".", "min", "(", "turn", ",", "100", ")", ",", "-", "100", ")", "var", "reducedSpeed", "=", "otherSpeed", "(", "turn", ",", "speed", ")",...
Convert turn in to left and right speeds @param {Number} turn -100 to 100 @param {Number} speed @return {Object}
[ "Convert", "turn", "in", "to", "left", "and", "right", "speeds" ]
e63dad977a77b6d2ecc7b81ebf288cc595d76771
https://github.com/ev3-js/ev3-client/blob/e63dad977a77b6d2ecc7b81ebf288cc595d76771/lib/move.js#L150-L161
48,479
ev3-js/ev3-client
lib/move.js
turnToDegrees
function turnToDegrees (turn, speed, degrees) { turn = Math.max(Math.min(turn, 100), -100) var opts = turnToSpeeds(turn, speed) opts.left = { speed: opts.left } opts.right = { speed: opts.right } var reducedSpeed = otherSpeed(turn, speed) var reducedDegrees = Math.round((reducedSpeed / speed) * degrees) opts.left.degrees = turn < 0 ? reducedDegrees : degrees opts.right.degrees = turn > 0 ? reducedDegrees : degrees return opts }
javascript
function turnToDegrees (turn, speed, degrees) { turn = Math.max(Math.min(turn, 100), -100) var opts = turnToSpeeds(turn, speed) opts.left = { speed: opts.left } opts.right = { speed: opts.right } var reducedSpeed = otherSpeed(turn, speed) var reducedDegrees = Math.round((reducedSpeed / speed) * degrees) opts.left.degrees = turn < 0 ? reducedDegrees : degrees opts.right.degrees = turn > 0 ? reducedDegrees : degrees return opts }
[ "function", "turnToDegrees", "(", "turn", ",", "speed", ",", "degrees", ")", "{", "turn", "=", "Math", ".", "max", "(", "Math", ".", "min", "(", "turn", ",", "100", ")", ",", "-", "100", ")", "var", "opts", "=", "turnToSpeeds", "(", "turn", ",", ...
Params for degrees based on turn @param {Number} turn @param {Number} speed @param {Number} degrees @return {Object} opts object of degrees and speed for each motor
[ "Params", "for", "degrees", "based", "on", "turn" ]
e63dad977a77b6d2ecc7b81ebf288cc595d76771
https://github.com/ev3-js/ev3-client/blob/e63dad977a77b6d2ecc7b81ebf288cc595d76771/lib/move.js#L170-L184
48,480
overlookmotel/lock-queue
lib/index.js
joinQueue
function joinQueue(fn, ctx, exclusive) { // Promisify `fn` fn = promisify(fn, 0); // Add into queue var deferred = defer(); this.queue.push({fn: fn, ctx: ctx, deferred: deferred, exclusive: exclusive}); // Run queue runQueue.call(this); // Return deferred promise return deferred.promise; }
javascript
function joinQueue(fn, ctx, exclusive) { // Promisify `fn` fn = promisify(fn, 0); // Add into queue var deferred = defer(); this.queue.push({fn: fn, ctx: ctx, deferred: deferred, exclusive: exclusive}); // Run queue runQueue.call(this); // Return deferred promise return deferred.promise; }
[ "function", "joinQueue", "(", "fn", ",", "ctx", ",", "exclusive", ")", "{", "// Promisify `fn`", "fn", "=", "promisify", "(", "fn", ",", "0", ")", ";", "// Add into queue", "var", "deferred", "=", "defer", "(", ")", ";", "this", ".", "queue", ".", "pus...
Add process to the queue and run queue @param {Function} fn - Function to queue @param {*} [ctx] - `this` context to run function with @param {boolean} - `true` if function requires an exclusive lock @returns {Promise} - Promise which resolves/rejects with eventual outcome of `fn()`
[ "Add", "process", "to", "the", "queue", "and", "run", "queue" ]
1d0eed62b63f49b25d1648f5d7cad02602989daf
https://github.com/overlookmotel/lock-queue/blob/1d0eed62b63f49b25d1648f5d7cad02602989daf/lib/index.js#L74-L87
48,481
overlookmotel/lock-queue
lib/index.js
runNext
function runNext() { if (this.locked) return false; var item = this.queue[0]; if (!item) return false; if (item.exclusive) { if (this.running) return false; this.locked = true; } this.queue.shift(); this.running++; var self = this; item.fn.call(item.ctx).then(function(res) { runDone.call(self, item, true, res); }, function(err) { runDone.call(self, item, false, err); }); return true; }
javascript
function runNext() { if (this.locked) return false; var item = this.queue[0]; if (!item) return false; if (item.exclusive) { if (this.running) return false; this.locked = true; } this.queue.shift(); this.running++; var self = this; item.fn.call(item.ctx).then(function(res) { runDone.call(self, item, true, res); }, function(err) { runDone.call(self, item, false, err); }); return true; }
[ "function", "runNext", "(", ")", "{", "if", "(", "this", ".", "locked", ")", "return", "false", ";", "var", "item", "=", "this", ".", "queue", "[", "0", "]", ";", "if", "(", "!", "item", ")", "return", "false", ";", "if", "(", "item", ".", "exc...
Run next item in queue @returns {boolean} - `true` if was able to run an item, `false` if not
[ "Run", "next", "item", "in", "queue" ]
1d0eed62b63f49b25d1648f5d7cad02602989daf
https://github.com/overlookmotel/lock-queue/blob/1d0eed62b63f49b25d1648f5d7cad02602989daf/lib/index.js#L108-L131
48,482
overlookmotel/lock-queue
lib/index.js
runDone
function runDone(item, resolved, res) { // Adjust state of lock this.running--; if (this.locked) this.locked = false; // Resolve/reject promise item.deferred[resolved ? 'resolve' : 'reject'](res); // Run queue again runQueue.call(this); }
javascript
function runDone(item, resolved, res) { // Adjust state of lock this.running--; if (this.locked) this.locked = false; // Resolve/reject promise item.deferred[resolved ? 'resolve' : 'reject'](res); // Run queue again runQueue.call(this); }
[ "function", "runDone", "(", "item", ",", "resolved", ",", "res", ")", "{", "// Adjust state of lock", "this", ".", "running", "--", ";", "if", "(", "this", ".", "locked", ")", "this", ".", "locked", "=", "false", ";", "// Resolve/reject promise", "item", "...
Run complete. Update state, resolve deferred promise, and run queue again. @param {Object} - Queue item @param {boolean} - `true` if function resolved, `false` if rejected @param {*} - Result of function (resolve value or reject reason) @returns {undefined}
[ "Run", "complete", ".", "Update", "state", "resolve", "deferred", "promise", "and", "run", "queue", "again", "." ]
1d0eed62b63f49b25d1648f5d7cad02602989daf
https://github.com/overlookmotel/lock-queue/blob/1d0eed62b63f49b25d1648f5d7cad02602989daf/lib/index.js#L141-L151
48,483
anvaka/circle-enclose
index.js
encloseN
function encloseN(L, B) { var circle, l0 = null, l1 = L.head, l2, p1; switch (B.length) { case 1: circle = enclose1(B[0]); break; case 2: circle = enclose2(B[0], B[1]); break; case 3: circle = enclose3(B[0], B[1], B[2]); break; } while (l1) { p1 = l1._, l2 = l1.next; if (!circle || !encloses(circle, p1)) { // Temporarily truncate L before l1. if (l0) L.tail = l0, l0.next = null; else L.head = L.tail = null; B.push(p1); circle = encloseN(L, B); // Note: reorders L! B.pop(); // Move l1 to the front of L and reconnect the truncated list L. if (L.head) l1.next = L.head, L.head = l1; else l1.next = null, L.head = L.tail = l1; l0 = L.tail, l0.next = l2; } else { l0 = l1; } l1 = l2; } L.tail = l0; return circle; }
javascript
function encloseN(L, B) { var circle, l0 = null, l1 = L.head, l2, p1; switch (B.length) { case 1: circle = enclose1(B[0]); break; case 2: circle = enclose2(B[0], B[1]); break; case 3: circle = enclose3(B[0], B[1], B[2]); break; } while (l1) { p1 = l1._, l2 = l1.next; if (!circle || !encloses(circle, p1)) { // Temporarily truncate L before l1. if (l0) L.tail = l0, l0.next = null; else L.head = L.tail = null; B.push(p1); circle = encloseN(L, B); // Note: reorders L! B.pop(); // Move l1 to the front of L and reconnect the truncated list L. if (L.head) l1.next = L.head, L.head = l1; else l1.next = null, L.head = L.tail = l1; l0 = L.tail, l0.next = l2; } else { l0 = l1; } l1 = l2; } L.tail = l0; return circle; }
[ "function", "encloseN", "(", "L", ",", "B", ")", "{", "var", "circle", ",", "l0", "=", "null", ",", "l1", "=", "L", ".", "head", ",", "l2", ",", "p1", ";", "switch", "(", "B", ".", "length", ")", "{", "case", "1", ":", "circle", "=", "enclose...
Returns the smallest circle that contains circles L and intersects circles B.
[ "Returns", "the", "smallest", "circle", "that", "contains", "circles", "L", "and", "intersects", "circles", "B", "." ]
f411a81cdbc5964daaa30a81e3d96becca804248
https://github.com/anvaka/circle-enclose/blob/f411a81cdbc5964daaa30a81e3d96becca804248/index.js#L57-L95
48,484
yoshuawuyts/koa-watchify
index.js
kw
function kw(bundler) { assert.equal(typeof bundler, 'object') const handler = thenify(wreq(bundler)) // Koa middleware. // @param {Function} next // @return {Promise} return function *watchifyRequest(next) { const ctx = this return yield handler(this.req, this.res) .then(success) .catch(failure) function success(res) { ctx.response.body = res } function failure(err) { ctx.throw(err) } } }
javascript
function kw(bundler) { assert.equal(typeof bundler, 'object') const handler = thenify(wreq(bundler)) // Koa middleware. // @param {Function} next // @return {Promise} return function *watchifyRequest(next) { const ctx = this return yield handler(this.req, this.res) .then(success) .catch(failure) function success(res) { ctx.response.body = res } function failure(err) { ctx.throw(err) } } }
[ "function", "kw", "(", "bundler", ")", "{", "assert", ".", "equal", "(", "typeof", "bundler", ",", "'object'", ")", "const", "handler", "=", "thenify", "(", "wreq", "(", "bundler", ")", ")", "// Koa middleware.", "// @param {Function} next", "// @return {Promise...
Wrap `watchify-request` in koa middleware. @param {Object} bundler @return {Function*}
[ "Wrap", "watchify", "-", "request", "in", "koa", "middleware", "." ]
ee0b62723822465881e8558f5011b22ef501a79e
https://github.com/yoshuawuyts/koa-watchify/blob/ee0b62723822465881e8558f5011b22ef501a79e/index.js#L10-L32
48,485
deanlandolt/bytewise-core
index.js
serialize
function serialize(type, source, options) { var codec = type.codec if (!codec) return postEncode(new Buffer([ type.byte ]), options) var buffer = codec.encode(source, bytewise) if (options && options.nested && codec.escape) buffer = codec.escape(buffer) var hint = typeof codec.length === 'number' ? (codec.length + 1) : void 0 var buffers = [ new Buffer([ type.byte ]), buffer ] return postEncode(Buffer.concat(buffers, hint), options) }
javascript
function serialize(type, source, options) { var codec = type.codec if (!codec) return postEncode(new Buffer([ type.byte ]), options) var buffer = codec.encode(source, bytewise) if (options && options.nested && codec.escape) buffer = codec.escape(buffer) var hint = typeof codec.length === 'number' ? (codec.length + 1) : void 0 var buffers = [ new Buffer([ type.byte ]), buffer ] return postEncode(Buffer.concat(buffers, hint), options) }
[ "function", "serialize", "(", "type", ",", "source", ",", "options", ")", "{", "var", "codec", "=", "type", ".", "codec", "if", "(", "!", "codec", ")", "return", "postEncode", "(", "new", "Buffer", "(", "[", "type", ".", "byte", "]", ")", ",", "opt...
generate a buffer with type's byte prefix from source value
[ "generate", "a", "buffer", "with", "type", "s", "byte", "prefix", "from", "source", "value" ]
293f2eb2623903baf0fc02fd81a770f06d62c8de
https://github.com/deanlandolt/bytewise-core/blob/293f2eb2623903baf0fc02fd81a770f06d62c8de/index.js#L18-L31
48,486
deanlandolt/bytewise-core
index.js
postEncode
function postEncode(encoded, options) { if (options === null) return encoded return bytewise.postEncode(encoded, options) }
javascript
function postEncode(encoded, options) { if (options === null) return encoded return bytewise.postEncode(encoded, options) }
[ "function", "postEncode", "(", "encoded", ",", "options", ")", "{", "if", "(", "options", "===", "null", ")", "return", "encoded", "return", "bytewise", ".", "postEncode", "(", "encoded", ",", "options", ")", "}" ]
process top level
[ "process", "top", "level" ]
293f2eb2623903baf0fc02fd81a770f06d62c8de
https://github.com/deanlandolt/bytewise-core/blob/293f2eb2623903baf0fc02fd81a770f06d62c8de/index.js#L106-L111
48,487
joneit/filter-tree
js/FilterLeaf.js
cleanUpAndMoveOn
function cleanUpAndMoveOn(evt) { var el = evt.target; // remove `error` CSS class, which may have been added by `FilterLeaf.prototype.invalid` el.classList.remove('filter-tree-error'); // set or remove 'warning' CSS class, as per el.value FilterNode.setWarningClass(el); if (el === this.view.column) { // rebuild operator list according to selected column name or type, restoring selected item makeOpMenu.call(this, el.value); } if (el.value) { // find next sibling control, if any if (!el.multiple) { while ((el = el.nextElementSibling) && (!('name' in el) || el.value.trim() !== '')); // eslint-disable-line curly } // and click in it (opens select list) if (el && el.value.trim() === '') { el.value = ''; // rid of any white space FilterNode.clickIn(el); } } // forward the event to the application's event handler if (this.eventHandler) { this.eventHandler(evt); } }
javascript
function cleanUpAndMoveOn(evt) { var el = evt.target; // remove `error` CSS class, which may have been added by `FilterLeaf.prototype.invalid` el.classList.remove('filter-tree-error'); // set or remove 'warning' CSS class, as per el.value FilterNode.setWarningClass(el); if (el === this.view.column) { // rebuild operator list according to selected column name or type, restoring selected item makeOpMenu.call(this, el.value); } if (el.value) { // find next sibling control, if any if (!el.multiple) { while ((el = el.nextElementSibling) && (!('name' in el) || el.value.trim() !== '')); // eslint-disable-line curly } // and click in it (opens select list) if (el && el.value.trim() === '') { el.value = ''; // rid of any white space FilterNode.clickIn(el); } } // forward the event to the application's event handler if (this.eventHandler) { this.eventHandler(evt); } }
[ "function", "cleanUpAndMoveOn", "(", "evt", ")", "{", "var", "el", "=", "evt", ".", "target", ";", "// remove `error` CSS class, which may have been added by `FilterLeaf.prototype.invalid`", "el", ".", "classList", ".", "remove", "(", "'filter-tree-error'", ")", ";", "/...
`change` event handler for all form controls. Rebuilds the operator drop-down as needed. Removes error CSS class from control. Adds warning CSS class from control if blank; removes if not blank. Adds warning CSS class from control if blank; removes if not blank. Moves focus to next non-blank sibling control. @this {FilterLeaf}
[ "change", "event", "handler", "for", "all", "form", "controls", ".", "Rebuilds", "the", "operator", "drop", "-", "down", "as", "needed", ".", "Removes", "error", "CSS", "class", "from", "control", ".", "Adds", "warning", "CSS", "class", "from", "control", ...
c070a4045fced3e4ab20ed2e0c706c9a5fd07d1e
https://github.com/joneit/filter-tree/blob/c070a4045fced3e4ab20ed2e0c706c9a5fd07d1e/js/FilterLeaf.js#L412-L443
48,488
Kurento/kurento-module-crowddetector-js
lib/complexTypes/RegionOfInterest.js
RegionOfInterest
function RegionOfInterest(regionOfInterestDict){ if(!(this instanceof RegionOfInterest)) return new RegionOfInterest(regionOfInterestDict) regionOfInterestDict = regionOfInterestDict || {} // Check regionOfInterestDict has the required fields // // checkType('RelativePoint', 'regionOfInterestDict.points', regionOfInterestDict.points, {isArray: true, required: true}); // // checkType('RegionOfInterestConfig', 'regionOfInterestDict.regionOfInterestConfig', regionOfInterestDict.regionOfInterestConfig, {required: true}); // // checkType('String', 'regionOfInterestDict.id', regionOfInterestDict.id, {required: true}); // // Init parent class RegionOfInterest.super_.call(this, regionOfInterestDict) // Set object properties Object.defineProperties(this, { points: { writable: true, enumerable: true, value: regionOfInterestDict.points }, regionOfInterestConfig: { writable: true, enumerable: true, value: regionOfInterestDict.regionOfInterestConfig }, id: { writable: true, enumerable: true, value: regionOfInterestDict.id } }) }
javascript
function RegionOfInterest(regionOfInterestDict){ if(!(this instanceof RegionOfInterest)) return new RegionOfInterest(regionOfInterestDict) regionOfInterestDict = regionOfInterestDict || {} // Check regionOfInterestDict has the required fields // // checkType('RelativePoint', 'regionOfInterestDict.points', regionOfInterestDict.points, {isArray: true, required: true}); // // checkType('RegionOfInterestConfig', 'regionOfInterestDict.regionOfInterestConfig', regionOfInterestDict.regionOfInterestConfig, {required: true}); // // checkType('String', 'regionOfInterestDict.id', regionOfInterestDict.id, {required: true}); // // Init parent class RegionOfInterest.super_.call(this, regionOfInterestDict) // Set object properties Object.defineProperties(this, { points: { writable: true, enumerable: true, value: regionOfInterestDict.points }, regionOfInterestConfig: { writable: true, enumerable: true, value: regionOfInterestDict.regionOfInterestConfig }, id: { writable: true, enumerable: true, value: regionOfInterestDict.id } }) }
[ "function", "RegionOfInterest", "(", "regionOfInterestDict", ")", "{", "if", "(", "!", "(", "this", "instanceof", "RegionOfInterest", ")", ")", "return", "new", "RegionOfInterest", "(", "regionOfInterestDict", ")", "regionOfInterestDict", "=", "regionOfInterestDict", ...
Region of interest for some events in a video processing filter @constructor module:crowddetector/complexTypes.RegionOfInterest @property {module:crowddetector/complexTypes.RelativePoint} points list of points delimiting the region of interest @property {module:crowddetector/complexTypes.RegionOfInterestConfig} regionOfInterestConfig data structure for configuration of CrowdDetector regions of interest @property {external:String} id identifier of the region of interest. The string used for the id must begin with a letter followed by an alphanumeric character included (/-_.:+)
[ "Region", "of", "interest", "for", "some", "events", "in", "a", "video", "processing", "filter" ]
ae0a03c5d6bbc07a23d083fe8916017cb4a63855
https://github.com/Kurento/kurento-module-crowddetector-js/blob/ae0a03c5d6bbc07a23d083fe8916017cb4a63855/lib/complexTypes/RegionOfInterest.js#L42-L78
48,489
wilmoore/brackets2dots.js
index.js
brackets2dots
function brackets2dots(string) { return ({}).toString.call(string) == '[object String]' ? string.replace(REPLACE_BRACKETS, '.$1').replace(LFT_RT_TRIM_DOTS, '') : '' }
javascript
function brackets2dots(string) { return ({}).toString.call(string) == '[object String]' ? string.replace(REPLACE_BRACKETS, '.$1').replace(LFT_RT_TRIM_DOTS, '') : '' }
[ "function", "brackets2dots", "(", "string", ")", "{", "return", "(", "{", "}", ")", ".", "toString", ".", "call", "(", "string", ")", "==", "'[object String]'", "?", "string", ".", "replace", "(", "REPLACE_BRACKETS", ",", "'.$1'", ")", ".", "replace", "(...
Convert string with bracket notation to dot property notation. ### Examples: brackets2dots('group[0].section.a.seat[3]') //=> 'group.0.section.a.seat.3' brackets2dots('[0].section.a.seat[3]') //=> '0.section.a.seat.3' brackets2dots('people[*].age') //=> 'people.*.age' @param {String} string original string @return {String} dot/bracket-notation string
[ "Convert", "string", "with", "bracket", "notation", "to", "dot", "property", "notation", "." ]
83feb1226d0ede5306233721a488a4ac6ae7d8cd
https://github.com/wilmoore/brackets2dots.js/blob/83feb1226d0ede5306233721a488a4ac6ae7d8cd/index.js#L37-L41
48,490
nickdeis/metric-lcs
index.js
metriclcs
function metriclcs(s1, s2) { if (typeof s1 !== "string" || typeof s1 !== "string") return NaN; if (s1 === s2) return 1; const mlen = Math.max(s1.length, s2.length); if (mlen === 0) return 1; return lcsLength(s1, s2) / mlen; }
javascript
function metriclcs(s1, s2) { if (typeof s1 !== "string" || typeof s1 !== "string") return NaN; if (s1 === s2) return 1; const mlen = Math.max(s1.length, s2.length); if (mlen === 0) return 1; return lcsLength(s1, s2) / mlen; }
[ "function", "metriclcs", "(", "s1", ",", "s2", ")", "{", "if", "(", "typeof", "s1", "!==", "\"string\"", "||", "typeof", "s1", "!==", "\"string\"", ")", "return", "NaN", ";", "if", "(", "s1", "===", "s2", ")", "return", "1", ";", "const", "mlen", "...
Returns a number between 1 and 0, where 1 means they are exactly the same and 0 means no common subsequences. If either string is not a string, returns NaN @param {string} s1 @param {string} s2 @returns {number}
[ "Returns", "a", "number", "between", "1", "and", "0", "where", "1", "means", "they", "are", "exactly", "the", "same", "and", "0", "means", "no", "common", "subsequences", ".", "If", "either", "string", "is", "not", "a", "string", "returns", "NaN" ]
bcbfb61d3f8b1297d5ac7e109f0d1b000f3b0658
https://github.com/nickdeis/metric-lcs/blob/bcbfb61d3f8b1297d5ac7e109f0d1b000f3b0658/index.js#L32-L39
48,491
firesideguru/metalsmith-nested
lib/index.js
plugin
function plugin (config) { /** * Init */ // Throw an error if non-object supplied as `options` if (config && (typeof(config) !== 'object' || config instanceof Array)) { throw new Error('metalsmith-nested error: options argument must be an object'); } config = config || {}; // Set options or defaults let opts = { directory: config.directory || 'nested', generated: config.generated || 'layouts', pattern: config.pattern, // match to apply default layout default: config.default, // default layout }; // Throw an error if `nested` directory cannot be found if (!fs.existsSync(opts.directory)) { throw new Error(`metalsmith-nested error: could not find source directory (${opts.directory}) at location (${path.resolve(opts.directory)})`); } /** * Test if file has layout front-matter or matches pattern with default layout * * Code source: * https://github.com/superwolff/metalsmith-layouts/blob/master/lib/helpers/check.js * * @param {Object} files * @param {String} file * @param {String} pattern * @param {String} default * @return {Boolean} */ function check(files, file, pattern, def) { let data = files[file]; // Only process utf8 encoded files (so no binary) if (!utf8(data.contents)) { return false; } // Only process files that match the pattern (if there is a pattern) if (pattern && !match(file, pattern)[0]) { return false; } // Only process files with a specified layout or default template. // Allow the default template to be cancelled by layout: false. return 'layout' in data ? data.layout : def; } /** * Recursively look up specified `layout` in front-matter and combine * contents with previous results on `temp` via `injectContent` method * * @param {Object} tfiles * @param {String} tfile * @param {Object} resolved * @param {String} temp * @return {String} */ function resolveTemplate (tfiles, tfile, resolved, temp = '') { // If parent layout was called by a page directly (vs. through a child layout) // inject already resolved content with child `temp` if (resolved[tfile]) { return injectContent(resolved[tfile], temp); } // Process layout as prescribed else if (tfiles[tfile]) { // Lookup layout in tfiles tree let tdata = tfiles[tfile]; // Combine parent-child on `temp` via `injectContent` temp = injectContent(tdata.contents.toString(), temp); // If this layout has a parent `layout` in front-matter, "lather, rinse, repeat" return tdata.layout ? resolveTemplate(tfiles, tdata.layout, resolved, temp) : temp; } else { return temp; } } /** * Combine parent-child content on `{{{contents}}}` expression * This could be set as an options @property for `plugin` if wanted * * @param {String} parentContent * @param {String} childContent * @return {String} */ function injectContent (parentContent, childContent) { // If no `childContent` return `parentContent` as-is return childContent ? parentContent.replace(/\{\{\{\s*contents\s*\}\}\}/gim, childContent) : parentContent; } // Storage for resolved layouts let resolved = {}; /** * Main plugin function */ return function (files, metalsmith, done) { /** * Create build tree for layout files */ Metal(process.cwd()) .source(opts.directory) .destination(opts.generated) // Access layout build tree `tfiles` from `nested` directory .use(function(tfiles, metal, next) { setImmediate(next); // Process each page file (not layout) for `layout` front-matter or default layout Object.keys(files).forEach(file => { // Test if we use a layout on this page file or skip if (!check(files, file, opts.pattern, opts.default)) { return; // next page } let layout = files[file].layout || opts.default, combined; // Check if already resolved layout before processing if (resolved[layout]) { combined = resolved[layout]; } else { // Process-combine layout files recursively for this page combined = resolveTemplate(tfiles, layout, resolved); // Store combined results for future pages using same layout resolved[layout] = combined; } // Write combined layouts result to layout build tree // *** It's worth noting that until now we are always passing {String} values // converted from layout `tfile.contents` and not a file {Object} or {Buffer} tfiles[layout].contents = new Buffer(combined); }); }) // Write layout build tree to `generated` directory .build(function(err) { if (err) throw err; }); // We must allow time to disc write combined layout files // before processing `metalsmith-layout` plugin setTimeout(done, 100); }; }
javascript
function plugin (config) { /** * Init */ // Throw an error if non-object supplied as `options` if (config && (typeof(config) !== 'object' || config instanceof Array)) { throw new Error('metalsmith-nested error: options argument must be an object'); } config = config || {}; // Set options or defaults let opts = { directory: config.directory || 'nested', generated: config.generated || 'layouts', pattern: config.pattern, // match to apply default layout default: config.default, // default layout }; // Throw an error if `nested` directory cannot be found if (!fs.existsSync(opts.directory)) { throw new Error(`metalsmith-nested error: could not find source directory (${opts.directory}) at location (${path.resolve(opts.directory)})`); } /** * Test if file has layout front-matter or matches pattern with default layout * * Code source: * https://github.com/superwolff/metalsmith-layouts/blob/master/lib/helpers/check.js * * @param {Object} files * @param {String} file * @param {String} pattern * @param {String} default * @return {Boolean} */ function check(files, file, pattern, def) { let data = files[file]; // Only process utf8 encoded files (so no binary) if (!utf8(data.contents)) { return false; } // Only process files that match the pattern (if there is a pattern) if (pattern && !match(file, pattern)[0]) { return false; } // Only process files with a specified layout or default template. // Allow the default template to be cancelled by layout: false. return 'layout' in data ? data.layout : def; } /** * Recursively look up specified `layout` in front-matter and combine * contents with previous results on `temp` via `injectContent` method * * @param {Object} tfiles * @param {String} tfile * @param {Object} resolved * @param {String} temp * @return {String} */ function resolveTemplate (tfiles, tfile, resolved, temp = '') { // If parent layout was called by a page directly (vs. through a child layout) // inject already resolved content with child `temp` if (resolved[tfile]) { return injectContent(resolved[tfile], temp); } // Process layout as prescribed else if (tfiles[tfile]) { // Lookup layout in tfiles tree let tdata = tfiles[tfile]; // Combine parent-child on `temp` via `injectContent` temp = injectContent(tdata.contents.toString(), temp); // If this layout has a parent `layout` in front-matter, "lather, rinse, repeat" return tdata.layout ? resolveTemplate(tfiles, tdata.layout, resolved, temp) : temp; } else { return temp; } } /** * Combine parent-child content on `{{{contents}}}` expression * This could be set as an options @property for `plugin` if wanted * * @param {String} parentContent * @param {String} childContent * @return {String} */ function injectContent (parentContent, childContent) { // If no `childContent` return `parentContent` as-is return childContent ? parentContent.replace(/\{\{\{\s*contents\s*\}\}\}/gim, childContent) : parentContent; } // Storage for resolved layouts let resolved = {}; /** * Main plugin function */ return function (files, metalsmith, done) { /** * Create build tree for layout files */ Metal(process.cwd()) .source(opts.directory) .destination(opts.generated) // Access layout build tree `tfiles` from `nested` directory .use(function(tfiles, metal, next) { setImmediate(next); // Process each page file (not layout) for `layout` front-matter or default layout Object.keys(files).forEach(file => { // Test if we use a layout on this page file or skip if (!check(files, file, opts.pattern, opts.default)) { return; // next page } let layout = files[file].layout || opts.default, combined; // Check if already resolved layout before processing if (resolved[layout]) { combined = resolved[layout]; } else { // Process-combine layout files recursively for this page combined = resolveTemplate(tfiles, layout, resolved); // Store combined results for future pages using same layout resolved[layout] = combined; } // Write combined layouts result to layout build tree // *** It's worth noting that until now we are always passing {String} values // converted from layout `tfile.contents` and not a file {Object} or {Buffer} tfiles[layout].contents = new Buffer(combined); }); }) // Write layout build tree to `generated` directory .build(function(err) { if (err) throw err; }); // We must allow time to disc write combined layout files // before processing `metalsmith-layout` plugin setTimeout(done, 100); }; }
[ "function", "plugin", "(", "config", ")", "{", "/**\n * Init\n */", "// Throw an error if non-object supplied as `options`", "if", "(", "config", "&&", "(", "typeof", "(", "config", ")", "!==", "'object'", "||", "config", "instanceof", "Array", ")", ")", "{", ...
Metalsmith plugin to extend `metalsmith-layouts` to allow nested layouts using the `handlebars` engine @param {Object} options (optional) @property {String} directory (optional) @property {String} generated (optional) @property {String} pattern (optional) @property {String} default (optional) @return {Function}
[ "Metalsmith", "plugin", "to", "extend", "metalsmith", "-", "layouts", "to", "allow", "nested", "layouts", "using", "the", "handlebars", "engine" ]
925bbe0a4f078da1ea791504abd58808621d89d4
https://github.com/firesideguru/metalsmith-nested/blob/925bbe0a4f078da1ea791504abd58808621d89d4/lib/index.js#L37-L208
48,492
firesideguru/metalsmith-nested
lib/index.js
check
function check(files, file, pattern, def) { let data = files[file]; // Only process utf8 encoded files (so no binary) if (!utf8(data.contents)) { return false; } // Only process files that match the pattern (if there is a pattern) if (pattern && !match(file, pattern)[0]) { return false; } // Only process files with a specified layout or default template. // Allow the default template to be cancelled by layout: false. return 'layout' in data ? data.layout : def; }
javascript
function check(files, file, pattern, def) { let data = files[file]; // Only process utf8 encoded files (so no binary) if (!utf8(data.contents)) { return false; } // Only process files that match the pattern (if there is a pattern) if (pattern && !match(file, pattern)[0]) { return false; } // Only process files with a specified layout or default template. // Allow the default template to be cancelled by layout: false. return 'layout' in data ? data.layout : def; }
[ "function", "check", "(", "files", ",", "file", ",", "pattern", ",", "def", ")", "{", "let", "data", "=", "files", "[", "file", "]", ";", "// Only process utf8 encoded files (so no binary)", "if", "(", "!", "utf8", "(", "data", ".", "contents", ")", ")", ...
Test if file has layout front-matter or matches pattern with default layout Code source: https://github.com/superwolff/metalsmith-layouts/blob/master/lib/helpers/check.js @param {Object} files @param {String} file @param {String} pattern @param {String} default @return {Boolean}
[ "Test", "if", "file", "has", "layout", "front", "-", "matter", "or", "matches", "pattern", "with", "default", "layout" ]
925bbe0a4f078da1ea791504abd58808621d89d4
https://github.com/firesideguru/metalsmith-nested/blob/925bbe0a4f078da1ea791504abd58808621d89d4/lib/index.js#L76-L92
48,493
firesideguru/metalsmith-nested
lib/index.js
resolveTemplate
function resolveTemplate (tfiles, tfile, resolved, temp = '') { // If parent layout was called by a page directly (vs. through a child layout) // inject already resolved content with child `temp` if (resolved[tfile]) { return injectContent(resolved[tfile], temp); } // Process layout as prescribed else if (tfiles[tfile]) { // Lookup layout in tfiles tree let tdata = tfiles[tfile]; // Combine parent-child on `temp` via `injectContent` temp = injectContent(tdata.contents.toString(), temp); // If this layout has a parent `layout` in front-matter, "lather, rinse, repeat" return tdata.layout ? resolveTemplate(tfiles, tdata.layout, resolved, temp) : temp; } else { return temp; } }
javascript
function resolveTemplate (tfiles, tfile, resolved, temp = '') { // If parent layout was called by a page directly (vs. through a child layout) // inject already resolved content with child `temp` if (resolved[tfile]) { return injectContent(resolved[tfile], temp); } // Process layout as prescribed else if (tfiles[tfile]) { // Lookup layout in tfiles tree let tdata = tfiles[tfile]; // Combine parent-child on `temp` via `injectContent` temp = injectContent(tdata.contents.toString(), temp); // If this layout has a parent `layout` in front-matter, "lather, rinse, repeat" return tdata.layout ? resolveTemplate(tfiles, tdata.layout, resolved, temp) : temp; } else { return temp; } }
[ "function", "resolveTemplate", "(", "tfiles", ",", "tfile", ",", "resolved", ",", "temp", "=", "''", ")", "{", "// If parent layout was called by a page directly (vs. through a child layout)", "// inject already resolved content with child `temp`", "if", "(", "resolved", "[", ...
Recursively look up specified `layout` in front-matter and combine contents with previous results on `temp` via `injectContent` method @param {Object} tfiles @param {String} tfile @param {Object} resolved @param {String} temp @return {String}
[ "Recursively", "look", "up", "specified", "layout", "in", "front", "-", "matter", "and", "combine", "contents", "with", "previous", "results", "on", "temp", "via", "injectContent", "method" ]
925bbe0a4f078da1ea791504abd58808621d89d4
https://github.com/firesideguru/metalsmith-nested/blob/925bbe0a4f078da1ea791504abd58808621d89d4/lib/index.js#L105-L128
48,494
rtm/upward
src/Str.js
dasherize
function dasherize(str) { return str.replace( /([a-z])([A-Z])/g, (_, let1, let2) => `${let1}-${let2.toLowerCase()}` ); }
javascript
function dasherize(str) { return str.replace( /([a-z])([A-Z])/g, (_, let1, let2) => `${let1}-${let2.toLowerCase()}` ); }
[ "function", "dasherize", "(", "str", ")", "{", "return", "str", ".", "replace", "(", "/", "([a-z])([A-Z])", "/", "g", ",", "(", "_", ",", "let1", ",", "let2", ")", "=>", "`", "${", "let1", "}", "${", "let2", ".", "toLowerCase", "(", ")", "}", "`"...
`myClass` => `my-class`
[ "myClass", "=", ">", "my", "-", "class" ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Str.js#L14-L19
48,495
ev3-js/ev3-client
lib/actions.js
write
function write (type, port) { return createAction(WRITE, writeCommand) /** * function that returns a write actions * @private * @param {string} command * @param {object} opts move object * @return {object} write action object */ function writeCommand (command, opts) { return { type: type, command: command, opts: opts, port: port } } }
javascript
function write (type, port) { return createAction(WRITE, writeCommand) /** * function that returns a write actions * @private * @param {string} command * @param {object} opts move object * @return {object} write action object */ function writeCommand (command, opts) { return { type: type, command: command, opts: opts, port: port } } }
[ "function", "write", "(", "type", ",", "port", ")", "{", "return", "createAction", "(", "WRITE", ",", "writeCommand", ")", "/**\n * function that returns a write actions\n * @private\n * @param {string} command\n * @param {object} opts move object\n * @return {object} ...
curried function to return a write action creator @private @param {string} type The type of write command @param {string|array} port The port or ports that write action corresponds to @return {function} {@link writeCommand}
[ "curried", "function", "to", "return", "a", "write", "action", "creator" ]
e63dad977a77b6d2ecc7b81ebf288cc595d76771
https://github.com/ev3-js/ev3-client/blob/e63dad977a77b6d2ecc7b81ebf288cc595d76771/lib/actions.js#L76-L94
48,496
ev3-js/ev3-client
lib/actions.js
writeCommand
function writeCommand (command, opts) { return { type: type, command: command, opts: opts, port: port } }
javascript
function writeCommand (command, opts) { return { type: type, command: command, opts: opts, port: port } }
[ "function", "writeCommand", "(", "command", ",", "opts", ")", "{", "return", "{", "type", ":", "type", ",", "command", ":", "command", ",", "opts", ":", "opts", ",", "port", ":", "port", "}", "}" ]
function that returns a write actions @private @param {string} command @param {object} opts move object @return {object} write action object
[ "function", "that", "returns", "a", "write", "actions" ]
e63dad977a77b6d2ecc7b81ebf288cc595d76771
https://github.com/ev3-js/ev3-client/blob/e63dad977a77b6d2ecc7b81ebf288cc595d76771/lib/actions.js#L86-L93
48,497
smravi/docco-plus
Gruntfile.js
function(filepath) { // Construct the destination file path. var dest = path.join( grunt.config('copy.coverage.dest'), path.relative(process.cwd(), filepath) ); // Return false if the file exists. return !(grunt.file.exists(dest)); }
javascript
function(filepath) { // Construct the destination file path. var dest = path.join( grunt.config('copy.coverage.dest'), path.relative(process.cwd(), filepath) ); // Return false if the file exists. return !(grunt.file.exists(dest)); }
[ "function", "(", "filepath", ")", "{", "// Construct the destination file path.", "var", "dest", "=", "path", ".", "join", "(", "grunt", ".", "config", "(", "'copy.coverage.dest'", ")", ",", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",",...
Copy if file does not exist.
[ "Copy", "if", "file", "does", "not", "exist", "." ]
16a7b3fe3a5c591ed685ff2d853a0a7ad7ed63fb
https://github.com/smravi/docco-plus/blob/16a7b3fe3a5c591ed685ff2d853a0a7ad7ed63fb/Gruntfile.js#L56-L64
48,498
woaiso/auto-upgrade-npm-version
lib.js
getPackageVersion
function getPackageVersion() { var packageJson = path.join(process.cwd(), 'package.json'), version; try { version = require(packageJson).version; } catch (unused) { throw new Error('Could not load package.json, please make sure it exists'); } if (!semver.valid(version)) { throw new Error('Invalid version number found in package.json, please make sure it is valid'); } return [ semver.major(version), semver.minor(version), semver.patch(version) ].join('.'); }
javascript
function getPackageVersion() { var packageJson = path.join(process.cwd(), 'package.json'), version; try { version = require(packageJson).version; } catch (unused) { throw new Error('Could not load package.json, please make sure it exists'); } if (!semver.valid(version)) { throw new Error('Invalid version number found in package.json, please make sure it is valid'); } return [ semver.major(version), semver.minor(version), semver.patch(version) ].join('.'); }
[ "function", "getPackageVersion", "(", ")", "{", "var", "packageJson", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'package.json'", ")", ",", "version", ";", "try", "{", "version", "=", "require", "(", "packageJson", ")", ".", ...
Get the current version from the package.json @method getPackageVersion @return {String} MAJOR.MINOR version
[ "Get", "the", "current", "version", "from", "the", "package", ".", "json" ]
5bce6e238d8952b03cc30962285b2b91d0fde228
https://github.com/woaiso/auto-upgrade-npm-version/blob/5bce6e238d8952b03cc30962285b2b91d0fde228/lib.js#L13-L26
48,499
woaiso/auto-upgrade-npm-version
lib.js
writePackageVersion
function writePackageVersion(newVersion) { var packageJson = path.join(process.cwd(), 'package.json'), raw = require(packageJson); raw.version = newVersion; fs.writeFileSync(packageJson, JSON.stringify(raw, null, 2)); }
javascript
function writePackageVersion(newVersion) { var packageJson = path.join(process.cwd(), 'package.json'), raw = require(packageJson); raw.version = newVersion; fs.writeFileSync(packageJson, JSON.stringify(raw, null, 2)); }
[ "function", "writePackageVersion", "(", "newVersion", ")", "{", "var", "packageJson", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'package.json'", ")", ",", "raw", "=", "require", "(", "packageJson", ")", ";", "raw", ".", "versi...
Updates the package.json with the new version number @method writePackageVersion @param {String} newVersion New version string MAJOR.MINOR.PATCH
[ "Updates", "the", "package", ".", "json", "with", "the", "new", "version", "number" ]
5bce6e238d8952b03cc30962285b2b91d0fde228
https://github.com/woaiso/auto-upgrade-npm-version/blob/5bce6e238d8952b03cc30962285b2b91d0fde228/lib.js#L44-L51