id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
54,800 | Jam3/innkeeper | lib/storeRedis.js | function( roomID ) {
if( keys.length > 0 ) {
var randIdx = Math.round( Math.random() * ( keys.length - 1 ) ),
key = keys.splice( randIdx, 1 )[ 0 ];
keyToId[ key ] = roomID;
idToKey[ roomID ] = key;
return promise.resolve( key );
} else {
return promise.reject( 'Run out of keys' );
}
} | javascript | function( roomID ) {
if( keys.length > 0 ) {
var randIdx = Math.round( Math.random() * ( keys.length - 1 ) ),
key = keys.splice( randIdx, 1 )[ 0 ];
keyToId[ key ] = roomID;
idToKey[ roomID ] = key;
return promise.resolve( key );
} else {
return promise.reject( 'Run out of keys' );
}
} | [
"function",
"(",
"roomID",
")",
"{",
"if",
"(",
"keys",
".",
"length",
">",
"0",
")",
"{",
"var",
"randIdx",
"=",
"Math",
".",
"round",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"(",
"keys",
".",
"length",
"-",
"1",
")",
")",
",",
"key",
"=",
"keys",
".",
"splice",
"(",
"randIdx",
",",
"1",
")",
"[",
"0",
"]",
";",
"keyToId",
"[",
"key",
"]",
"=",
"roomID",
";",
"idToKey",
"[",
"roomID",
"]",
"=",
"key",
";",
"return",
"promise",
".",
"resolve",
"(",
"key",
")",
";",
"}",
"else",
"{",
"return",
"promise",
".",
"reject",
"(",
"'Run out of keys'",
")",
";",
"}",
"}"
] | get a key which can be used to enter a room vs entering room via
roomID
@param {String} roomID id of the room you'd like a key for
@return {Promise} A promise will be returned which will return a roomKey on success | [
"get",
"a",
"key",
"which",
"can",
"be",
"used",
"to",
"enter",
"a",
"room",
"vs",
"entering",
"room",
"via",
"roomID"
] | 95182271c62cf4416442c825189f025234b6ef1e | https://github.com/Jam3/innkeeper/blob/95182271c62cf4416442c825189f025234b6ef1e/lib/storeRedis.js#L118-L133 |
|
54,801 | Jam3/innkeeper | lib/storeRedis.js | function( roomID, key ) {
return this.getRoomIdForKey( key )
.then( function( savedRoomId ) {
if( savedRoomId == roomID ) {
delete idToKey[ roomID ];
delete keyToId[ key ];
keys.push( key );
return promise.resolve();
} else {
return promise.reject( 'roomID and roomID for key do not match' );
}
});
} | javascript | function( roomID, key ) {
return this.getRoomIdForKey( key )
.then( function( savedRoomId ) {
if( savedRoomId == roomID ) {
delete idToKey[ roomID ];
delete keyToId[ key ];
keys.push( key );
return promise.resolve();
} else {
return promise.reject( 'roomID and roomID for key do not match' );
}
});
} | [
"function",
"(",
"roomID",
",",
"key",
")",
"{",
"return",
"this",
".",
"getRoomIdForKey",
"(",
"key",
")",
".",
"then",
"(",
"function",
"(",
"savedRoomId",
")",
"{",
"if",
"(",
"savedRoomId",
"==",
"roomID",
")",
"{",
"delete",
"idToKey",
"[",
"roomID",
"]",
";",
"delete",
"keyToId",
"[",
"key",
"]",
";",
"keys",
".",
"push",
"(",
"key",
")",
";",
"return",
"promise",
".",
"resolve",
"(",
")",
";",
"}",
"else",
"{",
"return",
"promise",
".",
"reject",
"(",
"'roomID and roomID for key do not match'",
")",
";",
"}",
"}",
")",
";",
"}"
] | return a room key so someone else can use it.
@param {String} roomID id of the room you'll be returning a key for
@param {String} key the key you'd like to return
@return {Promise} This promise will succeed when the room key was returned | [
"return",
"a",
"room",
"key",
"so",
"someone",
"else",
"can",
"use",
"it",
"."
] | 95182271c62cf4416442c825189f025234b6ef1e | https://github.com/Jam3/innkeeper/blob/95182271c62cf4416442c825189f025234b6ef1e/lib/storeRedis.js#L142-L160 |
|
54,802 | Jam3/innkeeper | lib/storeRedis.js | function( key ) {
var savedRoomId = keyToId[ key ];
if( savedRoomId ) {
return promise.resolve( savedRoomId );
} else {
return promise.reject();
}
} | javascript | function( key ) {
var savedRoomId = keyToId[ key ];
if( savedRoomId ) {
return promise.resolve( savedRoomId );
} else {
return promise.reject();
}
} | [
"function",
"(",
"key",
")",
"{",
"var",
"savedRoomId",
"=",
"keyToId",
"[",
"key",
"]",
";",
"if",
"(",
"savedRoomId",
")",
"{",
"return",
"promise",
".",
"resolve",
"(",
"savedRoomId",
")",
";",
"}",
"else",
"{",
"return",
"promise",
".",
"reject",
"(",
")",
";",
"}",
"}"
] | return the room id for the given key
@param {String} key key used to enter the room
@return {Promise} This promise will succeed with the room id and fail if no room id exists for key | [
"return",
"the",
"room",
"id",
"for",
"the",
"given",
"key"
] | 95182271c62cf4416442c825189f025234b6ef1e | https://github.com/Jam3/innkeeper/blob/95182271c62cf4416442c825189f025234b6ef1e/lib/storeRedis.js#L168-L179 |
|
54,803 | Jam3/innkeeper | lib/storeRedis.js | function( roomID, key, value ) {
if( roomData[ roomID ] === undefined )
roomData[ roomID ] = {};
roomData[ roomID ][ key ] = value;
return promise.resolve( value );
} | javascript | function( roomID, key, value ) {
if( roomData[ roomID ] === undefined )
roomData[ roomID ] = {};
roomData[ roomID ][ key ] = value;
return promise.resolve( value );
} | [
"function",
"(",
"roomID",
",",
"key",
",",
"value",
")",
"{",
"if",
"(",
"roomData",
"[",
"roomID",
"]",
"===",
"undefined",
")",
"roomData",
"[",
"roomID",
"]",
"=",
"{",
"}",
";",
"roomData",
"[",
"roomID",
"]",
"[",
"key",
"]",
"=",
"value",
";",
"return",
"promise",
".",
"resolve",
"(",
"value",
")",
";",
"}"
] | set a variable on the rooms data object
@param {String} roomID id for the room whose
@param {String} key variable name/key that you want to set
@param {*} value Value you'd like to set for the variable
@return {Promise} once this promise succeeds the rooms variable will be set | [
"set",
"a",
"variable",
"on",
"the",
"rooms",
"data",
"object"
] | 95182271c62cf4416442c825189f025234b6ef1e | https://github.com/Jam3/innkeeper/blob/95182271c62cf4416442c825189f025234b6ef1e/lib/storeRedis.js#L189-L197 |
|
54,804 | Jam3/innkeeper | lib/storeRedis.js | function( roomID, key ) {
if( roomData[ roomID ] === undefined ) {
return promise.reject( 'There is no room by that id' );
} else {
return promise.resolve( roomData[ roomID ][ key ] );
}
} | javascript | function( roomID, key ) {
if( roomData[ roomID ] === undefined ) {
return promise.reject( 'There is no room by that id' );
} else {
return promise.resolve( roomData[ roomID ][ key ] );
}
} | [
"function",
"(",
"roomID",
",",
"key",
")",
"{",
"if",
"(",
"roomData",
"[",
"roomID",
"]",
"===",
"undefined",
")",
"{",
"return",
"promise",
".",
"reject",
"(",
"'There is no room by that id'",
")",
";",
"}",
"else",
"{",
"return",
"promise",
".",
"resolve",
"(",
"roomData",
"[",
"roomID",
"]",
"[",
"key",
"]",
")",
";",
"}",
"}"
] | get a variable from the rooms data object
@param {String} roomID id for the room
@param {String} key variable name/key that you want to get
@return {Promise} once this promise succeeds it will return the variable value it will fail if the variable does not exist | [
"get",
"a",
"variable",
"from",
"the",
"rooms",
"data",
"object"
] | 95182271c62cf4416442c825189f025234b6ef1e | https://github.com/Jam3/innkeeper/blob/95182271c62cf4416442c825189f025234b6ef1e/lib/storeRedis.js#L206-L215 |
|
54,805 | Jam3/innkeeper | lib/storeRedis.js | function( roomID, key ) {
var oldVal;
if( roomData[ roomID ] === undefined ) {
return promise.reject( 'There is no room by that id' );
} else {
oldVal = roomData[ roomID ][ key ];
delete roomData[ roomID ][ key ];
return promise.resolve( oldVal );
}
} | javascript | function( roomID, key ) {
var oldVal;
if( roomData[ roomID ] === undefined ) {
return promise.reject( 'There is no room by that id' );
} else {
oldVal = roomData[ roomID ][ key ];
delete roomData[ roomID ][ key ];
return promise.resolve( oldVal );
}
} | [
"function",
"(",
"roomID",
",",
"key",
")",
"{",
"var",
"oldVal",
";",
"if",
"(",
"roomData",
"[",
"roomID",
"]",
"===",
"undefined",
")",
"{",
"return",
"promise",
".",
"reject",
"(",
"'There is no room by that id'",
")",
";",
"}",
"else",
"{",
"oldVal",
"=",
"roomData",
"[",
"roomID",
"]",
"[",
"key",
"]",
";",
"delete",
"roomData",
"[",
"roomID",
"]",
"[",
"key",
"]",
";",
"return",
"promise",
".",
"resolve",
"(",
"oldVal",
")",
";",
"}",
"}"
] | delete a variable from the rooms data object
@param {String} roomID id for the room
@param {String} key variable name/key that you want to delete
@return {Promise} once this promise succeeds it will return the value that was stored before delete | [
"delete",
"a",
"variable",
"from",
"the",
"rooms",
"data",
"object"
] | 95182271c62cf4416442c825189f025234b6ef1e | https://github.com/Jam3/innkeeper/blob/95182271c62cf4416442c825189f025234b6ef1e/lib/storeRedis.js#L224-L239 |
|
54,806 | TribeMedia/tribemedia-kurento-client-core | lib/complexTypes/Tag.js | Tag | function Tag(tagDict){
if(!(this instanceof Tag))
return new Tag(tagDict)
// Check tagDict has the required fields
checkType('String', 'tagDict.key', tagDict.key, {required: true});
checkType('String', 'tagDict.value', tagDict.value, {required: true});
// Init parent class
Tag.super_.call(this, tagDict)
// Set object properties
Object.defineProperties(this, {
key: {
writable: true,
enumerable: true,
value: tagDict.key
},
value: {
writable: true,
enumerable: true,
value: tagDict.value
}
})
} | javascript | function Tag(tagDict){
if(!(this instanceof Tag))
return new Tag(tagDict)
// Check tagDict has the required fields
checkType('String', 'tagDict.key', tagDict.key, {required: true});
checkType('String', 'tagDict.value', tagDict.value, {required: true});
// Init parent class
Tag.super_.call(this, tagDict)
// Set object properties
Object.defineProperties(this, {
key: {
writable: true,
enumerable: true,
value: tagDict.key
},
value: {
writable: true,
enumerable: true,
value: tagDict.value
}
})
} | [
"function",
"Tag",
"(",
"tagDict",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Tag",
")",
")",
"return",
"new",
"Tag",
"(",
"tagDict",
")",
"// Check tagDict has the required fields",
"checkType",
"(",
"'String'",
",",
"'tagDict.key'",
",",
"tagDict",
".",
"key",
",",
"{",
"required",
":",
"true",
"}",
")",
";",
"checkType",
"(",
"'String'",
",",
"'tagDict.value'",
",",
"tagDict",
".",
"value",
",",
"{",
"required",
":",
"true",
"}",
")",
";",
"// Init parent class",
"Tag",
".",
"super_",
".",
"call",
"(",
"this",
",",
"tagDict",
")",
"// Set object properties",
"Object",
".",
"defineProperties",
"(",
"this",
",",
"{",
"key",
":",
"{",
"writable",
":",
"true",
",",
"enumerable",
":",
"true",
",",
"value",
":",
"tagDict",
".",
"key",
"}",
",",
"value",
":",
"{",
"writable",
":",
"true",
",",
"enumerable",
":",
"true",
",",
"value",
":",
"tagDict",
".",
"value",
"}",
"}",
")",
"}"
] | Pair key-value with info about a MediaObject
@constructor module:core/complexTypes.Tag
@property {external:String} key
Tag key
@property {external:String} value
Tag Value | [
"Pair",
"key",
"-",
"value",
"with",
"info",
"about",
"a",
"MediaObject"
] | de4c0094644aae91320e330f9cea418a3ac55468 | https://github.com/TribeMedia/tribemedia-kurento-client-core/blob/de4c0094644aae91320e330f9cea418a3ac55468/lib/complexTypes/Tag.js#L37-L61 |
54,807 | adriancmiranda/load-gulp-config | index.js | readJSON | function readJSON(filepath){
var buffer = {};
try{
buffer = JSON.parse(fs.readFileSync(filepath, { encoding:'utf8' }));
} catch(error){}
return buffer;
} | javascript | function readJSON(filepath){
var buffer = {};
try{
buffer = JSON.parse(fs.readFileSync(filepath, { encoding:'utf8' }));
} catch(error){}
return buffer;
} | [
"function",
"readJSON",
"(",
"filepath",
")",
"{",
"var",
"buffer",
"=",
"{",
"}",
";",
"try",
"{",
"buffer",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"filepath",
",",
"{",
"encoding",
":",
"'utf8'",
"}",
")",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"}",
"return",
"buffer",
";",
"}"
] | Synchronous version of `fs.readFile`. Returns the contents of the file and parse to JSON. @see https://nodejs.org/api/fs.html#fs_fs_readfilesync_file_options | [
"Synchronous",
"version",
"of",
"fs",
".",
"readFile",
".",
"Returns",
"the",
"contents",
"of",
"the",
"file",
"and",
"parse",
"to",
"JSON",
"."
] | feb6f9e460998f3e1ac1a2651739e6803671b40f | https://github.com/adriancmiranda/load-gulp-config/blob/feb6f9e460998f3e1ac1a2651739e6803671b40f/index.js#L47-L53 |
54,808 | adriancmiranda/load-gulp-config | index.js | readYAML | function readYAML(filepath){
var buffer = {};
try{
buffer = YAML.safeLoad(fs.readFileSync(filepath, { schema:YAML.DEFAULT_FULL_SCHEMA }));
}catch(error){
console.error(error);
}
return buffer;
} | javascript | function readYAML(filepath){
var buffer = {};
try{
buffer = YAML.safeLoad(fs.readFileSync(filepath, { schema:YAML.DEFAULT_FULL_SCHEMA }));
}catch(error){
console.error(error);
}
return buffer;
} | [
"function",
"readYAML",
"(",
"filepath",
")",
"{",
"var",
"buffer",
"=",
"{",
"}",
";",
"try",
"{",
"buffer",
"=",
"YAML",
".",
"safeLoad",
"(",
"fs",
".",
"readFileSync",
"(",
"filepath",
",",
"{",
"schema",
":",
"YAML",
".",
"DEFAULT_FULL_SCHEMA",
"}",
")",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"console",
".",
"error",
"(",
"error",
")",
";",
"}",
"return",
"buffer",
";",
"}"
] | Synchronous version of `fs.readFile`. Returns the contents of the file and parse to YAML. @see https://nodejs.org/api/fs.html#fs_fs_readfilesync_file_options | [
"Synchronous",
"version",
"of",
"fs",
".",
"readFile",
".",
"Returns",
"the",
"contents",
"of",
"the",
"file",
"and",
"parse",
"to",
"YAML",
"."
] | feb6f9e460998f3e1ac1a2651739e6803671b40f | https://github.com/adriancmiranda/load-gulp-config/blob/feb6f9e460998f3e1ac1a2651739e6803671b40f/index.js#L57-L65 |
54,809 | adriancmiranda/load-gulp-config | index.js | createMultitasks | function createMultitasks(gulp, aliases){
for(var task in aliases){
if(aliases.hasOwnProperty(task)){
var cmds = [];
aliases[task].forEach(function(cmd){
cmds.push(cmd);
});
gulp.task(task, cmds);
}
}
return aliases;
} | javascript | function createMultitasks(gulp, aliases){
for(var task in aliases){
if(aliases.hasOwnProperty(task)){
var cmds = [];
aliases[task].forEach(function(cmd){
cmds.push(cmd);
});
gulp.task(task, cmds);
}
}
return aliases;
} | [
"function",
"createMultitasks",
"(",
"gulp",
",",
"aliases",
")",
"{",
"for",
"(",
"var",
"task",
"in",
"aliases",
")",
"{",
"if",
"(",
"aliases",
".",
"hasOwnProperty",
"(",
"task",
")",
")",
"{",
"var",
"cmds",
"=",
"[",
"]",
";",
"aliases",
"[",
"task",
"]",
".",
"forEach",
"(",
"function",
"(",
"cmd",
")",
"{",
"cmds",
".",
"push",
"(",
"cmd",
")",
";",
"}",
")",
";",
"gulp",
".",
"task",
"(",
"task",
",",
"cmds",
")",
";",
"}",
"}",
"return",
"aliases",
";",
"}"
] | Configure multitasks from aliases.yml | [
"Configure",
"multitasks",
"from",
"aliases",
".",
"yml"
] | feb6f9e460998f3e1ac1a2651739e6803671b40f | https://github.com/adriancmiranda/load-gulp-config/blob/feb6f9e460998f3e1ac1a2651739e6803671b40f/index.js#L137-L148 |
54,810 | adriancmiranda/load-gulp-config | index.js | filterFiles | function filterFiles(gulp, options, taskFile){
var ext = path.extname(taskFile);
if(/\.(js|coffee)$/i.test(ext)){
createTask(gulp, options, taskFile);
}else if(/\.(json)$/i.test(ext)){
createMultitasks(gulp, require(taskFile));
}else if(/\.(ya?ml)$/i.test(ext)){
createMultitasks(gulp, readYAML(taskFile));
}
} | javascript | function filterFiles(gulp, options, taskFile){
var ext = path.extname(taskFile);
if(/\.(js|coffee)$/i.test(ext)){
createTask(gulp, options, taskFile);
}else if(/\.(json)$/i.test(ext)){
createMultitasks(gulp, require(taskFile));
}else if(/\.(ya?ml)$/i.test(ext)){
createMultitasks(gulp, readYAML(taskFile));
}
} | [
"function",
"filterFiles",
"(",
"gulp",
",",
"options",
",",
"taskFile",
")",
"{",
"var",
"ext",
"=",
"path",
".",
"extname",
"(",
"taskFile",
")",
";",
"if",
"(",
"/",
"\\.(js|coffee)$",
"/",
"i",
".",
"test",
"(",
"ext",
")",
")",
"{",
"createTask",
"(",
"gulp",
",",
"options",
",",
"taskFile",
")",
";",
"}",
"else",
"if",
"(",
"/",
"\\.(json)$",
"/",
"i",
".",
"test",
"(",
"ext",
")",
")",
"{",
"createMultitasks",
"(",
"gulp",
",",
"require",
"(",
"taskFile",
")",
")",
";",
"}",
"else",
"if",
"(",
"/",
"\\.(ya?ml)$",
"/",
"i",
".",
"test",
"(",
"ext",
")",
")",
"{",
"createMultitasks",
"(",
"gulp",
",",
"readYAML",
"(",
"taskFile",
")",
")",
";",
"}",
"}"
] | Filter files by extension. | [
"Filter",
"files",
"by",
"extension",
"."
] | feb6f9e460998f3e1ac1a2651739e6803671b40f | https://github.com/adriancmiranda/load-gulp-config/blob/feb6f9e460998f3e1ac1a2651739e6803671b40f/index.js#L151-L160 |
54,811 | adriancmiranda/load-gulp-config | index.js | loadGulpConfig | function loadGulpConfig(gulp, options){
options = Object.assign({ data:{} }, options);
options.dirs = isObject(options.dirs) ? options.dirs : {};
options.configPath = isString(options.configPath) ? options.configPath : 'tasks';
glob.sync(options.configPath, { realpath:true }).forEach(filterFiles.bind(this, gulp, options));
loadGulpConfig.util.dir = rgdirs(options.dirs);
} | javascript | function loadGulpConfig(gulp, options){
options = Object.assign({ data:{} }, options);
options.dirs = isObject(options.dirs) ? options.dirs : {};
options.configPath = isString(options.configPath) ? options.configPath : 'tasks';
glob.sync(options.configPath, { realpath:true }).forEach(filterFiles.bind(this, gulp, options));
loadGulpConfig.util.dir = rgdirs(options.dirs);
} | [
"function",
"loadGulpConfig",
"(",
"gulp",
",",
"options",
")",
"{",
"options",
"=",
"Object",
".",
"assign",
"(",
"{",
"data",
":",
"{",
"}",
"}",
",",
"options",
")",
";",
"options",
".",
"dirs",
"=",
"isObject",
"(",
"options",
".",
"dirs",
")",
"?",
"options",
".",
"dirs",
":",
"{",
"}",
";",
"options",
".",
"configPath",
"=",
"isString",
"(",
"options",
".",
"configPath",
")",
"?",
"options",
".",
"configPath",
":",
"'tasks'",
";",
"glob",
".",
"sync",
"(",
"options",
".",
"configPath",
",",
"{",
"realpath",
":",
"true",
"}",
")",
".",
"forEach",
"(",
"filterFiles",
".",
"bind",
"(",
"this",
",",
"gulp",
",",
"options",
")",
")",
";",
"loadGulpConfig",
".",
"util",
".",
"dir",
"=",
"rgdirs",
"(",
"options",
".",
"dirs",
")",
";",
"}"
] | Load multiple gulp tasks using globbing patterns. | [
"Load",
"multiple",
"gulp",
"tasks",
"using",
"globbing",
"patterns",
"."
] | feb6f9e460998f3e1ac1a2651739e6803671b40f | https://github.com/adriancmiranda/load-gulp-config/blob/feb6f9e460998f3e1ac1a2651739e6803671b40f/index.js#L163-L169 |
54,812 | leizongmin/node-lei-pipe | lib/sort.js | setAfter | function setAfter (pipes, ai, bi) {
// console.log(' move %s => %s', ai, bi);
var ap = pipes[ai];
pipes.splice(ai, 1);
pipes.splice(bi, 0, ap);
} | javascript | function setAfter (pipes, ai, bi) {
// console.log(' move %s => %s', ai, bi);
var ap = pipes[ai];
pipes.splice(ai, 1);
pipes.splice(bi, 0, ap);
} | [
"function",
"setAfter",
"(",
"pipes",
",",
"ai",
",",
"bi",
")",
"{",
"// console.log(' move %s => %s', ai, bi);",
"var",
"ap",
"=",
"pipes",
"[",
"ai",
"]",
";",
"pipes",
".",
"splice",
"(",
"ai",
",",
"1",
")",
";",
"pipes",
".",
"splice",
"(",
"bi",
",",
"0",
",",
"ap",
")",
";",
"}"
] | set a after b | [
"set",
"a",
"after",
"b"
] | d211b59a3d9ce78bf0d01fd45115fc9f61495a00 | https://github.com/leizongmin/node-lei-pipe/blob/d211b59a3d9ce78bf0d01fd45115fc9f61495a00/lib/sort.js#L68-L73 |
54,813 | leizongmin/node-lei-pipe | lib/sort.js | setBefore | function setBefore (pipes, ai, bi) {
// console.log(' move %s => %s', ai, bi);
var ap = pipes[ai];
pipes.splice(ai, 1);
pipes.splice(bi, 0, ap);
} | javascript | function setBefore (pipes, ai, bi) {
// console.log(' move %s => %s', ai, bi);
var ap = pipes[ai];
pipes.splice(ai, 1);
pipes.splice(bi, 0, ap);
} | [
"function",
"setBefore",
"(",
"pipes",
",",
"ai",
",",
"bi",
")",
"{",
"// console.log(' move %s => %s', ai, bi);",
"var",
"ap",
"=",
"pipes",
"[",
"ai",
"]",
";",
"pipes",
".",
"splice",
"(",
"ai",
",",
"1",
")",
";",
"pipes",
".",
"splice",
"(",
"bi",
",",
"0",
",",
"ap",
")",
";",
"}"
] | set a before b | [
"set",
"a",
"before",
"b"
] | d211b59a3d9ce78bf0d01fd45115fc9f61495a00 | https://github.com/leizongmin/node-lei-pipe/blob/d211b59a3d9ce78bf0d01fd45115fc9f61495a00/lib/sort.js#L76-L81 |
54,814 | redisjs/jsr-validate | lib/validators/arity.js | arity | function arity(cmd, args, info, sub) {
var subcommand = sub !== undefined;
// command validation decorated the info
var def = sub || info.command.def
, expected = def.arity
, first = def.first
, last = def.last
, step = def.step
, min = Math.abs(expected)
, max
// account for command, redis includes command
// in the arity
, count = args.length + 1;
//console.dir(def);
// only command is allowed - zero args (COMMAND etc)
if(expected === 0 && first === 0 && last === 0) {
min = max = 1;
// positive fixed args length (TYPE etc)
}else if(expected > 0) {
min = max = expected;
// variable length arguments (MGET/MSET etc)
}else{
max = Number.MAX_VALUE;
// test for step
if(step > 1 && (args.length % step !== 0)) {
throw new CommandArgLength(cmd);
}
}
// made it this far, check subcommands
// for commands that require a subcommand
if(!subcommand && Constants.SUBCOMMAND[cmd] && args.length && arity !== 1) {
sub = Constants.SUBCOMMAND[cmd][args[0]];
arity(args[0], args.slice(1), info, sub);
}else if(count < min || count > max) {
if(subcommand) throw UnknownSubcommand;
throw new CommandArgLength(cmd);
}
return true;
} | javascript | function arity(cmd, args, info, sub) {
var subcommand = sub !== undefined;
// command validation decorated the info
var def = sub || info.command.def
, expected = def.arity
, first = def.first
, last = def.last
, step = def.step
, min = Math.abs(expected)
, max
// account for command, redis includes command
// in the arity
, count = args.length + 1;
//console.dir(def);
// only command is allowed - zero args (COMMAND etc)
if(expected === 0 && first === 0 && last === 0) {
min = max = 1;
// positive fixed args length (TYPE etc)
}else if(expected > 0) {
min = max = expected;
// variable length arguments (MGET/MSET etc)
}else{
max = Number.MAX_VALUE;
// test for step
if(step > 1 && (args.length % step !== 0)) {
throw new CommandArgLength(cmd);
}
}
// made it this far, check subcommands
// for commands that require a subcommand
if(!subcommand && Constants.SUBCOMMAND[cmd] && args.length && arity !== 1) {
sub = Constants.SUBCOMMAND[cmd][args[0]];
arity(args[0], args.slice(1), info, sub);
}else if(count < min || count > max) {
if(subcommand) throw UnknownSubcommand;
throw new CommandArgLength(cmd);
}
return true;
} | [
"function",
"arity",
"(",
"cmd",
",",
"args",
",",
"info",
",",
"sub",
")",
"{",
"var",
"subcommand",
"=",
"sub",
"!==",
"undefined",
";",
"// command validation decorated the info",
"var",
"def",
"=",
"sub",
"||",
"info",
".",
"command",
".",
"def",
",",
"expected",
"=",
"def",
".",
"arity",
",",
"first",
"=",
"def",
".",
"first",
",",
"last",
"=",
"def",
".",
"last",
",",
"step",
"=",
"def",
".",
"step",
",",
"min",
"=",
"Math",
".",
"abs",
"(",
"expected",
")",
",",
"max",
"// account for command, redis includes command",
"// in the arity",
",",
"count",
"=",
"args",
".",
"length",
"+",
"1",
";",
"//console.dir(def);",
"// only command is allowed - zero args (COMMAND etc)",
"if",
"(",
"expected",
"===",
"0",
"&&",
"first",
"===",
"0",
"&&",
"last",
"===",
"0",
")",
"{",
"min",
"=",
"max",
"=",
"1",
";",
"// positive fixed args length (TYPE etc)",
"}",
"else",
"if",
"(",
"expected",
">",
"0",
")",
"{",
"min",
"=",
"max",
"=",
"expected",
";",
"// variable length arguments (MGET/MSET etc)",
"}",
"else",
"{",
"max",
"=",
"Number",
".",
"MAX_VALUE",
";",
"// test for step",
"if",
"(",
"step",
">",
"1",
"&&",
"(",
"args",
".",
"length",
"%",
"step",
"!==",
"0",
")",
")",
"{",
"throw",
"new",
"CommandArgLength",
"(",
"cmd",
")",
";",
"}",
"}",
"// made it this far, check subcommands",
"// for commands that require a subcommand",
"if",
"(",
"!",
"subcommand",
"&&",
"Constants",
".",
"SUBCOMMAND",
"[",
"cmd",
"]",
"&&",
"args",
".",
"length",
"&&",
"arity",
"!==",
"1",
")",
"{",
"sub",
"=",
"Constants",
".",
"SUBCOMMAND",
"[",
"cmd",
"]",
"[",
"args",
"[",
"0",
"]",
"]",
";",
"arity",
"(",
"args",
"[",
"0",
"]",
",",
"args",
".",
"slice",
"(",
"1",
")",
",",
"info",
",",
"sub",
")",
";",
"}",
"else",
"if",
"(",
"count",
"<",
"min",
"||",
"count",
">",
"max",
")",
"{",
"if",
"(",
"subcommand",
")",
"throw",
"UnknownSubcommand",
";",
"throw",
"new",
"CommandArgLength",
"(",
"cmd",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Validate argument length.
@param cmd The command name (lowercase).
@param args The command arguments, must be an array.
@param info The server information. | [
"Validate",
"argument",
"length",
"."
] | 2e0dddafb32c019ef9293a35b96cdd78dd8e4ae5 | https://github.com/redisjs/jsr-validate/blob/2e0dddafb32c019ef9293a35b96cdd78dd8e4ae5/lib/validators/arity.js#L14-L57 |
54,815 | meisterplayer/js-dev | gulp/jsdoc.js | createGenerateDocs | function createGenerateDocs(inPath, outPath) {
if (!inPath) {
throw new Error('Input path(s) argument is required');
}
if (!outPath) {
throw new Error('Output path argument is required');
}
const jsDocConfig = {
opts: {
destination: outPath,
},
};
return function generateDocs(done) {
gulp.src(inPath, { read: false })
.pipe(jsdoc(jsDocConfig, done));
};
} | javascript | function createGenerateDocs(inPath, outPath) {
if (!inPath) {
throw new Error('Input path(s) argument is required');
}
if (!outPath) {
throw new Error('Output path argument is required');
}
const jsDocConfig = {
opts: {
destination: outPath,
},
};
return function generateDocs(done) {
gulp.src(inPath, { read: false })
.pipe(jsdoc(jsDocConfig, done));
};
} | [
"function",
"createGenerateDocs",
"(",
"inPath",
",",
"outPath",
")",
"{",
"if",
"(",
"!",
"inPath",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Input path(s) argument is required'",
")",
";",
"}",
"if",
"(",
"!",
"outPath",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Output path argument is required'",
")",
";",
"}",
"const",
"jsDocConfig",
"=",
"{",
"opts",
":",
"{",
"destination",
":",
"outPath",
",",
"}",
",",
"}",
";",
"return",
"function",
"generateDocs",
"(",
"done",
")",
"{",
"gulp",
".",
"src",
"(",
"inPath",
",",
"{",
"read",
":",
"false",
"}",
")",
".",
"pipe",
"(",
"jsdoc",
"(",
"jsDocConfig",
",",
"done",
")",
")",
";",
"}",
";",
"}"
] | Higher order function to create gulp function that generates JSdocs from parsed files.
@param {string|string[]} inPath The globs to the files from which the docs should be generated
@param {string} outPath The destination path for the docs
@return {function} Function that can be used as a gulp task | [
"Higher",
"order",
"function",
"to",
"create",
"gulp",
"function",
"that",
"generates",
"JSdocs",
"from",
"parsed",
"files",
"."
] | c2646678c49dcdaa120ba3f24824da52b0c63e31 | https://github.com/meisterplayer/js-dev/blob/c2646678c49dcdaa120ba3f24824da52b0c63e31/gulp/jsdoc.js#L10-L29 |
54,816 | warehouseai/feedsme-api-client | index.js | Feedsme | function Feedsme(opts) {
if (!this) new Feedsme(opts); // eslint-disable-line no-new
if (typeof opts === 'string') {
this.base = opts;
} else if (opts.protocol && opts.href) {
this.base = url.format(opts);
} else if (opts.url || opts.uri) {
this.base = opts.url || opts.uri;
} else {
throw new Error('Feedsme URL required');
}
this.version = (opts.version === '1' || opts.version === 'v1' || opts.version === 1) ? '' : 'v2';
//
// Handle all possible cases
//
this.base = typeof this.base === 'object'
? url.format(this.base)
: this.base;
this.agent = opts.agent;
this.retry = opts.retry;
} | javascript | function Feedsme(opts) {
if (!this) new Feedsme(opts); // eslint-disable-line no-new
if (typeof opts === 'string') {
this.base = opts;
} else if (opts.protocol && opts.href) {
this.base = url.format(opts);
} else if (opts.url || opts.uri) {
this.base = opts.url || opts.uri;
} else {
throw new Error('Feedsme URL required');
}
this.version = (opts.version === '1' || opts.version === 'v1' || opts.version === 1) ? '' : 'v2';
//
// Handle all possible cases
//
this.base = typeof this.base === 'object'
? url.format(this.base)
: this.base;
this.agent = opts.agent;
this.retry = opts.retry;
} | [
"function",
"Feedsme",
"(",
"opts",
")",
"{",
"if",
"(",
"!",
"this",
")",
"new",
"Feedsme",
"(",
"opts",
")",
";",
"// eslint-disable-line no-new",
"if",
"(",
"typeof",
"opts",
"===",
"'string'",
")",
"{",
"this",
".",
"base",
"=",
"opts",
";",
"}",
"else",
"if",
"(",
"opts",
".",
"protocol",
"&&",
"opts",
".",
"href",
")",
"{",
"this",
".",
"base",
"=",
"url",
".",
"format",
"(",
"opts",
")",
";",
"}",
"else",
"if",
"(",
"opts",
".",
"url",
"||",
"opts",
".",
"uri",
")",
"{",
"this",
".",
"base",
"=",
"opts",
".",
"url",
"||",
"opts",
".",
"uri",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Feedsme URL required'",
")",
";",
"}",
"this",
".",
"version",
"=",
"(",
"opts",
".",
"version",
"===",
"'1'",
"||",
"opts",
".",
"version",
"===",
"'v1'",
"||",
"opts",
".",
"version",
"===",
"1",
")",
"?",
"''",
":",
"'v2'",
";",
"//",
"// Handle all possible cases",
"//",
"this",
".",
"base",
"=",
"typeof",
"this",
".",
"base",
"===",
"'object'",
"?",
"url",
".",
"format",
"(",
"this",
".",
"base",
")",
":",
"this",
".",
"base",
";",
"this",
".",
"agent",
"=",
"opts",
".",
"agent",
";",
"this",
".",
"retry",
"=",
"opts",
".",
"retry",
";",
"}"
] | Feedsme API client.
@constructor
@param {Object|String} opts Options for root URL of feedsme service
@param {String} opts.url The root URL of the feedsme service
@param {String} opts.uri The root URL of the feedsme service
@param {String} opts.href The href for root URL of the feedsme service
@param {String} opts.protocol Protocol for root URL of the feedsme service
@param {String} opts.version Which feedsme api version to use (defaults to v2)
@public | [
"Feedsme",
"API",
"client",
"."
] | da7aa3b2d05704808da29752fd590e93d6af87d7 | https://github.com/warehouseai/feedsme-api-client/blob/da7aa3b2d05704808da29752fd590e93d6af87d7/index.js#L26-L50 |
54,817 | warehouseai/feedsme-api-client | index.js | validateBody | function validateBody(err, body) {
body = tryParse(body);
if (err || !body) {
return next(err || new Error('Unparsable response with statusCode ' + statusCode));
}
if (statusCode !== 200) {
return next(new Error(body.message || 'Invalid status code ' + statusCode));
}
next(null, body);
} | javascript | function validateBody(err, body) {
body = tryParse(body);
if (err || !body) {
return next(err || new Error('Unparsable response with statusCode ' + statusCode));
}
if (statusCode !== 200) {
return next(new Error(body.message || 'Invalid status code ' + statusCode));
}
next(null, body);
} | [
"function",
"validateBody",
"(",
"err",
",",
"body",
")",
"{",
"body",
"=",
"tryParse",
"(",
"body",
")",
";",
"if",
"(",
"err",
"||",
"!",
"body",
")",
"{",
"return",
"next",
"(",
"err",
"||",
"new",
"Error",
"(",
"'Unparsable response with statusCode '",
"+",
"statusCode",
")",
")",
";",
"}",
"if",
"(",
"statusCode",
"!==",
"200",
")",
"{",
"return",
"next",
"(",
"new",
"Error",
"(",
"body",
".",
"message",
"||",
"'Invalid status code '",
"+",
"statusCode",
")",
")",
";",
"}",
"next",
"(",
"null",
",",
"body",
")",
";",
"}"
] | If a callback is passed, validate the returned body | [
"If",
"a",
"callback",
"is",
"passed",
"validate",
"the",
"returned",
"body"
] | da7aa3b2d05704808da29752fd590e93d6af87d7 | https://github.com/warehouseai/feedsme-api-client/blob/da7aa3b2d05704808da29752fd590e93d6af87d7/index.js#L138-L150 |
54,818 | happner/happner-test-modules | lib/as_late.js | AsLate | function AsLate(arg, u, ments) {
this.args = arg + u + ments;
this.started = false;
} | javascript | function AsLate(arg, u, ments) {
this.args = arg + u + ments;
this.started = false;
} | [
"function",
"AsLate",
"(",
"arg",
",",
"u",
",",
"ments",
")",
"{",
"this",
".",
"args",
"=",
"arg",
"+",
"u",
"+",
"ments",
";",
"this",
".",
"started",
"=",
"false",
";",
"}"
] | Tests use this module to inssert into an already running mesh node | [
"Tests",
"use",
"this",
"module",
"to",
"inssert",
"into",
"an",
"already",
"running",
"mesh",
"node"
] | c091371de6392478f731fce4aba262403d89aeff | https://github.com/happner/happner-test-modules/blob/c091371de6392478f731fce4aba262403d89aeff/lib/as_late.js#L5-L8 |
54,819 | kubicle/nice-emitter | index.js | getObjectClassname | function getObjectClassname (listener) {
if (!listener) return DEFAULT_LISTENER;
if (typeof listener === 'string') return listener;
var constr = listener.constructor;
return constr.name || constr.toString().split(/ |\(/, 2)[1];
} | javascript | function getObjectClassname (listener) {
if (!listener) return DEFAULT_LISTENER;
if (typeof listener === 'string') return listener;
var constr = listener.constructor;
return constr.name || constr.toString().split(/ |\(/, 2)[1];
} | [
"function",
"getObjectClassname",
"(",
"listener",
")",
"{",
"if",
"(",
"!",
"listener",
")",
"return",
"DEFAULT_LISTENER",
";",
"if",
"(",
"typeof",
"listener",
"===",
"'string'",
")",
"return",
"listener",
";",
"var",
"constr",
"=",
"listener",
".",
"constructor",
";",
"return",
"constr",
".",
"name",
"||",
"constr",
".",
"toString",
"(",
")",
".",
"split",
"(",
"/",
" |\\(",
"/",
",",
"2",
")",
"[",
"1",
"]",
";",
"}"
] | Using 0 is a bit faster for old API when in debug mode | [
"Using",
"0",
"is",
"a",
"bit",
"faster",
"for",
"old",
"API",
"when",
"in",
"debug",
"mode"
] | 17b8ea1ac01a7d22a714dfa3c512c197c45b847f | https://github.com/kubicle/nice-emitter/blob/17b8ea1ac01a7d22a714dfa3c512c197c45b847f/index.js#L506-L511 |
54,820 | byu-oit/sans-server | bin/server/sans-server.js | SansServer | function SansServer(configuration) {
if (!(this instanceof SansServer)) return new SansServer(configuration);
const config = configuration && typeof configuration === 'object' ? Object.assign(configuration) : {};
config.logs = config.hasOwnProperty('logs') ? config.logs : true;
config.rejectable = config.hasOwnProperty('rejectable') ? config.rejectable : false;
config.timeout = config.hasOwnProperty('timeout') && !isNaN(config.timeout) && config.timeout >= 0 ? config.timeout : 30;
config.useBuiltInHooks = config.hasOwnProperty('useBuiltInHooks') ? config.useBuiltInHooks : true;
const hooks = {};
const keys = {};
const runners = {
symbols: {},
types: {}
};
const server = this;
/**
* Define a hook that is applied to all requests.
* @param {string} type
* @param {number} [weight=0]
* @param {...function} hook
* @returns {SansServer}
*/
this.hook = addHook.bind(server, hooks);
/**
* Define a hook runner and get back a Symbol that is used to execute the hooks.
* @name SansServer#hook.define
* @function
* @param {string} type
* @returns {Symbol}
*/
this.hook.define = type => defineHookRunner(runners, type);
/**
* Get the hook type for a specific symbol.
* @name SansServer#hook.type
* @function
* @param {Symbol} key The symbol to use to get they type.
* @returns {string}
*/
this.hook.type = key => runners.symbols[key];
/**
* Have the server execute a request.
* @param {object|string} [req={}] An object that has request details or a string that is a GET endpoint.
* @param {function} [callback] The function to call once the request has been processed.
* @returns {Request}
* @listens Request#log
*/
this.request = (req, callback) => request(server, config, hooks, keys, req, callback);
/**
* Specify a middleware to use.
* @param {...Function} middleware
* @throws {Error}
* @returns {SansServer}
*/
this.use = this.hook.bind(this, 'request', 0);
// define the request and response hooks
keys.request = this.hook.define('request');
keys.response = this.hook.define('response');
// set request hooks
if (config.timeout) this.hook('request', Number.MIN_SAFE_INTEGER + 10, timeout(config.timeout));
if (config.useBuiltInHooks) this.hook('request', -100000, validMethod);
// set response hooks
if (config.useBuiltInHooks) this.hook('response', -100000, transform);
} | javascript | function SansServer(configuration) {
if (!(this instanceof SansServer)) return new SansServer(configuration);
const config = configuration && typeof configuration === 'object' ? Object.assign(configuration) : {};
config.logs = config.hasOwnProperty('logs') ? config.logs : true;
config.rejectable = config.hasOwnProperty('rejectable') ? config.rejectable : false;
config.timeout = config.hasOwnProperty('timeout') && !isNaN(config.timeout) && config.timeout >= 0 ? config.timeout : 30;
config.useBuiltInHooks = config.hasOwnProperty('useBuiltInHooks') ? config.useBuiltInHooks : true;
const hooks = {};
const keys = {};
const runners = {
symbols: {},
types: {}
};
const server = this;
/**
* Define a hook that is applied to all requests.
* @param {string} type
* @param {number} [weight=0]
* @param {...function} hook
* @returns {SansServer}
*/
this.hook = addHook.bind(server, hooks);
/**
* Define a hook runner and get back a Symbol that is used to execute the hooks.
* @name SansServer#hook.define
* @function
* @param {string} type
* @returns {Symbol}
*/
this.hook.define = type => defineHookRunner(runners, type);
/**
* Get the hook type for a specific symbol.
* @name SansServer#hook.type
* @function
* @param {Symbol} key The symbol to use to get they type.
* @returns {string}
*/
this.hook.type = key => runners.symbols[key];
/**
* Have the server execute a request.
* @param {object|string} [req={}] An object that has request details or a string that is a GET endpoint.
* @param {function} [callback] The function to call once the request has been processed.
* @returns {Request}
* @listens Request#log
*/
this.request = (req, callback) => request(server, config, hooks, keys, req, callback);
/**
* Specify a middleware to use.
* @param {...Function} middleware
* @throws {Error}
* @returns {SansServer}
*/
this.use = this.hook.bind(this, 'request', 0);
// define the request and response hooks
keys.request = this.hook.define('request');
keys.response = this.hook.define('response');
// set request hooks
if (config.timeout) this.hook('request', Number.MIN_SAFE_INTEGER + 10, timeout(config.timeout));
if (config.useBuiltInHooks) this.hook('request', -100000, validMethod);
// set response hooks
if (config.useBuiltInHooks) this.hook('response', -100000, transform);
} | [
"function",
"SansServer",
"(",
"configuration",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"SansServer",
")",
")",
"return",
"new",
"SansServer",
"(",
"configuration",
")",
";",
"const",
"config",
"=",
"configuration",
"&&",
"typeof",
"configuration",
"===",
"'object'",
"?",
"Object",
".",
"assign",
"(",
"configuration",
")",
":",
"{",
"}",
";",
"config",
".",
"logs",
"=",
"config",
".",
"hasOwnProperty",
"(",
"'logs'",
")",
"?",
"config",
".",
"logs",
":",
"true",
";",
"config",
".",
"rejectable",
"=",
"config",
".",
"hasOwnProperty",
"(",
"'rejectable'",
")",
"?",
"config",
".",
"rejectable",
":",
"false",
";",
"config",
".",
"timeout",
"=",
"config",
".",
"hasOwnProperty",
"(",
"'timeout'",
")",
"&&",
"!",
"isNaN",
"(",
"config",
".",
"timeout",
")",
"&&",
"config",
".",
"timeout",
">=",
"0",
"?",
"config",
".",
"timeout",
":",
"30",
";",
"config",
".",
"useBuiltInHooks",
"=",
"config",
".",
"hasOwnProperty",
"(",
"'useBuiltInHooks'",
")",
"?",
"config",
".",
"useBuiltInHooks",
":",
"true",
";",
"const",
"hooks",
"=",
"{",
"}",
";",
"const",
"keys",
"=",
"{",
"}",
";",
"const",
"runners",
"=",
"{",
"symbols",
":",
"{",
"}",
",",
"types",
":",
"{",
"}",
"}",
";",
"const",
"server",
"=",
"this",
";",
"/**\n * Define a hook that is applied to all requests.\n * @param {string} type\n * @param {number} [weight=0]\n * @param {...function} hook\n * @returns {SansServer}\n */",
"this",
".",
"hook",
"=",
"addHook",
".",
"bind",
"(",
"server",
",",
"hooks",
")",
";",
"/**\n * Define a hook runner and get back a Symbol that is used to execute the hooks.\n * @name SansServer#hook.define\n * @function\n * @param {string} type\n * @returns {Symbol}\n */",
"this",
".",
"hook",
".",
"define",
"=",
"type",
"=>",
"defineHookRunner",
"(",
"runners",
",",
"type",
")",
";",
"/**\n * Get the hook type for a specific symbol.\n * @name SansServer#hook.type\n * @function\n * @param {Symbol} key The symbol to use to get they type.\n * @returns {string}\n */",
"this",
".",
"hook",
".",
"type",
"=",
"key",
"=>",
"runners",
".",
"symbols",
"[",
"key",
"]",
";",
"/**\n * Have the server execute a request.\n * @param {object|string} [req={}] An object that has request details or a string that is a GET endpoint.\n * @param {function} [callback] The function to call once the request has been processed.\n * @returns {Request}\n * @listens Request#log\n */",
"this",
".",
"request",
"=",
"(",
"req",
",",
"callback",
")",
"=>",
"request",
"(",
"server",
",",
"config",
",",
"hooks",
",",
"keys",
",",
"req",
",",
"callback",
")",
";",
"/**\n * Specify a middleware to use.\n * @param {...Function} middleware\n * @throws {Error}\n * @returns {SansServer}\n */",
"this",
".",
"use",
"=",
"this",
".",
"hook",
".",
"bind",
"(",
"this",
",",
"'request'",
",",
"0",
")",
";",
"// define the request and response hooks",
"keys",
".",
"request",
"=",
"this",
".",
"hook",
".",
"define",
"(",
"'request'",
")",
";",
"keys",
".",
"response",
"=",
"this",
".",
"hook",
".",
"define",
"(",
"'response'",
")",
";",
"// set request hooks",
"if",
"(",
"config",
".",
"timeout",
")",
"this",
".",
"hook",
"(",
"'request'",
",",
"Number",
".",
"MIN_SAFE_INTEGER",
"+",
"10",
",",
"timeout",
"(",
"config",
".",
"timeout",
")",
")",
";",
"if",
"(",
"config",
".",
"useBuiltInHooks",
")",
"this",
".",
"hook",
"(",
"'request'",
",",
"-",
"100000",
",",
"validMethod",
")",
";",
"// set response hooks",
"if",
"(",
"config",
".",
"useBuiltInHooks",
")",
"this",
".",
"hook",
"(",
"'response'",
",",
"-",
"100000",
",",
"transform",
")",
";",
"}"
] | Create a san-server instance.
@param {object} [configuration] Configuration options.
@param {boolean} [configuration.logs=true] Whether to output grouped logs at the end of a request.
@param {boolean} [configuration.rejectable=false] Whether an error while processing the request should cause a failure or return a 500 response.
@param {number} [configuration.timeout=30] The number of seconds to wait before timeout for a request.
@param {boolean} [configuration.useBuiltInHooks=true] Whether to use built in middleware.
@returns {SansServer}
@constructor | [
"Create",
"a",
"san",
"-",
"server",
"instance",
"."
] | 022bcf7b47321e6e8aa20467cd96a6a84a457ec8 | https://github.com/byu-oit/sans-server/blob/022bcf7b47321e6e8aa20467cd96a6a84a457ec8/bin/server/sans-server.js#L37-L110 |
54,821 | byu-oit/sans-server | bin/server/sans-server.js | addHook | function addHook(hooks, type, weight, hook) {
const length = arguments.length;
let start = 2;
if (typeof type !== 'string') {
const err = Error('Expected first parameter to be a string. Received: ' + type);
err.code = 'ESHOOK';
throw err;
}
// handle variable input parameters
if (typeof arguments[2] === 'number') {
start = 3;
} else {
weight = 0;
}
if (!hooks[type]) hooks[type] = [];
const store = hooks[type];
for (let i = start; i < length; i++) {
const hook = arguments[i];
if (typeof hook !== 'function') {
const err = Error('Invalid hook specified. Expected a function. Received: ' + hook);
err.code = 'ESHOOK';
throw err;
}
store.push({ weight: weight, hook: hook });
}
return this;
} | javascript | function addHook(hooks, type, weight, hook) {
const length = arguments.length;
let start = 2;
if (typeof type !== 'string') {
const err = Error('Expected first parameter to be a string. Received: ' + type);
err.code = 'ESHOOK';
throw err;
}
// handle variable input parameters
if (typeof arguments[2] === 'number') {
start = 3;
} else {
weight = 0;
}
if (!hooks[type]) hooks[type] = [];
const store = hooks[type];
for (let i = start; i < length; i++) {
const hook = arguments[i];
if (typeof hook !== 'function') {
const err = Error('Invalid hook specified. Expected a function. Received: ' + hook);
err.code = 'ESHOOK';
throw err;
}
store.push({ weight: weight, hook: hook });
}
return this;
} | [
"function",
"addHook",
"(",
"hooks",
",",
"type",
",",
"weight",
",",
"hook",
")",
"{",
"const",
"length",
"=",
"arguments",
".",
"length",
";",
"let",
"start",
"=",
"2",
";",
"if",
"(",
"typeof",
"type",
"!==",
"'string'",
")",
"{",
"const",
"err",
"=",
"Error",
"(",
"'Expected first parameter to be a string. Received: '",
"+",
"type",
")",
";",
"err",
".",
"code",
"=",
"'ESHOOK'",
";",
"throw",
"err",
";",
"}",
"// handle variable input parameters",
"if",
"(",
"typeof",
"arguments",
"[",
"2",
"]",
"===",
"'number'",
")",
"{",
"start",
"=",
"3",
";",
"}",
"else",
"{",
"weight",
"=",
"0",
";",
"}",
"if",
"(",
"!",
"hooks",
"[",
"type",
"]",
")",
"hooks",
"[",
"type",
"]",
"=",
"[",
"]",
";",
"const",
"store",
"=",
"hooks",
"[",
"type",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"start",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"const",
"hook",
"=",
"arguments",
"[",
"i",
"]",
";",
"if",
"(",
"typeof",
"hook",
"!==",
"'function'",
")",
"{",
"const",
"err",
"=",
"Error",
"(",
"'Invalid hook specified. Expected a function. Received: '",
"+",
"hook",
")",
";",
"err",
".",
"code",
"=",
"'ESHOOK'",
";",
"throw",
"err",
";",
"}",
"store",
".",
"push",
"(",
"{",
"weight",
":",
"weight",
",",
"hook",
":",
"hook",
"}",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Define a hook that is applied to all requests.
@param {object} hooks
@param {string} type
@param {number} [weight=0]
@param {...function} hook
@returns {SansServer} | [
"Define",
"a",
"hook",
"that",
"is",
"applied",
"to",
"all",
"requests",
"."
] | 022bcf7b47321e6e8aa20467cd96a6a84a457ec8 | https://github.com/byu-oit/sans-server/blob/022bcf7b47321e6e8aa20467cd96a6a84a457ec8/bin/server/sans-server.js#L130-L160 |
54,822 | byu-oit/sans-server | bin/server/sans-server.js | defineHookRunner | function defineHookRunner(runners, type) {
if (runners.types.hasOwnProperty(type)) {
const err = Error('There is already a hook runner defined for this type: ' + type);
err.code = 'ESHOOK';
throw err;
}
const s = Symbol(type);
runners.types[type] = s;
runners.symbols[s] = type;
return s;
} | javascript | function defineHookRunner(runners, type) {
if (runners.types.hasOwnProperty(type)) {
const err = Error('There is already a hook runner defined for this type: ' + type);
err.code = 'ESHOOK';
throw err;
}
const s = Symbol(type);
runners.types[type] = s;
runners.symbols[s] = type;
return s;
} | [
"function",
"defineHookRunner",
"(",
"runners",
",",
"type",
")",
"{",
"if",
"(",
"runners",
".",
"types",
".",
"hasOwnProperty",
"(",
"type",
")",
")",
"{",
"const",
"err",
"=",
"Error",
"(",
"'There is already a hook runner defined for this type: '",
"+",
"type",
")",
";",
"err",
".",
"code",
"=",
"'ESHOOK'",
";",
"throw",
"err",
";",
"}",
"const",
"s",
"=",
"Symbol",
"(",
"type",
")",
";",
"runners",
".",
"types",
"[",
"type",
"]",
"=",
"s",
";",
"runners",
".",
"symbols",
"[",
"s",
"]",
"=",
"type",
";",
"return",
"s",
";",
"}"
] | Define a hook runner by specifying a unique type that can only be executed using the symbol returned.
@param {{types: object, symbols: object}} runners
@param {string} type
@returns {Symbol} | [
"Define",
"a",
"hook",
"runner",
"by",
"specifying",
"a",
"unique",
"type",
"that",
"can",
"only",
"be",
"executed",
"using",
"the",
"symbol",
"returned",
"."
] | 022bcf7b47321e6e8aa20467cd96a6a84a457ec8 | https://github.com/byu-oit/sans-server/blob/022bcf7b47321e6e8aa20467cd96a6a84a457ec8/bin/server/sans-server.js#L168-L180 |
54,823 | byu-oit/sans-server | bin/server/sans-server.js | request | function request(server, config, hooks, keys, request, callback) {
const start = Date.now();
if (typeof request === 'function' && typeof callback !== 'function') {
callback = request;
request = {};
}
// handle argument variations and get Request instance
const args = Array.from(arguments).slice(4).filter(v => v !== undefined);
const req = (function() {
const length = args.length;
if (length === 0) {
return new Request(server, keys, config.rejectable);
} else if (length === 1 && typeof args[0] === 'function') {
callback = args[0];
return new Request(server, keys, config.rejectable);
} else {
return new Request(server, keys, config.rejectable, request);
}
})();
// event log aggregation
const queue = config.logs ? [] : null;
if (queue) req.on('log', event => queue.push(event));
// if logging enabled then produce the log when the request is fulfilled or rejected
if (queue) {
const log = function(state) {
const events = queue.map((event, index) => {
const seconds = util.seconds(event.timestamp - (index > 0 ? queue[index - 1].timestamp : start));
return '[+' + seconds + 's] ' + event.category + ':' + event.type + ' ' + event.data;
});
console.log(state.statusCode + ' ' + req.method + ' ' + req.url +
(state.statusCode === 302 ? '\n Redirect To: ' + state.headers['location'] : '') +
'\n ID: ' + req.id +
'\n Start: ' + new Date(start).toISOString() +
'\n Duration: ' + prettyPrint.seconds(Date.now() - start) +
'\n Events:\n ' +
events.join('\n '));
};
req.then(log, () => log(req.res.state));
}
// copy hooks into request
req.log('initialized');
Object.keys(hooks).forEach(type => {
hooks[type].forEach(d => {
req.hook(type, d.weight, d.hook)
});
});
req.log('hooks applied');
// is using a callback paradigm then execute the callback
if (typeof callback === 'function') req.then(state => callback(null, state), err => callback(err, req.res.state));
return req;
} | javascript | function request(server, config, hooks, keys, request, callback) {
const start = Date.now();
if (typeof request === 'function' && typeof callback !== 'function') {
callback = request;
request = {};
}
// handle argument variations and get Request instance
const args = Array.from(arguments).slice(4).filter(v => v !== undefined);
const req = (function() {
const length = args.length;
if (length === 0) {
return new Request(server, keys, config.rejectable);
} else if (length === 1 && typeof args[0] === 'function') {
callback = args[0];
return new Request(server, keys, config.rejectable);
} else {
return new Request(server, keys, config.rejectable, request);
}
})();
// event log aggregation
const queue = config.logs ? [] : null;
if (queue) req.on('log', event => queue.push(event));
// if logging enabled then produce the log when the request is fulfilled or rejected
if (queue) {
const log = function(state) {
const events = queue.map((event, index) => {
const seconds = util.seconds(event.timestamp - (index > 0 ? queue[index - 1].timestamp : start));
return '[+' + seconds + 's] ' + event.category + ':' + event.type + ' ' + event.data;
});
console.log(state.statusCode + ' ' + req.method + ' ' + req.url +
(state.statusCode === 302 ? '\n Redirect To: ' + state.headers['location'] : '') +
'\n ID: ' + req.id +
'\n Start: ' + new Date(start).toISOString() +
'\n Duration: ' + prettyPrint.seconds(Date.now() - start) +
'\n Events:\n ' +
events.join('\n '));
};
req.then(log, () => log(req.res.state));
}
// copy hooks into request
req.log('initialized');
Object.keys(hooks).forEach(type => {
hooks[type].forEach(d => {
req.hook(type, d.weight, d.hook)
});
});
req.log('hooks applied');
// is using a callback paradigm then execute the callback
if (typeof callback === 'function') req.then(state => callback(null, state), err => callback(err, req.res.state));
return req;
} | [
"function",
"request",
"(",
"server",
",",
"config",
",",
"hooks",
",",
"keys",
",",
"request",
",",
"callback",
")",
"{",
"const",
"start",
"=",
"Date",
".",
"now",
"(",
")",
";",
"if",
"(",
"typeof",
"request",
"===",
"'function'",
"&&",
"typeof",
"callback",
"!==",
"'function'",
")",
"{",
"callback",
"=",
"request",
";",
"request",
"=",
"{",
"}",
";",
"}",
"// handle argument variations and get Request instance",
"const",
"args",
"=",
"Array",
".",
"from",
"(",
"arguments",
")",
".",
"slice",
"(",
"4",
")",
".",
"filter",
"(",
"v",
"=>",
"v",
"!==",
"undefined",
")",
";",
"const",
"req",
"=",
"(",
"function",
"(",
")",
"{",
"const",
"length",
"=",
"args",
".",
"length",
";",
"if",
"(",
"length",
"===",
"0",
")",
"{",
"return",
"new",
"Request",
"(",
"server",
",",
"keys",
",",
"config",
".",
"rejectable",
")",
";",
"}",
"else",
"if",
"(",
"length",
"===",
"1",
"&&",
"typeof",
"args",
"[",
"0",
"]",
"===",
"'function'",
")",
"{",
"callback",
"=",
"args",
"[",
"0",
"]",
";",
"return",
"new",
"Request",
"(",
"server",
",",
"keys",
",",
"config",
".",
"rejectable",
")",
";",
"}",
"else",
"{",
"return",
"new",
"Request",
"(",
"server",
",",
"keys",
",",
"config",
".",
"rejectable",
",",
"request",
")",
";",
"}",
"}",
")",
"(",
")",
";",
"// event log aggregation",
"const",
"queue",
"=",
"config",
".",
"logs",
"?",
"[",
"]",
":",
"null",
";",
"if",
"(",
"queue",
")",
"req",
".",
"on",
"(",
"'log'",
",",
"event",
"=>",
"queue",
".",
"push",
"(",
"event",
")",
")",
";",
"// if logging enabled then produce the log when the request is fulfilled or rejected",
"if",
"(",
"queue",
")",
"{",
"const",
"log",
"=",
"function",
"(",
"state",
")",
"{",
"const",
"events",
"=",
"queue",
".",
"map",
"(",
"(",
"event",
",",
"index",
")",
"=>",
"{",
"const",
"seconds",
"=",
"util",
".",
"seconds",
"(",
"event",
".",
"timestamp",
"-",
"(",
"index",
">",
"0",
"?",
"queue",
"[",
"index",
"-",
"1",
"]",
".",
"timestamp",
":",
"start",
")",
")",
";",
"return",
"'[+'",
"+",
"seconds",
"+",
"'s] '",
"+",
"event",
".",
"category",
"+",
"':'",
"+",
"event",
".",
"type",
"+",
"' '",
"+",
"event",
".",
"data",
";",
"}",
")",
";",
"console",
".",
"log",
"(",
"state",
".",
"statusCode",
"+",
"' '",
"+",
"req",
".",
"method",
"+",
"' '",
"+",
"req",
".",
"url",
"+",
"(",
"state",
".",
"statusCode",
"===",
"302",
"?",
"'\\n Redirect To: '",
"+",
"state",
".",
"headers",
"[",
"'location'",
"]",
":",
"''",
")",
"+",
"'\\n ID: '",
"+",
"req",
".",
"id",
"+",
"'\\n Start: '",
"+",
"new",
"Date",
"(",
"start",
")",
".",
"toISOString",
"(",
")",
"+",
"'\\n Duration: '",
"+",
"prettyPrint",
".",
"seconds",
"(",
"Date",
".",
"now",
"(",
")",
"-",
"start",
")",
"+",
"'\\n Events:\\n '",
"+",
"events",
".",
"join",
"(",
"'\\n '",
")",
")",
";",
"}",
";",
"req",
".",
"then",
"(",
"log",
",",
"(",
")",
"=>",
"log",
"(",
"req",
".",
"res",
".",
"state",
")",
")",
";",
"}",
"// copy hooks into request",
"req",
".",
"log",
"(",
"'initialized'",
")",
";",
"Object",
".",
"keys",
"(",
"hooks",
")",
".",
"forEach",
"(",
"type",
"=>",
"{",
"hooks",
"[",
"type",
"]",
".",
"forEach",
"(",
"d",
"=>",
"{",
"req",
".",
"hook",
"(",
"type",
",",
"d",
".",
"weight",
",",
"d",
".",
"hook",
")",
"}",
")",
";",
"}",
")",
";",
"req",
".",
"log",
"(",
"'hooks applied'",
")",
";",
"// is using a callback paradigm then execute the callback",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"req",
".",
"then",
"(",
"state",
"=>",
"callback",
"(",
"null",
",",
"state",
")",
",",
"err",
"=>",
"callback",
"(",
"err",
",",
"req",
".",
"res",
".",
"state",
")",
")",
";",
"return",
"req",
";",
"}"
] | Get a request started.
@param {SansServer} server
@param {object} config
@param {object} hooks
@param {object} keys
@param {object} [request]
@param {function} [callback] | [
"Get",
"a",
"request",
"started",
"."
] | 022bcf7b47321e6e8aa20467cd96a6a84a457ec8 | https://github.com/byu-oit/sans-server/blob/022bcf7b47321e6e8aa20467cd96a6a84a457ec8/bin/server/sans-server.js#L191-L250 |
54,824 | byu-oit/sans-server | bin/server/sans-server.js | timeout | function timeout(seconds) {
return function timeoutSet(req, res, next) {
const timeoutId = setTimeout(() => {
if (!res.sent) res.sendStatus(504)
}, 1000 * seconds);
req.hook('response', Number.MAX_SAFE_INTEGER - 1000, function timeoutClear(req, res, next) {
clearTimeout(timeoutId);
next();
});
next();
};
} | javascript | function timeout(seconds) {
return function timeoutSet(req, res, next) {
const timeoutId = setTimeout(() => {
if (!res.sent) res.sendStatus(504)
}, 1000 * seconds);
req.hook('response', Number.MAX_SAFE_INTEGER - 1000, function timeoutClear(req, res, next) {
clearTimeout(timeoutId);
next();
});
next();
};
} | [
"function",
"timeout",
"(",
"seconds",
")",
"{",
"return",
"function",
"timeoutSet",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"const",
"timeoutId",
"=",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"!",
"res",
".",
"sent",
")",
"res",
".",
"sendStatus",
"(",
"504",
")",
"}",
",",
"1000",
"*",
"seconds",
")",
";",
"req",
".",
"hook",
"(",
"'response'",
",",
"Number",
".",
"MAX_SAFE_INTEGER",
"-",
"1000",
",",
"function",
"timeoutClear",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"clearTimeout",
"(",
"timeoutId",
")",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"next",
"(",
")",
";",
"}",
";",
"}"
] | Request middleware to apply timeouts to the request.
@param {number} seconds
@returns {function} | [
"Request",
"middleware",
"to",
"apply",
"timeouts",
"to",
"the",
"request",
"."
] | 022bcf7b47321e6e8aa20467cd96a6a84a457ec8 | https://github.com/byu-oit/sans-server/blob/022bcf7b47321e6e8aa20467cd96a6a84a457ec8/bin/server/sans-server.js#L257-L270 |
54,825 | byu-oit/sans-server | bin/server/sans-server.js | transform | function transform(req, res, next) {
const state = res.state;
const body = state.body;
const type = typeof body;
const isBuffer = body instanceof Buffer;
let contentType;
// error conversion
if (body instanceof Error) {
res.log('transform', 'Converting Error to response');
res.status(500).body(httpStatus[500]).set('content-type', 'text/plain');
// buffer conversion
} else if (isBuffer) {
res.log('transform', 'Converting Buffer to base64 string');
res.body(body.toString('base64'));
contentType = 'application/octet-stream';
// object conversion
} else if (type === 'object') {
res.log('transform', 'Converting object to JSON string');
res.body(JSON.stringify(body));
contentType = 'application/json';
// not string conversion
} else if (type !== 'string') {
res.log('transform', 'Converting ' + type + ' to string');
res.body(String(body));
contentType = 'text/plain';
} else {
contentType = 'text/html';
}
// set content type if not yet set
if (!state.headers.hasOwnProperty('content-type') && contentType) {
res.log('transform', 'Set content type');
res.set('Content-Type', contentType);
}
next();
} | javascript | function transform(req, res, next) {
const state = res.state;
const body = state.body;
const type = typeof body;
const isBuffer = body instanceof Buffer;
let contentType;
// error conversion
if (body instanceof Error) {
res.log('transform', 'Converting Error to response');
res.status(500).body(httpStatus[500]).set('content-type', 'text/plain');
// buffer conversion
} else if (isBuffer) {
res.log('transform', 'Converting Buffer to base64 string');
res.body(body.toString('base64'));
contentType = 'application/octet-stream';
// object conversion
} else if (type === 'object') {
res.log('transform', 'Converting object to JSON string');
res.body(JSON.stringify(body));
contentType = 'application/json';
// not string conversion
} else if (type !== 'string') {
res.log('transform', 'Converting ' + type + ' to string');
res.body(String(body));
contentType = 'text/plain';
} else {
contentType = 'text/html';
}
// set content type if not yet set
if (!state.headers.hasOwnProperty('content-type') && contentType) {
res.log('transform', 'Set content type');
res.set('Content-Type', contentType);
}
next();
} | [
"function",
"transform",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"const",
"state",
"=",
"res",
".",
"state",
";",
"const",
"body",
"=",
"state",
".",
"body",
";",
"const",
"type",
"=",
"typeof",
"body",
";",
"const",
"isBuffer",
"=",
"body",
"instanceof",
"Buffer",
";",
"let",
"contentType",
";",
"// error conversion",
"if",
"(",
"body",
"instanceof",
"Error",
")",
"{",
"res",
".",
"log",
"(",
"'transform'",
",",
"'Converting Error to response'",
")",
";",
"res",
".",
"status",
"(",
"500",
")",
".",
"body",
"(",
"httpStatus",
"[",
"500",
"]",
")",
".",
"set",
"(",
"'content-type'",
",",
"'text/plain'",
")",
";",
"// buffer conversion",
"}",
"else",
"if",
"(",
"isBuffer",
")",
"{",
"res",
".",
"log",
"(",
"'transform'",
",",
"'Converting Buffer to base64 string'",
")",
";",
"res",
".",
"body",
"(",
"body",
".",
"toString",
"(",
"'base64'",
")",
")",
";",
"contentType",
"=",
"'application/octet-stream'",
";",
"// object conversion",
"}",
"else",
"if",
"(",
"type",
"===",
"'object'",
")",
"{",
"res",
".",
"log",
"(",
"'transform'",
",",
"'Converting object to JSON string'",
")",
";",
"res",
".",
"body",
"(",
"JSON",
".",
"stringify",
"(",
"body",
")",
")",
";",
"contentType",
"=",
"'application/json'",
";",
"// not string conversion",
"}",
"else",
"if",
"(",
"type",
"!==",
"'string'",
")",
"{",
"res",
".",
"log",
"(",
"'transform'",
",",
"'Converting '",
"+",
"type",
"+",
"' to string'",
")",
";",
"res",
".",
"body",
"(",
"String",
"(",
"body",
")",
")",
";",
"contentType",
"=",
"'text/plain'",
";",
"}",
"else",
"{",
"contentType",
"=",
"'text/html'",
";",
"}",
"// set content type if not yet set",
"if",
"(",
"!",
"state",
".",
"headers",
".",
"hasOwnProperty",
"(",
"'content-type'",
")",
"&&",
"contentType",
")",
"{",
"res",
".",
"log",
"(",
"'transform'",
",",
"'Set content type'",
")",
";",
"res",
".",
"set",
"(",
"'Content-Type'",
",",
"contentType",
")",
";",
"}",
"next",
"(",
")",
";",
"}"
] | Response middleware for transforming the response body and setting content type.
@param {Request} req
@param {Response} res
@param {function} next | [
"Response",
"middleware",
"for",
"transforming",
"the",
"response",
"body",
"and",
"setting",
"content",
"type",
"."
] | 022bcf7b47321e6e8aa20467cd96a6a84a457ec8 | https://github.com/byu-oit/sans-server/blob/022bcf7b47321e6e8aa20467cd96a6a84a457ec8/bin/server/sans-server.js#L278-L319 |
54,826 | byu-oit/sans-server | bin/server/sans-server.js | validMethod | function validMethod(req, res, next) {
if (httpMethods.indexOf(req.method) === -1) {
res.sendStatus(405);
} else {
next();
}
} | javascript | function validMethod(req, res, next) {
if (httpMethods.indexOf(req.method) === -1) {
res.sendStatus(405);
} else {
next();
}
} | [
"function",
"validMethod",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"httpMethods",
".",
"indexOf",
"(",
"req",
".",
"method",
")",
"===",
"-",
"1",
")",
"{",
"res",
".",
"sendStatus",
"(",
"405",
")",
";",
"}",
"else",
"{",
"next",
"(",
")",
";",
"}",
"}"
] | Middleware to make sure the method is valid.
@param {Request} req
@param {Response} res
@param {function} next | [
"Middleware",
"to",
"make",
"sure",
"the",
"method",
"is",
"valid",
"."
] | 022bcf7b47321e6e8aa20467cd96a6a84a457ec8 | https://github.com/byu-oit/sans-server/blob/022bcf7b47321e6e8aa20467cd96a6a84a457ec8/bin/server/sans-server.js#L327-L333 |
54,827 | huafu/ember-dev-fixtures | private/utils/dev-fixtures/model.js | function (name) {
if (!this.instances[name]) {
this.instances[name] = DevFixturesModel.create({name: name});
}
return this.instances[name];
} | javascript | function (name) {
if (!this.instances[name]) {
this.instances[name] = DevFixturesModel.create({name: name});
}
return this.instances[name];
} | [
"function",
"(",
"name",
")",
"{",
"if",
"(",
"!",
"this",
".",
"instances",
"[",
"name",
"]",
")",
"{",
"this",
".",
"instances",
"[",
"name",
"]",
"=",
"DevFixturesModel",
".",
"create",
"(",
"{",
"name",
":",
"name",
"}",
")",
";",
"}",
"return",
"this",
".",
"instances",
"[",
"name",
"]",
";",
"}"
] | Get or create the singleton instance for given model name
@method for
@param {string} name
@return {DevFixturesModel} | [
"Get",
"or",
"create",
"the",
"singleton",
"instance",
"for",
"given",
"model",
"name"
] | 811ed4d339c2dc840d5b297b5b244726cf1339ca | https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/utils/dev-fixtures/model.js#L78-L83 |
|
54,828 | KeyboardLeopard/leopardize | index.js | sliceOf | function sliceOf(ars, i, parts) {
return ars.slice(
Math.floor(i/parts*ars.length),
Math.floor((i+1)/parts*ars.length));
} | javascript | function sliceOf(ars, i, parts) {
return ars.slice(
Math.floor(i/parts*ars.length),
Math.floor((i+1)/parts*ars.length));
} | [
"function",
"sliceOf",
"(",
"ars",
",",
"i",
",",
"parts",
")",
"{",
"return",
"ars",
".",
"slice",
"(",
"Math",
".",
"floor",
"(",
"i",
"/",
"parts",
"*",
"ars",
".",
"length",
")",
",",
"Math",
".",
"floor",
"(",
"(",
"i",
"+",
"1",
")",
"/",
"parts",
"*",
"ars",
".",
"length",
")",
")",
";",
"}"
] | Slice against, for arrays or strings. | [
"Slice",
"against",
"for",
"arrays",
"or",
"strings",
"."
] | 5b89d648318401cfc0c8325cae71e473d759e1db | https://github.com/KeyboardLeopard/leopardize/blob/5b89d648318401cfc0c8325cae71e473d759e1db/index.js#L24-L28 |
54,829 | digiaonline/generator-nord-backbone | app/templates/components/viewManager.js | function(className, viewArgs) {
var self = this,
view = this.views[className],
dfd = $.Deferred();
if (view) {
view.undelegateEvents();
}
this.loader.load(className)
.then(function(Constructor) {
viewArgs.manager = self;
view = new Constructor(viewArgs);
self.views[className] = view;
dfd.resolve(view);
});
return dfd.promise();
} | javascript | function(className, viewArgs) {
var self = this,
view = this.views[className],
dfd = $.Deferred();
if (view) {
view.undelegateEvents();
}
this.loader.load(className)
.then(function(Constructor) {
viewArgs.manager = self;
view = new Constructor(viewArgs);
self.views[className] = view;
dfd.resolve(view);
});
return dfd.promise();
} | [
"function",
"(",
"className",
",",
"viewArgs",
")",
"{",
"var",
"self",
"=",
"this",
",",
"view",
"=",
"this",
".",
"views",
"[",
"className",
"]",
",",
"dfd",
"=",
"$",
".",
"Deferred",
"(",
")",
";",
"if",
"(",
"view",
")",
"{",
"view",
".",
"undelegateEvents",
"(",
")",
";",
"}",
"this",
".",
"loader",
".",
"load",
"(",
"className",
")",
".",
"then",
"(",
"function",
"(",
"Constructor",
")",
"{",
"viewArgs",
".",
"manager",
"=",
"self",
";",
"view",
"=",
"new",
"Constructor",
"(",
"viewArgs",
")",
";",
"self",
".",
"views",
"[",
"className",
"]",
"=",
"view",
";",
"dfd",
".",
"resolve",
"(",
"view",
")",
";",
"}",
")",
";",
"return",
"dfd",
".",
"promise",
"(",
")",
";",
"}"
] | Creates a new view.
@param {string} className the view to create
@param {Object} viewArgs view options | [
"Creates",
"a",
"new",
"view",
"."
] | bc962e16b6354c7a4034ce09cf4030b9d300202e | https://github.com/digiaonline/generator-nord-backbone/blob/bc962e16b6354c7a4034ce09cf4030b9d300202e/app/templates/components/viewManager.js#L29-L47 |
|
54,830 | jantimon/ng-directive-parser | lib/ng-directive-parser.js | Directive | function Directive(filename, directiveArguments) {
this.filename = filename;
this.name = directiveArguments[0].value;
var directiveConfiguration = directiveArguments[1];
// Extract the last attribute of the array
if (directiveConfiguration.type === 'ArrayExpression' && directiveConfiguration.elements.length) {
directiveConfiguration = directiveConfiguration.elements[directiveConfiguration.elements.length - 1];
}
// Parse the function
if (directiveConfiguration && directiveConfiguration.type === 'FunctionExpression') {
directiveConfiguration = esprimaHelper.getFirstReturnStatement(directiveConfiguration);
}
// Get the returnStatement
if (directiveConfiguration && directiveConfiguration.type === 'ReturnStatement') {
directiveConfiguration = directiveConfiguration.argument;
}
// Parse the object
if (directiveConfiguration && directiveConfiguration.type === 'ObjectExpression') {
var properties = esprimaHelper.parseObjectExpressions(directiveConfiguration);
this.replace = !!properties.replace;
this.transclude = !!properties.transclude;
this.template = properties.template;
this.templateUrl = properties.templateUrl;
if (properties.restrict) {
this.restrict = {
A: properties.restrict.toUpperCase().indexOf('A') >= 0,
E: properties.restrict.toUpperCase().indexOf('E') >= 0,
C: properties.restrict.toUpperCase().indexOf('C') >= 0
};
}
}
// Add parse warning
if (!this.restrict) {
module.exports.logger('no restriction set for', this.filename, this.name);
this.restrict = {
A: true,
E: false,
C: false
};
}
} | javascript | function Directive(filename, directiveArguments) {
this.filename = filename;
this.name = directiveArguments[0].value;
var directiveConfiguration = directiveArguments[1];
// Extract the last attribute of the array
if (directiveConfiguration.type === 'ArrayExpression' && directiveConfiguration.elements.length) {
directiveConfiguration = directiveConfiguration.elements[directiveConfiguration.elements.length - 1];
}
// Parse the function
if (directiveConfiguration && directiveConfiguration.type === 'FunctionExpression') {
directiveConfiguration = esprimaHelper.getFirstReturnStatement(directiveConfiguration);
}
// Get the returnStatement
if (directiveConfiguration && directiveConfiguration.type === 'ReturnStatement') {
directiveConfiguration = directiveConfiguration.argument;
}
// Parse the object
if (directiveConfiguration && directiveConfiguration.type === 'ObjectExpression') {
var properties = esprimaHelper.parseObjectExpressions(directiveConfiguration);
this.replace = !!properties.replace;
this.transclude = !!properties.transclude;
this.template = properties.template;
this.templateUrl = properties.templateUrl;
if (properties.restrict) {
this.restrict = {
A: properties.restrict.toUpperCase().indexOf('A') >= 0,
E: properties.restrict.toUpperCase().indexOf('E') >= 0,
C: properties.restrict.toUpperCase().indexOf('C') >= 0
};
}
}
// Add parse warning
if (!this.restrict) {
module.exports.logger('no restriction set for', this.filename, this.name);
this.restrict = {
A: true,
E: false,
C: false
};
}
} | [
"function",
"Directive",
"(",
"filename",
",",
"directiveArguments",
")",
"{",
"this",
".",
"filename",
"=",
"filename",
";",
"this",
".",
"name",
"=",
"directiveArguments",
"[",
"0",
"]",
".",
"value",
";",
"var",
"directiveConfiguration",
"=",
"directiveArguments",
"[",
"1",
"]",
";",
"// Extract the last attribute of the array",
"if",
"(",
"directiveConfiguration",
".",
"type",
"===",
"'ArrayExpression'",
"&&",
"directiveConfiguration",
".",
"elements",
".",
"length",
")",
"{",
"directiveConfiguration",
"=",
"directiveConfiguration",
".",
"elements",
"[",
"directiveConfiguration",
".",
"elements",
".",
"length",
"-",
"1",
"]",
";",
"}",
"// Parse the function",
"if",
"(",
"directiveConfiguration",
"&&",
"directiveConfiguration",
".",
"type",
"===",
"'FunctionExpression'",
")",
"{",
"directiveConfiguration",
"=",
"esprimaHelper",
".",
"getFirstReturnStatement",
"(",
"directiveConfiguration",
")",
";",
"}",
"// Get the returnStatement",
"if",
"(",
"directiveConfiguration",
"&&",
"directiveConfiguration",
".",
"type",
"===",
"'ReturnStatement'",
")",
"{",
"directiveConfiguration",
"=",
"directiveConfiguration",
".",
"argument",
";",
"}",
"// Parse the object",
"if",
"(",
"directiveConfiguration",
"&&",
"directiveConfiguration",
".",
"type",
"===",
"'ObjectExpression'",
")",
"{",
"var",
"properties",
"=",
"esprimaHelper",
".",
"parseObjectExpressions",
"(",
"directiveConfiguration",
")",
";",
"this",
".",
"replace",
"=",
"!",
"!",
"properties",
".",
"replace",
";",
"this",
".",
"transclude",
"=",
"!",
"!",
"properties",
".",
"transclude",
";",
"this",
".",
"template",
"=",
"properties",
".",
"template",
";",
"this",
".",
"templateUrl",
"=",
"properties",
".",
"templateUrl",
";",
"if",
"(",
"properties",
".",
"restrict",
")",
"{",
"this",
".",
"restrict",
"=",
"{",
"A",
":",
"properties",
".",
"restrict",
".",
"toUpperCase",
"(",
")",
".",
"indexOf",
"(",
"'A'",
")",
">=",
"0",
",",
"E",
":",
"properties",
".",
"restrict",
".",
"toUpperCase",
"(",
")",
".",
"indexOf",
"(",
"'E'",
")",
">=",
"0",
",",
"C",
":",
"properties",
".",
"restrict",
".",
"toUpperCase",
"(",
")",
".",
"indexOf",
"(",
"'C'",
")",
">=",
"0",
"}",
";",
"}",
"}",
"// Add parse warning",
"if",
"(",
"!",
"this",
".",
"restrict",
")",
"{",
"module",
".",
"exports",
".",
"logger",
"(",
"'no restriction set for'",
",",
"this",
".",
"filename",
",",
"this",
".",
"name",
")",
";",
"this",
".",
"restrict",
"=",
"{",
"A",
":",
"true",
",",
"E",
":",
"false",
",",
"C",
":",
"false",
"}",
";",
"}",
"}"
] | Class for a directive information bundle
@param filename
@param directiveArguments
@constructor | [
"Class",
"for",
"a",
"directive",
"information",
"bundle"
] | e7bb3b800243be7399d8af3ab2546dd3f159beda | https://github.com/jantimon/ng-directive-parser/blob/e7bb3b800243be7399d8af3ab2546dd3f159beda/lib/ng-directive-parser.js#L21-L61 |
54,831 | jantimon/ng-directive-parser | lib/ng-directive-parser.js | parseAst | function parseAst(filename, ast) {
var directives = [];
esprimaHelper.traverse(ast, function (node) {
var calleeExpressionName = esprimaHelper.getCallExpressionName(node);
if (calleeExpressionName === 'directive') {
var directiveArguments = node['arguments'] || [];
if (directiveArguments.length >= 2 && directiveArguments[0].type === 'Literal') {
directives.push(new Directive(filename, directiveArguments));
}
}
});
return directives;
} | javascript | function parseAst(filename, ast) {
var directives = [];
esprimaHelper.traverse(ast, function (node) {
var calleeExpressionName = esprimaHelper.getCallExpressionName(node);
if (calleeExpressionName === 'directive') {
var directiveArguments = node['arguments'] || [];
if (directiveArguments.length >= 2 && directiveArguments[0].type === 'Literal') {
directives.push(new Directive(filename, directiveArguments));
}
}
});
return directives;
} | [
"function",
"parseAst",
"(",
"filename",
",",
"ast",
")",
"{",
"var",
"directives",
"=",
"[",
"]",
";",
"esprimaHelper",
".",
"traverse",
"(",
"ast",
",",
"function",
"(",
"node",
")",
"{",
"var",
"calleeExpressionName",
"=",
"esprimaHelper",
".",
"getCallExpressionName",
"(",
"node",
")",
";",
"if",
"(",
"calleeExpressionName",
"===",
"'directive'",
")",
"{",
"var",
"directiveArguments",
"=",
"node",
"[",
"'arguments'",
"]",
"||",
"[",
"]",
";",
"if",
"(",
"directiveArguments",
".",
"length",
">=",
"2",
"&&",
"directiveArguments",
"[",
"0",
"]",
".",
"type",
"===",
"'Literal'",
")",
"{",
"directives",
".",
"push",
"(",
"new",
"Directive",
"(",
"filename",
",",
"directiveArguments",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"directives",
";",
"}"
] | Parse the given AST
@returns {Directive[]} | [
"Parse",
"the",
"given",
"AST"
] | e7bb3b800243be7399d8af3ab2546dd3f159beda | https://github.com/jantimon/ng-directive-parser/blob/e7bb3b800243be7399d8af3ab2546dd3f159beda/lib/ng-directive-parser.js#L68-L80 |
54,832 | jantimon/ng-directive-parser | lib/ng-directive-parser.js | parseFile | function parseFile(filename, code) {
if (/directive/.test(code)) {
return ngDirectiveParser.parseAst(filename, esprima.parse(code));
}
return [];
} | javascript | function parseFile(filename, code) {
if (/directive/.test(code)) {
return ngDirectiveParser.parseAst(filename, esprima.parse(code));
}
return [];
} | [
"function",
"parseFile",
"(",
"filename",
",",
"code",
")",
"{",
"if",
"(",
"/",
"directive",
"/",
".",
"test",
"(",
"code",
")",
")",
"{",
"return",
"ngDirectiveParser",
".",
"parseAst",
"(",
"filename",
",",
"esprima",
".",
"parse",
"(",
"code",
")",
")",
";",
"}",
"return",
"[",
"]",
";",
"}"
] | Parses the given source
@returns {Directive[]} | [
"Parses",
"the",
"given",
"source"
] | e7bb3b800243be7399d8af3ab2546dd3f159beda | https://github.com/jantimon/ng-directive-parser/blob/e7bb3b800243be7399d8af3ab2546dd3f159beda/lib/ng-directive-parser.js#L90-L95 |
54,833 | markselby/node-db-pool | lib/db-pool.js | connStr | function connStr(conn) {
var conf = mergeDefaults(conn);
var connString = conf.driver + '://' + conf.username + (conf.password ? ':' + conf.password : '') + '@' + conf.host
+ (conf.port ? ':' + conf.port : '') + '/' + conf.database;
return connString;
} | javascript | function connStr(conn) {
var conf = mergeDefaults(conn);
var connString = conf.driver + '://' + conf.username + (conf.password ? ':' + conf.password : '') + '@' + conf.host
+ (conf.port ? ':' + conf.port : '') + '/' + conf.database;
return connString;
} | [
"function",
"connStr",
"(",
"conn",
")",
"{",
"var",
"conf",
"=",
"mergeDefaults",
"(",
"conn",
")",
";",
"var",
"connString",
"=",
"conf",
".",
"driver",
"+",
"'://'",
"+",
"conf",
".",
"username",
"+",
"(",
"conf",
".",
"password",
"?",
"':'",
"+",
"conf",
".",
"password",
":",
"''",
")",
"+",
"'@'",
"+",
"conf",
".",
"host",
"+",
"(",
"conf",
".",
"port",
"?",
"':'",
"+",
"conf",
".",
"port",
":",
"''",
")",
"+",
"'/'",
"+",
"conf",
".",
"database",
";",
"return",
"connString",
";",
"}"
] | Build a connection string from target db + env hash | [
"Build",
"a",
"connection",
"string",
"from",
"target",
"db",
"+",
"env",
"hash"
] | 97a329ca7cb625f9453dc4c887b84b5ac591a49f | https://github.com/markselby/node-db-pool/blob/97a329ca7cb625f9453dc4c887b84b5ac591a49f/lib/db-pool.js#L100-L105 |
54,834 | markselby/node-db-pool | lib/db-pool.js | createPool | function createPool(conn) {
var conf = connectionConfig[conn.app][conn.env];
conf.connStr = connStr(conn);
console.log('Creating pool to : ' + conf.connStr);
// Create the pool on the conf object for easy future access
conf.pool = anydb.createPool(conf.connStr, {
min: conf.min,
max: conf.max,
onConnect: function (conn, done) {
done(null, conn);
},
reset: function (conn, done) {
done(null);
}
});
// Remember all connection pools for easy termination
pools.push(conf.pool);
return conf.pool;
} | javascript | function createPool(conn) {
var conf = connectionConfig[conn.app][conn.env];
conf.connStr = connStr(conn);
console.log('Creating pool to : ' + conf.connStr);
// Create the pool on the conf object for easy future access
conf.pool = anydb.createPool(conf.connStr, {
min: conf.min,
max: conf.max,
onConnect: function (conn, done) {
done(null, conn);
},
reset: function (conn, done) {
done(null);
}
});
// Remember all connection pools for easy termination
pools.push(conf.pool);
return conf.pool;
} | [
"function",
"createPool",
"(",
"conn",
")",
"{",
"var",
"conf",
"=",
"connectionConfig",
"[",
"conn",
".",
"app",
"]",
"[",
"conn",
".",
"env",
"]",
";",
"conf",
".",
"connStr",
"=",
"connStr",
"(",
"conn",
")",
";",
"console",
".",
"log",
"(",
"'Creating pool to : '",
"+",
"conf",
".",
"connStr",
")",
";",
"// Create the pool on the conf object for easy future access",
"conf",
".",
"pool",
"=",
"anydb",
".",
"createPool",
"(",
"conf",
".",
"connStr",
",",
"{",
"min",
":",
"conf",
".",
"min",
",",
"max",
":",
"conf",
".",
"max",
",",
"onConnect",
":",
"function",
"(",
"conn",
",",
"done",
")",
"{",
"done",
"(",
"null",
",",
"conn",
")",
";",
"}",
",",
"reset",
":",
"function",
"(",
"conn",
",",
"done",
")",
"{",
"done",
"(",
"null",
")",
";",
"}",
"}",
")",
";",
"// Remember all connection pools for easy termination",
"pools",
".",
"push",
"(",
"conf",
".",
"pool",
")",
";",
"return",
"conf",
".",
"pool",
";",
"}"
] | Create the connection pool via any-db | [
"Create",
"the",
"connection",
"pool",
"via",
"any",
"-",
"db"
] | 97a329ca7cb625f9453dc4c887b84b5ac591a49f | https://github.com/markselby/node-db-pool/blob/97a329ca7cb625f9453dc4c887b84b5ac591a49f/lib/db-pool.js#L108-L126 |
54,835 | ottopecz/talentcomposer | lib/mlMutators.js | parseML | function parseML(memberLog, required) {
return memberLog.map(member => {
const cloned = clone(member);
const key = Reflect.ownKeys(cloned)[0];
const value = cloned[key];
cloned[key] = value.filter(elem => (elem !== required));
return cloned;
});
} | javascript | function parseML(memberLog, required) {
return memberLog.map(member => {
const cloned = clone(member);
const key = Reflect.ownKeys(cloned)[0];
const value = cloned[key];
cloned[key] = value.filter(elem => (elem !== required));
return cloned;
});
} | [
"function",
"parseML",
"(",
"memberLog",
",",
"required",
")",
"{",
"return",
"memberLog",
".",
"map",
"(",
"member",
"=>",
"{",
"const",
"cloned",
"=",
"clone",
"(",
"member",
")",
";",
"const",
"key",
"=",
"Reflect",
".",
"ownKeys",
"(",
"cloned",
")",
"[",
"0",
"]",
";",
"const",
"value",
"=",
"cloned",
"[",
"key",
"]",
";",
"cloned",
"[",
"key",
"]",
"=",
"value",
".",
"filter",
"(",
"elem",
"=>",
"(",
"elem",
"!==",
"required",
")",
")",
";",
"return",
"cloned",
";",
"}",
")",
";",
"}"
] | Removes the required members of the member log
@param {Array.<Object>} memberLog The array of the members. The entries are objects with one own key
@param {Symbol} required The required marker
@returns {Array.<Object>} The parsed member log | [
"Removes",
"the",
"required",
"members",
"of",
"the",
"member",
"log"
] | 440c73248ccb6538c7805ada6a8feb5b3ae4a973 | https://github.com/ottopecz/talentcomposer/blob/440c73248ccb6538c7805ada6a8feb5b3ae4a973/lib/mlMutators.js#L11-L23 |
54,836 | ottopecz/talentcomposer | lib/mlMutators.js | addSourceInfoToML | function addSourceInfoToML(memberLog, source) {
let cloned = memberLog.slice();
for (const [key, value] of getIterableObjectEntries(source)) {
if (Talent.typeCheck(value)) {
cloned = addSourceInfoToML(cloned, value);
}
const foundAndCloned = clone(findWhereKey(cloned, key));
if (!foundAndCloned && !Talent.typeCheck(value)) {
cloned.push({[key]: [value]});
} else if (!Talent.typeCheck(value)) {
foundAndCloned[key].push(value);
}
}
return cloned;
} | javascript | function addSourceInfoToML(memberLog, source) {
let cloned = memberLog.slice();
for (const [key, value] of getIterableObjectEntries(source)) {
if (Talent.typeCheck(value)) {
cloned = addSourceInfoToML(cloned, value);
}
const foundAndCloned = clone(findWhereKey(cloned, key));
if (!foundAndCloned && !Talent.typeCheck(value)) {
cloned.push({[key]: [value]});
} else if (!Talent.typeCheck(value)) {
foundAndCloned[key].push(value);
}
}
return cloned;
} | [
"function",
"addSourceInfoToML",
"(",
"memberLog",
",",
"source",
")",
"{",
"let",
"cloned",
"=",
"memberLog",
".",
"slice",
"(",
")",
";",
"for",
"(",
"const",
"[",
"key",
",",
"value",
"]",
"of",
"getIterableObjectEntries",
"(",
"source",
")",
")",
"{",
"if",
"(",
"Talent",
".",
"typeCheck",
"(",
"value",
")",
")",
"{",
"cloned",
"=",
"addSourceInfoToML",
"(",
"cloned",
",",
"value",
")",
";",
"}",
"const",
"foundAndCloned",
"=",
"clone",
"(",
"findWhereKey",
"(",
"cloned",
",",
"key",
")",
")",
";",
"if",
"(",
"!",
"foundAndCloned",
"&&",
"!",
"Talent",
".",
"typeCheck",
"(",
"value",
")",
")",
"{",
"cloned",
".",
"push",
"(",
"{",
"[",
"key",
"]",
":",
"[",
"value",
"]",
"}",
")",
";",
"}",
"else",
"if",
"(",
"!",
"Talent",
".",
"typeCheck",
"(",
"value",
")",
")",
"{",
"foundAndCloned",
"[",
"key",
"]",
".",
"push",
"(",
"value",
")",
";",
"}",
"}",
"return",
"cloned",
";",
"}"
] | Adds new entry to the member log or modifies an existing one
@param {Array.<Object>} memberLog The array of the members. The entries are objects with one own key
@param {Talent} source The talent which info needs to be added. (Might be nested)
@returns {Array.<Object>} The modified member log | [
"Adds",
"new",
"entry",
"to",
"the",
"member",
"log",
"or",
"modifies",
"an",
"existing",
"one"
] | 440c73248ccb6538c7805ada6a8feb5b3ae4a973 | https://github.com/ottopecz/talentcomposer/blob/440c73248ccb6538c7805ada6a8feb5b3ae4a973/lib/mlMutators.js#L31-L54 |
54,837 | benadamstyles/roots-i18n | lib/index.js | translate | function translate(content, langFile) {
return content.replace(templateRegEx, function (match, capture) {
return (0, _lodash2.default)(langMap.get(langFile), capture);
});
} | javascript | function translate(content, langFile) {
return content.replace(templateRegEx, function (match, capture) {
return (0, _lodash2.default)(langMap.get(langFile), capture);
});
} | [
"function",
"translate",
"(",
"content",
",",
"langFile",
")",
"{",
"return",
"content",
".",
"replace",
"(",
"templateRegEx",
",",
"function",
"(",
"match",
",",
"capture",
")",
"{",
"return",
"(",
"0",
",",
"_lodash2",
".",
"default",
")",
"(",
"langMap",
".",
"get",
"(",
"langFile",
")",
",",
"capture",
")",
";",
"}",
")",
";",
"}"
] | Pure function to translate a view template file
@param {String} content The file content
@param {String} langFile The file's path
@return {String} The file content, translated | [
"Pure",
"function",
"to",
"translate",
"a",
"view",
"template",
"file"
] | 333976649f6705a6b31bd5da74aa973b51a39bb5 | https://github.com/benadamstyles/roots-i18n/blob/333976649f6705a6b31bd5da74aa973b51a39bb5/lib/index.js#L55-L59 |
54,838 | ItsAsbreuk/itsa-mojitonthefly-addon | assets/itsa-mojitonthefly.client.js | function (promise) {
var targets = this._targets;
targets.push(promise);
promise['catch'](
function() {
return true;
}
).then(
function() {
targets.splice(targets.indexOf(promise), 1);
}
);
return Notifier.decorate(promise);
} | javascript | function (promise) {
var targets = this._targets;
targets.push(promise);
promise['catch'](
function() {
return true;
}
).then(
function() {
targets.splice(targets.indexOf(promise), 1);
}
);
return Notifier.decorate(promise);
} | [
"function",
"(",
"promise",
")",
"{",
"var",
"targets",
"=",
"this",
".",
"_targets",
";",
"targets",
".",
"push",
"(",
"promise",
")",
";",
"promise",
"[",
"'catch'",
"]",
"(",
"function",
"(",
")",
"{",
"return",
"true",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"targets",
".",
"splice",
"(",
"targets",
".",
"indexOf",
"(",
"promise",
")",
",",
"1",
")",
";",
"}",
")",
";",
"return",
"Notifier",
".",
"decorate",
"(",
"promise",
")",
";",
"}"
] | Decorate a promise and register it and its kin as targets for notifications
from this instance.
Returns the input promise.
@method addEvents
@param {Promise} promise The Promise to add event support to
@return {Promise} | [
"Decorate",
"a",
"promise",
"and",
"register",
"it",
"and",
"its",
"kin",
"as",
"targets",
"for",
"notifications",
"from",
"this",
"instance",
"."
] | 500de397fef8f80f719360d4ac023bb860934ec0 | https://github.com/ItsAsbreuk/itsa-mojitonthefly-addon/blob/500de397fef8f80f719360d4ac023bb860934ec0/assets/itsa-mojitonthefly.client.js#L118-L131 |
|
54,839 | ItsAsbreuk/itsa-mojitonthefly-addon | assets/itsa-mojitonthefly.client.js | function (type) {
var targets = this._targets.slice(),
known = {},
args = arguments.length > 1 && toArray(arguments, 1, true),
target, subs,
i, j, jlen, guid, callback;
// Add index 0 and 1 entries for use in Y.bind.apply(Y, args) below.
// Index 0 will be set to the callback, and index 1 will be left as null
// resulting in Y.bind.apply(Y, [callback, null, arg0,...argN])
if (args) {
args.unshift(null, null);
}
// Breadth-first notification order, mimicking resolution order
// Note: Not caching a length comparator because this pushes to the end
// of the targets array as it iterates.
for (i = 0; i < targets.length; ++i) {
target = targets[i];
if (targets[i]._evts) {
// Not that this should ever happen, but don't push known
// promise targets onto the list again. That would make for an
// infinite loop
guid = Y.stamp(targets[i]);
if (known[guid]) {
continue;
}
known[guid] = 1;
// Queue any child promises to get notified
targets.push.apply(targets, targets[i]._evts.targets);
// Notify subscribers
subs = target._evts.subs[type];
if (subs) {
for (j = 0, jlen = subs.length; j < jlen; ++j) {
callback = subs[j];
if (args) {
args[0] = callback;
callback = Y.bind.apply(Y, args);
}
// Force async to mimic resolution lifecycle, and
// each callback in its own event loop turn to
// avoid swallowing errors and errors breaking the
// current js thread.
// TODO: would synchronous notifications be better?
Y.soon(callback);
}
}
}
}
return this;
} | javascript | function (type) {
var targets = this._targets.slice(),
known = {},
args = arguments.length > 1 && toArray(arguments, 1, true),
target, subs,
i, j, jlen, guid, callback;
// Add index 0 and 1 entries for use in Y.bind.apply(Y, args) below.
// Index 0 will be set to the callback, and index 1 will be left as null
// resulting in Y.bind.apply(Y, [callback, null, arg0,...argN])
if (args) {
args.unshift(null, null);
}
// Breadth-first notification order, mimicking resolution order
// Note: Not caching a length comparator because this pushes to the end
// of the targets array as it iterates.
for (i = 0; i < targets.length; ++i) {
target = targets[i];
if (targets[i]._evts) {
// Not that this should ever happen, but don't push known
// promise targets onto the list again. That would make for an
// infinite loop
guid = Y.stamp(targets[i]);
if (known[guid]) {
continue;
}
known[guid] = 1;
// Queue any child promises to get notified
targets.push.apply(targets, targets[i]._evts.targets);
// Notify subscribers
subs = target._evts.subs[type];
if (subs) {
for (j = 0, jlen = subs.length; j < jlen; ++j) {
callback = subs[j];
if (args) {
args[0] = callback;
callback = Y.bind.apply(Y, args);
}
// Force async to mimic resolution lifecycle, and
// each callback in its own event loop turn to
// avoid swallowing errors and errors breaking the
// current js thread.
// TODO: would synchronous notifications be better?
Y.soon(callback);
}
}
}
}
return this;
} | [
"function",
"(",
"type",
")",
"{",
"var",
"targets",
"=",
"this",
".",
"_targets",
".",
"slice",
"(",
")",
",",
"known",
"=",
"{",
"}",
",",
"args",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"toArray",
"(",
"arguments",
",",
"1",
",",
"true",
")",
",",
"target",
",",
"subs",
",",
"i",
",",
"j",
",",
"jlen",
",",
"guid",
",",
"callback",
";",
"// Add index 0 and 1 entries for use in Y.bind.apply(Y, args) below.",
"// Index 0 will be set to the callback, and index 1 will be left as null",
"// resulting in Y.bind.apply(Y, [callback, null, arg0,...argN])",
"if",
"(",
"args",
")",
"{",
"args",
".",
"unshift",
"(",
"null",
",",
"null",
")",
";",
"}",
"// Breadth-first notification order, mimicking resolution order",
"// Note: Not caching a length comparator because this pushes to the end",
"// of the targets array as it iterates.",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"targets",
".",
"length",
";",
"++",
"i",
")",
"{",
"target",
"=",
"targets",
"[",
"i",
"]",
";",
"if",
"(",
"targets",
"[",
"i",
"]",
".",
"_evts",
")",
"{",
"// Not that this should ever happen, but don't push known",
"// promise targets onto the list again. That would make for an",
"// infinite loop",
"guid",
"=",
"Y",
".",
"stamp",
"(",
"targets",
"[",
"i",
"]",
")",
";",
"if",
"(",
"known",
"[",
"guid",
"]",
")",
"{",
"continue",
";",
"}",
"known",
"[",
"guid",
"]",
"=",
"1",
";",
"// Queue any child promises to get notified",
"targets",
".",
"push",
".",
"apply",
"(",
"targets",
",",
"targets",
"[",
"i",
"]",
".",
"_evts",
".",
"targets",
")",
";",
"// Notify subscribers",
"subs",
"=",
"target",
".",
"_evts",
".",
"subs",
"[",
"type",
"]",
";",
"if",
"(",
"subs",
")",
"{",
"for",
"(",
"j",
"=",
"0",
",",
"jlen",
"=",
"subs",
".",
"length",
";",
"j",
"<",
"jlen",
";",
"++",
"j",
")",
"{",
"callback",
"=",
"subs",
"[",
"j",
"]",
";",
"if",
"(",
"args",
")",
"{",
"args",
"[",
"0",
"]",
"=",
"callback",
";",
"callback",
"=",
"Y",
".",
"bind",
".",
"apply",
"(",
"Y",
",",
"args",
")",
";",
"}",
"// Force async to mimic resolution lifecycle, and",
"// each callback in its own event loop turn to",
"// avoid swallowing errors and errors breaking the",
"// current js thread.",
"// TODO: would synchronous notifications be better?",
"Y",
".",
"soon",
"(",
"callback",
")",
";",
"}",
"}",
"}",
"}",
"return",
"this",
";",
"}"
] | Notify registered Promises and their children of an event. Subscription
callbacks will be passed additional _args_ parameters.
@method fire
@param {String} type The name of the event to notify subscribers of
@param {Any*} [args*] Arguments to pass to the callbacks
@return {Promise.EventNotifier} this instance
@chainable | [
"Notify",
"registered",
"Promises",
"and",
"their",
"children",
"of",
"an",
"event",
".",
"Subscription",
"callbacks",
"will",
"be",
"passed",
"additional",
"_args_",
"parameters",
"."
] | 500de397fef8f80f719360d4ac023bb860934ec0 | https://github.com/ItsAsbreuk/itsa-mojitonthefly-addon/blob/500de397fef8f80f719360d4ac023bb860934ec0/assets/itsa-mojitonthefly.client.js#L143-L202 |
|
54,840 | ItsAsbreuk/itsa-mojitonthefly-addon | assets/itsa-mojitonthefly.client.js | function(anchornode) {
var valid = (anchornode.get('tagName')==='A') && anchornode.getAttribute('data-pjax-mojit'),
attributes, i, parheader;
if (valid) {
attributes = {
'data-pjax-mojit': anchornode.getAttribute('data-pjax-mojit'),
'data-pjax-action': anchornode.getAttribute('data-pjax-action'),
'data-pjax-container': anchornode.getAttribute('data-pjax-container'),
'data-pjax-preload': anchornode.getAttribute('data-pjax-preload')
};
i = 0;
/*jshint boss:true */
while (parheader=anchornode.getAttribute('data-pjax-par'+(++i))) {
attributes['data-pjax-par'+i] = parheader;
}
/*jshint boss:false */
Y.fire(EVT_PJAX, {uri: anchornode.getAttribute('href'), targetid: anchornode.get('id'), attributes: attributes, fromhistorychange: false});
}
} | javascript | function(anchornode) {
var valid = (anchornode.get('tagName')==='A') && anchornode.getAttribute('data-pjax-mojit'),
attributes, i, parheader;
if (valid) {
attributes = {
'data-pjax-mojit': anchornode.getAttribute('data-pjax-mojit'),
'data-pjax-action': anchornode.getAttribute('data-pjax-action'),
'data-pjax-container': anchornode.getAttribute('data-pjax-container'),
'data-pjax-preload': anchornode.getAttribute('data-pjax-preload')
};
i = 0;
/*jshint boss:true */
while (parheader=anchornode.getAttribute('data-pjax-par'+(++i))) {
attributes['data-pjax-par'+i] = parheader;
}
/*jshint boss:false */
Y.fire(EVT_PJAX, {uri: anchornode.getAttribute('href'), targetid: anchornode.get('id'), attributes: attributes, fromhistorychange: false});
}
} | [
"function",
"(",
"anchornode",
")",
"{",
"var",
"valid",
"=",
"(",
"anchornode",
".",
"get",
"(",
"'tagName'",
")",
"===",
"'A'",
")",
"&&",
"anchornode",
".",
"getAttribute",
"(",
"'data-pjax-mojit'",
")",
",",
"attributes",
",",
"i",
",",
"parheader",
";",
"if",
"(",
"valid",
")",
"{",
"attributes",
"=",
"{",
"'data-pjax-mojit'",
":",
"anchornode",
".",
"getAttribute",
"(",
"'data-pjax-mojit'",
")",
",",
"'data-pjax-action'",
":",
"anchornode",
".",
"getAttribute",
"(",
"'data-pjax-action'",
")",
",",
"'data-pjax-container'",
":",
"anchornode",
".",
"getAttribute",
"(",
"'data-pjax-container'",
")",
",",
"'data-pjax-preload'",
":",
"anchornode",
".",
"getAttribute",
"(",
"'data-pjax-preload'",
")",
"}",
";",
"i",
"=",
"0",
";",
"/*jshint boss:true */",
"while",
"(",
"parheader",
"=",
"anchornode",
".",
"getAttribute",
"(",
"'data-pjax-par'",
"+",
"(",
"++",
"i",
")",
")",
")",
"{",
"attributes",
"[",
"'data-pjax-par'",
"+",
"i",
"]",
"=",
"parheader",
";",
"}",
"/*jshint boss:false */",
"Y",
".",
"fire",
"(",
"EVT_PJAX",
",",
"{",
"uri",
":",
"anchornode",
".",
"getAttribute",
"(",
"'href'",
")",
",",
"targetid",
":",
"anchornode",
".",
"get",
"(",
"'id'",
")",
",",
"attributes",
":",
"attributes",
",",
"fromhistorychange",
":",
"false",
"}",
")",
";",
"}",
"}"
] | Simulates an achorclick on a Pjax-link-element.
@method Y.mojito.pjax.simulateAnchorClick
@param anchornode {Y.Node} the node on which the click should be simulated | [
"Simulates",
"an",
"achorclick",
"on",
"a",
"Pjax",
"-",
"link",
"-",
"element",
"."
] | 500de397fef8f80f719360d4ac023bb860934ec0 | https://github.com/ItsAsbreuk/itsa-mojitonthefly-addon/blob/500de397fef8f80f719360d4ac023bb860934ec0/assets/itsa-mojitonthefly.client.js#L957-L975 |
|
54,841 | cheng-kang/vuewild | src/vuewild.js | _getRef | function _getRef (refOrQuery) {
if (typeof refOrQuery.ref === 'function') {
refOrQuery = refOrQuery.ref()
} else if (typeof refOrQuery.ref === 'object') {
refOrQuery = refOrQuery.ref
}
return refOrQuery
} | javascript | function _getRef (refOrQuery) {
if (typeof refOrQuery.ref === 'function') {
refOrQuery = refOrQuery.ref()
} else if (typeof refOrQuery.ref === 'object') {
refOrQuery = refOrQuery.ref
}
return refOrQuery
} | [
"function",
"_getRef",
"(",
"refOrQuery",
")",
"{",
"if",
"(",
"typeof",
"refOrQuery",
".",
"ref",
"===",
"'function'",
")",
"{",
"refOrQuery",
"=",
"refOrQuery",
".",
"ref",
"(",
")",
"}",
"else",
"if",
"(",
"typeof",
"refOrQuery",
".",
"ref",
"===",
"'object'",
")",
"{",
"refOrQuery",
"=",
"refOrQuery",
".",
"ref",
"}",
"return",
"refOrQuery",
"}"
] | Returns the original reference of a Wilddog reference or query across SDK versions.
@param {WilddogReference|WilddogQuery} refOrQuery
@return {WilddogReference} | [
"Returns",
"the",
"original",
"reference",
"of",
"a",
"Wilddog",
"reference",
"or",
"query",
"across",
"SDK",
"versions",
"."
] | 76288484f73eaa99217dea92a2f34eb67e27405a | https://github.com/cheng-kang/vuewild/blob/76288484f73eaa99217dea92a2f34eb67e27405a/src/vuewild.js#L21-L29 |
54,842 | cheng-kang/vuewild | src/vuewild.js | createRecord | function createRecord (snapshot) {
var value = snapshot.val()
var res = isObject(value)
? value
: { '.value': value }
res['.key'] = _getKey(snapshot)
return res
} | javascript | function createRecord (snapshot) {
var value = snapshot.val()
var res = isObject(value)
? value
: { '.value': value }
res['.key'] = _getKey(snapshot)
return res
} | [
"function",
"createRecord",
"(",
"snapshot",
")",
"{",
"var",
"value",
"=",
"snapshot",
".",
"val",
"(",
")",
"var",
"res",
"=",
"isObject",
"(",
"value",
")",
"?",
"value",
":",
"{",
"'.value'",
":",
"value",
"}",
"res",
"[",
"'.key'",
"]",
"=",
"_getKey",
"(",
"snapshot",
")",
"return",
"res",
"}"
] | Convert wilddog snapshot into a bindable data record.
@param {WilddogSnapshot} snapshot
@return {Object} | [
"Convert",
"wilddog",
"snapshot",
"into",
"a",
"bindable",
"data",
"record",
"."
] | 76288484f73eaa99217dea92a2f34eb67e27405a | https://github.com/cheng-kang/vuewild/blob/76288484f73eaa99217dea92a2f34eb67e27405a/src/vuewild.js#L47-L54 |
54,843 | cheng-kang/vuewild | src/vuewild.js | indexForKey | function indexForKey (array, key) {
for (var i = 0; i < array.length; i++) {
if (array[i]['.key'] === key) {
return i
}
}
/* istanbul ignore next */
return -1
} | javascript | function indexForKey (array, key) {
for (var i = 0; i < array.length; i++) {
if (array[i]['.key'] === key) {
return i
}
}
/* istanbul ignore next */
return -1
} | [
"function",
"indexForKey",
"(",
"array",
",",
"key",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"array",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"array",
"[",
"i",
"]",
"[",
"'.key'",
"]",
"===",
"key",
")",
"{",
"return",
"i",
"}",
"}",
"/* istanbul ignore next */",
"return",
"-",
"1",
"}"
] | Find the index for an object with given key.
@param {array} array
@param {string} key
@return {number} | [
"Find",
"the",
"index",
"for",
"an",
"object",
"with",
"given",
"key",
"."
] | 76288484f73eaa99217dea92a2f34eb67e27405a | https://github.com/cheng-kang/vuewild/blob/76288484f73eaa99217dea92a2f34eb67e27405a/src/vuewild.js#L63-L71 |
54,844 | cheng-kang/vuewild | src/vuewild.js | bind | function bind (vm, key, source) {
var asObject = false
var cancelCallback = null
var readyCallback = null
// check { source, asArray, cancelCallback } syntax
if (isObject(source) && source.hasOwnProperty('source')) {
asObject = source.asObject
cancelCallback = source.cancelCallback
readyCallback = source.readyCallback
source = source.source
}
if (!isObject(source)) {
throw new Error('VueWild: invalid Wilddog binding source.')
}
var ref = _getRef(source)
vm.$wilddogRefs[key] = ref
vm._wilddogSources[key] = source
if (cancelCallback) {
cancelCallback = cancelCallback.bind(vm)
}
// bind based on initial value type
if (asObject) {
bindAsObject(vm, key, source, cancelCallback)
} else {
bindAsArray(vm, key, source, cancelCallback)
}
if (readyCallback) {
source.once('value', readyCallback.bind(vm))
}
} | javascript | function bind (vm, key, source) {
var asObject = false
var cancelCallback = null
var readyCallback = null
// check { source, asArray, cancelCallback } syntax
if (isObject(source) && source.hasOwnProperty('source')) {
asObject = source.asObject
cancelCallback = source.cancelCallback
readyCallback = source.readyCallback
source = source.source
}
if (!isObject(source)) {
throw new Error('VueWild: invalid Wilddog binding source.')
}
var ref = _getRef(source)
vm.$wilddogRefs[key] = ref
vm._wilddogSources[key] = source
if (cancelCallback) {
cancelCallback = cancelCallback.bind(vm)
}
// bind based on initial value type
if (asObject) {
bindAsObject(vm, key, source, cancelCallback)
} else {
bindAsArray(vm, key, source, cancelCallback)
}
if (readyCallback) {
source.once('value', readyCallback.bind(vm))
}
} | [
"function",
"bind",
"(",
"vm",
",",
"key",
",",
"source",
")",
"{",
"var",
"asObject",
"=",
"false",
"var",
"cancelCallback",
"=",
"null",
"var",
"readyCallback",
"=",
"null",
"// check { source, asArray, cancelCallback } syntax",
"if",
"(",
"isObject",
"(",
"source",
")",
"&&",
"source",
".",
"hasOwnProperty",
"(",
"'source'",
")",
")",
"{",
"asObject",
"=",
"source",
".",
"asObject",
"cancelCallback",
"=",
"source",
".",
"cancelCallback",
"readyCallback",
"=",
"source",
".",
"readyCallback",
"source",
"=",
"source",
".",
"source",
"}",
"if",
"(",
"!",
"isObject",
"(",
"source",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'VueWild: invalid Wilddog binding source.'",
")",
"}",
"var",
"ref",
"=",
"_getRef",
"(",
"source",
")",
"vm",
".",
"$wilddogRefs",
"[",
"key",
"]",
"=",
"ref",
"vm",
".",
"_wilddogSources",
"[",
"key",
"]",
"=",
"source",
"if",
"(",
"cancelCallback",
")",
"{",
"cancelCallback",
"=",
"cancelCallback",
".",
"bind",
"(",
"vm",
")",
"}",
"// bind based on initial value type",
"if",
"(",
"asObject",
")",
"{",
"bindAsObject",
"(",
"vm",
",",
"key",
",",
"source",
",",
"cancelCallback",
")",
"}",
"else",
"{",
"bindAsArray",
"(",
"vm",
",",
"key",
",",
"source",
",",
"cancelCallback",
")",
"}",
"if",
"(",
"readyCallback",
")",
"{",
"source",
".",
"once",
"(",
"'value'",
",",
"readyCallback",
".",
"bind",
"(",
"vm",
")",
")",
"}",
"}"
] | Bind a wilddog data source to a key on a vm.
@param {Vue} vm
@param {string} key
@param {object} source | [
"Bind",
"a",
"wilddog",
"data",
"source",
"to",
"a",
"key",
"on",
"a",
"vm",
"."
] | 76288484f73eaa99217dea92a2f34eb67e27405a | https://github.com/cheng-kang/vuewild/blob/76288484f73eaa99217dea92a2f34eb67e27405a/src/vuewild.js#L80-L109 |
54,845 | cheng-kang/vuewild | src/vuewild.js | defineReactive | function defineReactive (vm, key, val) {
if (key in vm) {
vm[key] = val
} else {
Vue.util.defineReactive(vm, key, val)
}
} | javascript | function defineReactive (vm, key, val) {
if (key in vm) {
vm[key] = val
} else {
Vue.util.defineReactive(vm, key, val)
}
} | [
"function",
"defineReactive",
"(",
"vm",
",",
"key",
",",
"val",
")",
"{",
"if",
"(",
"key",
"in",
"vm",
")",
"{",
"vm",
"[",
"key",
"]",
"=",
"val",
"}",
"else",
"{",
"Vue",
".",
"util",
".",
"defineReactive",
"(",
"vm",
",",
"key",
",",
"val",
")",
"}",
"}"
] | Define a reactive property in a given vm if it's not defined
yet
@param {Vue} vm
@param {string} key
@param {*} val | [
"Define",
"a",
"reactive",
"property",
"in",
"a",
"given",
"vm",
"if",
"it",
"s",
"not",
"defined",
"yet"
] | 76288484f73eaa99217dea92a2f34eb67e27405a | https://github.com/cheng-kang/vuewild/blob/76288484f73eaa99217dea92a2f34eb67e27405a/src/vuewild.js#L119-L125 |
54,846 | cheng-kang/vuewild | src/vuewild.js | bindAsArray | function bindAsArray (vm, key, source, cancelCallback) {
var array = []
defineReactive(vm, key, array)
var onAdd = source.on('child_added', function (snapshot, prevKey) {
var index = prevKey ? indexForKey(array, prevKey) + 1 : 0
array.splice(index, 0, createRecord(snapshot))
}, cancelCallback)
var onRemove = source.on('child_removed', function (snapshot) {
var index = indexForKey(array, _getKey(snapshot))
array.splice(index, 1)
}, cancelCallback)
var onChange = source.on('child_changed', function (snapshot) {
var index = indexForKey(array, _getKey(snapshot))
array.splice(index, 1, createRecord(snapshot))
}, cancelCallback)
var onMove = source.on('child_moved', function (snapshot, prevKey) {
var index = indexForKey(array, _getKey(snapshot))
var record = array.splice(index, 1)[0]
var newIndex = prevKey ? indexForKey(array, prevKey) + 1 : 0
array.splice(newIndex, 0, record)
}, cancelCallback)
vm._wilddogListeners[key] = {
child_added: onAdd,
child_removed: onRemove,
child_changed: onChange,
child_moved: onMove
}
} | javascript | function bindAsArray (vm, key, source, cancelCallback) {
var array = []
defineReactive(vm, key, array)
var onAdd = source.on('child_added', function (snapshot, prevKey) {
var index = prevKey ? indexForKey(array, prevKey) + 1 : 0
array.splice(index, 0, createRecord(snapshot))
}, cancelCallback)
var onRemove = source.on('child_removed', function (snapshot) {
var index = indexForKey(array, _getKey(snapshot))
array.splice(index, 1)
}, cancelCallback)
var onChange = source.on('child_changed', function (snapshot) {
var index = indexForKey(array, _getKey(snapshot))
array.splice(index, 1, createRecord(snapshot))
}, cancelCallback)
var onMove = source.on('child_moved', function (snapshot, prevKey) {
var index = indexForKey(array, _getKey(snapshot))
var record = array.splice(index, 1)[0]
var newIndex = prevKey ? indexForKey(array, prevKey) + 1 : 0
array.splice(newIndex, 0, record)
}, cancelCallback)
vm._wilddogListeners[key] = {
child_added: onAdd,
child_removed: onRemove,
child_changed: onChange,
child_moved: onMove
}
} | [
"function",
"bindAsArray",
"(",
"vm",
",",
"key",
",",
"source",
",",
"cancelCallback",
")",
"{",
"var",
"array",
"=",
"[",
"]",
"defineReactive",
"(",
"vm",
",",
"key",
",",
"array",
")",
"var",
"onAdd",
"=",
"source",
".",
"on",
"(",
"'child_added'",
",",
"function",
"(",
"snapshot",
",",
"prevKey",
")",
"{",
"var",
"index",
"=",
"prevKey",
"?",
"indexForKey",
"(",
"array",
",",
"prevKey",
")",
"+",
"1",
":",
"0",
"array",
".",
"splice",
"(",
"index",
",",
"0",
",",
"createRecord",
"(",
"snapshot",
")",
")",
"}",
",",
"cancelCallback",
")",
"var",
"onRemove",
"=",
"source",
".",
"on",
"(",
"'child_removed'",
",",
"function",
"(",
"snapshot",
")",
"{",
"var",
"index",
"=",
"indexForKey",
"(",
"array",
",",
"_getKey",
"(",
"snapshot",
")",
")",
"array",
".",
"splice",
"(",
"index",
",",
"1",
")",
"}",
",",
"cancelCallback",
")",
"var",
"onChange",
"=",
"source",
".",
"on",
"(",
"'child_changed'",
",",
"function",
"(",
"snapshot",
")",
"{",
"var",
"index",
"=",
"indexForKey",
"(",
"array",
",",
"_getKey",
"(",
"snapshot",
")",
")",
"array",
".",
"splice",
"(",
"index",
",",
"1",
",",
"createRecord",
"(",
"snapshot",
")",
")",
"}",
",",
"cancelCallback",
")",
"var",
"onMove",
"=",
"source",
".",
"on",
"(",
"'child_moved'",
",",
"function",
"(",
"snapshot",
",",
"prevKey",
")",
"{",
"var",
"index",
"=",
"indexForKey",
"(",
"array",
",",
"_getKey",
"(",
"snapshot",
")",
")",
"var",
"record",
"=",
"array",
".",
"splice",
"(",
"index",
",",
"1",
")",
"[",
"0",
"]",
"var",
"newIndex",
"=",
"prevKey",
"?",
"indexForKey",
"(",
"array",
",",
"prevKey",
")",
"+",
"1",
":",
"0",
"array",
".",
"splice",
"(",
"newIndex",
",",
"0",
",",
"record",
")",
"}",
",",
"cancelCallback",
")",
"vm",
".",
"_wilddogListeners",
"[",
"key",
"]",
"=",
"{",
"child_added",
":",
"onAdd",
",",
"child_removed",
":",
"onRemove",
",",
"child_changed",
":",
"onChange",
",",
"child_moved",
":",
"onMove",
"}",
"}"
] | Bind a wilddog data source to a key on a vm as an Array.
@param {Vue} vm
@param {string} key
@param {object} source
@param {function|null} cancelCallback | [
"Bind",
"a",
"wilddog",
"data",
"source",
"to",
"a",
"key",
"on",
"a",
"vm",
"as",
"an",
"Array",
"."
] | 76288484f73eaa99217dea92a2f34eb67e27405a | https://github.com/cheng-kang/vuewild/blob/76288484f73eaa99217dea92a2f34eb67e27405a/src/vuewild.js#L135-L167 |
54,847 | cheng-kang/vuewild | src/vuewild.js | bindAsObject | function bindAsObject (vm, key, source, cancelCallback) {
defineReactive(vm, key, {})
var cb = source.on('value', function (snapshot) {
vm[key] = createRecord(snapshot)
}, cancelCallback)
vm._wilddogListeners[key] = { value: cb }
} | javascript | function bindAsObject (vm, key, source, cancelCallback) {
defineReactive(vm, key, {})
var cb = source.on('value', function (snapshot) {
vm[key] = createRecord(snapshot)
}, cancelCallback)
vm._wilddogListeners[key] = { value: cb }
} | [
"function",
"bindAsObject",
"(",
"vm",
",",
"key",
",",
"source",
",",
"cancelCallback",
")",
"{",
"defineReactive",
"(",
"vm",
",",
"key",
",",
"{",
"}",
")",
"var",
"cb",
"=",
"source",
".",
"on",
"(",
"'value'",
",",
"function",
"(",
"snapshot",
")",
"{",
"vm",
"[",
"key",
"]",
"=",
"createRecord",
"(",
"snapshot",
")",
"}",
",",
"cancelCallback",
")",
"vm",
".",
"_wilddogListeners",
"[",
"key",
"]",
"=",
"{",
"value",
":",
"cb",
"}",
"}"
] | Bind a wilddog data source to a key on a vm as an Object.
@param {Vue} vm
@param {string} key
@param {Object} source
@param {function|null} cancelCallback | [
"Bind",
"a",
"wilddog",
"data",
"source",
"to",
"a",
"key",
"on",
"a",
"vm",
"as",
"an",
"Object",
"."
] | 76288484f73eaa99217dea92a2f34eb67e27405a | https://github.com/cheng-kang/vuewild/blob/76288484f73eaa99217dea92a2f34eb67e27405a/src/vuewild.js#L177-L183 |
54,848 | cheng-kang/vuewild | src/vuewild.js | unbind | function unbind (vm, key) {
var source = vm._wilddogSources && vm._wilddogSources[key]
if (!source) {
throw new Error(
'VueWild: unbind failed: "' + key + '" is not bound to ' +
'a Wilddog reference.'
)
}
var listeners = vm._wilddogListeners[key]
for (var event in listeners) {
source.off(event, listeners[event])
}
vm[key] = null
vm.$wilddogRefs[key] = null
vm._wilddogSources[key] = null
vm._wilddogListeners[key] = null
} | javascript | function unbind (vm, key) {
var source = vm._wilddogSources && vm._wilddogSources[key]
if (!source) {
throw new Error(
'VueWild: unbind failed: "' + key + '" is not bound to ' +
'a Wilddog reference.'
)
}
var listeners = vm._wilddogListeners[key]
for (var event in listeners) {
source.off(event, listeners[event])
}
vm[key] = null
vm.$wilddogRefs[key] = null
vm._wilddogSources[key] = null
vm._wilddogListeners[key] = null
} | [
"function",
"unbind",
"(",
"vm",
",",
"key",
")",
"{",
"var",
"source",
"=",
"vm",
".",
"_wilddogSources",
"&&",
"vm",
".",
"_wilddogSources",
"[",
"key",
"]",
"if",
"(",
"!",
"source",
")",
"{",
"throw",
"new",
"Error",
"(",
"'VueWild: unbind failed: \"'",
"+",
"key",
"+",
"'\" is not bound to '",
"+",
"'a Wilddog reference.'",
")",
"}",
"var",
"listeners",
"=",
"vm",
".",
"_wilddogListeners",
"[",
"key",
"]",
"for",
"(",
"var",
"event",
"in",
"listeners",
")",
"{",
"source",
".",
"off",
"(",
"event",
",",
"listeners",
"[",
"event",
"]",
")",
"}",
"vm",
"[",
"key",
"]",
"=",
"null",
"vm",
".",
"$wilddogRefs",
"[",
"key",
"]",
"=",
"null",
"vm",
".",
"_wilddogSources",
"[",
"key",
"]",
"=",
"null",
"vm",
".",
"_wilddogListeners",
"[",
"key",
"]",
"=",
"null",
"}"
] | Unbind a wilddog-bound key from a vm.
@param {Vue} vm
@param {string} key | [
"Unbind",
"a",
"wilddog",
"-",
"bound",
"key",
"from",
"a",
"vm",
"."
] | 76288484f73eaa99217dea92a2f34eb67e27405a | https://github.com/cheng-kang/vuewild/blob/76288484f73eaa99217dea92a2f34eb67e27405a/src/vuewild.js#L191-L207 |
54,849 | cheng-kang/vuewild | src/vuewild.js | ensureRefs | function ensureRefs (vm) {
if (!vm.$wilddogRefs) {
vm.$wilddogRefs = Object.create(null)
vm._wilddogSources = Object.create(null)
vm._wilddogListeners = Object.create(null)
}
} | javascript | function ensureRefs (vm) {
if (!vm.$wilddogRefs) {
vm.$wilddogRefs = Object.create(null)
vm._wilddogSources = Object.create(null)
vm._wilddogListeners = Object.create(null)
}
} | [
"function",
"ensureRefs",
"(",
"vm",
")",
"{",
"if",
"(",
"!",
"vm",
".",
"$wilddogRefs",
")",
"{",
"vm",
".",
"$wilddogRefs",
"=",
"Object",
".",
"create",
"(",
"null",
")",
"vm",
".",
"_wilddogSources",
"=",
"Object",
".",
"create",
"(",
"null",
")",
"vm",
".",
"_wilddogListeners",
"=",
"Object",
".",
"create",
"(",
"null",
")",
"}",
"}"
] | Ensure the related bookkeeping variables on an instance.
@param {Vue} vm | [
"Ensure",
"the",
"related",
"bookkeeping",
"variables",
"on",
"an",
"instance",
"."
] | 76288484f73eaa99217dea92a2f34eb67e27405a | https://github.com/cheng-kang/vuewild/blob/76288484f73eaa99217dea92a2f34eb67e27405a/src/vuewild.js#L214-L220 |
54,850 | simbo/auto-plug | lib/auto-plug.js | getRequireNameForPackage | function getRequireNameForPackage(pkgName) {
if (this.options.rename[pkgName]) {
return this.options.rename[pkgName];
}
var requireName = pkgName.replace(this.options.replaceExp, '');
return this.options.camelize ? camelize(requireName) : requireName;
} | javascript | function getRequireNameForPackage(pkgName) {
if (this.options.rename[pkgName]) {
return this.options.rename[pkgName];
}
var requireName = pkgName.replace(this.options.replaceExp, '');
return this.options.camelize ? camelize(requireName) : requireName;
} | [
"function",
"getRequireNameForPackage",
"(",
"pkgName",
")",
"{",
"if",
"(",
"this",
".",
"options",
".",
"rename",
"[",
"pkgName",
"]",
")",
"{",
"return",
"this",
".",
"options",
".",
"rename",
"[",
"pkgName",
"]",
";",
"}",
"var",
"requireName",
"=",
"pkgName",
".",
"replace",
"(",
"this",
".",
"options",
".",
"replaceExp",
",",
"''",
")",
";",
"return",
"this",
".",
"options",
".",
"camelize",
"?",
"camelize",
"(",
"requireName",
")",
":",
"requireName",
";",
"}"
] | returns a filtered name for a require container property
@param {String} pkgName original package name
@return {String} filtered name | [
"returns",
"a",
"filtered",
"name",
"for",
"a",
"require",
"container",
"property"
] | ce7178b495c67787d7fd805a37854d927e45a999 | https://github.com/simbo/auto-plug/blob/ce7178b495c67787d7fd805a37854d927e45a999/lib/auto-plug.js#L188-L194 |
54,851 | commenthol/streamss | lib/readarray.js | ReadArray | function ReadArray (options, array) {
if (!(this instanceof ReadArray)) {
return new ReadArray(options, array)
}
if (Array.isArray(options)) {
array = options
options = {}
}
options = Object.assign({}, options)
Readable.call(this, options)
this._array = array || []
this._cnt = this._array.length
return this
} | javascript | function ReadArray (options, array) {
if (!(this instanceof ReadArray)) {
return new ReadArray(options, array)
}
if (Array.isArray(options)) {
array = options
options = {}
}
options = Object.assign({}, options)
Readable.call(this, options)
this._array = array || []
this._cnt = this._array.length
return this
} | [
"function",
"ReadArray",
"(",
"options",
",",
"array",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"ReadArray",
")",
")",
"{",
"return",
"new",
"ReadArray",
"(",
"options",
",",
"array",
")",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"options",
")",
")",
"{",
"array",
"=",
"options",
"options",
"=",
"{",
"}",
"}",
"options",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
")",
"Readable",
".",
"call",
"(",
"this",
",",
"options",
")",
"this",
".",
"_array",
"=",
"array",
"||",
"[",
"]",
"this",
".",
"_cnt",
"=",
"this",
".",
"_array",
".",
"length",
"return",
"this",
"}"
] | Read from an Array and push into stream.
Takes care on pausing to push to the stream if pipe is saturated.
@constructor
@param {Object} [options] - Stream Options `{encoding, highWaterMark, objectMode, ...}`
@param {Array} array - array to push down as stream (If array is an array of objects set `objectMode:true` or use `ReadArray.obj`)
@return {Readable} A readable stream | [
"Read",
"from",
"an",
"Array",
"and",
"push",
"into",
"stream",
"."
] | cfef5d0ed30c7efe002018886e2e843c91d3558f | https://github.com/commenthol/streamss/blob/cfef5d0ed30c7efe002018886e2e843c91d3558f/lib/readarray.js#L21-L38 |
54,852 | camshaft/rework-modules | lib/modules.js | select | function select(rule, prefix) {
return rule.selectors && rule.selectors[0] && rule.selectors[0].indexOf(prefix) === 0;
} | javascript | function select(rule, prefix) {
return rule.selectors && rule.selectors[0] && rule.selectors[0].indexOf(prefix) === 0;
} | [
"function",
"select",
"(",
"rule",
",",
"prefix",
")",
"{",
"return",
"rule",
".",
"selectors",
"&&",
"rule",
".",
"selectors",
"[",
"0",
"]",
"&&",
"rule",
".",
"selectors",
"[",
"0",
"]",
".",
"indexOf",
"(",
"prefix",
")",
"===",
"0",
";",
"}"
] | Match the rule's selector on prefix
@param {Object} rule
@param {String} prefix
@return {Boolean} | [
"Match",
"the",
"rule",
"s",
"selector",
"on",
"prefix"
] | 2c3616dbfaab5f039a395968890719887410514b | https://github.com/camshaft/rework-modules/blob/2c3616dbfaab5f039a395968890719887410514b/lib/modules.js#L353-L355 |
54,853 | yoshuawuyts/methodist | index.js | assertKeys | function assertKeys (routes) {
Object.keys(routes).forEach(function (route) {
assert.ok(meths.indexOf(route) !== -1, route + ' is an invalid method')
})
} | javascript | function assertKeys (routes) {
Object.keys(routes).forEach(function (route) {
assert.ok(meths.indexOf(route) !== -1, route + ' is an invalid method')
})
} | [
"function",
"assertKeys",
"(",
"routes",
")",
"{",
"Object",
".",
"keys",
"(",
"routes",
")",
".",
"forEach",
"(",
"function",
"(",
"route",
")",
"{",
"assert",
".",
"ok",
"(",
"meths",
".",
"indexOf",
"(",
"route",
")",
"!==",
"-",
"1",
",",
"route",
"+",
"' is an invalid method'",
")",
"}",
")",
"}"
] | assert object keys obj -> null | [
"assert",
"object",
"keys",
"obj",
"-",
">",
"null"
] | 27ea0672f5e021bec3ee95e00445cccabce6be79 | https://github.com/yoshuawuyts/methodist/blob/27ea0672f5e021bec3ee95e00445cccabce6be79/index.js#L34-L38 |
54,854 | bahmutov/connect-stop | index.js | getQueryResponse | function getQueryResponse(url) {
var response;
if (options.stopQueryParam) {
var parsedUrl = parseUrl(url, true);
if (parsedUrl.query && parsedUrl.query[options.stopQueryParam]) {
var queryResponse = parseInt(parsedUrl.query[options.stopQueryParam]);
if (queryResponse > 1) {
response = queryResponse;
}
}
}
return response;
} | javascript | function getQueryResponse(url) {
var response;
if (options.stopQueryParam) {
var parsedUrl = parseUrl(url, true);
if (parsedUrl.query && parsedUrl.query[options.stopQueryParam]) {
var queryResponse = parseInt(parsedUrl.query[options.stopQueryParam]);
if (queryResponse > 1) {
response = queryResponse;
}
}
}
return response;
} | [
"function",
"getQueryResponse",
"(",
"url",
")",
"{",
"var",
"response",
";",
"if",
"(",
"options",
".",
"stopQueryParam",
")",
"{",
"var",
"parsedUrl",
"=",
"parseUrl",
"(",
"url",
",",
"true",
")",
";",
"if",
"(",
"parsedUrl",
".",
"query",
"&&",
"parsedUrl",
".",
"query",
"[",
"options",
".",
"stopQueryParam",
"]",
")",
"{",
"var",
"queryResponse",
"=",
"parseInt",
"(",
"parsedUrl",
".",
"query",
"[",
"options",
".",
"stopQueryParam",
"]",
")",
";",
"if",
"(",
"queryResponse",
">",
"1",
")",
"{",
"response",
"=",
"queryResponse",
";",
"}",
"}",
"}",
"return",
"response",
";",
"}"
] | Return the response for this url, if defined | [
"Return",
"the",
"response",
"for",
"this",
"url",
"if",
"defined"
] | 558c0569f55cf25533dcda88a66495031cf1d140 | https://github.com/bahmutov/connect-stop/blob/558c0569f55cf25533dcda88a66495031cf1d140/index.js#L17-L31 |
54,855 | wigy/chronicles_of_angular | src/store/db.js | engine | function engine(url) {
var ret;
var parts = /^(\w+):/.exec(url);
if (!parts) {
d.fatal("Invalid engine URI", url);
}
try {
var Engine = angular.injector(['ng', 'coa.store']).get('Engine' + parts[1].ucfirst());
ret = new Engine(url);
} catch(e) {
d.fatal("Unable to instantiate engine for URI", url, e);
}
d('STORE', 'Creating an engine for URI', url, ':', ret);
return ret;
} | javascript | function engine(url) {
var ret;
var parts = /^(\w+):/.exec(url);
if (!parts) {
d.fatal("Invalid engine URI", url);
}
try {
var Engine = angular.injector(['ng', 'coa.store']).get('Engine' + parts[1].ucfirst());
ret = new Engine(url);
} catch(e) {
d.fatal("Unable to instantiate engine for URI", url, e);
}
d('STORE', 'Creating an engine for URI', url, ':', ret);
return ret;
} | [
"function",
"engine",
"(",
"url",
")",
"{",
"var",
"ret",
";",
"var",
"parts",
"=",
"/",
"^(\\w+):",
"/",
".",
"exec",
"(",
"url",
")",
";",
"if",
"(",
"!",
"parts",
")",
"{",
"d",
".",
"fatal",
"(",
"\"Invalid engine URI\"",
",",
"url",
")",
";",
"}",
"try",
"{",
"var",
"Engine",
"=",
"angular",
".",
"injector",
"(",
"[",
"'ng'",
",",
"'coa.store'",
"]",
")",
".",
"get",
"(",
"'Engine'",
"+",
"parts",
"[",
"1",
"]",
".",
"ucfirst",
"(",
")",
")",
";",
"ret",
"=",
"new",
"Engine",
"(",
"url",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"d",
".",
"fatal",
"(",
"\"Unable to instantiate engine for URI\"",
",",
"url",
",",
"e",
")",
";",
"}",
"d",
"(",
"'STORE'",
",",
"'Creating an engine for URI'",
",",
"url",
",",
"':'",
",",
"ret",
")",
";",
"return",
"ret",
";",
"}"
] | Parse URI and instantiate appropriate storage engine. | [
"Parse",
"URI",
"and",
"instantiate",
"appropriate",
"storage",
"engine",
"."
] | 3505c28291aff469bc58dabba80e192ed0eb3cce | https://github.com/wigy/chronicles_of_angular/blob/3505c28291aff469bc58dabba80e192ed0eb3cce/src/store/db.js#L22-L39 |
54,856 | wigy/chronicles_of_angular | src/store/db.js | getEngine | function getEngine(name) {
if (!dbconfig.has(name)) {
d.fatal("Trying to access data storage that is not configured:", name);
}
var conf = dbconfig.get(name);
if (!conf.engine) {
conf.engine = engine(conf.url);
}
return conf.engine;
} | javascript | function getEngine(name) {
if (!dbconfig.has(name)) {
d.fatal("Trying to access data storage that is not configured:", name);
}
var conf = dbconfig.get(name);
if (!conf.engine) {
conf.engine = engine(conf.url);
}
return conf.engine;
} | [
"function",
"getEngine",
"(",
"name",
")",
"{",
"if",
"(",
"!",
"dbconfig",
".",
"has",
"(",
"name",
")",
")",
"{",
"d",
".",
"fatal",
"(",
"\"Trying to access data storage that is not configured:\"",
",",
"name",
")",
";",
"}",
"var",
"conf",
"=",
"dbconfig",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"!",
"conf",
".",
"engine",
")",
"{",
"conf",
".",
"engine",
"=",
"engine",
"(",
"conf",
".",
"url",
")",
";",
"}",
"return",
"conf",
".",
"engine",
";",
"}"
] | Helper function to instantiate and initialize engine.
If the named engine is not yet set in `dbconfig`, it is
created and inserted there. Note that every time `dbconfig`
is changed, the engine is nullified and new one is instantiated
on the first use. | [
"Helper",
"function",
"to",
"instantiate",
"and",
"initialize",
"engine",
".",
"If",
"the",
"named",
"engine",
"is",
"not",
"yet",
"set",
"in",
"dbconfig",
"it",
"is",
"created",
"and",
"inserted",
"there",
".",
"Note",
"that",
"every",
"time",
"dbconfig",
"is",
"changed",
"the",
"engine",
"is",
"nullified",
"and",
"new",
"one",
"is",
"instantiated",
"on",
"the",
"first",
"use",
"."
] | 3505c28291aff469bc58dabba80e192ed0eb3cce | https://github.com/wigy/chronicles_of_angular/blob/3505c28291aff469bc58dabba80e192ed0eb3cce/src/store/db.js#L48-L57 |
54,857 | ForbesLindesay-Unmaintained/sauce-test | lib/run-driver.js | runDriver | function runDriver(location, driver, options) {
options.testComplete = options.testComplete || 'return window.TESTS_COMPLETE';
options.testPassed = options.testPassed || 'return window.TESTS_PASSED && !window.TESTS_FAILED';
var startTime = Date.now();
var jobInfo = {
name: options.name,
build: process.env.TRAVIS_JOB_ID
};
Object.keys(options.jobInfo || {}).forEach(function (key) {
jobInfo[key] = options.jobInfo[key];
});
return Promise.resolve(null).then(function () {
return retry(function () {
return driver.sauceJobUpdate(jobInfo);
}, 3, '500ms', {debug: options.debug})
}).then(function () {
return retry(function () {
return driver.browser().activeWindow().navigator().navigateTo(location.url)
}, 3, '500ms', {debug: options.debug}).catch(err => {
err.message += ' (while navigating to url)';
throw err;
});
}).then(function () {
return waitForJobToFinish(driver, {
allowExceptions: options.allowExceptions,
testComplete: options.testComplete,
timeout: options.timeout,
debug: options.debug
});
}).then(function () {
return retry(function () {
if (typeof options.testPassed === 'string') {
return driver.browser().activeWindow().execute(options.testPassed);
} else {
return Promise.resolve(options.testPassed(driver));
}
}, 5, '500ms', {debug: options.debug});
}).then(function (result) {
result = {passed: result, duration: Date.now() - startTime};
return retry(function () { return driver.dispose({passed: result.passed}); }, 5, {debug: options.debug}).then(function () {
return result;
});
}, function (err) {
err.duration = Date.now() - startTime;
return retry(function () { return driver.dispose({passed: false}); }, 2, {debug: options.debug}).then(function () {
throw err;
}, function () {
throw err;
});
});
} | javascript | function runDriver(location, driver, options) {
options.testComplete = options.testComplete || 'return window.TESTS_COMPLETE';
options.testPassed = options.testPassed || 'return window.TESTS_PASSED && !window.TESTS_FAILED';
var startTime = Date.now();
var jobInfo = {
name: options.name,
build: process.env.TRAVIS_JOB_ID
};
Object.keys(options.jobInfo || {}).forEach(function (key) {
jobInfo[key] = options.jobInfo[key];
});
return Promise.resolve(null).then(function () {
return retry(function () {
return driver.sauceJobUpdate(jobInfo);
}, 3, '500ms', {debug: options.debug})
}).then(function () {
return retry(function () {
return driver.browser().activeWindow().navigator().navigateTo(location.url)
}, 3, '500ms', {debug: options.debug}).catch(err => {
err.message += ' (while navigating to url)';
throw err;
});
}).then(function () {
return waitForJobToFinish(driver, {
allowExceptions: options.allowExceptions,
testComplete: options.testComplete,
timeout: options.timeout,
debug: options.debug
});
}).then(function () {
return retry(function () {
if (typeof options.testPassed === 'string') {
return driver.browser().activeWindow().execute(options.testPassed);
} else {
return Promise.resolve(options.testPassed(driver));
}
}, 5, '500ms', {debug: options.debug});
}).then(function (result) {
result = {passed: result, duration: Date.now() - startTime};
return retry(function () { return driver.dispose({passed: result.passed}); }, 5, {debug: options.debug}).then(function () {
return result;
});
}, function (err) {
err.duration = Date.now() - startTime;
return retry(function () { return driver.dispose({passed: false}); }, 2, {debug: options.debug}).then(function () {
throw err;
}, function () {
throw err;
});
});
} | [
"function",
"runDriver",
"(",
"location",
",",
"driver",
",",
"options",
")",
"{",
"options",
".",
"testComplete",
"=",
"options",
".",
"testComplete",
"||",
"'return window.TESTS_COMPLETE'",
";",
"options",
".",
"testPassed",
"=",
"options",
".",
"testPassed",
"||",
"'return window.TESTS_PASSED && !window.TESTS_FAILED'",
";",
"var",
"startTime",
"=",
"Date",
".",
"now",
"(",
")",
";",
"var",
"jobInfo",
"=",
"{",
"name",
":",
"options",
".",
"name",
",",
"build",
":",
"process",
".",
"env",
".",
"TRAVIS_JOB_ID",
"}",
";",
"Object",
".",
"keys",
"(",
"options",
".",
"jobInfo",
"||",
"{",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"jobInfo",
"[",
"key",
"]",
"=",
"options",
".",
"jobInfo",
"[",
"key",
"]",
";",
"}",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
"null",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"retry",
"(",
"function",
"(",
")",
"{",
"return",
"driver",
".",
"sauceJobUpdate",
"(",
"jobInfo",
")",
";",
"}",
",",
"3",
",",
"'500ms'",
",",
"{",
"debug",
":",
"options",
".",
"debug",
"}",
")",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"retry",
"(",
"function",
"(",
")",
"{",
"return",
"driver",
".",
"browser",
"(",
")",
".",
"activeWindow",
"(",
")",
".",
"navigator",
"(",
")",
".",
"navigateTo",
"(",
"location",
".",
"url",
")",
"}",
",",
"3",
",",
"'500ms'",
",",
"{",
"debug",
":",
"options",
".",
"debug",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"err",
".",
"message",
"+=",
"' (while navigating to url)'",
";",
"throw",
"err",
";",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"waitForJobToFinish",
"(",
"driver",
",",
"{",
"allowExceptions",
":",
"options",
".",
"allowExceptions",
",",
"testComplete",
":",
"options",
".",
"testComplete",
",",
"timeout",
":",
"options",
".",
"timeout",
",",
"debug",
":",
"options",
".",
"debug",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"retry",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"typeof",
"options",
".",
"testPassed",
"===",
"'string'",
")",
"{",
"return",
"driver",
".",
"browser",
"(",
")",
".",
"activeWindow",
"(",
")",
".",
"execute",
"(",
"options",
".",
"testPassed",
")",
";",
"}",
"else",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"options",
".",
"testPassed",
"(",
"driver",
")",
")",
";",
"}",
"}",
",",
"5",
",",
"'500ms'",
",",
"{",
"debug",
":",
"options",
".",
"debug",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"result",
"=",
"{",
"passed",
":",
"result",
",",
"duration",
":",
"Date",
".",
"now",
"(",
")",
"-",
"startTime",
"}",
";",
"return",
"retry",
"(",
"function",
"(",
")",
"{",
"return",
"driver",
".",
"dispose",
"(",
"{",
"passed",
":",
"result",
".",
"passed",
"}",
")",
";",
"}",
",",
"5",
",",
"{",
"debug",
":",
"options",
".",
"debug",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"result",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"err",
".",
"duration",
"=",
"Date",
".",
"now",
"(",
")",
"-",
"startTime",
";",
"return",
"retry",
"(",
"function",
"(",
")",
"{",
"return",
"driver",
".",
"dispose",
"(",
"{",
"passed",
":",
"false",
"}",
")",
";",
"}",
",",
"2",
",",
"{",
"debug",
":",
"options",
".",
"debug",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"throw",
"err",
";",
"}",
",",
"function",
"(",
")",
"{",
"throw",
"err",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Run a test against a given location with the suplied driver
@option {Object} jobInfo An object that gets passed to Sauce Labs
@option {Boolean} allowExceptions Set to `true` to skip the check for `window.onerror`
@option {String|Function} testComplete A function to test if the job is complete
@option {String|Function} testPassed A function to test if the job has passed
@option {String} timeout
@param {Location} location
@param {Cabbie} driver
@param {Options} options
@returns {Promise.<TestResult>} | [
"Run",
"a",
"test",
"against",
"a",
"given",
"location",
"with",
"the",
"suplied",
"driver"
] | 7c671b3321dc63aefc00c1c8d49e943ead2e7f5e | https://github.com/ForbesLindesay-Unmaintained/sauce-test/blob/7c671b3321dc63aefc00c1c8d49e943ead2e7f5e/lib/run-driver.js#L23-L73 |
54,858 | hitchyjs/odem | index.js | mergeAttributes | function mergeAttributes( target, source ) {
const propNames = Object.keys( source );
for ( let i = 0, numNames = propNames.length; i < numNames; i++ ) {
const name = propNames[i];
const attribute = source[name];
switch ( typeof attribute ) {
case "object" :
if ( attribute ) {
break;
}
// falls through
default :
throw new TypeError( `invalid definition of attribute named "${name}": must be object` );
}
target[name] = attribute;
}
} | javascript | function mergeAttributes( target, source ) {
const propNames = Object.keys( source );
for ( let i = 0, numNames = propNames.length; i < numNames; i++ ) {
const name = propNames[i];
const attribute = source[name];
switch ( typeof attribute ) {
case "object" :
if ( attribute ) {
break;
}
// falls through
default :
throw new TypeError( `invalid definition of attribute named "${name}": must be object` );
}
target[name] = attribute;
}
} | [
"function",
"mergeAttributes",
"(",
"target",
",",
"source",
")",
"{",
"const",
"propNames",
"=",
"Object",
".",
"keys",
"(",
"source",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"numNames",
"=",
"propNames",
".",
"length",
";",
"i",
"<",
"numNames",
";",
"i",
"++",
")",
"{",
"const",
"name",
"=",
"propNames",
"[",
"i",
"]",
";",
"const",
"attribute",
"=",
"source",
"[",
"name",
"]",
";",
"switch",
"(",
"typeof",
"attribute",
")",
"{",
"case",
"\"object\"",
":",
"if",
"(",
"attribute",
")",
"{",
"break",
";",
"}",
"// falls through",
"default",
":",
"throw",
"new",
"TypeError",
"(",
"`",
"${",
"name",
"}",
"`",
")",
";",
"}",
"target",
"[",
"name",
"]",
"=",
"attribute",
";",
"}",
"}"
] | Merges separately defined map of static attributes into single schema
matching expectations of hitchy-odem.
@param {object} target resulting schema for use with hitchy-odem
@param {object<string,function>} source maps names of attributes into either one's definition of type and validation requirements
@returns {void} | [
"Merges",
"separately",
"defined",
"map",
"of",
"static",
"attributes",
"into",
"single",
"schema",
"matching",
"expectations",
"of",
"hitchy",
"-",
"odem",
"."
] | 28f3dc31cc3314f9109d2cac1f5f7e20dad6521b | https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/index.js#L91-L111 |
54,859 | hitchyjs/odem | index.js | mergeComputeds | function mergeComputeds( target, source ) {
const propNames = Object.keys( source );
for ( let i = 0, numNames = propNames.length; i < numNames; i++ ) {
const name = propNames[i];
const computer = source[name];
switch ( typeof computer ) {
case "function" :
break;
default :
throw new TypeError( `invalid definition of computed attribute named "${name}": must be a function` );
}
target[name] = computer;
}
} | javascript | function mergeComputeds( target, source ) {
const propNames = Object.keys( source );
for ( let i = 0, numNames = propNames.length; i < numNames; i++ ) {
const name = propNames[i];
const computer = source[name];
switch ( typeof computer ) {
case "function" :
break;
default :
throw new TypeError( `invalid definition of computed attribute named "${name}": must be a function` );
}
target[name] = computer;
}
} | [
"function",
"mergeComputeds",
"(",
"target",
",",
"source",
")",
"{",
"const",
"propNames",
"=",
"Object",
".",
"keys",
"(",
"source",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"numNames",
"=",
"propNames",
".",
"length",
";",
"i",
"<",
"numNames",
";",
"i",
"++",
")",
"{",
"const",
"name",
"=",
"propNames",
"[",
"i",
"]",
";",
"const",
"computer",
"=",
"source",
"[",
"name",
"]",
";",
"switch",
"(",
"typeof",
"computer",
")",
"{",
"case",
"\"function\"",
":",
"break",
";",
"default",
":",
"throw",
"new",
"TypeError",
"(",
"`",
"${",
"name",
"}",
"`",
")",
";",
"}",
"target",
"[",
"name",
"]",
"=",
"computer",
";",
"}",
"}"
] | Merges separately defined map of computed attributes into single schema
matching expectations of hitchy-odem.
@param {object} target resulting schema for use with hitchy-odem
@param {object<string,function>} source maps names of computed attributes into the related computing function
@returns {void} | [
"Merges",
"separately",
"defined",
"map",
"of",
"computed",
"attributes",
"into",
"single",
"schema",
"matching",
"expectations",
"of",
"hitchy",
"-",
"odem",
"."
] | 28f3dc31cc3314f9109d2cac1f5f7e20dad6521b | https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/index.js#L121-L138 |
54,860 | hitchyjs/odem | index.js | mergeHooks | function mergeHooks( target, source ) {
const propNames = Object.keys( source );
for ( let i = 0, numNames = propNames.length; i < numNames; i++ ) {
const name = propNames[i];
let hook = source[name];
if ( typeof hook === "function" ) {
hook = [hook];
}
if ( !Array.isArray( hook ) ) {
throw new TypeError( `invalid definition of hook named "${name}": must be a function or list of functions` );
}
for ( let hi = 0, numHooks = hook.length; hi < numHooks; hi++ ) {
if ( typeof hook[hi] !== "function" ) {
throw new TypeError( `invalid definition of hook named "${name}": not a function at index #${hi}` );
}
}
target[name] = hook;
}
} | javascript | function mergeHooks( target, source ) {
const propNames = Object.keys( source );
for ( let i = 0, numNames = propNames.length; i < numNames; i++ ) {
const name = propNames[i];
let hook = source[name];
if ( typeof hook === "function" ) {
hook = [hook];
}
if ( !Array.isArray( hook ) ) {
throw new TypeError( `invalid definition of hook named "${name}": must be a function or list of functions` );
}
for ( let hi = 0, numHooks = hook.length; hi < numHooks; hi++ ) {
if ( typeof hook[hi] !== "function" ) {
throw new TypeError( `invalid definition of hook named "${name}": not a function at index #${hi}` );
}
}
target[name] = hook;
}
} | [
"function",
"mergeHooks",
"(",
"target",
",",
"source",
")",
"{",
"const",
"propNames",
"=",
"Object",
".",
"keys",
"(",
"source",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"numNames",
"=",
"propNames",
".",
"length",
";",
"i",
"<",
"numNames",
";",
"i",
"++",
")",
"{",
"const",
"name",
"=",
"propNames",
"[",
"i",
"]",
";",
"let",
"hook",
"=",
"source",
"[",
"name",
"]",
";",
"if",
"(",
"typeof",
"hook",
"===",
"\"function\"",
")",
"{",
"hook",
"=",
"[",
"hook",
"]",
";",
"}",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"hook",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"`",
"${",
"name",
"}",
"`",
")",
";",
"}",
"for",
"(",
"let",
"hi",
"=",
"0",
",",
"numHooks",
"=",
"hook",
".",
"length",
";",
"hi",
"<",
"numHooks",
";",
"hi",
"++",
")",
"{",
"if",
"(",
"typeof",
"hook",
"[",
"hi",
"]",
"!==",
"\"function\"",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"`",
"${",
"name",
"}",
"${",
"hi",
"}",
"`",
")",
";",
"}",
"}",
"target",
"[",
"name",
"]",
"=",
"hook",
";",
"}",
"}"
] | Merges separately defined map of lifecycle hooks into single schema matching
expectations of hitchy-odem.
@param {object} target resulting schema for use with hitchy-odem
@param {object<string,(function|function[])>} source maps names of lifecycle hooks into the related callback or list of callbacks
@returns {void} | [
"Merges",
"separately",
"defined",
"map",
"of",
"lifecycle",
"hooks",
"into",
"single",
"schema",
"matching",
"expectations",
"of",
"hitchy",
"-",
"odem",
"."
] | 28f3dc31cc3314f9109d2cac1f5f7e20dad6521b | https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/index.js#L148-L171 |
54,861 | limin/byteof | index.js | byteof | function byteof(object){
const objects = [object]
let bytes = 0;
for (let index = 0; index < objects.length; index ++){
const object=objects[index]
switch (typeof object){
case 'boolean':
bytes += BYTES.BOOLEAN
break
case 'number':
bytes += BYTES.NUMBER
break
case 'string':
bytes += BYTES.CHAR * object.length
break
case 'object':
//ignore the key's memory usage
for (let key in object){
let processed = false
for (let search = 0; search < objects.length; search ++){
if (objects[search] === object[key]){
processed = true
break
}
}
if (!processed) {
objects.push(object[key])
}
}
}
}
return bytes
} | javascript | function byteof(object){
const objects = [object]
let bytes = 0;
for (let index = 0; index < objects.length; index ++){
const object=objects[index]
switch (typeof object){
case 'boolean':
bytes += BYTES.BOOLEAN
break
case 'number':
bytes += BYTES.NUMBER
break
case 'string':
bytes += BYTES.CHAR * object.length
break
case 'object':
//ignore the key's memory usage
for (let key in object){
let processed = false
for (let search = 0; search < objects.length; search ++){
if (objects[search] === object[key]){
processed = true
break
}
}
if (!processed) {
objects.push(object[key])
}
}
}
}
return bytes
} | [
"function",
"byteof",
"(",
"object",
")",
"{",
"const",
"objects",
"=",
"[",
"object",
"]",
"let",
"bytes",
"=",
"0",
";",
"for",
"(",
"let",
"index",
"=",
"0",
";",
"index",
"<",
"objects",
".",
"length",
";",
"index",
"++",
")",
"{",
"const",
"object",
"=",
"objects",
"[",
"index",
"]",
"switch",
"(",
"typeof",
"object",
")",
"{",
"case",
"'boolean'",
":",
"bytes",
"+=",
"BYTES",
".",
"BOOLEAN",
"break",
"case",
"'number'",
":",
"bytes",
"+=",
"BYTES",
".",
"NUMBER",
"break",
"case",
"'string'",
":",
"bytes",
"+=",
"BYTES",
".",
"CHAR",
"*",
"object",
".",
"length",
"break",
"case",
"'object'",
":",
"//ignore the key's memory usage\r",
"for",
"(",
"let",
"key",
"in",
"object",
")",
"{",
"let",
"processed",
"=",
"false",
"for",
"(",
"let",
"search",
"=",
"0",
";",
"search",
"<",
"objects",
".",
"length",
";",
"search",
"++",
")",
"{",
"if",
"(",
"objects",
"[",
"search",
"]",
"===",
"object",
"[",
"key",
"]",
")",
"{",
"processed",
"=",
"true",
"break",
"}",
"}",
"if",
"(",
"!",
"processed",
")",
"{",
"objects",
".",
"push",
"(",
"object",
"[",
"key",
"]",
")",
"}",
"}",
"}",
"}",
"return",
"bytes",
"}"
] | Calculate the approximate memory usage of javascript object in bytes.
@param {*} object - The object to be calcuated memory usage in bytes
@returns {number} The memory usage in bytes
@example
// returns 8
byteof(2)
// returns 8
byteof(2.0)
// return 4
byteof(false)
// return 2*3=6
byteof("abc")
// return 32
const object={
"n":1,
"b":true,
"s":"1234567890"
};
byteof(object) | [
"Calculate",
"the",
"approximate",
"memory",
"usage",
"of",
"javascript",
"object",
"in",
"bytes",
"."
] | 3a6416da9e970723799bf547da6132105a73fab0 | https://github.com/limin/byteof/blob/3a6416da9e970723799bf547da6132105a73fab0/index.js#L42-L74 |
54,862 | colthreepv/promesso | index.js | promesso | function promesso (handler) {
const handleFn = isFunction(handler) ? [handler] : handler;
const middlewares = [];
let validations = 0;
handleFn.forEach(h => {
if (!isFunction(h)) throw new Error('Handler is expected to be a function or an Array of functions.');
if (isObject(handleFn['@validation'])) {
middlewares.push(validation(h['@validation']), validationMiddleware);
if (++validations > 1) throw new Error('Every handler can have only one validator per chain.');
}
middlewares.push(h);
});
return middlewares.map(rawOrPromise);
} | javascript | function promesso (handler) {
const handleFn = isFunction(handler) ? [handler] : handler;
const middlewares = [];
let validations = 0;
handleFn.forEach(h => {
if (!isFunction(h)) throw new Error('Handler is expected to be a function or an Array of functions.');
if (isObject(handleFn['@validation'])) {
middlewares.push(validation(h['@validation']), validationMiddleware);
if (++validations > 1) throw new Error('Every handler can have only one validator per chain.');
}
middlewares.push(h);
});
return middlewares.map(rawOrPromise);
} | [
"function",
"promesso",
"(",
"handler",
")",
"{",
"const",
"handleFn",
"=",
"isFunction",
"(",
"handler",
")",
"?",
"[",
"handler",
"]",
":",
"handler",
";",
"const",
"middlewares",
"=",
"[",
"]",
";",
"let",
"validations",
"=",
"0",
";",
"handleFn",
".",
"forEach",
"(",
"h",
"=>",
"{",
"if",
"(",
"!",
"isFunction",
"(",
"h",
")",
")",
"throw",
"new",
"Error",
"(",
"'Handler is expected to be a function or an Array of functions.'",
")",
";",
"if",
"(",
"isObject",
"(",
"handleFn",
"[",
"'@validation'",
"]",
")",
")",
"{",
"middlewares",
".",
"push",
"(",
"validation",
"(",
"h",
"[",
"'@validation'",
"]",
")",
",",
"validationMiddleware",
")",
";",
"if",
"(",
"++",
"validations",
">",
"1",
")",
"throw",
"new",
"Error",
"(",
"'Every handler can have only one validator per chain.'",
")",
";",
"}",
"middlewares",
".",
"push",
"(",
"h",
")",
";",
"}",
")",
";",
"return",
"middlewares",
".",
"map",
"(",
"rawOrPromise",
")",
";",
"}"
] | promesso takes a Promise-based middleware function and converts it to a classic array of middlewares
@param {Function|Function[]} handler: Promise-based Express middleware
@return {Function[]} Express-compliant Array of middlewares | [
"promesso",
"takes",
"a",
"Promise",
"-",
"based",
"middleware",
"function",
"and",
"converts",
"it",
"to",
"a",
"classic",
"array",
"of",
"middlewares"
] | 4076df7df42778484b1d000d1c5d4d4c01873fa6 | https://github.com/colthreepv/promesso/blob/4076df7df42778484b1d000d1c5d4d4c01873fa6/index.js#L33-L50 |
54,863 | colthreepv/promesso | index.js | validationMiddleware | function validationMiddleware (err, req, res, next) {
if (!err instanceof ValidationError) return next(err);
return res.status(err.status).send({ errors: err.errors });
} | javascript | function validationMiddleware (err, req, res, next) {
if (!err instanceof ValidationError) return next(err);
return res.status(err.status).send({ errors: err.errors });
} | [
"function",
"validationMiddleware",
"(",
"err",
",",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"!",
"err",
"instanceof",
"ValidationError",
")",
"return",
"next",
"(",
"err",
")",
";",
"return",
"res",
".",
"status",
"(",
"err",
".",
"status",
")",
".",
"send",
"(",
"{",
"errors",
":",
"err",
".",
"errors",
"}",
")",
";",
"}"
] | Handles thrown errors from express-validation | [
"Handles",
"thrown",
"errors",
"from",
"express",
"-",
"validation"
] | 4076df7df42778484b1d000d1c5d4d4c01873fa6 | https://github.com/colthreepv/promesso/blob/4076df7df42778484b1d000d1c5d4d4c01873fa6/index.js#L115-L118 |
54,864 | wilmoore/sum.js | index.js | sum | function sum(list, fun) {
fun = toString.call(fun) == '[object String]' ? selectn(fun) : fun;
end = list.length;
sum = -0;
idx = -1;
while (++idx < end) {
sum += typeof fun == 'function' ? fun(list[idx]) * 1000 : list[idx] * 1000;
}
return sum && (sum / 1000);
} | javascript | function sum(list, fun) {
fun = toString.call(fun) == '[object String]' ? selectn(fun) : fun;
end = list.length;
sum = -0;
idx = -1;
while (++idx < end) {
sum += typeof fun == 'function' ? fun(list[idx]) * 1000 : list[idx] * 1000;
}
return sum && (sum / 1000);
} | [
"function",
"sum",
"(",
"list",
",",
"fun",
")",
"{",
"fun",
"=",
"toString",
".",
"call",
"(",
"fun",
")",
"==",
"'[object String]'",
"?",
"selectn",
"(",
"fun",
")",
":",
"fun",
";",
"end",
"=",
"list",
".",
"length",
";",
"sum",
"=",
"-",
"0",
";",
"idx",
"=",
"-",
"1",
";",
"while",
"(",
"++",
"idx",
"<",
"end",
")",
"{",
"sum",
"+=",
"typeof",
"fun",
"==",
"'function'",
"?",
"fun",
"(",
"list",
"[",
"idx",
"]",
")",
"*",
"1000",
":",
"list",
"[",
"idx",
"]",
"*",
"1000",
";",
"}",
"return",
"sum",
"&&",
"(",
"sum",
"/",
"1000",
")",
";",
"}"
] | Returns the sum of a list supporting number literals, nested objects, or transformation function.
#### Number literals
sum([1, 2, 3, 4])
//=> 10
#### Nested object properties
var strings = [ 'literal', 'constructor' ];
sum(strings, 'length');
//=> 18
#### Custom function
sum([1, 2, 3, 4], function (n) { n * 60 });
//=> 600
@param {Array} list
list of numbers or list that will contain numbers after transforming.
@param {Function|String} [fun]
function which is given the current item and returns a number to be included in sum
or dot notation object property string (i.e. `length`).
@return {Array}
sum of list | [
"Returns",
"the",
"sum",
"of",
"a",
"list",
"supporting",
"number",
"literals",
"nested",
"objects",
"or",
"transformation",
"function",
"."
] | 23630999bf8b2c4d33bb6acef6387f8597ad3a85 | https://github.com/wilmoore/sum.js/blob/23630999bf8b2c4d33bb6acef6387f8597ad3a85/index.js#L37-L48 |
54,865 | jrgns/node_stream_handler | node_stream_handler.js | StreamHandler | function StreamHandler(host, port, delimiter) {
events.EventEmitter.call(this);
var self = this;
self.delimiter = delimiter || "\r\n";
self.host = host;
self.port = port;
self.buffer = '';
self.conn = net.createConnection(self.port, self.host);
self.conn.setEncoding("utf8");
self.conn.on('error', function(err) {
try {
self.emit('error', 'Stream error: ' + err, err);
} catch (e) {
console.log('' + err);
}
});
self.conn.on('data', function(data) {
self.conn.pause();
self.buffer += data;
if (self.buffer.match(/\n/)) {
var arr = self.buffer.split(self.delimiter);
//Everything except the last one
for(var i = 0; i < arr.length - 1; i++) {
self.emit('line', arr[i]);
}
self.buffer = arr[arr.length - 1];
}
if (self.conn.readyState == 'open') {
self.conn.resume();
}
});
self.conn.on('close', function(had_error) {
if (!had_error && self.buffer.length > 0) {
self.emit('line', self.buffer);
}
});
} | javascript | function StreamHandler(host, port, delimiter) {
events.EventEmitter.call(this);
var self = this;
self.delimiter = delimiter || "\r\n";
self.host = host;
self.port = port;
self.buffer = '';
self.conn = net.createConnection(self.port, self.host);
self.conn.setEncoding("utf8");
self.conn.on('error', function(err) {
try {
self.emit('error', 'Stream error: ' + err, err);
} catch (e) {
console.log('' + err);
}
});
self.conn.on('data', function(data) {
self.conn.pause();
self.buffer += data;
if (self.buffer.match(/\n/)) {
var arr = self.buffer.split(self.delimiter);
//Everything except the last one
for(var i = 0; i < arr.length - 1; i++) {
self.emit('line', arr[i]);
}
self.buffer = arr[arr.length - 1];
}
if (self.conn.readyState == 'open') {
self.conn.resume();
}
});
self.conn.on('close', function(had_error) {
if (!had_error && self.buffer.length > 0) {
self.emit('line', self.buffer);
}
});
} | [
"function",
"StreamHandler",
"(",
"host",
",",
"port",
",",
"delimiter",
")",
"{",
"events",
".",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"var",
"self",
"=",
"this",
";",
"self",
".",
"delimiter",
"=",
"delimiter",
"||",
"\"\\r\\n\"",
";",
"self",
".",
"host",
"=",
"host",
";",
"self",
".",
"port",
"=",
"port",
";",
"self",
".",
"buffer",
"=",
"''",
";",
"self",
".",
"conn",
"=",
"net",
".",
"createConnection",
"(",
"self",
".",
"port",
",",
"self",
".",
"host",
")",
";",
"self",
".",
"conn",
".",
"setEncoding",
"(",
"\"utf8\"",
")",
";",
"self",
".",
"conn",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"try",
"{",
"self",
".",
"emit",
"(",
"'error'",
",",
"'Stream error: '",
"+",
"err",
",",
"err",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"''",
"+",
"err",
")",
";",
"}",
"}",
")",
";",
"self",
".",
"conn",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"self",
".",
"conn",
".",
"pause",
"(",
")",
";",
"self",
".",
"buffer",
"+=",
"data",
";",
"if",
"(",
"self",
".",
"buffer",
".",
"match",
"(",
"/",
"\\n",
"/",
")",
")",
"{",
"var",
"arr",
"=",
"self",
".",
"buffer",
".",
"split",
"(",
"self",
".",
"delimiter",
")",
";",
"//Everything except the last one",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
"-",
"1",
";",
"i",
"++",
")",
"{",
"self",
".",
"emit",
"(",
"'line'",
",",
"arr",
"[",
"i",
"]",
")",
";",
"}",
"self",
".",
"buffer",
"=",
"arr",
"[",
"arr",
".",
"length",
"-",
"1",
"]",
";",
"}",
"if",
"(",
"self",
".",
"conn",
".",
"readyState",
"==",
"'open'",
")",
"{",
"self",
".",
"conn",
".",
"resume",
"(",
")",
";",
"}",
"}",
")",
";",
"self",
".",
"conn",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
"had_error",
")",
"{",
"if",
"(",
"!",
"had_error",
"&&",
"self",
".",
"buffer",
".",
"length",
">",
"0",
")",
"{",
"self",
".",
"emit",
"(",
"'line'",
",",
"self",
".",
"buffer",
")",
";",
"}",
"}",
")",
";",
"}"
] | Consume data until you get a new line, emit a line event, clean buffer, rinse, repeat | [
"Consume",
"data",
"until",
"you",
"get",
"a",
"new",
"line",
"emit",
"a",
"line",
"event",
"clean",
"buffer",
"rinse",
"repeat"
] | 3962e6ee1fcf46bc71231ab606627eccd06ebff5 | https://github.com/jrgns/node_stream_handler/blob/3962e6ee1fcf46bc71231ab606627eccd06ebff5/node_stream_handler.js#L11-L51 |
54,866 | tanepiper/nell | lib/generate/load_items.js | function(file, file_done) {
var item = {};
item.file_path = path.join(nell_site[type_path_key], file);
item.file_output = generateOutputDetails(nell_site, file, type);
item.link = item.file_output.link_path;
var processContent = concat(function(err, file_content_raw) {
if (err) {
return file_done(err);
}
item.file_content_raw = file_content_raw;
item.file_metadata = mde.metadata(item.file_content_raw);
item.file_content = mde.content(item.file_content_raw);
async.series([
function(callback) {
processMarkdown(nell_site, item, callback);
},
function(callback) {
nell_site[type_plural].push(item);
callback();
}
], file_done);
});
var fh = fs.createReadStream(item.file_path, {encoding: 'utf8'});
fh.on('error', file_done);
fh.pipe(processContent);
} | javascript | function(file, file_done) {
var item = {};
item.file_path = path.join(nell_site[type_path_key], file);
item.file_output = generateOutputDetails(nell_site, file, type);
item.link = item.file_output.link_path;
var processContent = concat(function(err, file_content_raw) {
if (err) {
return file_done(err);
}
item.file_content_raw = file_content_raw;
item.file_metadata = mde.metadata(item.file_content_raw);
item.file_content = mde.content(item.file_content_raw);
async.series([
function(callback) {
processMarkdown(nell_site, item, callback);
},
function(callback) {
nell_site[type_plural].push(item);
callback();
}
], file_done);
});
var fh = fs.createReadStream(item.file_path, {encoding: 'utf8'});
fh.on('error', file_done);
fh.pipe(processContent);
} | [
"function",
"(",
"file",
",",
"file_done",
")",
"{",
"var",
"item",
"=",
"{",
"}",
";",
"item",
".",
"file_path",
"=",
"path",
".",
"join",
"(",
"nell_site",
"[",
"type_path_key",
"]",
",",
"file",
")",
";",
"item",
".",
"file_output",
"=",
"generateOutputDetails",
"(",
"nell_site",
",",
"file",
",",
"type",
")",
";",
"item",
".",
"link",
"=",
"item",
".",
"file_output",
".",
"link_path",
";",
"var",
"processContent",
"=",
"concat",
"(",
"function",
"(",
"err",
",",
"file_content_raw",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"file_done",
"(",
"err",
")",
";",
"}",
"item",
".",
"file_content_raw",
"=",
"file_content_raw",
";",
"item",
".",
"file_metadata",
"=",
"mde",
".",
"metadata",
"(",
"item",
".",
"file_content_raw",
")",
";",
"item",
".",
"file_content",
"=",
"mde",
".",
"content",
"(",
"item",
".",
"file_content_raw",
")",
";",
"async",
".",
"series",
"(",
"[",
"function",
"(",
"callback",
")",
"{",
"processMarkdown",
"(",
"nell_site",
",",
"item",
",",
"callback",
")",
";",
"}",
",",
"function",
"(",
"callback",
")",
"{",
"nell_site",
"[",
"type_plural",
"]",
".",
"push",
"(",
"item",
")",
";",
"callback",
"(",
")",
";",
"}",
"]",
",",
"file_done",
")",
";",
"}",
")",
";",
"var",
"fh",
"=",
"fs",
".",
"createReadStream",
"(",
"item",
".",
"file_path",
",",
"{",
"encoding",
":",
"'utf8'",
"}",
")",
";",
"fh",
".",
"on",
"(",
"'error'",
",",
"file_done",
")",
";",
"fh",
".",
"pipe",
"(",
"processContent",
")",
";",
"}"
] | Function to process each item | [
"Function",
"to",
"process",
"each",
"item"
] | ecceaf63e8d685e08081e2d5f5fb85e71b17a037 | https://github.com/tanepiper/nell/blob/ecceaf63e8d685e08081e2d5f5fb85e71b17a037/lib/generate/load_items.js#L32-L60 |
|
54,867 | AlphaReplica/Connecta | lib/client/source/connectaSocket.js | connect | function connect()
{
if(scope._conn)
{
if(scope._conn.readyState === 1)
{
return;
}
scope._conn.close();
}
var url = (scope._redirectURL.length>0) ? scope._redirectURL : scope._url;
scope._conn = new WebSocket(url);
scope._conn.binaryType = "arraybuffer";
scope._conn.open = onOpen;
scope._conn.onerror = onerror;
scope._conn.onclose = onClose;
scope._conn.onmessage = onMessage;
} | javascript | function connect()
{
if(scope._conn)
{
if(scope._conn.readyState === 1)
{
return;
}
scope._conn.close();
}
var url = (scope._redirectURL.length>0) ? scope._redirectURL : scope._url;
scope._conn = new WebSocket(url);
scope._conn.binaryType = "arraybuffer";
scope._conn.open = onOpen;
scope._conn.onerror = onerror;
scope._conn.onclose = onClose;
scope._conn.onmessage = onMessage;
} | [
"function",
"connect",
"(",
")",
"{",
"if",
"(",
"scope",
".",
"_conn",
")",
"{",
"if",
"(",
"scope",
".",
"_conn",
".",
"readyState",
"===",
"1",
")",
"{",
"return",
";",
"}",
"scope",
".",
"_conn",
".",
"close",
"(",
")",
";",
"}",
"var",
"url",
"=",
"(",
"scope",
".",
"_redirectURL",
".",
"length",
">",
"0",
")",
"?",
"scope",
".",
"_redirectURL",
":",
"scope",
".",
"_url",
";",
"scope",
".",
"_conn",
"=",
"new",
"WebSocket",
"(",
"url",
")",
";",
"scope",
".",
"_conn",
".",
"binaryType",
"=",
"\"arraybuffer\"",
";",
"scope",
".",
"_conn",
".",
"open",
"=",
"onOpen",
";",
"scope",
".",
"_conn",
".",
"onerror",
"=",
"onerror",
";",
"scope",
".",
"_conn",
".",
"onclose",
"=",
"onClose",
";",
"scope",
".",
"_conn",
".",
"onmessage",
"=",
"onMessage",
";",
"}"
] | connects to server | [
"connects",
"to",
"server"
] | bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0 | https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connectaSocket.js#L31-L49 |
54,868 | AlphaReplica/Connecta | lib/client/source/connectaSocket.js | onArrayBuffer | function onArrayBuffer(data)
{
var arr = bufferToArray(scope.byteType,data);
if(arr)
{
if(arr[arr.length-1] == MessageType.RTC_FAIL && scope.rtcFallback == true && scope.useRTC == true)
{
if(scope.onRTCFallback)
{
scope.onRTCFallback(arr[arr.length-2],arr,true);
}
}
else
{
if(scope.onBytesMessage)
{
scope.onBytesMessage(arr);
}
}
}
} | javascript | function onArrayBuffer(data)
{
var arr = bufferToArray(scope.byteType,data);
if(arr)
{
if(arr[arr.length-1] == MessageType.RTC_FAIL && scope.rtcFallback == true && scope.useRTC == true)
{
if(scope.onRTCFallback)
{
scope.onRTCFallback(arr[arr.length-2],arr,true);
}
}
else
{
if(scope.onBytesMessage)
{
scope.onBytesMessage(arr);
}
}
}
} | [
"function",
"onArrayBuffer",
"(",
"data",
")",
"{",
"var",
"arr",
"=",
"bufferToArray",
"(",
"scope",
".",
"byteType",
",",
"data",
")",
";",
"if",
"(",
"arr",
")",
"{",
"if",
"(",
"arr",
"[",
"arr",
".",
"length",
"-",
"1",
"]",
"==",
"MessageType",
".",
"RTC_FAIL",
"&&",
"scope",
".",
"rtcFallback",
"==",
"true",
"&&",
"scope",
".",
"useRTC",
"==",
"true",
")",
"{",
"if",
"(",
"scope",
".",
"onRTCFallback",
")",
"{",
"scope",
".",
"onRTCFallback",
"(",
"arr",
"[",
"arr",
".",
"length",
"-",
"2",
"]",
",",
"arr",
",",
"true",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"scope",
".",
"onBytesMessage",
")",
"{",
"scope",
".",
"onBytesMessage",
"(",
"arr",
")",
";",
"}",
"}",
"}",
"}"
] | server message callback for bytebuffer message | [
"server",
"message",
"callback",
"for",
"bytebuffer",
"message"
] | bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0 | https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connectaSocket.js#L95-L116 |
54,869 | AlphaReplica/Connecta | lib/client/source/connectaSocket.js | changeServer | function changeServer(url)
{
scope._redirectURL = url;
if(scope._conn)
{
scope._conn.onopen = null;
scope._conn.onerror = null;
scope._conn.onclose = null;
scope._conn.onmessage = null;
scope._conn.close();
}
connect();
} | javascript | function changeServer(url)
{
scope._redirectURL = url;
if(scope._conn)
{
scope._conn.onopen = null;
scope._conn.onerror = null;
scope._conn.onclose = null;
scope._conn.onmessage = null;
scope._conn.close();
}
connect();
} | [
"function",
"changeServer",
"(",
"url",
")",
"{",
"scope",
".",
"_redirectURL",
"=",
"url",
";",
"if",
"(",
"scope",
".",
"_conn",
")",
"{",
"scope",
".",
"_conn",
".",
"onopen",
"=",
"null",
";",
"scope",
".",
"_conn",
".",
"onerror",
"=",
"null",
";",
"scope",
".",
"_conn",
".",
"onclose",
"=",
"null",
";",
"scope",
".",
"_conn",
".",
"onmessage",
"=",
"null",
";",
"scope",
".",
"_conn",
".",
"close",
"(",
")",
";",
"}",
"connect",
"(",
")",
";",
"}"
] | switches server by given url | [
"switches",
"server",
"by",
"given",
"url"
] | bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0 | https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connectaSocket.js#L286-L298 |
54,870 | airicyu/stateful-result | src/models/exception.js | Exception | function Exception(code, message) {
Error.captureStackTrace(this, Exception);
this.name = Exception.name;
this.code = code;
this.message = message;
} | javascript | function Exception(code, message) {
Error.captureStackTrace(this, Exception);
this.name = Exception.name;
this.code = code;
this.message = message;
} | [
"function",
"Exception",
"(",
"code",
",",
"message",
")",
"{",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"Exception",
")",
";",
"this",
".",
"name",
"=",
"Exception",
".",
"name",
";",
"this",
".",
"code",
"=",
"code",
";",
"this",
".",
"message",
"=",
"message",
";",
"}"
] | Exception object. Extended from Error to support having the error code attribute.
@param {integer} code
@param {string} message | [
"Exception",
"object",
".",
"Extended",
"from",
"Error",
"to",
"support",
"having",
"the",
"error",
"code",
"attribute",
"."
] | d0658294587792476bed618d7489868715f15fcb | https://github.com/airicyu/stateful-result/blob/d0658294587792476bed618d7489868715f15fcb/src/models/exception.js#L13-L18 |
54,871 | intervolga/bem-utils | lib/bem-dirs.js | bemDirs | function bemDirs(bemdeps) {
const dirFilter = {};
bemdeps.forEach((dep) => {
const depPath = bemPath(dep);
const depDir = path.dirname(depPath);
dirFilter[depDir] = true;
});
return Object.keys(dirFilter);
} | javascript | function bemDirs(bemdeps) {
const dirFilter = {};
bemdeps.forEach((dep) => {
const depPath = bemPath(dep);
const depDir = path.dirname(depPath);
dirFilter[depDir] = true;
});
return Object.keys(dirFilter);
} | [
"function",
"bemDirs",
"(",
"bemdeps",
")",
"{",
"const",
"dirFilter",
"=",
"{",
"}",
";",
"bemdeps",
".",
"forEach",
"(",
"(",
"dep",
")",
"=>",
"{",
"const",
"depPath",
"=",
"bemPath",
"(",
"dep",
")",
";",
"const",
"depDir",
"=",
"path",
".",
"dirname",
"(",
"depPath",
")",
";",
"dirFilter",
"[",
"depDir",
"]",
"=",
"true",
";",
"}",
")",
";",
"return",
"Object",
".",
"keys",
"(",
"dirFilter",
")",
";",
"}"
] | Convert BemDeps to directory names
@param {Array} bemdeps
@return {Array} | [
"Convert",
"BemDeps",
"to",
"directory",
"names"
] | 3b81bb9bc408275486175326dc7f35c563a46563 | https://github.com/intervolga/bem-utils/blob/3b81bb9bc408275486175326dc7f35c563a46563/lib/bem-dirs.js#L10-L19 |
54,872 | skylarkutils/skylark-utils | dist/uncompressed/skylark-utils/models.js | function(options) {
options = langx.mixin({parse: true}, options);
var entity = this;
var success = options.success;
options.success = function(resp) {
var serverAttrs = options.parse ? entity.parse(resp, options) : resp;
if (!entity.set(serverAttrs, options)) return false;
if (success) success.call(options.context, entity, resp, options);
entity.trigger('sync', entity, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
} | javascript | function(options) {
options = langx.mixin({parse: true}, options);
var entity = this;
var success = options.success;
options.success = function(resp) {
var serverAttrs = options.parse ? entity.parse(resp, options) : resp;
if (!entity.set(serverAttrs, options)) return false;
if (success) success.call(options.context, entity, resp, options);
entity.trigger('sync', entity, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
} | [
"function",
"(",
"options",
")",
"{",
"options",
"=",
"langx",
".",
"mixin",
"(",
"{",
"parse",
":",
"true",
"}",
",",
"options",
")",
";",
"var",
"entity",
"=",
"this",
";",
"var",
"success",
"=",
"options",
".",
"success",
";",
"options",
".",
"success",
"=",
"function",
"(",
"resp",
")",
"{",
"var",
"serverAttrs",
"=",
"options",
".",
"parse",
"?",
"entity",
".",
"parse",
"(",
"resp",
",",
"options",
")",
":",
"resp",
";",
"if",
"(",
"!",
"entity",
".",
"set",
"(",
"serverAttrs",
",",
"options",
")",
")",
"return",
"false",
";",
"if",
"(",
"success",
")",
"success",
".",
"call",
"(",
"options",
".",
"context",
",",
"entity",
",",
"resp",
",",
"options",
")",
";",
"entity",
".",
"trigger",
"(",
"'sync'",
",",
"entity",
",",
"resp",
",",
"options",
")",
";",
"}",
";",
"wrapError",
"(",
"this",
",",
"options",
")",
";",
"return",
"this",
".",
"sync",
"(",
"'read'",
",",
"this",
",",
"options",
")",
";",
"}"
] | Fetch the entity from the server, merging the response with the entity's local attributes. Any changed attributes will trigger a "change" event. | [
"Fetch",
"the",
"entity",
"from",
"the",
"server",
"merging",
"the",
"response",
"with",
"the",
"entity",
"s",
"local",
"attributes",
".",
"Any",
"changed",
"attributes",
"will",
"trigger",
"a",
"change",
"event",
"."
] | ef082bb53b162b4a2c6992ef07a3e32553f6aed5 | https://github.com/skylarkutils/skylark-utils/blob/ef082bb53b162b4a2c6992ef07a3e32553f6aed5/dist/uncompressed/skylark-utils/models.js#L94-L106 |
|
54,873 | skylarkutils/skylark-utils | dist/uncompressed/skylark-utils/models.js | function(entities, options) {
return this.set(entities, langx.mixin({merge: false}, options, addOptions));
} | javascript | function(entities, options) {
return this.set(entities, langx.mixin({merge: false}, options, addOptions));
} | [
"function",
"(",
"entities",
",",
"options",
")",
"{",
"return",
"this",
".",
"set",
"(",
"entities",
",",
"langx",
".",
"mixin",
"(",
"{",
"merge",
":",
"false",
"}",
",",
"options",
",",
"addOptions",
")",
")",
";",
"}"
] | Add a entity, or list of entities to the set. `entities` may be Backbone Entitys or raw JavaScript objects to be converted to Entitys, or any combination of the two. | [
"Add",
"a",
"entity",
"or",
"list",
"of",
"entities",
"to",
"the",
"set",
".",
"entities",
"may",
"be",
"Backbone",
"Entitys",
"or",
"raw",
"JavaScript",
"objects",
"to",
"be",
"converted",
"to",
"Entitys",
"or",
"any",
"combination",
"of",
"the",
"two",
"."
] | ef082bb53b162b4a2c6992ef07a3e32553f6aed5 | https://github.com/skylarkutils/skylark-utils/blob/ef082bb53b162b4a2c6992ef07a3e32553f6aed5/dist/uncompressed/skylark-utils/models.js#L263-L265 |
|
54,874 | skylarkutils/skylark-utils | dist/uncompressed/skylark-utils/models.js | function(entities, options) {
options = langx.mixin({}, options);
var singular = !langx.isArray(entities);
entities = singular ? [entities] : entities.slice();
var removed = this._removeEntitys(entities, options);
if (!options.silent && removed.length) {
options.changes = {added: [], merged: [], removed: removed};
this.trigger('update', this, options);
}
return singular ? removed[0] : removed;
} | javascript | function(entities, options) {
options = langx.mixin({}, options);
var singular = !langx.isArray(entities);
entities = singular ? [entities] : entities.slice();
var removed = this._removeEntitys(entities, options);
if (!options.silent && removed.length) {
options.changes = {added: [], merged: [], removed: removed};
this.trigger('update', this, options);
}
return singular ? removed[0] : removed;
} | [
"function",
"(",
"entities",
",",
"options",
")",
"{",
"options",
"=",
"langx",
".",
"mixin",
"(",
"{",
"}",
",",
"options",
")",
";",
"var",
"singular",
"=",
"!",
"langx",
".",
"isArray",
"(",
"entities",
")",
";",
"entities",
"=",
"singular",
"?",
"[",
"entities",
"]",
":",
"entities",
".",
"slice",
"(",
")",
";",
"var",
"removed",
"=",
"this",
".",
"_removeEntitys",
"(",
"entities",
",",
"options",
")",
";",
"if",
"(",
"!",
"options",
".",
"silent",
"&&",
"removed",
".",
"length",
")",
"{",
"options",
".",
"changes",
"=",
"{",
"added",
":",
"[",
"]",
",",
"merged",
":",
"[",
"]",
",",
"removed",
":",
"removed",
"}",
";",
"this",
".",
"trigger",
"(",
"'update'",
",",
"this",
",",
"options",
")",
";",
"}",
"return",
"singular",
"?",
"removed",
"[",
"0",
"]",
":",
"removed",
";",
"}"
] | Remove a entity, or a list of entities from the set. | [
"Remove",
"a",
"entity",
"or",
"a",
"list",
"of",
"entities",
"from",
"the",
"set",
"."
] | ef082bb53b162b4a2c6992ef07a3e32553f6aed5 | https://github.com/skylarkutils/skylark-utils/blob/ef082bb53b162b4a2c6992ef07a3e32553f6aed5/dist/uncompressed/skylark-utils/models.js#L268-L278 |
|
54,875 | skylarkutils/skylark-utils | dist/uncompressed/skylark-utils/models.js | function(entities, options) {
options = options ? langx.clone(options) : {};
for (var i = 0; i < this.entities.length; i++) {
this._removeReference(this.entities[i], options);
}
options.previousEntitys = this.entities;
this._reset();
entities = this.add(entities, langx.mixin({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return entities;
} | javascript | function(entities, options) {
options = options ? langx.clone(options) : {};
for (var i = 0; i < this.entities.length; i++) {
this._removeReference(this.entities[i], options);
}
options.previousEntitys = this.entities;
this._reset();
entities = this.add(entities, langx.mixin({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return entities;
} | [
"function",
"(",
"entities",
",",
"options",
")",
"{",
"options",
"=",
"options",
"?",
"langx",
".",
"clone",
"(",
"options",
")",
":",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"entities",
".",
"length",
";",
"i",
"++",
")",
"{",
"this",
".",
"_removeReference",
"(",
"this",
".",
"entities",
"[",
"i",
"]",
",",
"options",
")",
";",
"}",
"options",
".",
"previousEntitys",
"=",
"this",
".",
"entities",
";",
"this",
".",
"_reset",
"(",
")",
";",
"entities",
"=",
"this",
".",
"add",
"(",
"entities",
",",
"langx",
".",
"mixin",
"(",
"{",
"silent",
":",
"true",
"}",
",",
"options",
")",
")",
";",
"if",
"(",
"!",
"options",
".",
"silent",
")",
"this",
".",
"trigger",
"(",
"'reset'",
",",
"this",
",",
"options",
")",
";",
"return",
"entities",
";",
"}"
] | When you have more items than you want to add or remove individually, you can reset the entire set with a new list of entities, without firing any granular `add` or `remove` events. Fires `reset` when finished. Useful for bulk operations and optimizations. | [
"When",
"you",
"have",
"more",
"items",
"than",
"you",
"want",
"to",
"add",
"or",
"remove",
"individually",
"you",
"can",
"reset",
"the",
"entire",
"set",
"with",
"a",
"new",
"list",
"of",
"entities",
"without",
"firing",
"any",
"granular",
"add",
"or",
"remove",
"events",
".",
"Fires",
"reset",
"when",
"finished",
".",
"Useful",
"for",
"bulk",
"operations",
"and",
"optimizations",
"."
] | ef082bb53b162b4a2c6992ef07a3e32553f6aed5 | https://github.com/skylarkutils/skylark-utils/blob/ef082bb53b162b4a2c6992ef07a3e32553f6aed5/dist/uncompressed/skylark-utils/models.js#L403-L413 |
|
54,876 | skylarkutils/skylark-utils | dist/uncompressed/skylark-utils/models.js | function(obj) {
if (obj == null) return void 0;
return this._byId[obj] ||
this._byId[this.entityId(obj.attributes || obj)] ||
obj.cid && this._byId[obj.cid];
} | javascript | function(obj) {
if (obj == null) return void 0;
return this._byId[obj] ||
this._byId[this.entityId(obj.attributes || obj)] ||
obj.cid && this._byId[obj.cid];
} | [
"function",
"(",
"obj",
")",
"{",
"if",
"(",
"obj",
"==",
"null",
")",
"return",
"void",
"0",
";",
"return",
"this",
".",
"_byId",
"[",
"obj",
"]",
"||",
"this",
".",
"_byId",
"[",
"this",
".",
"entityId",
"(",
"obj",
".",
"attributes",
"||",
"obj",
")",
"]",
"||",
"obj",
".",
"cid",
"&&",
"this",
".",
"_byId",
"[",
"obj",
".",
"cid",
"]",
";",
"}"
] | Get a entity from the set by id, cid, entity object with id or cid properties, or an attributes object that is transformed through entityId. | [
"Get",
"a",
"entity",
"from",
"the",
"set",
"by",
"id",
"cid",
"entity",
"object",
"with",
"id",
"or",
"cid",
"properties",
"or",
"an",
"attributes",
"object",
"that",
"is",
"transformed",
"through",
"entityId",
"."
] | ef082bb53b162b4a2c6992ef07a3e32553f6aed5 | https://github.com/skylarkutils/skylark-utils/blob/ef082bb53b162b4a2c6992ef07a3e32553f6aed5/dist/uncompressed/skylark-utils/models.js#L444-L449 |
|
54,877 | skylarkutils/skylark-utils | dist/uncompressed/skylark-utils/models.js | function(entity, options) {
this._byId[entity.cid] = entity;
var id = this.entityId(entity.attributes);
if (id != null) this._byId[id] = entity;
entity.on('all', this._onEntityEvent, this);
} | javascript | function(entity, options) {
this._byId[entity.cid] = entity;
var id = this.entityId(entity.attributes);
if (id != null) this._byId[id] = entity;
entity.on('all', this._onEntityEvent, this);
} | [
"function",
"(",
"entity",
",",
"options",
")",
"{",
"this",
".",
"_byId",
"[",
"entity",
".",
"cid",
"]",
"=",
"entity",
";",
"var",
"id",
"=",
"this",
".",
"entityId",
"(",
"entity",
".",
"attributes",
")",
";",
"if",
"(",
"id",
"!=",
"null",
")",
"this",
".",
"_byId",
"[",
"id",
"]",
"=",
"entity",
";",
"entity",
".",
"on",
"(",
"'all'",
",",
"this",
".",
"_onEntityEvent",
",",
"this",
")",
";",
"}"
] | Internal method to create a entity's ties to a collection. | [
"Internal",
"method",
"to",
"create",
"a",
"entity",
"s",
"ties",
"to",
"a",
"collection",
"."
] | ef082bb53b162b4a2c6992ef07a3e32553f6aed5 | https://github.com/skylarkutils/skylark-utils/blob/ef082bb53b162b4a2c6992ef07a3e32553f6aed5/dist/uncompressed/skylark-utils/models.js#L613-L618 |
|
54,878 | skylarkutils/skylark-utils | dist/uncompressed/skylark-utils/models.js | function(entity, options) {
delete this._byId[entity.cid];
var id = this.entityId(entity.attributes);
if (id != null) delete this._byId[id];
if (this === entity.collection) delete entity.collection;
entity.off('all', this._onEntityEvent, this);
} | javascript | function(entity, options) {
delete this._byId[entity.cid];
var id = this.entityId(entity.attributes);
if (id != null) delete this._byId[id];
if (this === entity.collection) delete entity.collection;
entity.off('all', this._onEntityEvent, this);
} | [
"function",
"(",
"entity",
",",
"options",
")",
"{",
"delete",
"this",
".",
"_byId",
"[",
"entity",
".",
"cid",
"]",
";",
"var",
"id",
"=",
"this",
".",
"entityId",
"(",
"entity",
".",
"attributes",
")",
";",
"if",
"(",
"id",
"!=",
"null",
")",
"delete",
"this",
".",
"_byId",
"[",
"id",
"]",
";",
"if",
"(",
"this",
"===",
"entity",
".",
"collection",
")",
"delete",
"entity",
".",
"collection",
";",
"entity",
".",
"off",
"(",
"'all'",
",",
"this",
".",
"_onEntityEvent",
",",
"this",
")",
";",
"}"
] | Internal method to sever a entity's ties to a collection. | [
"Internal",
"method",
"to",
"sever",
"a",
"entity",
"s",
"ties",
"to",
"a",
"collection",
"."
] | ef082bb53b162b4a2c6992ef07a3e32553f6aed5 | https://github.com/skylarkutils/skylark-utils/blob/ef082bb53b162b4a2c6992ef07a3e32553f6aed5/dist/uncompressed/skylark-utils/models.js#L621-L627 |
|
54,879 | skylarkutils/skylark-utils | dist/uncompressed/skylark-utils/models.js | function(event, entity, collection, options) {
if (entity) {
if ((event === 'add' || event === 'remove') && collection !== this) return;
if (event === 'destroy') this.remove(entity, options);
if (event === 'change') {
var prevId = this.entityId(entity.previousAttributes());
var id = this.entityId(entity.attributes);
if (prevId !== id) {
if (prevId != null) delete this._byId[prevId];
if (id != null) this._byId[id] = entity;
}
}
}
this.trigger.apply(this, arguments);
} | javascript | function(event, entity, collection, options) {
if (entity) {
if ((event === 'add' || event === 'remove') && collection !== this) return;
if (event === 'destroy') this.remove(entity, options);
if (event === 'change') {
var prevId = this.entityId(entity.previousAttributes());
var id = this.entityId(entity.attributes);
if (prevId !== id) {
if (prevId != null) delete this._byId[prevId];
if (id != null) this._byId[id] = entity;
}
}
}
this.trigger.apply(this, arguments);
} | [
"function",
"(",
"event",
",",
"entity",
",",
"collection",
",",
"options",
")",
"{",
"if",
"(",
"entity",
")",
"{",
"if",
"(",
"(",
"event",
"===",
"'add'",
"||",
"event",
"===",
"'remove'",
")",
"&&",
"collection",
"!==",
"this",
")",
"return",
";",
"if",
"(",
"event",
"===",
"'destroy'",
")",
"this",
".",
"remove",
"(",
"entity",
",",
"options",
")",
";",
"if",
"(",
"event",
"===",
"'change'",
")",
"{",
"var",
"prevId",
"=",
"this",
".",
"entityId",
"(",
"entity",
".",
"previousAttributes",
"(",
")",
")",
";",
"var",
"id",
"=",
"this",
".",
"entityId",
"(",
"entity",
".",
"attributes",
")",
";",
"if",
"(",
"prevId",
"!==",
"id",
")",
"{",
"if",
"(",
"prevId",
"!=",
"null",
")",
"delete",
"this",
".",
"_byId",
"[",
"prevId",
"]",
";",
"if",
"(",
"id",
"!=",
"null",
")",
"this",
".",
"_byId",
"[",
"id",
"]",
"=",
"entity",
";",
"}",
"}",
"}",
"this",
".",
"trigger",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}"
] | Internal method called every time a entity in the set fires an event. Sets need to update their indexes when entities change ids. All other events simply proxy through. "add" and "remove" events that originate in other collections are ignored. | [
"Internal",
"method",
"called",
"every",
"time",
"a",
"entity",
"in",
"the",
"set",
"fires",
"an",
"event",
".",
"Sets",
"need",
"to",
"update",
"their",
"indexes",
"when",
"entities",
"change",
"ids",
".",
"All",
"other",
"events",
"simply",
"proxy",
"through",
".",
"add",
"and",
"remove",
"events",
"that",
"originate",
"in",
"other",
"collections",
"are",
"ignored",
"."
] | ef082bb53b162b4a2c6992ef07a3e32553f6aed5 | https://github.com/skylarkutils/skylark-utils/blob/ef082bb53b162b4a2c6992ef07a3e32553f6aed5/dist/uncompressed/skylark-utils/models.js#L633-L647 |
|
54,880 | tgi-io/tgi-store-remote | lib/tgi-store-host.source.js | function (args) {
//console.log('PutModel messageContents: json ' + JSON.stringify(messageContents));
Model.call(this, args);
this.modelType = messageContents.modelType;
this.attributes = [];
var a, attrib, v;
for (a in messageContents.attributes) {
//console.log('PutModel Attribute: json ' + JSON.stringify(messageContents.attributes[a]));
if (messageContents.attributes[a].type == 'Model') {
v = new Attribute.ModelID(createModelFromModelType(messageContents.attributes[a].modelType));
v.value = messageContents.attributes[a].value.value;
if (messageContents.attributes[a].value.name)
v.name = messageContents.attributes[a].value.name;
attrib = new Attribute({name: messageContents.attributes[a].name, type: 'Model', value: v});
} else if (messageContents.attributes[a].type == 'Date') {
attrib = new Attribute(messageContents.attributes[a].name, messageContents.attributes[a].type);
try {
attrib.value = messageContents.attributes[a].value === null ? null : new Date(messageContents.attributes[a].value);
} catch (e) {
attrib.value = null;
}
} else {
attrib = new Attribute(messageContents.attributes[a].name, messageContents.attributes[a].type);
if (attrib.name == 'id') { // TODO only If mongo! or refactor mongo to normalize IDs
if (attrib.value != messageContents.attributes[a].value)
attrib.value = messageContents.attributes[a].value;
} else {
attrib.value = messageContents.attributes[a].value;
}
}
this.attributes.push(attrib);
}
} | javascript | function (args) {
//console.log('PutModel messageContents: json ' + JSON.stringify(messageContents));
Model.call(this, args);
this.modelType = messageContents.modelType;
this.attributes = [];
var a, attrib, v;
for (a in messageContents.attributes) {
//console.log('PutModel Attribute: json ' + JSON.stringify(messageContents.attributes[a]));
if (messageContents.attributes[a].type == 'Model') {
v = new Attribute.ModelID(createModelFromModelType(messageContents.attributes[a].modelType));
v.value = messageContents.attributes[a].value.value;
if (messageContents.attributes[a].value.name)
v.name = messageContents.attributes[a].value.name;
attrib = new Attribute({name: messageContents.attributes[a].name, type: 'Model', value: v});
} else if (messageContents.attributes[a].type == 'Date') {
attrib = new Attribute(messageContents.attributes[a].name, messageContents.attributes[a].type);
try {
attrib.value = messageContents.attributes[a].value === null ? null : new Date(messageContents.attributes[a].value);
} catch (e) {
attrib.value = null;
}
} else {
attrib = new Attribute(messageContents.attributes[a].name, messageContents.attributes[a].type);
if (attrib.name == 'id') { // TODO only If mongo! or refactor mongo to normalize IDs
if (attrib.value != messageContents.attributes[a].value)
attrib.value = messageContents.attributes[a].value;
} else {
attrib.value = messageContents.attributes[a].value;
}
}
this.attributes.push(attrib);
}
} | [
"function",
"(",
"args",
")",
"{",
"//console.log('PutModel messageContents: json ' + JSON.stringify(messageContents));",
"Model",
".",
"call",
"(",
"this",
",",
"args",
")",
";",
"this",
".",
"modelType",
"=",
"messageContents",
".",
"modelType",
";",
"this",
".",
"attributes",
"=",
"[",
"]",
";",
"var",
"a",
",",
"attrib",
",",
"v",
";",
"for",
"(",
"a",
"in",
"messageContents",
".",
"attributes",
")",
"{",
"//console.log('PutModel Attribute: json ' + JSON.stringify(messageContents.attributes[a]));",
"if",
"(",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"type",
"==",
"'Model'",
")",
"{",
"v",
"=",
"new",
"Attribute",
".",
"ModelID",
"(",
"createModelFromModelType",
"(",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"modelType",
")",
")",
";",
"v",
".",
"value",
"=",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"value",
".",
"value",
";",
"if",
"(",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"value",
".",
"name",
")",
"v",
".",
"name",
"=",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"value",
".",
"name",
";",
"attrib",
"=",
"new",
"Attribute",
"(",
"{",
"name",
":",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"name",
",",
"type",
":",
"'Model'",
",",
"value",
":",
"v",
"}",
")",
";",
"}",
"else",
"if",
"(",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"type",
"==",
"'Date'",
")",
"{",
"attrib",
"=",
"new",
"Attribute",
"(",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"name",
",",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"type",
")",
";",
"try",
"{",
"attrib",
".",
"value",
"=",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"value",
"===",
"null",
"?",
"null",
":",
"new",
"Date",
"(",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"value",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"attrib",
".",
"value",
"=",
"null",
";",
"}",
"}",
"else",
"{",
"attrib",
"=",
"new",
"Attribute",
"(",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"name",
",",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"type",
")",
";",
"if",
"(",
"attrib",
".",
"name",
"==",
"'id'",
")",
"{",
"// TODO only If mongo! or refactor mongo to normalize IDs",
"if",
"(",
"attrib",
".",
"value",
"!=",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"value",
")",
"attrib",
".",
"value",
"=",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"value",
";",
"}",
"else",
"{",
"attrib",
".",
"value",
"=",
"messageContents",
".",
"attributes",
"[",
"a",
"]",
".",
"value",
";",
"}",
"}",
"this",
".",
"attributes",
".",
"push",
"(",
"attrib",
")",
";",
"}",
"}"
] | create proxy for client model | [
"create",
"proxy",
"for",
"client",
"model"
] | 8c143c0bbd97c29fe7b12ce2501f6a2602eb71ad | https://github.com/tgi-io/tgi-store-remote/blob/8c143c0bbd97c29fe7b12ce2501f6a2602eb71ad/lib/tgi-store-host.source.js#L7-L39 |
|
54,881 | jpommerening/node-markdown-bdd | index.js | containedInOrder | function containedInOrder(needle, haystack) {
var i, j = 0;
for (i = 0; i < needle.length; i++) {
while (j < haystack.length && needle[i] !== haystack[j]) j++;
}
return i === needle.length && j < haystack.length;
} | javascript | function containedInOrder(needle, haystack) {
var i, j = 0;
for (i = 0; i < needle.length; i++) {
while (j < haystack.length && needle[i] !== haystack[j]) j++;
}
return i === needle.length && j < haystack.length;
} | [
"function",
"containedInOrder",
"(",
"needle",
",",
"haystack",
")",
"{",
"var",
"i",
",",
"j",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"needle",
".",
"length",
";",
"i",
"++",
")",
"{",
"while",
"(",
"j",
"<",
"haystack",
".",
"length",
"&&",
"needle",
"[",
"i",
"]",
"!==",
"haystack",
"[",
"j",
"]",
")",
"j",
"++",
";",
"}",
"return",
"i",
"===",
"needle",
".",
"length",
"&&",
"j",
"<",
"haystack",
".",
"length",
";",
"}"
] | Test that each item in needle is contained in haystack in the right order. | [
"Test",
"that",
"each",
"item",
"in",
"needle",
"is",
"contained",
"in",
"haystack",
"in",
"the",
"right",
"order",
"."
] | 44739151903dd472dbfa74b3479e2c7ab9682616 | https://github.com/jpommerening/node-markdown-bdd/blob/44739151903dd472dbfa74b3479e2c7ab9682616/index.js#L8-L14 |
54,882 | IonicaBizau/node-package-dependents | lib/index.js | PackageDependents | function PackageDependents(name, version, callback) {
if (typeof version === "function") {
callback = version
version = "latest"
}
GetDependents(name, function(err, packages) {
if (err) { return callback(err) }
SameTime(packages.map(function (c) {
return function (fn) {
PackageJson(c, version).then(function (json) {
fn(null, json)
}).catch(function (err) {
fn(err)
})
}
}), function (err, packages) {
callback(err, packages || [])
})
})
} | javascript | function PackageDependents(name, version, callback) {
if (typeof version === "function") {
callback = version
version = "latest"
}
GetDependents(name, function(err, packages) {
if (err) { return callback(err) }
SameTime(packages.map(function (c) {
return function (fn) {
PackageJson(c, version).then(function (json) {
fn(null, json)
}).catch(function (err) {
fn(err)
})
}
}), function (err, packages) {
callback(err, packages || [])
})
})
} | [
"function",
"PackageDependents",
"(",
"name",
",",
"version",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"version",
"===",
"\"function\"",
")",
"{",
"callback",
"=",
"version",
"version",
"=",
"\"latest\"",
"}",
"GetDependents",
"(",
"name",
",",
"function",
"(",
"err",
",",
"packages",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
"}",
"SameTime",
"(",
"packages",
".",
"map",
"(",
"function",
"(",
"c",
")",
"{",
"return",
"function",
"(",
"fn",
")",
"{",
"PackageJson",
"(",
"c",
",",
"version",
")",
".",
"then",
"(",
"function",
"(",
"json",
")",
"{",
"fn",
"(",
"null",
",",
"json",
")",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"fn",
"(",
"err",
")",
"}",
")",
"}",
"}",
")",
",",
"function",
"(",
"err",
",",
"packages",
")",
"{",
"callback",
"(",
"err",
",",
"packages",
"||",
"[",
"]",
")",
"}",
")",
"}",
")",
"}"
] | PackageDependents
Get the dependents of a given packages. The callback function is called with
an error and an array of objects.
@name PackageDependents
@function
@param {String} name The package name.
@param {String} version The package version (default: `"latest"`).
@param {Function} callback The callback function. | [
"PackageDependents",
"Get",
"the",
"dependents",
"of",
"a",
"given",
"packages",
".",
"The",
"callback",
"function",
"is",
"called",
"with",
"an",
"error",
"and",
"an",
"array",
"of",
"objects",
"."
] | e49accbbe767cb81721d9db1063b690c19c5eb48 | https://github.com/IonicaBizau/node-package-dependents/blob/e49accbbe767cb81721d9db1063b690c19c5eb48/lib/index.js#L18-L37 |
54,883 | hl198181/neptune | misc/demo/public/vendor/angular-form-for/form-for.js | function () {
if (!filterText) {
var filterTextSelector = $element.find('input');
if (filterTextSelector.length) {
filterText = filterTextSelector[0];
}
}
if (filterText) {
$timeout_(filterText.focus.bind(filterText));
}
} | javascript | function () {
if (!filterText) {
var filterTextSelector = $element.find('input');
if (filterTextSelector.length) {
filterText = filterTextSelector[0];
}
}
if (filterText) {
$timeout_(filterText.focus.bind(filterText));
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"filterText",
")",
"{",
"var",
"filterTextSelector",
"=",
"$element",
".",
"find",
"(",
"'input'",
")",
";",
"if",
"(",
"filterTextSelector",
".",
"length",
")",
"{",
"filterText",
"=",
"filterTextSelector",
"[",
"0",
"]",
";",
"}",
"}",
"if",
"(",
"filterText",
")",
"{",
"$timeout_",
"(",
"filterText",
".",
"focus",
".",
"bind",
"(",
"filterText",
")",
")",
";",
"}",
"}"
] | Helper method for setting focus on an item after a delay | [
"Helper",
"method",
"for",
"setting",
"focus",
"on",
"an",
"item",
"after",
"a",
"delay"
] | 88030bb4222945900e6a225469380cc43a016c13 | https://github.com/hl198181/neptune/blob/88030bb4222945900e6a225469380cc43a016c13/misc/demo/public/vendor/angular-form-for/form-for.js#L2109-L2119 |
|
54,884 | JoniDB/trumpygrimm | index.js | newMarkov | function newMarkov() {
var options = {
maxLength: 140,
minWords: 10,
minScore: 20,
};
//new instance
markov = new Markov(data, options);
console.log(markov);
var markovStrings = [];
// Build the corpus
markov.buildCorpus();
} | javascript | function newMarkov() {
var options = {
maxLength: 140,
minWords: 10,
minScore: 20,
};
//new instance
markov = new Markov(data, options);
console.log(markov);
var markovStrings = [];
// Build the corpus
markov.buildCorpus();
} | [
"function",
"newMarkov",
"(",
")",
"{",
"var",
"options",
"=",
"{",
"maxLength",
":",
"140",
",",
"minWords",
":",
"10",
",",
"minScore",
":",
"20",
",",
"}",
";",
"//new instance",
"markov",
"=",
"new",
"Markov",
"(",
"data",
",",
"options",
")",
";",
"console",
".",
"log",
"(",
"markov",
")",
";",
"var",
"markovStrings",
"=",
"[",
"]",
";",
"// Build the corpus",
"markov",
".",
"buildCorpus",
"(",
")",
";",
"}"
] | Some options to generate Twitter-ready strings | [
"Some",
"options",
"to",
"generate",
"Twitter",
"-",
"ready",
"strings"
] | f3564dd4709a02d77f0726988fb43e473d024fe4 | https://github.com/JoniDB/trumpygrimm/blob/f3564dd4709a02d77f0726988fb43e473d024fe4/index.js#L79-L93 |
54,885 | novemberborn/thenstream | lib/Thenstream.js | onReadable | function onReadable() {
if (self._assimilationState.waiting) {
self._assimilationState.waiting = false;
self._pushChunks();
}
} | javascript | function onReadable() {
if (self._assimilationState.waiting) {
self._assimilationState.waiting = false;
self._pushChunks();
}
} | [
"function",
"onReadable",
"(",
")",
"{",
"if",
"(",
"self",
".",
"_assimilationState",
".",
"waiting",
")",
"{",
"self",
".",
"_assimilationState",
".",
"waiting",
"=",
"false",
";",
"self",
".",
"_pushChunks",
"(",
")",
";",
"}",
"}"
] | Push more chunks when data becomes available. | [
"Push",
"more",
"chunks",
"when",
"data",
"becomes",
"available",
"."
] | 57499b6e35d7ecc10662d9080a227be726b11b19 | https://github.com/novemberborn/thenstream/blob/57499b6e35d7ecc10662d9080a227be726b11b19/lib/Thenstream.js#L129-L134 |
54,886 | airosa/sdmxmllib | samples/sdmxmlmap/js/sdmxmlmap.js | function () {
if (req.status !== 200) {
console.warn(req.responseText);
return;
}
// Show the raw response text on page
xmlOutput.textContent = req.responseText;
// convert XML to javascript objects
var json = sdmxmllib.mapSDMXMLResponse(req.responseText);
// Convert to json and show on page
jsonOutput.textContent = JSON.stringify(json, null, 2);
} | javascript | function () {
if (req.status !== 200) {
console.warn(req.responseText);
return;
}
// Show the raw response text on page
xmlOutput.textContent = req.responseText;
// convert XML to javascript objects
var json = sdmxmllib.mapSDMXMLResponse(req.responseText);
// Convert to json and show on page
jsonOutput.textContent = JSON.stringify(json, null, 2);
} | [
"function",
"(",
")",
"{",
"if",
"(",
"req",
".",
"status",
"!==",
"200",
")",
"{",
"console",
".",
"warn",
"(",
"req",
".",
"responseText",
")",
";",
"return",
";",
"}",
"// Show the raw response text on page",
"xmlOutput",
".",
"textContent",
"=",
"req",
".",
"responseText",
";",
"// convert XML to javascript objects",
"var",
"json",
"=",
"sdmxmllib",
".",
"mapSDMXMLResponse",
"(",
"req",
".",
"responseText",
")",
";",
"// Convert to json and show on page",
"jsonOutput",
".",
"textContent",
"=",
"JSON",
".",
"stringify",
"(",
"json",
",",
"null",
",",
"2",
")",
";",
"}"
] | Response handler. Check the console for errors. | [
"Response",
"handler",
".",
"Check",
"the",
"console",
"for",
"errors",
"."
] | 27e1e41a60dcc383ac06edafda6f37fbfed71d83 | https://github.com/airosa/sdmxmllib/blob/27e1e41a60dcc383ac06edafda6f37fbfed71d83/samples/sdmxmlmap/js/sdmxmlmap.js#L14-L25 |
|
54,887 | tungtung-dev/common-helper | src/object/index.js | convertData | function convertData(objectBody, objectChange) {
const keysChange = Object.keys(objectChange);
let objectReturn = {};
keysChange.map(keyChange => {
let changeOption = objectChange[keyChange];
let valueKeyReturn = getValueChangeOption(objectBody, keyChange, changeOption, objectReturn);
if(valueKeyReturn !== undefined && valueKeyReturn !== null){
objectReturn[keyChange] = valueKeyReturn;
}
return keyChange;
});
return objectReturn;
} | javascript | function convertData(objectBody, objectChange) {
const keysChange = Object.keys(objectChange);
let objectReturn = {};
keysChange.map(keyChange => {
let changeOption = objectChange[keyChange];
let valueKeyReturn = getValueChangeOption(objectBody, keyChange, changeOption, objectReturn);
if(valueKeyReturn !== undefined && valueKeyReturn !== null){
objectReturn[keyChange] = valueKeyReturn;
}
return keyChange;
});
return objectReturn;
} | [
"function",
"convertData",
"(",
"objectBody",
",",
"objectChange",
")",
"{",
"const",
"keysChange",
"=",
"Object",
".",
"keys",
"(",
"objectChange",
")",
";",
"let",
"objectReturn",
"=",
"{",
"}",
";",
"keysChange",
".",
"map",
"(",
"keyChange",
"=>",
"{",
"let",
"changeOption",
"=",
"objectChange",
"[",
"keyChange",
"]",
";",
"let",
"valueKeyReturn",
"=",
"getValueChangeOption",
"(",
"objectBody",
",",
"keyChange",
",",
"changeOption",
",",
"objectReturn",
")",
";",
"if",
"(",
"valueKeyReturn",
"!==",
"undefined",
"&&",
"valueKeyReturn",
"!==",
"null",
")",
"{",
"objectReturn",
"[",
"keyChange",
"]",
"=",
"valueKeyReturn",
";",
"}",
"return",
"keyChange",
";",
"}",
")",
";",
"return",
"objectReturn",
";",
"}"
] | Parse body Object to data Object
@param objectBody
@param objectChange
@returns {{}} | [
"Parse",
"body",
"Object",
"to",
"data",
"Object"
] | 94abeff34fee3b2366b308571e94f2da8b0db655 | https://github.com/tungtung-dev/common-helper/blob/94abeff34fee3b2366b308571e94f2da8b0db655/src/object/index.js#L32-L44 |
54,888 | sourdough-css/preprocessor | lib/index.js | cssToSss | function cssToSss (css, file) {
if (path.extname(file) === '.css') {
return postcss().process(css, { stringifier: sugarss }).then(function (result) {
return result.css
})
} else {
return css
}
} | javascript | function cssToSss (css, file) {
if (path.extname(file) === '.css') {
return postcss().process(css, { stringifier: sugarss }).then(function (result) {
return result.css
})
} else {
return css
}
} | [
"function",
"cssToSss",
"(",
"css",
",",
"file",
")",
"{",
"if",
"(",
"path",
".",
"extname",
"(",
"file",
")",
"===",
"'.css'",
")",
"{",
"return",
"postcss",
"(",
")",
".",
"process",
"(",
"css",
",",
"{",
"stringifier",
":",
"sugarss",
"}",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"return",
"result",
".",
"css",
"}",
")",
"}",
"else",
"{",
"return",
"css",
"}",
"}"
] | Transform .css files to sss syntax | [
"Transform",
".",
"css",
"files",
"to",
"sss",
"syntax"
] | d065000ac3c7c31524058793409de2f78a092d04 | https://github.com/sourdough-css/preprocessor/blob/d065000ac3c7c31524058793409de2f78a092d04/lib/index.js#L51-L59 |
54,889 | odentools/denhub-device | scripts/generator.js | generateCode | function generateCode (config, is_all_yes) {
console.log(colors.bold('--------------- Code Generator ---------------\n'));
// Check the configuration
if (!config.commands) {
throw new Error('commands undefined in your config.js');
}
// Start the processes
var entry_js = null, handler_js = null, package_json = null, is_modules_installed = false;
Promise.resolve()
.then(function () {
// Generate the entry point script
entry_js = generateCodeEntryJs(config);
// Preview of the entry point script
console.log(entry_js);
// To skip mode
if (is_all_yes) return {isSaveEntryJs: true};
// Confirm to user
return inquirer.prompt([{
type: 'confirm',
name: 'isSaveEntryJs',
message: 'The entry point was generated. Would you write it to ' + ENTRY_POINT_FILENAME + ' ?'
}]);
}).then(function (answer) {
if (!answer.isSaveEntryJs) {
entry_js = null;
return false;
}
// Save the entry point script
console.log('\nWriting to ' + process.cwd() + '/' + ENTRY_POINT_FILENAME);
fs.writeFileSync(ENTRY_POINT_FILENAME, entry_js);
console.log('Writing has been completed.\n\n');
return true;
}).then(function (result) {
// Generate the commands handler script
handler_js = generateCodeHandlerJs(config);
// Preview of the commands handler script
console.log(handler_js);
// To skip mode
if (is_all_yes) return {isSaveHandlerJs: true};
// Confirm to user
return inquirer.prompt([{
type: 'confirm',
name: 'isSaveHandlerJs',
message: 'The commands handler was generated. Would you write it to ' + HANDLER_FILENAME + ' ?'
}]);
}).then(function (answer) {
if (!answer.isSaveHandlerJs) {
handler_js = null;
return false;
}
// Save the commands handler script
console.log('\nWriting to ' + process.cwd() + '/' + HANDLER_FILENAME);
fs.writeFileSync(HANDLER_FILENAME, handler_js);
console.log('Writing has been completed.\n\n');
return true;
}).then(function (result) {
// Generate the package.json
package_json = generatePackageJson(config);
if (package_json == null) { // If user's package.json exists and invalid
// Skip
return { answer: { isSavePackageJson: false} };
}
// Preview of the package.json
console.log(package_json + '\n');
// To skip mode
if (is_all_yes) return {isSavePackageJson: true};
// Confirm to user
return inquirer.prompt([{
type: 'confirm',
name: 'isSavePackageJson',
message: 'The package.json was generated. Would you write it to package.json ?'
}]);
}).then(function (answer) {
if (!answer.isSavePackageJson) {
package_json = null;
return false;
}
// Save the commands handler script
console.log('\nWriting to ' + process.cwd() + '/package.json');
fs.writeFileSync('package.json', package_json);
console.log('Writing has been completed.\n\n');
return true;
}).then(function (result) {
// Confirm to whether the dependency modules are installed
var dir_list = [];
try {
dir_list = fs.readdirSync('./node_modules/');
} catch (e) {
dir_list = [];
}
is_modules_installed = false;
dir_list.forEach(function (name, i) {
if (name == 'denhub-device') {
is_modules_installed = true;
}
});
if (is_modules_installed || is_all_yes) {
return {isDependencyInstall: false};
}
// Confirm to user
return inquirer.prompt([{
type: 'confirm',
name: 'isDependencyInstall',
message: 'The required modules are not installed. Would you install it now ?'
}]);
}).then(function (answer) {
if (!answer.isDependencyInstall) {
return false;
}
// Install the dependency modules
is_modules_installed = true;
return execDependencyInstall();
}).then(function (result) {
console.log(colors.bold.green('All was completed.'));
if (!entry_js && !handler_js) {
console.log('');
process.exit(0);
return;
}
// Show the guide
console.log(colors.bold('Enjoy :)\n'));
if (!is_modules_installed) console.log('$ npm install');
console.log('$ npm start -- --dev\n');
console.log('For details, please refer to https://github.com/odentools/denhub-device/\n');
});
} | javascript | function generateCode (config, is_all_yes) {
console.log(colors.bold('--------------- Code Generator ---------------\n'));
// Check the configuration
if (!config.commands) {
throw new Error('commands undefined in your config.js');
}
// Start the processes
var entry_js = null, handler_js = null, package_json = null, is_modules_installed = false;
Promise.resolve()
.then(function () {
// Generate the entry point script
entry_js = generateCodeEntryJs(config);
// Preview of the entry point script
console.log(entry_js);
// To skip mode
if (is_all_yes) return {isSaveEntryJs: true};
// Confirm to user
return inquirer.prompt([{
type: 'confirm',
name: 'isSaveEntryJs',
message: 'The entry point was generated. Would you write it to ' + ENTRY_POINT_FILENAME + ' ?'
}]);
}).then(function (answer) {
if (!answer.isSaveEntryJs) {
entry_js = null;
return false;
}
// Save the entry point script
console.log('\nWriting to ' + process.cwd() + '/' + ENTRY_POINT_FILENAME);
fs.writeFileSync(ENTRY_POINT_FILENAME, entry_js);
console.log('Writing has been completed.\n\n');
return true;
}).then(function (result) {
// Generate the commands handler script
handler_js = generateCodeHandlerJs(config);
// Preview of the commands handler script
console.log(handler_js);
// To skip mode
if (is_all_yes) return {isSaveHandlerJs: true};
// Confirm to user
return inquirer.prompt([{
type: 'confirm',
name: 'isSaveHandlerJs',
message: 'The commands handler was generated. Would you write it to ' + HANDLER_FILENAME + ' ?'
}]);
}).then(function (answer) {
if (!answer.isSaveHandlerJs) {
handler_js = null;
return false;
}
// Save the commands handler script
console.log('\nWriting to ' + process.cwd() + '/' + HANDLER_FILENAME);
fs.writeFileSync(HANDLER_FILENAME, handler_js);
console.log('Writing has been completed.\n\n');
return true;
}).then(function (result) {
// Generate the package.json
package_json = generatePackageJson(config);
if (package_json == null) { // If user's package.json exists and invalid
// Skip
return { answer: { isSavePackageJson: false} };
}
// Preview of the package.json
console.log(package_json + '\n');
// To skip mode
if (is_all_yes) return {isSavePackageJson: true};
// Confirm to user
return inquirer.prompt([{
type: 'confirm',
name: 'isSavePackageJson',
message: 'The package.json was generated. Would you write it to package.json ?'
}]);
}).then(function (answer) {
if (!answer.isSavePackageJson) {
package_json = null;
return false;
}
// Save the commands handler script
console.log('\nWriting to ' + process.cwd() + '/package.json');
fs.writeFileSync('package.json', package_json);
console.log('Writing has been completed.\n\n');
return true;
}).then(function (result) {
// Confirm to whether the dependency modules are installed
var dir_list = [];
try {
dir_list = fs.readdirSync('./node_modules/');
} catch (e) {
dir_list = [];
}
is_modules_installed = false;
dir_list.forEach(function (name, i) {
if (name == 'denhub-device') {
is_modules_installed = true;
}
});
if (is_modules_installed || is_all_yes) {
return {isDependencyInstall: false};
}
// Confirm to user
return inquirer.prompt([{
type: 'confirm',
name: 'isDependencyInstall',
message: 'The required modules are not installed. Would you install it now ?'
}]);
}).then(function (answer) {
if (!answer.isDependencyInstall) {
return false;
}
// Install the dependency modules
is_modules_installed = true;
return execDependencyInstall();
}).then(function (result) {
console.log(colors.bold.green('All was completed.'));
if (!entry_js && !handler_js) {
console.log('');
process.exit(0);
return;
}
// Show the guide
console.log(colors.bold('Enjoy :)\n'));
if (!is_modules_installed) console.log('$ npm install');
console.log('$ npm start -- --dev\n');
console.log('For details, please refer to https://github.com/odentools/denhub-device/\n');
});
} | [
"function",
"generateCode",
"(",
"config",
",",
"is_all_yes",
")",
"{",
"console",
".",
"log",
"(",
"colors",
".",
"bold",
"(",
"'--------------- Code Generator ---------------\\n'",
")",
")",
";",
"// Check the configuration",
"if",
"(",
"!",
"config",
".",
"commands",
")",
"{",
"throw",
"new",
"Error",
"(",
"'commands undefined in your config.js'",
")",
";",
"}",
"// Start the processes",
"var",
"entry_js",
"=",
"null",
",",
"handler_js",
"=",
"null",
",",
"package_json",
"=",
"null",
",",
"is_modules_installed",
"=",
"false",
";",
"Promise",
".",
"resolve",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"// Generate the entry point script",
"entry_js",
"=",
"generateCodeEntryJs",
"(",
"config",
")",
";",
"// Preview of the entry point script",
"console",
".",
"log",
"(",
"entry_js",
")",
";",
"// To skip mode",
"if",
"(",
"is_all_yes",
")",
"return",
"{",
"isSaveEntryJs",
":",
"true",
"}",
";",
"// Confirm to user",
"return",
"inquirer",
".",
"prompt",
"(",
"[",
"{",
"type",
":",
"'confirm'",
",",
"name",
":",
"'isSaveEntryJs'",
",",
"message",
":",
"'The entry point was generated. Would you write it to '",
"+",
"ENTRY_POINT_FILENAME",
"+",
"' ?'",
"}",
"]",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"answer",
")",
"{",
"if",
"(",
"!",
"answer",
".",
"isSaveEntryJs",
")",
"{",
"entry_js",
"=",
"null",
";",
"return",
"false",
";",
"}",
"// Save the entry point script",
"console",
".",
"log",
"(",
"'\\nWriting to '",
"+",
"process",
".",
"cwd",
"(",
")",
"+",
"'/'",
"+",
"ENTRY_POINT_FILENAME",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"ENTRY_POINT_FILENAME",
",",
"entry_js",
")",
";",
"console",
".",
"log",
"(",
"'Writing has been completed.\\n\\n'",
")",
";",
"return",
"true",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"// Generate the commands handler script",
"handler_js",
"=",
"generateCodeHandlerJs",
"(",
"config",
")",
";",
"// Preview of the commands handler script",
"console",
".",
"log",
"(",
"handler_js",
")",
";",
"// To skip mode",
"if",
"(",
"is_all_yes",
")",
"return",
"{",
"isSaveHandlerJs",
":",
"true",
"}",
";",
"// Confirm to user",
"return",
"inquirer",
".",
"prompt",
"(",
"[",
"{",
"type",
":",
"'confirm'",
",",
"name",
":",
"'isSaveHandlerJs'",
",",
"message",
":",
"'The commands handler was generated. Would you write it to '",
"+",
"HANDLER_FILENAME",
"+",
"' ?'",
"}",
"]",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"answer",
")",
"{",
"if",
"(",
"!",
"answer",
".",
"isSaveHandlerJs",
")",
"{",
"handler_js",
"=",
"null",
";",
"return",
"false",
";",
"}",
"// Save the commands handler script",
"console",
".",
"log",
"(",
"'\\nWriting to '",
"+",
"process",
".",
"cwd",
"(",
")",
"+",
"'/'",
"+",
"HANDLER_FILENAME",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"HANDLER_FILENAME",
",",
"handler_js",
")",
";",
"console",
".",
"log",
"(",
"'Writing has been completed.\\n\\n'",
")",
";",
"return",
"true",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"// Generate the package.json",
"package_json",
"=",
"generatePackageJson",
"(",
"config",
")",
";",
"if",
"(",
"package_json",
"==",
"null",
")",
"{",
"// If user's package.json exists and invalid",
"// Skip",
"return",
"{",
"answer",
":",
"{",
"isSavePackageJson",
":",
"false",
"}",
"}",
";",
"}",
"// Preview of the package.json",
"console",
".",
"log",
"(",
"package_json",
"+",
"'\\n'",
")",
";",
"// To skip mode",
"if",
"(",
"is_all_yes",
")",
"return",
"{",
"isSavePackageJson",
":",
"true",
"}",
";",
"// Confirm to user",
"return",
"inquirer",
".",
"prompt",
"(",
"[",
"{",
"type",
":",
"'confirm'",
",",
"name",
":",
"'isSavePackageJson'",
",",
"message",
":",
"'The package.json was generated. Would you write it to package.json ?'",
"}",
"]",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"answer",
")",
"{",
"if",
"(",
"!",
"answer",
".",
"isSavePackageJson",
")",
"{",
"package_json",
"=",
"null",
";",
"return",
"false",
";",
"}",
"// Save the commands handler script",
"console",
".",
"log",
"(",
"'\\nWriting to '",
"+",
"process",
".",
"cwd",
"(",
")",
"+",
"'/package.json'",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"'package.json'",
",",
"package_json",
")",
";",
"console",
".",
"log",
"(",
"'Writing has been completed.\\n\\n'",
")",
";",
"return",
"true",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"// Confirm to whether the dependency modules are installed",
"var",
"dir_list",
"=",
"[",
"]",
";",
"try",
"{",
"dir_list",
"=",
"fs",
".",
"readdirSync",
"(",
"'./node_modules/'",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"dir_list",
"=",
"[",
"]",
";",
"}",
"is_modules_installed",
"=",
"false",
";",
"dir_list",
".",
"forEach",
"(",
"function",
"(",
"name",
",",
"i",
")",
"{",
"if",
"(",
"name",
"==",
"'denhub-device'",
")",
"{",
"is_modules_installed",
"=",
"true",
";",
"}",
"}",
")",
";",
"if",
"(",
"is_modules_installed",
"||",
"is_all_yes",
")",
"{",
"return",
"{",
"isDependencyInstall",
":",
"false",
"}",
";",
"}",
"// Confirm to user",
"return",
"inquirer",
".",
"prompt",
"(",
"[",
"{",
"type",
":",
"'confirm'",
",",
"name",
":",
"'isDependencyInstall'",
",",
"message",
":",
"'The required modules are not installed. Would you install it now ?'",
"}",
"]",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"answer",
")",
"{",
"if",
"(",
"!",
"answer",
".",
"isDependencyInstall",
")",
"{",
"return",
"false",
";",
"}",
"// Install the dependency modules",
"is_modules_installed",
"=",
"true",
";",
"return",
"execDependencyInstall",
"(",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"console",
".",
"log",
"(",
"colors",
".",
"bold",
".",
"green",
"(",
"'All was completed.'",
")",
")",
";",
"if",
"(",
"!",
"entry_js",
"&&",
"!",
"handler_js",
")",
"{",
"console",
".",
"log",
"(",
"''",
")",
";",
"process",
".",
"exit",
"(",
"0",
")",
";",
"return",
";",
"}",
"// Show the guide",
"console",
".",
"log",
"(",
"colors",
".",
"bold",
"(",
"'Enjoy :)\\n'",
")",
")",
";",
"if",
"(",
"!",
"is_modules_installed",
")",
"console",
".",
"log",
"(",
"'$ npm install'",
")",
";",
"console",
".",
"log",
"(",
"'$ npm start -- --dev\\n'",
")",
";",
"console",
".",
"log",
"(",
"'For details, please refer to https://github.com/odentools/denhub-device/\\n'",
")",
";",
"}",
")",
";",
"}"
] | Generate the source code for device daemon
@param {Object} config Device configuration
@param {Boolea} is_all_yes Whether the response will choose yes automatically | [
"Generate",
"the",
"source",
"code",
"for",
"device",
"daemon"
] | 50d35aca96db3a07a3272f1765a660ea893735ce | https://github.com/odentools/denhub-device/blob/50d35aca96db3a07a3272f1765a660ea893735ce/scripts/generator.js#L254-L421 |
54,890 | odentools/denhub-device | scripts/generator.js | generateCodeEntryJs | function generateCodeEntryJs (config) {
// Read the entry point script
var entry_js = null;
try {
// Read from current script
entry_js = fs.readFileSync(ENTRY_POINT_FILENAME).toString();
} catch (e) {
// Read from template script
entry_js = fs.readFileSync(__dirname + '/../templates/' + ENTRY_POINT_FILENAME + '.tmpl').toString() + '\n';
}
return entry_js;
} | javascript | function generateCodeEntryJs (config) {
// Read the entry point script
var entry_js = null;
try {
// Read from current script
entry_js = fs.readFileSync(ENTRY_POINT_FILENAME).toString();
} catch (e) {
// Read from template script
entry_js = fs.readFileSync(__dirname + '/../templates/' + ENTRY_POINT_FILENAME + '.tmpl').toString() + '\n';
}
return entry_js;
} | [
"function",
"generateCodeEntryJs",
"(",
"config",
")",
"{",
"// Read the entry point script",
"var",
"entry_js",
"=",
"null",
";",
"try",
"{",
"// Read from current script",
"entry_js",
"=",
"fs",
".",
"readFileSync",
"(",
"ENTRY_POINT_FILENAME",
")",
".",
"toString",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// Read from template script",
"entry_js",
"=",
"fs",
".",
"readFileSync",
"(",
"__dirname",
"+",
"'/../templates/'",
"+",
"ENTRY_POINT_FILENAME",
"+",
"'.tmpl'",
")",
".",
"toString",
"(",
")",
"+",
"'\\n'",
";",
"}",
"return",
"entry_js",
";",
"}"
] | Generate the source code for entory point
@param {Object} config Device configuration
@return {String} Source code | [
"Generate",
"the",
"source",
"code",
"for",
"entory",
"point"
] | 50d35aca96db3a07a3272f1765a660ea893735ce | https://github.com/odentools/denhub-device/blob/50d35aca96db3a07a3272f1765a660ea893735ce/scripts/generator.js#L429-L443 |
54,891 | odentools/denhub-device | scripts/generator.js | generateCodeHandlerJs | function generateCodeHandlerJs (config) {
// Read the handler script
var handler_js = null;
try {
// Read from current script
handler_js = fs.readFileSync(HANDLER_FILENAME).toString();
} catch (e) {
// Read from template script
handler_js = fs.readFileSync(__dirname + '/../templates/' + HANDLER_FILENAME + '.tmpl').toString();
}
// Iterate the each commands
for (var cmd_name in config.commands) {
if (!cmd_name.match(/^[a-zA-Z][a-zA-Z0-9]+$/)) {
throw new Error('Defined method name is invalid format: ' + cmd_name);
}
if (handler_js.indexOf(cmd_name) != -1) { // handler for this command was written
continue; // skip
}
// Make a handler for this command
var cmd = config.commands[cmd_name];
var js_func = '\n\n\
/**\n\
* %cmdDescription%\n\
* @param {Object} args Arguments of the received command\n\
* @param {Function} cb_runner Callback runner for response\n\
* @return {Boolean} if returns true, handler indicates won\'t use the callback \n\
*/\n\
CommandsHandler.prototype.' + cmd_name + ' = function (args, cb_runner) {\n\
\t\n';
// To align the line length of argument examples
var cmd_args = cmd.arguments || cmd.args || [];
var longest_length_of_arg_name = 0;
for (var name_ in cmd_args) {
if (longest_length_of_arg_name < name_.length) longest_length_of_arg_name = name_.length;
}
// Generate the argument examples
for (var name in cmd_args) {
// Generate an example
var line = '\tthis.logger.log(args.' + name + ');';
// Generate a comment
var comment_spaces = new String(' ');
for (var i = 0, l = longest_length_of_arg_name - name.length; i < l; i++) {
comment_spaces += ' ';
}
var comment = '// ' + cmd_args[name];
js_func += line + comment_spaces + comment + '\n';
}
if (0 < Object.keys(cmd_args).length) {
js_func += '\t\n';
}
js_func += '\tcb_runner.send(null, \'OKAY\');\n\t\n\};\n';
// Replace the command placeholders of the commands handler script
js_func = js_func.replace(/\%cmdName\%/g, cmd_name);
if (cmd.description) {
js_func = js_func.replace(/\%cmdDescription\%/g, cmd.description);
}
// Done
handler_js += js_func;
}
// Replace the placeholders (e.g. %deviceType%) of whole of commands handler script
for (var config_key in config) {
handler_js = handler_js.replace(new RegExp('\\%' + config_key + '\\%', 'g'), config[config_key]);
}
// Append the module.exports
if (!handler_js.match(/module\.exports = CommandsHandler;/)) {
handler_js += '\n\nmodule.exports = CommandsHandler;\n';
}
return handler_js;
} | javascript | function generateCodeHandlerJs (config) {
// Read the handler script
var handler_js = null;
try {
// Read from current script
handler_js = fs.readFileSync(HANDLER_FILENAME).toString();
} catch (e) {
// Read from template script
handler_js = fs.readFileSync(__dirname + '/../templates/' + HANDLER_FILENAME + '.tmpl').toString();
}
// Iterate the each commands
for (var cmd_name in config.commands) {
if (!cmd_name.match(/^[a-zA-Z][a-zA-Z0-9]+$/)) {
throw new Error('Defined method name is invalid format: ' + cmd_name);
}
if (handler_js.indexOf(cmd_name) != -1) { // handler for this command was written
continue; // skip
}
// Make a handler for this command
var cmd = config.commands[cmd_name];
var js_func = '\n\n\
/**\n\
* %cmdDescription%\n\
* @param {Object} args Arguments of the received command\n\
* @param {Function} cb_runner Callback runner for response\n\
* @return {Boolean} if returns true, handler indicates won\'t use the callback \n\
*/\n\
CommandsHandler.prototype.' + cmd_name + ' = function (args, cb_runner) {\n\
\t\n';
// To align the line length of argument examples
var cmd_args = cmd.arguments || cmd.args || [];
var longest_length_of_arg_name = 0;
for (var name_ in cmd_args) {
if (longest_length_of_arg_name < name_.length) longest_length_of_arg_name = name_.length;
}
// Generate the argument examples
for (var name in cmd_args) {
// Generate an example
var line = '\tthis.logger.log(args.' + name + ');';
// Generate a comment
var comment_spaces = new String(' ');
for (var i = 0, l = longest_length_of_arg_name - name.length; i < l; i++) {
comment_spaces += ' ';
}
var comment = '// ' + cmd_args[name];
js_func += line + comment_spaces + comment + '\n';
}
if (0 < Object.keys(cmd_args).length) {
js_func += '\t\n';
}
js_func += '\tcb_runner.send(null, \'OKAY\');\n\t\n\};\n';
// Replace the command placeholders of the commands handler script
js_func = js_func.replace(/\%cmdName\%/g, cmd_name);
if (cmd.description) {
js_func = js_func.replace(/\%cmdDescription\%/g, cmd.description);
}
// Done
handler_js += js_func;
}
// Replace the placeholders (e.g. %deviceType%) of whole of commands handler script
for (var config_key in config) {
handler_js = handler_js.replace(new RegExp('\\%' + config_key + '\\%', 'g'), config[config_key]);
}
// Append the module.exports
if (!handler_js.match(/module\.exports = CommandsHandler;/)) {
handler_js += '\n\nmodule.exports = CommandsHandler;\n';
}
return handler_js;
} | [
"function",
"generateCodeHandlerJs",
"(",
"config",
")",
"{",
"// Read the handler script",
"var",
"handler_js",
"=",
"null",
";",
"try",
"{",
"// Read from current script",
"handler_js",
"=",
"fs",
".",
"readFileSync",
"(",
"HANDLER_FILENAME",
")",
".",
"toString",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// Read from template script",
"handler_js",
"=",
"fs",
".",
"readFileSync",
"(",
"__dirname",
"+",
"'/../templates/'",
"+",
"HANDLER_FILENAME",
"+",
"'.tmpl'",
")",
".",
"toString",
"(",
")",
";",
"}",
"// Iterate the each commands",
"for",
"(",
"var",
"cmd_name",
"in",
"config",
".",
"commands",
")",
"{",
"if",
"(",
"!",
"cmd_name",
".",
"match",
"(",
"/",
"^[a-zA-Z][a-zA-Z0-9]+$",
"/",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Defined method name is invalid format: '",
"+",
"cmd_name",
")",
";",
"}",
"if",
"(",
"handler_js",
".",
"indexOf",
"(",
"cmd_name",
")",
"!=",
"-",
"1",
")",
"{",
"// handler for this command was written",
"continue",
";",
"// skip",
"}",
"// Make a handler for this command",
"var",
"cmd",
"=",
"config",
".",
"commands",
"[",
"cmd_name",
"]",
";",
"var",
"js_func",
"=",
"'\\n\\n\\\n/**\\n\\\n* %cmdDescription%\\n\\\n* @param {Object} args Arguments of the received command\\n\\\n* @param {Function} cb_runner Callback runner for response\\n\\\n* @return {Boolean} if returns true, handler indicates won\\'t use the callback \\n\\\n*/\\n\\\nCommandsHandler.prototype.'",
"+",
"cmd_name",
"+",
"' = function (args, cb_runner) {\\n\\\n\\t\\n'",
";",
"// To align the line length of argument examples",
"var",
"cmd_args",
"=",
"cmd",
".",
"arguments",
"||",
"cmd",
".",
"args",
"||",
"[",
"]",
";",
"var",
"longest_length_of_arg_name",
"=",
"0",
";",
"for",
"(",
"var",
"name_",
"in",
"cmd_args",
")",
"{",
"if",
"(",
"longest_length_of_arg_name",
"<",
"name_",
".",
"length",
")",
"longest_length_of_arg_name",
"=",
"name_",
".",
"length",
";",
"}",
"// Generate the argument examples",
"for",
"(",
"var",
"name",
"in",
"cmd_args",
")",
"{",
"// Generate an example",
"var",
"line",
"=",
"'\\tthis.logger.log(args.'",
"+",
"name",
"+",
"');'",
";",
"// Generate a comment",
"var",
"comment_spaces",
"=",
"new",
"String",
"(",
"' '",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"longest_length_of_arg_name",
"-",
"name",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"comment_spaces",
"+=",
"' '",
";",
"}",
"var",
"comment",
"=",
"'// '",
"+",
"cmd_args",
"[",
"name",
"]",
";",
"js_func",
"+=",
"line",
"+",
"comment_spaces",
"+",
"comment",
"+",
"'\\n'",
";",
"}",
"if",
"(",
"0",
"<",
"Object",
".",
"keys",
"(",
"cmd_args",
")",
".",
"length",
")",
"{",
"js_func",
"+=",
"'\\t\\n'",
";",
"}",
"js_func",
"+=",
"'\\tcb_runner.send(null, \\'OKAY\\');\\n\\t\\n\\};\\n'",
";",
"// Replace the command placeholders of the commands handler script",
"js_func",
"=",
"js_func",
".",
"replace",
"(",
"/",
"\\%cmdName\\%",
"/",
"g",
",",
"cmd_name",
")",
";",
"if",
"(",
"cmd",
".",
"description",
")",
"{",
"js_func",
"=",
"js_func",
".",
"replace",
"(",
"/",
"\\%cmdDescription\\%",
"/",
"g",
",",
"cmd",
".",
"description",
")",
";",
"}",
"// Done",
"handler_js",
"+=",
"js_func",
";",
"}",
"// Replace the placeholders (e.g. %deviceType%) of whole of commands handler script",
"for",
"(",
"var",
"config_key",
"in",
"config",
")",
"{",
"handler_js",
"=",
"handler_js",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'\\\\%'",
"+",
"config_key",
"+",
"'\\\\%'",
",",
"'g'",
")",
",",
"config",
"[",
"config_key",
"]",
")",
";",
"}",
"// Append the module.exports",
"if",
"(",
"!",
"handler_js",
".",
"match",
"(",
"/",
"module\\.exports = CommandsHandler;",
"/",
")",
")",
"{",
"handler_js",
"+=",
"'\\n\\nmodule.exports = CommandsHandler;\\n'",
";",
"}",
"return",
"handler_js",
";",
"}"
] | Generate the source code for commands handler
@param {Object} config Device configuration
@return {String} Source code | [
"Generate",
"the",
"source",
"code",
"for",
"commands",
"handler"
] | 50d35aca96db3a07a3272f1765a660ea893735ce | https://github.com/odentools/denhub-device/blob/50d35aca96db3a07a3272f1765a660ea893735ce/scripts/generator.js#L451-L539 |
54,892 | odentools/denhub-device | scripts/generator.js | generatePackageJson | function generatePackageJson (config) {
// Read the user's package.json
var user_file;
try {
// Read from current file
user_file = fs.readFileSync('./package.json').toString();
} catch (e) {
user_file = null;
}
// Parse the user's package.json
var user_json = null;
if (user_file) {
try {
user_json = JSON.parse(user_file);
} catch (e) {
console.log(colors.bold.red('Your package.json was invalid!\n\
We skipped the merging of your package.json with template.'));
console.log(user_json);
return null;
}
} else {
user_json = {};
}
// Read the template package.json
var tmpl_file = fs.readFileSync(__dirname + '/../templates/package.json.tmpl').toString();
// Replace the placeholders (e.g. %deviceType%) of whole of template
for (var config_key in config) {
tmpl_file = tmpl_file.replace(new RegExp('\\%' + config_key + '\\%', 'g'), config[config_key]);
}
tmpl_file = tmpl_file.replace(new RegExp('\\%libVersion\\%', 'g'), helper.getPackageInfo().version);
// Parse the template package.json
var tmpl_json = null;
try {
tmpl_json = JSON.parse(tmpl_file);
} catch (e) {
console.error('Could not parse the template file:\n' + tmpl_file + '\n' + e.stack.toString());
process.exit(0);
}
// Merge the fields with template package.json
for (var key in tmpl_json) {
if (user_json[key] == null) {
user_json[key] = tmpl_json[key];
} else if (helper.isType(user_json[key], 'Object')) {
for (var key_ in tmpl_json[key]) {
if (user_json[key][key_] == null) user_json[key][key_] = tmpl_json[key][key_];
}
}
}
// Done
return JSON.stringify(user_json, null, ' ');
} | javascript | function generatePackageJson (config) {
// Read the user's package.json
var user_file;
try {
// Read from current file
user_file = fs.readFileSync('./package.json').toString();
} catch (e) {
user_file = null;
}
// Parse the user's package.json
var user_json = null;
if (user_file) {
try {
user_json = JSON.parse(user_file);
} catch (e) {
console.log(colors.bold.red('Your package.json was invalid!\n\
We skipped the merging of your package.json with template.'));
console.log(user_json);
return null;
}
} else {
user_json = {};
}
// Read the template package.json
var tmpl_file = fs.readFileSync(__dirname + '/../templates/package.json.tmpl').toString();
// Replace the placeholders (e.g. %deviceType%) of whole of template
for (var config_key in config) {
tmpl_file = tmpl_file.replace(new RegExp('\\%' + config_key + '\\%', 'g'), config[config_key]);
}
tmpl_file = tmpl_file.replace(new RegExp('\\%libVersion\\%', 'g'), helper.getPackageInfo().version);
// Parse the template package.json
var tmpl_json = null;
try {
tmpl_json = JSON.parse(tmpl_file);
} catch (e) {
console.error('Could not parse the template file:\n' + tmpl_file + '\n' + e.stack.toString());
process.exit(0);
}
// Merge the fields with template package.json
for (var key in tmpl_json) {
if (user_json[key] == null) {
user_json[key] = tmpl_json[key];
} else if (helper.isType(user_json[key], 'Object')) {
for (var key_ in tmpl_json[key]) {
if (user_json[key][key_] == null) user_json[key][key_] = tmpl_json[key][key_];
}
}
}
// Done
return JSON.stringify(user_json, null, ' ');
} | [
"function",
"generatePackageJson",
"(",
"config",
")",
"{",
"// Read the user's package.json",
"var",
"user_file",
";",
"try",
"{",
"// Read from current file",
"user_file",
"=",
"fs",
".",
"readFileSync",
"(",
"'./package.json'",
")",
".",
"toString",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"user_file",
"=",
"null",
";",
"}",
"// Parse the user's package.json",
"var",
"user_json",
"=",
"null",
";",
"if",
"(",
"user_file",
")",
"{",
"try",
"{",
"user_json",
"=",
"JSON",
".",
"parse",
"(",
"user_file",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"colors",
".",
"bold",
".",
"red",
"(",
"'Your package.json was invalid!\\n\\\n\tWe skipped the merging of your package.json with template.'",
")",
")",
";",
"console",
".",
"log",
"(",
"user_json",
")",
";",
"return",
"null",
";",
"}",
"}",
"else",
"{",
"user_json",
"=",
"{",
"}",
";",
"}",
"// Read the template package.json",
"var",
"tmpl_file",
"=",
"fs",
".",
"readFileSync",
"(",
"__dirname",
"+",
"'/../templates/package.json.tmpl'",
")",
".",
"toString",
"(",
")",
";",
"// Replace the placeholders (e.g. %deviceType%) of whole of template",
"for",
"(",
"var",
"config_key",
"in",
"config",
")",
"{",
"tmpl_file",
"=",
"tmpl_file",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'\\\\%'",
"+",
"config_key",
"+",
"'\\\\%'",
",",
"'g'",
")",
",",
"config",
"[",
"config_key",
"]",
")",
";",
"}",
"tmpl_file",
"=",
"tmpl_file",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'\\\\%libVersion\\\\%'",
",",
"'g'",
")",
",",
"helper",
".",
"getPackageInfo",
"(",
")",
".",
"version",
")",
";",
"// Parse the template package.json",
"var",
"tmpl_json",
"=",
"null",
";",
"try",
"{",
"tmpl_json",
"=",
"JSON",
".",
"parse",
"(",
"tmpl_file",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"error",
"(",
"'Could not parse the template file:\\n'",
"+",
"tmpl_file",
"+",
"'\\n'",
"+",
"e",
".",
"stack",
".",
"toString",
"(",
")",
")",
";",
"process",
".",
"exit",
"(",
"0",
")",
";",
"}",
"// Merge the fields with template package.json",
"for",
"(",
"var",
"key",
"in",
"tmpl_json",
")",
"{",
"if",
"(",
"user_json",
"[",
"key",
"]",
"==",
"null",
")",
"{",
"user_json",
"[",
"key",
"]",
"=",
"tmpl_json",
"[",
"key",
"]",
";",
"}",
"else",
"if",
"(",
"helper",
".",
"isType",
"(",
"user_json",
"[",
"key",
"]",
",",
"'Object'",
")",
")",
"{",
"for",
"(",
"var",
"key_",
"in",
"tmpl_json",
"[",
"key",
"]",
")",
"{",
"if",
"(",
"user_json",
"[",
"key",
"]",
"[",
"key_",
"]",
"==",
"null",
")",
"user_json",
"[",
"key",
"]",
"[",
"key_",
"]",
"=",
"tmpl_json",
"[",
"key",
"]",
"[",
"key_",
"]",
";",
"}",
"}",
"}",
"// Done",
"return",
"JSON",
".",
"stringify",
"(",
"user_json",
",",
"null",
",",
"' '",
")",
";",
"}"
] | Generate the package.json
@param {Object} config Device configuration
@return {String} JSON code | [
"Generate",
"the",
"package",
".",
"json"
] | 50d35aca96db3a07a3272f1765a660ea893735ce | https://github.com/odentools/denhub-device/blob/50d35aca96db3a07a3272f1765a660ea893735ce/scripts/generator.js#L547-L605 |
54,893 | odentools/denhub-device | scripts/generator.js | execDependencyInstall | function execDependencyInstall () {
console.log('\nExecuting npm install command...');
return new Promise(function(resolve, reject){
var child = require('child_process').spawn('npm', ['install'], {
cwd: process.cwd,
detached: false,
env: process.env,
stdio: [process.stdin, process.stdout, process.stderr]
});
child.on('error', function (error) {
console.error(colors.bold.red('ERROR: Could not install the required modules:'));
console.error(error.stack.toString());
process.exit(255);
});
child.on('close', function (exit_code) {
if (exit_code !== 0) {
console.error(colors.bold.red('\nERROR: npm install has been failed.'));
process.exit(255);
}
console.log('\nnpm install has been completed.\n\n');
resolve(true);
});
});
} | javascript | function execDependencyInstall () {
console.log('\nExecuting npm install command...');
return new Promise(function(resolve, reject){
var child = require('child_process').spawn('npm', ['install'], {
cwd: process.cwd,
detached: false,
env: process.env,
stdio: [process.stdin, process.stdout, process.stderr]
});
child.on('error', function (error) {
console.error(colors.bold.red('ERROR: Could not install the required modules:'));
console.error(error.stack.toString());
process.exit(255);
});
child.on('close', function (exit_code) {
if (exit_code !== 0) {
console.error(colors.bold.red('\nERROR: npm install has been failed.'));
process.exit(255);
}
console.log('\nnpm install has been completed.\n\n');
resolve(true);
});
});
} | [
"function",
"execDependencyInstall",
"(",
")",
"{",
"console",
".",
"log",
"(",
"'\\nExecuting npm install command...'",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"child",
"=",
"require",
"(",
"'child_process'",
")",
".",
"spawn",
"(",
"'npm'",
",",
"[",
"'install'",
"]",
",",
"{",
"cwd",
":",
"process",
".",
"cwd",
",",
"detached",
":",
"false",
",",
"env",
":",
"process",
".",
"env",
",",
"stdio",
":",
"[",
"process",
".",
"stdin",
",",
"process",
".",
"stdout",
",",
"process",
".",
"stderr",
"]",
"}",
")",
";",
"child",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"error",
")",
"{",
"console",
".",
"error",
"(",
"colors",
".",
"bold",
".",
"red",
"(",
"'ERROR: Could not install the required modules:'",
")",
")",
";",
"console",
".",
"error",
"(",
"error",
".",
"stack",
".",
"toString",
"(",
")",
")",
";",
"process",
".",
"exit",
"(",
"255",
")",
";",
"}",
")",
";",
"child",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
"exit_code",
")",
"{",
"if",
"(",
"exit_code",
"!==",
"0",
")",
"{",
"console",
".",
"error",
"(",
"colors",
".",
"bold",
".",
"red",
"(",
"'\\nERROR: npm install has been failed.'",
")",
")",
";",
"process",
".",
"exit",
"(",
"255",
")",
";",
"}",
"console",
".",
"log",
"(",
"'\\nnpm install has been completed.\\n\\n'",
")",
";",
"resolve",
"(",
"true",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Install the dependency modules with using npm command
@return {Boolean} Whether the install has been successful | [
"Install",
"the",
"dependency",
"modules",
"with",
"using",
"npm",
"command"
] | 50d35aca96db3a07a3272f1765a660ea893735ce | https://github.com/odentools/denhub-device/blob/50d35aca96db3a07a3272f1765a660ea893735ce/scripts/generator.js#L612-L642 |
54,894 | odentools/denhub-device | scripts/generator.js | startCmdEditor | function startCmdEditor (config, is_skip_header) {
if (!is_skip_header) {
console.log(colors.bold('--------------- Command Editor ---------------'));
}
// Show a prompt for choose the mode
var promise = inquirer.prompt([{
type: 'list',
name: 'mode',
message: 'What you want to do ?',
choices: [
'Show commands list', 'Add new command', 'Edit command', 'Delete command'
]
}]);
promise.then(function (answer) {
var mode = answer.mode;
var promise = null;
if (mode == 'Add new command') {
promise = addCommandOnCmdEditor(config);
} else if (mode == 'Edit command') {
promise = editCommandOnCmdEditor(config);
} else if (mode == 'Delete command') {
promise = deleteCommandOnCmdEditor(config);
} else if (mode == 'Show commands list') {
promise = showCommandsOnCmdEditor(config);
}
if (!promise) {
startCmdEditor(config, true);
return;
}
promise.then(function () {
startCmdEditor(config, true);
});
});
} | javascript | function startCmdEditor (config, is_skip_header) {
if (!is_skip_header) {
console.log(colors.bold('--------------- Command Editor ---------------'));
}
// Show a prompt for choose the mode
var promise = inquirer.prompt([{
type: 'list',
name: 'mode',
message: 'What you want to do ?',
choices: [
'Show commands list', 'Add new command', 'Edit command', 'Delete command'
]
}]);
promise.then(function (answer) {
var mode = answer.mode;
var promise = null;
if (mode == 'Add new command') {
promise = addCommandOnCmdEditor(config);
} else if (mode == 'Edit command') {
promise = editCommandOnCmdEditor(config);
} else if (mode == 'Delete command') {
promise = deleteCommandOnCmdEditor(config);
} else if (mode == 'Show commands list') {
promise = showCommandsOnCmdEditor(config);
}
if (!promise) {
startCmdEditor(config, true);
return;
}
promise.then(function () {
startCmdEditor(config, true);
});
});
} | [
"function",
"startCmdEditor",
"(",
"config",
",",
"is_skip_header",
")",
"{",
"if",
"(",
"!",
"is_skip_header",
")",
"{",
"console",
".",
"log",
"(",
"colors",
".",
"bold",
"(",
"'--------------- Command Editor ---------------'",
")",
")",
";",
"}",
"// Show a prompt for choose the mode",
"var",
"promise",
"=",
"inquirer",
".",
"prompt",
"(",
"[",
"{",
"type",
":",
"'list'",
",",
"name",
":",
"'mode'",
",",
"message",
":",
"'What you want to do ?'",
",",
"choices",
":",
"[",
"'Show commands list'",
",",
"'Add new command'",
",",
"'Edit command'",
",",
"'Delete command'",
"]",
"}",
"]",
")",
";",
"promise",
".",
"then",
"(",
"function",
"(",
"answer",
")",
"{",
"var",
"mode",
"=",
"answer",
".",
"mode",
";",
"var",
"promise",
"=",
"null",
";",
"if",
"(",
"mode",
"==",
"'Add new command'",
")",
"{",
"promise",
"=",
"addCommandOnCmdEditor",
"(",
"config",
")",
";",
"}",
"else",
"if",
"(",
"mode",
"==",
"'Edit command'",
")",
"{",
"promise",
"=",
"editCommandOnCmdEditor",
"(",
"config",
")",
";",
"}",
"else",
"if",
"(",
"mode",
"==",
"'Delete command'",
")",
"{",
"promise",
"=",
"deleteCommandOnCmdEditor",
"(",
"config",
")",
";",
"}",
"else",
"if",
"(",
"mode",
"==",
"'Show commands list'",
")",
"{",
"promise",
"=",
"showCommandsOnCmdEditor",
"(",
"config",
")",
";",
"}",
"if",
"(",
"!",
"promise",
")",
"{",
"startCmdEditor",
"(",
"config",
",",
"true",
")",
";",
"return",
";",
"}",
"promise",
".",
"then",
"(",
"function",
"(",
")",
"{",
"startCmdEditor",
"(",
"config",
",",
"true",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Start the command editor
@param {Object} config Current configuration
@param {Boolean} is_skip_header Whether the header should be skipped | [
"Start",
"the",
"command",
"editor"
] | 50d35aca96db3a07a3272f1765a660ea893735ce | https://github.com/odentools/denhub-device/blob/50d35aca96db3a07a3272f1765a660ea893735ce/scripts/generator.js#L650-L692 |
54,895 | odentools/denhub-device | scripts/generator.js | showCommandsOnCmdEditor | function showCommandsOnCmdEditor (config) {
console.log(colors.bold('\nAvailable Commands for ' + config.deviceName + ':\n'));
// Iterate the each commands
var commands = config.commands || {};
if (Object.keys(commands).length == 0) {
console.log ('\nThere is no command.');
} else {
for (var name in commands) {
var desc = commands[name].description || '';
console.log(colors.bold('\n' + name + '') + '\n ' + desc + '\n');
// Iterate the each arguments
var args = commands[name].args || {};
if (Object.keys(args).length == 0) {
console.log ('\tThe arguments of this command are not defined');
} else {
for (var arg_name in args) {
var arg_spec = args[arg_name] || '';
console.log('\t* ' + arg_name + ' - ' + arg_spec);
}
}
}
}
console.log('\n');
// Done
return new Promise(function (resolve, reject) {
resolve();
});
} | javascript | function showCommandsOnCmdEditor (config) {
console.log(colors.bold('\nAvailable Commands for ' + config.deviceName + ':\n'));
// Iterate the each commands
var commands = config.commands || {};
if (Object.keys(commands).length == 0) {
console.log ('\nThere is no command.');
} else {
for (var name in commands) {
var desc = commands[name].description || '';
console.log(colors.bold('\n' + name + '') + '\n ' + desc + '\n');
// Iterate the each arguments
var args = commands[name].args || {};
if (Object.keys(args).length == 0) {
console.log ('\tThe arguments of this command are not defined');
} else {
for (var arg_name in args) {
var arg_spec = args[arg_name] || '';
console.log('\t* ' + arg_name + ' - ' + arg_spec);
}
}
}
}
console.log('\n');
// Done
return new Promise(function (resolve, reject) {
resolve();
});
} | [
"function",
"showCommandsOnCmdEditor",
"(",
"config",
")",
"{",
"console",
".",
"log",
"(",
"colors",
".",
"bold",
"(",
"'\\nAvailable Commands for '",
"+",
"config",
".",
"deviceName",
"+",
"':\\n'",
")",
")",
";",
"// Iterate the each commands",
"var",
"commands",
"=",
"config",
".",
"commands",
"||",
"{",
"}",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"commands",
")",
".",
"length",
"==",
"0",
")",
"{",
"console",
".",
"log",
"(",
"'\\nThere is no command.'",
")",
";",
"}",
"else",
"{",
"for",
"(",
"var",
"name",
"in",
"commands",
")",
"{",
"var",
"desc",
"=",
"commands",
"[",
"name",
"]",
".",
"description",
"||",
"''",
";",
"console",
".",
"log",
"(",
"colors",
".",
"bold",
"(",
"'\\n'",
"+",
"name",
"+",
"''",
")",
"+",
"'\\n '",
"+",
"desc",
"+",
"'\\n'",
")",
";",
"// Iterate the each arguments",
"var",
"args",
"=",
"commands",
"[",
"name",
"]",
".",
"args",
"||",
"{",
"}",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"args",
")",
".",
"length",
"==",
"0",
")",
"{",
"console",
".",
"log",
"(",
"'\\tThe arguments of this command are not defined'",
")",
";",
"}",
"else",
"{",
"for",
"(",
"var",
"arg_name",
"in",
"args",
")",
"{",
"var",
"arg_spec",
"=",
"args",
"[",
"arg_name",
"]",
"||",
"''",
";",
"console",
".",
"log",
"(",
"'\\t* '",
"+",
"arg_name",
"+",
"' - '",
"+",
"arg_spec",
")",
";",
"}",
"}",
"}",
"}",
"console",
".",
"log",
"(",
"'\\n'",
")",
";",
"// Done",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}"
] | Command Editor - Show a list of the commands
@param {Object} config Current configuration
@return {Promise} | [
"Command",
"Editor",
"-",
"Show",
"a",
"list",
"of",
"the",
"commands"
] | 50d35aca96db3a07a3272f1765a660ea893735ce | https://github.com/odentools/denhub-device/blob/50d35aca96db3a07a3272f1765a660ea893735ce/scripts/generator.js#L700-L734 |
54,896 | odentools/denhub-device | scripts/generator.js | addCommandOnCmdEditor | function addCommandOnCmdEditor (config) {
var cmd_name = null;
var promise = inquirer.prompt([{
type: 'input',
name: 'cmdName',
message: 'What is name of a command (e.g. setMotorPower) ?',
validate: function (value) {
if (value.length == 0) return true;
if (config.commands[value] != null) return 'This command name has already existed.';
if (!value.match(/^[A-Za-z0-9_]+$/)) return 'Available characters for argument name: A-Z, a-z, 0-9, underscore.\n\
Or, if you want to cancel, please press the enter key left empty.';
return true;
}
}]).then(function (answer) {
cmd_name = answer.cmdName || null;
if (cmd_name == null || cmd_name.length == 0) {
return null;
}
return inquirer.prompt([{
type: 'input',
name: 'cmdDesc',
message: 'What is description of ' + cmd_name + ' command ?'
}]);
}).then(function (answer) {
if (cmd_name == null) return false;
var commands = config.commands || {};
commands[cmd_name] = {
description: answer.cmdDesc || null,
args: {}
};
// Done
console.log(colors.bold.green('This command has been created: ' + cmd_name));
// Save to the commands file
console.log('\nWriting to ' + process.cwd() + '/' + COMMANDS_FILENAME);
fs.writeFileSync(COMMANDS_FILENAME, JSON.stringify(config.commands));
console.log('Writing has been completed.\n\n');
return true;
});
return promise;
} | javascript | function addCommandOnCmdEditor (config) {
var cmd_name = null;
var promise = inquirer.prompt([{
type: 'input',
name: 'cmdName',
message: 'What is name of a command (e.g. setMotorPower) ?',
validate: function (value) {
if (value.length == 0) return true;
if (config.commands[value] != null) return 'This command name has already existed.';
if (!value.match(/^[A-Za-z0-9_]+$/)) return 'Available characters for argument name: A-Z, a-z, 0-9, underscore.\n\
Or, if you want to cancel, please press the enter key left empty.';
return true;
}
}]).then(function (answer) {
cmd_name = answer.cmdName || null;
if (cmd_name == null || cmd_name.length == 0) {
return null;
}
return inquirer.prompt([{
type: 'input',
name: 'cmdDesc',
message: 'What is description of ' + cmd_name + ' command ?'
}]);
}).then(function (answer) {
if (cmd_name == null) return false;
var commands = config.commands || {};
commands[cmd_name] = {
description: answer.cmdDesc || null,
args: {}
};
// Done
console.log(colors.bold.green('This command has been created: ' + cmd_name));
// Save to the commands file
console.log('\nWriting to ' + process.cwd() + '/' + COMMANDS_FILENAME);
fs.writeFileSync(COMMANDS_FILENAME, JSON.stringify(config.commands));
console.log('Writing has been completed.\n\n');
return true;
});
return promise;
} | [
"function",
"addCommandOnCmdEditor",
"(",
"config",
")",
"{",
"var",
"cmd_name",
"=",
"null",
";",
"var",
"promise",
"=",
"inquirer",
".",
"prompt",
"(",
"[",
"{",
"type",
":",
"'input'",
",",
"name",
":",
"'cmdName'",
",",
"message",
":",
"'What is name of a command (e.g. setMotorPower) ?'",
",",
"validate",
":",
"function",
"(",
"value",
")",
"{",
"if",
"(",
"value",
".",
"length",
"==",
"0",
")",
"return",
"true",
";",
"if",
"(",
"config",
".",
"commands",
"[",
"value",
"]",
"!=",
"null",
")",
"return",
"'This command name has already existed.'",
";",
"if",
"(",
"!",
"value",
".",
"match",
"(",
"/",
"^[A-Za-z0-9_]+$",
"/",
")",
")",
"return",
"'Available characters for argument name: A-Z, a-z, 0-9, underscore.\\n\\\nOr, if you want to cancel, please press the enter key left empty.'",
";",
"return",
"true",
";",
"}",
"}",
"]",
")",
".",
"then",
"(",
"function",
"(",
"answer",
")",
"{",
"cmd_name",
"=",
"answer",
".",
"cmdName",
"||",
"null",
";",
"if",
"(",
"cmd_name",
"==",
"null",
"||",
"cmd_name",
".",
"length",
"==",
"0",
")",
"{",
"return",
"null",
";",
"}",
"return",
"inquirer",
".",
"prompt",
"(",
"[",
"{",
"type",
":",
"'input'",
",",
"name",
":",
"'cmdDesc'",
",",
"message",
":",
"'What is description of '",
"+",
"cmd_name",
"+",
"' command ?'",
"}",
"]",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"answer",
")",
"{",
"if",
"(",
"cmd_name",
"==",
"null",
")",
"return",
"false",
";",
"var",
"commands",
"=",
"config",
".",
"commands",
"||",
"{",
"}",
";",
"commands",
"[",
"cmd_name",
"]",
"=",
"{",
"description",
":",
"answer",
".",
"cmdDesc",
"||",
"null",
",",
"args",
":",
"{",
"}",
"}",
";",
"// Done",
"console",
".",
"log",
"(",
"colors",
".",
"bold",
".",
"green",
"(",
"'This command has been created: '",
"+",
"cmd_name",
")",
")",
";",
"// Save to the commands file",
"console",
".",
"log",
"(",
"'\\nWriting to '",
"+",
"process",
".",
"cwd",
"(",
")",
"+",
"'/'",
"+",
"COMMANDS_FILENAME",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"COMMANDS_FILENAME",
",",
"JSON",
".",
"stringify",
"(",
"config",
".",
"commands",
")",
")",
";",
"console",
".",
"log",
"(",
"'Writing has been completed.\\n\\n'",
")",
";",
"return",
"true",
";",
"}",
")",
";",
"return",
"promise",
";",
"}"
] | Command Editor - Add a command
@param {Object} config Current configuration
@return {Promise} | [
"Command",
"Editor",
"-",
"Add",
"a",
"command"
] | 50d35aca96db3a07a3272f1765a660ea893735ce | https://github.com/odentools/denhub-device/blob/50d35aca96db3a07a3272f1765a660ea893735ce/scripts/generator.js#L742-L795 |
54,897 | odentools/denhub-device | scripts/generator.js | deleteCommandOnCmdEditor | function deleteCommandOnCmdEditor (config) {
var commands = config.commands || {};
var command_names = Object.keys(commands);
command_names.unshift('<< Cancel');
var promise = inquirer.prompt([{
type: 'list',
name: 'cmdName',
message: 'Choose the command you want to delete',
choices: command_names
}]);
return promise.then(function (answer) {
if (answer.cmdName == '<< Cancel') {
return false;
}
delete config.commands[answer.cmdName];
// Done
console.log(colors.bold.green('\n\nThis command has been deleted: ' + answer.cmdName));
// Save to the commands file
console.log('\nWriting to ' + process.cwd() + '/' + COMMANDS_FILENAME);
fs.writeFileSync(COMMANDS_FILENAME, JSON.stringify(config.commands));
console.log('Writing has been completed.\n\n');
return true;
});
} | javascript | function deleteCommandOnCmdEditor (config) {
var commands = config.commands || {};
var command_names = Object.keys(commands);
command_names.unshift('<< Cancel');
var promise = inquirer.prompt([{
type: 'list',
name: 'cmdName',
message: 'Choose the command you want to delete',
choices: command_names
}]);
return promise.then(function (answer) {
if (answer.cmdName == '<< Cancel') {
return false;
}
delete config.commands[answer.cmdName];
// Done
console.log(colors.bold.green('\n\nThis command has been deleted: ' + answer.cmdName));
// Save to the commands file
console.log('\nWriting to ' + process.cwd() + '/' + COMMANDS_FILENAME);
fs.writeFileSync(COMMANDS_FILENAME, JSON.stringify(config.commands));
console.log('Writing has been completed.\n\n');
return true;
});
} | [
"function",
"deleteCommandOnCmdEditor",
"(",
"config",
")",
"{",
"var",
"commands",
"=",
"config",
".",
"commands",
"||",
"{",
"}",
";",
"var",
"command_names",
"=",
"Object",
".",
"keys",
"(",
"commands",
")",
";",
"command_names",
".",
"unshift",
"(",
"'<< Cancel'",
")",
";",
"var",
"promise",
"=",
"inquirer",
".",
"prompt",
"(",
"[",
"{",
"type",
":",
"'list'",
",",
"name",
":",
"'cmdName'",
",",
"message",
":",
"'Choose the command you want to delete'",
",",
"choices",
":",
"command_names",
"}",
"]",
")",
";",
"return",
"promise",
".",
"then",
"(",
"function",
"(",
"answer",
")",
"{",
"if",
"(",
"answer",
".",
"cmdName",
"==",
"'<< Cancel'",
")",
"{",
"return",
"false",
";",
"}",
"delete",
"config",
".",
"commands",
"[",
"answer",
".",
"cmdName",
"]",
";",
"// Done",
"console",
".",
"log",
"(",
"colors",
".",
"bold",
".",
"green",
"(",
"'\\n\\nThis command has been deleted: '",
"+",
"answer",
".",
"cmdName",
")",
")",
";",
"// Save to the commands file",
"console",
".",
"log",
"(",
"'\\nWriting to '",
"+",
"process",
".",
"cwd",
"(",
")",
"+",
"'/'",
"+",
"COMMANDS_FILENAME",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"COMMANDS_FILENAME",
",",
"JSON",
".",
"stringify",
"(",
"config",
".",
"commands",
")",
")",
";",
"console",
".",
"log",
"(",
"'Writing has been completed.\\n\\n'",
")",
";",
"return",
"true",
";",
"}",
")",
";",
"}"
] | Command Editor - Delete a command
@param {Object} config Current configuration
@return {Promise} | [
"Command",
"Editor",
"-",
"Delete",
"a",
"command"
] | 50d35aca96db3a07a3272f1765a660ea893735ce | https://github.com/odentools/denhub-device/blob/50d35aca96db3a07a3272f1765a660ea893735ce/scripts/generator.js#L803-L836 |
54,898 | gtriggiano/dnsmq-messagebus | src/PubConnection.js | connect | function connect (master) {
if (_socket && _socket._master.name === master.name) {
debug(`already connected to master ${master.name}`)
return
}
if (_connectingMaster && _connectingMaster.name === master.name) {
debug(`already connecting to master ${master.name}`)
return
}
_connectingMaster = master
let newSocket = _getSocket(master)
let _messagesToResend = []
let _onMessagePublished = (...args) => {
if (_socket) _messagesToResend.push(args)
}
_publishStream.on('message', _onMessagePublished)
debug(`connecting to ${master.name} at ${master.endpoint}`)
let connectionStart = Date.now()
const onSocketConnected = timingoutCallback((err) => {
_publishStream.removeListener('message', _onMessagePublished)
newSocket.unmonitor()
if (
err ||
!_connectingMaster ||
_connectingMaster.name === !master.name
) {
newSocket.close()
if (err) {
debug(`failed to connect to ${master.name} at ${master.endpoint}`)
disconnect()
}
return
}
_connectingMaster = null
let previousSocket = _socket
debug(`${previousSocket ? 'switched' : 'connected'} to ${master.name} at ${master.endpoint} in ${Date.now() - connectionStart} ms`)
_socket = newSocket
let totalMessagesToResend = _messagesToResend.length
if (totalMessagesToResend) {
debug(`resending ${totalMessagesToResend} messages published while transitioning`)
_messagesToResend.forEach(message => _socket.send(message))
}
if (previousSocket) {
previousSocket.close()
debug(`closed previous connection to ${previousSocket._master.name} at ${previousSocket._master.endpoint}`)
} else {
connection.emit('connect')
}
}, 500)
newSocket.once('connect', () => onSocketConnected())
return connection
} | javascript | function connect (master) {
if (_socket && _socket._master.name === master.name) {
debug(`already connected to master ${master.name}`)
return
}
if (_connectingMaster && _connectingMaster.name === master.name) {
debug(`already connecting to master ${master.name}`)
return
}
_connectingMaster = master
let newSocket = _getSocket(master)
let _messagesToResend = []
let _onMessagePublished = (...args) => {
if (_socket) _messagesToResend.push(args)
}
_publishStream.on('message', _onMessagePublished)
debug(`connecting to ${master.name} at ${master.endpoint}`)
let connectionStart = Date.now()
const onSocketConnected = timingoutCallback((err) => {
_publishStream.removeListener('message', _onMessagePublished)
newSocket.unmonitor()
if (
err ||
!_connectingMaster ||
_connectingMaster.name === !master.name
) {
newSocket.close()
if (err) {
debug(`failed to connect to ${master.name} at ${master.endpoint}`)
disconnect()
}
return
}
_connectingMaster = null
let previousSocket = _socket
debug(`${previousSocket ? 'switched' : 'connected'} to ${master.name} at ${master.endpoint} in ${Date.now() - connectionStart} ms`)
_socket = newSocket
let totalMessagesToResend = _messagesToResend.length
if (totalMessagesToResend) {
debug(`resending ${totalMessagesToResend} messages published while transitioning`)
_messagesToResend.forEach(message => _socket.send(message))
}
if (previousSocket) {
previousSocket.close()
debug(`closed previous connection to ${previousSocket._master.name} at ${previousSocket._master.endpoint}`)
} else {
connection.emit('connect')
}
}, 500)
newSocket.once('connect', () => onSocketConnected())
return connection
} | [
"function",
"connect",
"(",
"master",
")",
"{",
"if",
"(",
"_socket",
"&&",
"_socket",
".",
"_master",
".",
"name",
"===",
"master",
".",
"name",
")",
"{",
"debug",
"(",
"`",
"${",
"master",
".",
"name",
"}",
"`",
")",
"return",
"}",
"if",
"(",
"_connectingMaster",
"&&",
"_connectingMaster",
".",
"name",
"===",
"master",
".",
"name",
")",
"{",
"debug",
"(",
"`",
"${",
"master",
".",
"name",
"}",
"`",
")",
"return",
"}",
"_connectingMaster",
"=",
"master",
"let",
"newSocket",
"=",
"_getSocket",
"(",
"master",
")",
"let",
"_messagesToResend",
"=",
"[",
"]",
"let",
"_onMessagePublished",
"=",
"(",
"...",
"args",
")",
"=>",
"{",
"if",
"(",
"_socket",
")",
"_messagesToResend",
".",
"push",
"(",
"args",
")",
"}",
"_publishStream",
".",
"on",
"(",
"'message'",
",",
"_onMessagePublished",
")",
"debug",
"(",
"`",
"${",
"master",
".",
"name",
"}",
"${",
"master",
".",
"endpoint",
"}",
"`",
")",
"let",
"connectionStart",
"=",
"Date",
".",
"now",
"(",
")",
"const",
"onSocketConnected",
"=",
"timingoutCallback",
"(",
"(",
"err",
")",
"=>",
"{",
"_publishStream",
".",
"removeListener",
"(",
"'message'",
",",
"_onMessagePublished",
")",
"newSocket",
".",
"unmonitor",
"(",
")",
"if",
"(",
"err",
"||",
"!",
"_connectingMaster",
"||",
"_connectingMaster",
".",
"name",
"===",
"!",
"master",
".",
"name",
")",
"{",
"newSocket",
".",
"close",
"(",
")",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"`",
"${",
"master",
".",
"name",
"}",
"${",
"master",
".",
"endpoint",
"}",
"`",
")",
"disconnect",
"(",
")",
"}",
"return",
"}",
"_connectingMaster",
"=",
"null",
"let",
"previousSocket",
"=",
"_socket",
"debug",
"(",
"`",
"${",
"previousSocket",
"?",
"'switched'",
":",
"'connected'",
"}",
"${",
"master",
".",
"name",
"}",
"${",
"master",
".",
"endpoint",
"}",
"${",
"Date",
".",
"now",
"(",
")",
"-",
"connectionStart",
"}",
"`",
")",
"_socket",
"=",
"newSocket",
"let",
"totalMessagesToResend",
"=",
"_messagesToResend",
".",
"length",
"if",
"(",
"totalMessagesToResend",
")",
"{",
"debug",
"(",
"`",
"${",
"totalMessagesToResend",
"}",
"`",
")",
"_messagesToResend",
".",
"forEach",
"(",
"message",
"=>",
"_socket",
".",
"send",
"(",
"message",
")",
")",
"}",
"if",
"(",
"previousSocket",
")",
"{",
"previousSocket",
".",
"close",
"(",
")",
"debug",
"(",
"`",
"${",
"previousSocket",
".",
"_master",
".",
"name",
"}",
"${",
"previousSocket",
".",
"_master",
".",
"endpoint",
"}",
"`",
")",
"}",
"else",
"{",
"connection",
".",
"emit",
"(",
"'connect'",
")",
"}",
"}",
",",
"500",
")",
"newSocket",
".",
"once",
"(",
"'connect'",
",",
"(",
")",
"=>",
"onSocketConnected",
"(",
")",
")",
"return",
"connection",
"}"
] | creates a new pub socket and tries to connect it to the provided master;
after connection the socket is used to publish messages in the bus
and an eventual previous socket is closed
@param {object} master
@return {object} the publishConnection instance | [
"creates",
"a",
"new",
"pub",
"socket",
"and",
"tries",
"to",
"connect",
"it",
"to",
"the",
"provided",
"master",
";",
"after",
"connection",
"the",
"socket",
"is",
"used",
"to",
"publish",
"messages",
"in",
"the",
"bus",
"and",
"an",
"eventual",
"previous",
"socket",
"is",
"closed"
] | ab935cae537f8a7e61a6ed6fba247661281c9374 | https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/PubConnection.js#L48-L110 |
54,899 | gtriggiano/dnsmq-messagebus | src/PubConnection.js | disconnect | function disconnect () {
_connectingMaster = null
if (_socket) {
_socket.close()
_socket = null
debug('disconnected')
connection.emit('disconnect')
}
return connection
} | javascript | function disconnect () {
_connectingMaster = null
if (_socket) {
_socket.close()
_socket = null
debug('disconnected')
connection.emit('disconnect')
}
return connection
} | [
"function",
"disconnect",
"(",
")",
"{",
"_connectingMaster",
"=",
"null",
"if",
"(",
"_socket",
")",
"{",
"_socket",
".",
"close",
"(",
")",
"_socket",
"=",
"null",
"debug",
"(",
"'disconnected'",
")",
"connection",
".",
"emit",
"(",
"'disconnect'",
")",
"}",
"return",
"connection",
"}"
] | if present, closes the pub socket
@return {object} the publishConnection instance | [
"if",
"present",
"closes",
"the",
"pub",
"socket"
] | ab935cae537f8a7e61a6ed6fba247661281c9374 | https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/PubConnection.js#L115-L124 |
Subsets and Splits