repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
oskargustafsson/BFF | src/event-emitter.js | function (eventName, argsArray) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (arguments.length > 1 && (!argsArray || argsArray.length === undefined)) {
throw '"argsArray" must have a length property';
}
}
if (!this.__private || !this.__private.listeners) { return; }
var listenersForEvent = this.__private.listeners[eventName];
if (!listenersForEvent) { return; }
for (var i = 0, n = listenersForEvent.length; i < n; ++i) {
listenersForEvent[i].apply(undefined, argsArray);
}
} | javascript | function (eventName, argsArray) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (arguments.length > 1 && (!argsArray || argsArray.length === undefined)) {
throw '"argsArray" must have a length property';
}
}
if (!this.__private || !this.__private.listeners) { return; }
var listenersForEvent = this.__private.listeners[eventName];
if (!listenersForEvent) { return; }
for (var i = 0, n = listenersForEvent.length; i < n; ++i) {
listenersForEvent[i].apply(undefined, argsArray);
}
} | [
"function",
"(",
"eventName",
",",
"argsArray",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
")",
"{",
"if",
"(",
"typeof",
"eventName",
"!==",
"'string'",
")",
"{",
"throw",
"'\"eventName\" argument must be a string'",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
">",
"1",
"&&",
"(",
"!",
"argsArray",
"||",
"argsArray",
".",
"length",
"===",
"undefined",
")",
")",
"{",
"throw",
"'\"argsArray\" must have a length property'",
";",
"}",
"}",
"if",
"(",
"!",
"this",
".",
"__private",
"||",
"!",
"this",
".",
"__private",
".",
"listeners",
")",
"{",
"return",
";",
"}",
"var",
"listenersForEvent",
"=",
"this",
".",
"__private",
".",
"listeners",
"[",
"eventName",
"]",
";",
"if",
"(",
"!",
"listenersForEvent",
")",
"{",
"return",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"listenersForEvent",
".",
"length",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"listenersForEvent",
"[",
"i",
"]",
".",
"apply",
"(",
"undefined",
",",
"argsArray",
")",
";",
"}",
"}"
] | Emit an event. Callbacks will be called with arguments given as an an array in the second argument
@instance
@arg {string} eventName - Identifier string for the event.
@arg {Array} [argsArray] - An array of arguments with which the callbacks will be called. Each item in
the array will be provided as an individual argument to the callbacks. | [
"Emit",
"an",
"event",
".",
"Callbacks",
"will",
"be",
"called",
"with",
"arguments",
"given",
"as",
"an",
"an",
"array",
"in",
"the",
"second",
"argument"
] | 38ebebf3b69f758da78ffb50a97742d33d6d5931 | https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/event-emitter.js#L43-L61 | train |
|
oskargustafsson/BFF | src/event-emitter.js | function (eventName, callback) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (typeof callback !== 'function') {
throw '"callback" argument must be a function';
}
}
this.__private || Object.defineProperty(this, '__private', { writable: true, value: {}, });
var listeners = this.__private.listeners || (this.__private.listeners = {});
var listenersForEvent = listeners[eventName] || (listeners[eventName] = []);
if (RUNTIME_CHECKS && listenersForEvent.indexOf(callback) !== -1) {
throw 'This listener has already been added (event: ' + eventName + ')';
}
listenersForEvent.push(callback);
} | javascript | function (eventName, callback) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (typeof callback !== 'function') {
throw '"callback" argument must be a function';
}
}
this.__private || Object.defineProperty(this, '__private', { writable: true, value: {}, });
var listeners = this.__private.listeners || (this.__private.listeners = {});
var listenersForEvent = listeners[eventName] || (listeners[eventName] = []);
if (RUNTIME_CHECKS && listenersForEvent.indexOf(callback) !== -1) {
throw 'This listener has already been added (event: ' + eventName + ')';
}
listenersForEvent.push(callback);
} | [
"function",
"(",
"eventName",
",",
"callback",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
")",
"{",
"if",
"(",
"typeof",
"eventName",
"!==",
"'string'",
")",
"{",
"throw",
"'\"eventName\" argument must be a string'",
";",
"}",
"if",
"(",
"typeof",
"callback",
"!==",
"'function'",
")",
"{",
"throw",
"'\"callback\" argument must be a function'",
";",
"}",
"}",
"this",
".",
"__private",
"||",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'__private'",
",",
"{",
"writable",
":",
"true",
",",
"value",
":",
"{",
"}",
",",
"}",
")",
";",
"var",
"listeners",
"=",
"this",
".",
"__private",
".",
"listeners",
"||",
"(",
"this",
".",
"__private",
".",
"listeners",
"=",
"{",
"}",
")",
";",
"var",
"listenersForEvent",
"=",
"listeners",
"[",
"eventName",
"]",
"||",
"(",
"listeners",
"[",
"eventName",
"]",
"=",
"[",
"]",
")",
";",
"if",
"(",
"RUNTIME_CHECKS",
"&&",
"listenersForEvent",
".",
"indexOf",
"(",
"callback",
")",
"!==",
"-",
"1",
")",
"{",
"throw",
"'This listener has already been added (event: '",
"+",
"eventName",
"+",
"')'",
";",
"}",
"listenersForEvent",
".",
"push",
"(",
"callback",
")",
";",
"}"
] | Add an event listener function that will be called whenever the given event is emitted. Trying to add the exact same function twice till throw an error, as that is rarely ever the intention and a common source of errors.
@instance
@arg {string} eventName - Identifier string for the event that is to be listened to.
@arg {function} callback - The function that will be called when the event is emitted. | [
"Add",
"an",
"event",
"listener",
"function",
"that",
"will",
"be",
"called",
"whenever",
"the",
"given",
"event",
"is",
"emitted",
".",
"Trying",
"to",
"add",
"the",
"exact",
"same",
"function",
"twice",
"till",
"throw",
"an",
"error",
"as",
"that",
"is",
"rarely",
"ever",
"the",
"intention",
"and",
"a",
"common",
"source",
"of",
"errors",
"."
] | 38ebebf3b69f758da78ffb50a97742d33d6d5931 | https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/event-emitter.js#L69-L88 | train |
|
oskargustafsson/BFF | src/event-emitter.js | function (eventName, callback) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (arguments.length === 2 && typeof callback !== 'function') {
throw '"callback" argument must be a function'; // Catch a common cause of errors
}
}
// No listeners at all? We are done.
if (!this.__private || !this.__private.listeners) { return; }
var listenersForEvent = this.__private.listeners[eventName];
if (!listenersForEvent) { return; } // No listeners for this event? We are done.
if (callback) {
var pos = listenersForEvent.indexOf(callback);
if (pos === -1) { return; }
listenersForEvent.splice(pos, 1);
} else {
listenersForEvent.length = 0;
}
listenersForEvent.length === 0 && (delete this.__private.listeners[eventName]);
} | javascript | function (eventName, callback) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (arguments.length === 2 && typeof callback !== 'function') {
throw '"callback" argument must be a function'; // Catch a common cause of errors
}
}
// No listeners at all? We are done.
if (!this.__private || !this.__private.listeners) { return; }
var listenersForEvent = this.__private.listeners[eventName];
if (!listenersForEvent) { return; } // No listeners for this event? We are done.
if (callback) {
var pos = listenersForEvent.indexOf(callback);
if (pos === -1) { return; }
listenersForEvent.splice(pos, 1);
} else {
listenersForEvent.length = 0;
}
listenersForEvent.length === 0 && (delete this.__private.listeners[eventName]);
} | [
"function",
"(",
"eventName",
",",
"callback",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
")",
"{",
"if",
"(",
"typeof",
"eventName",
"!==",
"'string'",
")",
"{",
"throw",
"'\"eventName\" argument must be a string'",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
"===",
"2",
"&&",
"typeof",
"callback",
"!==",
"'function'",
")",
"{",
"throw",
"'\"callback\" argument must be a function'",
";",
"}",
"}",
"if",
"(",
"!",
"this",
".",
"__private",
"||",
"!",
"this",
".",
"__private",
".",
"listeners",
")",
"{",
"return",
";",
"}",
"var",
"listenersForEvent",
"=",
"this",
".",
"__private",
".",
"listeners",
"[",
"eventName",
"]",
";",
"if",
"(",
"!",
"listenersForEvent",
")",
"{",
"return",
";",
"}",
"if",
"(",
"callback",
")",
"{",
"var",
"pos",
"=",
"listenersForEvent",
".",
"indexOf",
"(",
"callback",
")",
";",
"if",
"(",
"pos",
"===",
"-",
"1",
")",
"{",
"return",
";",
"}",
"listenersForEvent",
".",
"splice",
"(",
"pos",
",",
"1",
")",
";",
"}",
"else",
"{",
"listenersForEvent",
".",
"length",
"=",
"0",
";",
"}",
"listenersForEvent",
".",
"length",
"===",
"0",
"&&",
"(",
"delete",
"this",
".",
"__private",
".",
"listeners",
"[",
"eventName",
"]",
")",
";",
"}"
] | Removes an event listener function. If the function was never a listener, do nothing.
@instance
@arg {string} eventName - Identifier string for the event in question.
@arg {function} [callback] - If not given, all event listeners to the provided eventName will be removed. If given, only the given callback will be removed from the given eventName. | [
"Removes",
"an",
"event",
"listener",
"function",
".",
"If",
"the",
"function",
"was",
"never",
"a",
"listener",
"do",
"nothing",
"."
] | 38ebebf3b69f758da78ffb50a97742d33d6d5931 | https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/event-emitter.js#L96-L120 | train |
|
sofa/sofa-core | src/sofa.util.js | function (collection, callback) {
var index,
iterable = collection,
result = iterable;
if (!iterable) {
return result;
}
if (!sofa.Util.objectTypes[typeof iterable]) {
return result;
}
for (index in iterable) {
if (Object.prototype.hasOwnProperty.call(iterable, index)) {
if (callback(iterable[index], index, collection) === false) {
return result;
}
}
}
return result;
} | javascript | function (collection, callback) {
var index,
iterable = collection,
result = iterable;
if (!iterable) {
return result;
}
if (!sofa.Util.objectTypes[typeof iterable]) {
return result;
}
for (index in iterable) {
if (Object.prototype.hasOwnProperty.call(iterable, index)) {
if (callback(iterable[index], index, collection) === false) {
return result;
}
}
}
return result;
} | [
"function",
"(",
"collection",
",",
"callback",
")",
"{",
"var",
"index",
",",
"iterable",
"=",
"collection",
",",
"result",
"=",
"iterable",
";",
"if",
"(",
"!",
"iterable",
")",
"{",
"return",
"result",
";",
"}",
"if",
"(",
"!",
"sofa",
".",
"Util",
".",
"objectTypes",
"[",
"typeof",
"iterable",
"]",
")",
"{",
"return",
"result",
";",
"}",
"for",
"(",
"index",
"in",
"iterable",
")",
"{",
"if",
"(",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"iterable",
",",
"index",
")",
")",
"{",
"if",
"(",
"callback",
"(",
"iterable",
"[",
"index",
"]",
",",
"index",
",",
"collection",
")",
"===",
"false",
")",
"{",
"return",
"result",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
] | this method is ripped out from lo-dash | [
"this",
"method",
"is",
"ripped",
"out",
"from",
"lo",
"-",
"dash"
] | 654b12bdda24f46e496417beb2d7772a6a50fea1 | https://github.com/sofa/sofa-core/blob/654b12bdda24f46e496417beb2d7772a6a50fea1/src/sofa.util.js#L278-L299 | train |
|
juliostanley/websdk | build/index.js | function(filepath){
filepath = filepath.replace(pathSepExp,'/'); // Use unix paths regardless. Makes these checks easier
if(filepath &&
(
( // If filepath has the jsIncludeDir, but does not include the node_modules directory under them
filepath.match(expressions.jsIncludeDir)
&& !filepath.match(expressions.jsExcludeDir)
)
// Or the filepath has nothing to do with node_modules, app_modules/vendor
|| !filepath.match(expressions.jsAlwaysIncludeDir)
|| filepath.match(/node_modules(\\|\/)@polymer|node_modules(\\|\/)@webcomponents(\\|\/)shadycss/)
)
) {
// console.log('===================================')
// console.log(filepath)
// console.log('### Transpiling: '+filepath);
return true;
}
} | javascript | function(filepath){
filepath = filepath.replace(pathSepExp,'/'); // Use unix paths regardless. Makes these checks easier
if(filepath &&
(
( // If filepath has the jsIncludeDir, but does not include the node_modules directory under them
filepath.match(expressions.jsIncludeDir)
&& !filepath.match(expressions.jsExcludeDir)
)
// Or the filepath has nothing to do with node_modules, app_modules/vendor
|| !filepath.match(expressions.jsAlwaysIncludeDir)
|| filepath.match(/node_modules(\\|\/)@polymer|node_modules(\\|\/)@webcomponents(\\|\/)shadycss/)
)
) {
// console.log('===================================')
// console.log(filepath)
// console.log('### Transpiling: '+filepath);
return true;
}
} | [
"function",
"(",
"filepath",
")",
"{",
"filepath",
"=",
"filepath",
".",
"replace",
"(",
"pathSepExp",
",",
"'/'",
")",
";",
"if",
"(",
"filepath",
"&&",
"(",
"(",
"filepath",
".",
"match",
"(",
"expressions",
".",
"jsIncludeDir",
")",
"&&",
"!",
"filepath",
".",
"match",
"(",
"expressions",
".",
"jsExcludeDir",
")",
")",
"||",
"!",
"filepath",
".",
"match",
"(",
"expressions",
".",
"jsAlwaysIncludeDir",
")",
"||",
"filepath",
".",
"match",
"(",
"/",
"node_modules(\\\\|\\/)@polymer|node_modules(\\\\|\\/)@webcomponents(\\\\|\\/)shadycss",
"/",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"}"
] | jQuery is not needed | [
"jQuery",
"is",
"not",
"needed"
] | 0657c04eb0ceed488be3f67e95f1d1d3b873c869 | https://github.com/juliostanley/websdk/blob/0657c04eb0ceed488be3f67e95f1d1d3b873c869/build/index.js#L76-L94 | train |
|
juliostanley/websdk | build/index.js | function(config, cb){
// This will tell webpack to create a new chunk
rq.ensure(['INDEX_PATH'],function(rq){
let library = rq('INDEX_PATH');
library = library.default || library; // To preven issues between versions
cb(
// Expected to export an initializing function
library(config)
);
},'NAME');
} | javascript | function(config, cb){
// This will tell webpack to create a new chunk
rq.ensure(['INDEX_PATH'],function(rq){
let library = rq('INDEX_PATH');
library = library.default || library; // To preven issues between versions
cb(
// Expected to export an initializing function
library(config)
);
},'NAME');
} | [
"function",
"(",
"config",
",",
"cb",
")",
"{",
"rq",
".",
"ensure",
"(",
"[",
"'INDEX_PATH'",
"]",
",",
"function",
"(",
"rq",
")",
"{",
"let",
"library",
"=",
"rq",
"(",
"'INDEX_PATH'",
")",
";",
"library",
"=",
"library",
".",
"default",
"||",
"library",
";",
"cb",
"(",
"library",
"(",
"config",
")",
")",
";",
"}",
",",
"'NAME'",
")",
";",
"}"
] | Create a common loader | [
"Create",
"a",
"common",
"loader"
] | 0657c04eb0ceed488be3f67e95f1d1d3b873c869 | https://github.com/juliostanley/websdk/blob/0657c04eb0ceed488be3f67e95f1d1d3b873c869/build/index.js#L675-L685 | train |
|
emmetio/stylesheet-formatters | index.js | getFormat | function getFormat(syntax, options) {
let format = syntaxFormat[syntax];
if (typeof format === 'string') {
format = syntaxFormat[format];
}
return Object.assign({}, format, options && options.format);
} | javascript | function getFormat(syntax, options) {
let format = syntaxFormat[syntax];
if (typeof format === 'string') {
format = syntaxFormat[format];
}
return Object.assign({}, format, options && options.format);
} | [
"function",
"getFormat",
"(",
"syntax",
",",
"options",
")",
"{",
"let",
"format",
"=",
"syntaxFormat",
"[",
"syntax",
"]",
";",
"if",
"(",
"typeof",
"format",
"===",
"'string'",
")",
"{",
"format",
"=",
"syntaxFormat",
"[",
"format",
"]",
";",
"}",
"return",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"format",
",",
"options",
"&&",
"options",
".",
"format",
")",
";",
"}"
] | Returns formatter object for given syntax
@param {String} syntax
@param {Object} [options]
@return {Object} Formatter object as defined in `syntaxFormat` | [
"Returns",
"formatter",
"object",
"for",
"given",
"syntax"
] | 1ba9fa2609b8088e7567547990f123106de84b1d | https://github.com/emmetio/stylesheet-formatters/blob/1ba9fa2609b8088e7567547990f123106de84b1d/index.js#L75-L82 | train |
openbiz/openbiz | lib/loaders/RouteLoader.js | function(newRoutes)
{
for(var key in newRoutes)
{
if(routes.hasOwnProperty(key))
{
if(typeof routes[key] == 'Array')
{
routes[key].push(newRoutes[key]);
}
else
{
routes[key] = [routes[key],newRoutes[key]];
}
}
else
{
routes[key] = newRoutes[key];
}
}
} | javascript | function(newRoutes)
{
for(var key in newRoutes)
{
if(routes.hasOwnProperty(key))
{
if(typeof routes[key] == 'Array')
{
routes[key].push(newRoutes[key]);
}
else
{
routes[key] = [routes[key],newRoutes[key]];
}
}
else
{
routes[key] = newRoutes[key];
}
}
} | [
"function",
"(",
"newRoutes",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"newRoutes",
")",
"{",
"if",
"(",
"routes",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"if",
"(",
"typeof",
"routes",
"[",
"key",
"]",
"==",
"'Array'",
")",
"{",
"routes",
"[",
"key",
"]",
".",
"push",
"(",
"newRoutes",
"[",
"key",
"]",
")",
";",
"}",
"else",
"{",
"routes",
"[",
"key",
"]",
"=",
"[",
"routes",
"[",
"key",
"]",
",",
"newRoutes",
"[",
"key",
"]",
"]",
";",
"}",
"}",
"else",
"{",
"routes",
"[",
"key",
"]",
"=",
"newRoutes",
"[",
"key",
"]",
";",
"}",
"}",
"}"
] | define route merge method | [
"define",
"route",
"merge",
"method"
] | 997f1398396683d7ad667b1b360ce74c7c7fcf6f | https://github.com/openbiz/openbiz/blob/997f1398396683d7ad667b1b360ce74c7c7fcf6f/lib/loaders/RouteLoader.js#L10-L30 | train |
|
mikl/node-drupal | lib/user.js | role_permissions | function role_permissions(roles, callback) {
var permissions = [],
fetch = [];
if (roles) {
// TODO: Here we could do with some caching like Drupal does.
roles.forEach(function (name, rid) {
fetch.push(rid);
});
// Get permissions for the rids.
if (fetch) {
db.query("SELECT rid, permission FROM role_permission WHERE rid IN ($1);", [fetch], function (err, rows) {
if (err) {
callback(err, null);
}
if (rows.length > 0) {
rows.forEach(function (row) {
permissions.push(row.permission);
});
}
callback(null, permissions);
});
}
}
} | javascript | function role_permissions(roles, callback) {
var permissions = [],
fetch = [];
if (roles) {
// TODO: Here we could do with some caching like Drupal does.
roles.forEach(function (name, rid) {
fetch.push(rid);
});
// Get permissions for the rids.
if (fetch) {
db.query("SELECT rid, permission FROM role_permission WHERE rid IN ($1);", [fetch], function (err, rows) {
if (err) {
callback(err, null);
}
if (rows.length > 0) {
rows.forEach(function (row) {
permissions.push(row.permission);
});
}
callback(null, permissions);
});
}
}
} | [
"function",
"role_permissions",
"(",
"roles",
",",
"callback",
")",
"{",
"var",
"permissions",
"=",
"[",
"]",
",",
"fetch",
"=",
"[",
"]",
";",
"if",
"(",
"roles",
")",
"{",
"roles",
".",
"forEach",
"(",
"function",
"(",
"name",
",",
"rid",
")",
"{",
"fetch",
".",
"push",
"(",
"rid",
")",
";",
"}",
")",
";",
"if",
"(",
"fetch",
")",
"{",
"db",
".",
"query",
"(",
"\"SELECT rid, permission FROM role_permission WHERE rid IN ($1);\"",
",",
"[",
"fetch",
"]",
",",
"function",
"(",
"err",
",",
"rows",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"null",
")",
";",
"}",
"if",
"(",
"rows",
".",
"length",
">",
"0",
")",
"{",
"rows",
".",
"forEach",
"(",
"function",
"(",
"row",
")",
"{",
"permissions",
".",
"push",
"(",
"row",
".",
"permission",
")",
";",
"}",
")",
";",
"}",
"callback",
"(",
"null",
",",
"permissions",
")",
";",
"}",
")",
";",
"}",
"}",
"}"
] | Get all permissions granted to a set of roles.
Like user_role_permissions() in Drupal core. | [
"Get",
"all",
"permissions",
"granted",
"to",
"a",
"set",
"of",
"roles",
"."
] | 0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd | https://github.com/mikl/node-drupal/blob/0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd/lib/user.js#L67-L94 | train |
mikl/node-drupal | lib/user.js | access | function access(permission, account, callback) {
// User #1 has all privileges:
if (account.uid === 1) {
callback(null, true);
return;
}
// If permissions is already loaded, use them.
if (account.permissions) {
callback(null, account.permissions.indexOf(permission) > -1);
return;
}
role_permissions(account.roles, function (err, permissions) {
if (err) {
callback(err);
return;
}
callback(null, permissions.indexOf(permission) > -1);
});
} | javascript | function access(permission, account, callback) {
// User #1 has all privileges:
if (account.uid === 1) {
callback(null, true);
return;
}
// If permissions is already loaded, use them.
if (account.permissions) {
callback(null, account.permissions.indexOf(permission) > -1);
return;
}
role_permissions(account.roles, function (err, permissions) {
if (err) {
callback(err);
return;
}
callback(null, permissions.indexOf(permission) > -1);
});
} | [
"function",
"access",
"(",
"permission",
",",
"account",
",",
"callback",
")",
"{",
"if",
"(",
"account",
".",
"uid",
"===",
"1",
")",
"{",
"callback",
"(",
"null",
",",
"true",
")",
";",
"return",
";",
"}",
"if",
"(",
"account",
".",
"permissions",
")",
"{",
"callback",
"(",
"null",
",",
"account",
".",
"permissions",
".",
"indexOf",
"(",
"permission",
")",
">",
"-",
"1",
")",
";",
"return",
";",
"}",
"role_permissions",
"(",
"account",
".",
"roles",
",",
"function",
"(",
"err",
",",
"permissions",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"return",
";",
"}",
"callback",
"(",
"null",
",",
"permissions",
".",
"indexOf",
"(",
"permission",
")",
">",
"-",
"1",
")",
";",
"}",
")",
";",
"}"
] | Check if user has a specific permission.
Like user_access() in Drupal core.
Unlike in Drupal, we do not have a global user object, so this
implementation always require the account parameter to be set. | [
"Check",
"if",
"user",
"has",
"a",
"specific",
"permission",
"."
] | 0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd | https://github.com/mikl/node-drupal/blob/0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd/lib/user.js#L104-L125 | train |
mikl/node-drupal | lib/user.js | session_load | function session_load(sid, callback) {
var rows = [];
db.query("SELECT * FROM sessions WHERE sid = $1;", [sid], function (err, rows) {
if (err) {
callback(err, null);
return;
}
if (rows.length > 0) {
callback(null, rows[0]);
}
else {
callback('Session not found', null);
}
});
} | javascript | function session_load(sid, callback) {
var rows = [];
db.query("SELECT * FROM sessions WHERE sid = $1;", [sid], function (err, rows) {
if (err) {
callback(err, null);
return;
}
if (rows.length > 0) {
callback(null, rows[0]);
}
else {
callback('Session not found', null);
}
});
} | [
"function",
"session_load",
"(",
"sid",
",",
"callback",
")",
"{",
"var",
"rows",
"=",
"[",
"]",
";",
"db",
".",
"query",
"(",
"\"SELECT * FROM sessions WHERE sid = $1;\"",
",",
"[",
"sid",
"]",
",",
"function",
"(",
"err",
",",
"rows",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"null",
")",
";",
"return",
";",
"}",
"if",
"(",
"rows",
".",
"length",
">",
"0",
")",
"{",
"callback",
"(",
"null",
",",
"rows",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"'Session not found'",
",",
"null",
")",
";",
"}",
"}",
")",
";",
"}"
] | Load a user session.
This function does not exist in Drupal core, as it uses PHPs rather
complex session system we do not attempt to reconstruct here.
This only works when Drupal uses the (default) database session
backend. Memcache and other session backends not supported. | [
"Load",
"a",
"user",
"session",
"."
] | 0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd | https://github.com/mikl/node-drupal/blob/0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd/lib/user.js#L136-L152 | train |
bholloway/persistent-cache-webpack-plugin | lib/decode.js | decode | function decode(object) {
var result = {};
// enumerable properties
for (var key in object) {
var value = object[key];
// nested object
if (value && (typeof value === 'object')) {
// instance
if (value.$class && value.$props) {
result[value] = assign(new classes.getDefinition(value.$class), decode(value.$props));
}
// plain object
else {
result[value] = decode(value);
}
}
// other
else {
result[value] = value;
}
}
// complete
return result;
} | javascript | function decode(object) {
var result = {};
// enumerable properties
for (var key in object) {
var value = object[key];
// nested object
if (value && (typeof value === 'object')) {
// instance
if (value.$class && value.$props) {
result[value] = assign(new classes.getDefinition(value.$class), decode(value.$props));
}
// plain object
else {
result[value] = decode(value);
}
}
// other
else {
result[value] = value;
}
}
// complete
return result;
} | [
"function",
"decode",
"(",
"object",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"object",
")",
"{",
"var",
"value",
"=",
"object",
"[",
"key",
"]",
";",
"if",
"(",
"value",
"&&",
"(",
"typeof",
"value",
"===",
"'object'",
")",
")",
"{",
"if",
"(",
"value",
".",
"$class",
"&&",
"value",
".",
"$props",
")",
"{",
"result",
"[",
"value",
"]",
"=",
"assign",
"(",
"new",
"classes",
".",
"getDefinition",
"(",
"value",
".",
"$class",
")",
",",
"decode",
"(",
"value",
".",
"$props",
")",
")",
";",
"}",
"else",
"{",
"result",
"[",
"value",
"]",
"=",
"decode",
"(",
"value",
")",
";",
"}",
"}",
"else",
"{",
"result",
"[",
"value",
"]",
"=",
"value",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | Decode the given acyclic object, instantiating using any embedded class information.
@param {object} object The object to decode
@returns {object} An acyclic object with possibly typed members | [
"Decode",
"the",
"given",
"acyclic",
"object",
"instantiating",
"using",
"any",
"embedded",
"class",
"information",
"."
] | bd5aec58b1b38477218dcdc0fb144c6981604fa8 | https://github.com/bholloway/persistent-cache-webpack-plugin/blob/bd5aec58b1b38477218dcdc0fb144c6981604fa8/lib/decode.js#L12-L39 | train |
mikolalysenko/polytope-closest-point | lib/closest_point_nd.js | closestPointnd | function closestPointnd(c, positions, x, result) {
var D = numeric.rep([c.length, c.length], 0.0);
var dvec = numeric.rep([c.length], 0.0);
for(var i=0; i<c.length; ++i) {
var pi = positions[c[i]];
dvec[i] = numeric.dot(pi, x);
for(var j=0; j<c.length; ++j) {
var pj = positions[c[j]];
D[i][j] = D[j][i] = numeric.dot(pi, pj);
}
}
var A = numeric.rep([c.length, c.length+2], 0.0);
var b = numeric.rep([c.length+2], 0.0);
b[0] = 1.0-EPSILON;
b[1] = -(1.0+EPSILON);
for(var i=0; i<c.length; ++i) {
A[i][0] = 1;
A[i][1] = -1
A[i][i+2] = 1;
}
for(var attempts=0; attempts<15; ++attempts) {
var fortran_poop = numeric.solveQP(D, dvec, A, b);
if(fortran_poop.message.length > 0) {
//Quadratic form may be singular, perturb and resolve
for(var i=0; i<c.length; ++i) {
D[i][i] += 1e-8;
}
continue;
} else if(isNaN(fortran_poop.value[0])) {
break;
} else {
//Success!
var solution = fortran_poop.solution;
for(var i=0; i<x.length; ++i) {
result[i] = 0.0;
for(var j=0; j<solution.length; ++j) {
result[i] += solution[j] * positions[c[j]][i];
}
}
return 2.0 * fortran_poop.value[0] + numeric.dot(x,x);
}
}
for(var i=0; i<x.length; ++i) {
result[i] = Number.NaN;
}
return Number.NaN;
} | javascript | function closestPointnd(c, positions, x, result) {
var D = numeric.rep([c.length, c.length], 0.0);
var dvec = numeric.rep([c.length], 0.0);
for(var i=0; i<c.length; ++i) {
var pi = positions[c[i]];
dvec[i] = numeric.dot(pi, x);
for(var j=0; j<c.length; ++j) {
var pj = positions[c[j]];
D[i][j] = D[j][i] = numeric.dot(pi, pj);
}
}
var A = numeric.rep([c.length, c.length+2], 0.0);
var b = numeric.rep([c.length+2], 0.0);
b[0] = 1.0-EPSILON;
b[1] = -(1.0+EPSILON);
for(var i=0; i<c.length; ++i) {
A[i][0] = 1;
A[i][1] = -1
A[i][i+2] = 1;
}
for(var attempts=0; attempts<15; ++attempts) {
var fortran_poop = numeric.solveQP(D, dvec, A, b);
if(fortran_poop.message.length > 0) {
//Quadratic form may be singular, perturb and resolve
for(var i=0; i<c.length; ++i) {
D[i][i] += 1e-8;
}
continue;
} else if(isNaN(fortran_poop.value[0])) {
break;
} else {
//Success!
var solution = fortran_poop.solution;
for(var i=0; i<x.length; ++i) {
result[i] = 0.0;
for(var j=0; j<solution.length; ++j) {
result[i] += solution[j] * positions[c[j]][i];
}
}
return 2.0 * fortran_poop.value[0] + numeric.dot(x,x);
}
}
for(var i=0; i<x.length; ++i) {
result[i] = Number.NaN;
}
return Number.NaN;
} | [
"function",
"closestPointnd",
"(",
"c",
",",
"positions",
",",
"x",
",",
"result",
")",
"{",
"var",
"D",
"=",
"numeric",
".",
"rep",
"(",
"[",
"c",
".",
"length",
",",
"c",
".",
"length",
"]",
",",
"0.0",
")",
";",
"var",
"dvec",
"=",
"numeric",
".",
"rep",
"(",
"[",
"c",
".",
"length",
"]",
",",
"0.0",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"c",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"pi",
"=",
"positions",
"[",
"c",
"[",
"i",
"]",
"]",
";",
"dvec",
"[",
"i",
"]",
"=",
"numeric",
".",
"dot",
"(",
"pi",
",",
"x",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"c",
".",
"length",
";",
"++",
"j",
")",
"{",
"var",
"pj",
"=",
"positions",
"[",
"c",
"[",
"j",
"]",
"]",
";",
"D",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"D",
"[",
"j",
"]",
"[",
"i",
"]",
"=",
"numeric",
".",
"dot",
"(",
"pi",
",",
"pj",
")",
";",
"}",
"}",
"var",
"A",
"=",
"numeric",
".",
"rep",
"(",
"[",
"c",
".",
"length",
",",
"c",
".",
"length",
"+",
"2",
"]",
",",
"0.0",
")",
";",
"var",
"b",
"=",
"numeric",
".",
"rep",
"(",
"[",
"c",
".",
"length",
"+",
"2",
"]",
",",
"0.0",
")",
";",
"b",
"[",
"0",
"]",
"=",
"1.0",
"-",
"EPSILON",
";",
"b",
"[",
"1",
"]",
"=",
"-",
"(",
"1.0",
"+",
"EPSILON",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"c",
".",
"length",
";",
"++",
"i",
")",
"{",
"A",
"[",
"i",
"]",
"[",
"0",
"]",
"=",
"1",
";",
"A",
"[",
"i",
"]",
"[",
"1",
"]",
"=",
"-",
"1",
"A",
"[",
"i",
"]",
"[",
"i",
"+",
"2",
"]",
"=",
"1",
";",
"}",
"for",
"(",
"var",
"attempts",
"=",
"0",
";",
"attempts",
"<",
"15",
";",
"++",
"attempts",
")",
"{",
"var",
"fortran_poop",
"=",
"numeric",
".",
"solveQP",
"(",
"D",
",",
"dvec",
",",
"A",
",",
"b",
")",
";",
"if",
"(",
"fortran_poop",
".",
"message",
".",
"length",
">",
"0",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"c",
".",
"length",
";",
"++",
"i",
")",
"{",
"D",
"[",
"i",
"]",
"[",
"i",
"]",
"+=",
"1e-8",
";",
"}",
"continue",
";",
"}",
"else",
"if",
"(",
"isNaN",
"(",
"fortran_poop",
".",
"value",
"[",
"0",
"]",
")",
")",
"{",
"break",
";",
"}",
"else",
"{",
"var",
"solution",
"=",
"fortran_poop",
".",
"solution",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"x",
".",
"length",
";",
"++",
"i",
")",
"{",
"result",
"[",
"i",
"]",
"=",
"0.0",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"solution",
".",
"length",
";",
"++",
"j",
")",
"{",
"result",
"[",
"i",
"]",
"+=",
"solution",
"[",
"j",
"]",
"*",
"positions",
"[",
"c",
"[",
"j",
"]",
"]",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"2.0",
"*",
"fortran_poop",
".",
"value",
"[",
"0",
"]",
"+",
"numeric",
".",
"dot",
"(",
"x",
",",
"x",
")",
";",
"}",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"x",
".",
"length",
";",
"++",
"i",
")",
"{",
"result",
"[",
"i",
"]",
"=",
"Number",
".",
"NaN",
";",
"}",
"return",
"Number",
".",
"NaN",
";",
"}"
] | General purpose algorithm, uses quadratic programming, very slow | [
"General",
"purpose",
"algorithm",
"uses",
"quadratic",
"programming",
"very",
"slow"
] | de523419bf633743f4333d0768b5e929bc82fd80 | https://github.com/mikolalysenko/polytope-closest-point/blob/de523419bf633743f4333d0768b5e929bc82fd80/lib/closest_point_nd.js#L7-L53 | train |
blakeembrey/dombars | lib/runtime.js | function (subscriptions, fn, context) {
for (var id in subscriptions) {
for (var property in subscriptions[id]) {
fn.call(context, subscriptions[id][property], property, id);
}
}
} | javascript | function (subscriptions, fn, context) {
for (var id in subscriptions) {
for (var property in subscriptions[id]) {
fn.call(context, subscriptions[id][property], property, id);
}
}
} | [
"function",
"(",
"subscriptions",
",",
"fn",
",",
"context",
")",
"{",
"for",
"(",
"var",
"id",
"in",
"subscriptions",
")",
"{",
"for",
"(",
"var",
"property",
"in",
"subscriptions",
"[",
"id",
"]",
")",
"{",
"fn",
".",
"call",
"(",
"context",
",",
"subscriptions",
"[",
"id",
"]",
"[",
"property",
"]",
",",
"property",
",",
"id",
")",
";",
"}",
"}",
"}"
] | Iterate over a subscriptions object, calling a function with the object
property details and a unique callback function.
@param {Array} subscriptions
@param {Function} fn
@param {Function} callback | [
"Iterate",
"over",
"a",
"subscriptions",
"object",
"calling",
"a",
"function",
"with",
"the",
"object",
"property",
"details",
"and",
"a",
"unique",
"callback",
"function",
"."
] | 2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed | https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L28-L34 | train |
|
blakeembrey/dombars | lib/runtime.js | function (fn, update, container) {
// Alias passed in variables for later access.
this._fn = fn;
this._update = update;
this._container = container;
// Assign every subscription instance a unique id. This helps with linking
// between parent and child subscription instances.
this.cid = 'c' + Utils.uniqueId();
this.children = {};
this.subscriptions = {};
this.unsubscriptions = [];
// Create statically bound function instances for public consumption.
this.boundUpdate = Utils.bind(this.update, this);
this.boundUnsubscription = Utils.bind(this.unsubscription, this);
} | javascript | function (fn, update, container) {
// Alias passed in variables for later access.
this._fn = fn;
this._update = update;
this._container = container;
// Assign every subscription instance a unique id. This helps with linking
// between parent and child subscription instances.
this.cid = 'c' + Utils.uniqueId();
this.children = {};
this.subscriptions = {};
this.unsubscriptions = [];
// Create statically bound function instances for public consumption.
this.boundUpdate = Utils.bind(this.update, this);
this.boundUnsubscription = Utils.bind(this.unsubscription, this);
} | [
"function",
"(",
"fn",
",",
"update",
",",
"container",
")",
"{",
"this",
".",
"_fn",
"=",
"fn",
";",
"this",
".",
"_update",
"=",
"update",
";",
"this",
".",
"_container",
"=",
"container",
";",
"this",
".",
"cid",
"=",
"'c'",
"+",
"Utils",
".",
"uniqueId",
"(",
")",
";",
"this",
".",
"children",
"=",
"{",
"}",
";",
"this",
".",
"subscriptions",
"=",
"{",
"}",
";",
"this",
".",
"unsubscriptions",
"=",
"[",
"]",
";",
"this",
".",
"boundUpdate",
"=",
"Utils",
".",
"bind",
"(",
"this",
".",
"update",
",",
"this",
")",
";",
"this",
".",
"boundUnsubscription",
"=",
"Utils",
".",
"bind",
"(",
"this",
".",
"unsubscription",
",",
"this",
")",
";",
"}"
] | Create a new subsciption instance. This functionality is tightly coupled to
DOMBars program execution.
@param {Function} fn
@param {Function} update
@param {Object} container | [
"Create",
"a",
"new",
"subsciption",
"instance",
".",
"This",
"functionality",
"is",
"tightly",
"coupled",
"to",
"DOMBars",
"program",
"execution",
"."
] | 2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed | https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L44-L60 | train |
|
blakeembrey/dombars | lib/runtime.js | function (fn, create, update) {
var subscriber = new Subscription(fn, update, this);
// Immediately alias the starting value.
subscriber.value = subscriber.execute();
Utils.isFunction(create) && (subscriber.value = create(subscriber.value));
return subscriber;
} | javascript | function (fn, create, update) {
var subscriber = new Subscription(fn, update, this);
// Immediately alias the starting value.
subscriber.value = subscriber.execute();
Utils.isFunction(create) && (subscriber.value = create(subscriber.value));
return subscriber;
} | [
"function",
"(",
"fn",
",",
"create",
",",
"update",
")",
"{",
"var",
"subscriber",
"=",
"new",
"Subscription",
"(",
"fn",
",",
"update",
",",
"this",
")",
";",
"subscriber",
".",
"value",
"=",
"subscriber",
".",
"execute",
"(",
")",
";",
"Utils",
".",
"isFunction",
"(",
"create",
")",
"&&",
"(",
"subscriber",
".",
"value",
"=",
"create",
"(",
"subscriber",
".",
"value",
")",
")",
";",
"return",
"subscriber",
";",
"}"
] | Subscriber to function in the DOMBars execution instance.
@param {Function} fn
@param {Function} create
@param {Function} update
@return {Object} | [
"Subscriber",
"to",
"function",
"in",
"the",
"DOMBars",
"execution",
"instance",
"."
] | 2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed | https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L343-L351 | train |
|
blakeembrey/dombars | lib/runtime.js | function (fn) {
var container = this;
var program = function () {
var subscriber = new Subscription(fn, null, container);
return subscriber.execute.apply(subscriber, arguments);
};
Utils.extend(program, fn);
return program;
} | javascript | function (fn) {
var container = this;
var program = function () {
var subscriber = new Subscription(fn, null, container);
return subscriber.execute.apply(subscriber, arguments);
};
Utils.extend(program, fn);
return program;
} | [
"function",
"(",
"fn",
")",
"{",
"var",
"container",
"=",
"this",
";",
"var",
"program",
"=",
"function",
"(",
")",
"{",
"var",
"subscriber",
"=",
"new",
"Subscription",
"(",
"fn",
",",
"null",
",",
"container",
")",
";",
"return",
"subscriber",
".",
"execute",
".",
"apply",
"(",
"subscriber",
",",
"arguments",
")",
";",
"}",
";",
"Utils",
".",
"extend",
"(",
"program",
",",
"fn",
")",
";",
"return",
"program",
";",
"}"
] | Wrap a function with a sanitized public subscriber object.
@param {Function} fn
@return {Function} | [
"Wrap",
"a",
"function",
"with",
"a",
"sanitized",
"public",
"subscriber",
"object",
"."
] | 2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed | https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L359-L370 | train |
|
blakeembrey/dombars | lib/runtime.js | function (fn, create) {
return subscribe.call(this, fn, function (value) {
return Utils.trackNode(create(value));
}, function (value) {
this.value.replace(create(value));
}).value.fragment;
} | javascript | function (fn, create) {
return subscribe.call(this, fn, function (value) {
return Utils.trackNode(create(value));
}, function (value) {
this.value.replace(create(value));
}).value.fragment;
} | [
"function",
"(",
"fn",
",",
"create",
")",
"{",
"return",
"subscribe",
".",
"call",
"(",
"this",
",",
"fn",
",",
"function",
"(",
"value",
")",
"{",
"return",
"Utils",
".",
"trackNode",
"(",
"create",
"(",
"value",
")",
")",
";",
"}",
",",
"function",
"(",
"value",
")",
"{",
"this",
".",
"value",
".",
"replace",
"(",
"create",
"(",
"value",
")",
")",
";",
"}",
")",
".",
"value",
".",
"fragment",
";",
"}"
] | Render and subscribe a single DOM node using a custom creation function.
@param {Function} fn
@param {Function} create
@return {Node} | [
"Render",
"and",
"subscribe",
"a",
"single",
"DOM",
"node",
"using",
"a",
"custom",
"creation",
"function",
"."
] | 2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed | https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L379-L385 | train |
|
blakeembrey/dombars | lib/runtime.js | function (fn, cb) {
return subscribe.call(this, fn, function (value) {
return VM.createElement(value);
}, function (value) {
cb(this.value = VM.setTagName(this.value, value));
}).value;
} | javascript | function (fn, cb) {
return subscribe.call(this, fn, function (value) {
return VM.createElement(value);
}, function (value) {
cb(this.value = VM.setTagName(this.value, value));
}).value;
} | [
"function",
"(",
"fn",
",",
"cb",
")",
"{",
"return",
"subscribe",
".",
"call",
"(",
"this",
",",
"fn",
",",
"function",
"(",
"value",
")",
"{",
"return",
"VM",
".",
"createElement",
"(",
"value",
")",
";",
"}",
",",
"function",
"(",
"value",
")",
"{",
"cb",
"(",
"this",
".",
"value",
"=",
"VM",
".",
"setTagName",
"(",
"this",
".",
"value",
",",
"value",
")",
")",
";",
"}",
")",
".",
"value",
";",
"}"
] | Create an element and subscribe to any changes. This method requires a
callback function for any element changes since you can't change a tag
name in place.
@param {Function} fn
@param {Function} cb
@return {Element} | [
"Create",
"an",
"element",
"and",
"subscribe",
"to",
"any",
"changes",
".",
"This",
"method",
"requires",
"a",
"callback",
"function",
"for",
"any",
"element",
"changes",
"since",
"you",
"can",
"t",
"change",
"a",
"tag",
"name",
"in",
"place",
"."
] | 2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed | https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L396-L402 | train |
|
blakeembrey/dombars | lib/runtime.js | function (currentEl, nameFn, valueFn) {
var attrName = subscribe.call(this, nameFn, null, function (value) {
VM.removeAttribute(currentEl(), this.value);
VM.setAttribute(currentEl(), this.value = value, attrValue.value);
});
var attrValue = subscribe.call(this, valueFn, null, function (value) {
VM.setAttribute(currentEl(), attrName.value, this.value = value);
});
return VM.setAttribute(currentEl(), attrName.value, attrValue.value);
} | javascript | function (currentEl, nameFn, valueFn) {
var attrName = subscribe.call(this, nameFn, null, function (value) {
VM.removeAttribute(currentEl(), this.value);
VM.setAttribute(currentEl(), this.value = value, attrValue.value);
});
var attrValue = subscribe.call(this, valueFn, null, function (value) {
VM.setAttribute(currentEl(), attrName.value, this.value = value);
});
return VM.setAttribute(currentEl(), attrName.value, attrValue.value);
} | [
"function",
"(",
"currentEl",
",",
"nameFn",
",",
"valueFn",
")",
"{",
"var",
"attrName",
"=",
"subscribe",
".",
"call",
"(",
"this",
",",
"nameFn",
",",
"null",
",",
"function",
"(",
"value",
")",
"{",
"VM",
".",
"removeAttribute",
"(",
"currentEl",
"(",
")",
",",
"this",
".",
"value",
")",
";",
"VM",
".",
"setAttribute",
"(",
"currentEl",
"(",
")",
",",
"this",
".",
"value",
"=",
"value",
",",
"attrValue",
".",
"value",
")",
";",
"}",
")",
";",
"var",
"attrValue",
"=",
"subscribe",
".",
"call",
"(",
"this",
",",
"valueFn",
",",
"null",
",",
"function",
"(",
"value",
")",
"{",
"VM",
".",
"setAttribute",
"(",
"currentEl",
"(",
")",
",",
"attrName",
".",
"value",
",",
"this",
".",
"value",
"=",
"value",
")",
";",
"}",
")",
";",
"return",
"VM",
".",
"setAttribute",
"(",
"currentEl",
"(",
")",
",",
"attrName",
".",
"value",
",",
"attrValue",
".",
"value",
")",
";",
"}"
] | Set an elements attribute. We accept the current element a function
because when a tag name changes we will lose reference to the actively
rendered element.
@param {Function} currentEl
@param {Function} nameFn
@param {Function} valueFn | [
"Set",
"an",
"elements",
"attribute",
".",
"We",
"accept",
"the",
"current",
"element",
"a",
"function",
"because",
"when",
"a",
"tag",
"name",
"changes",
"we",
"will",
"lose",
"reference",
"to",
"the",
"actively",
"rendered",
"element",
"."
] | 2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed | https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L426-L437 | train |
|
blakeembrey/dombars | lib/runtime.js | function (fn) {
return subscribe.call(this, fn, function (value) {
return VM.createComment(value);
}, function (value) {
this.value.textContent = value;
}).value;
} | javascript | function (fn) {
return subscribe.call(this, fn, function (value) {
return VM.createComment(value);
}, function (value) {
this.value.textContent = value;
}).value;
} | [
"function",
"(",
"fn",
")",
"{",
"return",
"subscribe",
".",
"call",
"(",
"this",
",",
"fn",
",",
"function",
"(",
"value",
")",
"{",
"return",
"VM",
".",
"createComment",
"(",
"value",
")",
";",
"}",
",",
"function",
"(",
"value",
")",
"{",
"this",
".",
"value",
".",
"textContent",
"=",
"value",
";",
"}",
")",
".",
"value",
";",
"}"
] | Create a comment node and subscribe to any changes.
@param {Function} fn
@return {Comment} | [
"Create",
"a",
"comment",
"node",
"and",
"subscribe",
"to",
"any",
"changes",
"."
] | 2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed | https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L465-L471 | train |
|
openbiz/openbiz | lib/services/ObjectService.js | function(objectName)
{
var app = this;
var objectName = objectName.split(".");
var obj = {};
try
{
switch(objectName.length){
case 1:
for(var module in app.modules)
{
if(app.modules[module].models.hasOwnProperty(objectName[0]))
{
objectName[1]=objectName[0];
objectName[0]=module;
break;
}
}
break;
}
if(app.modules[objectName[0]].models.hasOwnProperty(objectName[1])){
obj = app.modules[objectName[0]].models[objectName[1]];
}else{
throw "not found";
}
}
catch(e)
{
switch(objectName.length){
case 1:
var modulePath = path.join(app._path,"modules");
fs.readdirSync(modulePath).forEach(function(moduleName){
var objFilePath = path.join(app._path,"modules",moduleName,"models",objectName[0]);
if(fs.existsSync(objFilePath+".js"))
{
if( app.modules.hasOwnProperty(moduleName) &&
app.modules[moduleName].hasOwnProperty('models') &&
app.modules[moduleName].models.hasOwnProperty(objectName[0])){
var obj = app.modules[moduleName].models[objectName[0]];
return obj;
}else{
var obj = require(objFilePath)(app);
if(typeof app.modules[moduleName] != "object") app.modules[moduleName]={};
if(typeof app.modules[moduleName].models != "object") app.modules[moduleName].models={};
}
app.modules[moduleName].models[objectName[0]] = obj;
}
});
break;
case 2:
var objFilePath = path.join(app._path,"modules",objectName[0],"models",objectName[1]);
if(fs.existsSync(objFilePath+".js"))
{
var obj = require(objFilePath)(app);
if(typeof app.modules[objectName[0]] != "object") app.modules[objectName[0]]={};
if(typeof app.modules[objectName[0]].models != "object") app.modules[objectName[0]].models={};
app.modules[objectName[0]].models[objectName[1]] = obj;
}
break;
}
}
return obj;
} | javascript | function(objectName)
{
var app = this;
var objectName = objectName.split(".");
var obj = {};
try
{
switch(objectName.length){
case 1:
for(var module in app.modules)
{
if(app.modules[module].models.hasOwnProperty(objectName[0]))
{
objectName[1]=objectName[0];
objectName[0]=module;
break;
}
}
break;
}
if(app.modules[objectName[0]].models.hasOwnProperty(objectName[1])){
obj = app.modules[objectName[0]].models[objectName[1]];
}else{
throw "not found";
}
}
catch(e)
{
switch(objectName.length){
case 1:
var modulePath = path.join(app._path,"modules");
fs.readdirSync(modulePath).forEach(function(moduleName){
var objFilePath = path.join(app._path,"modules",moduleName,"models",objectName[0]);
if(fs.existsSync(objFilePath+".js"))
{
if( app.modules.hasOwnProperty(moduleName) &&
app.modules[moduleName].hasOwnProperty('models') &&
app.modules[moduleName].models.hasOwnProperty(objectName[0])){
var obj = app.modules[moduleName].models[objectName[0]];
return obj;
}else{
var obj = require(objFilePath)(app);
if(typeof app.modules[moduleName] != "object") app.modules[moduleName]={};
if(typeof app.modules[moduleName].models != "object") app.modules[moduleName].models={};
}
app.modules[moduleName].models[objectName[0]] = obj;
}
});
break;
case 2:
var objFilePath = path.join(app._path,"modules",objectName[0],"models",objectName[1]);
if(fs.existsSync(objFilePath+".js"))
{
var obj = require(objFilePath)(app);
if(typeof app.modules[objectName[0]] != "object") app.modules[objectName[0]]={};
if(typeof app.modules[objectName[0]].models != "object") app.modules[objectName[0]].models={};
app.modules[objectName[0]].models[objectName[1]] = obj;
}
break;
}
}
return obj;
} | [
"function",
"(",
"objectName",
")",
"{",
"var",
"app",
"=",
"this",
";",
"var",
"objectName",
"=",
"objectName",
".",
"split",
"(",
"\".\"",
")",
";",
"var",
"obj",
"=",
"{",
"}",
";",
"try",
"{",
"switch",
"(",
"objectName",
".",
"length",
")",
"{",
"case",
"1",
":",
"for",
"(",
"var",
"module",
"in",
"app",
".",
"modules",
")",
"{",
"if",
"(",
"app",
".",
"modules",
"[",
"module",
"]",
".",
"models",
".",
"hasOwnProperty",
"(",
"objectName",
"[",
"0",
"]",
")",
")",
"{",
"objectName",
"[",
"1",
"]",
"=",
"objectName",
"[",
"0",
"]",
";",
"objectName",
"[",
"0",
"]",
"=",
"module",
";",
"break",
";",
"}",
"}",
"break",
";",
"}",
"if",
"(",
"app",
".",
"modules",
"[",
"objectName",
"[",
"0",
"]",
"]",
".",
"models",
".",
"hasOwnProperty",
"(",
"objectName",
"[",
"1",
"]",
")",
")",
"{",
"obj",
"=",
"app",
".",
"modules",
"[",
"objectName",
"[",
"0",
"]",
"]",
".",
"models",
"[",
"objectName",
"[",
"1",
"]",
"]",
";",
"}",
"else",
"{",
"throw",
"\"not found\"",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"switch",
"(",
"objectName",
".",
"length",
")",
"{",
"case",
"1",
":",
"var",
"modulePath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"_path",
",",
"\"modules\"",
")",
";",
"fs",
".",
"readdirSync",
"(",
"modulePath",
")",
".",
"forEach",
"(",
"function",
"(",
"moduleName",
")",
"{",
"var",
"objFilePath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"_path",
",",
"\"modules\"",
",",
"moduleName",
",",
"\"models\"",
",",
"objectName",
"[",
"0",
"]",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"objFilePath",
"+",
"\".js\"",
")",
")",
"{",
"if",
"(",
"app",
".",
"modules",
".",
"hasOwnProperty",
"(",
"moduleName",
")",
"&&",
"app",
".",
"modules",
"[",
"moduleName",
"]",
".",
"hasOwnProperty",
"(",
"'models'",
")",
"&&",
"app",
".",
"modules",
"[",
"moduleName",
"]",
".",
"models",
".",
"hasOwnProperty",
"(",
"objectName",
"[",
"0",
"]",
")",
")",
"{",
"var",
"obj",
"=",
"app",
".",
"modules",
"[",
"moduleName",
"]",
".",
"models",
"[",
"objectName",
"[",
"0",
"]",
"]",
";",
"return",
"obj",
";",
"}",
"else",
"{",
"var",
"obj",
"=",
"require",
"(",
"objFilePath",
")",
"(",
"app",
")",
";",
"if",
"(",
"typeof",
"app",
".",
"modules",
"[",
"moduleName",
"]",
"!=",
"\"object\"",
")",
"app",
".",
"modules",
"[",
"moduleName",
"]",
"=",
"{",
"}",
";",
"if",
"(",
"typeof",
"app",
".",
"modules",
"[",
"moduleName",
"]",
".",
"models",
"!=",
"\"object\"",
")",
"app",
".",
"modules",
"[",
"moduleName",
"]",
".",
"models",
"=",
"{",
"}",
";",
"}",
"app",
".",
"modules",
"[",
"moduleName",
"]",
".",
"models",
"[",
"objectName",
"[",
"0",
"]",
"]",
"=",
"obj",
";",
"}",
"}",
")",
";",
"break",
";",
"case",
"2",
":",
"var",
"objFilePath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"_path",
",",
"\"modules\"",
",",
"objectName",
"[",
"0",
"]",
",",
"\"models\"",
",",
"objectName",
"[",
"1",
"]",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"objFilePath",
"+",
"\".js\"",
")",
")",
"{",
"var",
"obj",
"=",
"require",
"(",
"objFilePath",
")",
"(",
"app",
")",
";",
"if",
"(",
"typeof",
"app",
".",
"modules",
"[",
"objectName",
"[",
"0",
"]",
"]",
"!=",
"\"object\"",
")",
"app",
".",
"modules",
"[",
"objectName",
"[",
"0",
"]",
"]",
"=",
"{",
"}",
";",
"if",
"(",
"typeof",
"app",
".",
"modules",
"[",
"objectName",
"[",
"0",
"]",
"]",
".",
"models",
"!=",
"\"object\"",
")",
"app",
".",
"modules",
"[",
"objectName",
"[",
"0",
"]",
"]",
".",
"models",
"=",
"{",
"}",
";",
"app",
".",
"modules",
"[",
"objectName",
"[",
"0",
"]",
"]",
".",
"models",
"[",
"objectName",
"[",
"1",
"]",
"]",
"=",
"obj",
";",
"}",
"break",
";",
"}",
"}",
"return",
"obj",
";",
"}"
] | Get specified openbiz data model class
This method it part of {@link openbiz.objects.Application},
please never call this directly by ObjectService
if need to call this method, you have to use javascript's function.apply(applicationPointer,params)
please see sample
@memberof openbiz.services.ObjectService
@param {string} objectName - The specified openbiz controller name
@returns {openbiz.objects.Controller}
@example
//below code is how to get a instance of "openbiz-cubi.user.User" class
//cubiApp is instance of openbiz.objects.Application
var myModel = cubiApp.getModel("User");
//then you can access methods of this model like 'hasPermission()'
if(myModel.hasPermission('some-permission')){
...
}
@example
//if you want to call this method directly , please try this way
require('openbiz/services/ObjectService').getController.apply(applicationPointer,objectName) | [
"Get",
"specified",
"openbiz",
"data",
"model",
"class"
] | 997f1398396683d7ad667b1b360ce74c7c7fcf6f | https://github.com/openbiz/openbiz/blob/997f1398396683d7ad667b1b360ce74c7c7fcf6f/lib/services/ObjectService.js#L56-L118 | train |
|
openbiz/openbiz | lib/services/ObjectService.js | function(policyName)
{
var app = this;
var objectName = policyName;
var obj = {};
try
{
if(app.policies.hasOwnProperty(policyName)){
obj = app.policies[policyName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"policies",policyName);
if(fs.existsSync(objFilePath+".js"))
{
obj = require(objFilePath);
if(typeof app.policies != "object") app.policies={};
app.policies[policyName] = obj;
}
}
return obj;
} | javascript | function(policyName)
{
var app = this;
var objectName = policyName;
var obj = {};
try
{
if(app.policies.hasOwnProperty(policyName)){
obj = app.policies[policyName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"policies",policyName);
if(fs.existsSync(objFilePath+".js"))
{
obj = require(objFilePath);
if(typeof app.policies != "object") app.policies={};
app.policies[policyName] = obj;
}
}
return obj;
} | [
"function",
"(",
"policyName",
")",
"{",
"var",
"app",
"=",
"this",
";",
"var",
"objectName",
"=",
"policyName",
";",
"var",
"obj",
"=",
"{",
"}",
";",
"try",
"{",
"if",
"(",
"app",
".",
"policies",
".",
"hasOwnProperty",
"(",
"policyName",
")",
")",
"{",
"obj",
"=",
"app",
".",
"policies",
"[",
"policyName",
"]",
";",
"}",
"else",
"{",
"throw",
"\"not found\"",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"var",
"objFilePath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"_path",
",",
"\"policies\"",
",",
"policyName",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"objFilePath",
"+",
"\".js\"",
")",
")",
"{",
"obj",
"=",
"require",
"(",
"objFilePath",
")",
";",
"if",
"(",
"typeof",
"app",
".",
"policies",
"!=",
"\"object\"",
")",
"app",
".",
"policies",
"=",
"{",
"}",
";",
"app",
".",
"policies",
"[",
"policyName",
"]",
"=",
"obj",
";",
"}",
"}",
"return",
"obj",
";",
"}"
] | Get specified openbiz policy middle-ware function.
This method it part of {@link openbiz.objects.Application},
please never call this directly by ObjectService.
if need to call this method, you have to use javascript's function.apply(applicationPointer,params)
please see sample
@memberof openbiz.services.ObjectService
@param {string} policyName - The specified policy middle-ware name
@returns {function}
@example
//below code is how to get the middle-ware of "cubi.user.ensureSomething" function
//cubiApp is instance of openbiz.objects.Application
var something = cubiApp.getPolicy("ensureSomething");
@example
//if you want to call this method directly , please try this way
require('openbiz/services/ObjectService').getPolicy.apply(applicationPointer,policyName) | [
"Get",
"specified",
"openbiz",
"policy",
"middle",
"-",
"ware",
"function",
"."
] | 997f1398396683d7ad667b1b360ce74c7c7fcf6f | https://github.com/openbiz/openbiz/blob/997f1398396683d7ad667b1b360ce74c7c7fcf6f/lib/services/ObjectService.js#L223-L247 | train |
|
openbiz/openbiz | lib/services/ObjectService.js | function(roleName)
{
var app = this;
var role = {permissions:[]};
try
{
if(app.roles.hasOwnProperty(roleName)){
role = app.roles[roleName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"roles",roleName);
if(fs.existsSync(objFilePath+".js"))
{
var roleConfig = require(objFilePath);
if(typeof app.roles != "object") app.roles={};
app.roles[roleName]= roleConfig.permissions;
if(roleConfig.hasOwnProperty('isDefault') && roleConfig.isDefault == true){
app.defaultRoles.push(roleName);
}
role = roleConfig.permissions;
}
}
return role;
} | javascript | function(roleName)
{
var app = this;
var role = {permissions:[]};
try
{
if(app.roles.hasOwnProperty(roleName)){
role = app.roles[roleName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"roles",roleName);
if(fs.existsSync(objFilePath+".js"))
{
var roleConfig = require(objFilePath);
if(typeof app.roles != "object") app.roles={};
app.roles[roleName]= roleConfig.permissions;
if(roleConfig.hasOwnProperty('isDefault') && roleConfig.isDefault == true){
app.defaultRoles.push(roleName);
}
role = roleConfig.permissions;
}
}
return role;
} | [
"function",
"(",
"roleName",
")",
"{",
"var",
"app",
"=",
"this",
";",
"var",
"role",
"=",
"{",
"permissions",
":",
"[",
"]",
"}",
";",
"try",
"{",
"if",
"(",
"app",
".",
"roles",
".",
"hasOwnProperty",
"(",
"roleName",
")",
")",
"{",
"role",
"=",
"app",
".",
"roles",
"[",
"roleName",
"]",
";",
"}",
"else",
"{",
"throw",
"\"not found\"",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"var",
"objFilePath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"_path",
",",
"\"roles\"",
",",
"roleName",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"objFilePath",
"+",
"\".js\"",
")",
")",
"{",
"var",
"roleConfig",
"=",
"require",
"(",
"objFilePath",
")",
";",
"if",
"(",
"typeof",
"app",
".",
"roles",
"!=",
"\"object\"",
")",
"app",
".",
"roles",
"=",
"{",
"}",
";",
"app",
".",
"roles",
"[",
"roleName",
"]",
"=",
"roleConfig",
".",
"permissions",
";",
"if",
"(",
"roleConfig",
".",
"hasOwnProperty",
"(",
"'isDefault'",
")",
"&&",
"roleConfig",
".",
"isDefault",
"==",
"true",
")",
"{",
"app",
".",
"defaultRoles",
".",
"push",
"(",
"roleName",
")",
";",
"}",
"role",
"=",
"roleConfig",
".",
"permissions",
";",
"}",
"}",
"return",
"role",
";",
"}"
] | Get specified openbiz pre-defined system role.
This method it part of {@link openbiz.objects.Application},
please never call this directly by ObjectService.
if need to call this method, you have to use javascript's function.apply(applicationPointer,params)
please see sample
@memberof openbiz.services.ObjectService
@param {string} roleName - The specified system role name
@returns {array.<string>} Array of permission names,
the permission could be used by {@link openbiz.policies.ensurePermission} middle-ware for protect resource access
@example
//below code is how to get the role named "cubi-admin"
//cubiApp is instance of openbiz.objects.Application
var cubiAdmin = app.getRole("cubi-admin");
//cubiAdmin will looks like below
// [
// "cubi-user-manage",
// "cubi-contact-manage",
// "cubi-account-manage"
// ]
@example
//if you want to call this method directly , please try this way
require('openbiz/services/ObjectService').getRole.apply(applicationPointer,roleName) | [
"Get",
"specified",
"openbiz",
"pre",
"-",
"defined",
"system",
"role",
"."
] | 997f1398396683d7ad667b1b360ce74c7c7fcf6f | https://github.com/openbiz/openbiz/blob/997f1398396683d7ad667b1b360ce74c7c7fcf6f/lib/services/ObjectService.js#L276-L303 | train |
|
openbiz/openbiz | lib/services/ObjectService.js | function(exceptionName)
{
var app = this;
var exception = {};
try
{
if(app.exceptions.hasOwnProperty(exceptionName)){
exception = app.exceptions[exceptionName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"exceptions",exceptionName);
if(fs.existsSync(objFilePath+".js"))
{
var exceptionConfig = require(objFilePath);
if(typeof app.exceptions != "object") app.exceptions={};
app.exceptions[exceptionName]= exceptionConfig;
exception = exceptionConfig;
}
}
return exception;
} | javascript | function(exceptionName)
{
var app = this;
var exception = {};
try
{
if(app.exceptions.hasOwnProperty(exceptionName)){
exception = app.exceptions[exceptionName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"exceptions",exceptionName);
if(fs.existsSync(objFilePath+".js"))
{
var exceptionConfig = require(objFilePath);
if(typeof app.exceptions != "object") app.exceptions={};
app.exceptions[exceptionName]= exceptionConfig;
exception = exceptionConfig;
}
}
return exception;
} | [
"function",
"(",
"exceptionName",
")",
"{",
"var",
"app",
"=",
"this",
";",
"var",
"exception",
"=",
"{",
"}",
";",
"try",
"{",
"if",
"(",
"app",
".",
"exceptions",
".",
"hasOwnProperty",
"(",
"exceptionName",
")",
")",
"{",
"exception",
"=",
"app",
".",
"exceptions",
"[",
"exceptionName",
"]",
";",
"}",
"else",
"{",
"throw",
"\"not found\"",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"var",
"objFilePath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"_path",
",",
"\"exceptions\"",
",",
"exceptionName",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"objFilePath",
"+",
"\".js\"",
")",
")",
"{",
"var",
"exceptionConfig",
"=",
"require",
"(",
"objFilePath",
")",
";",
"if",
"(",
"typeof",
"app",
".",
"exceptions",
"!=",
"\"object\"",
")",
"app",
".",
"exceptions",
"=",
"{",
"}",
";",
"app",
".",
"exceptions",
"[",
"exceptionName",
"]",
"=",
"exceptionConfig",
";",
"exception",
"=",
"exceptionConfig",
";",
"}",
"}",
"return",
"exception",
";",
"}"
] | Get specified openbiz pre-defined system exception.
This method it part of {@link openbiz.objects.Application},
please never call this directly by ObjectService.
if need to call this method, you have to use javascript's function.apply(applicationPointer,params)
please see sample
@memberof openbiz.services.ObjectService
@param {string} exceptionName
@returns object Exception object
@example
var Exception = app.openbiz.apps.xxxx.getExecption("Exception");
throw new Exception(exceptionCode, error); | [
"Get",
"specified",
"openbiz",
"pre",
"-",
"defined",
"system",
"exception",
"."
] | 997f1398396683d7ad667b1b360ce74c7c7fcf6f | https://github.com/openbiz/openbiz/blob/997f1398396683d7ad667b1b360ce74c7c7fcf6f/lib/services/ObjectService.js#L322-L346 | train |
|
arobson/consequent | src/loader.js | loadModule | function loadModule (actorPath) {
try {
let key = path.resolve(actorPath)
delete require.cache[ key ]
return require(actorPath)
} catch (err) {
log.error(`Error loading actor module at ${actorPath} with ${err.stack}`)
return undefined
}
} | javascript | function loadModule (actorPath) {
try {
let key = path.resolve(actorPath)
delete require.cache[ key ]
return require(actorPath)
} catch (err) {
log.error(`Error loading actor module at ${actorPath} with ${err.stack}`)
return undefined
}
} | [
"function",
"loadModule",
"(",
"actorPath",
")",
"{",
"try",
"{",
"let",
"key",
"=",
"path",
".",
"resolve",
"(",
"actorPath",
")",
"delete",
"require",
".",
"cache",
"[",
"key",
"]",
"return",
"require",
"(",
"actorPath",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"log",
".",
"error",
"(",
"`",
"${",
"actorPath",
"}",
"${",
"err",
".",
"stack",
"}",
"`",
")",
"return",
"undefined",
"}",
"}"
] | loads a module based on the file path | [
"loads",
"a",
"module",
"based",
"on",
"the",
"file",
"path"
] | 70cf5c7cd07ae530ca1b5996b53211c520908b4f | https://github.com/arobson/consequent/blob/70cf5c7cd07ae530ca1b5996b53211c520908b4f/src/loader.js#L19-L28 | train |
arobson/consequent | src/loader.js | loadActors | function loadActors (fount, actors) {
let result
function addActor (acc, instance) {
let factory = isFunction(instance.state)
? instance.state : () => clone(instance.state)
processHandles(instance)
acc[ instance.actor.type ] = {
factory: factory,
metadata: instance
}
return acc
}
function onActors (list) {
function onInstances (instances) {
return instances.reduce(addActor, {})
}
let modules = filter(list)
let promises = modules.map((modulePath) => {
let actorFn = loadModule(modulePath)
return fount.inject(actorFn)
})
return Promise
.all(promises)
.then(onInstances)
}
if (isString(actors)) {
let filePath = actors
if (!fs.existsSync(filePath)) {
filePath = path.resolve(process.cwd(), filePath)
}
return getActors(filePath)
.then(onActors)
} else if (Array.isArray(actors)) {
result = actors.reduce((acc, instance) => {
addActor(acc, instance)
return acc
}, {})
return Promise.resolve(result)
} else if (isObject(actors)) {
let keys = Object.keys(actors)
result = keys.reduce((acc, key) => {
let instance = actors[ key ]
addActor(acc, instance)
return acc
}, {})
return Promise.resolve(result)
} else if (isFunction(actors)) {
result = actors()
if (!result.then) {
result = Promise.resolve(result)
}
return result.then(function (list) {
return list.reduce((acc, instance) => {
addActor(acc, instance)
return Promise.resolve(acc)
}, {})
})
}
} | javascript | function loadActors (fount, actors) {
let result
function addActor (acc, instance) {
let factory = isFunction(instance.state)
? instance.state : () => clone(instance.state)
processHandles(instance)
acc[ instance.actor.type ] = {
factory: factory,
metadata: instance
}
return acc
}
function onActors (list) {
function onInstances (instances) {
return instances.reduce(addActor, {})
}
let modules = filter(list)
let promises = modules.map((modulePath) => {
let actorFn = loadModule(modulePath)
return fount.inject(actorFn)
})
return Promise
.all(promises)
.then(onInstances)
}
if (isString(actors)) {
let filePath = actors
if (!fs.existsSync(filePath)) {
filePath = path.resolve(process.cwd(), filePath)
}
return getActors(filePath)
.then(onActors)
} else if (Array.isArray(actors)) {
result = actors.reduce((acc, instance) => {
addActor(acc, instance)
return acc
}, {})
return Promise.resolve(result)
} else if (isObject(actors)) {
let keys = Object.keys(actors)
result = keys.reduce((acc, key) => {
let instance = actors[ key ]
addActor(acc, instance)
return acc
}, {})
return Promise.resolve(result)
} else if (isFunction(actors)) {
result = actors()
if (!result.then) {
result = Promise.resolve(result)
}
return result.then(function (list) {
return list.reduce((acc, instance) => {
addActor(acc, instance)
return Promise.resolve(acc)
}, {})
})
}
} | [
"function",
"loadActors",
"(",
"fount",
",",
"actors",
")",
"{",
"let",
"result",
"function",
"addActor",
"(",
"acc",
",",
"instance",
")",
"{",
"let",
"factory",
"=",
"isFunction",
"(",
"instance",
".",
"state",
")",
"?",
"instance",
".",
"state",
":",
"(",
")",
"=>",
"clone",
"(",
"instance",
".",
"state",
")",
"processHandles",
"(",
"instance",
")",
"acc",
"[",
"instance",
".",
"actor",
".",
"type",
"]",
"=",
"{",
"factory",
":",
"factory",
",",
"metadata",
":",
"instance",
"}",
"return",
"acc",
"}",
"function",
"onActors",
"(",
"list",
")",
"{",
"function",
"onInstances",
"(",
"instances",
")",
"{",
"return",
"instances",
".",
"reduce",
"(",
"addActor",
",",
"{",
"}",
")",
"}",
"let",
"modules",
"=",
"filter",
"(",
"list",
")",
"let",
"promises",
"=",
"modules",
".",
"map",
"(",
"(",
"modulePath",
")",
"=>",
"{",
"let",
"actorFn",
"=",
"loadModule",
"(",
"modulePath",
")",
"return",
"fount",
".",
"inject",
"(",
"actorFn",
")",
"}",
")",
"return",
"Promise",
".",
"all",
"(",
"promises",
")",
".",
"then",
"(",
"onInstances",
")",
"}",
"if",
"(",
"isString",
"(",
"actors",
")",
")",
"{",
"let",
"filePath",
"=",
"actors",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"filePath",
")",
")",
"{",
"filePath",
"=",
"path",
".",
"resolve",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"filePath",
")",
"}",
"return",
"getActors",
"(",
"filePath",
")",
".",
"then",
"(",
"onActors",
")",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"actors",
")",
")",
"{",
"result",
"=",
"actors",
".",
"reduce",
"(",
"(",
"acc",
",",
"instance",
")",
"=>",
"{",
"addActor",
"(",
"acc",
",",
"instance",
")",
"return",
"acc",
"}",
",",
"{",
"}",
")",
"return",
"Promise",
".",
"resolve",
"(",
"result",
")",
"}",
"else",
"if",
"(",
"isObject",
"(",
"actors",
")",
")",
"{",
"let",
"keys",
"=",
"Object",
".",
"keys",
"(",
"actors",
")",
"result",
"=",
"keys",
".",
"reduce",
"(",
"(",
"acc",
",",
"key",
")",
"=>",
"{",
"let",
"instance",
"=",
"actors",
"[",
"key",
"]",
"addActor",
"(",
"acc",
",",
"instance",
")",
"return",
"acc",
"}",
",",
"{",
"}",
")",
"return",
"Promise",
".",
"resolve",
"(",
"result",
")",
"}",
"else",
"if",
"(",
"isFunction",
"(",
"actors",
")",
")",
"{",
"result",
"=",
"actors",
"(",
")",
"if",
"(",
"!",
"result",
".",
"then",
")",
"{",
"result",
"=",
"Promise",
".",
"resolve",
"(",
"result",
")",
"}",
"return",
"result",
".",
"then",
"(",
"function",
"(",
"list",
")",
"{",
"return",
"list",
".",
"reduce",
"(",
"(",
"acc",
",",
"instance",
")",
"=>",
"{",
"addActor",
"(",
"acc",
",",
"instance",
")",
"return",
"Promise",
".",
"resolve",
"(",
"acc",
")",
"}",
",",
"{",
"}",
")",
"}",
")",
"}",
"}"
] | load actors from path and returns the modules once they're loaded | [
"load",
"actors",
"from",
"path",
"and",
"returns",
"the",
"modules",
"once",
"they",
"re",
"loaded"
] | 70cf5c7cd07ae530ca1b5996b53211c520908b4f | https://github.com/arobson/consequent/blob/70cf5c7cd07ae530ca1b5996b53211c520908b4f/src/loader.js#L31-L94 | train |
mlewand-org/vscode-test-set-content | src/index.js | setContent | function setContent( content, options ) {
options = getOptions( options );
return vscode.workspace.openTextDocument( {
language: options.language
} )
.then( doc => vscode.window.showTextDocument( doc ) )
.then( editor => {
let editBuilder = textEdit => {
textEdit.insert( new vscode.Position( 0, 0 ), String( content ) );
};
return editor.edit( editBuilder, {
undoStopBefore: true,
undoStopAfter: false
} )
.then( () => editor );
} );
} | javascript | function setContent( content, options ) {
options = getOptions( options );
return vscode.workspace.openTextDocument( {
language: options.language
} )
.then( doc => vscode.window.showTextDocument( doc ) )
.then( editor => {
let editBuilder = textEdit => {
textEdit.insert( new vscode.Position( 0, 0 ), String( content ) );
};
return editor.edit( editBuilder, {
undoStopBefore: true,
undoStopAfter: false
} )
.then( () => editor );
} );
} | [
"function",
"setContent",
"(",
"content",
",",
"options",
")",
"{",
"options",
"=",
"getOptions",
"(",
"options",
")",
";",
"return",
"vscode",
".",
"workspace",
".",
"openTextDocument",
"(",
"{",
"language",
":",
"options",
".",
"language",
"}",
")",
".",
"then",
"(",
"doc",
"=>",
"vscode",
".",
"window",
".",
"showTextDocument",
"(",
"doc",
")",
")",
".",
"then",
"(",
"editor",
"=>",
"{",
"let",
"editBuilder",
"=",
"textEdit",
"=>",
"{",
"textEdit",
".",
"insert",
"(",
"new",
"vscode",
".",
"Position",
"(",
"0",
",",
"0",
")",
",",
"String",
"(",
"content",
")",
")",
";",
"}",
";",
"return",
"editor",
".",
"edit",
"(",
"editBuilder",
",",
"{",
"undoStopBefore",
":",
"true",
",",
"undoStopAfter",
":",
"false",
"}",
")",
".",
"then",
"(",
"(",
")",
"=>",
"editor",
")",
";",
"}",
")",
";",
"}"
] | Returns a promise that will provide a tet editor with given `content`.
@param {String} content
@param {Object} [options] Config object.
@param {String} [options.language='text'] Indicates what language should the editor use.
@param {String} [options.caret='^'] Character used to represent caret (collapsed selection).
@param {Object} [options.anchor]
@param {String} [options.anchor.start='['] Selection anchor open character.
@param {String} [options.anchor.end=']'] Selection anchor close character.
@param {Object} [options.active]
@param {String} [options.active.start='{'] Selection active part open character.
@param {String} [options.active.end='}'] Selection active part close character.
@returns {Promise<TextEditor>} | [
"Returns",
"a",
"promise",
"that",
"will",
"provide",
"a",
"tet",
"editor",
"with",
"given",
"content",
"."
] | 6ac90d0dfa943602d1a6c8f209f794649cfd2275 | https://github.com/mlewand-org/vscode-test-set-content/blob/6ac90d0dfa943602d1a6c8f209f794649cfd2275/src/index.js#L20-L38 | train |
freshout-dev/fluorine | fluorine.js | init | function init(config) {
Object.keys(config).forEach(function (property) {
this[property] = config[property];
}, this);
} | javascript | function init(config) {
Object.keys(config).forEach(function (property) {
this[property] = config[property];
}, this);
} | [
"function",
"init",
"(",
"config",
")",
"{",
"Object",
".",
"keys",
"(",
"config",
")",
".",
"forEach",
"(",
"function",
"(",
"property",
")",
"{",
"this",
"[",
"property",
"]",
"=",
"config",
"[",
"property",
"]",
";",
"}",
",",
"this",
")",
";",
"}"
] | initializer for the class
@property init <public> [Function]
@argument config <optional> [Object] | [
"initializer",
"for",
"the",
"class"
] | deccd2e0d003678c035a91dffdc6873d9eba8d50 | https://github.com/freshout-dev/fluorine/blob/deccd2e0d003678c035a91dffdc6873d9eba8d50/fluorine.js#L22-L26 | train |
freshout-dev/fluorine | fluorine.js | toDot | function toDot() {
var dotGraph = [];
dotGraph.push("digraph " + this.name + " {");
this.children.forEach(function (step) {
dotGraph.push(step.name);
step.dependencies.forEach(function (dependencyName) {
dotGraph.push(dependencyName + " -> " + step.name);
});
});
dotGraph.push("}");
console.debug("Put this in a file and run this in a terminal: dot -Tsvg yourDotFile > graph.svg");
return dotGraph.join("\n");
} | javascript | function toDot() {
var dotGraph = [];
dotGraph.push("digraph " + this.name + " {");
this.children.forEach(function (step) {
dotGraph.push(step.name);
step.dependencies.forEach(function (dependencyName) {
dotGraph.push(dependencyName + " -> " + step.name);
});
});
dotGraph.push("}");
console.debug("Put this in a file and run this in a terminal: dot -Tsvg yourDotFile > graph.svg");
return dotGraph.join("\n");
} | [
"function",
"toDot",
"(",
")",
"{",
"var",
"dotGraph",
"=",
"[",
"]",
";",
"dotGraph",
".",
"push",
"(",
"\"digraph \"",
"+",
"this",
".",
"name",
"+",
"\" {\"",
")",
";",
"this",
".",
"children",
".",
"forEach",
"(",
"function",
"(",
"step",
")",
"{",
"dotGraph",
".",
"push",
"(",
"step",
".",
"name",
")",
";",
"step",
".",
"dependencies",
".",
"forEach",
"(",
"function",
"(",
"dependencyName",
")",
"{",
"dotGraph",
".",
"push",
"(",
"dependencyName",
"+",
"\" -> \"",
"+",
"step",
".",
"name",
")",
";",
"}",
")",
";",
"}",
")",
";",
"dotGraph",
".",
"push",
"(",
"\"}\"",
")",
";",
"console",
".",
"debug",
"(",
"\"Put this in a file and run this in a terminal: dot -Tsvg yourDotFile > graph.svg\"",
")",
";",
"return",
"dotGraph",
".",
"join",
"(",
"\"\\n\"",
")",
";",
"}"
] | This is a utility method to introspect a flow. flow use case is for when a complex sequence
needs to be solved and its very hard to solve it by simpler programming constructs, so mapping
this sequences is hard, this method dumps the flow into a dot directed graph to be visualized.
@property toDot <public> [Function]
@return string The actual dot string that represents this flow graph. | [
"This",
"is",
"a",
"utility",
"method",
"to",
"introspect",
"a",
"flow",
".",
"flow",
"use",
"case",
"is",
"for",
"when",
"a",
"complex",
"sequence",
"needs",
"to",
"be",
"solved",
"and",
"its",
"very",
"hard",
"to",
"solve",
"it",
"by",
"simpler",
"programming",
"constructs",
"so",
"mapping",
"this",
"sequences",
"is",
"hard",
"this",
"method",
"dumps",
"the",
"flow",
"into",
"a",
"dot",
"directed",
"graph",
"to",
"be",
"visualized",
"."
] | deccd2e0d003678c035a91dffdc6873d9eba8d50 | https://github.com/freshout-dev/fluorine/blob/deccd2e0d003678c035a91dffdc6873d9eba8d50/fluorine.js#L146-L161 | train |
freshout-dev/fluorine | fluorine.js | function (nodeLikeObject) {
var node = this;
if (nodeLikeObject.hasOwnProperty('data') === true) {
setTimeout(function runFlowNode() {
node.code(nodeLikeObject);
}, 0);
}
else if (typeof this.errorCode !== 'undefined') {
setTimeout(function runFlowNodeError() {
node.errorCode(nodeLikeObject);
}, 0);
}
} | javascript | function (nodeLikeObject) {
var node = this;
if (nodeLikeObject.hasOwnProperty('data') === true) {
setTimeout(function runFlowNode() {
node.code(nodeLikeObject);
}, 0);
}
else if (typeof this.errorCode !== 'undefined') {
setTimeout(function runFlowNodeError() {
node.errorCode(nodeLikeObject);
}, 0);
}
} | [
"function",
"(",
"nodeLikeObject",
")",
"{",
"var",
"node",
"=",
"this",
";",
"if",
"(",
"nodeLikeObject",
".",
"hasOwnProperty",
"(",
"'data'",
")",
"===",
"true",
")",
"{",
"setTimeout",
"(",
"function",
"runFlowNode",
"(",
")",
"{",
"node",
".",
"code",
"(",
"nodeLikeObject",
")",
";",
"}",
",",
"0",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"this",
".",
"errorCode",
"!==",
"'undefined'",
")",
"{",
"setTimeout",
"(",
"function",
"runFlowNodeError",
"(",
")",
"{",
"node",
".",
"errorCode",
"(",
"nodeLikeObject",
")",
";",
"}",
",",
"0",
")",
";",
"}",
"}"
] | Executes the node. This is done via a setTimeout to release the stack depth.
Even thought it is required for events to be synchronous, a flow step does
not represent a safe data signal propagation, instead is a pass to other process
like behavior.
@property run <public> [Function]
@argument FlowNode <required> [Object]
@return Undefined | [
"Executes",
"the",
"node",
".",
"This",
"is",
"done",
"via",
"a",
"setTimeout",
"to",
"release",
"the",
"stack",
"depth",
".",
"Even",
"thought",
"it",
"is",
"required",
"for",
"events",
"to",
"be",
"synchronous",
"a",
"flow",
"step",
"does",
"not",
"represent",
"a",
"safe",
"data",
"signal",
"propagation",
"instead",
"is",
"a",
"pass",
"to",
"other",
"process",
"like",
"behavior",
"."
] | deccd2e0d003678c035a91dffdc6873d9eba8d50 | https://github.com/freshout-dev/fluorine/blob/deccd2e0d003678c035a91dffdc6873d9eba8d50/fluorine.js#L240-L252 | train |
|
freshout-dev/fluorine | fluorine.js | function (data) {
this.data = data;
this.isFulfilled = true;
if (this.parent === null) {
return;
}
this.parent.dispatch(this.name);
} | javascript | function (data) {
this.data = data;
this.isFulfilled = true;
if (this.parent === null) {
return;
}
this.parent.dispatch(this.name);
} | [
"function",
"(",
"data",
")",
"{",
"this",
".",
"data",
"=",
"data",
";",
"this",
".",
"isFulfilled",
"=",
"true",
";",
"if",
"(",
"this",
".",
"parent",
"===",
"null",
")",
"{",
"return",
";",
"}",
"this",
".",
"parent",
".",
"dispatch",
"(",
"this",
".",
"name",
")",
";",
"}"
] | method to notify that the step executed succesfully.
@property fulfill <public> [Function] | [
"method",
"to",
"notify",
"that",
"the",
"step",
"executed",
"succesfully",
"."
] | deccd2e0d003678c035a91dffdc6873d9eba8d50 | https://github.com/freshout-dev/fluorine/blob/deccd2e0d003678c035a91dffdc6873d9eba8d50/fluorine.js#L258-L267 | train |
|
freshout-dev/fluorine | fluorine.js | function (error) {
this.error = error;
this.isRejected = true;
if (this.parent === null) {
return;
}
this.parent.dispatch(this.name);
this.parent.dispatch('reject', {
data : { node : this, error: error }
});
} | javascript | function (error) {
this.error = error;
this.isRejected = true;
if (this.parent === null) {
return;
}
this.parent.dispatch(this.name);
this.parent.dispatch('reject', {
data : { node : this, error: error }
});
} | [
"function",
"(",
"error",
")",
"{",
"this",
".",
"error",
"=",
"error",
";",
"this",
".",
"isRejected",
"=",
"true",
";",
"if",
"(",
"this",
".",
"parent",
"===",
"null",
")",
"{",
"return",
";",
"}",
"this",
".",
"parent",
".",
"dispatch",
"(",
"this",
".",
"name",
")",
";",
"this",
".",
"parent",
".",
"dispatch",
"(",
"'reject'",
",",
"{",
"data",
":",
"{",
"node",
":",
"this",
",",
"error",
":",
"error",
"}",
"}",
")",
";",
"}"
] | method to notify that the step executed wrong.
@property reject <public> [Function] | [
"method",
"to",
"notify",
"that",
"the",
"step",
"executed",
"wrong",
"."
] | deccd2e0d003678c035a91dffdc6873d9eba8d50 | https://github.com/freshout-dev/fluorine/blob/deccd2e0d003678c035a91dffdc6873d9eba8d50/fluorine.js#L273-L285 | train |
|
novemberborn/cloudflare-origin-pull | src/index.js | tryVerify | function tryVerify (rawBytes) {
const {
tbsCertificate,
tbsCertificate: {
validity: {
notBefore: { value: notBefore },
notAfter: { value: notAfter }
}
},
signatureAlgorithm: { algorithm },
signature: { data: signature }
} = Certificate.decode(rawBytes, 'der')
// Require sha512WithRSAEncryption.
if (algorithm.join('.') !== '1.2.840.113549.1.1.13') {
return false
}
// Check if certificate is still valid.–
const now = Date.now()
if (now < notBefore || now > notAfter) {
return false
}
// Make sure the certificate was signed by CloudFlare's origin pull
// certificate authority.
const verifier = createVerify('RSA-SHA512')
verifier.update(TBSCertificate.encode(tbsCertificate, 'der'))
return verifier.verify(originPullCa, signature)
} | javascript | function tryVerify (rawBytes) {
const {
tbsCertificate,
tbsCertificate: {
validity: {
notBefore: { value: notBefore },
notAfter: { value: notAfter }
}
},
signatureAlgorithm: { algorithm },
signature: { data: signature }
} = Certificate.decode(rawBytes, 'der')
// Require sha512WithRSAEncryption.
if (algorithm.join('.') !== '1.2.840.113549.1.1.13') {
return false
}
// Check if certificate is still valid.–
const now = Date.now()
if (now < notBefore || now > notAfter) {
return false
}
// Make sure the certificate was signed by CloudFlare's origin pull
// certificate authority.
const verifier = createVerify('RSA-SHA512')
verifier.update(TBSCertificate.encode(tbsCertificate, 'der'))
return verifier.verify(originPullCa, signature)
} | [
"function",
"tryVerify",
"(",
"rawBytes",
")",
"{",
"const",
"{",
"tbsCertificate",
",",
"tbsCertificate",
":",
"{",
"validity",
":",
"{",
"notBefore",
":",
"{",
"value",
":",
"notBefore",
"}",
",",
"notAfter",
":",
"{",
"value",
":",
"notAfter",
"}",
"}",
"}",
",",
"signatureAlgorithm",
":",
"{",
"algorithm",
"}",
",",
"signature",
":",
"{",
"data",
":",
"signature",
"}",
"}",
"=",
"Certificate",
".",
"decode",
"(",
"rawBytes",
",",
"'der'",
")",
"if",
"(",
"algorithm",
".",
"join",
"(",
"'.'",
")",
"!==",
"'1.2.840.113549.1.1.13'",
")",
"{",
"return",
"false",
"}",
"const",
"now",
"=",
"Date",
".",
"now",
"(",
")",
"if",
"(",
"now",
"<",
"notBefore",
"||",
"now",
">",
"notAfter",
")",
"{",
"return",
"false",
"}",
"const",
"verifier",
"=",
"createVerify",
"(",
"'RSA-SHA512'",
")",
"verifier",
".",
"update",
"(",
"TBSCertificate",
".",
"encode",
"(",
"tbsCertificate",
",",
"'der'",
")",
")",
"return",
"verifier",
".",
"verify",
"(",
"originPullCa",
",",
"signature",
")",
"}"
] | N.B. This only checks if the timestamps are valid and if the signature matches. Proper certificate validation requires more checks but that seems unnecessary in this case. | [
"N",
".",
"B",
".",
"This",
"only",
"checks",
"if",
"the",
"timestamps",
"are",
"valid",
"and",
"if",
"the",
"signature",
"matches",
".",
"Proper",
"certificate",
"validation",
"requires",
"more",
"checks",
"but",
"that",
"seems",
"unnecessary",
"in",
"this",
"case",
"."
] | 01fa94b020e67ca54bef99175e1ece22e0c2eb08 | https://github.com/novemberborn/cloudflare-origin-pull/blob/01fa94b020e67ca54bef99175e1ece22e0c2eb08/src/index.js#L60-L88 | train |
fergaldoyle/gulp-require-angular | parseNg.js | parse | function parse(source) {
var moduleDefinitions = {},
moduleReferences = [];
estraverse.traverse(esprima.parse(source), {
leave: function (node, parent) {
if(!isAngular(node)) {
return;
}
//console.log('node:', JSON.stringify(node, null, 3));
//console.log('parent:', JSON.stringify(parent, null, 3));
var moduleName = parent.arguments[0].value;
// if a second argument exists
// this is a module definition
if(parent.arguments[1]) {
if(parent.arguments[1].type === 'ArrayExpression') {
moduleDefinitions[moduleName] = parent.arguments[1].elements.map(function(item){
return item['value'];
});
} else {
throw 'Argument must be an ArrayExpression, not a variable';
}
} else {
// is a module reference
pushDistinct(moduleReferences, moduleName);
}
}
});
return {
modules: moduleDefinitions,
references: moduleReferences
}
} | javascript | function parse(source) {
var moduleDefinitions = {},
moduleReferences = [];
estraverse.traverse(esprima.parse(source), {
leave: function (node, parent) {
if(!isAngular(node)) {
return;
}
//console.log('node:', JSON.stringify(node, null, 3));
//console.log('parent:', JSON.stringify(parent, null, 3));
var moduleName = parent.arguments[0].value;
// if a second argument exists
// this is a module definition
if(parent.arguments[1]) {
if(parent.arguments[1].type === 'ArrayExpression') {
moduleDefinitions[moduleName] = parent.arguments[1].elements.map(function(item){
return item['value'];
});
} else {
throw 'Argument must be an ArrayExpression, not a variable';
}
} else {
// is a module reference
pushDistinct(moduleReferences, moduleName);
}
}
});
return {
modules: moduleDefinitions,
references: moduleReferences
}
} | [
"function",
"parse",
"(",
"source",
")",
"{",
"var",
"moduleDefinitions",
"=",
"{",
"}",
",",
"moduleReferences",
"=",
"[",
"]",
";",
"estraverse",
".",
"traverse",
"(",
"esprima",
".",
"parse",
"(",
"source",
")",
",",
"{",
"leave",
":",
"function",
"(",
"node",
",",
"parent",
")",
"{",
"if",
"(",
"!",
"isAngular",
"(",
"node",
")",
")",
"{",
"return",
";",
"}",
"var",
"moduleName",
"=",
"parent",
".",
"arguments",
"[",
"0",
"]",
".",
"value",
";",
"if",
"(",
"parent",
".",
"arguments",
"[",
"1",
"]",
")",
"{",
"if",
"(",
"parent",
".",
"arguments",
"[",
"1",
"]",
".",
"type",
"===",
"'ArrayExpression'",
")",
"{",
"moduleDefinitions",
"[",
"moduleName",
"]",
"=",
"parent",
".",
"arguments",
"[",
"1",
"]",
".",
"elements",
".",
"map",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"item",
"[",
"'value'",
"]",
";",
"}",
")",
";",
"}",
"else",
"{",
"throw",
"'Argument must be an ArrayExpression, not a variable'",
";",
"}",
"}",
"else",
"{",
"pushDistinct",
"(",
"moduleReferences",
",",
"moduleName",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"{",
"modules",
":",
"moduleDefinitions",
",",
"references",
":",
"moduleReferences",
"}",
"}"
] | Find module definitions and the dependencies of those modules Find module references | [
"Find",
"module",
"definitions",
"and",
"the",
"dependencies",
"of",
"those",
"modules",
"Find",
"module",
"references"
] | 9b6250dada310590b4575e030a1e03293454b98f | https://github.com/fergaldoyle/gulp-require-angular/blob/9b6250dada310590b4575e030a1e03293454b98f/parseNg.js#L18-L57 | train |
oskargustafsson/BFF | src/view.js | View | function View() {
Object.defineProperty(this, '__private', { writable: true, value: {}, });
this.__private.isRenderRequested = false;
var delegates = this.__private.eventDelegates = {};
this.__private.onDelegatedEvent = function onDelegatedEvent(ev) {
var delegatesForEvent = delegates[ev.type];
var el = ev.target;
for (var selectorStr in delegatesForEvent) {
if (!elMatchesSelector(el, selectorStr)) { continue; }
var delegatesForEventAndSelector = delegatesForEvent[selectorStr];
for (var i = 0, n = delegatesForEventAndSelector.length; i < n; ++i) {
delegatesForEventAndSelector[i](ev);
}
}
};
/**
* The root DOM element of the view. The default implementation of {@link module:bff/view#render} assigns to and updates this element. Delegated event listeners, created by calling {@link module:bff/view#listenTo} are attached to this element.
* Replacing the current element with another will clear all currently delegated event listeners - it is usually a better approach update the element (using e.g. {@link module:bff/patch-dom}) instead of replacing it.
* @instance
* @member {HTMLElement|undefined} el
*/
Object.defineProperty(this, 'el', {
enumerable: true,
get: function () { return this.__private.el; },
set: function (el) {
this.stopListening('*');
this.__private.el = el;
}
});
this.__private.childViews = new List();
this.listenTo(this.__private.childViews, 'item:destroyed', function (childView) {
this.__private.childViews.remove(childView);
});
/**
* A list of this view's child views. Initially empty.
* @instance
* @member {module:bff/list} children
*/
Object.defineProperty(this, 'children', {
enumerable: true,
get: function () { return this.__private.childViews; },
});
} | javascript | function View() {
Object.defineProperty(this, '__private', { writable: true, value: {}, });
this.__private.isRenderRequested = false;
var delegates = this.__private.eventDelegates = {};
this.__private.onDelegatedEvent = function onDelegatedEvent(ev) {
var delegatesForEvent = delegates[ev.type];
var el = ev.target;
for (var selectorStr in delegatesForEvent) {
if (!elMatchesSelector(el, selectorStr)) { continue; }
var delegatesForEventAndSelector = delegatesForEvent[selectorStr];
for (var i = 0, n = delegatesForEventAndSelector.length; i < n; ++i) {
delegatesForEventAndSelector[i](ev);
}
}
};
/**
* The root DOM element of the view. The default implementation of {@link module:bff/view#render} assigns to and updates this element. Delegated event listeners, created by calling {@link module:bff/view#listenTo} are attached to this element.
* Replacing the current element with another will clear all currently delegated event listeners - it is usually a better approach update the element (using e.g. {@link module:bff/patch-dom}) instead of replacing it.
* @instance
* @member {HTMLElement|undefined} el
*/
Object.defineProperty(this, 'el', {
enumerable: true,
get: function () { return this.__private.el; },
set: function (el) {
this.stopListening('*');
this.__private.el = el;
}
});
this.__private.childViews = new List();
this.listenTo(this.__private.childViews, 'item:destroyed', function (childView) {
this.__private.childViews.remove(childView);
});
/**
* A list of this view's child views. Initially empty.
* @instance
* @member {module:bff/list} children
*/
Object.defineProperty(this, 'children', {
enumerable: true,
get: function () { return this.__private.childViews; },
});
} | [
"function",
"View",
"(",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'__private'",
",",
"{",
"writable",
":",
"true",
",",
"value",
":",
"{",
"}",
",",
"}",
")",
";",
"this",
".",
"__private",
".",
"isRenderRequested",
"=",
"false",
";",
"var",
"delegates",
"=",
"this",
".",
"__private",
".",
"eventDelegates",
"=",
"{",
"}",
";",
"this",
".",
"__private",
".",
"onDelegatedEvent",
"=",
"function",
"onDelegatedEvent",
"(",
"ev",
")",
"{",
"var",
"delegatesForEvent",
"=",
"delegates",
"[",
"ev",
".",
"type",
"]",
";",
"var",
"el",
"=",
"ev",
".",
"target",
";",
"for",
"(",
"var",
"selectorStr",
"in",
"delegatesForEvent",
")",
"{",
"if",
"(",
"!",
"elMatchesSelector",
"(",
"el",
",",
"selectorStr",
")",
")",
"{",
"continue",
";",
"}",
"var",
"delegatesForEventAndSelector",
"=",
"delegatesForEvent",
"[",
"selectorStr",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"delegatesForEventAndSelector",
".",
"length",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"delegatesForEventAndSelector",
"[",
"i",
"]",
"(",
"ev",
")",
";",
"}",
"}",
"}",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'el'",
",",
"{",
"enumerable",
":",
"true",
",",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"__private",
".",
"el",
";",
"}",
",",
"set",
":",
"function",
"(",
"el",
")",
"{",
"this",
".",
"stopListening",
"(",
"'*'",
")",
";",
"this",
".",
"__private",
".",
"el",
"=",
"el",
";",
"}",
"}",
")",
";",
"this",
".",
"__private",
".",
"childViews",
"=",
"new",
"List",
"(",
")",
";",
"this",
".",
"listenTo",
"(",
"this",
".",
"__private",
".",
"childViews",
",",
"'item:destroyed'",
",",
"function",
"(",
"childView",
")",
"{",
"this",
".",
"__private",
".",
"childViews",
".",
"remove",
"(",
"childView",
")",
";",
"}",
")",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'children'",
",",
"{",
"enumerable",
":",
"true",
",",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"__private",
".",
"childViews",
";",
"}",
",",
"}",
")",
";",
"}"
] | Creates a new View instance.
@constructor
@mixes module:bff/event-emitter
@mixes module:bff/event-listener
@alias module:bff/view | [
"Creates",
"a",
"new",
"View",
"instance",
"."
] | 38ebebf3b69f758da78ffb50a97742d33d6d5931 | https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/view.js#L39-L86 | train |
oskargustafsson/BFF | src/view.js | function (htmlString, returnAll) {
if (RUNTIME_CHECKS) {
if (typeof htmlString !== 'string') {
throw '"htmlString" argument must be a string';
}
if (arguments.length > 1 && typeof returnAll !== 'boolean') {
throw '"returnAll" argument must be a boolean value';
}
}
HTML_PARSER_EL.innerHTML = htmlString;
if (RUNTIME_CHECKS && !returnAll && HTML_PARSER_EL.children.length > 1) {
throw 'The parsed HTML contains more than one root element.' +
'Specify returnAll = true to return all of them';
}
var ret = returnAll ? HTML_PARSER_EL.children : HTML_PARSER_EL.firstChild;
while (HTML_PARSER_EL.firstChild) {
HTML_PARSER_EL.removeChild(HTML_PARSER_EL.firstChild);
}
return ret;
} | javascript | function (htmlString, returnAll) {
if (RUNTIME_CHECKS) {
if (typeof htmlString !== 'string') {
throw '"htmlString" argument must be a string';
}
if (arguments.length > 1 && typeof returnAll !== 'boolean') {
throw '"returnAll" argument must be a boolean value';
}
}
HTML_PARSER_EL.innerHTML = htmlString;
if (RUNTIME_CHECKS && !returnAll && HTML_PARSER_EL.children.length > 1) {
throw 'The parsed HTML contains more than one root element.' +
'Specify returnAll = true to return all of them';
}
var ret = returnAll ? HTML_PARSER_EL.children : HTML_PARSER_EL.firstChild;
while (HTML_PARSER_EL.firstChild) {
HTML_PARSER_EL.removeChild(HTML_PARSER_EL.firstChild);
}
return ret;
} | [
"function",
"(",
"htmlString",
",",
"returnAll",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
")",
"{",
"if",
"(",
"typeof",
"htmlString",
"!==",
"'string'",
")",
"{",
"throw",
"'\"htmlString\" argument must be a string'",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
">",
"1",
"&&",
"typeof",
"returnAll",
"!==",
"'boolean'",
")",
"{",
"throw",
"'\"returnAll\" argument must be a boolean value'",
";",
"}",
"}",
"HTML_PARSER_EL",
".",
"innerHTML",
"=",
"htmlString",
";",
"if",
"(",
"RUNTIME_CHECKS",
"&&",
"!",
"returnAll",
"&&",
"HTML_PARSER_EL",
".",
"children",
".",
"length",
">",
"1",
")",
"{",
"throw",
"'The parsed HTML contains more than one root element.'",
"+",
"'Specify returnAll = true to return all of them'",
";",
"}",
"var",
"ret",
"=",
"returnAll",
"?",
"HTML_PARSER_EL",
".",
"children",
":",
"HTML_PARSER_EL",
".",
"firstChild",
";",
"while",
"(",
"HTML_PARSER_EL",
".",
"firstChild",
")",
"{",
"HTML_PARSER_EL",
".",
"removeChild",
"(",
"HTML_PARSER_EL",
".",
"firstChild",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | Helper function that parses an HTML string into an HTMLElement hierarchy and returns the first element in the NodeList, unless the returnAll flag is true, in which case the whole node list is returned.
@instance
@arg {string} htmlString - The string to be parsed
@arg {boolean} returnAll - If true will return all top level elements | [
"Helper",
"function",
"that",
"parses",
"an",
"HTML",
"string",
"into",
"an",
"HTMLElement",
"hierarchy",
"and",
"returns",
"the",
"first",
"element",
"in",
"the",
"NodeList",
"unless",
"the",
"returnAll",
"flag",
"is",
"true",
"in",
"which",
"case",
"the",
"whole",
"node",
"list",
"is",
"returned",
"."
] | 38ebebf3b69f758da78ffb50a97742d33d6d5931 | https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/view.js#L160-L182 | train |
|
oskargustafsson/BFF | src/view.js | function (childView, el) {
if (RUNTIME_CHECKS) {
if (!(childView instanceof View)) {
throw '"childView" argument must be a BFF View';
}
if (arguments.length > 1 && !(el === false || el instanceof HTMLElement)) {
throw '"el" argument must be an HTMLElement or the boolean value false';
}
}
this.__private.childViews.push(childView);
el !== false && (el || this.el).appendChild(childView.el);
return childView;
} | javascript | function (childView, el) {
if (RUNTIME_CHECKS) {
if (!(childView instanceof View)) {
throw '"childView" argument must be a BFF View';
}
if (arguments.length > 1 && !(el === false || el instanceof HTMLElement)) {
throw '"el" argument must be an HTMLElement or the boolean value false';
}
}
this.__private.childViews.push(childView);
el !== false && (el || this.el).appendChild(childView.el);
return childView;
} | [
"function",
"(",
"childView",
",",
"el",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
")",
"{",
"if",
"(",
"!",
"(",
"childView",
"instanceof",
"View",
")",
")",
"{",
"throw",
"'\"childView\" argument must be a BFF View'",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
">",
"1",
"&&",
"!",
"(",
"el",
"===",
"false",
"||",
"el",
"instanceof",
"HTMLElement",
")",
")",
"{",
"throw",
"'\"el\" argument must be an HTMLElement or the boolean value false'",
";",
"}",
"}",
"this",
".",
"__private",
".",
"childViews",
".",
"push",
"(",
"childView",
")",
";",
"el",
"!==",
"false",
"&&",
"(",
"el",
"||",
"this",
".",
"el",
")",
".",
"appendChild",
"(",
"childView",
".",
"el",
")",
";",
"return",
"childView",
";",
"}"
] | Adds another view as a child to the view. A child view will be automatically added to this view's root element and destroyed whenever its parent view is destroyed.
@instance
@arg {module:bff/view} childView - The view that will be added to the list of this view's children.
@arg {HTMLElement|boolean} [optional] - An element to which the child view's root element will be appended. If not specified, it will be appended to this view's root element. Can also be `false`, in which case the child view will not be appended to anything. | [
"Adds",
"another",
"view",
"as",
"a",
"child",
"to",
"the",
"view",
".",
"A",
"child",
"view",
"will",
"be",
"automatically",
"added",
"to",
"this",
"view",
"s",
"root",
"element",
"and",
"destroyed",
"whenever",
"its",
"parent",
"view",
"is",
"destroyed",
"."
] | 38ebebf3b69f758da78ffb50a97742d33d6d5931 | https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/view.js#L216-L229 | train |
|
oskargustafsson/BFF | src/view.js | function () {
// Iterate backwards because the list might shrink while being iterated
for (var i = this.__private.childViews.length - 1; i >= 0; --i) {
this.__private.childViews[i].destroy();
}
} | javascript | function () {
// Iterate backwards because the list might shrink while being iterated
for (var i = this.__private.childViews.length - 1; i >= 0; --i) {
this.__private.childViews[i].destroy();
}
} | [
"function",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"this",
".",
"__private",
".",
"childViews",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"--",
"i",
")",
"{",
"this",
".",
"__private",
".",
"childViews",
"[",
"i",
"]",
".",
"destroy",
"(",
")",
";",
"}",
"}"
] | Destroy all child views of this view.
@instance | [
"Destroy",
"all",
"child",
"views",
"of",
"this",
"view",
"."
] | 38ebebf3b69f758da78ffb50a97742d33d6d5931 | https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/view.js#L235-L240 | train |
|
TorchlightSoftware/particle | dist/lodash.js | createCache | function createCache(array) {
var index = -1,
length = array.length;
var cache = getObject();
cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;
var result = getObject();
result.array = array;
result.cache = cache;
result.push = cachePush;
while (++index < length) {
result.push(array[index]);
}
return cache.object === false
? (releaseObject(result), null)
: result;
} | javascript | function createCache(array) {
var index = -1,
length = array.length;
var cache = getObject();
cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;
var result = getObject();
result.array = array;
result.cache = cache;
result.push = cachePush;
while (++index < length) {
result.push(array[index]);
}
return cache.object === false
? (releaseObject(result), null)
: result;
} | [
"function",
"createCache",
"(",
"array",
")",
"{",
"var",
"index",
"=",
"-",
"1",
",",
"length",
"=",
"array",
".",
"length",
";",
"var",
"cache",
"=",
"getObject",
"(",
")",
";",
"cache",
"[",
"'false'",
"]",
"=",
"cache",
"[",
"'null'",
"]",
"=",
"cache",
"[",
"'true'",
"]",
"=",
"cache",
"[",
"'undefined'",
"]",
"=",
"false",
";",
"var",
"result",
"=",
"getObject",
"(",
")",
";",
"result",
".",
"array",
"=",
"array",
";",
"result",
".",
"cache",
"=",
"cache",
";",
"result",
".",
"push",
"=",
"cachePush",
";",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"result",
".",
"push",
"(",
"array",
"[",
"index",
"]",
")",
";",
"}",
"return",
"cache",
".",
"object",
"===",
"false",
"?",
"(",
"releaseObject",
"(",
"result",
")",
",",
"null",
")",
":",
"result",
";",
"}"
] | Creates a cache object to optimize linear searches of large arrays.
@private
@param {Array} [array=[]] The array to search.
@returns {Null|Object} Returns the cache object or `null` if caching should not be used. | [
"Creates",
"a",
"cache",
"object",
"to",
"optimize",
"linear",
"searches",
"of",
"large",
"arrays",
"."
] | 1312f00d04477c46325420329012681bda152c71 | https://github.com/TorchlightSoftware/particle/blob/1312f00d04477c46325420329012681bda152c71/dist/lodash.js#L212-L230 | train |
TorchlightSoftware/particle | dist/lodash.js | getIndexOf | function getIndexOf(array, value, fromIndex) {
var result = (result = lodash.indexOf) === indexOf ? basicIndexOf : result;
return result;
} | javascript | function getIndexOf(array, value, fromIndex) {
var result = (result = lodash.indexOf) === indexOf ? basicIndexOf : result;
return result;
} | [
"function",
"getIndexOf",
"(",
"array",
",",
"value",
",",
"fromIndex",
")",
"{",
"var",
"result",
"=",
"(",
"result",
"=",
"lodash",
".",
"indexOf",
")",
"===",
"indexOf",
"?",
"basicIndexOf",
":",
"result",
";",
"return",
"result",
";",
"}"
] | Gets the appropriate "indexOf" function. If the `_.indexOf` method is
customized, this method returns the custom method, otherwise it returns
the `basicIndexOf` function.
@private
@returns {Function} Returns the "indexOf" function. | [
"Gets",
"the",
"appropriate",
"indexOf",
"function",
".",
"If",
"the",
"_",
".",
"indexOf",
"method",
"is",
"customized",
"this",
"method",
"returns",
"the",
"custom",
"method",
"otherwise",
"it",
"returns",
"the",
"basicIndexOf",
"function",
"."
] | 1312f00d04477c46325420329012681bda152c71 | https://github.com/TorchlightSoftware/particle/blob/1312f00d04477c46325420329012681bda152c71/dist/lodash.js#L801-L804 | train |
axke/rs-api | lib/apis/distraction/spotlight.js | function () {
return new Promise(function (resolve, reject) {
var rotations = [];
for (var i = 0; i < spotlightRotations.length; i++) {
var now = new Date();
var daysToAdd = 3 * i;
now.setDate(now.getDate() + daysToAdd);
var currentSpotlight = Math.floor((((Math.floor((now / 1000) / (24 * 60 * 60))) - 49) % (3 * spotlightRotations.length)) / 3);
var daysUntilNext = (3 - ((Math.floor((now / 1000) / (24 * 60 * 60))) - 49) % (3 * spotlightRotations.length) % 3) + daysToAdd;
var start = new Date();
start.setDate(start.getDate() + (daysUntilNext - 3));
var obj = {
rotation: spotlightRotations[currentSpotlight],
daysUntilNext: daysUntilNext,
startDate: start
};
rotations.push(obj);
}
resolve(rotations);
});
} | javascript | function () {
return new Promise(function (resolve, reject) {
var rotations = [];
for (var i = 0; i < spotlightRotations.length; i++) {
var now = new Date();
var daysToAdd = 3 * i;
now.setDate(now.getDate() + daysToAdd);
var currentSpotlight = Math.floor((((Math.floor((now / 1000) / (24 * 60 * 60))) - 49) % (3 * spotlightRotations.length)) / 3);
var daysUntilNext = (3 - ((Math.floor((now / 1000) / (24 * 60 * 60))) - 49) % (3 * spotlightRotations.length) % 3) + daysToAdd;
var start = new Date();
start.setDate(start.getDate() + (daysUntilNext - 3));
var obj = {
rotation: spotlightRotations[currentSpotlight],
daysUntilNext: daysUntilNext,
startDate: start
};
rotations.push(obj);
}
resolve(rotations);
});
} | [
"function",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"rotations",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"spotlightRotations",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"now",
"=",
"new",
"Date",
"(",
")",
";",
"var",
"daysToAdd",
"=",
"3",
"*",
"i",
";",
"now",
".",
"setDate",
"(",
"now",
".",
"getDate",
"(",
")",
"+",
"daysToAdd",
")",
";",
"var",
"currentSpotlight",
"=",
"Math",
".",
"floor",
"(",
"(",
"(",
"(",
"Math",
".",
"floor",
"(",
"(",
"now",
"/",
"1000",
")",
"/",
"(",
"24",
"*",
"60",
"*",
"60",
")",
")",
")",
"-",
"49",
")",
"%",
"(",
"3",
"*",
"spotlightRotations",
".",
"length",
")",
")",
"/",
"3",
")",
";",
"var",
"daysUntilNext",
"=",
"(",
"3",
"-",
"(",
"(",
"Math",
".",
"floor",
"(",
"(",
"now",
"/",
"1000",
")",
"/",
"(",
"24",
"*",
"60",
"*",
"60",
")",
")",
")",
"-",
"49",
")",
"%",
"(",
"3",
"*",
"spotlightRotations",
".",
"length",
")",
"%",
"3",
")",
"+",
"daysToAdd",
";",
"var",
"start",
"=",
"new",
"Date",
"(",
")",
";",
"start",
".",
"setDate",
"(",
"start",
".",
"getDate",
"(",
")",
"+",
"(",
"daysUntilNext",
"-",
"3",
")",
")",
";",
"var",
"obj",
"=",
"{",
"rotation",
":",
"spotlightRotations",
"[",
"currentSpotlight",
"]",
",",
"daysUntilNext",
":",
"daysUntilNext",
",",
"startDate",
":",
"start",
"}",
";",
"rotations",
".",
"push",
"(",
"obj",
")",
";",
"}",
"resolve",
"(",
"rotations",
")",
";",
"}",
")",
";",
"}"
] | Gets upcoming rotations | [
"Gets",
"upcoming",
"rotations"
] | 71af4973e1d079f09b7d888b6d24735784185942 | https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/apis/distraction/spotlight.js#L122-L144 | train |
|
primus/deumdify | index.js | prune | function prune(code) {
var ast = esprima.parse(code);
estraverse.replace(ast, {
leave: function leave(node, parent) {
var ret;
if ('IfStatement' === node.type) {
if ('BinaryExpression' !== node.test.type) return;
if ('self' === node.test.left.argument.name) {
node.alternate = null;
} else if ('global' === node.test.left.argument.name) {
ret = node.alternate;
}
return ret;
}
if (
'BlockStatement' === node.type
&& 'FunctionExpression' === parent.type
) {
return node.body[0].alternate.alternate;
}
}
});
return escodegen.generate(ast, {
format: {
indent: { style: ' ' },
semicolons: false,
compact: true
}
});
} | javascript | function prune(code) {
var ast = esprima.parse(code);
estraverse.replace(ast, {
leave: function leave(node, parent) {
var ret;
if ('IfStatement' === node.type) {
if ('BinaryExpression' !== node.test.type) return;
if ('self' === node.test.left.argument.name) {
node.alternate = null;
} else if ('global' === node.test.left.argument.name) {
ret = node.alternate;
}
return ret;
}
if (
'BlockStatement' === node.type
&& 'FunctionExpression' === parent.type
) {
return node.body[0].alternate.alternate;
}
}
});
return escodegen.generate(ast, {
format: {
indent: { style: ' ' },
semicolons: false,
compact: true
}
});
} | [
"function",
"prune",
"(",
"code",
")",
"{",
"var",
"ast",
"=",
"esprima",
".",
"parse",
"(",
"code",
")",
";",
"estraverse",
".",
"replace",
"(",
"ast",
",",
"{",
"leave",
":",
"function",
"leave",
"(",
"node",
",",
"parent",
")",
"{",
"var",
"ret",
";",
"if",
"(",
"'IfStatement'",
"===",
"node",
".",
"type",
")",
"{",
"if",
"(",
"'BinaryExpression'",
"!==",
"node",
".",
"test",
".",
"type",
")",
"return",
";",
"if",
"(",
"'self'",
"===",
"node",
".",
"test",
".",
"left",
".",
"argument",
".",
"name",
")",
"{",
"node",
".",
"alternate",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"'global'",
"===",
"node",
".",
"test",
".",
"left",
".",
"argument",
".",
"name",
")",
"{",
"ret",
"=",
"node",
".",
"alternate",
";",
"}",
"return",
"ret",
";",
"}",
"if",
"(",
"'BlockStatement'",
"===",
"node",
".",
"type",
"&&",
"'FunctionExpression'",
"===",
"parent",
".",
"type",
")",
"{",
"return",
"node",
".",
"body",
"[",
"0",
"]",
".",
"alternate",
".",
"alternate",
";",
"}",
"}",
"}",
")",
";",
"return",
"escodegen",
".",
"generate",
"(",
"ast",
",",
"{",
"format",
":",
"{",
"indent",
":",
"{",
"style",
":",
"' '",
"}",
",",
"semicolons",
":",
"false",
",",
"compact",
":",
"true",
"}",
"}",
")",
";",
"}"
] | Prune unwanted branches from the given source code.
@param {String} code Source code to prune
@returns {String} Pruned source code
@api private | [
"Prune",
"unwanted",
"branches",
"from",
"the",
"given",
"source",
"code",
"."
] | 3a6ca83742a0d984ed9c5ca0d992366fa19805f6 | https://github.com/primus/deumdify/blob/3a6ca83742a0d984ed9c5ca0d992366fa19805f6/index.js#L20-L55 | train |
primus/deumdify | index.js | createStream | function createStream() {
var firstChunk = true;
var stream = through(function transform(chunk, encoding, next) {
if (!firstChunk) return next(null, chunk);
firstChunk = false;
var regex = /^(.+?)(\(function\(\)\{)/
, pattern;
chunk = chunk.toString().replace(regex, function replacer(match, p1, p2) {
pattern = p1;
return p2;
});
this.push(prune(pattern) + chunk);
next();
});
stream.label = 'prune-umd';
return stream;
} | javascript | function createStream() {
var firstChunk = true;
var stream = through(function transform(chunk, encoding, next) {
if (!firstChunk) return next(null, chunk);
firstChunk = false;
var regex = /^(.+?)(\(function\(\)\{)/
, pattern;
chunk = chunk.toString().replace(regex, function replacer(match, p1, p2) {
pattern = p1;
return p2;
});
this.push(prune(pattern) + chunk);
next();
});
stream.label = 'prune-umd';
return stream;
} | [
"function",
"createStream",
"(",
")",
"{",
"var",
"firstChunk",
"=",
"true",
";",
"var",
"stream",
"=",
"through",
"(",
"function",
"transform",
"(",
"chunk",
",",
"encoding",
",",
"next",
")",
"{",
"if",
"(",
"!",
"firstChunk",
")",
"return",
"next",
"(",
"null",
",",
"chunk",
")",
";",
"firstChunk",
"=",
"false",
";",
"var",
"regex",
"=",
"/",
"^(.+?)(\\(function\\(\\)\\{)",
"/",
",",
"pattern",
";",
"chunk",
"=",
"chunk",
".",
"toString",
"(",
")",
".",
"replace",
"(",
"regex",
",",
"function",
"replacer",
"(",
"match",
",",
"p1",
",",
"p2",
")",
"{",
"pattern",
"=",
"p1",
";",
"return",
"p2",
";",
"}",
")",
";",
"this",
".",
"push",
"(",
"prune",
"(",
"pattern",
")",
"+",
"chunk",
")",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"stream",
".",
"label",
"=",
"'prune-umd'",
";",
"return",
"stream",
";",
"}"
] | Create a transform stream.
@returns {Stream} Transform stream
@api private | [
"Create",
"a",
"transform",
"stream",
"."
] | 3a6ca83742a0d984ed9c5ca0d992366fa19805f6 | https://github.com/primus/deumdify/blob/3a6ca83742a0d984ed9c5ca0d992366fa19805f6/index.js#L63-L85 | train |
primus/deumdify | index.js | deumdify | function deumdify(browserify) {
//
// Bail out if there is no UMD wrapper.
//
if (!browserify._options.standalone) return;
browserify.pipeline.push(createStream());
browserify.on('reset', function reset() {
browserify.pipeline.push(createStream());
});
} | javascript | function deumdify(browserify) {
//
// Bail out if there is no UMD wrapper.
//
if (!browserify._options.standalone) return;
browserify.pipeline.push(createStream());
browserify.on('reset', function reset() {
browserify.pipeline.push(createStream());
});
} | [
"function",
"deumdify",
"(",
"browserify",
")",
"{",
"if",
"(",
"!",
"browserify",
".",
"_options",
".",
"standalone",
")",
"return",
";",
"browserify",
".",
"pipeline",
".",
"push",
"(",
"createStream",
"(",
")",
")",
";",
"browserify",
".",
"on",
"(",
"'reset'",
",",
"function",
"reset",
"(",
")",
"{",
"browserify",
".",
"pipeline",
".",
"push",
"(",
"createStream",
"(",
")",
")",
";",
"}",
")",
";",
"}"
] | Prune the UMD pattern from a Browserify bundle stream.
@param {Browserify} browserify Browserify instance
@api public | [
"Prune",
"the",
"UMD",
"pattern",
"from",
"a",
"Browserify",
"bundle",
"stream",
"."
] | 3a6ca83742a0d984ed9c5ca0d992366fa19805f6 | https://github.com/primus/deumdify/blob/3a6ca83742a0d984ed9c5ca0d992366fa19805f6/index.js#L93-L103 | train |
axke/rs-api | lib/apis/distraction/raven.js | Raven | function Raven() {
/**
* Pull from the rs forums...this can easily break if they stop using the version 4 of the thread
* http://services.runescape.com/m=forum/forums.ws?75,76,387,65763383
* @returns {Promise} current viswax
* @example
* rsapi.rs.distraction.viswax.getCurrent().then(function(vis) {
* console.log(vis);
* }).catch(console.error);
*/
this.getCurrent = function() {
return new Promise(function (resolve, reject) {
let spawned = false;
let daysUntilNext = 0;
let found = (((Math.floor((Date.now() / 1000) / (24 * 60 * 60))) + 7) % 13);
if (found < 1) {
daysUntilNext = 1 - found;
spawned = true;
}
else {
daysUntilNext = 13 - found;
spawned = false;
}
resolve({
isSpawned: spawned,
daysUntilNext: daysUntilNext
});
});
}
} | javascript | function Raven() {
/**
* Pull from the rs forums...this can easily break if they stop using the version 4 of the thread
* http://services.runescape.com/m=forum/forums.ws?75,76,387,65763383
* @returns {Promise} current viswax
* @example
* rsapi.rs.distraction.viswax.getCurrent().then(function(vis) {
* console.log(vis);
* }).catch(console.error);
*/
this.getCurrent = function() {
return new Promise(function (resolve, reject) {
let spawned = false;
let daysUntilNext = 0;
let found = (((Math.floor((Date.now() / 1000) / (24 * 60 * 60))) + 7) % 13);
if (found < 1) {
daysUntilNext = 1 - found;
spawned = true;
}
else {
daysUntilNext = 13 - found;
spawned = false;
}
resolve({
isSpawned: spawned,
daysUntilNext: daysUntilNext
});
});
}
} | [
"function",
"Raven",
"(",
")",
"{",
"this",
".",
"getCurrent",
"=",
"function",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"let",
"spawned",
"=",
"false",
";",
"let",
"daysUntilNext",
"=",
"0",
";",
"let",
"found",
"=",
"(",
"(",
"(",
"Math",
".",
"floor",
"(",
"(",
"Date",
".",
"now",
"(",
")",
"/",
"1000",
")",
"/",
"(",
"24",
"*",
"60",
"*",
"60",
")",
")",
")",
"+",
"7",
")",
"%",
"13",
")",
";",
"if",
"(",
"found",
"<",
"1",
")",
"{",
"daysUntilNext",
"=",
"1",
"-",
"found",
";",
"spawned",
"=",
"true",
";",
"}",
"else",
"{",
"daysUntilNext",
"=",
"13",
"-",
"found",
";",
"spawned",
"=",
"false",
";",
"}",
"resolve",
"(",
"{",
"isSpawned",
":",
"spawned",
",",
"daysUntilNext",
":",
"daysUntilNext",
"}",
")",
";",
"}",
")",
";",
"}",
"}"
] | Module containing Raven functions
@module Raven | [
"Module",
"containing",
"Raven",
"functions"
] | 71af4973e1d079f09b7d888b6d24735784185942 | https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/apis/distraction/raven.js#L10-L43 | train |
LaunchPadLab/lp-redux-api | src/handlers/handle-failure.js | handleFailure | function handleFailure (handler) {
return (state, action) => isFailureAction(action) ? handler(state, action, getDataFromAction(action)) : state
} | javascript | function handleFailure (handler) {
return (state, action) => isFailureAction(action) ? handler(state, action, getDataFromAction(action)) : state
} | [
"function",
"handleFailure",
"(",
"handler",
")",
"{",
"return",
"(",
"state",
",",
"action",
")",
"=>",
"isFailureAction",
"(",
"action",
")",
"?",
"handler",
"(",
"state",
",",
"action",
",",
"getDataFromAction",
"(",
"action",
")",
")",
":",
"state",
"}"
] | A function that takes an API action handler and only applies that handler when the request fails.
@name handleFailure
@param {Function} handler - An action handler that is passed `state`, `action` and `data` params
@returns {Function} An action handler that runs when a request is unsuccessful
@example
handleActions({
[apiActions.fetchUser]: handleFailure((state, action) => {
// This code only runs when the call was unsuccessful
return set('userFetchError', action.payload.data, state)
})
}) | [
"A",
"function",
"that",
"takes",
"an",
"API",
"action",
"handler",
"and",
"only",
"applies",
"that",
"handler",
"when",
"the",
"request",
"fails",
"."
] | 73eee231067365326780ddc1dbbfa50d3e65defc | https://github.com/LaunchPadLab/lp-redux-api/blob/73eee231067365326780ddc1dbbfa50d3e65defc/src/handlers/handle-failure.js#L20-L22 | train |
simonepri/phc-scrypt | index.js | hash | function hash(password, options) {
options = options || {};
const blocksize = options.blocksize || defaults.blocksize;
const cost = options.cost || defaults.cost;
const parallelism = options.parallelism || defaults.parallelism;
const saltSize = options.saltSize || defaults.saltSize;
// Blocksize Validation
if (typeof blocksize !== 'number' || !Number.isInteger(blocksize)) {
return Promise.reject(
new TypeError("The 'blocksize' option must be an integer")
);
}
if (blocksize < 1 || blocksize > MAX_UINT32) {
return Promise.reject(
new TypeError(
`The 'blocksize' option must be in the range (1 <= blocksize <= ${MAX_UINT32})`
)
);
}
// Cost Validation
if (typeof cost !== 'number' || !Number.isInteger(cost)) {
return Promise.reject(
new TypeError("The 'cost' option must be an integer")
);
}
const maxcost = (128 * blocksize) / 8 - 1;
if (cost < 2 || cost > maxcost) {
return Promise.reject(
new TypeError(
`The 'cost' option must be in the range (1 <= cost <= ${maxcost})`
)
);
}
// Parallelism Validation
if (typeof parallelism !== 'number' || !Number.isInteger(parallelism)) {
return Promise.reject(
new TypeError("The 'parallelism' option must be an integer")
);
}
const maxpar = Math.floor(((Math.pow(2, 32) - 1) * 32) / (128 * blocksize));
if (parallelism < 1 || parallelism > maxpar) {
return Promise.reject(
new TypeError(
`The 'parallelism' option must be in the range (1 <= parallelism <= ${maxpar})`
)
);
}
// Salt Size Validation
if (saltSize < 8 || saltSize > 1024) {
return Promise.reject(
new TypeError(
"The 'saltSize' option must be in the range (8 <= saltSize <= 1023)"
)
);
}
const params = {
N: Math.pow(2, cost),
r: blocksize,
p: parallelism
};
const keylen = 32;
return gensalt(saltSize).then(salt => {
return scrypt.hash(password, params, keylen, salt).then(hash => {
const phcstr = phc.serialize({
id: 'scrypt',
params: {
ln: cost,
r: blocksize,
p: parallelism
},
salt,
hash
});
return phcstr;
});
});
} | javascript | function hash(password, options) {
options = options || {};
const blocksize = options.blocksize || defaults.blocksize;
const cost = options.cost || defaults.cost;
const parallelism = options.parallelism || defaults.parallelism;
const saltSize = options.saltSize || defaults.saltSize;
// Blocksize Validation
if (typeof blocksize !== 'number' || !Number.isInteger(blocksize)) {
return Promise.reject(
new TypeError("The 'blocksize' option must be an integer")
);
}
if (blocksize < 1 || blocksize > MAX_UINT32) {
return Promise.reject(
new TypeError(
`The 'blocksize' option must be in the range (1 <= blocksize <= ${MAX_UINT32})`
)
);
}
// Cost Validation
if (typeof cost !== 'number' || !Number.isInteger(cost)) {
return Promise.reject(
new TypeError("The 'cost' option must be an integer")
);
}
const maxcost = (128 * blocksize) / 8 - 1;
if (cost < 2 || cost > maxcost) {
return Promise.reject(
new TypeError(
`The 'cost' option must be in the range (1 <= cost <= ${maxcost})`
)
);
}
// Parallelism Validation
if (typeof parallelism !== 'number' || !Number.isInteger(parallelism)) {
return Promise.reject(
new TypeError("The 'parallelism' option must be an integer")
);
}
const maxpar = Math.floor(((Math.pow(2, 32) - 1) * 32) / (128 * blocksize));
if (parallelism < 1 || parallelism > maxpar) {
return Promise.reject(
new TypeError(
`The 'parallelism' option must be in the range (1 <= parallelism <= ${maxpar})`
)
);
}
// Salt Size Validation
if (saltSize < 8 || saltSize > 1024) {
return Promise.reject(
new TypeError(
"The 'saltSize' option must be in the range (8 <= saltSize <= 1023)"
)
);
}
const params = {
N: Math.pow(2, cost),
r: blocksize,
p: parallelism
};
const keylen = 32;
return gensalt(saltSize).then(salt => {
return scrypt.hash(password, params, keylen, salt).then(hash => {
const phcstr = phc.serialize({
id: 'scrypt',
params: {
ln: cost,
r: blocksize,
p: parallelism
},
salt,
hash
});
return phcstr;
});
});
} | [
"function",
"hash",
"(",
"password",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"const",
"blocksize",
"=",
"options",
".",
"blocksize",
"||",
"defaults",
".",
"blocksize",
";",
"const",
"cost",
"=",
"options",
".",
"cost",
"||",
"defaults",
".",
"cost",
";",
"const",
"parallelism",
"=",
"options",
".",
"parallelism",
"||",
"defaults",
".",
"parallelism",
";",
"const",
"saltSize",
"=",
"options",
".",
"saltSize",
"||",
"defaults",
".",
"saltSize",
";",
"if",
"(",
"typeof",
"blocksize",
"!==",
"'number'",
"||",
"!",
"Number",
".",
"isInteger",
"(",
"blocksize",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"\"The 'blocksize' option must be an integer\"",
")",
")",
";",
"}",
"if",
"(",
"blocksize",
"<",
"1",
"||",
"blocksize",
">",
"MAX_UINT32",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"`",
"${",
"MAX_UINT32",
"}",
"`",
")",
")",
";",
"}",
"if",
"(",
"typeof",
"cost",
"!==",
"'number'",
"||",
"!",
"Number",
".",
"isInteger",
"(",
"cost",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"\"The 'cost' option must be an integer\"",
")",
")",
";",
"}",
"const",
"maxcost",
"=",
"(",
"128",
"*",
"blocksize",
")",
"/",
"8",
"-",
"1",
";",
"if",
"(",
"cost",
"<",
"2",
"||",
"cost",
">",
"maxcost",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"`",
"${",
"maxcost",
"}",
"`",
")",
")",
";",
"}",
"if",
"(",
"typeof",
"parallelism",
"!==",
"'number'",
"||",
"!",
"Number",
".",
"isInteger",
"(",
"parallelism",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"\"The 'parallelism' option must be an integer\"",
")",
")",
";",
"}",
"const",
"maxpar",
"=",
"Math",
".",
"floor",
"(",
"(",
"(",
"Math",
".",
"pow",
"(",
"2",
",",
"32",
")",
"-",
"1",
")",
"*",
"32",
")",
"/",
"(",
"128",
"*",
"blocksize",
")",
")",
";",
"if",
"(",
"parallelism",
"<",
"1",
"||",
"parallelism",
">",
"maxpar",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"`",
"${",
"maxpar",
"}",
"`",
")",
")",
";",
"}",
"if",
"(",
"saltSize",
"<",
"8",
"||",
"saltSize",
">",
"1024",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"\"The 'saltSize' option must be in the range (8 <= saltSize <= 1023)\"",
")",
")",
";",
"}",
"const",
"params",
"=",
"{",
"N",
":",
"Math",
".",
"pow",
"(",
"2",
",",
"cost",
")",
",",
"r",
":",
"blocksize",
",",
"p",
":",
"parallelism",
"}",
";",
"const",
"keylen",
"=",
"32",
";",
"return",
"gensalt",
"(",
"saltSize",
")",
".",
"then",
"(",
"salt",
"=>",
"{",
"return",
"scrypt",
".",
"hash",
"(",
"password",
",",
"params",
",",
"keylen",
",",
"salt",
")",
".",
"then",
"(",
"hash",
"=>",
"{",
"const",
"phcstr",
"=",
"phc",
".",
"serialize",
"(",
"{",
"id",
":",
"'scrypt'",
",",
"params",
":",
"{",
"ln",
":",
"cost",
",",
"r",
":",
"blocksize",
",",
"p",
":",
"parallelism",
"}",
",",
"salt",
",",
"hash",
"}",
")",
";",
"return",
"phcstr",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Computes the hash string of the given password in the PHC format using scrypt
package.
@public
@param {string} password The password to hash.
@param {Object} [options] Optional configurations related to the hashing
function.
@param {number} [options.blocksize=8] Optional amount of memory to use in
kibibytes.
Must be an integer within the range (`8` <= `memory` <= `2^32-1`).
@param {number} [options.cost=15] Optional CPU/memory cost parameter.
Must be an integer power of 2 within the range
(`2` <= `cost` <= `2^((128 * blocksize) / 8) - 1`).
@param {number} [options.parallelism=1] Optional degree of parallelism to
use.
Must be an integer within the range
(`1` <= `parallelism` <= `((2^32-1) * 32) / (128 * blocksize)`).
@return {Promise.<string>} The generated secure hash string in the PHC
format. | [
"Computes",
"the",
"hash",
"string",
"of",
"the",
"given",
"password",
"in",
"the",
"PHC",
"format",
"using",
"scrypt",
"package",
"."
] | c3fa7b360864135af4075fa448de3ed07be5a5a1 | https://github.com/simonepri/phc-scrypt/blob/c3fa7b360864135af4075fa448de3ed07be5a5a1/index.js#L47-L129 | train |
bholloway/persistent-cache-webpack-plugin | lib/application-classes.js | getName | function getName(candidate) {
var proto = getProto(candidate),
isValid = !!proto && !isPlainObject(candidate) && !Array.isArray(candidate);
if (isValid) {
for (var key in require.cache) {
var exports = require.cache[key].exports,
result = isPlainObject(exports) ? Object.keys(exports).reduce(test.bind(null, key), null) : test(key);
if (result) {
return result;
}
}
}
return null;
function test(filename, result, field) {
if (result) {
return result;
} else {
var candidate = field ? exports[field] : exports,
qualified = [filename, field].filter(Boolean).join('::'),
isDefinition = (typeof candidate === 'function') && !!candidate.prototype &&
(typeof candidate.prototype === 'object') && (candidate.prototype === proto);
return isDefinition && qualified || null;
}
}
} | javascript | function getName(candidate) {
var proto = getProto(candidate),
isValid = !!proto && !isPlainObject(candidate) && !Array.isArray(candidate);
if (isValid) {
for (var key in require.cache) {
var exports = require.cache[key].exports,
result = isPlainObject(exports) ? Object.keys(exports).reduce(test.bind(null, key), null) : test(key);
if (result) {
return result;
}
}
}
return null;
function test(filename, result, field) {
if (result) {
return result;
} else {
var candidate = field ? exports[field] : exports,
qualified = [filename, field].filter(Boolean).join('::'),
isDefinition = (typeof candidate === 'function') && !!candidate.prototype &&
(typeof candidate.prototype === 'object') && (candidate.prototype === proto);
return isDefinition && qualified || null;
}
}
} | [
"function",
"getName",
"(",
"candidate",
")",
"{",
"var",
"proto",
"=",
"getProto",
"(",
"candidate",
")",
",",
"isValid",
"=",
"!",
"!",
"proto",
"&&",
"!",
"isPlainObject",
"(",
"candidate",
")",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"candidate",
")",
";",
"if",
"(",
"isValid",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"require",
".",
"cache",
")",
"{",
"var",
"exports",
"=",
"require",
".",
"cache",
"[",
"key",
"]",
".",
"exports",
",",
"result",
"=",
"isPlainObject",
"(",
"exports",
")",
"?",
"Object",
".",
"keys",
"(",
"exports",
")",
".",
"reduce",
"(",
"test",
".",
"bind",
"(",
"null",
",",
"key",
")",
",",
"null",
")",
":",
"test",
"(",
"key",
")",
";",
"if",
"(",
"result",
")",
"{",
"return",
"result",
";",
"}",
"}",
"}",
"return",
"null",
";",
"function",
"test",
"(",
"filename",
",",
"result",
",",
"field",
")",
"{",
"if",
"(",
"result",
")",
"{",
"return",
"result",
";",
"}",
"else",
"{",
"var",
"candidate",
"=",
"field",
"?",
"exports",
"[",
"field",
"]",
":",
"exports",
",",
"qualified",
"=",
"[",
"filename",
",",
"field",
"]",
".",
"filter",
"(",
"Boolean",
")",
".",
"join",
"(",
"'::'",
")",
",",
"isDefinition",
"=",
"(",
"typeof",
"candidate",
"===",
"'function'",
")",
"&&",
"!",
"!",
"candidate",
".",
"prototype",
"&&",
"(",
"typeof",
"candidate",
".",
"prototype",
"===",
"'object'",
")",
"&&",
"(",
"candidate",
".",
"prototype",
"===",
"proto",
")",
";",
"return",
"isDefinition",
"&&",
"qualified",
"||",
"null",
";",
"}",
"}",
"}"
] | Find the class name of the given instance.
@param {object} candidate A possible instance to name
@returns {string} The absolute path to the candidate definition where it is an instance or null otherwise | [
"Find",
"the",
"class",
"name",
"of",
"the",
"given",
"instance",
"."
] | bd5aec58b1b38477218dcdc0fb144c6981604fa8 | https://github.com/bholloway/persistent-cache-webpack-plugin/blob/bd5aec58b1b38477218dcdc0fb144c6981604fa8/lib/application-classes.js#L15-L40 | train |
bholloway/persistent-cache-webpack-plugin | lib/application-classes.js | getDefinition | function getDefinition(name) {
var split = name.split('::'),
path = split[0],
field = split[1],
exported = (path in require.cache) && require.cache[path].exports,
definition = !!exported && (field ? exported[field] : exported);
return !!definition && !!getProto(definition) && definition || null;
} | javascript | function getDefinition(name) {
var split = name.split('::'),
path = split[0],
field = split[1],
exported = (path in require.cache) && require.cache[path].exports,
definition = !!exported && (field ? exported[field] : exported);
return !!definition && !!getProto(definition) && definition || null;
} | [
"function",
"getDefinition",
"(",
"name",
")",
"{",
"var",
"split",
"=",
"name",
".",
"split",
"(",
"'::'",
")",
",",
"path",
"=",
"split",
"[",
"0",
"]",
",",
"field",
"=",
"split",
"[",
"1",
"]",
",",
"exported",
"=",
"(",
"path",
"in",
"require",
".",
"cache",
")",
"&&",
"require",
".",
"cache",
"[",
"path",
"]",
".",
"exports",
",",
"definition",
"=",
"!",
"!",
"exported",
"&&",
"(",
"field",
"?",
"exported",
"[",
"field",
"]",
":",
"exported",
")",
";",
"return",
"!",
"!",
"definition",
"&&",
"!",
"!",
"getProto",
"(",
"definition",
")",
"&&",
"definition",
"||",
"null",
";",
"}"
] | Get the class definition by explicit path where already in the require cache.
@param {string} name The absolute path to the file containing the class
@returns {null} | [
"Get",
"the",
"class",
"definition",
"by",
"explicit",
"path",
"where",
"already",
"in",
"the",
"require",
"cache",
"."
] | bd5aec58b1b38477218dcdc0fb144c6981604fa8 | https://github.com/bholloway/persistent-cache-webpack-plugin/blob/bd5aec58b1b38477218dcdc0fb144c6981604fa8/lib/application-classes.js#L47-L54 | train |
axke/rs-api | lib/apis/player.js | Player | function Player(config) {
/**
* Gets a users hiscores and activities (available for `rs` / `osrs`)
* @param username {String} Display name of the user
* @param type {String} [Optional] normal, ironman, hardcore/ultimate
* @returns {Promise} Object of the users hiscores and activities
* @example
* // returns Sync's RS stats and activities
* rsapi.rs.player.hiscores('sync').then(function(stats) {
* console.log(stats);
* }).catch(console.error);
*
* // returns Sausage's RS stats and activities from the ironman game type
* api.rs.hiscores.player('sausage', 'ironman').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns Sausage's RS stats and activities from the hardcore ironman game type
* api.rs.hiscores.player('sausage', 'hardcore').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns hey jase's Old School RS stats and activities
* api.osrs.hiscores.player('hey jase').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns lezley's Old School RS stats and activities from the ironman game type
* api.osrs.hiscores.player('lezley', 'ironman').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns perm iron's Old School RS stats and activities from the ultimate ironman game type
* api.osrs.hiscores.player('perm iron', 'ultimate').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*/
this.hiscores = function (username, type) {
return new Hiscores(username, config.hiscores).lookup(type);
};
/**
* Gets a users events log (aka adventure log) (available for `rs`)
* @param username {String} Display name of the user
* @returns {Promise} Object of the users events log
* @example
* // returns Sync's events / adventure log
* rsapi.rs.player.events('sync').then(function(stats) {
* console.log(stats);
* }).catch(console.error);
*/
this.events = function (username) {
return new Events(username, config.events).lookup();
}
/**
* Returns the input user(s) clan, title, if the clan is recruiting, if the title is a suffix, as well as online status
* if process.env.username and process.env.password are configured to a valid RS sign-in
* @param usernames {string|array} String of a single username or array of multiple to lookup
* @returns {Promise} Object of the users player details
* @example
* rsapi.rs.player.details(['sync','xredfoxx']).then(function(details) {
* console.log(details);
* }).catch(console.error);
*/
this.details = function (usernames) {
return new Promise(function (resolve, reject) {
var names = [];
if (typeof usernames === 'string') {
names.push(usernames);
}
else if (typeof usernames === 'object') {
names = usernames;
}
else {
var jsonError = new Error('Unrecognized input for usernames. Should be a string or array.');
reject(jsonError);
}
request.createSession().then( function(session) {
request.jsonp(config.urls.playerDetails + JSON.stringify(names), session).then(resolve).catch(reject);
}
).catch(console.error);
});
}
/**
* Return RuneMetrics profile for user
* @param usernames
* @returns {Promise} Object of the users player profile
* @example
* rsapi.rs.player.profile('sync').then(function(profile) {
* console.log(profile);
* }).catch(console.error);
*/
this.profile = function(usernames) {
return new Profile(usernames, config).lookup();
}
} | javascript | function Player(config) {
/**
* Gets a users hiscores and activities (available for `rs` / `osrs`)
* @param username {String} Display name of the user
* @param type {String} [Optional] normal, ironman, hardcore/ultimate
* @returns {Promise} Object of the users hiscores and activities
* @example
* // returns Sync's RS stats and activities
* rsapi.rs.player.hiscores('sync').then(function(stats) {
* console.log(stats);
* }).catch(console.error);
*
* // returns Sausage's RS stats and activities from the ironman game type
* api.rs.hiscores.player('sausage', 'ironman').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns Sausage's RS stats and activities from the hardcore ironman game type
* api.rs.hiscores.player('sausage', 'hardcore').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns hey jase's Old School RS stats and activities
* api.osrs.hiscores.player('hey jase').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns lezley's Old School RS stats and activities from the ironman game type
* api.osrs.hiscores.player('lezley', 'ironman').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns perm iron's Old School RS stats and activities from the ultimate ironman game type
* api.osrs.hiscores.player('perm iron', 'ultimate').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*/
this.hiscores = function (username, type) {
return new Hiscores(username, config.hiscores).lookup(type);
};
/**
* Gets a users events log (aka adventure log) (available for `rs`)
* @param username {String} Display name of the user
* @returns {Promise} Object of the users events log
* @example
* // returns Sync's events / adventure log
* rsapi.rs.player.events('sync').then(function(stats) {
* console.log(stats);
* }).catch(console.error);
*/
this.events = function (username) {
return new Events(username, config.events).lookup();
}
/**
* Returns the input user(s) clan, title, if the clan is recruiting, if the title is a suffix, as well as online status
* if process.env.username and process.env.password are configured to a valid RS sign-in
* @param usernames {string|array} String of a single username or array of multiple to lookup
* @returns {Promise} Object of the users player details
* @example
* rsapi.rs.player.details(['sync','xredfoxx']).then(function(details) {
* console.log(details);
* }).catch(console.error);
*/
this.details = function (usernames) {
return new Promise(function (resolve, reject) {
var names = [];
if (typeof usernames === 'string') {
names.push(usernames);
}
else if (typeof usernames === 'object') {
names = usernames;
}
else {
var jsonError = new Error('Unrecognized input for usernames. Should be a string or array.');
reject(jsonError);
}
request.createSession().then( function(session) {
request.jsonp(config.urls.playerDetails + JSON.stringify(names), session).then(resolve).catch(reject);
}
).catch(console.error);
});
}
/**
* Return RuneMetrics profile for user
* @param usernames
* @returns {Promise} Object of the users player profile
* @example
* rsapi.rs.player.profile('sync').then(function(profile) {
* console.log(profile);
* }).catch(console.error);
*/
this.profile = function(usernames) {
return new Profile(usernames, config).lookup();
}
} | [
"function",
"Player",
"(",
"config",
")",
"{",
"this",
".",
"hiscores",
"=",
"function",
"(",
"username",
",",
"type",
")",
"{",
"return",
"new",
"Hiscores",
"(",
"username",
",",
"config",
".",
"hiscores",
")",
".",
"lookup",
"(",
"type",
")",
";",
"}",
";",
"this",
".",
"events",
"=",
"function",
"(",
"username",
")",
"{",
"return",
"new",
"Events",
"(",
"username",
",",
"config",
".",
"events",
")",
".",
"lookup",
"(",
")",
";",
"}",
"this",
".",
"details",
"=",
"function",
"(",
"usernames",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"names",
"=",
"[",
"]",
";",
"if",
"(",
"typeof",
"usernames",
"===",
"'string'",
")",
"{",
"names",
".",
"push",
"(",
"usernames",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"usernames",
"===",
"'object'",
")",
"{",
"names",
"=",
"usernames",
";",
"}",
"else",
"{",
"var",
"jsonError",
"=",
"new",
"Error",
"(",
"'Unrecognized input for usernames. Should be a string or array.'",
")",
";",
"reject",
"(",
"jsonError",
")",
";",
"}",
"request",
".",
"createSession",
"(",
")",
".",
"then",
"(",
"function",
"(",
"session",
")",
"{",
"request",
".",
"jsonp",
"(",
"config",
".",
"urls",
".",
"playerDetails",
"+",
"JSON",
".",
"stringify",
"(",
"names",
")",
",",
"session",
")",
".",
"then",
"(",
"resolve",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
".",
"catch",
"(",
"console",
".",
"error",
")",
";",
"}",
")",
";",
"}",
"this",
".",
"profile",
"=",
"function",
"(",
"usernames",
")",
"{",
"return",
"new",
"Profile",
"(",
"usernames",
",",
"config",
")",
".",
"lookup",
"(",
")",
";",
"}",
"}"
] | Module containing Player functions
@module Player | [
"Module",
"containing",
"Player",
"functions"
] | 71af4973e1d079f09b7d888b6d24735784185942 | https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/apis/player.js#L13-L112 | train |
mysticatea/eslint4b | scripts/rollup-plugin/replace.js | toAbsolute | function toAbsolute(id) {
return id.startsWith("./") ? path.resolve(id) : require.resolve(id)
} | javascript | function toAbsolute(id) {
return id.startsWith("./") ? path.resolve(id) : require.resolve(id)
} | [
"function",
"toAbsolute",
"(",
"id",
")",
"{",
"return",
"id",
".",
"startsWith",
"(",
"\"./\"",
")",
"?",
"path",
".",
"resolve",
"(",
"id",
")",
":",
"require",
".",
"resolve",
"(",
"id",
")",
"}"
] | Convert a given moduleId to an absolute path.
@param {string} id The moduleId to normalize.
@returns {string} The normalized path. | [
"Convert",
"a",
"given",
"moduleId",
"to",
"an",
"absolute",
"path",
"."
] | e0ecf68565c252210131c2418437765bc2d8b641 | https://github.com/mysticatea/eslint4b/blob/e0ecf68565c252210131c2418437765bc2d8b641/scripts/rollup-plugin/replace.js#L12-L14 | train |
LaunchPadLab/lp-redux-api | src/selectors.js | stripNamespace | function stripNamespace (requestKey) {
return requestKey.startsWith(LP_API_ACTION_NAMESPACE)
? requestKey.slice(LP_API_ACTION_NAMESPACE.length)
: requestKey
} | javascript | function stripNamespace (requestKey) {
return requestKey.startsWith(LP_API_ACTION_NAMESPACE)
? requestKey.slice(LP_API_ACTION_NAMESPACE.length)
: requestKey
} | [
"function",
"stripNamespace",
"(",
"requestKey",
")",
"{",
"return",
"requestKey",
".",
"startsWith",
"(",
"LP_API_ACTION_NAMESPACE",
")",
"?",
"requestKey",
".",
"slice",
"(",
"LP_API_ACTION_NAMESPACE",
".",
"length",
")",
":",
"requestKey",
"}"
] | Remove action namespace if it's at the beginning | [
"Remove",
"action",
"namespace",
"if",
"it",
"s",
"at",
"the",
"beginning"
] | 73eee231067365326780ddc1dbbfa50d3e65defc | https://github.com/LaunchPadLab/lp-redux-api/blob/73eee231067365326780ddc1dbbfa50d3e65defc/src/selectors.js#L54-L58 | train |
jonschlinkert/deep-bind | index.js | deepBind | function deepBind(target, thisArg, options) {
if (!isObject(target)) {
throw new TypeError('expected an object');
}
options = options || {};
for (var key in target) {
var fn = target[key];
if (typeof fn === 'object') {
target[key] = deepBind(fn, thisArg);
} else if (typeof fn === 'function') {
target[key] = bind(thisArg, key, fn, options);
// copy function keys
for (var k in fn) {
target[key][k] = fn[k];
}
} else {
target[key] = fn;
}
}
return target;
} | javascript | function deepBind(target, thisArg, options) {
if (!isObject(target)) {
throw new TypeError('expected an object');
}
options = options || {};
for (var key in target) {
var fn = target[key];
if (typeof fn === 'object') {
target[key] = deepBind(fn, thisArg);
} else if (typeof fn === 'function') {
target[key] = bind(thisArg, key, fn, options);
// copy function keys
for (var k in fn) {
target[key][k] = fn[k];
}
} else {
target[key] = fn;
}
}
return target;
} | [
"function",
"deepBind",
"(",
"target",
",",
"thisArg",
",",
"options",
")",
"{",
"if",
"(",
"!",
"isObject",
"(",
"target",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'expected an object'",
")",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"target",
")",
"{",
"var",
"fn",
"=",
"target",
"[",
"key",
"]",
";",
"if",
"(",
"typeof",
"fn",
"===",
"'object'",
")",
"{",
"target",
"[",
"key",
"]",
"=",
"deepBind",
"(",
"fn",
",",
"thisArg",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"fn",
"===",
"'function'",
")",
"{",
"target",
"[",
"key",
"]",
"=",
"bind",
"(",
"thisArg",
",",
"key",
",",
"fn",
",",
"options",
")",
";",
"for",
"(",
"var",
"k",
"in",
"fn",
")",
"{",
"target",
"[",
"key",
"]",
"[",
"k",
"]",
"=",
"fn",
"[",
"k",
"]",
";",
"}",
"}",
"else",
"{",
"target",
"[",
"key",
"]",
"=",
"fn",
";",
"}",
"}",
"return",
"target",
";",
"}"
] | Bind a `thisArg` to all the functions on the target
@param {Object|Array} `target` Object or Array with functions as values that will be bound.
@param {Object} `thisArg` Object to bind to the functions
@return {Object|Array} Object or Array with bound functions.
@api public | [
"Bind",
"a",
"thisArg",
"to",
"all",
"the",
"functions",
"on",
"the",
"target"
] | c654562afd3712add9d41ec02cabdb5c45e99a0b | https://github.com/jonschlinkert/deep-bind/blob/c654562afd3712add9d41ec02cabdb5c45e99a0b/index.js#L14-L38 | train |
LaunchPadLab/lp-redux-api | src/handlers/handle-response.js | handleResponse | function handleResponse (successHandler, failureHandler) {
if (!(successHandler && failureHandler)) throw new Error('handleResponse requires both a success handler and failure handler.')
return (state, action) => {
if (isSuccessAction(action)) return successHandler(state, action, getDataFromAction(action))
if (isFailureAction(action)) return failureHandler(state, action, getDataFromAction(action))
return state
}
} | javascript | function handleResponse (successHandler, failureHandler) {
if (!(successHandler && failureHandler)) throw new Error('handleResponse requires both a success handler and failure handler.')
return (state, action) => {
if (isSuccessAction(action)) return successHandler(state, action, getDataFromAction(action))
if (isFailureAction(action)) return failureHandler(state, action, getDataFromAction(action))
return state
}
} | [
"function",
"handleResponse",
"(",
"successHandler",
",",
"failureHandler",
")",
"{",
"if",
"(",
"!",
"(",
"successHandler",
"&&",
"failureHandler",
")",
")",
"throw",
"new",
"Error",
"(",
"'handleResponse requires both a success handler and failure handler.'",
")",
"return",
"(",
"state",
",",
"action",
")",
"=>",
"{",
"if",
"(",
"isSuccessAction",
"(",
"action",
")",
")",
"return",
"successHandler",
"(",
"state",
",",
"action",
",",
"getDataFromAction",
"(",
"action",
")",
")",
"if",
"(",
"isFailureAction",
"(",
"action",
")",
")",
"return",
"failureHandler",
"(",
"state",
",",
"action",
",",
"getDataFromAction",
"(",
"action",
")",
")",
"return",
"state",
"}",
"}"
] | A function that takes two API action handlers, one for successful requests and one for failed requests,
and applies the handlers when the responses have the correct status.
@name handleResponse
@param {Function} successHandler - An action handler that is passed `state`, `action` and `data` params
@param {Function} failureHandler - An action handler that is passed `state`, `action` and `data` params
@returns {Function} An action handler runs the handler that corresponds to the request status
@example
handleActions({
[apiActions.fetchUser]: handleResponse(
(state, action) => {
// This code runs if the call is successful
return set('currentUser', action.payload.data, state)
},
(state, action) => {
// This code runs if the call is unsuccessful
return set('userFetchError', action.payload.data, state)
},
)
}) | [
"A",
"function",
"that",
"takes",
"two",
"API",
"action",
"handlers",
"one",
"for",
"successful",
"requests",
"and",
"one",
"for",
"failed",
"requests",
"and",
"applies",
"the",
"handlers",
"when",
"the",
"responses",
"have",
"the",
"correct",
"status",
"."
] | 73eee231067365326780ddc1dbbfa50d3e65defc | https://github.com/LaunchPadLab/lp-redux-api/blob/73eee231067365326780ddc1dbbfa50d3e65defc/src/handlers/handle-response.js#L28-L35 | train |
almost/string-replace-stream | string-replace-stream.js | buildTable | function buildTable(search) {
// Based on https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm#Description_of_pseudocode_for_the_table-building_algorithm
var table = Array(search.length), pos = 2, cnd = 0, searchLen = search.length;
table[0] = -1;
table[1] = 0;
while (pos < searchLen) {
if (search[pos-1] === search[cnd]) {
// the substring continues
cnd++;
table[pos] = cnd;
pos++;
} else if (cnd > 0) {
// it doesn't, but we can fall back
cnd = table[cnd];
} else {
// we have run part of candidates. Note cnd = 0
table[pos] = 0;
pos++;
}
}
return table;
} | javascript | function buildTable(search) {
// Based on https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm#Description_of_pseudocode_for_the_table-building_algorithm
var table = Array(search.length), pos = 2, cnd = 0, searchLen = search.length;
table[0] = -1;
table[1] = 0;
while (pos < searchLen) {
if (search[pos-1] === search[cnd]) {
// the substring continues
cnd++;
table[pos] = cnd;
pos++;
} else if (cnd > 0) {
// it doesn't, but we can fall back
cnd = table[cnd];
} else {
// we have run part of candidates. Note cnd = 0
table[pos] = 0;
pos++;
}
}
return table;
} | [
"function",
"buildTable",
"(",
"search",
")",
"{",
"var",
"table",
"=",
"Array",
"(",
"search",
".",
"length",
")",
",",
"pos",
"=",
"2",
",",
"cnd",
"=",
"0",
",",
"searchLen",
"=",
"search",
".",
"length",
";",
"table",
"[",
"0",
"]",
"=",
"-",
"1",
";",
"table",
"[",
"1",
"]",
"=",
"0",
";",
"while",
"(",
"pos",
"<",
"searchLen",
")",
"{",
"if",
"(",
"search",
"[",
"pos",
"-",
"1",
"]",
"===",
"search",
"[",
"cnd",
"]",
")",
"{",
"cnd",
"++",
";",
"table",
"[",
"pos",
"]",
"=",
"cnd",
";",
"pos",
"++",
";",
"}",
"else",
"if",
"(",
"cnd",
">",
"0",
")",
"{",
"cnd",
"=",
"table",
"[",
"cnd",
"]",
";",
"}",
"else",
"{",
"table",
"[",
"pos",
"]",
"=",
"0",
";",
"pos",
"++",
";",
"}",
"}",
"return",
"table",
";",
"}"
] | Build the Knuth-Morris-Pratt table | [
"Build",
"the",
"Knuth",
"-",
"Morris",
"-",
"Pratt",
"table"
] | f47cdfa8b0acbe27cf82685c0a4343df7a47bd73 | https://github.com/almost/string-replace-stream/blob/f47cdfa8b0acbe27cf82685c0a4343df7a47bd73/string-replace-stream.js#L8-L29 | train |
lvhaohua/react-candee | src/actions.js | actionCreator | function actionCreator(modelName, actionName) {
return data => (
dispatch({
type: getFullTypeName(modelName, actionName),
data
})
)
} | javascript | function actionCreator(modelName, actionName) {
return data => (
dispatch({
type: getFullTypeName(modelName, actionName),
data
})
)
} | [
"function",
"actionCreator",
"(",
"modelName",
",",
"actionName",
")",
"{",
"return",
"data",
"=>",
"(",
"dispatch",
"(",
"{",
"type",
":",
"getFullTypeName",
"(",
"modelName",
",",
"actionName",
")",
",",
"data",
"}",
")",
")",
"}"
] | auto dispatch action | [
"auto",
"dispatch",
"action"
] | d93d05e5dee580a547d9732c7f8157dace0b4eb6 | https://github.com/lvhaohua/react-candee/blob/d93d05e5dee580a547d9732c7f8157dace0b4eb6/src/actions.js#L8-L15 | train |
oskargustafsson/BFF | src/event-listener.js | function (eventEmitters, eventNames, callback, context, useCapture) {
if (RUNTIME_CHECKS) {
if (!eventEmitters || !(eventEmitters.addEventListener || eventEmitters instanceof Array)) {
throw '"eventEmitters" argument must be an event emitter or an array of event emitters';
}
if (typeof eventNames !== 'string' && !(eventNames instanceof Array)) {
throw '"eventNames" argument must be a string or an array of strings';
}
if (typeof callback !== 'function') {
throw '"callback" argument must be a function';
}
if (arguments.length > 4 && typeof useCapture !== 'boolean') {
throw '"useCapture" argument must be a boolean value';
}
}
// Convenience functionality that allows you to listen to all items in an Array or NodeList
// BFF Lists have this kind of functionality built it, so don't handle that case here
eventEmitters = eventEmitters instanceof Array ||
(typeof NodeList !== 'undefined' && eventEmitters instanceof NodeList) ? eventEmitters : [ eventEmitters ];
eventNames = eventNames instanceof Array ? eventNames : [ eventNames ];
for (var i = 0; i < eventEmitters.length; ++i) {
for (var j = 0; j < eventNames.length; ++j) {
setupListeners(this, eventEmitters[i], eventNames[j], callback, context, !!useCapture);
}
}
} | javascript | function (eventEmitters, eventNames, callback, context, useCapture) {
if (RUNTIME_CHECKS) {
if (!eventEmitters || !(eventEmitters.addEventListener || eventEmitters instanceof Array)) {
throw '"eventEmitters" argument must be an event emitter or an array of event emitters';
}
if (typeof eventNames !== 'string' && !(eventNames instanceof Array)) {
throw '"eventNames" argument must be a string or an array of strings';
}
if (typeof callback !== 'function') {
throw '"callback" argument must be a function';
}
if (arguments.length > 4 && typeof useCapture !== 'boolean') {
throw '"useCapture" argument must be a boolean value';
}
}
// Convenience functionality that allows you to listen to all items in an Array or NodeList
// BFF Lists have this kind of functionality built it, so don't handle that case here
eventEmitters = eventEmitters instanceof Array ||
(typeof NodeList !== 'undefined' && eventEmitters instanceof NodeList) ? eventEmitters : [ eventEmitters ];
eventNames = eventNames instanceof Array ? eventNames : [ eventNames ];
for (var i = 0; i < eventEmitters.length; ++i) {
for (var j = 0; j < eventNames.length; ++j) {
setupListeners(this, eventEmitters[i], eventNames[j], callback, context, !!useCapture);
}
}
} | [
"function",
"(",
"eventEmitters",
",",
"eventNames",
",",
"callback",
",",
"context",
",",
"useCapture",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
")",
"{",
"if",
"(",
"!",
"eventEmitters",
"||",
"!",
"(",
"eventEmitters",
".",
"addEventListener",
"||",
"eventEmitters",
"instanceof",
"Array",
")",
")",
"{",
"throw",
"'\"eventEmitters\" argument must be an event emitter or an array of event emitters'",
";",
"}",
"if",
"(",
"typeof",
"eventNames",
"!==",
"'string'",
"&&",
"!",
"(",
"eventNames",
"instanceof",
"Array",
")",
")",
"{",
"throw",
"'\"eventNames\" argument must be a string or an array of strings'",
";",
"}",
"if",
"(",
"typeof",
"callback",
"!==",
"'function'",
")",
"{",
"throw",
"'\"callback\" argument must be a function'",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
">",
"4",
"&&",
"typeof",
"useCapture",
"!==",
"'boolean'",
")",
"{",
"throw",
"'\"useCapture\" argument must be a boolean value'",
";",
"}",
"}",
"eventEmitters",
"=",
"eventEmitters",
"instanceof",
"Array",
"||",
"(",
"typeof",
"NodeList",
"!==",
"'undefined'",
"&&",
"eventEmitters",
"instanceof",
"NodeList",
")",
"?",
"eventEmitters",
":",
"[",
"eventEmitters",
"]",
";",
"eventNames",
"=",
"eventNames",
"instanceof",
"Array",
"?",
"eventNames",
":",
"[",
"eventNames",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"eventEmitters",
".",
"length",
";",
"++",
"i",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"eventNames",
".",
"length",
";",
"++",
"j",
")",
"{",
"setupListeners",
"(",
"this",
",",
"eventEmitters",
"[",
"i",
"]",
",",
"eventNames",
"[",
"j",
"]",
",",
"callback",
",",
"context",
",",
"!",
"!",
"useCapture",
")",
";",
"}",
"}",
"}"
] | Start listening to an event on a specified event emitting object. Both eventEmitters and eventNames arguments can be arrays. The total amount of listeners added will be the Cartesian product of the two lists.
@instance
@arg {Object|Array|NodeList} eventEmitters - One or more event emitters that will be listened to.
@arg {string|Array} eventNames - One or more string identifiers for events that will be listented to.
@arg {function} callback - The function that will be called when the event is emitted.
@arg {any} [context] - The context with which the callback will be called (i.e. what "this" will be).
Will default to the caller of .listenTo, if not provided. | [
"Start",
"listening",
"to",
"an",
"event",
"on",
"a",
"specified",
"event",
"emitting",
"object",
".",
"Both",
"eventEmitters",
"and",
"eventNames",
"arguments",
"can",
"be",
"arrays",
".",
"The",
"total",
"amount",
"of",
"listeners",
"added",
"will",
"be",
"the",
"Cartesian",
"product",
"of",
"the",
"two",
"lists",
"."
] | 38ebebf3b69f758da78ffb50a97742d33d6d5931 | https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/event-listener.js#L55-L83 | train |
|
oskargustafsson/BFF | src/event-listener.js | function (eventEmitter, eventName) {
if (RUNTIME_CHECKS) {
if (!!eventEmitter && !eventEmitter.addEventListener) {
throw '"eventEmitter" argument must be an event emitter';
}
if (arguments.length > 1 && typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
}
if (!this.__private || !this.__private.listeningTo) { return; } // Not listening to anything? We are done.
var eventNames = eventName ? {} : this.__private.listeningTo;
eventName && (eventNames[eventName] = true);
for (eventName in eventNames) {
var listeningToList = this.__private.listeningTo[eventName];
if (!listeningToList) { continue; }
filterList(listeningToList, eventName, eventEmitter);
listeningToList.length || (delete this.__private.listeningTo[eventName]);
}
} | javascript | function (eventEmitter, eventName) {
if (RUNTIME_CHECKS) {
if (!!eventEmitter && !eventEmitter.addEventListener) {
throw '"eventEmitter" argument must be an event emitter';
}
if (arguments.length > 1 && typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
}
if (!this.__private || !this.__private.listeningTo) { return; } // Not listening to anything? We are done.
var eventNames = eventName ? {} : this.__private.listeningTo;
eventName && (eventNames[eventName] = true);
for (eventName in eventNames) {
var listeningToList = this.__private.listeningTo[eventName];
if (!listeningToList) { continue; }
filterList(listeningToList, eventName, eventEmitter);
listeningToList.length || (delete this.__private.listeningTo[eventName]);
}
} | [
"function",
"(",
"eventEmitter",
",",
"eventName",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
")",
"{",
"if",
"(",
"!",
"!",
"eventEmitter",
"&&",
"!",
"eventEmitter",
".",
"addEventListener",
")",
"{",
"throw",
"'\"eventEmitter\" argument must be an event emitter'",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
">",
"1",
"&&",
"typeof",
"eventName",
"!==",
"'string'",
")",
"{",
"throw",
"'\"eventName\" argument must be a string'",
";",
"}",
"}",
"if",
"(",
"!",
"this",
".",
"__private",
"||",
"!",
"this",
".",
"__private",
".",
"listeningTo",
")",
"{",
"return",
";",
"}",
"var",
"eventNames",
"=",
"eventName",
"?",
"{",
"}",
":",
"this",
".",
"__private",
".",
"listeningTo",
";",
"eventName",
"&&",
"(",
"eventNames",
"[",
"eventName",
"]",
"=",
"true",
")",
";",
"for",
"(",
"eventName",
"in",
"eventNames",
")",
"{",
"var",
"listeningToList",
"=",
"this",
".",
"__private",
".",
"listeningTo",
"[",
"eventName",
"]",
";",
"if",
"(",
"!",
"listeningToList",
")",
"{",
"continue",
";",
"}",
"filterList",
"(",
"listeningToList",
",",
"eventName",
",",
"eventEmitter",
")",
";",
"listeningToList",
".",
"length",
"||",
"(",
"delete",
"this",
".",
"__private",
".",
"listeningTo",
"[",
"eventName",
"]",
")",
";",
"}",
"}"
] | Stop listening to events. If no arguments are provided, the listener removes all its event listeners. Providing any or both of the optional arguments will filter the list of event listeners removed.
@instance
@arg {Object} [eventEmitter] - If provided, only callbacks attached to the given event emitter will be removed.
@arg {string} [eventName] - If provided, only callbacks attached to the given event name will be removed. | [
"Stop",
"listening",
"to",
"events",
".",
"If",
"no",
"arguments",
"are",
"provided",
"the",
"listener",
"removes",
"all",
"its",
"event",
"listeners",
".",
"Providing",
"any",
"or",
"both",
"of",
"the",
"optional",
"arguments",
"will",
"filter",
"the",
"list",
"of",
"event",
"listeners",
"removed",
"."
] | 38ebebf3b69f758da78ffb50a97742d33d6d5931 | https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/event-listener.js#L91-L112 | train |
|
axke/rs-api | lib/apis/grandexchange.js | function (data) {
var items = [];
data.forEach(function (d, i) {
if (d.includes('ITEM:') && d.length > 3) {
var iid = data[i + 1];
var item = {
item: {
id: Number(iid[1].trim()),
name: d[2].replace(/_/g, ' '),
price: d[3],
change: d[4]
}
};
items.push(item);
}
});
return items;
} | javascript | function (data) {
var items = [];
data.forEach(function (d, i) {
if (d.includes('ITEM:') && d.length > 3) {
var iid = data[i + 1];
var item = {
item: {
id: Number(iid[1].trim()),
name: d[2].replace(/_/g, ' '),
price: d[3],
change: d[4]
}
};
items.push(item);
}
});
return items;
} | [
"function",
"(",
"data",
")",
"{",
"var",
"items",
"=",
"[",
"]",
";",
"data",
".",
"forEach",
"(",
"function",
"(",
"d",
",",
"i",
")",
"{",
"if",
"(",
"d",
".",
"includes",
"(",
"'ITEM:'",
")",
"&&",
"d",
".",
"length",
">",
"3",
")",
"{",
"var",
"iid",
"=",
"data",
"[",
"i",
"+",
"1",
"]",
";",
"var",
"item",
"=",
"{",
"item",
":",
"{",
"id",
":",
"Number",
"(",
"iid",
"[",
"1",
"]",
".",
"trim",
"(",
")",
")",
",",
"name",
":",
"d",
"[",
"2",
"]",
".",
"replace",
"(",
"/",
"_",
"/",
"g",
",",
"' '",
")",
",",
"price",
":",
"d",
"[",
"3",
"]",
",",
"change",
":",
"d",
"[",
"4",
"]",
"}",
"}",
";",
"items",
".",
"push",
"(",
"item",
")",
";",
"}",
"}",
")",
";",
"return",
"items",
";",
"}"
] | Read the RScript data and put it into an item array | [
"Read",
"the",
"RScript",
"data",
"and",
"put",
"it",
"into",
"an",
"item",
"array"
] | 71af4973e1d079f09b7d888b6d24735784185942 | https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/apis/grandexchange.js#L13-L30 | train |
|
skuid/skuid-grunt | tasks/lib/helpers.js | function(pagedef, pagedir){
var filenameBase = pagedir + pagedef.uniqueId;
var xmlDef = {ext: '.xml', contents: pd.xml(pagedef.body)};
var metaDef = {
ext: '.json',
contents: JSON.stringify(_.omit(pagedef, 'body'), null, 3)
};
_.each([xmlDef, metaDef], function(item){
var filename = filenameBase + item.ext;
grunt.file.write(filenameBase + item.ext, item.contents);
if(grunt.option('verbose')){
grunt.log.ok(filename + ' written to ' + pagedir);
}
});
} | javascript | function(pagedef, pagedir){
var filenameBase = pagedir + pagedef.uniqueId;
var xmlDef = {ext: '.xml', contents: pd.xml(pagedef.body)};
var metaDef = {
ext: '.json',
contents: JSON.stringify(_.omit(pagedef, 'body'), null, 3)
};
_.each([xmlDef, metaDef], function(item){
var filename = filenameBase + item.ext;
grunt.file.write(filenameBase + item.ext, item.contents);
if(grunt.option('verbose')){
grunt.log.ok(filename + ' written to ' + pagedir);
}
});
} | [
"function",
"(",
"pagedef",
",",
"pagedir",
")",
"{",
"var",
"filenameBase",
"=",
"pagedir",
"+",
"pagedef",
".",
"uniqueId",
";",
"var",
"xmlDef",
"=",
"{",
"ext",
":",
"'.xml'",
",",
"contents",
":",
"pd",
".",
"xml",
"(",
"pagedef",
".",
"body",
")",
"}",
";",
"var",
"metaDef",
"=",
"{",
"ext",
":",
"'.json'",
",",
"contents",
":",
"JSON",
".",
"stringify",
"(",
"_",
".",
"omit",
"(",
"pagedef",
",",
"'body'",
")",
",",
"null",
",",
"3",
")",
"}",
";",
"_",
".",
"each",
"(",
"[",
"xmlDef",
",",
"metaDef",
"]",
",",
"function",
"(",
"item",
")",
"{",
"var",
"filename",
"=",
"filenameBase",
"+",
"item",
".",
"ext",
";",
"grunt",
".",
"file",
".",
"write",
"(",
"filenameBase",
"+",
"item",
".",
"ext",
",",
"item",
".",
"contents",
")",
";",
"if",
"(",
"grunt",
".",
"option",
"(",
"'verbose'",
")",
")",
"{",
"grunt",
".",
"log",
".",
"ok",
"(",
"filename",
"+",
"' written to '",
"+",
"pagedir",
")",
";",
"}",
"}",
")",
";",
"}"
] | Prepare the xml and json meta files for the specified Skuid page
@param {[type]} pagedef [description]
@param {[type]} pagedir [description]
@return {[type]} [description] | [
"Prepare",
"the",
"xml",
"and",
"json",
"meta",
"files",
"for",
"the",
"specified",
"Skuid",
"page"
] | e714b0181ab2674f889b5e2571fd88e0802fbdf1 | https://github.com/skuid/skuid-grunt/blob/e714b0181ab2674f889b5e2571fd88e0802fbdf1/tasks/lib/helpers.js#L12-L26 | train |
|
junghans-schneider/extjs-dependencies | lib/parser.js | parseAlternateMappingsCall | function parseAlternateMappingsCall(node, output) {
var firstArgument = node.expression.arguments[0];
if (firstArgument && firstArgument.type === 'ObjectExpression') {
firstArgument.properties.forEach(function(prop) {
var aliasClassNames = getPropertyValue(prop); // Could be a string or an array of strings
if (aliasClassNames && aliasClassNames.length > 0) {
var className = prop.key.value;
if (! output.aliasNames) {
output.aliasNames = {};
}
if (typeof aliasClassNames === 'string') {
aliasClassNames = [ aliasClassNames ];
}
var existingAliasClassNames = output.aliasNames[className];
if (existingAliasClassNames) {
aliasClassNames = existingAliasClassNames.concat(aliasClassNames);
}
output.aliasNames[className] = unique(aliasClassNames);
}
});
if (options.optimizeSource) {
// Remove `uses` from parsed file
node.update('/* call to Ext.ClassManager.addNameAlternateMappings removed */');
}
}
} | javascript | function parseAlternateMappingsCall(node, output) {
var firstArgument = node.expression.arguments[0];
if (firstArgument && firstArgument.type === 'ObjectExpression') {
firstArgument.properties.forEach(function(prop) {
var aliasClassNames = getPropertyValue(prop); // Could be a string or an array of strings
if (aliasClassNames && aliasClassNames.length > 0) {
var className = prop.key.value;
if (! output.aliasNames) {
output.aliasNames = {};
}
if (typeof aliasClassNames === 'string') {
aliasClassNames = [ aliasClassNames ];
}
var existingAliasClassNames = output.aliasNames[className];
if (existingAliasClassNames) {
aliasClassNames = existingAliasClassNames.concat(aliasClassNames);
}
output.aliasNames[className] = unique(aliasClassNames);
}
});
if (options.optimizeSource) {
// Remove `uses` from parsed file
node.update('/* call to Ext.ClassManager.addNameAlternateMappings removed */');
}
}
} | [
"function",
"parseAlternateMappingsCall",
"(",
"node",
",",
"output",
")",
"{",
"var",
"firstArgument",
"=",
"node",
".",
"expression",
".",
"arguments",
"[",
"0",
"]",
";",
"if",
"(",
"firstArgument",
"&&",
"firstArgument",
".",
"type",
"===",
"'ObjectExpression'",
")",
"{",
"firstArgument",
".",
"properties",
".",
"forEach",
"(",
"function",
"(",
"prop",
")",
"{",
"var",
"aliasClassNames",
"=",
"getPropertyValue",
"(",
"prop",
")",
";",
"if",
"(",
"aliasClassNames",
"&&",
"aliasClassNames",
".",
"length",
">",
"0",
")",
"{",
"var",
"className",
"=",
"prop",
".",
"key",
".",
"value",
";",
"if",
"(",
"!",
"output",
".",
"aliasNames",
")",
"{",
"output",
".",
"aliasNames",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"typeof",
"aliasClassNames",
"===",
"'string'",
")",
"{",
"aliasClassNames",
"=",
"[",
"aliasClassNames",
"]",
";",
"}",
"var",
"existingAliasClassNames",
"=",
"output",
".",
"aliasNames",
"[",
"className",
"]",
";",
"if",
"(",
"existingAliasClassNames",
")",
"{",
"aliasClassNames",
"=",
"existingAliasClassNames",
".",
"concat",
"(",
"aliasClassNames",
")",
";",
"}",
"output",
".",
"aliasNames",
"[",
"className",
"]",
"=",
"unique",
"(",
"aliasClassNames",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"options",
".",
"optimizeSource",
")",
"{",
"node",
".",
"update",
"(",
"'/* call to Ext.ClassManager.addNameAlternateMappings removed */'",
")",
";",
"}",
"}",
"}"
] | Parses a call to Ext.ClassManager.addNameAlternateMappings | [
"Parses",
"a",
"call",
"to",
"Ext",
".",
"ClassManager",
".",
"addNameAlternateMappings"
] | be36e87339b0973883c490fe2535414e74b1413b | https://github.com/junghans-schneider/extjs-dependencies/blob/be36e87339b0973883c490fe2535414e74b1413b/lib/parser.js#L297-L328 | train |
junghans-schneider/extjs-dependencies | lib/parser.js | parseLoaderSetPathCall | function parseLoaderSetPathCall(node, output) {
// Example: `Ext.Loader.setPath('Ext.ux', 'lib/extjs-ux/src');`
var classPrefixArg = node.expression.arguments[0];
var pathArg = node.expression.arguments[1];
if (classPrefixArg && pathArg) {
addResolvePath(classPrefixArg.value, pathArg.value, output);
}
} | javascript | function parseLoaderSetPathCall(node, output) {
// Example: `Ext.Loader.setPath('Ext.ux', 'lib/extjs-ux/src');`
var classPrefixArg = node.expression.arguments[0];
var pathArg = node.expression.arguments[1];
if (classPrefixArg && pathArg) {
addResolvePath(classPrefixArg.value, pathArg.value, output);
}
} | [
"function",
"parseLoaderSetPathCall",
"(",
"node",
",",
"output",
")",
"{",
"var",
"classPrefixArg",
"=",
"node",
".",
"expression",
".",
"arguments",
"[",
"0",
"]",
";",
"var",
"pathArg",
"=",
"node",
".",
"expression",
".",
"arguments",
"[",
"1",
"]",
";",
"if",
"(",
"classPrefixArg",
"&&",
"pathArg",
")",
"{",
"addResolvePath",
"(",
"classPrefixArg",
".",
"value",
",",
"pathArg",
".",
"value",
",",
"output",
")",
";",
"}",
"}"
] | Parses call to Ext.Loader.setPath | [
"Parses",
"call",
"to",
"Ext",
".",
"Loader",
".",
"setPath"
] | be36e87339b0973883c490fe2535414e74b1413b | https://github.com/junghans-schneider/extjs-dependencies/blob/be36e87339b0973883c490fe2535414e74b1413b/lib/parser.js#L331-L338 | train |
twolfson/fontsmith | lib/fontsmith.js | fontsmith | function fontsmith(params, cb) {
// Collect paths
var files = params.src,
retObj = {};
// TODO: Allow specification of engine when we have more
// TODO: By default, use an `auto` engine which falls back through engines until it finds one.
// Load in our engine and assert it exists
var engine = engines['icomoon-phantomjs'];
assert(engine, 'fontsmith engine "icomoon-phantomjs" could not be loaded. Please verify its dependencies are satisfied.');
// In series
var palette;
async.waterfall([
// Create an engine to work with
function createEngine (cb) {
// TODO; Figure out what the options will be / where they come from
engine.create({}, cb);
},
// Save the palette for external reference
function savePalette (_palette, cb) {
palette = _palette;
cb();
},
// TODO: Each SVG might have a specified character
// TODO: This is the equivalent of a custom `layout` as defined in spritesmith
// Add in our svgs
function addSvgs (cb) {
// DEV: If we ever run into perf issue regarding this, we should make this a batch function as in spritesmith
async.forEach(files, palette.addSvg.bind(palette), cb);
},
// Export the resulting fonts/map
function exportFn (cb) {
// Format should be {map:{'absolute/path':'\unicode'}, fonts: {svg:'binary', ttf:'binary'}}
palette['export'](params.exportOptions || {}, cb);
}
], cb);
} | javascript | function fontsmith(params, cb) {
// Collect paths
var files = params.src,
retObj = {};
// TODO: Allow specification of engine when we have more
// TODO: By default, use an `auto` engine which falls back through engines until it finds one.
// Load in our engine and assert it exists
var engine = engines['icomoon-phantomjs'];
assert(engine, 'fontsmith engine "icomoon-phantomjs" could not be loaded. Please verify its dependencies are satisfied.');
// In series
var palette;
async.waterfall([
// Create an engine to work with
function createEngine (cb) {
// TODO; Figure out what the options will be / where they come from
engine.create({}, cb);
},
// Save the palette for external reference
function savePalette (_palette, cb) {
palette = _palette;
cb();
},
// TODO: Each SVG might have a specified character
// TODO: This is the equivalent of a custom `layout` as defined in spritesmith
// Add in our svgs
function addSvgs (cb) {
// DEV: If we ever run into perf issue regarding this, we should make this a batch function as in spritesmith
async.forEach(files, palette.addSvg.bind(palette), cb);
},
// Export the resulting fonts/map
function exportFn (cb) {
// Format should be {map:{'absolute/path':'\unicode'}, fonts: {svg:'binary', ttf:'binary'}}
palette['export'](params.exportOptions || {}, cb);
}
], cb);
} | [
"function",
"fontsmith",
"(",
"params",
",",
"cb",
")",
"{",
"var",
"files",
"=",
"params",
".",
"src",
",",
"retObj",
"=",
"{",
"}",
";",
"var",
"engine",
"=",
"engines",
"[",
"'icomoon-phantomjs'",
"]",
";",
"assert",
"(",
"engine",
",",
"'fontsmith engine \"icomoon-phantomjs\" could not be loaded. Please verify its dependencies are satisfied.'",
")",
";",
"var",
"palette",
";",
"async",
".",
"waterfall",
"(",
"[",
"function",
"createEngine",
"(",
"cb",
")",
"{",
"engine",
".",
"create",
"(",
"{",
"}",
",",
"cb",
")",
";",
"}",
",",
"function",
"savePalette",
"(",
"_palette",
",",
"cb",
")",
"{",
"palette",
"=",
"_palette",
";",
"cb",
"(",
")",
";",
"}",
",",
"function",
"addSvgs",
"(",
"cb",
")",
"{",
"async",
".",
"forEach",
"(",
"files",
",",
"palette",
".",
"addSvg",
".",
"bind",
"(",
"palette",
")",
",",
"cb",
")",
";",
"}",
",",
"function",
"exportFn",
"(",
"cb",
")",
"{",
"palette",
"[",
"'export'",
"]",
"(",
"params",
".",
"exportOptions",
"||",
"{",
"}",
",",
"cb",
")",
";",
"}",
"]",
",",
"cb",
")",
";",
"}"
] | Function which eats SVGs and outputs fonts and a mapping from file names to unicode values
@param {Object} params Object containing all parameters for fontsmith
@param {String[]} params.src Array of paths to SVGs to compile
@param {Function} cb Error-first function to callback with composition results | [
"Function",
"which",
"eats",
"SVGs",
"and",
"outputs",
"fonts",
"and",
"a",
"mapping",
"from",
"file",
"names",
"to",
"unicode",
"values"
] | c5b1e24f4bb06fdefba57b0b73af8971024d9216 | https://github.com/twolfson/fontsmith/blob/c5b1e24f4bb06fdefba57b0b73af8971024d9216/lib/fontsmith.js#L12-L49 | train |
blakeembrey/dombars | lib/raf.js | function () {
/**
* Return the current timestamp integer.
*/
var now = Date.now || function () {
return new Date().getTime();
};
// Keep track of the previous "animation frame" manually.
var prev = now();
return function (fn) {
var curr = now();
var ms = Math.max(0, 16 - (curr - prev));
var req = setTimeout(fn, ms);
prev = curr;
return req;
};
} | javascript | function () {
/**
* Return the current timestamp integer.
*/
var now = Date.now || function () {
return new Date().getTime();
};
// Keep track of the previous "animation frame" manually.
var prev = now();
return function (fn) {
var curr = now();
var ms = Math.max(0, 16 - (curr - prev));
var req = setTimeout(fn, ms);
prev = curr;
return req;
};
} | [
"function",
"(",
")",
"{",
"var",
"now",
"=",
"Date",
".",
"now",
"||",
"function",
"(",
")",
"{",
"return",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"}",
";",
"var",
"prev",
"=",
"now",
"(",
")",
";",
"return",
"function",
"(",
"fn",
")",
"{",
"var",
"curr",
"=",
"now",
"(",
")",
";",
"var",
"ms",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"16",
"-",
"(",
"curr",
"-",
"prev",
")",
")",
";",
"var",
"req",
"=",
"setTimeout",
"(",
"fn",
",",
"ms",
")",
";",
"prev",
"=",
"curr",
";",
"return",
"req",
";",
"}",
";",
"}"
] | Fallback animation frame implementation.
@return {Function} | [
"Fallback",
"animation",
"frame",
"implementation",
"."
] | 2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed | https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/raf.js#L10-L30 | train |
|
enquirer/prompt-question | index.js | Question | function Question(name, message, options) {
debug('initializing from <%s>', __filename);
if (arguments.length === 0) {
throw new TypeError('expected a string or object');
}
if (Question.isQuestion(name)) {
return name;
}
this.type = 'input';
this.options = {};
this.getDefault();
if (Array.isArray(message)) {
options = { choices: message };
message = name;
}
if (Array.isArray(options)) {
options = { choices: options };
}
define(this, 'Choices', Choices);
define(this, 'isQuestion', true);
utils.assign(this, {
name: name,
message: message,
options: options
});
} | javascript | function Question(name, message, options) {
debug('initializing from <%s>', __filename);
if (arguments.length === 0) {
throw new TypeError('expected a string or object');
}
if (Question.isQuestion(name)) {
return name;
}
this.type = 'input';
this.options = {};
this.getDefault();
if (Array.isArray(message)) {
options = { choices: message };
message = name;
}
if (Array.isArray(options)) {
options = { choices: options };
}
define(this, 'Choices', Choices);
define(this, 'isQuestion', true);
utils.assign(this, {
name: name,
message: message,
options: options
});
} | [
"function",
"Question",
"(",
"name",
",",
"message",
",",
"options",
")",
"{",
"debug",
"(",
"'initializing from <%s>'",
",",
"__filename",
")",
";",
"if",
"(",
"arguments",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'expected a string or object'",
")",
";",
"}",
"if",
"(",
"Question",
".",
"isQuestion",
"(",
"name",
")",
")",
"{",
"return",
"name",
";",
"}",
"this",
".",
"type",
"=",
"'input'",
";",
"this",
".",
"options",
"=",
"{",
"}",
";",
"this",
".",
"getDefault",
"(",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"message",
")",
")",
"{",
"options",
"=",
"{",
"choices",
":",
"message",
"}",
";",
"message",
"=",
"name",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"options",
")",
")",
"{",
"options",
"=",
"{",
"choices",
":",
"options",
"}",
";",
"}",
"define",
"(",
"this",
",",
"'Choices'",
",",
"Choices",
")",
";",
"define",
"(",
"this",
",",
"'isQuestion'",
",",
"true",
")",
";",
"utils",
".",
"assign",
"(",
"this",
",",
"{",
"name",
":",
"name",
",",
"message",
":",
"message",
",",
"options",
":",
"options",
"}",
")",
";",
"}"
] | Create a new question with the given `name`, `message` and `options`.
```js
var question = new Question('first', 'What is your first name?');
console.log(question);
// {
// type: 'input',
// name: 'color',
// message: 'What is your favorite color?'
// }
```
@param {String|Object} `name` Question name or options.
@param {String|Object} `message` Question message or options.
@param {String|Object} `options` Question options.
@api public | [
"Create",
"a",
"new",
"question",
"with",
"the",
"given",
"name",
"message",
"and",
"options",
"."
] | 8261c899a3ff0a4f76f7e39851538c6374991ddb | https://github.com/enquirer/prompt-question/blob/8261c899a3ff0a4f76f7e39851538c6374991ddb/index.js#L29-L59 | train |
zynga/gravity | gravity.js | addLineHints | function addLineHints(name, content) {
var
i = -1,
lines = content.split('\n'),
len = lines.length,
out = []
;
while (++i < len) {
out.push(lines[i] +
((i % 10 === 9) ? ' //' + name + ':' + (i + 1) + '//' : ''));
}
return out.join('\n');
} | javascript | function addLineHints(name, content) {
var
i = -1,
lines = content.split('\n'),
len = lines.length,
out = []
;
while (++i < len) {
out.push(lines[i] +
((i % 10 === 9) ? ' //' + name + ':' + (i + 1) + '//' : ''));
}
return out.join('\n');
} | [
"function",
"addLineHints",
"(",
"name",
",",
"content",
")",
"{",
"var",
"i",
"=",
"-",
"1",
",",
"lines",
"=",
"content",
".",
"split",
"(",
"'\\n'",
")",
",",
"\\n",
",",
"len",
"=",
"lines",
".",
"length",
";",
"out",
"=",
"[",
"]",
"while",
"(",
"++",
"i",
"<",
"len",
")",
"{",
"out",
".",
"push",
"(",
"lines",
"[",
"i",
"]",
"+",
"(",
"(",
"i",
"%",
"10",
"===",
"9",
")",
"?",
"' //'",
"+",
"name",
"+",
"':'",
"+",
"(",
"i",
"+",
"1",
")",
"+",
"'//'",
":",
"''",
")",
")",
";",
"}",
"}"
] | Add JavaScript line-hint comments to every 10th line of a file. | [
"Add",
"JavaScript",
"line",
"-",
"hint",
"comments",
"to",
"every",
"10th",
"line",
"of",
"a",
"file",
"."
] | 79916523c2c0733be80c21354e5a2aa0ea4cf2c7 | https://github.com/zynga/gravity/blob/79916523c2c0733be80c21354e5a2aa0ea4cf2c7/gravity.js#L65-L77 | train |
zynga/gravity | gravity.js | joinBuffers | function joinBuffers(buffers) {
var
i = -1, j = -1,
num = buffers.length,
totalBytes = 0,
bytesWritten = 0,
buff,
superBuff
;
while (++i < num) {
totalBytes += buffers[i].length;
}
superBuff = new Buffer(totalBytes);
while (++j < num) {
buff = buffers[j];
buff.copy(superBuff, bytesWritten, 0);
bytesWritten += buff.length;
}
return superBuff;
} | javascript | function joinBuffers(buffers) {
var
i = -1, j = -1,
num = buffers.length,
totalBytes = 0,
bytesWritten = 0,
buff,
superBuff
;
while (++i < num) {
totalBytes += buffers[i].length;
}
superBuff = new Buffer(totalBytes);
while (++j < num) {
buff = buffers[j];
buff.copy(superBuff, bytesWritten, 0);
bytesWritten += buff.length;
}
return superBuff;
} | [
"function",
"joinBuffers",
"(",
"buffers",
")",
"{",
"var",
"i",
"=",
"-",
"1",
",",
"j",
"=",
"-",
"1",
",",
"num",
"=",
"buffers",
".",
"length",
",",
"totalBytes",
"=",
"0",
",",
"bytesWritten",
"=",
"0",
",",
"buff",
",",
"superBuff",
";",
"while",
"(",
"++",
"i",
"<",
"num",
")",
"{",
"totalBytes",
"+=",
"buffers",
"[",
"i",
"]",
".",
"length",
";",
"}",
"superBuff",
"=",
"new",
"Buffer",
"(",
"totalBytes",
")",
";",
"while",
"(",
"++",
"j",
"<",
"num",
")",
"{",
"buff",
"=",
"buffers",
"[",
"j",
"]",
";",
"buff",
".",
"copy",
"(",
"superBuff",
",",
"bytesWritten",
",",
"0",
")",
";",
"bytesWritten",
"+=",
"buff",
".",
"length",
";",
"}",
"return",
"superBuff",
";",
"}"
] | Concatentate an array of Buffers into a single one. | [
"Concatentate",
"an",
"array",
"of",
"Buffers",
"into",
"a",
"single",
"one",
"."
] | 79916523c2c0733be80c21354e5a2aa0ea4cf2c7 | https://github.com/zynga/gravity/blob/79916523c2c0733be80c21354e5a2aa0ea4cf2c7/gravity.js#L81-L100 | train |
zynga/gravity | gravity.js | wget | function wget(fileURL, callback) {
var
chunks = [],
isHTTPS = fileURL.indexOf('https') === 0,
client = isHTTPS ? https : http,
options = fileURL
;
if (isHTTPS) {
options = url.parse(fileURL);
options.rejectUnauthorized = false;
options.agent = new https.Agent(options);
}
client.get(options, function (res) {
res.on('data', function (chunk) {
chunks.push(chunk);
}).on('end', function () {
callback(null, joinBuffers(chunks));
});
});
} | javascript | function wget(fileURL, callback) {
var
chunks = [],
isHTTPS = fileURL.indexOf('https') === 0,
client = isHTTPS ? https : http,
options = fileURL
;
if (isHTTPS) {
options = url.parse(fileURL);
options.rejectUnauthorized = false;
options.agent = new https.Agent(options);
}
client.get(options, function (res) {
res.on('data', function (chunk) {
chunks.push(chunk);
}).on('end', function () {
callback(null, joinBuffers(chunks));
});
});
} | [
"function",
"wget",
"(",
"fileURL",
",",
"callback",
")",
"{",
"var",
"chunks",
"=",
"[",
"]",
",",
"isHTTPS",
"=",
"fileURL",
".",
"indexOf",
"(",
"'https'",
")",
"===",
"0",
",",
"client",
"=",
"isHTTPS",
"?",
"https",
":",
"http",
",",
"options",
"=",
"fileURL",
";",
"if",
"(",
"isHTTPS",
")",
"{",
"options",
"=",
"url",
".",
"parse",
"(",
"fileURL",
")",
";",
"options",
".",
"rejectUnauthorized",
"=",
"false",
";",
"options",
".",
"agent",
"=",
"new",
"https",
".",
"Agent",
"(",
"options",
")",
";",
"}",
"client",
".",
"get",
"(",
"options",
",",
"function",
"(",
"res",
")",
"{",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"chunks",
".",
"push",
"(",
"chunk",
")",
";",
"}",
")",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"callback",
"(",
"null",
",",
"joinBuffers",
"(",
"chunks",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Given a web URL, fetch the file contents. | [
"Given",
"a",
"web",
"URL",
"fetch",
"the",
"file",
"contents",
"."
] | 79916523c2c0733be80c21354e5a2aa0ea4cf2c7 | https://github.com/zynga/gravity/blob/79916523c2c0733be80c21354e5a2aa0ea4cf2c7/gravity.js#L104-L123 | train |
zynga/gravity | gravity.js | reduce | function reduce(map, path) {
var mapNode, prefix, split, splits = getResourcePathSplits(path),
subValue, suffix;
while (splits.length) {
split = splits.shift();
suffix = split[1];
prefix = suffix ? split[0] + '/' : split[0];
mapNode = map[prefix];
if (mapNode) {
if (!suffix || typeof mapNode === 'string') {
return { map: mapNode, prefix: prefix, suffix: suffix };
}
if (typeof mapNode === 'object') {
subValue = reduce(mapNode, suffix);
if (subValue) {
subValue.prefix = prefix + '/' + subValue.prefix;
return subValue;
}
}
}
}
return { map: map, prefix: '', suffix: path };
} | javascript | function reduce(map, path) {
var mapNode, prefix, split, splits = getResourcePathSplits(path),
subValue, suffix;
while (splits.length) {
split = splits.shift();
suffix = split[1];
prefix = suffix ? split[0] + '/' : split[0];
mapNode = map[prefix];
if (mapNode) {
if (!suffix || typeof mapNode === 'string') {
return { map: mapNode, prefix: prefix, suffix: suffix };
}
if (typeof mapNode === 'object') {
subValue = reduce(mapNode, suffix);
if (subValue) {
subValue.prefix = prefix + '/' + subValue.prefix;
return subValue;
}
}
}
}
return { map: map, prefix: '', suffix: path };
} | [
"function",
"reduce",
"(",
"map",
",",
"path",
")",
"{",
"var",
"mapNode",
",",
"prefix",
",",
"split",
",",
"splits",
"=",
"getResourcePathSplits",
"(",
"path",
")",
",",
"subValue",
",",
"suffix",
";",
"while",
"(",
"splits",
".",
"length",
")",
"{",
"split",
"=",
"splits",
".",
"shift",
"(",
")",
";",
"suffix",
"=",
"split",
"[",
"1",
"]",
";",
"prefix",
"=",
"suffix",
"?",
"split",
"[",
"0",
"]",
"+",
"'/'",
":",
"split",
"[",
"0",
"]",
";",
"mapNode",
"=",
"map",
"[",
"prefix",
"]",
";",
"if",
"(",
"mapNode",
")",
"{",
"if",
"(",
"!",
"suffix",
"||",
"typeof",
"mapNode",
"===",
"'string'",
")",
"{",
"return",
"{",
"map",
":",
"mapNode",
",",
"prefix",
":",
"prefix",
",",
"suffix",
":",
"suffix",
"}",
";",
"}",
"if",
"(",
"typeof",
"mapNode",
"===",
"'object'",
")",
"{",
"subValue",
"=",
"reduce",
"(",
"mapNode",
",",
"suffix",
")",
";",
"if",
"(",
"subValue",
")",
"{",
"subValue",
".",
"prefix",
"=",
"prefix",
"+",
"'/'",
"+",
"subValue",
".",
"prefix",
";",
"return",
"subValue",
";",
"}",
"}",
"}",
"}",
"return",
"{",
"map",
":",
"map",
",",
"prefix",
":",
"''",
",",
"suffix",
":",
"path",
"}",
";",
"}"
] | Given a map and a resource path, drill down in the map to find the most specific map node that matches the path. Return the map node, the matched path prefix, and the unmatched path suffix. | [
"Given",
"a",
"map",
"and",
"a",
"resource",
"path",
"drill",
"down",
"in",
"the",
"map",
"to",
"find",
"the",
"most",
"specific",
"map",
"node",
"that",
"matches",
"the",
"path",
".",
"Return",
"the",
"map",
"node",
"the",
"matched",
"path",
"prefix",
"and",
"the",
"unmatched",
"path",
"suffix",
"."
] | 79916523c2c0733be80c21354e5a2aa0ea4cf2c7 | https://github.com/zynga/gravity/blob/79916523c2c0733be80c21354e5a2aa0ea4cf2c7/gravity.js#L154-L176 | train |
zynga/gravity | gravity.js | getResource | function getResource(map, base, internal, path, callback, addLineHints) {
var
reduced = reduce(map, path),
reducedMap = reduced.map,
reducedMapType = nodeType(reducedMap),
reducedPrefix = reduced.prefix,
reducedSuffix = reduced.suffix,
firstChar = path.charAt(0),
temporary = firstChar === '~',
literal = firstChar === '='
;
if (isURL(path)) {
wget(path, callback);
} else if (literal) {
callback(null, new Buffer(path.substr(1) + '\n'));
} else if (temporary && !internal) {
// External request for a temporary resource.
callback({ code: 403, message: 'Forbidden' });
} else if (reducedSuffix) {
// We did NOT find an exact match in the map.
if (!reducedPrefix && internal) {
getFile(base, path, callback, addLineHints);
} else if (reducedMapType === 'string') {
getFile(base, reducedMap + '/' + reducedSuffix, callback, addLineHints);
} else {
callback({ code: 404, message: 'Not Found' });
}
} else {
// We found an exact match in the map.
if (reducedMap === reducedPrefix) {
// This is just a local file/dir to expose.
getFile(base, reducedPrefix, callback, addLineHints);
} else if (reducedMapType === 'string') {
// A string value may be a web URL.
if (isURL(reducedMap)) {
wget(reducedMap, callback);
} else {
// Otherwise, it's another resource path.
getResource(map, base, true, reducedMap, callback, addLineHints);
}
} else if (reducedMapType === 'array') {
// An array is a list of resources to get packed together.
packResources(map, base, reducedMap, callback);
//} else if (reducedMapType === 'object') {
// An object is a directory. We could return a listing...
// TODO: Do we really want to support listings?
} else {
callback({ code: 500, message: 'Unable to read gravity.map.' });
}
}
} | javascript | function getResource(map, base, internal, path, callback, addLineHints) {
var
reduced = reduce(map, path),
reducedMap = reduced.map,
reducedMapType = nodeType(reducedMap),
reducedPrefix = reduced.prefix,
reducedSuffix = reduced.suffix,
firstChar = path.charAt(0),
temporary = firstChar === '~',
literal = firstChar === '='
;
if (isURL(path)) {
wget(path, callback);
} else if (literal) {
callback(null, new Buffer(path.substr(1) + '\n'));
} else if (temporary && !internal) {
// External request for a temporary resource.
callback({ code: 403, message: 'Forbidden' });
} else if (reducedSuffix) {
// We did NOT find an exact match in the map.
if (!reducedPrefix && internal) {
getFile(base, path, callback, addLineHints);
} else if (reducedMapType === 'string') {
getFile(base, reducedMap + '/' + reducedSuffix, callback, addLineHints);
} else {
callback({ code: 404, message: 'Not Found' });
}
} else {
// We found an exact match in the map.
if (reducedMap === reducedPrefix) {
// This is just a local file/dir to expose.
getFile(base, reducedPrefix, callback, addLineHints);
} else if (reducedMapType === 'string') {
// A string value may be a web URL.
if (isURL(reducedMap)) {
wget(reducedMap, callback);
} else {
// Otherwise, it's another resource path.
getResource(map, base, true, reducedMap, callback, addLineHints);
}
} else if (reducedMapType === 'array') {
// An array is a list of resources to get packed together.
packResources(map, base, reducedMap, callback);
//} else if (reducedMapType === 'object') {
// An object is a directory. We could return a listing...
// TODO: Do we really want to support listings?
} else {
callback({ code: 500, message: 'Unable to read gravity.map.' });
}
}
} | [
"function",
"getResource",
"(",
"map",
",",
"base",
",",
"internal",
",",
"path",
",",
"callback",
",",
"addLineHints",
")",
"{",
"var",
"reduced",
"=",
"reduce",
"(",
"map",
",",
"path",
")",
",",
"reducedMap",
"=",
"reduced",
".",
"map",
",",
"reducedMapType",
"=",
"nodeType",
"(",
"reducedMap",
")",
",",
"reducedPrefix",
"=",
"reduced",
".",
"prefix",
",",
"reducedSuffix",
"=",
"reduced",
".",
"suffix",
",",
"firstChar",
"=",
"path",
".",
"charAt",
"(",
"0",
")",
",",
"temporary",
"=",
"firstChar",
"===",
"'~'",
",",
"literal",
"=",
"firstChar",
"===",
"'='",
";",
"if",
"(",
"isURL",
"(",
"path",
")",
")",
"{",
"wget",
"(",
"path",
",",
"callback",
")",
";",
"}",
"else",
"if",
"(",
"literal",
")",
"{",
"callback",
"(",
"null",
",",
"new",
"Buffer",
"(",
"path",
".",
"substr",
"(",
"1",
")",
"+",
"'\\n'",
")",
")",
";",
"}",
"else",
"\\n",
"}"
] | Given a resource path, retrieve the associated content. Internal requests are always allowed, whereas external requests will only have access to resources explicitly exposed by the gravity map. | [
"Given",
"a",
"resource",
"path",
"retrieve",
"the",
"associated",
"content",
".",
"Internal",
"requests",
"are",
"always",
"allowed",
"whereas",
"external",
"requests",
"will",
"only",
"have",
"access",
"to",
"resources",
"explicitly",
"exposed",
"by",
"the",
"gravity",
"map",
"."
] | 79916523c2c0733be80c21354e5a2aa0ea4cf2c7 | https://github.com/zynga/gravity/blob/79916523c2c0733be80c21354e5a2aa0ea4cf2c7/gravity.js#L210-L271 | train |
arschmitz/ember-cli-standard | blueprints/ember-cli-standard/index.js | synchronize | function synchronize (items, cb) {
return items.reduce(function (promise, item) {
return promise.then(function () {
return cb.call(this, item)
})
}, RSVP.resolve())
} | javascript | function synchronize (items, cb) {
return items.reduce(function (promise, item) {
return promise.then(function () {
return cb.call(this, item)
})
}, RSVP.resolve())
} | [
"function",
"synchronize",
"(",
"items",
",",
"cb",
")",
"{",
"return",
"items",
".",
"reduce",
"(",
"function",
"(",
"promise",
",",
"item",
")",
"{",
"return",
"promise",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"cb",
".",
"call",
"(",
"this",
",",
"item",
")",
"}",
")",
"}",
",",
"RSVP",
".",
"resolve",
"(",
")",
")",
"}"
] | For each item in the array, call the callback, passing the item as the argument.
However, only call the next callback after the promise returned by the previous
one has resolved.
@param {*[]} items the elements to iterate over
@param {Function} cb called for each item, with the item as the parameter. Should return a promise
@return {Promise} | [
"For",
"each",
"item",
"in",
"the",
"array",
"call",
"the",
"callback",
"passing",
"the",
"item",
"as",
"the",
"argument",
".",
"However",
"only",
"call",
"the",
"next",
"callback",
"after",
"the",
"promise",
"returned",
"by",
"the",
"previous",
"one",
"has",
"resolved",
"."
] | 2395264c329fffd97f2581b8cb739185bfc615b3 | https://github.com/arschmitz/ember-cli-standard/blob/2395264c329fffd97f2581b8cb739185bfc615b3/blueprints/ember-cli-standard/index.js#L17-L23 | train |
arschmitz/ember-cli-standard | blueprints/ember-cli-standard/index.js | function () {
var promptRemove = this._promptRemove.bind(this)
var removeFile = this._removeFile.bind(this)
var ui = this.ui
return this._findConfigFiles()
.then(function (files) {
if (files.length === 0) {
ui.writeLine('No JSHint or ESLint config files found.')
return RSVP.resolve({
result: {
deleteFiles: 'none'
}
})
}
ui.writeLine('\nI found the following JSHint and ESLint config files:')
files.forEach(function (file) {
ui.writeLine(' ' + file)
})
var promptPromise = ui.prompt({
type: 'list',
name: 'deleteFiles',
message: 'What would you like to do?',
choices: [
{ name: 'Remove them all', value: 'all' },
{ name: 'Remove individually', value: 'each' },
{ name: 'Nothing', value: 'none' }
]
})
return RSVP.hash({
result: promptPromise,
files: files
})
}).then(function (data) {
var value = data.result.deleteFiles
var files = data.files
// Noop if we're not deleting any files
if (value === 'none') {
return RSVP.resolve()
}
if (value === 'all') {
return RSVP.all(files.map(function (fileName) {
return removeFile(fileName)
}))
}
if (value === 'each') {
return synchronize(files, function (fileName) {
return promptRemove(fileName)
})
}
})
} | javascript | function () {
var promptRemove = this._promptRemove.bind(this)
var removeFile = this._removeFile.bind(this)
var ui = this.ui
return this._findConfigFiles()
.then(function (files) {
if (files.length === 0) {
ui.writeLine('No JSHint or ESLint config files found.')
return RSVP.resolve({
result: {
deleteFiles: 'none'
}
})
}
ui.writeLine('\nI found the following JSHint and ESLint config files:')
files.forEach(function (file) {
ui.writeLine(' ' + file)
})
var promptPromise = ui.prompt({
type: 'list',
name: 'deleteFiles',
message: 'What would you like to do?',
choices: [
{ name: 'Remove them all', value: 'all' },
{ name: 'Remove individually', value: 'each' },
{ name: 'Nothing', value: 'none' }
]
})
return RSVP.hash({
result: promptPromise,
files: files
})
}).then(function (data) {
var value = data.result.deleteFiles
var files = data.files
// Noop if we're not deleting any files
if (value === 'none') {
return RSVP.resolve()
}
if (value === 'all') {
return RSVP.all(files.map(function (fileName) {
return removeFile(fileName)
}))
}
if (value === 'each') {
return synchronize(files, function (fileName) {
return promptRemove(fileName)
})
}
})
} | [
"function",
"(",
")",
"{",
"var",
"promptRemove",
"=",
"this",
".",
"_promptRemove",
".",
"bind",
"(",
"this",
")",
"var",
"removeFile",
"=",
"this",
".",
"_removeFile",
".",
"bind",
"(",
"this",
")",
"var",
"ui",
"=",
"this",
".",
"ui",
"return",
"this",
".",
"_findConfigFiles",
"(",
")",
".",
"then",
"(",
"function",
"(",
"files",
")",
"{",
"if",
"(",
"files",
".",
"length",
"===",
"0",
")",
"{",
"ui",
".",
"writeLine",
"(",
"'No JSHint or ESLint config files found.'",
")",
"return",
"RSVP",
".",
"resolve",
"(",
"{",
"result",
":",
"{",
"deleteFiles",
":",
"'none'",
"}",
"}",
")",
"}",
"ui",
".",
"writeLine",
"(",
"'\\nI found the following JSHint and ESLint config files:'",
")",
"\\n",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"ui",
".",
"writeLine",
"(",
"' '",
"+",
"file",
")",
"}",
")",
"var",
"promptPromise",
"=",
"ui",
".",
"prompt",
"(",
"{",
"type",
":",
"'list'",
",",
"name",
":",
"'deleteFiles'",
",",
"message",
":",
"'What would you like to do?'",
",",
"choices",
":",
"[",
"{",
"name",
":",
"'Remove them all'",
",",
"value",
":",
"'all'",
"}",
",",
"{",
"name",
":",
"'Remove individually'",
",",
"value",
":",
"'each'",
"}",
",",
"{",
"name",
":",
"'Nothing'",
",",
"value",
":",
"'none'",
"}",
"]",
"}",
")",
"}",
")",
".",
"return",
"RSVP",
".",
"hash",
"(",
"{",
"result",
":",
"promptPromise",
",",
"files",
":",
"files",
"}",
")",
"then",
"}"
] | Find JSHint and ESLint configuration files and offer to remove them
@return {RSVP.Promise} | [
"Find",
"JSHint",
"and",
"ESLint",
"configuration",
"files",
"and",
"offer",
"to",
"remove",
"them"
] | 2395264c329fffd97f2581b8cb739185bfc615b3 | https://github.com/arschmitz/ember-cli-standard/blob/2395264c329fffd97f2581b8cb739185bfc615b3/blueprints/ember-cli-standard/index.js#L54-L111 | train |
|
arschmitz/ember-cli-standard | blueprints/ember-cli-standard/index.js | function () {
var projectRoot = this.project.root
var ui = this.ui
ui.startProgress('Searching for JSHint and ESLint config files')
return new RSVP.Promise(function (resolve) {
var files = walkSync(projectRoot, {
globs: ['**/.jshintrc', '**/.eslintrc.js'],
ignore: [
'**/bower_components',
'**/dist',
'**/node_modules',
'**/tmp'
]
})
ui.stopProgress()
resolve(files)
})
} | javascript | function () {
var projectRoot = this.project.root
var ui = this.ui
ui.startProgress('Searching for JSHint and ESLint config files')
return new RSVP.Promise(function (resolve) {
var files = walkSync(projectRoot, {
globs: ['**/.jshintrc', '**/.eslintrc.js'],
ignore: [
'**/bower_components',
'**/dist',
'**/node_modules',
'**/tmp'
]
})
ui.stopProgress()
resolve(files)
})
} | [
"function",
"(",
")",
"{",
"var",
"projectRoot",
"=",
"this",
".",
"project",
".",
"root",
"var",
"ui",
"=",
"this",
".",
"ui",
"ui",
".",
"startProgress",
"(",
"'Searching for JSHint and ESLint config files'",
")",
"return",
"new",
"RSVP",
".",
"Promise",
"(",
"function",
"(",
"resolve",
")",
"{",
"var",
"files",
"=",
"walkSync",
"(",
"projectRoot",
",",
"{",
"globs",
":",
"[",
"'**/.jshintrc'",
",",
"'**/.eslintrc.js'",
"]",
",",
"ignore",
":",
"[",
"'**/bower_components'",
",",
"'**/dist'",
",",
"'**/node_modules'",
",",
"'**/tmp'",
"]",
"}",
")",
"ui",
".",
"stopProgress",
"(",
")",
"resolve",
"(",
"files",
")",
"}",
")",
"}"
] | Find JSHint and ESLint configuration files
@return {Promise->string[]} found file names | [
"Find",
"JSHint",
"and",
"ESLint",
"configuration",
"files"
] | 2395264c329fffd97f2581b8cb739185bfc615b3 | https://github.com/arschmitz/ember-cli-standard/blob/2395264c329fffd97f2581b8cb739185bfc615b3/blueprints/ember-cli-standard/index.js#L144-L163 | train |
|
arschmitz/ember-cli-standard | blueprints/ember-cli-standard/index.js | function (filePath) {
var removeFile = this._removeFile.bind(this)
var message = 'Should I remove `' + filePath + '`?'
var promptPromise = this.ui.prompt({
type: 'confirm',
name: 'answer',
message: message,
choices: [
{ key: 'y', name: 'Yes, remove it', value: 'yes' },
{ key: 'n', name: 'No, leave it there', value: 'no' }
]
})
return promptPromise.then(function (response) {
if (response.answer) {
return removeFile(filePath)
} else {
return RSVP.resolve()
}
})
} | javascript | function (filePath) {
var removeFile = this._removeFile.bind(this)
var message = 'Should I remove `' + filePath + '`?'
var promptPromise = this.ui.prompt({
type: 'confirm',
name: 'answer',
message: message,
choices: [
{ key: 'y', name: 'Yes, remove it', value: 'yes' },
{ key: 'n', name: 'No, leave it there', value: 'no' }
]
})
return promptPromise.then(function (response) {
if (response.answer) {
return removeFile(filePath)
} else {
return RSVP.resolve()
}
})
} | [
"function",
"(",
"filePath",
")",
"{",
"var",
"removeFile",
"=",
"this",
".",
"_removeFile",
".",
"bind",
"(",
"this",
")",
"var",
"message",
"=",
"'Should I remove `'",
"+",
"filePath",
"+",
"'`?'",
"var",
"promptPromise",
"=",
"this",
".",
"ui",
".",
"prompt",
"(",
"{",
"type",
":",
"'confirm'",
",",
"name",
":",
"'answer'",
",",
"message",
":",
"message",
",",
"choices",
":",
"[",
"{",
"key",
":",
"'y'",
",",
"name",
":",
"'Yes, remove it'",
",",
"value",
":",
"'yes'",
"}",
",",
"{",
"key",
":",
"'n'",
",",
"name",
":",
"'No, leave it there'",
",",
"value",
":",
"'no'",
"}",
"]",
"}",
")",
"return",
"promptPromise",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"if",
"(",
"response",
".",
"answer",
")",
"{",
"return",
"removeFile",
"(",
"filePath",
")",
"}",
"else",
"{",
"return",
"RSVP",
".",
"resolve",
"(",
")",
"}",
"}",
")",
"}"
] | Prompt the user about whether or not they want to remove the given file
@param {string} filePath the path to the file
@return {RSVP.Promise} | [
"Prompt",
"the",
"user",
"about",
"whether",
"or",
"not",
"they",
"want",
"to",
"remove",
"the",
"given",
"file"
] | 2395264c329fffd97f2581b8cb739185bfc615b3 | https://github.com/arschmitz/ember-cli-standard/blob/2395264c329fffd97f2581b8cb739185bfc615b3/blueprints/ember-cli-standard/index.js#L171-L192 | train |
|
arschmitz/ember-cli-standard | blueprints/ember-cli-standard/index.js | function (filePath) {
var projectRoot = this.project.root
var fullPath = resolve(projectRoot, filePath)
return RSVP.denodeify(unlink)(fullPath)
} | javascript | function (filePath) {
var projectRoot = this.project.root
var fullPath = resolve(projectRoot, filePath)
return RSVP.denodeify(unlink)(fullPath)
} | [
"function",
"(",
"filePath",
")",
"{",
"var",
"projectRoot",
"=",
"this",
".",
"project",
".",
"root",
"var",
"fullPath",
"=",
"resolve",
"(",
"projectRoot",
",",
"filePath",
")",
"return",
"RSVP",
".",
"denodeify",
"(",
"unlink",
")",
"(",
"fullPath",
")",
"}"
] | Remove the specified file
@param {string} filePath the relative path (from the project root) to remove
@return {RSVP.Promise} | [
"Remove",
"the",
"specified",
"file"
] | 2395264c329fffd97f2581b8cb739185bfc615b3 | https://github.com/arschmitz/ember-cli-standard/blob/2395264c329fffd97f2581b8cb739185bfc615b3/blueprints/ember-cli-standard/index.js#L200-L205 | train |
|
LaunchPadLab/lp-redux-api | src/middleware/parse-options.js | parseOptions | function parseOptions ({
type,
onUnauthorized,
actions,
types,
requestAction,
successAction,
failureAction,
isStub,
stubData,
adapter,
...requestOptions
}) {
return {
configOptions: omitUndefined({
type,
onUnauthorized,
actions,
types,
requestAction,
successAction,
failureAction,
isStub,
stubData,
adapter,
}),
requestOptions,
}
} | javascript | function parseOptions ({
type,
onUnauthorized,
actions,
types,
requestAction,
successAction,
failureAction,
isStub,
stubData,
adapter,
...requestOptions
}) {
return {
configOptions: omitUndefined({
type,
onUnauthorized,
actions,
types,
requestAction,
successAction,
failureAction,
isStub,
stubData,
adapter,
}),
requestOptions,
}
} | [
"function",
"parseOptions",
"(",
"{",
"type",
",",
"onUnauthorized",
",",
"actions",
",",
"types",
",",
"requestAction",
",",
"successAction",
",",
"failureAction",
",",
"isStub",
",",
"stubData",
",",
"adapter",
",",
"...",
"requestOptions",
"}",
")",
"{",
"return",
"{",
"configOptions",
":",
"omitUndefined",
"(",
"{",
"type",
",",
"onUnauthorized",
",",
"actions",
",",
"types",
",",
"requestAction",
",",
"successAction",
",",
"failureAction",
",",
"isStub",
",",
"stubData",
",",
"adapter",
",",
"}",
")",
",",
"requestOptions",
",",
"}",
"}"
] | Separate middleware options into config options and request options | [
"Separate",
"middleware",
"options",
"into",
"config",
"options",
"and",
"request",
"options"
] | 73eee231067365326780ddc1dbbfa50d3e65defc | https://github.com/LaunchPadLab/lp-redux-api/blob/73eee231067365326780ddc1dbbfa50d3e65defc/src/middleware/parse-options.js#L5-L33 | train |
fergaldoyle/gulp-require-angular | index.js | dive | function dive(name) {
// check if this module has already been
// processed in case of circular dependency
if (dive[name]) {
return;
}
dive[name] = true;
dive.required.push(name);
var deps = allModules[name] || [];
deps.forEach(function (item) {
dive(item);
});
} | javascript | function dive(name) {
// check if this module has already been
// processed in case of circular dependency
if (dive[name]) {
return;
}
dive[name] = true;
dive.required.push(name);
var deps = allModules[name] || [];
deps.forEach(function (item) {
dive(item);
});
} | [
"function",
"dive",
"(",
"name",
")",
"{",
"if",
"(",
"dive",
"[",
"name",
"]",
")",
"{",
"return",
";",
"}",
"dive",
"[",
"name",
"]",
"=",
"true",
";",
"dive",
".",
"required",
".",
"push",
"(",
"name",
")",
";",
"var",
"deps",
"=",
"allModules",
"[",
"name",
"]",
"||",
"[",
"]",
";",
"deps",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"dive",
"(",
"item",
")",
";",
"}",
")",
";",
"}"
] | recursive function, dive into the dependencies | [
"recursive",
"function",
"dive",
"into",
"the",
"dependencies"
] | 9b6250dada310590b4575e030a1e03293454b98f | https://github.com/fergaldoyle/gulp-require-angular/blob/9b6250dada310590b4575e030a1e03293454b98f/index.js#L25-L38 | train |
mikl/node-drupal | lib/db.js | getClient | function getClient(callback) {
if (!connectionOptions) {
callback('Connection options missing. Please call db.connect before any other database functions to configure the database configuration');
}
if (activeBackend === 'mysql') {
if (activeDb) {
return callback(null, activeDb);
}
else {
connect(connectionOptions);
return callback(null, activeDb);
}
}
else if (activeBackend === 'pgsql') {
return pg.connect(connectionOptions, callback);
}
} | javascript | function getClient(callback) {
if (!connectionOptions) {
callback('Connection options missing. Please call db.connect before any other database functions to configure the database configuration');
}
if (activeBackend === 'mysql') {
if (activeDb) {
return callback(null, activeDb);
}
else {
connect(connectionOptions);
return callback(null, activeDb);
}
}
else if (activeBackend === 'pgsql') {
return pg.connect(connectionOptions, callback);
}
} | [
"function",
"getClient",
"(",
"callback",
")",
"{",
"if",
"(",
"!",
"connectionOptions",
")",
"{",
"callback",
"(",
"'Connection options missing. Please call db.connect before any other database functions to configure the database configuration'",
")",
";",
"}",
"if",
"(",
"activeBackend",
"===",
"'mysql'",
")",
"{",
"if",
"(",
"activeDb",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"activeDb",
")",
";",
"}",
"else",
"{",
"connect",
"(",
"connectionOptions",
")",
";",
"return",
"callback",
"(",
"null",
",",
"activeDb",
")",
";",
"}",
"}",
"else",
"if",
"(",
"activeBackend",
"===",
"'pgsql'",
")",
"{",
"return",
"pg",
".",
"connect",
"(",
"connectionOptions",
",",
"callback",
")",
";",
"}",
"}"
] | Get the client object for the current database connection. | [
"Get",
"the",
"client",
"object",
"for",
"the",
"current",
"database",
"connection",
"."
] | 0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd | https://github.com/mikl/node-drupal/blob/0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd/lib/db.js#L44-L61 | train |
mikl/node-drupal | lib/db.js | runQuery | function runQuery(client, queryString, args, callback) {
if (activeBackend === 'mysql') {
queryString = queryString.replace(/\$\d+/, '?');
}
client.query(queryString, args, function (err, result) {
if (err) {
callback(err, null);
return;
}
if (activeBackend === 'mysql') {
callback(err, result);
}
else if (activeBackend === 'pgsql') {
var rows = [];
if (result.rows) {
rows = result.rows;
}
callback(err, rows);
}
});
} | javascript | function runQuery(client, queryString, args, callback) {
if (activeBackend === 'mysql') {
queryString = queryString.replace(/\$\d+/, '?');
}
client.query(queryString, args, function (err, result) {
if (err) {
callback(err, null);
return;
}
if (activeBackend === 'mysql') {
callback(err, result);
}
else if (activeBackend === 'pgsql') {
var rows = [];
if (result.rows) {
rows = result.rows;
}
callback(err, rows);
}
});
} | [
"function",
"runQuery",
"(",
"client",
",",
"queryString",
",",
"args",
",",
"callback",
")",
"{",
"if",
"(",
"activeBackend",
"===",
"'mysql'",
")",
"{",
"queryString",
"=",
"queryString",
".",
"replace",
"(",
"/",
"\\$\\d+",
"/",
",",
"'?'",
")",
";",
"}",
"client",
".",
"query",
"(",
"queryString",
",",
"args",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"null",
")",
";",
"return",
";",
"}",
"if",
"(",
"activeBackend",
"===",
"'mysql'",
")",
"{",
"callback",
"(",
"err",
",",
"result",
")",
";",
"}",
"else",
"if",
"(",
"activeBackend",
"===",
"'pgsql'",
")",
"{",
"var",
"rows",
"=",
"[",
"]",
";",
"if",
"(",
"result",
".",
"rows",
")",
"{",
"rows",
"=",
"result",
".",
"rows",
";",
"}",
"callback",
"(",
"err",
",",
"rows",
")",
";",
"}",
"}",
")",
";",
"}"
] | Do the actual work of running the query. | [
"Do",
"the",
"actual",
"work",
"of",
"running",
"the",
"query",
"."
] | 0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd | https://github.com/mikl/node-drupal/blob/0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd/lib/db.js#L82-L103 | train |
kt3k/kocha | packages/kocha/src/reporters/json.js | errorJSON | function errorJSON (err) {
var res = {}
Object.getOwnPropertyNames(err).forEach(function (key) {
res[key] = err[key]
}, err)
return res
} | javascript | function errorJSON (err) {
var res = {}
Object.getOwnPropertyNames(err).forEach(function (key) {
res[key] = err[key]
}, err)
return res
} | [
"function",
"errorJSON",
"(",
"err",
")",
"{",
"var",
"res",
"=",
"{",
"}",
"Object",
".",
"getOwnPropertyNames",
"(",
"err",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"res",
"[",
"key",
"]",
"=",
"err",
"[",
"key",
"]",
"}",
",",
"err",
")",
"return",
"res",
"}"
] | Transform `error` into a JSON object.
@api private
@param {Error} err
@return {Object} | [
"Transform",
"error",
"into",
"a",
"JSON",
"object",
"."
] | 3dab0d0a0aaaf152e4a71fa2a68f3835dcdbf68d | https://github.com/kt3k/kocha/blob/3dab0d0a0aaaf152e4a71fa2a68f3835dcdbf68d/packages/kocha/src/reporters/json.js#L80-L86 | train |
lludol/clf-date | src/main.js | getCLFOffset | function getCLFOffset(date) {
const offset = date.getTimezoneOffset().toString();
const op = offset[0] === '-' ? '-' : '+';
let number = offset.replace(op, '');
while (number.length < 4) {
number = `0${number}`;
}
return `${op}${number}`;
} | javascript | function getCLFOffset(date) {
const offset = date.getTimezoneOffset().toString();
const op = offset[0] === '-' ? '-' : '+';
let number = offset.replace(op, '');
while (number.length < 4) {
number = `0${number}`;
}
return `${op}${number}`;
} | [
"function",
"getCLFOffset",
"(",
"date",
")",
"{",
"const",
"offset",
"=",
"date",
".",
"getTimezoneOffset",
"(",
")",
".",
"toString",
"(",
")",
";",
"const",
"op",
"=",
"offset",
"[",
"0",
"]",
"===",
"'-'",
"?",
"'-'",
":",
"'+'",
";",
"let",
"number",
"=",
"offset",
".",
"replace",
"(",
"op",
",",
"''",
")",
";",
"while",
"(",
"number",
".",
"length",
"<",
"4",
")",
"{",
"number",
"=",
"`",
"${",
"number",
"}",
"`",
";",
"}",
"return",
"`",
"${",
"op",
"}",
"${",
"number",
"}",
"`",
";",
"}"
] | Return the offset from UTC in CLF format.
@param {Date} date - The date
@return {String} The offset. | [
"Return",
"the",
"offset",
"from",
"UTC",
"in",
"CLF",
"format",
"."
] | 3c5ee7ac4dc4f034a46b83d910ef328e81257d19 | https://github.com/lludol/clf-date/blob/3c5ee7ac4dc4f034a46b83d910ef328e81257d19/src/main.js#L16-L26 | train |
lammas/tree-traversal | tree-traversal.js | traverseBreadthFirst | function traverseBreadthFirst(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, callback, userdata) { callback(); },
onComplete: function(rootNode) {},
userdata: null
}, options);
var queue = [];
queue.push([rootNode, options.userdata]);
(function next() {
if (queue.length == 0) {
options.onComplete(rootNode);
return;
}
var front = queue.shift();
var node = front[0];
var data = front[1];
options.onNode(node, function() {
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
async.eachSeries(subnodes,
function(subnode, nextNode) {
queue.push([subnode, subnodeData]);
async.setImmediate(nextNode);
},
function() {
async.setImmediate(next);
}
);
},
data);
})();
} | javascript | function traverseBreadthFirst(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, callback, userdata) { callback(); },
onComplete: function(rootNode) {},
userdata: null
}, options);
var queue = [];
queue.push([rootNode, options.userdata]);
(function next() {
if (queue.length == 0) {
options.onComplete(rootNode);
return;
}
var front = queue.shift();
var node = front[0];
var data = front[1];
options.onNode(node, function() {
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
async.eachSeries(subnodes,
function(subnode, nextNode) {
queue.push([subnode, subnodeData]);
async.setImmediate(nextNode);
},
function() {
async.setImmediate(next);
}
);
},
data);
})();
} | [
"function",
"traverseBreadthFirst",
"(",
"rootNode",
",",
"options",
")",
"{",
"options",
"=",
"extend",
"(",
"{",
"subnodesAccessor",
":",
"function",
"(",
"node",
")",
"{",
"return",
"node",
".",
"subnodes",
";",
"}",
",",
"userdataAccessor",
":",
"function",
"(",
"node",
",",
"userdata",
")",
"{",
"return",
"userdata",
";",
"}",
",",
"onNode",
":",
"function",
"(",
"node",
",",
"callback",
",",
"userdata",
")",
"{",
"callback",
"(",
")",
";",
"}",
",",
"onComplete",
":",
"function",
"(",
"rootNode",
")",
"{",
"}",
",",
"userdata",
":",
"null",
"}",
",",
"options",
")",
";",
"var",
"queue",
"=",
"[",
"]",
";",
"queue",
".",
"push",
"(",
"[",
"rootNode",
",",
"options",
".",
"userdata",
"]",
")",
";",
"(",
"function",
"next",
"(",
")",
"{",
"if",
"(",
"queue",
".",
"length",
"==",
"0",
")",
"{",
"options",
".",
"onComplete",
"(",
"rootNode",
")",
";",
"return",
";",
"}",
"var",
"front",
"=",
"queue",
".",
"shift",
"(",
")",
";",
"var",
"node",
"=",
"front",
"[",
"0",
"]",
";",
"var",
"data",
"=",
"front",
"[",
"1",
"]",
";",
"options",
".",
"onNode",
"(",
"node",
",",
"function",
"(",
")",
"{",
"var",
"subnodeData",
"=",
"options",
".",
"userdataAccessor",
"(",
"node",
",",
"data",
")",
";",
"var",
"subnodes",
"=",
"options",
".",
"subnodesAccessor",
"(",
"node",
")",
";",
"async",
".",
"eachSeries",
"(",
"subnodes",
",",
"function",
"(",
"subnode",
",",
"nextNode",
")",
"{",
"queue",
".",
"push",
"(",
"[",
"subnode",
",",
"subnodeData",
"]",
")",
";",
"async",
".",
"setImmediate",
"(",
"nextNode",
")",
";",
"}",
",",
"function",
"(",
")",
"{",
"async",
".",
"setImmediate",
"(",
"next",
")",
";",
"}",
")",
";",
"}",
",",
"data",
")",
";",
"}",
")",
"(",
")",
";",
"}"
] | Asynchronously traverses the tree breadth first. | [
"Asynchronously",
"traverses",
"the",
"tree",
"breadth",
"first",
"."
] | ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47 | https://github.com/lammas/tree-traversal/blob/ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47/tree-traversal.js#L17-L54 | train |
lammas/tree-traversal | tree-traversal.js | traverseBreadthFirstSync | function traverseBreadthFirstSync(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, userdata) {},
userdata: null
}, options);
var queue = [];
queue.push([rootNode, options.userdata]);
while (queue.length>0) {
var front = queue.shift();
var node = front[0];
var data = front[1];
options.onNode(node, data);
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
for (var i=0; i<subnodes.length; i++) {
queue.push([subnodes[i], subnodeData]);
}
}
return rootNode;
} | javascript | function traverseBreadthFirstSync(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, userdata) {},
userdata: null
}, options);
var queue = [];
queue.push([rootNode, options.userdata]);
while (queue.length>0) {
var front = queue.shift();
var node = front[0];
var data = front[1];
options.onNode(node, data);
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
for (var i=0; i<subnodes.length; i++) {
queue.push([subnodes[i], subnodeData]);
}
}
return rootNode;
} | [
"function",
"traverseBreadthFirstSync",
"(",
"rootNode",
",",
"options",
")",
"{",
"options",
"=",
"extend",
"(",
"{",
"subnodesAccessor",
":",
"function",
"(",
"node",
")",
"{",
"return",
"node",
".",
"subnodes",
";",
"}",
",",
"userdataAccessor",
":",
"function",
"(",
"node",
",",
"userdata",
")",
"{",
"return",
"userdata",
";",
"}",
",",
"onNode",
":",
"function",
"(",
"node",
",",
"userdata",
")",
"{",
"}",
",",
"userdata",
":",
"null",
"}",
",",
"options",
")",
";",
"var",
"queue",
"=",
"[",
"]",
";",
"queue",
".",
"push",
"(",
"[",
"rootNode",
",",
"options",
".",
"userdata",
"]",
")",
";",
"while",
"(",
"queue",
".",
"length",
">",
"0",
")",
"{",
"var",
"front",
"=",
"queue",
".",
"shift",
"(",
")",
";",
"var",
"node",
"=",
"front",
"[",
"0",
"]",
";",
"var",
"data",
"=",
"front",
"[",
"1",
"]",
";",
"options",
".",
"onNode",
"(",
"node",
",",
"data",
")",
";",
"var",
"subnodeData",
"=",
"options",
".",
"userdataAccessor",
"(",
"node",
",",
"data",
")",
";",
"var",
"subnodes",
"=",
"options",
".",
"subnodesAccessor",
"(",
"node",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"subnodes",
".",
"length",
";",
"i",
"++",
")",
"{",
"queue",
".",
"push",
"(",
"[",
"subnodes",
"[",
"i",
"]",
",",
"subnodeData",
"]",
")",
";",
"}",
"}",
"return",
"rootNode",
";",
"}"
] | Synchronously traverses the tree breadth first. | [
"Synchronously",
"traverses",
"the",
"tree",
"breadth",
"first",
"."
] | ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47 | https://github.com/lammas/tree-traversal/blob/ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47/tree-traversal.js#L59-L84 | train |
lammas/tree-traversal | tree-traversal.js | traverseDepthFirst | function traverseDepthFirst(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, callback, userdata) { callback(); },
onComplete: function(rootNode) {},
userdata: null
}, options);
var stack = [];
stack.push([rootNode, options.userdata]);
(function next() {
if (stack.length == 0) {
options.onComplete(rootNode);
return;
}
var top = stack.pop();
var node = top[0];
var data = top[1];
options.onNode(node, function() {
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
async.eachSeries(subnodes,
function(subnode, nextNode) {
stack.push([subnode, subnodeData]);
async.setImmediate(nextNode);
},
function() {
async.setImmediate(next);
}
);
}, data);
})();
} | javascript | function traverseDepthFirst(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, callback, userdata) { callback(); },
onComplete: function(rootNode) {},
userdata: null
}, options);
var stack = [];
stack.push([rootNode, options.userdata]);
(function next() {
if (stack.length == 0) {
options.onComplete(rootNode);
return;
}
var top = stack.pop();
var node = top[0];
var data = top[1];
options.onNode(node, function() {
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
async.eachSeries(subnodes,
function(subnode, nextNode) {
stack.push([subnode, subnodeData]);
async.setImmediate(nextNode);
},
function() {
async.setImmediate(next);
}
);
}, data);
})();
} | [
"function",
"traverseDepthFirst",
"(",
"rootNode",
",",
"options",
")",
"{",
"options",
"=",
"extend",
"(",
"{",
"subnodesAccessor",
":",
"function",
"(",
"node",
")",
"{",
"return",
"node",
".",
"subnodes",
";",
"}",
",",
"userdataAccessor",
":",
"function",
"(",
"node",
",",
"userdata",
")",
"{",
"return",
"userdata",
";",
"}",
",",
"onNode",
":",
"function",
"(",
"node",
",",
"callback",
",",
"userdata",
")",
"{",
"callback",
"(",
")",
";",
"}",
",",
"onComplete",
":",
"function",
"(",
"rootNode",
")",
"{",
"}",
",",
"userdata",
":",
"null",
"}",
",",
"options",
")",
";",
"var",
"stack",
"=",
"[",
"]",
";",
"stack",
".",
"push",
"(",
"[",
"rootNode",
",",
"options",
".",
"userdata",
"]",
")",
";",
"(",
"function",
"next",
"(",
")",
"{",
"if",
"(",
"stack",
".",
"length",
"==",
"0",
")",
"{",
"options",
".",
"onComplete",
"(",
"rootNode",
")",
";",
"return",
";",
"}",
"var",
"top",
"=",
"stack",
".",
"pop",
"(",
")",
";",
"var",
"node",
"=",
"top",
"[",
"0",
"]",
";",
"var",
"data",
"=",
"top",
"[",
"1",
"]",
";",
"options",
".",
"onNode",
"(",
"node",
",",
"function",
"(",
")",
"{",
"var",
"subnodeData",
"=",
"options",
".",
"userdataAccessor",
"(",
"node",
",",
"data",
")",
";",
"var",
"subnodes",
"=",
"options",
".",
"subnodesAccessor",
"(",
"node",
")",
";",
"async",
".",
"eachSeries",
"(",
"subnodes",
",",
"function",
"(",
"subnode",
",",
"nextNode",
")",
"{",
"stack",
".",
"push",
"(",
"[",
"subnode",
",",
"subnodeData",
"]",
")",
";",
"async",
".",
"setImmediate",
"(",
"nextNode",
")",
";",
"}",
",",
"function",
"(",
")",
"{",
"async",
".",
"setImmediate",
"(",
"next",
")",
";",
"}",
")",
";",
"}",
",",
"data",
")",
";",
"}",
")",
"(",
")",
";",
"}"
] | Asynchronously traverses the tree depth first. | [
"Asynchronously",
"traverses",
"the",
"tree",
"depth",
"first",
"."
] | ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47 | https://github.com/lammas/tree-traversal/blob/ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47/tree-traversal.js#L90-L126 | train |
lammas/tree-traversal | tree-traversal.js | traverseDepthFirstSync | function traverseDepthFirstSync(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, userdata) {},
userdata: null
}, options);
var stack = [];
stack.push([rootNode, options.userdata]);
while (stack.length>0) {
var top = stack.pop();
var node = top[0];
var data = top[1];
options.onNode(node, data);
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
for (var i=0; i<subnodes.length; i++)
stack.push([subnodes[i], subnodeData]);
}
return rootNode;
} | javascript | function traverseDepthFirstSync(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, userdata) {},
userdata: null
}, options);
var stack = [];
stack.push([rootNode, options.userdata]);
while (stack.length>0) {
var top = stack.pop();
var node = top[0];
var data = top[1];
options.onNode(node, data);
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
for (var i=0; i<subnodes.length; i++)
stack.push([subnodes[i], subnodeData]);
}
return rootNode;
} | [
"function",
"traverseDepthFirstSync",
"(",
"rootNode",
",",
"options",
")",
"{",
"options",
"=",
"extend",
"(",
"{",
"subnodesAccessor",
":",
"function",
"(",
"node",
")",
"{",
"return",
"node",
".",
"subnodes",
";",
"}",
",",
"userdataAccessor",
":",
"function",
"(",
"node",
",",
"userdata",
")",
"{",
"return",
"userdata",
";",
"}",
",",
"onNode",
":",
"function",
"(",
"node",
",",
"userdata",
")",
"{",
"}",
",",
"userdata",
":",
"null",
"}",
",",
"options",
")",
";",
"var",
"stack",
"=",
"[",
"]",
";",
"stack",
".",
"push",
"(",
"[",
"rootNode",
",",
"options",
".",
"userdata",
"]",
")",
";",
"while",
"(",
"stack",
".",
"length",
">",
"0",
")",
"{",
"var",
"top",
"=",
"stack",
".",
"pop",
"(",
")",
";",
"var",
"node",
"=",
"top",
"[",
"0",
"]",
";",
"var",
"data",
"=",
"top",
"[",
"1",
"]",
";",
"options",
".",
"onNode",
"(",
"node",
",",
"data",
")",
";",
"var",
"subnodeData",
"=",
"options",
".",
"userdataAccessor",
"(",
"node",
",",
"data",
")",
";",
"var",
"subnodes",
"=",
"options",
".",
"subnodesAccessor",
"(",
"node",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"subnodes",
".",
"length",
";",
"i",
"++",
")",
"stack",
".",
"push",
"(",
"[",
"subnodes",
"[",
"i",
"]",
",",
"subnodeData",
"]",
")",
";",
"}",
"return",
"rootNode",
";",
"}"
] | Synchronously traverses the tree depth first. | [
"Synchronously",
"traverses",
"the",
"tree",
"depth",
"first",
"."
] | ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47 | https://github.com/lammas/tree-traversal/blob/ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47/tree-traversal.js#L131-L154 | train |
lammas/tree-traversal | tree-traversal.js | traverseRecursive | function traverseRecursive(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
onNode: function(node, callback, userdata) {},
onComplete: function(rootNode) {},
userdata: null
}, options);
(function visitNode(node, callback) {
var subnodes = options.subnodesAccessor(node);
async.eachSeries(subnodes, function(subnode, next) {
visitNode(subnode, function() {
async.setImmediate(next);
});
},
function() {
options.onNode(node, function() {
async.setImmediate(callback);
}, options.userdata);
});
})(rootNode, function() {
options.onComplete(rootNode);
});
} | javascript | function traverseRecursive(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
onNode: function(node, callback, userdata) {},
onComplete: function(rootNode) {},
userdata: null
}, options);
(function visitNode(node, callback) {
var subnodes = options.subnodesAccessor(node);
async.eachSeries(subnodes, function(subnode, next) {
visitNode(subnode, function() {
async.setImmediate(next);
});
},
function() {
options.onNode(node, function() {
async.setImmediate(callback);
}, options.userdata);
});
})(rootNode, function() {
options.onComplete(rootNode);
});
} | [
"function",
"traverseRecursive",
"(",
"rootNode",
",",
"options",
")",
"{",
"options",
"=",
"extend",
"(",
"{",
"subnodesAccessor",
":",
"function",
"(",
"node",
")",
"{",
"return",
"node",
".",
"subnodes",
";",
"}",
",",
"onNode",
":",
"function",
"(",
"node",
",",
"callback",
",",
"userdata",
")",
"{",
"}",
",",
"onComplete",
":",
"function",
"(",
"rootNode",
")",
"{",
"}",
",",
"userdata",
":",
"null",
"}",
",",
"options",
")",
";",
"(",
"function",
"visitNode",
"(",
"node",
",",
"callback",
")",
"{",
"var",
"subnodes",
"=",
"options",
".",
"subnodesAccessor",
"(",
"node",
")",
";",
"async",
".",
"eachSeries",
"(",
"subnodes",
",",
"function",
"(",
"subnode",
",",
"next",
")",
"{",
"visitNode",
"(",
"subnode",
",",
"function",
"(",
")",
"{",
"async",
".",
"setImmediate",
"(",
"next",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
")",
"{",
"options",
".",
"onNode",
"(",
"node",
",",
"function",
"(",
")",
"{",
"async",
".",
"setImmediate",
"(",
"callback",
")",
";",
"}",
",",
"options",
".",
"userdata",
")",
";",
"}",
")",
";",
"}",
")",
"(",
"rootNode",
",",
"function",
"(",
")",
"{",
"options",
".",
"onComplete",
"(",
"rootNode",
")",
";",
"}",
")",
";",
"}"
] | Asynchronously traverses the tree recursively. | [
"Asynchronously",
"traverses",
"the",
"tree",
"recursively",
"."
] | ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47 | https://github.com/lammas/tree-traversal/blob/ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47/tree-traversal.js#L160-L183 | train |
lammas/tree-traversal | tree-traversal.js | traverseRecursiveSync | function traverseRecursiveSync(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
onNode: function(node, userdata) {},
userdata: null
}, options);
(function visitNode(node) {
var subnodes = options.subnodesAccessor(node);
for (var i=0; i<subnodes.length; i++) {
visitNode(subnodes[i]);
}
options.onNode(node, options.userdata);
})(rootNode);
return rootNode;
} | javascript | function traverseRecursiveSync(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
onNode: function(node, userdata) {},
userdata: null
}, options);
(function visitNode(node) {
var subnodes = options.subnodesAccessor(node);
for (var i=0; i<subnodes.length; i++) {
visitNode(subnodes[i]);
}
options.onNode(node, options.userdata);
})(rootNode);
return rootNode;
} | [
"function",
"traverseRecursiveSync",
"(",
"rootNode",
",",
"options",
")",
"{",
"options",
"=",
"extend",
"(",
"{",
"subnodesAccessor",
":",
"function",
"(",
"node",
")",
"{",
"return",
"node",
".",
"subnodes",
";",
"}",
",",
"onNode",
":",
"function",
"(",
"node",
",",
"userdata",
")",
"{",
"}",
",",
"userdata",
":",
"null",
"}",
",",
"options",
")",
";",
"(",
"function",
"visitNode",
"(",
"node",
")",
"{",
"var",
"subnodes",
"=",
"options",
".",
"subnodesAccessor",
"(",
"node",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"subnodes",
".",
"length",
";",
"i",
"++",
")",
"{",
"visitNode",
"(",
"subnodes",
"[",
"i",
"]",
")",
";",
"}",
"options",
".",
"onNode",
"(",
"node",
",",
"options",
".",
"userdata",
")",
";",
"}",
")",
"(",
"rootNode",
")",
";",
"return",
"rootNode",
";",
"}"
] | Synchronously traverses the tree recursively. | [
"Synchronously",
"traverses",
"the",
"tree",
"recursively",
"."
] | ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47 | https://github.com/lammas/tree-traversal/blob/ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47/tree-traversal.js#L188-L204 | train |
dalekjs/dalek-reporter-junit | index.js | Reporter | function Reporter (opts) {
this.events = opts.events;
this.config = opts.config;
this.testCount = 0;
this.testIdx = -1;
this.variationCount = -1;
this.data = {};
this.data.tests = [];
this.browser = null;
var defaultReportFolder = 'report';
this.dest = this.config.get('junit-reporter') && this.config.get('junit-reporter').dest ? this.config.get('junit-reporter').dest : defaultReportFolder;
// prepare base xml
this.xml = [
{
name: 'resource',
attrs: {
name:'DalekJSTest'
},
children: []
}
];
this.startListening();
} | javascript | function Reporter (opts) {
this.events = opts.events;
this.config = opts.config;
this.testCount = 0;
this.testIdx = -1;
this.variationCount = -1;
this.data = {};
this.data.tests = [];
this.browser = null;
var defaultReportFolder = 'report';
this.dest = this.config.get('junit-reporter') && this.config.get('junit-reporter').dest ? this.config.get('junit-reporter').dest : defaultReportFolder;
// prepare base xml
this.xml = [
{
name: 'resource',
attrs: {
name:'DalekJSTest'
},
children: []
}
];
this.startListening();
} | [
"function",
"Reporter",
"(",
"opts",
")",
"{",
"this",
".",
"events",
"=",
"opts",
".",
"events",
";",
"this",
".",
"config",
"=",
"opts",
".",
"config",
";",
"this",
".",
"testCount",
"=",
"0",
";",
"this",
".",
"testIdx",
"=",
"-",
"1",
";",
"this",
".",
"variationCount",
"=",
"-",
"1",
";",
"this",
".",
"data",
"=",
"{",
"}",
";",
"this",
".",
"data",
".",
"tests",
"=",
"[",
"]",
";",
"this",
".",
"browser",
"=",
"null",
";",
"var",
"defaultReportFolder",
"=",
"'report'",
";",
"this",
".",
"dest",
"=",
"this",
".",
"config",
".",
"get",
"(",
"'junit-reporter'",
")",
"&&",
"this",
".",
"config",
".",
"get",
"(",
"'junit-reporter'",
")",
".",
"dest",
"?",
"this",
".",
"config",
".",
"get",
"(",
"'junit-reporter'",
")",
".",
"dest",
":",
"defaultReportFolder",
";",
"this",
".",
"xml",
"=",
"[",
"{",
"name",
":",
"'resource'",
",",
"attrs",
":",
"{",
"name",
":",
"'DalekJSTest'",
"}",
",",
"children",
":",
"[",
"]",
"}",
"]",
";",
"this",
".",
"startListening",
"(",
")",
";",
"}"
] | The jUnit reporter can produce a jUnit compatible file with the results of your testrun,
this reporter enables you to use daleks testresults within a CI environment like Jenkins.
The reporter can be installed with the following command:
```bash
$ npm install dalek-reporter-junit --save-dev
```
The file will follow the jUnit XML format:
```html
<?xml version="1.0" encoding="utf-8"?>
<resource name="DalekJSTest">
<testsuite start="1375125067" name="Click - DalekJS guinea pig [Phantomjs]" end="1375125067" totalTests="1">
<testcase start="1375125067" name="Can click a select option (OK, jQuery style, no message)" end="1375125067" result="pass">
<variation start="1375125067" name="val" end="1375125067">
<severity>pass</severity>
<description><![CDATA[David is the favourite]]></description>
<resource>DalekJSTest</resource>
</variation>
<variation start="1375125067" name="val" end="1375125067">
<severity>pass</severity>
<description><![CDATA[Matt is now my favourite, bow ties are cool]]></description>
<resource>DalekJSTest</resource>
</variation>
</testcase>
</testsuite>
</resource>
```
By default the file will be written to `report/dalek.xml`,
you can change this by adding a config option to the your Dalekfile
```javascript
"junit-reporter": {
"dest": "your/folder/your_file.xml"
}
```
If you would like to use the reporter (in addition to the std. console reporter),
you can start dalek with a special command line argument
```bash
$ dalek your_test.js -r console,junit
```
or you can add it to your Dalekfile
```javascript
"reporter": ["console", "junit"]
```
@class Reporter
@constructor
@part JUnit
@api | [
"The",
"jUnit",
"reporter",
"can",
"produce",
"a",
"jUnit",
"compatible",
"file",
"with",
"the",
"results",
"of",
"your",
"testrun",
"this",
"reporter",
"enables",
"you",
"to",
"use",
"daleks",
"testresults",
"within",
"a",
"CI",
"environment",
"like",
"Jenkins",
"."
] | af67e4716ad02b911f450d0a0333e0e7d92752df | https://github.com/dalekjs/dalek-reporter-junit/blob/af67e4716ad02b911f450d0a0333e0e7d92752df/index.js#L95-L120 | train |
dalekjs/dalek-reporter-junit | index.js | function (name) {
this.testCount = 0;
this.testIdx++;
this.xml[0].children.push({
name: 'testsuite',
children: [],
attrs: {
name: name + ' [' + this.browser + ']',
}
});
return this;
} | javascript | function (name) {
this.testCount = 0;
this.testIdx++;
this.xml[0].children.push({
name: 'testsuite',
children: [],
attrs: {
name: name + ' [' + this.browser + ']',
}
});
return this;
} | [
"function",
"(",
"name",
")",
"{",
"this",
".",
"testCount",
"=",
"0",
";",
"this",
".",
"testIdx",
"++",
";",
"this",
".",
"xml",
"[",
"0",
"]",
".",
"children",
".",
"push",
"(",
"{",
"name",
":",
"'testsuite'",
",",
"children",
":",
"[",
"]",
",",
"attrs",
":",
"{",
"name",
":",
"name",
"+",
"' ['",
"+",
"this",
".",
"browser",
"+",
"']'",
",",
"}",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Generates XML skeleton for testsuites
@method testsuiteStarted
@param {string} name Testsuite name
@chainable | [
"Generates",
"XML",
"skeleton",
"for",
"testsuites"
] | af67e4716ad02b911f450d0a0333e0e7d92752df | https://github.com/dalekjs/dalek-reporter-junit/blob/af67e4716ad02b911f450d0a0333e0e7d92752df/index.js#L175-L186 | train |
|
dalekjs/dalek-reporter-junit | index.js | function (data) {
if (! data.success) {
//var timestamp = Math.round(new Date().getTime() / 1000);
this.xml[0].children[this.testIdx].children[this.testCount].children.push({
name: 'failure',
attrs: {
name: data.type,
message: (data.message ? data.message : 'Expected: ' + data.expected + 'Actual: ' + data.value)
}
});
//if (this.variationCount > -1 && this.xml[0].children[this.testIdx].children[this.testCount].children[this.variationCount]) {
//this.xml[0].children[this.testIdx].children[this.testCount].children[this.variationCount].attrs.end = timestamp;
//}
this.variationCount++;
}
return this;
} | javascript | function (data) {
if (! data.success) {
//var timestamp = Math.round(new Date().getTime() / 1000);
this.xml[0].children[this.testIdx].children[this.testCount].children.push({
name: 'failure',
attrs: {
name: data.type,
message: (data.message ? data.message : 'Expected: ' + data.expected + 'Actual: ' + data.value)
}
});
//if (this.variationCount > -1 && this.xml[0].children[this.testIdx].children[this.testCount].children[this.variationCount]) {
//this.xml[0].children[this.testIdx].children[this.testCount].children[this.variationCount].attrs.end = timestamp;
//}
this.variationCount++;
}
return this;
} | [
"function",
"(",
"data",
")",
"{",
"if",
"(",
"!",
"data",
".",
"success",
")",
"{",
"this",
".",
"xml",
"[",
"0",
"]",
".",
"children",
"[",
"this",
".",
"testIdx",
"]",
".",
"children",
"[",
"this",
".",
"testCount",
"]",
".",
"children",
".",
"push",
"(",
"{",
"name",
":",
"'failure'",
",",
"attrs",
":",
"{",
"name",
":",
"data",
".",
"type",
",",
"message",
":",
"(",
"data",
".",
"message",
"?",
"data",
".",
"message",
":",
"'Expected: '",
"+",
"data",
".",
"expected",
"+",
"'Actual: '",
"+",
"data",
".",
"value",
")",
"}",
"}",
")",
";",
"this",
".",
"variationCount",
"++",
";",
"}",
"return",
"this",
";",
"}"
] | Generates XML skeleton for an assertion
@method assertion
@param {object} data Event data
@chainable | [
"Generates",
"XML",
"skeleton",
"for",
"an",
"assertion"
] | af67e4716ad02b911f450d0a0333e0e7d92752df | https://github.com/dalekjs/dalek-reporter-junit/blob/af67e4716ad02b911f450d0a0333e0e7d92752df/index.js#L208-L227 | train |
|
dalekjs/dalek-reporter-junit | index.js | function (data) {
this.variationCount = -1;
this.xml[0].children[this.testIdx].children.push({
name: 'testcase',
children: [],
attrs: {
classname: this.xml[0].children[this.testIdx].attrs.name,
name: data.name
}
});
return this;
} | javascript | function (data) {
this.variationCount = -1;
this.xml[0].children[this.testIdx].children.push({
name: 'testcase',
children: [],
attrs: {
classname: this.xml[0].children[this.testIdx].attrs.name,
name: data.name
}
});
return this;
} | [
"function",
"(",
"data",
")",
"{",
"this",
".",
"variationCount",
"=",
"-",
"1",
";",
"this",
".",
"xml",
"[",
"0",
"]",
".",
"children",
"[",
"this",
".",
"testIdx",
"]",
".",
"children",
".",
"push",
"(",
"{",
"name",
":",
"'testcase'",
",",
"children",
":",
"[",
"]",
",",
"attrs",
":",
"{",
"classname",
":",
"this",
".",
"xml",
"[",
"0",
"]",
".",
"children",
"[",
"this",
".",
"testIdx",
"]",
".",
"attrs",
".",
"name",
",",
"name",
":",
"data",
".",
"name",
"}",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Generates XML skeleton for a testcase
@method testStarted
@param {object} data Event data
@chainable | [
"Generates",
"XML",
"skeleton",
"for",
"a",
"testcase"
] | af67e4716ad02b911f450d0a0333e0e7d92752df | https://github.com/dalekjs/dalek-reporter-junit/blob/af67e4716ad02b911f450d0a0333e0e7d92752df/index.js#L237-L249 | train |
|
dalekjs/dalek-reporter-junit | index.js | function () {
//var timestamp = Math.round(new Date().getTime() / 1000);
if (this._checkNodeAttributes(this.testIdx, this.testCount)) {
this.xml[0].children[this.testIdx].children[this.testCount].attrs = {};
}
//this.xml[0].children[this.testIdx].children[this.testCount].attrs.end = timestamp;
//this.xml[0].children[this.testIdx].children[this.testCount].attrs.result = data.status ? 'Passed' : 'Failed';
if (this.variationCount > -1) {
if (this._checkNodeAttributes(this.testIdx, this.testCount, this.variationCount)) {
this.xml[0].children[this.testIdx].children[this.testCount].children[this.variationCount].attrs = {};
}
//this.xml[0].children[this.testIdx].children[this.testCount].children[this.variationCount].attrs.end = timestamp;
}
this.testCount++;
this.variationCount = -1;
return this;
} | javascript | function () {
//var timestamp = Math.round(new Date().getTime() / 1000);
if (this._checkNodeAttributes(this.testIdx, this.testCount)) {
this.xml[0].children[this.testIdx].children[this.testCount].attrs = {};
}
//this.xml[0].children[this.testIdx].children[this.testCount].attrs.end = timestamp;
//this.xml[0].children[this.testIdx].children[this.testCount].attrs.result = data.status ? 'Passed' : 'Failed';
if (this.variationCount > -1) {
if (this._checkNodeAttributes(this.testIdx, this.testCount, this.variationCount)) {
this.xml[0].children[this.testIdx].children[this.testCount].children[this.variationCount].attrs = {};
}
//this.xml[0].children[this.testIdx].children[this.testCount].children[this.variationCount].attrs.end = timestamp;
}
this.testCount++;
this.variationCount = -1;
return this;
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"_checkNodeAttributes",
"(",
"this",
".",
"testIdx",
",",
"this",
".",
"testCount",
")",
")",
"{",
"this",
".",
"xml",
"[",
"0",
"]",
".",
"children",
"[",
"this",
".",
"testIdx",
"]",
".",
"children",
"[",
"this",
".",
"testCount",
"]",
".",
"attrs",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"this",
".",
"variationCount",
">",
"-",
"1",
")",
"{",
"if",
"(",
"this",
".",
"_checkNodeAttributes",
"(",
"this",
".",
"testIdx",
",",
"this",
".",
"testCount",
",",
"this",
".",
"variationCount",
")",
")",
"{",
"this",
".",
"xml",
"[",
"0",
"]",
".",
"children",
"[",
"this",
".",
"testIdx",
"]",
".",
"children",
"[",
"this",
".",
"testCount",
"]",
".",
"children",
"[",
"this",
".",
"variationCount",
"]",
".",
"attrs",
"=",
"{",
"}",
";",
"}",
"}",
"this",
".",
"testCount",
"++",
";",
"this",
".",
"variationCount",
"=",
"-",
"1",
";",
"return",
"this",
";",
"}"
] | Finishes XML skeleton for a testcase
@method testFinished
@param {object} data Event data
@chainable | [
"Finishes",
"XML",
"skeleton",
"for",
"a",
"testcase"
] | af67e4716ad02b911f450d0a0333e0e7d92752df | https://github.com/dalekjs/dalek-reporter-junit/blob/af67e4716ad02b911f450d0a0333e0e7d92752df/index.js#L259-L278 | train |
|
dalekjs/dalek-reporter-junit | index.js | function (data) {
this.data.elapsedTime = data.elapsedTime;
this.data.status = data.status;
this.data.assertions = data.assertions;
this.data.assertionsFailed = data.assertionsFailed;
this.data.assertionsPassed = data.assertionsPassed;
var contents = jsonxml(this.xml, {escape: true, removeIllegalNameCharacters: true, prettyPrint: true, xmlHeader: 'version="1.0" encoding="UTF-8"'});
if (path.extname(this.dest) !== '.xml') {
this.dest = this.dest + '/dalek.xml';
}
this.events.emit('report:written', {type: 'junit', dest: this.dest});
this._recursiveMakeDirSync(path.dirname(this.dest.replace(path.basename(this.dest, ''))));
fs.writeFileSync(this.dest, contents, 'utf8');
} | javascript | function (data) {
this.data.elapsedTime = data.elapsedTime;
this.data.status = data.status;
this.data.assertions = data.assertions;
this.data.assertionsFailed = data.assertionsFailed;
this.data.assertionsPassed = data.assertionsPassed;
var contents = jsonxml(this.xml, {escape: true, removeIllegalNameCharacters: true, prettyPrint: true, xmlHeader: 'version="1.0" encoding="UTF-8"'});
if (path.extname(this.dest) !== '.xml') {
this.dest = this.dest + '/dalek.xml';
}
this.events.emit('report:written', {type: 'junit', dest: this.dest});
this._recursiveMakeDirSync(path.dirname(this.dest.replace(path.basename(this.dest, ''))));
fs.writeFileSync(this.dest, contents, 'utf8');
} | [
"function",
"(",
"data",
")",
"{",
"this",
".",
"data",
".",
"elapsedTime",
"=",
"data",
".",
"elapsedTime",
";",
"this",
".",
"data",
".",
"status",
"=",
"data",
".",
"status",
";",
"this",
".",
"data",
".",
"assertions",
"=",
"data",
".",
"assertions",
";",
"this",
".",
"data",
".",
"assertionsFailed",
"=",
"data",
".",
"assertionsFailed",
";",
"this",
".",
"data",
".",
"assertionsPassed",
"=",
"data",
".",
"assertionsPassed",
";",
"var",
"contents",
"=",
"jsonxml",
"(",
"this",
".",
"xml",
",",
"{",
"escape",
":",
"true",
",",
"removeIllegalNameCharacters",
":",
"true",
",",
"prettyPrint",
":",
"true",
",",
"xmlHeader",
":",
"'version=\"1.0\" encoding=\"UTF-8\"'",
"}",
")",
";",
"if",
"(",
"path",
".",
"extname",
"(",
"this",
".",
"dest",
")",
"!==",
"'.xml'",
")",
"{",
"this",
".",
"dest",
"=",
"this",
".",
"dest",
"+",
"'/dalek.xml'",
";",
"}",
"this",
".",
"events",
".",
"emit",
"(",
"'report:written'",
",",
"{",
"type",
":",
"'junit'",
",",
"dest",
":",
"this",
".",
"dest",
"}",
")",
";",
"this",
".",
"_recursiveMakeDirSync",
"(",
"path",
".",
"dirname",
"(",
"this",
".",
"dest",
".",
"replace",
"(",
"path",
".",
"basename",
"(",
"this",
".",
"dest",
",",
"''",
")",
")",
")",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"this",
".",
"dest",
",",
"contents",
",",
"'utf8'",
")",
";",
"}"
] | Finishes XML and writes file to the file system
@method runnerFinished
@param {object} data Event data
@chainable | [
"Finishes",
"XML",
"and",
"writes",
"file",
"to",
"the",
"file",
"system"
] | af67e4716ad02b911f450d0a0333e0e7d92752df | https://github.com/dalekjs/dalek-reporter-junit/blob/af67e4716ad02b911f450d0a0333e0e7d92752df/index.js#L288-L304 | train |
|
dalekjs/dalek-reporter-junit | index.js | function (path) {
var pathSep = require('path').sep;
var dirs = path.split(pathSep);
var root = '';
while (dirs.length > 0) {
var dir = dirs.shift();
if (dir === '') {
root = pathSep;
}
if (!fs.existsSync(root + dir)) {
fs.mkdirSync(root + dir);
}
root += dir + pathSep;
}
} | javascript | function (path) {
var pathSep = require('path').sep;
var dirs = path.split(pathSep);
var root = '';
while (dirs.length > 0) {
var dir = dirs.shift();
if (dir === '') {
root = pathSep;
}
if (!fs.existsSync(root + dir)) {
fs.mkdirSync(root + dir);
}
root += dir + pathSep;
}
} | [
"function",
"(",
"path",
")",
"{",
"var",
"pathSep",
"=",
"require",
"(",
"'path'",
")",
".",
"sep",
";",
"var",
"dirs",
"=",
"path",
".",
"split",
"(",
"pathSep",
")",
";",
"var",
"root",
"=",
"''",
";",
"while",
"(",
"dirs",
".",
"length",
">",
"0",
")",
"{",
"var",
"dir",
"=",
"dirs",
".",
"shift",
"(",
")",
";",
"if",
"(",
"dir",
"===",
"''",
")",
"{",
"root",
"=",
"pathSep",
";",
"}",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"root",
"+",
"dir",
")",
")",
"{",
"fs",
".",
"mkdirSync",
"(",
"root",
"+",
"dir",
")",
";",
"}",
"root",
"+=",
"dir",
"+",
"pathSep",
";",
"}",
"}"
] | Helper method to generate deeper nested directory structures
@method _recursiveMakeDirSync
@param {string} path PAth to create | [
"Helper",
"method",
"to",
"generate",
"deeper",
"nested",
"directory",
"structures"
] | af67e4716ad02b911f450d0a0333e0e7d92752df | https://github.com/dalekjs/dalek-reporter-junit/blob/af67e4716ad02b911f450d0a0333e0e7d92752df/index.js#L313-L328 | train |
|
dalekjs/dalek-reporter-junit | index.js | function (testIdx, testCount, variationCount) {
if (variationCount === undefined) {
return typeof this.xml[0].children[testIdx].children[testCount].attrs === 'undefined';
}
return typeof this.xml[0].children[testIdx].children[testCount].children[variationCount].attrs === 'undefined';
} | javascript | function (testIdx, testCount, variationCount) {
if (variationCount === undefined) {
return typeof this.xml[0].children[testIdx].children[testCount].attrs === 'undefined';
}
return typeof this.xml[0].children[testIdx].children[testCount].children[variationCount].attrs === 'undefined';
} | [
"function",
"(",
"testIdx",
",",
"testCount",
",",
"variationCount",
")",
"{",
"if",
"(",
"variationCount",
"===",
"undefined",
")",
"{",
"return",
"typeof",
"this",
".",
"xml",
"[",
"0",
"]",
".",
"children",
"[",
"testIdx",
"]",
".",
"children",
"[",
"testCount",
"]",
".",
"attrs",
"===",
"'undefined'",
";",
"}",
"return",
"typeof",
"this",
".",
"xml",
"[",
"0",
"]",
".",
"children",
"[",
"testIdx",
"]",
".",
"children",
"[",
"testCount",
"]",
".",
"children",
"[",
"variationCount",
"]",
".",
"attrs",
"===",
"'undefined'",
";",
"}"
] | Helper method to check if attributes should be set to an empty object literal
@method _checkNodeAttributes
@param {string} testIdx Id of the test node
@param {string} testCount Id of the child node
@param {string} variationCount Id of the testCount child node | [
"Helper",
"method",
"to",
"check",
"if",
"attributes",
"should",
"be",
"set",
"to",
"an",
"empty",
"object",
"literal"
] | af67e4716ad02b911f450d0a0333e0e7d92752df | https://github.com/dalekjs/dalek-reporter-junit/blob/af67e4716ad02b911f450d0a0333e0e7d92752df/index.js#L339-L345 | train |
|
folktale/control.async | lib/core.js | resolveFuture | function resolveFuture(reject, resolve) {
state = STARTED
return future.fork( function(error) { state = REJECTED
value = error
invokePending('rejected', error)
return reject(error) }
, function(data) { state = RESOLVED
value = data
invokePending('resolved', data)
return resolve(data) })} | javascript | function resolveFuture(reject, resolve) {
state = STARTED
return future.fork( function(error) { state = REJECTED
value = error
invokePending('rejected', error)
return reject(error) }
, function(data) { state = RESOLVED
value = data
invokePending('resolved', data)
return resolve(data) })} | [
"function",
"resolveFuture",
"(",
"reject",
",",
"resolve",
")",
"{",
"state",
"=",
"STARTED",
"return",
"future",
".",
"fork",
"(",
"function",
"(",
"error",
")",
"{",
"state",
"=",
"REJECTED",
"value",
"=",
"error",
"invokePending",
"(",
"'rejected'",
",",
"error",
")",
"return",
"reject",
"(",
"error",
")",
"}",
",",
"function",
"(",
"data",
")",
"{",
"state",
"=",
"RESOLVED",
"value",
"=",
"data",
"invokePending",
"(",
"'resolved'",
",",
"data",
")",
"return",
"resolve",
"(",
"data",
")",
"}",
")",
"}"
] | Resolves the future, places the machine in a resolved state, and invokes all pending operations. | [
"Resolves",
"the",
"future",
"places",
"the",
"machine",
"in",
"a",
"resolved",
"state",
"and",
"invokes",
"all",
"pending",
"operations",
"."
] | 83f4d2a16cb3d2739ee58ae69372deb53fc38835 | https://github.com/folktale/control.async/blob/83f4d2a16cb3d2739ee58ae69372deb53fc38835/lib/core.js#L92-L102 | train |
folktale/control.async | lib/core.js | invokePending | function invokePending(kind, data) {
var xs = pending
pending.length = 0
for (var i = 0; i < xs.length; ++i) xs[i][kind](value) } | javascript | function invokePending(kind, data) {
var xs = pending
pending.length = 0
for (var i = 0; i < xs.length; ++i) xs[i][kind](value) } | [
"function",
"invokePending",
"(",
"kind",
",",
"data",
")",
"{",
"var",
"xs",
"=",
"pending",
"pending",
".",
"length",
"=",
"0",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"xs",
".",
"length",
";",
"++",
"i",
")",
"xs",
"[",
"i",
"]",
"[",
"kind",
"]",
"(",
"value",
")",
"}"
] | Invokes all pending operations. | [
"Invokes",
"all",
"pending",
"operations",
"."
] | 83f4d2a16cb3d2739ee58ae69372deb53fc38835 | https://github.com/folktale/control.async/blob/83f4d2a16cb3d2739ee58ae69372deb53fc38835/lib/core.js#L105-L108 | train |
dsfields/elv | lib/index.js | function (val) {
return (!behavior.enableUndefined || typeof val !== 'undefined')
&& (!behavior.enableNull || val !== null)
&& (!behavior.enableFalse || val !== false)
&& (!behavior.enableNaN || !Number.isNaN(val));
} | javascript | function (val) {
return (!behavior.enableUndefined || typeof val !== 'undefined')
&& (!behavior.enableNull || val !== null)
&& (!behavior.enableFalse || val !== false)
&& (!behavior.enableNaN || !Number.isNaN(val));
} | [
"function",
"(",
"val",
")",
"{",
"return",
"(",
"!",
"behavior",
".",
"enableUndefined",
"||",
"typeof",
"val",
"!==",
"'undefined'",
")",
"&&",
"(",
"!",
"behavior",
".",
"enableNull",
"||",
"val",
"!==",
"null",
")",
"&&",
"(",
"!",
"behavior",
".",
"enableFalse",
"||",
"val",
"!==",
"false",
")",
"&&",
"(",
"!",
"behavior",
".",
"enableNaN",
"||",
"!",
"Number",
".",
"isNaN",
"(",
"val",
")",
")",
";",
"}"
] | Checks if the provided value is defined.
@method
@param {*} val - The value on which to perform an existential check.
@returns {boolean} | [
"Checks",
"if",
"the",
"provided",
"value",
"is",
"defined",
"."
] | c603170c645b6ad0c2df6d7f8ba572bf77821ede | https://github.com/dsfields/elv/blob/c603170c645b6ad0c2df6d7f8ba572bf77821ede/lib/index.js#L21-L26 | train |
|
cgiffard/SteamShovel | lib/instrumentor.js | function (node) {
// Does this node have a body? If so we can replace its contents.
if (node.body && node.body.length) {
node.body =
[].slice.call(node.body, 0)
.reduce(function(body, node) {
if (!~allowedPrepend.indexOf(node.type))
return body.concat(node);
id++;
sourceMapAdd(id, node, true);
return body.concat(
expressionStatement(
callExpression(filetag, id)
),
node
);
}, []);
}
if (node.noReplace)
return;
// If we're allowed to replace the node,
// replace it with a Call Expression.
if (~allowedReplacements.indexOf(node.type))
return (
id ++,
sourceMapAdd(id, node, false),
callExpression(filetag, id, node)
);
} | javascript | function (node) {
// Does this node have a body? If so we can replace its contents.
if (node.body && node.body.length) {
node.body =
[].slice.call(node.body, 0)
.reduce(function(body, node) {
if (!~allowedPrepend.indexOf(node.type))
return body.concat(node);
id++;
sourceMapAdd(id, node, true);
return body.concat(
expressionStatement(
callExpression(filetag, id)
),
node
);
}, []);
}
if (node.noReplace)
return;
// If we're allowed to replace the node,
// replace it with a Call Expression.
if (~allowedReplacements.indexOf(node.type))
return (
id ++,
sourceMapAdd(id, node, false),
callExpression(filetag, id, node)
);
} | [
"function",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"body",
"&&",
"node",
".",
"body",
".",
"length",
")",
"{",
"node",
".",
"body",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"node",
".",
"body",
",",
"0",
")",
".",
"reduce",
"(",
"function",
"(",
"body",
",",
"node",
")",
"{",
"if",
"(",
"!",
"~",
"allowedPrepend",
".",
"indexOf",
"(",
"node",
".",
"type",
")",
")",
"return",
"body",
".",
"concat",
"(",
"node",
")",
";",
"id",
"++",
";",
"sourceMapAdd",
"(",
"id",
",",
"node",
",",
"true",
")",
";",
"return",
"body",
".",
"concat",
"(",
"expressionStatement",
"(",
"callExpression",
"(",
"filetag",
",",
"id",
")",
")",
",",
"node",
")",
";",
"}",
",",
"[",
"]",
")",
";",
"}",
"if",
"(",
"node",
".",
"noReplace",
")",
"return",
";",
"if",
"(",
"~",
"allowedReplacements",
".",
"indexOf",
"(",
"node",
".",
"type",
")",
")",
"return",
"(",
"id",
"++",
",",
"sourceMapAdd",
"(",
"id",
",",
"node",
",",
"false",
")",
",",
"callExpression",
"(",
"filetag",
",",
"id",
",",
"node",
")",
")",
";",
"}"
] | Leave is where we replace the actual nodes. | [
"Leave",
"is",
"where",
"we",
"replace",
"the",
"actual",
"nodes",
"."
] | 7c9a4baf4e1f9390b352742ab26a6900c78b6e25 | https://github.com/cgiffard/SteamShovel/blob/7c9a4baf4e1f9390b352742ab26a6900c78b6e25/lib/instrumentor.js#L102-L138 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.