repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
davidrayoussef/funcifyr | funcifyr.js | function(n) {
return function chunk(arg) {
if ( Array.isArray(arg) ) {
return arg.reduce((acc,_,i,a) => {
return i % n === 0 ? acc.concat( [a.slice(i, i + n)] ) : acc;
}, []);
}
else if ( typeof arg === 'string' ) {
return arg.match( new RegExp('.{1,' + n + '}', 'g') ) || [];
}
else throw new TypeError('Incorrect type. Passed in value should be an array or string.');
}
} | javascript | function(n) {
return function chunk(arg) {
if ( Array.isArray(arg) ) {
return arg.reduce((acc,_,i,a) => {
return i % n === 0 ? acc.concat( [a.slice(i, i + n)] ) : acc;
}, []);
}
else if ( typeof arg === 'string' ) {
return arg.match( new RegExp('.{1,' + n + '}', 'g') ) || [];
}
else throw new TypeError('Incorrect type. Passed in value should be an array or string.');
}
} | [
"function",
"(",
"n",
")",
"{",
"return",
"function",
"chunk",
"(",
"arg",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"arg",
")",
")",
"{",
"return",
"arg",
".",
"reduce",
"(",
"(",
"acc",
",",
"_",
",",
"i",
",",
"a",
")",
"=>",
"{",
"return",
"i",
"%",
"n",
"===",
"0",
"?",
"acc",
".",
"concat",
"(",
"[",
"a",
".",
"slice",
"(",
"i",
",",
"i",
"+",
"n",
")",
"]",
")",
":",
"acc",
";",
"}",
",",
"[",
"]",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"arg",
"===",
"'string'",
")",
"{",
"return",
"arg",
".",
"match",
"(",
"new",
"RegExp",
"(",
"'.{1,'",
"+",
"n",
"+",
"'}'",
",",
"'g'",
")",
")",
"||",
"[",
"]",
";",
"}",
"else",
"throw",
"new",
"TypeError",
"(",
"'Incorrect type. Passed in value should be an array or string.'",
")",
";",
"}",
"}"
]
| Returns an array of arrays or strings in chunks of n.
chunkBy :: (n) β (a) β arr
@param n - A number to use as chunk's length
@returns function
@param arg - An array or string to chunk
@returns array | [
"Returns",
"an",
"array",
"of",
"arrays",
"or",
"strings",
"in",
"chunks",
"of",
"n",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L56-L68 | train |
|
davidrayoussef/funcifyr | funcifyr.js | function(fn1, fn2) {
return function composed() {
return fn1.call(null, fn2.apply(null, arguments));
}
} | javascript | function(fn1, fn2) {
return function composed() {
return fn1.call(null, fn2.apply(null, arguments));
}
} | [
"function",
"(",
"fn1",
",",
"fn2",
")",
"{",
"return",
"function",
"composed",
"(",
")",
"{",
"return",
"fn1",
".",
"call",
"(",
"null",
",",
"fn2",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
")",
";",
"}",
"}"
]
| Creates a function from two functions that runs fn1 on the results of fn2.
compose :: (fn, fn) β (a) β r
@param (fn1, fn2) - Two functions
@returns function
@param arguments - Any arguments passed to inner function
@returns Result of fn1(fn2(arguments)) | [
"Creates",
"a",
"function",
"from",
"two",
"functions",
"that",
"runs",
"fn1",
"on",
"the",
"results",
"of",
"fn2",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L80-L84 | train |
|
davidrayoussef/funcifyr | funcifyr.js | function(fn) {
return function curried() {
var gatheredArgs = [].slice.call(arguments);
if ( gatheredArgs.length >= fn.length ) {
return fn.apply(null, gatheredArgs);
}
return function(innerArg) {
var newArgs = [].concat(gatheredArgs, innerArg);
return curried.apply(null, newArgs);
}
}
} | javascript | function(fn) {
return function curried() {
var gatheredArgs = [].slice.call(arguments);
if ( gatheredArgs.length >= fn.length ) {
return fn.apply(null, gatheredArgs);
}
return function(innerArg) {
var newArgs = [].concat(gatheredArgs, innerArg);
return curried.apply(null, newArgs);
}
}
} | [
"function",
"(",
"fn",
")",
"{",
"return",
"function",
"curried",
"(",
")",
"{",
"var",
"gatheredArgs",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"if",
"(",
"gatheredArgs",
".",
"length",
">=",
"fn",
".",
"length",
")",
"{",
"return",
"fn",
".",
"apply",
"(",
"null",
",",
"gatheredArgs",
")",
";",
"}",
"return",
"function",
"(",
"innerArg",
")",
"{",
"var",
"newArgs",
"=",
"[",
"]",
".",
"concat",
"(",
"gatheredArgs",
",",
"innerArg",
")",
";",
"return",
"curried",
".",
"apply",
"(",
"null",
",",
"newArgs",
")",
";",
"}",
"}",
"}"
]
| Takes a variadic function and returns unary functions until all parameters are used.
curry :: (fn β (a,b,c,d)) β (a) β (b) β (c) β (d) β r
@param fn - A function to be curried
@returns The curried function
@param arguments - Any arguments passed
@returns Either the result of original function if all params were used, OR a unary function
@param innerArg
@returns Call to curried function with additional arg | [
"Takes",
"a",
"variadic",
"function",
"and",
"returns",
"unary",
"functions",
"until",
"all",
"parameters",
"are",
"used",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L98-L111 | train |
|
davidrayoussef/funcifyr | funcifyr.js | function(value, times) {
if (Array.fill) {
return new Array(times).fill(value);
}
return Array.apply(null, Array(+times)).map(function() {
return value;
});
} | javascript | function(value, times) {
if (Array.fill) {
return new Array(times).fill(value);
}
return Array.apply(null, Array(+times)).map(function() {
return value;
});
} | [
"function",
"(",
"value",
",",
"times",
")",
"{",
"if",
"(",
"Array",
".",
"fill",
")",
"{",
"return",
"new",
"Array",
"(",
"times",
")",
".",
"fill",
"(",
"value",
")",
";",
"}",
"return",
"Array",
".",
"apply",
"(",
"null",
",",
"Array",
"(",
"+",
"times",
")",
")",
".",
"map",
"(",
"function",
"(",
")",
"{",
"return",
"value",
";",
"}",
")",
";",
"}"
]
| Returns an array filled with a value repeated a number of times.
fill :: (n, n) β arr
@param (value, times) - The value to fill, and the length of the new array
@returns array | [
"Returns",
"an",
"array",
"filled",
"with",
"a",
"value",
"repeated",
"a",
"number",
"of",
"times",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L121-L128 | train |
|
davidrayoussef/funcifyr | funcifyr.js | function(x, fn) {
if (Array.isArray(x) ) {
return x.reduce(function(acc, curr) {
return acc.concat( funcifyr.flatMap(curr, fn) );
}, []);
}
return fn(x);
} | javascript | function(x, fn) {
if (Array.isArray(x) ) {
return x.reduce(function(acc, curr) {
return acc.concat( funcifyr.flatMap(curr, fn) );
}, []);
}
return fn(x);
} | [
"function",
"(",
"x",
",",
"fn",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"x",
")",
")",
"{",
"return",
"x",
".",
"reduce",
"(",
"function",
"(",
"acc",
",",
"curr",
")",
"{",
"return",
"acc",
".",
"concat",
"(",
"funcifyr",
".",
"flatMap",
"(",
"curr",
",",
"fn",
")",
")",
";",
"}",
",",
"[",
"]",
")",
";",
"}",
"return",
"fn",
"(",
"x",
")",
";",
"}"
]
| Takes a multidimensional array and a callback function, and returns a new, flattened array with the
results of calling the callback function on each value.
flatMap :: ([a, [b, [c, d]]], fn) β [a, b, c, d]
@param (x, fn) - A multidimensional array and a callback function
@returns array | [
"Takes",
"a",
"multidimensional",
"array",
"and",
"a",
"callback",
"function",
"and",
"returns",
"a",
"new",
"flattened",
"array",
"with",
"the",
"results",
"of",
"calling",
"the",
"callback",
"function",
"on",
"each",
"value",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L139-L146 | train |
|
davidrayoussef/funcifyr | funcifyr.js | function(key) {
return function group(arr) {
return arr.reduce(function(obj, item) {
(obj[item[key]] = obj[item[key]] || []).push(item);
return obj;
}, {});
}
} | javascript | function(key) {
return function group(arr) {
return arr.reduce(function(obj, item) {
(obj[item[key]] = obj[item[key]] || []).push(item);
return obj;
}, {});
}
} | [
"function",
"(",
"key",
")",
"{",
"return",
"function",
"group",
"(",
"arr",
")",
"{",
"return",
"arr",
".",
"reduce",
"(",
"function",
"(",
"obj",
",",
"item",
")",
"{",
"(",
"obj",
"[",
"item",
"[",
"key",
"]",
"]",
"=",
"obj",
"[",
"item",
"[",
"key",
"]",
"]",
"||",
"[",
"]",
")",
".",
"push",
"(",
"item",
")",
";",
"return",
"obj",
";",
"}",
",",
"{",
"}",
")",
";",
"}",
"}"
]
| Groups together related prop values from an array of objects.
groupBy :: (a) β (arr) β obj
@param key - A property name used to do the grouping
@returns function
@param arr - An array of objects
@returns An object of key-value pairs grouped by the key | [
"Groups",
"together",
"related",
"prop",
"values",
"from",
"an",
"array",
"of",
"objects",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L189-L196 | train |
|
davidrayoussef/funcifyr | funcifyr.js | function(collection, fn) {
if ( Array.isArray(collection) ) {
var result = [];
for (var i = 0; i < collection.length; i++) {
result[i] = fn(collection[i], i, collection);
}
return result;
}
else if ( Object.prototype.toString.call(collection) === '[object Object]' ) {
var result = {};
for (var key in collection) {
if ( collection.hasOwnProperty(key) ) {
result[key] = fn(collection[key]);
}
}
return result;
}
else throw new TypeError('Invalid type. First argument must be an array or an object.');
} | javascript | function(collection, fn) {
if ( Array.isArray(collection) ) {
var result = [];
for (var i = 0; i < collection.length; i++) {
result[i] = fn(collection[i], i, collection);
}
return result;
}
else if ( Object.prototype.toString.call(collection) === '[object Object]' ) {
var result = {};
for (var key in collection) {
if ( collection.hasOwnProperty(key) ) {
result[key] = fn(collection[key]);
}
}
return result;
}
else throw new TypeError('Invalid type. First argument must be an array or an object.');
} | [
"function",
"(",
"collection",
",",
"fn",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"collection",
")",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"collection",
".",
"length",
";",
"i",
"++",
")",
"{",
"result",
"[",
"i",
"]",
"=",
"fn",
"(",
"collection",
"[",
"i",
"]",
",",
"i",
",",
"collection",
")",
";",
"}",
"return",
"result",
";",
"}",
"else",
"if",
"(",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"collection",
")",
"===",
"'[object Object]'",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"collection",
")",
"{",
"if",
"(",
"collection",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"result",
"[",
"key",
"]",
"=",
"fn",
"(",
"collection",
"[",
"key",
"]",
")",
";",
"}",
"}",
"return",
"result",
";",
"}",
"else",
"throw",
"new",
"TypeError",
"(",
"'Invalid type. First argument must be an array or an object.'",
")",
";",
"}"
]
| Maps over a collection and runs a callback on each item.
map :: (obj, fn) β arr
@param (collection, fn) - An array or object to iterate over, and a callback function to run
@returns array or object | [
"Maps",
"over",
"a",
"collection",
"and",
"runs",
"a",
"callback",
"on",
"each",
"item",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L238-L260 | train |
|
davidrayoussef/funcifyr | funcifyr.js | function(fn1, fn2) {
return function orified(arg) {
return fn1.call(null, arg) || fn2.call(null, arg);
}
} | javascript | function(fn1, fn2) {
return function orified(arg) {
return fn1.call(null, arg) || fn2.call(null, arg);
}
} | [
"function",
"(",
"fn1",
",",
"fn2",
")",
"{",
"return",
"function",
"orified",
"(",
"arg",
")",
"{",
"return",
"fn1",
".",
"call",
"(",
"null",
",",
"arg",
")",
"||",
"fn2",
".",
"call",
"(",
"null",
",",
"arg",
")",
";",
"}",
"}"
]
| Runs two predicate functions on an argument and returns true if either are true.
or :: (fn, fn) β (a) β bool
@param (fn1, fn2) - Two predicate functions
@returns function
@param arg - An argument to run the two predicate functions on
@returns true or false | [
"Runs",
"two",
"predicate",
"functions",
"on",
"an",
"argument",
"and",
"returns",
"true",
"if",
"either",
"are",
"true",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L304-L308 | train |
|
davidrayoussef/funcifyr | funcifyr.js | function(/*fns*/) {
var fns = [].slice.call(arguments);
return function piped(/*args*/) {
var args = [].slice.call(arguments);
fns.forEach(function(fn) {
args = [fn.apply(null, args)];
});
return args[0];
};
} | javascript | function(/*fns*/) {
var fns = [].slice.call(arguments);
return function piped(/*args*/) {
var args = [].slice.call(arguments);
fns.forEach(function(fn) {
args = [fn.apply(null, args)];
});
return args[0];
};
} | [
"function",
"(",
")",
"{",
"var",
"fns",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"return",
"function",
"piped",
"(",
")",
"{",
"var",
"args",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"fns",
".",
"forEach",
"(",
"function",
"(",
"fn",
")",
"{",
"args",
"=",
"[",
"fn",
".",
"apply",
"(",
"null",
",",
"args",
")",
"]",
";",
"}",
")",
";",
"return",
"args",
"[",
"0",
"]",
";",
"}",
";",
"}"
]
| Runs several functions, using the result of one function as the argument for the next.
pipe :: (fns) β (a) β r
@param arguments - A variadic number of functions
@returns function
@param arguments - A variadic number of arguments
@returns The result of calling each function on the arguments | [
"Runs",
"several",
"functions",
"using",
"the",
"result",
"of",
"one",
"function",
"as",
"the",
"argument",
"for",
"the",
"next",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L336-L345 | train |
|
davidrayoussef/funcifyr | funcifyr.js | function(start, stop, step) {
if (arguments.length === 1) return funcifyr.range(1, start, 1);
if (arguments.length === 2) return funcifyr.range(start, stop, 1);
var result = [];
for (var i = start; i <= stop; i += step) {
result.push(i);
}
return result;
} | javascript | function(start, stop, step) {
if (arguments.length === 1) return funcifyr.range(1, start, 1);
if (arguments.length === 2) return funcifyr.range(start, stop, 1);
var result = [];
for (var i = start; i <= stop; i += step) {
result.push(i);
}
return result;
} | [
"function",
"(",
"start",
",",
"stop",
",",
"step",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"return",
"funcifyr",
".",
"range",
"(",
"1",
",",
"start",
",",
"1",
")",
";",
"if",
"(",
"arguments",
".",
"length",
"===",
"2",
")",
"return",
"funcifyr",
".",
"range",
"(",
"start",
",",
"stop",
",",
"1",
")",
";",
"var",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"start",
";",
"i",
"<=",
"stop",
";",
"i",
"+=",
"step",
")",
"{",
"result",
".",
"push",
"(",
"i",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| Returns an array of numbers ranging from start to stop, incremented by step.
range :: (n, n, n) β arr
@param (start, stop, step) - A start value, a stop value, and a step value to increment by
@returns An array of the range of numbers | [
"Returns",
"an",
"array",
"of",
"numbers",
"ranging",
"from",
"start",
"to",
"stop",
"incremented",
"by",
"step",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L385-L396 | train |
|
davidrayoussef/funcifyr | funcifyr.js | function(str, times) {
if (String.prototype.repeat) return str.repeat(times);
return Array.apply(null, new Array(times)).map(function() {
return str;
}).join('');
} | javascript | function(str, times) {
if (String.prototype.repeat) return str.repeat(times);
return Array.apply(null, new Array(times)).map(function() {
return str;
}).join('');
} | [
"function",
"(",
"str",
",",
"times",
")",
"{",
"if",
"(",
"String",
".",
"prototype",
".",
"repeat",
")",
"return",
"str",
".",
"repeat",
"(",
"times",
")",
";",
"return",
"Array",
".",
"apply",
"(",
"null",
",",
"new",
"Array",
"(",
"times",
")",
")",
".",
"map",
"(",
"function",
"(",
")",
"{",
"return",
"str",
";",
"}",
")",
".",
"join",
"(",
"''",
")",
";",
"}"
]
| Repeats a string a number of times.
repeat :: (a, n) β r
@param (str, times) - A string to repeat, and a number for the amount of repetitions
@returns A repeated string | [
"Repeats",
"a",
"string",
"a",
"number",
"of",
"times",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L406-L411 | train |
|
davidrayoussef/funcifyr | funcifyr.js | function(arr) {
for (var i = 0; i < arr.length; i++) {
var randIndex = Math.floor(Math.random() * arr.length);
var temp = arr[randIndex];
arr[randIndex] = arr[i];
arr[i] = temp;
}
return arr;
} | javascript | function(arr) {
for (var i = 0; i < arr.length; i++) {
var randIndex = Math.floor(Math.random() * arr.length);
var temp = arr[randIndex];
arr[randIndex] = arr[i];
arr[i] = temp;
}
return arr;
} | [
"function",
"(",
"arr",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"randIndex",
"=",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"arr",
".",
"length",
")",
";",
"var",
"temp",
"=",
"arr",
"[",
"randIndex",
"]",
";",
"arr",
"[",
"randIndex",
"]",
"=",
"arr",
"[",
"i",
"]",
";",
"arr",
"[",
"i",
"]",
"=",
"temp",
";",
"}",
"return",
"arr",
";",
"}"
]
| Randomly shuffles items in an array.
shuffle :: (arr) β arr
@param arr - An array to be shuffled
@returns A shuffled array | [
"Randomly",
"shuffles",
"items",
"in",
"an",
"array",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L436-L444 | train |
|
davidrayoussef/funcifyr | funcifyr.js | function(prop) {
return function tallied(arrayOfObjects) {
return arrayOfObjects.reduce(function(acc, curr) {
acc[curr[prop]] = (acc[curr[prop]] || 0) + 1;
return acc;
}, {});
}
} | javascript | function(prop) {
return function tallied(arrayOfObjects) {
return arrayOfObjects.reduce(function(acc, curr) {
acc[curr[prop]] = (acc[curr[prop]] || 0) + 1;
return acc;
}, {});
}
} | [
"function",
"(",
"prop",
")",
"{",
"return",
"function",
"tallied",
"(",
"arrayOfObjects",
")",
"{",
"return",
"arrayOfObjects",
".",
"reduce",
"(",
"function",
"(",
"acc",
",",
"curr",
")",
"{",
"acc",
"[",
"curr",
"[",
"prop",
"]",
"]",
"=",
"(",
"acc",
"[",
"curr",
"[",
"prop",
"]",
"]",
"||",
"0",
")",
"+",
"1",
";",
"return",
"acc",
";",
"}",
",",
"{",
"}",
")",
";",
"}",
"}"
]
| Returns an object with the number of occurrences of a property value found in an array of objects.
tally :: (a) β (arr) β obj
@param prop - A string representation of a property to target
@returns function
@param arrayOfObjects - An array of objects
@returns An object with the prop as a key, and the number of its occurences as the value | [
"Returns",
"an",
"object",
"with",
"the",
"number",
"of",
"occurrences",
"of",
"a",
"property",
"value",
"found",
"in",
"an",
"array",
"of",
"objects",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L456-L463 | train |
|
davidrayoussef/funcifyr | funcifyr.js | function(value) {
return {
value: value,
then: function(fn) {
this.value = fn(this.value);
return this;
},
end: function() {
return this.value;
}
};
} | javascript | function(value) {
return {
value: value,
then: function(fn) {
this.value = fn(this.value);
return this;
},
end: function() {
return this.value;
}
};
} | [
"function",
"(",
"value",
")",
"{",
"return",
"{",
"value",
":",
"value",
",",
"then",
":",
"function",
"(",
"fn",
")",
"{",
"this",
".",
"value",
"=",
"fn",
"(",
"this",
".",
"value",
")",
";",
"return",
"this",
";",
"}",
",",
"end",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"value",
";",
"}",
"}",
";",
"}"
]
| Creates sequence of chainable actions.
thenify :: (a) β obj
@param value - An initial value
@returns An object with a then function to run on the value, and an end function to return the final value | [
"Creates",
"sequence",
"of",
"chainable",
"actions",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L473-L484 | train |
|
davidrayoussef/funcifyr | funcifyr.js | function(arr) {
if (Array.prototype.from) return Array.from(new Set(arr));
return arr.filter(function(v,i,a) {
return i === a.indexOf(v);
});
} | javascript | function(arr) {
if (Array.prototype.from) return Array.from(new Set(arr));
return arr.filter(function(v,i,a) {
return i === a.indexOf(v);
});
} | [
"function",
"(",
"arr",
")",
"{",
"if",
"(",
"Array",
".",
"prototype",
".",
"from",
")",
"return",
"Array",
".",
"from",
"(",
"new",
"Set",
"(",
"arr",
")",
")",
";",
"return",
"arr",
".",
"filter",
"(",
"function",
"(",
"v",
",",
"i",
",",
"a",
")",
"{",
"return",
"i",
"===",
"a",
".",
"indexOf",
"(",
"v",
")",
";",
"}",
")",
";",
"}"
]
| Takes an array with duplicates and returns a new one with all dupes removed.
unique :: (arr) β arr
@param arr
@returns A new array with duplicates removed | [
"Takes",
"an",
"array",
"with",
"duplicates",
"and",
"returns",
"a",
"new",
"one",
"with",
"all",
"dupes",
"removed",
"."
]
| 84042752f605a74953b9698c65db4b90b5c4f484 | https://github.com/davidrayoussef/funcifyr/blob/84042752f605a74953b9698c65db4b90b5c4f484/funcifyr.js#L494-L499 | train |
|
winding-lines/ember-cli-typify | lib/typescript-preprocessor.js | typePaths | function typePaths(config) {
var out = [
"node_modules/@types",
];
var paths = (config.compilerOptions && config.compilerOptions.paths) || {};
Object.keys(paths).forEach( function eachEntry(k) {
// paths may contain a /*, eliminate it
paths[k].forEach(function eachPath(a) {
var p = a.split("/\*")[0];
if (out.indexOf(p) < 0) {
out.push(p);
}
});
});
debug("type paths", out);
return out;
} | javascript | function typePaths(config) {
var out = [
"node_modules/@types",
];
var paths = (config.compilerOptions && config.compilerOptions.paths) || {};
Object.keys(paths).forEach( function eachEntry(k) {
// paths may contain a /*, eliminate it
paths[k].forEach(function eachPath(a) {
var p = a.split("/\*")[0];
if (out.indexOf(p) < 0) {
out.push(p);
}
});
});
debug("type paths", out);
return out;
} | [
"function",
"typePaths",
"(",
"config",
")",
"{",
"var",
"out",
"=",
"[",
"\"node_modules/@types\"",
",",
"]",
";",
"var",
"paths",
"=",
"(",
"config",
".",
"compilerOptions",
"&&",
"config",
".",
"compilerOptions",
".",
"paths",
")",
"||",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"paths",
")",
".",
"forEach",
"(",
"function",
"eachEntry",
"(",
"k",
")",
"{",
"paths",
"[",
"k",
"]",
".",
"forEach",
"(",
"function",
"eachPath",
"(",
"a",
")",
"{",
"var",
"p",
"=",
"a",
".",
"split",
"(",
"\"/\\*\"",
")",
"[",
"\\*",
"]",
";",
"0",
"}",
")",
";",
"}",
")",
";",
"if",
"(",
"out",
".",
"indexOf",
"(",
"p",
")",
"<",
"0",
")",
"{",
"out",
".",
"push",
"(",
"p",
")",
";",
"}",
"debug",
"(",
"\"type paths\"",
",",
"out",
")",
";",
"}"
]
| Return the paths which contain type information. | [
"Return",
"the",
"paths",
"which",
"contain",
"type",
"information",
"."
]
| 3551e75bf6e00850b77365b18c3f6cef8b24137b | https://github.com/winding-lines/ember-cli-typify/blob/3551e75bf6e00850b77365b18c3f6cef8b24137b/lib/typescript-preprocessor.js#L30-L46 | train |
wzrdtales/umigrate-mariadb | index.js | function ( config, callback )
{
var self = this;
var db = Array(),
diff = Array(),
first = true;
for( var c = 0; c < 2; ++c )
{
db[ c ] = Array();
for( var d = 0; d < 2; ++d )
{
db[ c ][ d ] = Array();
}
}
var query = util.format( 'USE %s; SHOW FULL TABLES', config.database );
this.runSql( query, null, { useArray: true } )
.on( 'result', function ( res )
{
res.on( 'data', function ( row )
{
if ( row[ 0 ] && row[ 1 ] === 'VIEW' )
db[ 0 ][ 1 ].push( row[ 0 ] );
else if ( row[ 0 ] && row[ 0 ] !== 'migrations' )
db[ 0 ][ 0 ].push( row[ 0 ] );
} );
} )
.on( 'end', function ()
{
if ( config.diffDump )
first = false;
else
callback( db );
} );
if ( config.diffDump )
{
query = util.format( 'USE %s; SHOW FULL TABLES', config.database_diff );
this.runSql( query, null, { useArray: true } )
.on( 'result', function ( res )
{
res.on( 'data', function ( row )
{
if ( row[ 0 ] && row[ 1 ] === 'VIEW' )
db[ 1 ][ 1 ].push( row[ 0 ] );
else if ( row[ 0 ] && row[ 0 ] !== 'migrations' )
db[ 1 ][ 0 ].push( row[ 0 ] );
} );
} )
.on( 'end', function ()
{
while ( first )
{
deasync.sleep( 100 );
}
callback( db );
} );
}
} | javascript | function ( config, callback )
{
var self = this;
var db = Array(),
diff = Array(),
first = true;
for( var c = 0; c < 2; ++c )
{
db[ c ] = Array();
for( var d = 0; d < 2; ++d )
{
db[ c ][ d ] = Array();
}
}
var query = util.format( 'USE %s; SHOW FULL TABLES', config.database );
this.runSql( query, null, { useArray: true } )
.on( 'result', function ( res )
{
res.on( 'data', function ( row )
{
if ( row[ 0 ] && row[ 1 ] === 'VIEW' )
db[ 0 ][ 1 ].push( row[ 0 ] );
else if ( row[ 0 ] && row[ 0 ] !== 'migrations' )
db[ 0 ][ 0 ].push( row[ 0 ] );
} );
} )
.on( 'end', function ()
{
if ( config.diffDump )
first = false;
else
callback( db );
} );
if ( config.diffDump )
{
query = util.format( 'USE %s; SHOW FULL TABLES', config.database_diff );
this.runSql( query, null, { useArray: true } )
.on( 'result', function ( res )
{
res.on( 'data', function ( row )
{
if ( row[ 0 ] && row[ 1 ] === 'VIEW' )
db[ 1 ][ 1 ].push( row[ 0 ] );
else if ( row[ 0 ] && row[ 0 ] !== 'migrations' )
db[ 1 ][ 0 ].push( row[ 0 ] );
} );
} )
.on( 'end', function ()
{
while ( first )
{
deasync.sleep( 100 );
}
callback( db );
} );
}
} | [
"function",
"(",
"config",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"db",
"=",
"Array",
"(",
")",
",",
"diff",
"=",
"Array",
"(",
")",
",",
"first",
"=",
"true",
";",
"for",
"(",
"var",
"c",
"=",
"0",
";",
"c",
"<",
"2",
";",
"++",
"c",
")",
"{",
"db",
"[",
"c",
"]",
"=",
"Array",
"(",
")",
";",
"for",
"(",
"var",
"d",
"=",
"0",
";",
"d",
"<",
"2",
";",
"++",
"d",
")",
"{",
"db",
"[",
"c",
"]",
"[",
"d",
"]",
"=",
"Array",
"(",
")",
";",
"}",
"}",
"var",
"query",
"=",
"util",
".",
"format",
"(",
"'USE %s; SHOW FULL TABLES'",
",",
"config",
".",
"database",
")",
";",
"this",
".",
"runSql",
"(",
"query",
",",
"null",
",",
"{",
"useArray",
":",
"true",
"}",
")",
".",
"on",
"(",
"'result'",
",",
"function",
"(",
"res",
")",
"{",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"row",
")",
"{",
"if",
"(",
"row",
"[",
"0",
"]",
"&&",
"row",
"[",
"1",
"]",
"===",
"'VIEW'",
")",
"db",
"[",
"0",
"]",
"[",
"1",
"]",
".",
"push",
"(",
"row",
"[",
"0",
"]",
")",
";",
"else",
"if",
"(",
"row",
"[",
"0",
"]",
"&&",
"row",
"[",
"0",
"]",
"!==",
"'migrations'",
")",
"db",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"push",
"(",
"row",
"[",
"0",
"]",
")",
";",
"}",
")",
";",
"}",
")",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"config",
".",
"diffDump",
")",
"first",
"=",
"false",
";",
"else",
"callback",
"(",
"db",
")",
";",
"}",
")",
";",
"if",
"(",
"config",
".",
"diffDump",
")",
"{",
"query",
"=",
"util",
".",
"format",
"(",
"'USE %s; SHOW FULL TABLES'",
",",
"config",
".",
"database_diff",
")",
";",
"this",
".",
"runSql",
"(",
"query",
",",
"null",
",",
"{",
"useArray",
":",
"true",
"}",
")",
".",
"on",
"(",
"'result'",
",",
"function",
"(",
"res",
")",
"{",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"row",
")",
"{",
"if",
"(",
"row",
"[",
"0",
"]",
"&&",
"row",
"[",
"1",
"]",
"===",
"'VIEW'",
")",
"db",
"[",
"1",
"]",
"[",
"1",
"]",
".",
"push",
"(",
"row",
"[",
"0",
"]",
")",
";",
"else",
"if",
"(",
"row",
"[",
"0",
"]",
"&&",
"row",
"[",
"0",
"]",
"!==",
"'migrations'",
")",
"db",
"[",
"1",
"]",
"[",
"0",
"]",
".",
"push",
"(",
"row",
"[",
"0",
"]",
")",
";",
"}",
")",
";",
"}",
")",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"while",
"(",
"first",
")",
"{",
"deasync",
".",
"sleep",
"(",
"100",
")",
";",
"}",
"callback",
"(",
"db",
")",
";",
"}",
")",
";",
"}",
"}"
]
| Returns an array containing the Tables.
General return information:
This array has 2 layers, the final information layer has
8 elements.
Array Format:
Layer 1:
[0] = real table, [1] = diff table
Layer 3 (Result formatting):
[0] = table array*, [1] = view array*
Table Array (Content)
List of table name per array element
View Array (Content)
List of view name per array element
@return array | [
"Returns",
"an",
"array",
"containing",
"the",
"Tables",
"."
]
| b3ca76d7adb0660044b464c3564a852a454d24f0 | https://github.com/wzrdtales/umigrate-mariadb/blob/b3ca76d7adb0660044b464c3564a852a454d24f0/index.js#L43-L104 | train |
|
wzrdtales/umigrate-mariadb | index.js | function ( config, callback )
{
var self = this;
var db = Array(),
diff = Array(),
first = true;
db[ 0 ] = Array();
db[ 1 ] = Array();
diff[ 0 ] = Array();
diff[ 1 ] = Array();
var query = 'SELECT name, modified, type FROM mysql.proc WHERE db = ?';
this.runSql( query, [ config.database ] )
.on( 'result', function ( res )
{
res.on( 'data', function ( row )
{
if ( row.type === 'FUNCTION' )
db[ 0 ].push( [ row.name, row.modified ] );
else if ( row.type === 'PROCEDURE' )
db[ 1 ].push( [ row.name, row.modified ] );
} );
} )
.on( 'end', function ()
{
if ( config.diffDump )
first = false;
else
callback( db );
} );
if ( config.diffDump )
{
var query = 'SELECT name, modified, type FROM mysql.proc WHERE db = ?';
this.runSql( query, [ config.database_diff ], false )
.on( 'result', function ( res )
{
res.on( 'data', function ( row )
{
if ( row.type === 'FUNCTION' )
diff[ 0 ].push( [ row.name, row.modified ] );
else if ( row.type === 'PROCEDURE' )
diff[ 1 ].push( [ row.name, row.modified ] );
} );
} )
.on( 'end', function ()
{
while ( first )
{
deasync.sleep( 100 );
}
callback( db, diff );
} );
}
} | javascript | function ( config, callback )
{
var self = this;
var db = Array(),
diff = Array(),
first = true;
db[ 0 ] = Array();
db[ 1 ] = Array();
diff[ 0 ] = Array();
diff[ 1 ] = Array();
var query = 'SELECT name, modified, type FROM mysql.proc WHERE db = ?';
this.runSql( query, [ config.database ] )
.on( 'result', function ( res )
{
res.on( 'data', function ( row )
{
if ( row.type === 'FUNCTION' )
db[ 0 ].push( [ row.name, row.modified ] );
else if ( row.type === 'PROCEDURE' )
db[ 1 ].push( [ row.name, row.modified ] );
} );
} )
.on( 'end', function ()
{
if ( config.diffDump )
first = false;
else
callback( db );
} );
if ( config.diffDump )
{
var query = 'SELECT name, modified, type FROM mysql.proc WHERE db = ?';
this.runSql( query, [ config.database_diff ], false )
.on( 'result', function ( res )
{
res.on( 'data', function ( row )
{
if ( row.type === 'FUNCTION' )
diff[ 0 ].push( [ row.name, row.modified ] );
else if ( row.type === 'PROCEDURE' )
diff[ 1 ].push( [ row.name, row.modified ] );
} );
} )
.on( 'end', function ()
{
while ( first )
{
deasync.sleep( 100 );
}
callback( db, diff );
} );
}
} | [
"function",
"(",
"config",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"db",
"=",
"Array",
"(",
")",
",",
"diff",
"=",
"Array",
"(",
")",
",",
"first",
"=",
"true",
";",
"db",
"[",
"0",
"]",
"=",
"Array",
"(",
")",
";",
"db",
"[",
"1",
"]",
"=",
"Array",
"(",
")",
";",
"diff",
"[",
"0",
"]",
"=",
"Array",
"(",
")",
";",
"diff",
"[",
"1",
"]",
"=",
"Array",
"(",
")",
";",
"var",
"query",
"=",
"'SELECT name, modified, type FROM mysql.proc WHERE db = ?'",
";",
"this",
".",
"runSql",
"(",
"query",
",",
"[",
"config",
".",
"database",
"]",
")",
".",
"on",
"(",
"'result'",
",",
"function",
"(",
"res",
")",
"{",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"row",
")",
"{",
"if",
"(",
"row",
".",
"type",
"===",
"'FUNCTION'",
")",
"db",
"[",
"0",
"]",
".",
"push",
"(",
"[",
"row",
".",
"name",
",",
"row",
".",
"modified",
"]",
")",
";",
"else",
"if",
"(",
"row",
".",
"type",
"===",
"'PROCEDURE'",
")",
"db",
"[",
"1",
"]",
".",
"push",
"(",
"[",
"row",
".",
"name",
",",
"row",
".",
"modified",
"]",
")",
";",
"}",
")",
";",
"}",
")",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"config",
".",
"diffDump",
")",
"first",
"=",
"false",
";",
"else",
"callback",
"(",
"db",
")",
";",
"}",
")",
";",
"if",
"(",
"config",
".",
"diffDump",
")",
"{",
"var",
"query",
"=",
"'SELECT name, modified, type FROM mysql.proc WHERE db = ?'",
";",
"this",
".",
"runSql",
"(",
"query",
",",
"[",
"config",
".",
"database_diff",
"]",
",",
"false",
")",
".",
"on",
"(",
"'result'",
",",
"function",
"(",
"res",
")",
"{",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"row",
")",
"{",
"if",
"(",
"row",
".",
"type",
"===",
"'FUNCTION'",
")",
"diff",
"[",
"0",
"]",
".",
"push",
"(",
"[",
"row",
".",
"name",
",",
"row",
".",
"modified",
"]",
")",
";",
"else",
"if",
"(",
"row",
".",
"type",
"===",
"'PROCEDURE'",
")",
"diff",
"[",
"1",
"]",
".",
"push",
"(",
"[",
"row",
".",
"name",
",",
"row",
".",
"modified",
"]",
")",
";",
"}",
")",
";",
"}",
")",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"while",
"(",
"first",
")",
"{",
"deasync",
".",
"sleep",
"(",
"100",
")",
";",
"}",
"callback",
"(",
"db",
",",
"diff",
")",
";",
"}",
")",
";",
"}",
"}"
]
| No specification yet.
@return useless | [
"No",
"specification",
"yet",
"."
]
| b3ca76d7adb0660044b464c3564a852a454d24f0 | https://github.com/wzrdtales/umigrate-mariadb/blob/b3ca76d7adb0660044b464c3564a852a454d24f0/index.js#L222-L278 | train |
|
wzrdtales/umigrate-mariadb | index.js | function ( config, tables, context, callback )
{
var self = this;
var db = Array(),
counter = 0,
query = 'SHOW INDEX FROM %s.%s;';
db[ 0 ] = Array();
db[ 1 ] = Array();
var len = ( tables.tables[ 0 ].length > tables.tables[ 1 ].length ) ?
tables.tables[ 0 ].length : tables.tables[ 1 ].length;
for ( var i = 0; i < len; ++i )
{
var q = '',
stmt = 0;
if ( tables.tables[ 0 ][ i ] )
q = util.format( query, config.database, tables.tables[ 0 ][ i ] );
else ++stmt;
if ( tables.tables[ 1 ][ i ] )
q += util.format( query, config.database_diff, tables.tables[ 1 ][ i ] );
//scoping stmt and interator to event
( function ( stmt, i )
{
self.runSql( q, null, { useArray: true } )
.on( 'result', function ( res )
{
var local = stmt++;
res.on( 'data', function ( row )
{
row[ 0 ] = row[ 2 ]; //replace table by key name
row[ 1 ] = row[ 1 ] === '0';
row.splice( 2, 1 ); //delete moved key name
//<-- Seq_in_index has now moved one index lower
row.splice( 4, 4 ); //delete until null info
row[ 4 ] = ( row[ 4 ] === 'YES' ) ? true : false;
//Comment and Index_comment will be simply ignored
//Maybe I'm going to implement them later, but not for now.
if ( !db[ local ][ tables.tables[ local ][ i ] ] )
db[ local ][ tables.tables[ local ][ i ] ] = Array();
db[ local ][ tables.tables[ local ][ i ] ].push( row );
} );
} )
.on( 'end', function ()
{
if ( ++counter >= len )
callback( context, db );
} );
} )( stmt, i );
}
} | javascript | function ( config, tables, context, callback )
{
var self = this;
var db = Array(),
counter = 0,
query = 'SHOW INDEX FROM %s.%s;';
db[ 0 ] = Array();
db[ 1 ] = Array();
var len = ( tables.tables[ 0 ].length > tables.tables[ 1 ].length ) ?
tables.tables[ 0 ].length : tables.tables[ 1 ].length;
for ( var i = 0; i < len; ++i )
{
var q = '',
stmt = 0;
if ( tables.tables[ 0 ][ i ] )
q = util.format( query, config.database, tables.tables[ 0 ][ i ] );
else ++stmt;
if ( tables.tables[ 1 ][ i ] )
q += util.format( query, config.database_diff, tables.tables[ 1 ][ i ] );
//scoping stmt and interator to event
( function ( stmt, i )
{
self.runSql( q, null, { useArray: true } )
.on( 'result', function ( res )
{
var local = stmt++;
res.on( 'data', function ( row )
{
row[ 0 ] = row[ 2 ]; //replace table by key name
row[ 1 ] = row[ 1 ] === '0';
row.splice( 2, 1 ); //delete moved key name
//<-- Seq_in_index has now moved one index lower
row.splice( 4, 4 ); //delete until null info
row[ 4 ] = ( row[ 4 ] === 'YES' ) ? true : false;
//Comment and Index_comment will be simply ignored
//Maybe I'm going to implement them later, but not for now.
if ( !db[ local ][ tables.tables[ local ][ i ] ] )
db[ local ][ tables.tables[ local ][ i ] ] = Array();
db[ local ][ tables.tables[ local ][ i ] ].push( row );
} );
} )
.on( 'end', function ()
{
if ( ++counter >= len )
callback( context, db );
} );
} )( stmt, i );
}
} | [
"function",
"(",
"config",
",",
"tables",
",",
"context",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"db",
"=",
"Array",
"(",
")",
",",
"counter",
"=",
"0",
",",
"query",
"=",
"'SHOW INDEX FROM %s.%s;'",
";",
"db",
"[",
"0",
"]",
"=",
"Array",
"(",
")",
";",
"db",
"[",
"1",
"]",
"=",
"Array",
"(",
")",
";",
"var",
"len",
"=",
"(",
"tables",
".",
"tables",
"[",
"0",
"]",
".",
"length",
">",
"tables",
".",
"tables",
"[",
"1",
"]",
".",
"length",
")",
"?",
"tables",
".",
"tables",
"[",
"0",
"]",
".",
"length",
":",
"tables",
".",
"tables",
"[",
"1",
"]",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"var",
"q",
"=",
"''",
",",
"stmt",
"=",
"0",
";",
"if",
"(",
"tables",
".",
"tables",
"[",
"0",
"]",
"[",
"i",
"]",
")",
"q",
"=",
"util",
".",
"format",
"(",
"query",
",",
"config",
".",
"database",
",",
"tables",
".",
"tables",
"[",
"0",
"]",
"[",
"i",
"]",
")",
";",
"else",
"++",
"stmt",
";",
"if",
"(",
"tables",
".",
"tables",
"[",
"1",
"]",
"[",
"i",
"]",
")",
"q",
"+=",
"util",
".",
"format",
"(",
"query",
",",
"config",
".",
"database_diff",
",",
"tables",
".",
"tables",
"[",
"1",
"]",
"[",
"i",
"]",
")",
";",
"(",
"function",
"(",
"stmt",
",",
"i",
")",
"{",
"self",
".",
"runSql",
"(",
"q",
",",
"null",
",",
"{",
"useArray",
":",
"true",
"}",
")",
".",
"on",
"(",
"'result'",
",",
"function",
"(",
"res",
")",
"{",
"var",
"local",
"=",
"stmt",
"++",
";",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"row",
")",
"{",
"row",
"[",
"0",
"]",
"=",
"row",
"[",
"2",
"]",
";",
"row",
"[",
"1",
"]",
"=",
"row",
"[",
"1",
"]",
"===",
"'0'",
";",
"row",
".",
"splice",
"(",
"2",
",",
"1",
")",
";",
"row",
".",
"splice",
"(",
"4",
",",
"4",
")",
";",
"row",
"[",
"4",
"]",
"=",
"(",
"row",
"[",
"4",
"]",
"===",
"'YES'",
")",
"?",
"true",
":",
"false",
";",
"if",
"(",
"!",
"db",
"[",
"local",
"]",
"[",
"tables",
".",
"tables",
"[",
"local",
"]",
"[",
"i",
"]",
"]",
")",
"db",
"[",
"local",
"]",
"[",
"tables",
".",
"tables",
"[",
"local",
"]",
"[",
"i",
"]",
"]",
"=",
"Array",
"(",
")",
";",
"db",
"[",
"local",
"]",
"[",
"tables",
".",
"tables",
"[",
"local",
"]",
"[",
"i",
"]",
"]",
".",
"push",
"(",
"row",
")",
";",
"}",
")",
";",
"}",
")",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"++",
"counter",
">=",
"len",
")",
"callback",
"(",
"context",
",",
"db",
")",
";",
"}",
")",
";",
"}",
")",
"(",
"stmt",
",",
"i",
")",
";",
"}",
"}"
]
| Returns an array containing the indizies.
General return information:
This array has 3 layers, the final information layer has
6 elements.
Array Format:
Layer 1:
[0] = real table, [1] = diff table
Layer 2:
['tablename'] = Array for final table indizies information
Layer 3 (Result formatting):
[0] = key name, [1] = unique( true or false ),
[2] = Position of column in index (Sequence in index),
[3] = column name, [4] = Nullable, [5] = index type
@return array | [
"Returns",
"an",
"array",
"containing",
"the",
"indizies",
"."
]
| b3ca76d7adb0660044b464c3564a852a454d24f0 | https://github.com/wzrdtales/umigrate-mariadb/blob/b3ca76d7adb0660044b464c3564a852a454d24f0/index.js#L369-L426 | train |
|
wzrdtales/umigrate-mariadb | index.js | function ( config, tables, context, callback )
{
var self = this,
db = Array(),
counter = 0;
db[ 0 ] = Array();
db[ 1 ] = Array();
var len = ( tables.tables[ 0 ].length > tables.tables[ 1 ].length ) ?
tables.tables[ 0 ].length : tables.tables[ 1 ].length;
var query = [
'SELECT const.CONSTRAINT_NAME, const.CONSTRAINT_SCHEMA,const.TABLE_NAME,',
'const.REFERENCED_TABLE_NAME,const.UPDATE_RULE,const.DELETE_RULE,',
'const_keys.COLUMN_NAME,const_keys.POSITION_IN_UNIQUE_CONSTRAINT,',
'const_keys.REFERENCED_COLUMN_NAME,const_keys.REFERENCED_TABLE_SCHEMA',
'FROM information_schema.REFERENTIAL_CONSTRAINTS const',
'INNER JOIN information_schema.KEY_COLUMN_USAGE const_keys ON ( ',
'const_keys.CONSTRAINT_SCHEMA = const.CONSTRAINT_SCHEMA',
'AND const_keys.CONSTRAINT_NAME = const.CONSTRAINT_NAME )',
'WHERE const.CONSTRAINT_SCHEMA = ?',
'AND const.TABLE_NAME = ?;'
]
.join( ' ' );
for ( var i = 0; i < len; ++i )
{
var q = '',
params = Array(),
stmt = 0;
if ( tables.tables[ 0 ][ i ] )
{
q = query;
params.push( config.database );
params.push( tables.tables[ 0 ][ i ] );
}
else ++stmt;
if ( tables.tables[ 1 ][ i ] )
{
q += query;
params.push( config.database_diff );
params.push( tables.tables[ 1 ][ i ] );
}
//scoping stmt and interator to event
( function ( stmt, i )
{
self.runSql( q, params, { useArray: true } )
.on( 'result', function ( res )
{
var local = stmt++;
res.on( 'data', function ( row )
{
constraint = Array();
if ( !db[ local ][ tables.tables[ local ][ i ] ] )
db[ local ][ tables.tables[ local ][ i ] ] = Array();
constraint[ 0 ] = row[ 0 ]; //constraint_name
constraint[ 1 ] = row[ 6 ]; //column_name
constraint[ 2 ] = row[ 9 ]; //referenced_table_schema
constraint[ 3 ] = row[ 3 ]; //referenced_table_name
constraint[ 4 ] = row[ 8 ]; //referenced_column_name
constraint[ 5 ] = row[ 7 ]; //position_in_unique_constraint
constraint[ 6 ] = row[ 4 ]; //on_update
constraint[ 7 ] = row[ 5 ]; //on_delete
db[ local ][ tables.tables[ local ][ i ] ].push( constraint );
} );
} )
.on( 'end', function ()
{
if ( ++counter >= len )
callback( context, db );
} );
} )( stmt, i );
}
} | javascript | function ( config, tables, context, callback )
{
var self = this,
db = Array(),
counter = 0;
db[ 0 ] = Array();
db[ 1 ] = Array();
var len = ( tables.tables[ 0 ].length > tables.tables[ 1 ].length ) ?
tables.tables[ 0 ].length : tables.tables[ 1 ].length;
var query = [
'SELECT const.CONSTRAINT_NAME, const.CONSTRAINT_SCHEMA,const.TABLE_NAME,',
'const.REFERENCED_TABLE_NAME,const.UPDATE_RULE,const.DELETE_RULE,',
'const_keys.COLUMN_NAME,const_keys.POSITION_IN_UNIQUE_CONSTRAINT,',
'const_keys.REFERENCED_COLUMN_NAME,const_keys.REFERENCED_TABLE_SCHEMA',
'FROM information_schema.REFERENTIAL_CONSTRAINTS const',
'INNER JOIN information_schema.KEY_COLUMN_USAGE const_keys ON ( ',
'const_keys.CONSTRAINT_SCHEMA = const.CONSTRAINT_SCHEMA',
'AND const_keys.CONSTRAINT_NAME = const.CONSTRAINT_NAME )',
'WHERE const.CONSTRAINT_SCHEMA = ?',
'AND const.TABLE_NAME = ?;'
]
.join( ' ' );
for ( var i = 0; i < len; ++i )
{
var q = '',
params = Array(),
stmt = 0;
if ( tables.tables[ 0 ][ i ] )
{
q = query;
params.push( config.database );
params.push( tables.tables[ 0 ][ i ] );
}
else ++stmt;
if ( tables.tables[ 1 ][ i ] )
{
q += query;
params.push( config.database_diff );
params.push( tables.tables[ 1 ][ i ] );
}
//scoping stmt and interator to event
( function ( stmt, i )
{
self.runSql( q, params, { useArray: true } )
.on( 'result', function ( res )
{
var local = stmt++;
res.on( 'data', function ( row )
{
constraint = Array();
if ( !db[ local ][ tables.tables[ local ][ i ] ] )
db[ local ][ tables.tables[ local ][ i ] ] = Array();
constraint[ 0 ] = row[ 0 ]; //constraint_name
constraint[ 1 ] = row[ 6 ]; //column_name
constraint[ 2 ] = row[ 9 ]; //referenced_table_schema
constraint[ 3 ] = row[ 3 ]; //referenced_table_name
constraint[ 4 ] = row[ 8 ]; //referenced_column_name
constraint[ 5 ] = row[ 7 ]; //position_in_unique_constraint
constraint[ 6 ] = row[ 4 ]; //on_update
constraint[ 7 ] = row[ 5 ]; //on_delete
db[ local ][ tables.tables[ local ][ i ] ].push( constraint );
} );
} )
.on( 'end', function ()
{
if ( ++counter >= len )
callback( context, db );
} );
} )( stmt, i );
}
} | [
"function",
"(",
"config",
",",
"tables",
",",
"context",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
",",
"db",
"=",
"Array",
"(",
")",
",",
"counter",
"=",
"0",
";",
"db",
"[",
"0",
"]",
"=",
"Array",
"(",
")",
";",
"db",
"[",
"1",
"]",
"=",
"Array",
"(",
")",
";",
"var",
"len",
"=",
"(",
"tables",
".",
"tables",
"[",
"0",
"]",
".",
"length",
">",
"tables",
".",
"tables",
"[",
"1",
"]",
".",
"length",
")",
"?",
"tables",
".",
"tables",
"[",
"0",
"]",
".",
"length",
":",
"tables",
".",
"tables",
"[",
"1",
"]",
".",
"length",
";",
"var",
"query",
"=",
"[",
"'SELECT const.CONSTRAINT_NAME, const.CONSTRAINT_SCHEMA,const.TABLE_NAME,'",
",",
"'const.REFERENCED_TABLE_NAME,const.UPDATE_RULE,const.DELETE_RULE,'",
",",
"'const_keys.COLUMN_NAME,const_keys.POSITION_IN_UNIQUE_CONSTRAINT,'",
",",
"'const_keys.REFERENCED_COLUMN_NAME,const_keys.REFERENCED_TABLE_SCHEMA'",
",",
"'FROM information_schema.REFERENTIAL_CONSTRAINTS const'",
",",
"'INNER JOIN information_schema.KEY_COLUMN_USAGE const_keys ON ( '",
",",
"'const_keys.CONSTRAINT_SCHEMA = const.CONSTRAINT_SCHEMA'",
",",
"'AND const_keys.CONSTRAINT_NAME = const.CONSTRAINT_NAME )'",
",",
"'WHERE const.CONSTRAINT_SCHEMA = ?'",
",",
"'AND const.TABLE_NAME = ?;'",
"]",
".",
"join",
"(",
"' '",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"var",
"q",
"=",
"''",
",",
"params",
"=",
"Array",
"(",
")",
",",
"stmt",
"=",
"0",
";",
"if",
"(",
"tables",
".",
"tables",
"[",
"0",
"]",
"[",
"i",
"]",
")",
"{",
"q",
"=",
"query",
";",
"params",
".",
"push",
"(",
"config",
".",
"database",
")",
";",
"params",
".",
"push",
"(",
"tables",
".",
"tables",
"[",
"0",
"]",
"[",
"i",
"]",
")",
";",
"}",
"else",
"++",
"stmt",
";",
"if",
"(",
"tables",
".",
"tables",
"[",
"1",
"]",
"[",
"i",
"]",
")",
"{",
"q",
"+=",
"query",
";",
"params",
".",
"push",
"(",
"config",
".",
"database_diff",
")",
";",
"params",
".",
"push",
"(",
"tables",
".",
"tables",
"[",
"1",
"]",
"[",
"i",
"]",
")",
";",
"}",
"(",
"function",
"(",
"stmt",
",",
"i",
")",
"{",
"self",
".",
"runSql",
"(",
"q",
",",
"params",
",",
"{",
"useArray",
":",
"true",
"}",
")",
".",
"on",
"(",
"'result'",
",",
"function",
"(",
"res",
")",
"{",
"var",
"local",
"=",
"stmt",
"++",
";",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"row",
")",
"{",
"constraint",
"=",
"Array",
"(",
")",
";",
"if",
"(",
"!",
"db",
"[",
"local",
"]",
"[",
"tables",
".",
"tables",
"[",
"local",
"]",
"[",
"i",
"]",
"]",
")",
"db",
"[",
"local",
"]",
"[",
"tables",
".",
"tables",
"[",
"local",
"]",
"[",
"i",
"]",
"]",
"=",
"Array",
"(",
")",
";",
"constraint",
"[",
"0",
"]",
"=",
"row",
"[",
"0",
"]",
";",
"constraint",
"[",
"1",
"]",
"=",
"row",
"[",
"6",
"]",
";",
"constraint",
"[",
"2",
"]",
"=",
"row",
"[",
"9",
"]",
";",
"constraint",
"[",
"3",
"]",
"=",
"row",
"[",
"3",
"]",
";",
"constraint",
"[",
"4",
"]",
"=",
"row",
"[",
"8",
"]",
";",
"constraint",
"[",
"5",
"]",
"=",
"row",
"[",
"7",
"]",
";",
"constraint",
"[",
"6",
"]",
"=",
"row",
"[",
"4",
"]",
";",
"constraint",
"[",
"7",
"]",
"=",
"row",
"[",
"5",
"]",
";",
"db",
"[",
"local",
"]",
"[",
"tables",
".",
"tables",
"[",
"local",
"]",
"[",
"i",
"]",
"]",
".",
"push",
"(",
"constraint",
")",
";",
"}",
")",
";",
"}",
")",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"++",
"counter",
">=",
"len",
")",
"callback",
"(",
"context",
",",
"db",
")",
";",
"}",
")",
";",
"}",
")",
"(",
"stmt",
",",
"i",
")",
";",
"}",
"}"
]
| Returns an array containing the foreign keys.
General return information:
This array has 3 layers, the final information layer has
8 elements.
Array Format:
Layer 1:
[0] = real table, [1] = diff table
Layer 2:
['tablename'] = Array for final table indizies information
Layer 3 (Result formatting):
[0] = foreign_key_name, [1] = column_name, [2] = referenced_table_schema,
[3] = referenced_table_name, [4] = referenced_column_name,
[5] = position_in_unique_constraint, [6] = on_update,
[7] = on_delete
@return array | [
"Returns",
"an",
"array",
"containing",
"the",
"foreign",
"keys",
"."
]
| b3ca76d7adb0660044b464c3564a852a454d24f0 | https://github.com/wzrdtales/umigrate-mariadb/blob/b3ca76d7adb0660044b464c3564a852a454d24f0/index.js#L451-L531 | train |
|
Arcath/etch-router | docs/js/components/static.js | function (wholeMatch, match, left, right) {
// unescape match to prevent double escaping
match = htmlunencode(match);
return left + hljs.highlightAuto(match).value + right;
} | javascript | function (wholeMatch, match, left, right) {
// unescape match to prevent double escaping
match = htmlunencode(match);
return left + hljs.highlightAuto(match).value + right;
} | [
"function",
"(",
"wholeMatch",
",",
"match",
",",
"left",
",",
"right",
")",
"{",
"match",
"=",
"htmlunencode",
"(",
"match",
")",
";",
"return",
"left",
"+",
"hljs",
".",
"highlightAuto",
"(",
"match",
")",
".",
"value",
"+",
"right",
";",
"}"
]
| use new shodown's regexp engine to conditionally parse codeblocks | [
"use",
"new",
"shodown",
"s",
"regexp",
"engine",
"to",
"conditionally",
"parse",
"codeblocks"
]
| 90b1e2f69c567d6b9f7165a13ca0144e789d7edb | https://github.com/Arcath/etch-router/blob/90b1e2f69c567d6b9f7165a13ca0144e789d7edb/docs/js/components/static.js#L23-L27 | train |
|
heroqu/hash-through | index.js | HashThrough | function HashThrough (createHash) {
const hashThrough = new Transform()
const hash = createHash()
hashThrough._transform = function (chunk, encoding, cb) {
setImmediate(_ => {
try {
hash.update(chunk)
cb(null, chunk)
} catch (err) {
cb(err)
}
})
}
// bind the digest function to hash object
hashThrough.digest = format => hash.digest(format)
return hashThrough
} | javascript | function HashThrough (createHash) {
const hashThrough = new Transform()
const hash = createHash()
hashThrough._transform = function (chunk, encoding, cb) {
setImmediate(_ => {
try {
hash.update(chunk)
cb(null, chunk)
} catch (err) {
cb(err)
}
})
}
// bind the digest function to hash object
hashThrough.digest = format => hash.digest(format)
return hashThrough
} | [
"function",
"HashThrough",
"(",
"createHash",
")",
"{",
"const",
"hashThrough",
"=",
"new",
"Transform",
"(",
")",
"const",
"hash",
"=",
"createHash",
"(",
")",
"hashThrough",
".",
"_transform",
"=",
"function",
"(",
"chunk",
",",
"encoding",
",",
"cb",
")",
"{",
"setImmediate",
"(",
"_",
"=>",
"{",
"try",
"{",
"hash",
".",
"update",
"(",
"chunk",
")",
"cb",
"(",
"null",
",",
"chunk",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
"}",
"}",
")",
"}",
"hashThrough",
".",
"digest",
"=",
"format",
"=>",
"hash",
".",
"digest",
"(",
"format",
")",
"return",
"hashThrough",
"}"
]
| Effectively a PassThrough stream that taps to chunks flow
and accumulating the hash | [
"Effectively",
"a",
"PassThrough",
"stream",
"that",
"taps",
"to",
"chunks",
"flow",
"and",
"accumulating",
"the",
"hash"
]
| 47a8d55b581cbc6f22f1b2be4f8f88ceeb5612b3 | https://github.com/heroqu/hash-through/blob/47a8d55b581cbc6f22f1b2be4f8f88ceeb5612b3/index.js#L11-L31 | train |
kuhnza/node-tubesio | lib/tubesio/logging.js | Logger | function Logger(level) {
if (_.isString(level) && _.has(LogLevel, level)) {
this.level = LogLevel[level];
} else if (_.isNumber(level) && level >= 0 && level <= 4) {
this.level = level;
} else {
this.level = LogLevel.info;
}
} | javascript | function Logger(level) {
if (_.isString(level) && _.has(LogLevel, level)) {
this.level = LogLevel[level];
} else if (_.isNumber(level) && level >= 0 && level <= 4) {
this.level = level;
} else {
this.level = LogLevel.info;
}
} | [
"function",
"Logger",
"(",
"level",
")",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"level",
")",
"&&",
"_",
".",
"has",
"(",
"LogLevel",
",",
"level",
")",
")",
"{",
"this",
".",
"level",
"=",
"LogLevel",
"[",
"level",
"]",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isNumber",
"(",
"level",
")",
"&&",
"level",
">=",
"0",
"&&",
"level",
"<=",
"4",
")",
"{",
"this",
".",
"level",
"=",
"level",
";",
"}",
"else",
"{",
"this",
".",
"level",
"=",
"LogLevel",
".",
"info",
";",
"}",
"}"
]
| Logger that logs exclusively to stderr so that logging doesn't pollute the
scraper result which is written to stdout. | [
"Logger",
"that",
"logs",
"exclusively",
"to",
"stderr",
"so",
"that",
"logging",
"doesn",
"t",
"pollute",
"the",
"scraper",
"result",
"which",
"is",
"written",
"to",
"stdout",
"."
]
| 198d005de764480485fe038d1832ccb0f6e0596e | https://github.com/kuhnza/node-tubesio/blob/198d005de764480485fe038d1832ccb0f6e0596e/lib/tubesio/logging.js#L27-L35 | train |
hl198181/neptune | misc/demo/public/vendor/angular/docs/js/docs.js | localSearchFactory | function localSearchFactory($http, $timeout, NG_PAGES) {
console.log('Using Local Search Index');
// Create the lunr index
var index = lunr(function() {
this.ref('path');
this.field('titleWords', {boost: 50});
this.field('members', { boost: 40});
this.field('keywords', { boost : 20 });
});
// Delay building the index by loading the data asynchronously
var indexReadyPromise = $http.get('js/search-data.json').then(function(response) {
var searchData = response.data;
// Delay building the index for 500ms to allow the page to render
return $timeout(function() {
// load the page data into the index
angular.forEach(searchData, function(page) {
index.add(page);
});
}, 500);
});
// The actual service is a function that takes a query string and
// returns a promise to the search results
// (In this case we just resolve the promise immediately as it is not
// inherently an async process)
return function(q) {
return indexReadyPromise.then(function() {
var hits = index.search(q);
var results = [];
angular.forEach(hits, function(hit) {
results.push(NG_PAGES[hit.ref]);
});
return results;
});
};
} | javascript | function localSearchFactory($http, $timeout, NG_PAGES) {
console.log('Using Local Search Index');
// Create the lunr index
var index = lunr(function() {
this.ref('path');
this.field('titleWords', {boost: 50});
this.field('members', { boost: 40});
this.field('keywords', { boost : 20 });
});
// Delay building the index by loading the data asynchronously
var indexReadyPromise = $http.get('js/search-data.json').then(function(response) {
var searchData = response.data;
// Delay building the index for 500ms to allow the page to render
return $timeout(function() {
// load the page data into the index
angular.forEach(searchData, function(page) {
index.add(page);
});
}, 500);
});
// The actual service is a function that takes a query string and
// returns a promise to the search results
// (In this case we just resolve the promise immediately as it is not
// inherently an async process)
return function(q) {
return indexReadyPromise.then(function() {
var hits = index.search(q);
var results = [];
angular.forEach(hits, function(hit) {
results.push(NG_PAGES[hit.ref]);
});
return results;
});
};
} | [
"function",
"localSearchFactory",
"(",
"$http",
",",
"$timeout",
",",
"NG_PAGES",
")",
"{",
"console",
".",
"log",
"(",
"'Using Local Search Index'",
")",
";",
"var",
"index",
"=",
"lunr",
"(",
"function",
"(",
")",
"{",
"this",
".",
"ref",
"(",
"'path'",
")",
";",
"this",
".",
"field",
"(",
"'titleWords'",
",",
"{",
"boost",
":",
"50",
"}",
")",
";",
"this",
".",
"field",
"(",
"'members'",
",",
"{",
"boost",
":",
"40",
"}",
")",
";",
"this",
".",
"field",
"(",
"'keywords'",
",",
"{",
"boost",
":",
"20",
"}",
")",
";",
"}",
")",
";",
"var",
"indexReadyPromise",
"=",
"$http",
".",
"get",
"(",
"'js/search-data.json'",
")",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"var",
"searchData",
"=",
"response",
".",
"data",
";",
"return",
"$timeout",
"(",
"function",
"(",
")",
"{",
"angular",
".",
"forEach",
"(",
"searchData",
",",
"function",
"(",
"page",
")",
"{",
"index",
".",
"add",
"(",
"page",
")",
";",
"}",
")",
";",
"}",
",",
"500",
")",
";",
"}",
")",
";",
"return",
"function",
"(",
"q",
")",
"{",
"return",
"indexReadyPromise",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"hits",
"=",
"index",
".",
"search",
"(",
"q",
")",
";",
"var",
"results",
"=",
"[",
"]",
";",
"angular",
".",
"forEach",
"(",
"hits",
",",
"function",
"(",
"hit",
")",
"{",
"results",
".",
"push",
"(",
"NG_PAGES",
"[",
"hit",
".",
"ref",
"]",
")",
";",
"}",
")",
";",
"return",
"results",
";",
"}",
")",
";",
"}",
";",
"}"
]
| This version of the service builds the index in the current thread, which blocks rendering and other browser activities. It should only be used where the browser does not support WebWorkers | [
"This",
"version",
"of",
"the",
"service",
"builds",
"the",
"index",
"in",
"the",
"current",
"thread",
"which",
"blocks",
"rendering",
"and",
"other",
"browser",
"activities",
".",
"It",
"should",
"only",
"be",
"used",
"where",
"the",
"browser",
"does",
"not",
"support",
"WebWorkers"
]
| 88030bb4222945900e6a225469380cc43a016c13 | https://github.com/hl198181/neptune/blob/88030bb4222945900e6a225469380cc43a016c13/misc/demo/public/vendor/angular/docs/js/docs.js#L354-L392 | train |
hl198181/neptune | misc/demo/public/vendor/angular/docs/js/docs.js | webWorkerSearchFactory | function webWorkerSearchFactory($q, $rootScope, NG_PAGES) {
console.log('Using WebWorker Search Index')
var searchIndex = $q.defer();
var results;
var worker = new Worker('js/search-worker.js');
// The worker will send us a message in two situations:
// - when the index has been built, ready to run a query
// - when it has completed a search query and the results are available
worker.onmessage = function(oEvent) {
$rootScope.$apply(function() {
switch(oEvent.data.e) {
case 'index-ready':
searchIndex.resolve();
break;
case 'query-ready':
var pages = oEvent.data.d.map(function(path) {
return NG_PAGES[path];
});
results.resolve(pages);
break;
}
});
};
// The actual service is a function that takes a query string and
// returns a promise to the search results
return function(q) {
// We only run the query once the index is ready
return searchIndex.promise.then(function() {
results = $q.defer();
worker.postMessage({ q: q });
return results.promise;
});
};
} | javascript | function webWorkerSearchFactory($q, $rootScope, NG_PAGES) {
console.log('Using WebWorker Search Index')
var searchIndex = $q.defer();
var results;
var worker = new Worker('js/search-worker.js');
// The worker will send us a message in two situations:
// - when the index has been built, ready to run a query
// - when it has completed a search query and the results are available
worker.onmessage = function(oEvent) {
$rootScope.$apply(function() {
switch(oEvent.data.e) {
case 'index-ready':
searchIndex.resolve();
break;
case 'query-ready':
var pages = oEvent.data.d.map(function(path) {
return NG_PAGES[path];
});
results.resolve(pages);
break;
}
});
};
// The actual service is a function that takes a query string and
// returns a promise to the search results
return function(q) {
// We only run the query once the index is ready
return searchIndex.promise.then(function() {
results = $q.defer();
worker.postMessage({ q: q });
return results.promise;
});
};
} | [
"function",
"webWorkerSearchFactory",
"(",
"$q",
",",
"$rootScope",
",",
"NG_PAGES",
")",
"{",
"console",
".",
"log",
"(",
"'Using WebWorker Search Index'",
")",
"var",
"searchIndex",
"=",
"$q",
".",
"defer",
"(",
")",
";",
"var",
"results",
";",
"var",
"worker",
"=",
"new",
"Worker",
"(",
"'js/search-worker.js'",
")",
";",
"worker",
".",
"onmessage",
"=",
"function",
"(",
"oEvent",
")",
"{",
"$rootScope",
".",
"$apply",
"(",
"function",
"(",
")",
"{",
"switch",
"(",
"oEvent",
".",
"data",
".",
"e",
")",
"{",
"case",
"'index-ready'",
":",
"searchIndex",
".",
"resolve",
"(",
")",
";",
"break",
";",
"case",
"'query-ready'",
":",
"var",
"pages",
"=",
"oEvent",
".",
"data",
".",
"d",
".",
"map",
"(",
"function",
"(",
"path",
")",
"{",
"return",
"NG_PAGES",
"[",
"path",
"]",
";",
"}",
")",
";",
"results",
".",
"resolve",
"(",
"pages",
")",
";",
"break",
";",
"}",
"}",
")",
";",
"}",
";",
"return",
"function",
"(",
"q",
")",
"{",
"return",
"searchIndex",
".",
"promise",
".",
"then",
"(",
"function",
"(",
")",
"{",
"results",
"=",
"$q",
".",
"defer",
"(",
")",
";",
"worker",
".",
"postMessage",
"(",
"{",
"q",
":",
"q",
"}",
")",
";",
"return",
"results",
".",
"promise",
";",
"}",
")",
";",
"}",
";",
"}"
]
| This version of the service builds the index in a WebWorker, which does not block rendering and other browser activities. It should only be used where the browser does support WebWorkers | [
"This",
"version",
"of",
"the",
"service",
"builds",
"the",
"index",
"in",
"a",
"WebWorker",
"which",
"does",
"not",
"block",
"rendering",
"and",
"other",
"browser",
"activities",
".",
"It",
"should",
"only",
"be",
"used",
"where",
"the",
"browser",
"does",
"support",
"WebWorkers"
]
| 88030bb4222945900e6a225469380cc43a016c13 | https://github.com/hl198181/neptune/blob/88030bb4222945900e6a225469380cc43a016c13/misc/demo/public/vendor/angular/docs/js/docs.js#L398-L439 | train |
dominictarr/level-queue | index.js | queue | function queue (job, value, put) {
var ts = timestamp()
var key = toKey(job, ts)
var id = hash(job+':'+value)
if(pending[id]) return null //this job is already queued.
pending[id] = Date.now()
if(put === false) {
//return the job to be queued, to include it in a batch insert.
return {
type: 'put',
key: Buffer.isBuffer(key) ? key : new Buffer(key),
value: Buffer.isBuffer(key) ? value : new Buffer(value)
}
} else {
db.put(key, value)
}
} | javascript | function queue (job, value, put) {
var ts = timestamp()
var key = toKey(job, ts)
var id = hash(job+':'+value)
if(pending[id]) return null //this job is already queued.
pending[id] = Date.now()
if(put === false) {
//return the job to be queued, to include it in a batch insert.
return {
type: 'put',
key: Buffer.isBuffer(key) ? key : new Buffer(key),
value: Buffer.isBuffer(key) ? value : new Buffer(value)
}
} else {
db.put(key, value)
}
} | [
"function",
"queue",
"(",
"job",
",",
"value",
",",
"put",
")",
"{",
"var",
"ts",
"=",
"timestamp",
"(",
")",
"var",
"key",
"=",
"toKey",
"(",
"job",
",",
"ts",
")",
"var",
"id",
"=",
"hash",
"(",
"job",
"+",
"':'",
"+",
"value",
")",
"if",
"(",
"pending",
"[",
"id",
"]",
")",
"return",
"null",
"pending",
"[",
"id",
"]",
"=",
"Date",
".",
"now",
"(",
")",
"if",
"(",
"put",
"===",
"false",
")",
"{",
"return",
"{",
"type",
":",
"'put'",
",",
"key",
":",
"Buffer",
".",
"isBuffer",
"(",
"key",
")",
"?",
"key",
":",
"new",
"Buffer",
"(",
"key",
")",
",",
"value",
":",
"Buffer",
".",
"isBuffer",
"(",
"key",
")",
"?",
"value",
":",
"new",
"Buffer",
"(",
"value",
")",
"}",
"}",
"else",
"{",
"db",
".",
"put",
"(",
"key",
",",
"value",
")",
"}",
"}"
]
| put=false means return a job to be queued | [
"put",
"=",
"false",
"means",
"return",
"a",
"job",
"to",
"be",
"queued"
]
| 2ac2ee1f088a86d14e58e4d5c140498e7ba30875 | https://github.com/dominictarr/level-queue/blob/2ac2ee1f088a86d14e58e4d5c140498e7ba30875/index.js#L117-L135 | train |
pinyin/outline | vendor/transformation-matrix/skew.js | skew | function skew(ax, ay) {
return {
a: 1, c: tan(ax), e: 0,
b: tan(ay), d: 1, f: 0
};
} | javascript | function skew(ax, ay) {
return {
a: 1, c: tan(ax), e: 0,
b: tan(ay), d: 1, f: 0
};
} | [
"function",
"skew",
"(",
"ax",
",",
"ay",
")",
"{",
"return",
"{",
"a",
":",
"1",
",",
"c",
":",
"tan",
"(",
"ax",
")",
",",
"e",
":",
"0",
",",
"b",
":",
"tan",
"(",
"ay",
")",
",",
"d",
":",
"1",
",",
"f",
":",
"0",
"}",
";",
"}"
]
| Calculate a skew matrix
@param ax Skew on axis x
@param ay Skew on axis y
@returns {{a: number, b: number, c: number, e: number, d: number, f: number}} Affine matrix | [
"Calculate",
"a",
"skew",
"matrix"
]
| e49f05d2f8ab384f5b1d71b2b10875cd48d41051 | https://github.com/pinyin/outline/blob/e49f05d2f8ab384f5b1d71b2b10875cd48d41051/vendor/transformation-matrix/skew.js#L18-L23 | train |
pinyin/outline | vendor/transformation-matrix/skew.js | skewDEG | function skewDEG(ax, ay) {
return skew(ax * Math.PI / 180, ay * Math.PI / 180);
} | javascript | function skewDEG(ax, ay) {
return skew(ax * Math.PI / 180, ay * Math.PI / 180);
} | [
"function",
"skewDEG",
"(",
"ax",
",",
"ay",
")",
"{",
"return",
"skew",
"(",
"ax",
"*",
"Math",
".",
"PI",
"/",
"180",
",",
"ay",
"*",
"Math",
".",
"PI",
"/",
"180",
")",
";",
"}"
]
| Calculate a skew matrix using DEG angles
@param ax Skew on axis x
@param ay Skew on axis y
@returns {{a: number, b: number, c: number, e: number, d: number, f: number}} Affine matrix | [
"Calculate",
"a",
"skew",
"matrix",
"using",
"DEG",
"angles"
]
| e49f05d2f8ab384f5b1d71b2b10875cd48d41051 | https://github.com/pinyin/outline/blob/e49f05d2f8ab384f5b1d71b2b10875cd48d41051/vendor/transformation-matrix/skew.js#L31-L33 | train |
Industryswarm/isnode-mod-data | lib/mongodb/bson/lib/bson/objectid.js | ObjectID | function ObjectID(id) {
// Duck-typing to support ObjectId from different npm packages
if (id instanceof ObjectID) return id;
if (!(this instanceof ObjectID)) return new ObjectID(id);
this._bsontype = 'ObjectID';
// The most common usecase (blank id, new objectId instance)
if (id == null || typeof id === 'number') {
// Generate a new id
this.id = this.generate(id);
// If we are caching the hex string
if (ObjectID.cacheHexString) this.__id = this.toString('hex');
// Return the object
return;
}
// Check if the passed in id is valid
var valid = ObjectID.isValid(id);
// Throw an error if it's not a valid setup
if (!valid && id != null) {
throw new Error(
'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'
);
} else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) {
return new ObjectID(new Buffer(id, 'hex'));
} else if (valid && typeof id === 'string' && id.length === 24) {
return ObjectID.createFromHexString(id);
} else if (id != null && id.length === 12) {
// assume 12 byte string
this.id = id;
} else if (id != null && id.toHexString) {
// Duck-typing to support ObjectId from different npm packages
return id;
} else {
throw new Error(
'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'
);
}
if (ObjectID.cacheHexString) this.__id = this.toString('hex');
} | javascript | function ObjectID(id) {
// Duck-typing to support ObjectId from different npm packages
if (id instanceof ObjectID) return id;
if (!(this instanceof ObjectID)) return new ObjectID(id);
this._bsontype = 'ObjectID';
// The most common usecase (blank id, new objectId instance)
if (id == null || typeof id === 'number') {
// Generate a new id
this.id = this.generate(id);
// If we are caching the hex string
if (ObjectID.cacheHexString) this.__id = this.toString('hex');
// Return the object
return;
}
// Check if the passed in id is valid
var valid = ObjectID.isValid(id);
// Throw an error if it's not a valid setup
if (!valid && id != null) {
throw new Error(
'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'
);
} else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) {
return new ObjectID(new Buffer(id, 'hex'));
} else if (valid && typeof id === 'string' && id.length === 24) {
return ObjectID.createFromHexString(id);
} else if (id != null && id.length === 12) {
// assume 12 byte string
this.id = id;
} else if (id != null && id.toHexString) {
// Duck-typing to support ObjectId from different npm packages
return id;
} else {
throw new Error(
'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'
);
}
if (ObjectID.cacheHexString) this.__id = this.toString('hex');
} | [
"function",
"ObjectID",
"(",
"id",
")",
"{",
"if",
"(",
"id",
"instanceof",
"ObjectID",
")",
"return",
"id",
";",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"ObjectID",
")",
")",
"return",
"new",
"ObjectID",
"(",
"id",
")",
";",
"this",
".",
"_bsontype",
"=",
"'ObjectID'",
";",
"if",
"(",
"id",
"==",
"null",
"||",
"typeof",
"id",
"===",
"'number'",
")",
"{",
"this",
".",
"id",
"=",
"this",
".",
"generate",
"(",
"id",
")",
";",
"if",
"(",
"ObjectID",
".",
"cacheHexString",
")",
"this",
".",
"__id",
"=",
"this",
".",
"toString",
"(",
"'hex'",
")",
";",
"return",
";",
"}",
"var",
"valid",
"=",
"ObjectID",
".",
"isValid",
"(",
"id",
")",
";",
"if",
"(",
"!",
"valid",
"&&",
"id",
"!=",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'",
")",
";",
"}",
"else",
"if",
"(",
"valid",
"&&",
"typeof",
"id",
"===",
"'string'",
"&&",
"id",
".",
"length",
"===",
"24",
"&&",
"hasBufferType",
")",
"{",
"return",
"new",
"ObjectID",
"(",
"new",
"Buffer",
"(",
"id",
",",
"'hex'",
")",
")",
";",
"}",
"else",
"if",
"(",
"valid",
"&&",
"typeof",
"id",
"===",
"'string'",
"&&",
"id",
".",
"length",
"===",
"24",
")",
"{",
"return",
"ObjectID",
".",
"createFromHexString",
"(",
"id",
")",
";",
"}",
"else",
"if",
"(",
"id",
"!=",
"null",
"&&",
"id",
".",
"length",
"===",
"12",
")",
"{",
"this",
".",
"id",
"=",
"id",
";",
"}",
"else",
"if",
"(",
"id",
"!=",
"null",
"&&",
"id",
".",
"toHexString",
")",
"{",
"return",
"id",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'",
")",
";",
"}",
"if",
"(",
"ObjectID",
".",
"cacheHexString",
")",
"this",
".",
"__id",
"=",
"this",
".",
"toString",
"(",
"'hex'",
")",
";",
"}"
]
| Create a new ObjectID instance
@class
@param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number.
@property {number} generationTime The generation time of this ObjectId instance
@return {ObjectID} instance of ObjectID. | [
"Create",
"a",
"new",
"ObjectID",
"instance"
]
| 5adc639b88a0d72cbeef23a6b5df7f4540745089 | https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/bson/lib/bson/objectid.js#L35-L77 | train |
nathanfrancy/safetext | lib/index.js | init | function init(masterPassword, map) {
var fileContents = JSON.stringify(map);
var encryptedFileContents = encryption.encrypt(fileContents, masterPassword);
file.writeToFile(encryptedFileContents);
} | javascript | function init(masterPassword, map) {
var fileContents = JSON.stringify(map);
var encryptedFileContents = encryption.encrypt(fileContents, masterPassword);
file.writeToFile(encryptedFileContents);
} | [
"function",
"init",
"(",
"masterPassword",
",",
"map",
")",
"{",
"var",
"fileContents",
"=",
"JSON",
".",
"stringify",
"(",
"map",
")",
";",
"var",
"encryptedFileContents",
"=",
"encryption",
".",
"encrypt",
"(",
"fileContents",
",",
"masterPassword",
")",
";",
"file",
".",
"writeToFile",
"(",
"encryptedFileContents",
")",
";",
"}"
]
| Make a new safetext file with encrypted contents.
@param masterPassword
@param map
@returns {Promise.<TResult>} | [
"Make",
"a",
"new",
"safetext",
"file",
"with",
"encrypted",
"contents",
"."
]
| 960733dacae4edd522f35178a99fc80e4ac8d096 | https://github.com/nathanfrancy/safetext/blob/960733dacae4edd522f35178a99fc80e4ac8d096/lib/index.js#L10-L14 | train |
nathanfrancy/safetext | lib/index.js | getContents | function getContents(masterPassword) {
var encryptedContents = file.readFile();
try {
var contents = encryption.decrypt(encryptedContents, masterPassword);
return JSON.parse(contents);
} catch(err) {
console.log(err);
throw new Error("Error reading file contents. This most likely means the provided password is wrong.");
}
} | javascript | function getContents(masterPassword) {
var encryptedContents = file.readFile();
try {
var contents = encryption.decrypt(encryptedContents, masterPassword);
return JSON.parse(contents);
} catch(err) {
console.log(err);
throw new Error("Error reading file contents. This most likely means the provided password is wrong.");
}
} | [
"function",
"getContents",
"(",
"masterPassword",
")",
"{",
"var",
"encryptedContents",
"=",
"file",
".",
"readFile",
"(",
")",
";",
"try",
"{",
"var",
"contents",
"=",
"encryption",
".",
"decrypt",
"(",
"encryptedContents",
",",
"masterPassword",
")",
";",
"return",
"JSON",
".",
"parse",
"(",
"contents",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"err",
")",
";",
"throw",
"new",
"Error",
"(",
"\"Error reading file contents. This most likely means the provided password is wrong.\"",
")",
";",
"}",
"}"
]
| Read object out of safetext, must include master password.
@param masterPassword
@returns {Promise.<TResult>} | [
"Read",
"object",
"out",
"of",
"safetext",
"must",
"include",
"master",
"password",
"."
]
| 960733dacae4edd522f35178a99fc80e4ac8d096 | https://github.com/nathanfrancy/safetext/blob/960733dacae4edd522f35178a99fc80e4ac8d096/lib/index.js#L21-L30 | train |
nathanfrancy/safetext | lib/index.js | getKey | function getKey(key, masterPassword) {
var contents = getContents(masterPassword);
if (contents[key] != undefined) return contents[key];
else throw new Error(`Unable to find key '${key}' in password safe.`);
} | javascript | function getKey(key, masterPassword) {
var contents = getContents(masterPassword);
if (contents[key] != undefined) return contents[key];
else throw new Error(`Unable to find key '${key}' in password safe.`);
} | [
"function",
"getKey",
"(",
"key",
",",
"masterPassword",
")",
"{",
"var",
"contents",
"=",
"getContents",
"(",
"masterPassword",
")",
";",
"if",
"(",
"contents",
"[",
"key",
"]",
"!=",
"undefined",
")",
"return",
"contents",
"[",
"key",
"]",
";",
"else",
"throw",
"new",
"Error",
"(",
"`",
"${",
"key",
"}",
"`",
")",
";",
"}"
]
| Get a specific key value from safetext file.
@param key
@param masterPassword
@returns {Promise.<TResult>} | [
"Get",
"a",
"specific",
"key",
"value",
"from",
"safetext",
"file",
"."
]
| 960733dacae4edd522f35178a99fc80e4ac8d096 | https://github.com/nathanfrancy/safetext/blob/960733dacae4edd522f35178a99fc80e4ac8d096/lib/index.js#L54-L58 | train |
nathanfrancy/safetext | lib/index.js | writeKey | function writeKey(key, value, masterPassword) {
var contents = getContents(masterPassword);
contents[key] = value;
var fileContents = JSON.stringify(contents);
var encryptedFileContents = encryption.encrypt(fileContents, masterPassword);
file.writeToFile(encryptedFileContents);
} | javascript | function writeKey(key, value, masterPassword) {
var contents = getContents(masterPassword);
contents[key] = value;
var fileContents = JSON.stringify(contents);
var encryptedFileContents = encryption.encrypt(fileContents, masterPassword);
file.writeToFile(encryptedFileContents);
} | [
"function",
"writeKey",
"(",
"key",
",",
"value",
",",
"masterPassword",
")",
"{",
"var",
"contents",
"=",
"getContents",
"(",
"masterPassword",
")",
";",
"contents",
"[",
"key",
"]",
"=",
"value",
";",
"var",
"fileContents",
"=",
"JSON",
".",
"stringify",
"(",
"contents",
")",
";",
"var",
"encryptedFileContents",
"=",
"encryption",
".",
"encrypt",
"(",
"fileContents",
",",
"masterPassword",
")",
";",
"file",
".",
"writeToFile",
"(",
"encryptedFileContents",
")",
";",
"}"
]
| Writes a key to the safetext file.
@param key
@param value
@param masterPassword
@returns {Promise.<TResult>} | [
"Writes",
"a",
"key",
"to",
"the",
"safetext",
"file",
"."
]
| 960733dacae4edd522f35178a99fc80e4ac8d096 | https://github.com/nathanfrancy/safetext/blob/960733dacae4edd522f35178a99fc80e4ac8d096/lib/index.js#L67-L73 | train |
nathanfrancy/safetext | lib/index.js | removeKey | function removeKey(key, masterPassword) {
var contents = getContents(masterPassword);
if (contents[key] != undefined) delete contents[key];
var fileContents = JSON.stringify(contents);
var encryptedFileContents = encryption.encrypt(fileContents, masterPassword);
file.writeToFile(encryptedFileContents);
} | javascript | function removeKey(key, masterPassword) {
var contents = getContents(masterPassword);
if (contents[key] != undefined) delete contents[key];
var fileContents = JSON.stringify(contents);
var encryptedFileContents = encryption.encrypt(fileContents, masterPassword);
file.writeToFile(encryptedFileContents);
} | [
"function",
"removeKey",
"(",
"key",
",",
"masterPassword",
")",
"{",
"var",
"contents",
"=",
"getContents",
"(",
"masterPassword",
")",
";",
"if",
"(",
"contents",
"[",
"key",
"]",
"!=",
"undefined",
")",
"delete",
"contents",
"[",
"key",
"]",
";",
"var",
"fileContents",
"=",
"JSON",
".",
"stringify",
"(",
"contents",
")",
";",
"var",
"encryptedFileContents",
"=",
"encryption",
".",
"encrypt",
"(",
"fileContents",
",",
"masterPassword",
")",
";",
"file",
".",
"writeToFile",
"(",
"encryptedFileContents",
")",
";",
"}"
]
| Removes a key from the safetext password file.
@param key
@param masterPassword
@returns {Promise.<TResult>} | [
"Removes",
"a",
"key",
"from",
"the",
"safetext",
"password",
"file",
"."
]
| 960733dacae4edd522f35178a99fc80e4ac8d096 | https://github.com/nathanfrancy/safetext/blob/960733dacae4edd522f35178a99fc80e4ac8d096/lib/index.js#L81-L88 | train |
nathanfrancy/safetext | lib/index.js | changePassword | function changePassword(masterPassword, newPassword1, newPassword2) {
if (newPassword1 !== newPassword2) throw new Error("New passwords must match.");
else {
var contents = getContents(masterPassword);
init(newPassword1, contents);
}
} | javascript | function changePassword(masterPassword, newPassword1, newPassword2) {
if (newPassword1 !== newPassword2) throw new Error("New passwords must match.");
else {
var contents = getContents(masterPassword);
init(newPassword1, contents);
}
} | [
"function",
"changePassword",
"(",
"masterPassword",
",",
"newPassword1",
",",
"newPassword2",
")",
"{",
"if",
"(",
"newPassword1",
"!==",
"newPassword2",
")",
"throw",
"new",
"Error",
"(",
"\"New passwords must match.\"",
")",
";",
"else",
"{",
"var",
"contents",
"=",
"getContents",
"(",
"masterPassword",
")",
";",
"init",
"(",
"newPassword1",
",",
"contents",
")",
";",
"}",
"}"
]
| Changes the password of the safetext file.
@param masterPassword
@param newPassword1
@param newPassword2 | [
"Changes",
"the",
"password",
"of",
"the",
"safetext",
"file",
"."
]
| 960733dacae4edd522f35178a99fc80e4ac8d096 | https://github.com/nathanfrancy/safetext/blob/960733dacae4edd522f35178a99fc80e4ac8d096/lib/index.js#L96-L102 | train |
ibc/eventcollector | lib/eventcollector.js | function(total, timeout) {
events.EventEmitter.call(this);
if (! isPositiveInteger(total)) {
throw new Error('`total` must be a positive integer');
}
if (timeout && ! isPositiveInteger(timeout)) {
throw new Error('`timeout` must be a positive integer');
}
this.destroyed = false;
this.total = total;
this.fired = 0;
if (timeout) {
this.timer = setTimeout(function() {
this.onTimeout();
}.bind(this), timeout);
}
} | javascript | function(total, timeout) {
events.EventEmitter.call(this);
if (! isPositiveInteger(total)) {
throw new Error('`total` must be a positive integer');
}
if (timeout && ! isPositiveInteger(timeout)) {
throw new Error('`timeout` must be a positive integer');
}
this.destroyed = false;
this.total = total;
this.fired = 0;
if (timeout) {
this.timer = setTimeout(function() {
this.onTimeout();
}.bind(this), timeout);
}
} | [
"function",
"(",
"total",
",",
"timeout",
")",
"{",
"events",
".",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"if",
"(",
"!",
"isPositiveInteger",
"(",
"total",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'`total` must be a positive integer'",
")",
";",
"}",
"if",
"(",
"timeout",
"&&",
"!",
"isPositiveInteger",
"(",
"timeout",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'`timeout` must be a positive integer'",
")",
";",
"}",
"this",
".",
"destroyed",
"=",
"false",
";",
"this",
".",
"total",
"=",
"total",
";",
"this",
".",
"fired",
"=",
"0",
";",
"if",
"(",
"timeout",
")",
"{",
"this",
".",
"timer",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"this",
".",
"onTimeout",
"(",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
",",
"timeout",
")",
";",
"}",
"}"
]
| EventCollector class.
@class EventCollector
@constructor
@param {Number} total Number of events that must fire. | [
"EventCollector",
"class",
"."
]
| 685c533d50076a6d9d5b67bbeb5f9f081f53aa9a | https://github.com/ibc/eventcollector/blob/685c533d50076a6d9d5b67bbeb5f9f081f53aa9a/lib/eventcollector.js#L56-L75 | train |
|
switer/block-ast | index.js | _join | function _join(arr1, arr2) {
var len = arr1.length > arr2 ? arr1.length : arr2.length
var joinedArr = []
while(len --) {
joinedArr.push(arr1.shift())
joinedArr.push(arr2.shift())
}
// merge remains
return joinedArr.concat(arr1).concat(arr2)
} | javascript | function _join(arr1, arr2) {
var len = arr1.length > arr2 ? arr1.length : arr2.length
var joinedArr = []
while(len --) {
joinedArr.push(arr1.shift())
joinedArr.push(arr2.shift())
}
// merge remains
return joinedArr.concat(arr1).concat(arr2)
} | [
"function",
"_join",
"(",
"arr1",
",",
"arr2",
")",
"{",
"var",
"len",
"=",
"arr1",
".",
"length",
">",
"arr2",
"?",
"arr1",
".",
"length",
":",
"arr2",
".",
"length",
"var",
"joinedArr",
"=",
"[",
"]",
"while",
"(",
"len",
"--",
")",
"{",
"joinedArr",
".",
"push",
"(",
"arr1",
".",
"shift",
"(",
")",
")",
"joinedArr",
".",
"push",
"(",
"arr2",
".",
"shift",
"(",
")",
")",
"}",
"return",
"joinedArr",
".",
"concat",
"(",
"arr1",
")",
".",
"concat",
"(",
"arr2",
")",
"}"
]
| join arr2's items to arr
@param {Array} arr1 odd number index items
@param {Array} arr2 even number index items
@return {Array} new array with join result | [
"join",
"arr2",
"s",
"items",
"to",
"arr"
]
| cebc9b7671df8088f12538b9d748bbcbd4630f3e | https://github.com/switer/block-ast/blob/cebc9b7671df8088f12538b9d748bbcbd4630f3e/index.js#L14-L23 | train |
jansedivy/potion | examples/demo-pixi-bunny/pixi.dev.js | callCompat | function callCompat(obj) {
if(obj) {
obj = obj.prototype || obj;
PIXI.EventTarget.mixin(obj);
}
} | javascript | function callCompat(obj) {
if(obj) {
obj = obj.prototype || obj;
PIXI.EventTarget.mixin(obj);
}
} | [
"function",
"callCompat",
"(",
"obj",
")",
"{",
"if",
"(",
"obj",
")",
"{",
"obj",
"=",
"obj",
".",
"prototype",
"||",
"obj",
";",
"PIXI",
".",
"EventTarget",
".",
"mixin",
"(",
"obj",
")",
";",
"}",
"}"
]
| Backward compat from when this used to be a function | [
"Backward",
"compat",
"from",
"when",
"this",
"used",
"to",
"be",
"a",
"function"
]
| 2e740ee68898d8ec8a34f8a3b6ee8e8faffce253 | https://github.com/jansedivy/potion/blob/2e740ee68898d8ec8a34f8a3b6ee8e8faffce253/examples/demo-pixi-bunny/pixi.dev.js#L5459-L5464 | train |
jansedivy/potion | examples/demo-pixi-bunny/pixi.dev.js | function () {
var ikConstraints = this.ikConstraints;
var ikConstraintsCount = ikConstraints.length;
var arrayCount = ikConstraintsCount + 1;
var boneCache = this.boneCache;
if (boneCache.length > arrayCount) boneCache.length = arrayCount;
for (var i = 0, n = boneCache.length; i < n; i++)
boneCache[i].length = 0;
while (boneCache.length < arrayCount)
boneCache[boneCache.length] = [];
var nonIkBones = boneCache[0];
var bones = this.bones;
outer:
for (var i = 0, n = bones.length; i < n; i++) {
var bone = bones[i];
var current = bone;
do {
for (var ii = 0; ii < ikConstraintsCount; ii++) {
var ikConstraint = ikConstraints[ii];
var parent = ikConstraint.bones[0];
var child= ikConstraint.bones[ikConstraint.bones.length - 1];
while (true) {
if (current == child) {
boneCache[ii].push(bone);
boneCache[ii + 1].push(bone);
continue outer;
}
if (child == parent) break;
child = child.parent;
}
}
current = current.parent;
} while (current);
nonIkBones[nonIkBones.length] = bone;
}
} | javascript | function () {
var ikConstraints = this.ikConstraints;
var ikConstraintsCount = ikConstraints.length;
var arrayCount = ikConstraintsCount + 1;
var boneCache = this.boneCache;
if (boneCache.length > arrayCount) boneCache.length = arrayCount;
for (var i = 0, n = boneCache.length; i < n; i++)
boneCache[i].length = 0;
while (boneCache.length < arrayCount)
boneCache[boneCache.length] = [];
var nonIkBones = boneCache[0];
var bones = this.bones;
outer:
for (var i = 0, n = bones.length; i < n; i++) {
var bone = bones[i];
var current = bone;
do {
for (var ii = 0; ii < ikConstraintsCount; ii++) {
var ikConstraint = ikConstraints[ii];
var parent = ikConstraint.bones[0];
var child= ikConstraint.bones[ikConstraint.bones.length - 1];
while (true) {
if (current == child) {
boneCache[ii].push(bone);
boneCache[ii + 1].push(bone);
continue outer;
}
if (child == parent) break;
child = child.parent;
}
}
current = current.parent;
} while (current);
nonIkBones[nonIkBones.length] = bone;
}
} | [
"function",
"(",
")",
"{",
"var",
"ikConstraints",
"=",
"this",
".",
"ikConstraints",
";",
"var",
"ikConstraintsCount",
"=",
"ikConstraints",
".",
"length",
";",
"var",
"arrayCount",
"=",
"ikConstraintsCount",
"+",
"1",
";",
"var",
"boneCache",
"=",
"this",
".",
"boneCache",
";",
"if",
"(",
"boneCache",
".",
"length",
">",
"arrayCount",
")",
"boneCache",
".",
"length",
"=",
"arrayCount",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"boneCache",
".",
"length",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"boneCache",
"[",
"i",
"]",
".",
"length",
"=",
"0",
";",
"while",
"(",
"boneCache",
".",
"length",
"<",
"arrayCount",
")",
"boneCache",
"[",
"boneCache",
".",
"length",
"]",
"=",
"[",
"]",
";",
"var",
"nonIkBones",
"=",
"boneCache",
"[",
"0",
"]",
";",
"var",
"bones",
"=",
"this",
".",
"bones",
";",
"outer",
":",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"bones",
".",
"length",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"var",
"bone",
"=",
"bones",
"[",
"i",
"]",
";",
"var",
"current",
"=",
"bone",
";",
"do",
"{",
"for",
"(",
"var",
"ii",
"=",
"0",
";",
"ii",
"<",
"ikConstraintsCount",
";",
"ii",
"++",
")",
"{",
"var",
"ikConstraint",
"=",
"ikConstraints",
"[",
"ii",
"]",
";",
"var",
"parent",
"=",
"ikConstraint",
".",
"bones",
"[",
"0",
"]",
";",
"var",
"child",
"=",
"ikConstraint",
".",
"bones",
"[",
"ikConstraint",
".",
"bones",
".",
"length",
"-",
"1",
"]",
";",
"while",
"(",
"true",
")",
"{",
"if",
"(",
"current",
"==",
"child",
")",
"{",
"boneCache",
"[",
"ii",
"]",
".",
"push",
"(",
"bone",
")",
";",
"boneCache",
"[",
"ii",
"+",
"1",
"]",
".",
"push",
"(",
"bone",
")",
";",
"continue",
"outer",
";",
"}",
"if",
"(",
"child",
"==",
"parent",
")",
"break",
";",
"child",
"=",
"child",
".",
"parent",
";",
"}",
"}",
"current",
"=",
"current",
".",
"parent",
";",
"}",
"while",
"(",
"current",
")",
";",
"nonIkBones",
"[",
"nonIkBones",
".",
"length",
"]",
"=",
"bone",
";",
"}",
"}"
]
| Caches information about bones and IK constraints. Must be called if bones or IK constraints are added or removed. | [
"Caches",
"information",
"about",
"bones",
"and",
"IK",
"constraints",
".",
"Must",
"be",
"called",
"if",
"bones",
"or",
"IK",
"constraints",
"are",
"added",
"or",
"removed",
"."
]
| 2e740ee68898d8ec8a34f8a3b6ee8e8faffce253 | https://github.com/jansedivy/potion/blob/2e740ee68898d8ec8a34f8a3b6ee8e8faffce253/examples/demo-pixi-bunny/pixi.dev.js#L15018-L15056 | train |
|
darrencruse/sugarlisp-async | gentab.js | asyncifyFunctions | function asyncifyFunctions(forms) {
// for each subexpression form...
forms.forEach(function(form) {
if (sl.isList(form)) {
if(sl.typeOf(form[0]) === 'symbol' &&
sl.valueOf(form[0]) === 'function' &&
asyncNeeded(form)) {
form.unshift(sl.atom("async"));
asyncifyFunctions(form);
}
else {
asyncifyFunctions(form);
}
}
});
} | javascript | function asyncifyFunctions(forms) {
// for each subexpression form...
forms.forEach(function(form) {
if (sl.isList(form)) {
if(sl.typeOf(form[0]) === 'symbol' &&
sl.valueOf(form[0]) === 'function' &&
asyncNeeded(form)) {
form.unshift(sl.atom("async"));
asyncifyFunctions(form);
}
else {
asyncifyFunctions(form);
}
}
});
} | [
"function",
"asyncifyFunctions",
"(",
"forms",
")",
"{",
"forms",
".",
"forEach",
"(",
"function",
"(",
"form",
")",
"{",
"if",
"(",
"sl",
".",
"isList",
"(",
"form",
")",
")",
"{",
"if",
"(",
"sl",
".",
"typeOf",
"(",
"form",
"[",
"0",
"]",
")",
"===",
"'symbol'",
"&&",
"sl",
".",
"valueOf",
"(",
"form",
"[",
"0",
"]",
")",
"===",
"'function'",
"&&",
"asyncNeeded",
"(",
"form",
")",
")",
"{",
"form",
".",
"unshift",
"(",
"sl",
".",
"atom",
"(",
"\"async\"",
")",
")",
";",
"asyncifyFunctions",
"(",
"form",
")",
";",
"}",
"else",
"{",
"asyncifyFunctions",
"(",
"form",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
]
| Had to timebox this - double check it later - I've yet to handle functions nested down under other functions - in that case isn't co.wrap needed to be added both at the lowest level and at the higher levels? Right now I stop at the higher levels. | [
"Had",
"to",
"timebox",
"this",
"-",
"double",
"check",
"it",
"later",
"-",
"I",
"ve",
"yet",
"to",
"handle",
"functions",
"nested",
"down",
"under",
"other",
"functions",
"-",
"in",
"that",
"case",
"isn",
"t",
"co",
".",
"wrap",
"needed",
"to",
"be",
"added",
"both",
"at",
"the",
"lowest",
"level",
"and",
"at",
"the",
"higher",
"levels?",
"Right",
"now",
"I",
"stop",
"at",
"the",
"higher",
"levels",
"."
]
| f7c909da54396165ddc42b73749f98a19e01c595 | https://github.com/darrencruse/sugarlisp-async/blob/f7c909da54396165ddc42b73749f98a19e01c595/gentab.js#L73-L88 | train |
psiolent/trigger-maker | index.js | on | function on(event, fn) {
if (typeof event !== 'string') {
throw new Error('"event" not a string');
}
if (!(fn instanceof Function)) {
throw new Error('"fn" not a Function');
}
if (hasListener(event, fn)) {
return false;
}
if (!hasListeners(event)) {
listeners[event] = [];
}
listeners[event].push(fn);
return true;
} | javascript | function on(event, fn) {
if (typeof event !== 'string') {
throw new Error('"event" not a string');
}
if (!(fn instanceof Function)) {
throw new Error('"fn" not a Function');
}
if (hasListener(event, fn)) {
return false;
}
if (!hasListeners(event)) {
listeners[event] = [];
}
listeners[event].push(fn);
return true;
} | [
"function",
"on",
"(",
"event",
",",
"fn",
")",
"{",
"if",
"(",
"typeof",
"event",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'\"event\" not a string'",
")",
";",
"}",
"if",
"(",
"!",
"(",
"fn",
"instanceof",
"Function",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'\"fn\" not a Function'",
")",
";",
"}",
"if",
"(",
"hasListener",
"(",
"event",
",",
"fn",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"hasListeners",
"(",
"event",
")",
")",
"{",
"listeners",
"[",
"event",
"]",
"=",
"[",
"]",
";",
"}",
"listeners",
"[",
"event",
"]",
".",
"push",
"(",
"fn",
")",
";",
"return",
"true",
";",
"}"
]
| Registers a listener for a type of event.
@param {string} event the event type
@param {Function} fn the function to invoke to handle the event
@return {boolean} true if listener set was modified, false if not | [
"Registers",
"a",
"listener",
"for",
"a",
"type",
"of",
"event",
"."
]
| 10d6a3e0f204f6d5bc8c4565ee29236158a4c4b7 | https://github.com/psiolent/trigger-maker/blob/10d6a3e0f204f6d5bc8c4565ee29236158a4c4b7/index.js#L26-L44 | train |
psiolent/trigger-maker | index.js | off | function off(event, fn) {
if (typeof event !== 'string') {
throw new Error('"event" not a string');
}
if (fn !== undefined && !(fn instanceof Function)) {
throw new Error('"fn" not a Function');
}
if (fn) {
// do we event have this listener
if (!hasListener(event, fn)) {
return false;
}
// unregistering a specific listener for the event
listeners[event] = listeners[event].filter(function(l) {
return l !== fn;
});
if (listeners[event].length === 0) {
delete listeners[event];
}
} else {
// do we have any listeners for this event?
if (!hasListeners(event)) {
return false;
}
// unregistering all listeners for the event
delete listeners[event];
}
return true;
} | javascript | function off(event, fn) {
if (typeof event !== 'string') {
throw new Error('"event" not a string');
}
if (fn !== undefined && !(fn instanceof Function)) {
throw new Error('"fn" not a Function');
}
if (fn) {
// do we event have this listener
if (!hasListener(event, fn)) {
return false;
}
// unregistering a specific listener for the event
listeners[event] = listeners[event].filter(function(l) {
return l !== fn;
});
if (listeners[event].length === 0) {
delete listeners[event];
}
} else {
// do we have any listeners for this event?
if (!hasListeners(event)) {
return false;
}
// unregistering all listeners for the event
delete listeners[event];
}
return true;
} | [
"function",
"off",
"(",
"event",
",",
"fn",
")",
"{",
"if",
"(",
"typeof",
"event",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'\"event\" not a string'",
")",
";",
"}",
"if",
"(",
"fn",
"!==",
"undefined",
"&&",
"!",
"(",
"fn",
"instanceof",
"Function",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'\"fn\" not a Function'",
")",
";",
"}",
"if",
"(",
"fn",
")",
"{",
"if",
"(",
"!",
"hasListener",
"(",
"event",
",",
"fn",
")",
")",
"{",
"return",
"false",
";",
"}",
"listeners",
"[",
"event",
"]",
"=",
"listeners",
"[",
"event",
"]",
".",
"filter",
"(",
"function",
"(",
"l",
")",
"{",
"return",
"l",
"!==",
"fn",
";",
"}",
")",
";",
"if",
"(",
"listeners",
"[",
"event",
"]",
".",
"length",
"===",
"0",
")",
"{",
"delete",
"listeners",
"[",
"event",
"]",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"!",
"hasListeners",
"(",
"event",
")",
")",
"{",
"return",
"false",
";",
"}",
"delete",
"listeners",
"[",
"event",
"]",
";",
"}",
"return",
"true",
";",
"}"
]
| Unregisters one or all listeners for an event.
@param event the event to unregister for
@param [fn] if provided, the listener function to unregister; if not
provided, all listeners will be unregistered
@return {boolean} true if listener set was modified, false if not | [
"Unregisters",
"one",
"or",
"all",
"listeners",
"for",
"an",
"event",
"."
]
| 10d6a3e0f204f6d5bc8c4565ee29236158a4c4b7 | https://github.com/psiolent/trigger-maker/blob/10d6a3e0f204f6d5bc8c4565ee29236158a4c4b7/index.js#L53-L85 | train |
psiolent/trigger-maker | index.js | fire | function fire(event) {
if (typeof event !== 'string') {
throw new Error('"event" not a string');
}
// any listeners registered?
if (!hasListeners(event)) {
return triggerObject;
}
// get optional arguments
var args = Array.prototype.slice.call(arguments, 1);
// invoke listener functions
listeners[event].slice(0).forEach(function(fn) {
fn.apply(global, args);
});
return triggerObject;
} | javascript | function fire(event) {
if (typeof event !== 'string') {
throw new Error('"event" not a string');
}
// any listeners registered?
if (!hasListeners(event)) {
return triggerObject;
}
// get optional arguments
var args = Array.prototype.slice.call(arguments, 1);
// invoke listener functions
listeners[event].slice(0).forEach(function(fn) {
fn.apply(global, args);
});
return triggerObject;
} | [
"function",
"fire",
"(",
"event",
")",
"{",
"if",
"(",
"typeof",
"event",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'\"event\" not a string'",
")",
";",
"}",
"if",
"(",
"!",
"hasListeners",
"(",
"event",
")",
")",
"{",
"return",
"triggerObject",
";",
"}",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"listeners",
"[",
"event",
"]",
".",
"slice",
"(",
"0",
")",
".",
"forEach",
"(",
"function",
"(",
"fn",
")",
"{",
"fn",
".",
"apply",
"(",
"global",
",",
"args",
")",
";",
"}",
")",
";",
"return",
"triggerObject",
";",
"}"
]
| Fires an event.
@param {string} event the event to fire
@param {...*} arguments to pass to the event listeners
@returns {Object} this trigger object | [
"Fires",
"an",
"event",
"."
]
| 10d6a3e0f204f6d5bc8c4565ee29236158a4c4b7 | https://github.com/psiolent/trigger-maker/blob/10d6a3e0f204f6d5bc8c4565ee29236158a4c4b7/index.js#L93-L112 | train |
psiolent/trigger-maker | index.js | fireAsync | function fireAsync(event) {
var args = Array.prototype.slice.call(arguments);
setTimeout(function() {
fire.apply(triggerObject, args);
}, 0);
return triggerObject;
} | javascript | function fireAsync(event) {
var args = Array.prototype.slice.call(arguments);
setTimeout(function() {
fire.apply(triggerObject, args);
}, 0);
return triggerObject;
} | [
"function",
"fireAsync",
"(",
"event",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"fire",
".",
"apply",
"(",
"triggerObject",
",",
"args",
")",
";",
"}",
",",
"0",
")",
";",
"return",
"triggerObject",
";",
"}"
]
| Fires an event asynchronously. Event listeners are invoked
on the next tick rather than immediately.
@param {string} event the event to fire
@param {...*} arguments to pass to the event listeners
@returns {Object} this trigger object | [
"Fires",
"an",
"event",
"asynchronously",
".",
"Event",
"listeners",
"are",
"invoked",
"on",
"the",
"next",
"tick",
"rather",
"than",
"immediately",
"."
]
| 10d6a3e0f204f6d5bc8c4565ee29236158a4c4b7 | https://github.com/psiolent/trigger-maker/blob/10d6a3e0f204f6d5bc8c4565ee29236158a4c4b7/index.js#L121-L127 | train |
psiolent/trigger-maker | index.js | hasListener | function hasListener(event, fn) {
return listeners[event] ?
listeners[event].some(function(l) {
return l === fn;
}) :
false;
} | javascript | function hasListener(event, fn) {
return listeners[event] ?
listeners[event].some(function(l) {
return l === fn;
}) :
false;
} | [
"function",
"hasListener",
"(",
"event",
",",
"fn",
")",
"{",
"return",
"listeners",
"[",
"event",
"]",
"?",
"listeners",
"[",
"event",
"]",
".",
"some",
"(",
"function",
"(",
"l",
")",
"{",
"return",
"l",
"===",
"fn",
";",
"}",
")",
":",
"false",
";",
"}"
]
| Returns whether the specified event has the specified listener.
@param event the event to check for the listener
@param fn the listener to check for
@returns {boolean} whether the specified event has the specified listener | [
"Returns",
"whether",
"the",
"specified",
"event",
"has",
"the",
"specified",
"listener",
"."
]
| 10d6a3e0f204f6d5bc8c4565ee29236158a4c4b7 | https://github.com/psiolent/trigger-maker/blob/10d6a3e0f204f6d5bc8c4565ee29236158a4c4b7/index.js#L153-L159 | train |
nickschot/lux-jwt | lib/index.js | validCorsPreflight | function validCorsPreflight(request) {
if (request.method === 'OPTIONS' && request.headers.has('access-control-request-headers')) {
return request.headers.get('access-control-request-headers').split(',').map(function (header) {
return header.trim();
}).includes('authorization');
} else {
return false;
}
} | javascript | function validCorsPreflight(request) {
if (request.method === 'OPTIONS' && request.headers.has('access-control-request-headers')) {
return request.headers.get('access-control-request-headers').split(',').map(function (header) {
return header.trim();
}).includes('authorization');
} else {
return false;
}
} | [
"function",
"validCorsPreflight",
"(",
"request",
")",
"{",
"if",
"(",
"request",
".",
"method",
"===",
"'OPTIONS'",
"&&",
"request",
".",
"headers",
".",
"has",
"(",
"'access-control-request-headers'",
")",
")",
"{",
"return",
"request",
".",
"headers",
".",
"get",
"(",
"'access-control-request-headers'",
")",
".",
"split",
"(",
"','",
")",
".",
"map",
"(",
"function",
"(",
"header",
")",
"{",
"return",
"header",
".",
"trim",
"(",
")",
";",
"}",
")",
".",
"includes",
"(",
"'authorization'",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
]
| Checks if an OPTIONS request with the access-control-request-headers containing authorization is being made
@param request
@returns {boolean} | [
"Checks",
"if",
"an",
"OPTIONS",
"request",
"with",
"the",
"access",
"-",
"control",
"-",
"request",
"-",
"headers",
"containing",
"authorization",
"is",
"being",
"made"
]
| eeb03fefcc954ea675ad44870b4f123a41f0d585 | https://github.com/nickschot/lux-jwt/blob/eeb03fefcc954ea675ad44870b4f123a41f0d585/lib/index.js#L88-L96 | train |
nickschot/lux-jwt | lib/index.js | getTokenFromHeader | function getTokenFromHeader(request) {
if (!request.headers || !request.headers.has('authorization')) {
throw new UnauthorizedError('No authorization header present');
}
const parts = request.headers.get('authorization').split(" ");
if (parts.length === 2) {
const scheme = parts[0];
const credentials = parts[1];
if (/^Bearer$/i.test(scheme)) {
return credentials;
} else {
throw new UnauthorizedError('Bad Authorization header format. Format is "Authorization: Bearer token"');
}
} else {
throw new UnauthorizedError('Bad Authorization header format. Format is "Authorization: Bearer token"');
}
} | javascript | function getTokenFromHeader(request) {
if (!request.headers || !request.headers.has('authorization')) {
throw new UnauthorizedError('No authorization header present');
}
const parts = request.headers.get('authorization').split(" ");
if (parts.length === 2) {
const scheme = parts[0];
const credentials = parts[1];
if (/^Bearer$/i.test(scheme)) {
return credentials;
} else {
throw new UnauthorizedError('Bad Authorization header format. Format is "Authorization: Bearer token"');
}
} else {
throw new UnauthorizedError('Bad Authorization header format. Format is "Authorization: Bearer token"');
}
} | [
"function",
"getTokenFromHeader",
"(",
"request",
")",
"{",
"if",
"(",
"!",
"request",
".",
"headers",
"||",
"!",
"request",
".",
"headers",
".",
"has",
"(",
"'authorization'",
")",
")",
"{",
"throw",
"new",
"UnauthorizedError",
"(",
"'No authorization header present'",
")",
";",
"}",
"const",
"parts",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'authorization'",
")",
".",
"split",
"(",
"\" \"",
")",
";",
"if",
"(",
"parts",
".",
"length",
"===",
"2",
")",
"{",
"const",
"scheme",
"=",
"parts",
"[",
"0",
"]",
";",
"const",
"credentials",
"=",
"parts",
"[",
"1",
"]",
";",
"if",
"(",
"/",
"^Bearer$",
"/",
"i",
".",
"test",
"(",
"scheme",
")",
")",
"{",
"return",
"credentials",
";",
"}",
"else",
"{",
"throw",
"new",
"UnauthorizedError",
"(",
"'Bad Authorization header format. Format is \"Authorization: Bearer token\"'",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"UnauthorizedError",
"(",
"'Bad Authorization header format. Format is \"Authorization: Bearer token\"'",
")",
";",
"}",
"}"
]
| Retrieves the JWT from the authorization header
@param request
@returns {string} The JWT | [
"Retrieves",
"the",
"JWT",
"from",
"the",
"authorization",
"header"
]
| eeb03fefcc954ea675ad44870b4f123a41f0d585 | https://github.com/nickschot/lux-jwt/blob/eeb03fefcc954ea675ad44870b4f123a41f0d585/lib/index.js#L103-L122 | train |
pierrec/node-atok-parser | examples/block_stream.js | myParser | function myParser (size) {
if (typeof size !== 'number')
throw new Error('Invalid block size: ' + size)
function isEnd () {
return atok.ending ? atok.length - atok.offset : -1
}
atok
.trim()
.addRule(size, function (data) {
self.emit('data', data)
})
.addRule('', isEnd, function (data) {
var len = data.length
if (typeof data === 'string') {
var lastBlock = data + new Array(size - len + 1).join('0')
} else {
var lastBlock = new Buffer(size)
lastBlock.fill(0, len)
data.copy(lastBlock, 0)
}
self.emit('data', lastBlock)
})
.on('end', function () {
self.emit('end')
})
} | javascript | function myParser (size) {
if (typeof size !== 'number')
throw new Error('Invalid block size: ' + size)
function isEnd () {
return atok.ending ? atok.length - atok.offset : -1
}
atok
.trim()
.addRule(size, function (data) {
self.emit('data', data)
})
.addRule('', isEnd, function (data) {
var len = data.length
if (typeof data === 'string') {
var lastBlock = data + new Array(size - len + 1).join('0')
} else {
var lastBlock = new Buffer(size)
lastBlock.fill(0, len)
data.copy(lastBlock, 0)
}
self.emit('data', lastBlock)
})
.on('end', function () {
self.emit('end')
})
} | [
"function",
"myParser",
"(",
"size",
")",
"{",
"if",
"(",
"typeof",
"size",
"!==",
"'number'",
")",
"throw",
"new",
"Error",
"(",
"'Invalid block size: '",
"+",
"size",
")",
"function",
"isEnd",
"(",
")",
"{",
"return",
"atok",
".",
"ending",
"?",
"atok",
".",
"length",
"-",
"atok",
".",
"offset",
":",
"-",
"1",
"}",
"atok",
".",
"trim",
"(",
")",
".",
"addRule",
"(",
"size",
",",
"function",
"(",
"data",
")",
"{",
"self",
".",
"emit",
"(",
"'data'",
",",
"data",
")",
"}",
")",
".",
"addRule",
"(",
"''",
",",
"isEnd",
",",
"function",
"(",
"data",
")",
"{",
"var",
"len",
"=",
"data",
".",
"length",
"if",
"(",
"typeof",
"data",
"===",
"'string'",
")",
"{",
"var",
"lastBlock",
"=",
"data",
"+",
"new",
"Array",
"(",
"size",
"-",
"len",
"+",
"1",
")",
".",
"join",
"(",
"'0'",
")",
"}",
"else",
"{",
"var",
"lastBlock",
"=",
"new",
"Buffer",
"(",
"size",
")",
"lastBlock",
".",
"fill",
"(",
"0",
",",
"len",
")",
"data",
".",
"copy",
"(",
"lastBlock",
",",
"0",
")",
"}",
"self",
".",
"emit",
"(",
"'data'",
",",
"lastBlock",
")",
"}",
")",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"self",
".",
"emit",
"(",
"'end'",
")",
"}",
")",
"}"
]
| Stream data in blocks | [
"Stream",
"data",
"in",
"blocks"
]
| 414d39904dff73ffdde049212076c14ca40aa20b | https://github.com/pierrec/node-atok-parser/blob/414d39904dff73ffdde049212076c14ca40aa20b/examples/block_stream.js#L4-L32 | train |
AdityaHegde/ember-object-utils | addon/objectWithArrayMixin.js | getArrayFromRange | function getArrayFromRange(l, h, s) {
var a = [];
s = s || 1;
for(var i = l; i < h; i += s) {
a.push(i);
}
return a;
} | javascript | function getArrayFromRange(l, h, s) {
var a = [];
s = s || 1;
for(var i = l; i < h; i += s) {
a.push(i);
}
return a;
} | [
"function",
"getArrayFromRange",
"(",
"l",
",",
"h",
",",
"s",
")",
"{",
"var",
"a",
"=",
"[",
"]",
";",
"s",
"=",
"s",
"||",
"1",
";",
"for",
"(",
"var",
"i",
"=",
"l",
";",
"i",
"<",
"h",
";",
"i",
"+=",
"s",
")",
"{",
"a",
".",
"push",
"(",
"i",
")",
";",
"}",
"return",
"a",
";",
"}"
]
| Returns an array of integers from a starting number to another number with steps.
@method getArrayFromRange
@static
@param {Number} l Starting number.
@param {Number} h Ending number.
@param {Number} s Steps.
@returns {Array} | [
"Returns",
"an",
"array",
"of",
"integers",
"from",
"a",
"starting",
"number",
"to",
"another",
"number",
"with",
"steps",
"."
]
| bc57203c4b523fd3a632735b25a5bb1bbf55dbcb | https://github.com/AdityaHegde/ember-object-utils/blob/bc57203c4b523fd3a632735b25a5bb1bbf55dbcb/addon/objectWithArrayMixin.js#L13-L20 | train |
tabone/ipc-emitter | src/master.js | handleMasterPayload | function handleMasterPayload (payload) {
// Parse and validate received payload.
if ((payload = utils.parsePayload(payload)) === null) return
// Notify all workers except the worker who emitted the event.
sendPayload.call(this, payload)
} | javascript | function handleMasterPayload (payload) {
// Parse and validate received payload.
if ((payload = utils.parsePayload(payload)) === null) return
// Notify all workers except the worker who emitted the event.
sendPayload.call(this, payload)
} | [
"function",
"handleMasterPayload",
"(",
"payload",
")",
"{",
"if",
"(",
"(",
"payload",
"=",
"utils",
".",
"parsePayload",
"(",
"payload",
")",
")",
"===",
"null",
")",
"return",
"sendPayload",
".",
"call",
"(",
"this",
",",
"payload",
")",
"}"
]
| handleMasterPayload handles the payload recieved by the master process. If
payload is valid it is echoed back to all workers. Note that unlike the
handleWorkerPayload the listeners of the instance won't be notified.
@param {String} payload Payload received from a worker. | [
"handleMasterPayload",
"handles",
"the",
"payload",
"recieved",
"by",
"the",
"master",
"process",
".",
"If",
"payload",
"is",
"valid",
"it",
"is",
"echoed",
"back",
"to",
"all",
"workers",
".",
"Note",
"that",
"unlike",
"the",
"handleWorkerPayload",
"the",
"listeners",
"of",
"the",
"instance",
"won",
"t",
"be",
"notified",
"."
]
| 4717a9e228ab8b28f2fd6d0966779c452ad38405 | https://github.com/tabone/ipc-emitter/blob/4717a9e228ab8b28f2fd6d0966779c452ad38405/src/master.js#L208-L214 | train |
tabone/ipc-emitter | src/master.js | handleWorkerPayload | function handleWorkerPayload (payload) {
// Parse and validate received payload.
if ((payload = utils.parsePayload(payload)) === null) return
// If the master is configured to echo events to its own master, the event
// emitted by the worker should be echoed to the master.
if (this.__echoEvents === true) {
const echoPayload = JSON.parse(JSON.stringify(payload))
// Update PID as if the payload is originating from this process, the master
// is in. If this is not done, the master of this process, will resend the
// payload since the PID is different.
echoPayload[fields.pid] = process.pid
process.send(echoPayload)
}
// Unmarshal args.
payload[fields.args] = marshaller.unmarshal(payload[fields.args])
// Notify instance listeners.
events.prototype.emit.call(this, payload[fields.event],
...payload[fields.args])
// Notify all workers except the worker who emitted the event.
sendPayload.call(this, payload)
} | javascript | function handleWorkerPayload (payload) {
// Parse and validate received payload.
if ((payload = utils.parsePayload(payload)) === null) return
// If the master is configured to echo events to its own master, the event
// emitted by the worker should be echoed to the master.
if (this.__echoEvents === true) {
const echoPayload = JSON.parse(JSON.stringify(payload))
// Update PID as if the payload is originating from this process, the master
// is in. If this is not done, the master of this process, will resend the
// payload since the PID is different.
echoPayload[fields.pid] = process.pid
process.send(echoPayload)
}
// Unmarshal args.
payload[fields.args] = marshaller.unmarshal(payload[fields.args])
// Notify instance listeners.
events.prototype.emit.call(this, payload[fields.event],
...payload[fields.args])
// Notify all workers except the worker who emitted the event.
sendPayload.call(this, payload)
} | [
"function",
"handleWorkerPayload",
"(",
"payload",
")",
"{",
"if",
"(",
"(",
"payload",
"=",
"utils",
".",
"parsePayload",
"(",
"payload",
")",
")",
"===",
"null",
")",
"return",
"if",
"(",
"this",
".",
"__echoEvents",
"===",
"true",
")",
"{",
"const",
"echoPayload",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"payload",
")",
")",
"echoPayload",
"[",
"fields",
".",
"pid",
"]",
"=",
"process",
".",
"pid",
"process",
".",
"send",
"(",
"echoPayload",
")",
"}",
"payload",
"[",
"fields",
".",
"args",
"]",
"=",
"marshaller",
".",
"unmarshal",
"(",
"payload",
"[",
"fields",
".",
"args",
"]",
")",
"events",
".",
"prototype",
".",
"emit",
".",
"call",
"(",
"this",
",",
"payload",
"[",
"fields",
".",
"event",
"]",
",",
"...",
"payload",
"[",
"fields",
".",
"args",
"]",
")",
"sendPayload",
".",
"call",
"(",
"this",
",",
"payload",
")",
"}"
]
| handleWorkerPayload handles the payload received by a worker. If payload is
valid it is echoed back to all workers except the worker that it was received
from.
@param {String} payload Payload received from a worker. | [
"handleWorkerPayload",
"handles",
"the",
"payload",
"received",
"by",
"a",
"worker",
".",
"If",
"payload",
"is",
"valid",
"it",
"is",
"echoed",
"back",
"to",
"all",
"workers",
"except",
"the",
"worker",
"that",
"it",
"was",
"received",
"from",
"."
]
| 4717a9e228ab8b28f2fd6d0966779c452ad38405 | https://github.com/tabone/ipc-emitter/blob/4717a9e228ab8b28f2fd6d0966779c452ad38405/src/master.js#L222-L246 | train |
forfuturellc/svc-fbr | src/lib/db.js | getModels | function getModels(done) {
if (models) {
return done(models);
}
return orm.initialize(ormConfig, function(err, m) {
if (err) {
throw err;
}
// make the models available as soon as possible for other functions
models = m;
// ignore error if groups already created
let catcher = (createErr) => { if (createErr && createErr.code !== "E_VALIDATION") { throw createErr; } };
// create the administrators group
createGroup("admin", catcher);
// create the public group
createGroup("public", catcher);
return done(models);
});
} | javascript | function getModels(done) {
if (models) {
return done(models);
}
return orm.initialize(ormConfig, function(err, m) {
if (err) {
throw err;
}
// make the models available as soon as possible for other functions
models = m;
// ignore error if groups already created
let catcher = (createErr) => { if (createErr && createErr.code !== "E_VALIDATION") { throw createErr; } };
// create the administrators group
createGroup("admin", catcher);
// create the public group
createGroup("public", catcher);
return done(models);
});
} | [
"function",
"getModels",
"(",
"done",
")",
"{",
"if",
"(",
"models",
")",
"{",
"return",
"done",
"(",
"models",
")",
";",
"}",
"return",
"orm",
".",
"initialize",
"(",
"ormConfig",
",",
"function",
"(",
"err",
",",
"m",
")",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"err",
";",
"}",
"models",
"=",
"m",
";",
"let",
"catcher",
"=",
"(",
"createErr",
")",
"=>",
"{",
"if",
"(",
"createErr",
"&&",
"createErr",
".",
"code",
"!==",
"\"E_VALIDATION\"",
")",
"{",
"throw",
"createErr",
";",
"}",
"}",
";",
"createGroup",
"(",
"\"admin\"",
",",
"catcher",
")",
";",
"createGroup",
"(",
"\"public\"",
",",
"catcher",
")",
";",
"return",
"done",
"(",
"models",
")",
";",
"}",
")",
";",
"}"
]
| return models. It initializes Waterfall if not yet initialized in
this process.
@param {Function} done - done(models) | [
"return",
"models",
".",
"It",
"initializes",
"Waterfall",
"if",
"not",
"yet",
"initialized",
"in",
"this",
"process",
"."
]
| 8c07c71d6423d1dbd4f903a032dea0bfec63894e | https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/db.js#L145-L169 | train |
forfuturellc/svc-fbr | src/lib/db.js | createGroup | function createGroup(name, done) {
return getModels(function(m) {
return m.collections.group.create({ name }, done);
});
} | javascript | function createGroup(name, done) {
return getModels(function(m) {
return m.collections.group.create({ name }, done);
});
} | [
"function",
"createGroup",
"(",
"name",
",",
"done",
")",
"{",
"return",
"getModels",
"(",
"function",
"(",
"m",
")",
"{",
"return",
"m",
".",
"collections",
".",
"group",
".",
"create",
"(",
"{",
"name",
"}",
",",
"done",
")",
";",
"}",
")",
";",
"}"
]
| Create a new group | [
"Create",
"a",
"new",
"group"
]
| 8c07c71d6423d1dbd4f903a032dea0bfec63894e | https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/db.js#L175-L179 | train |
forfuturellc/svc-fbr | src/lib/db.js | getGroup | function getGroup(name, done) {
return getModels(function(m) {
return m.collections.group.findOne({ name })
.populate("members").populate("leaders").exec(done);
});
} | javascript | function getGroup(name, done) {
return getModels(function(m) {
return m.collections.group.findOne({ name })
.populate("members").populate("leaders").exec(done);
});
} | [
"function",
"getGroup",
"(",
"name",
",",
"done",
")",
"{",
"return",
"getModels",
"(",
"function",
"(",
"m",
")",
"{",
"return",
"m",
".",
"collections",
".",
"group",
".",
"findOne",
"(",
"{",
"name",
"}",
")",
".",
"populate",
"(",
"\"members\"",
")",
".",
"populate",
"(",
"\"leaders\"",
")",
".",
"exec",
"(",
"done",
")",
";",
"}",
")",
";",
"}"
]
| Get a group. It populates the members and leaders automatically.
@param {String} name
@param {Function} done - done(err, group) | [
"Get",
"a",
"group",
".",
"It",
"populates",
"the",
"members",
"and",
"leaders",
"automatically",
"."
]
| 8c07c71d6423d1dbd4f903a032dea0bfec63894e | https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/db.js#L188-L193 | train |
forfuturellc/svc-fbr | src/lib/db.js | getGroups | function getGroups(done) {
return getModels(function(m) {
return m.collections.group.find().exec(done);
});
} | javascript | function getGroups(done) {
return getModels(function(m) {
return m.collections.group.find().exec(done);
});
} | [
"function",
"getGroups",
"(",
"done",
")",
"{",
"return",
"getModels",
"(",
"function",
"(",
"m",
")",
"{",
"return",
"m",
".",
"collections",
".",
"group",
".",
"find",
"(",
")",
".",
"exec",
"(",
"done",
")",
";",
"}",
")",
";",
"}"
]
| Get all groups. Members and leaders are not loaded automatically.
This is by design; avoid too much data fetching.
@param {Function} done - done(err, groups) | [
"Get",
"all",
"groups",
".",
"Members",
"and",
"leaders",
"are",
"not",
"loaded",
"automatically",
".",
"This",
"is",
"by",
"design",
";",
"avoid",
"too",
"much",
"data",
"fetching",
"."
]
| 8c07c71d6423d1dbd4f903a032dea0bfec63894e | https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/db.js#L202-L206 | train |
forfuturellc/svc-fbr | src/lib/db.js | deleteGroup | function deleteGroup(name, done) {
return getGroup(name, function(getGroupErr, group) {
if (getGroupErr) {
return done(getGroupErr);
}
if (!group) {
return done(new Error(`group '${name}' not found`));
}
return group.destroy(done);
});
} | javascript | function deleteGroup(name, done) {
return getGroup(name, function(getGroupErr, group) {
if (getGroupErr) {
return done(getGroupErr);
}
if (!group) {
return done(new Error(`group '${name}' not found`));
}
return group.destroy(done);
});
} | [
"function",
"deleteGroup",
"(",
"name",
",",
"done",
")",
"{",
"return",
"getGroup",
"(",
"name",
",",
"function",
"(",
"getGroupErr",
",",
"group",
")",
"{",
"if",
"(",
"getGroupErr",
")",
"{",
"return",
"done",
"(",
"getGroupErr",
")",
";",
"}",
"if",
"(",
"!",
"group",
")",
"{",
"return",
"done",
"(",
"new",
"Error",
"(",
"`",
"${",
"name",
"}",
"`",
")",
")",
";",
"}",
"return",
"group",
".",
"destroy",
"(",
"done",
")",
";",
"}",
")",
";",
"}"
]
| Delete a group
@param {String} name
@param {Function} done - done(err) | [
"Delete",
"a",
"group"
]
| 8c07c71d6423d1dbd4f903a032dea0bfec63894e | https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/db.js#L215-L227 | train |
forfuturellc/svc-fbr | src/lib/db.js | composeAddRemoveGroupMember | function composeAddRemoveGroupMember({ action="add", roles="members" }) {
/**
* Add/Remove user from group
*
* @param {String} username
* @param {String} groupname
* @param {Function} done - done(err)
*/
return function(username, groupname, done) {
return getGroup(groupname, function(getGroupErr, group) {
if (getGroupErr) {
return done(getGroupErr);
}
if (!group) {
return done(new Error(`group '${groupname}' not found`));
}
return getUser(username, function(getUserErr, user) {
if (getUserErr) {
return done(getUserErr);
}
if (!user) {
return done(new Error(`user '${username}' not found`));
}
group[roles][action](user.id);
return group.save(done);
});
});
};
} | javascript | function composeAddRemoveGroupMember({ action="add", roles="members" }) {
/**
* Add/Remove user from group
*
* @param {String} username
* @param {String} groupname
* @param {Function} done - done(err)
*/
return function(username, groupname, done) {
return getGroup(groupname, function(getGroupErr, group) {
if (getGroupErr) {
return done(getGroupErr);
}
if (!group) {
return done(new Error(`group '${groupname}' not found`));
}
return getUser(username, function(getUserErr, user) {
if (getUserErr) {
return done(getUserErr);
}
if (!user) {
return done(new Error(`user '${username}' not found`));
}
group[roles][action](user.id);
return group.save(done);
});
});
};
} | [
"function",
"composeAddRemoveGroupMember",
"(",
"{",
"action",
"=",
"\"add\"",
",",
"roles",
"=",
"\"members\"",
"}",
")",
"{",
"return",
"function",
"(",
"username",
",",
"groupname",
",",
"done",
")",
"{",
"return",
"getGroup",
"(",
"groupname",
",",
"function",
"(",
"getGroupErr",
",",
"group",
")",
"{",
"if",
"(",
"getGroupErr",
")",
"{",
"return",
"done",
"(",
"getGroupErr",
")",
";",
"}",
"if",
"(",
"!",
"group",
")",
"{",
"return",
"done",
"(",
"new",
"Error",
"(",
"`",
"${",
"groupname",
"}",
"`",
")",
")",
";",
"}",
"return",
"getUser",
"(",
"username",
",",
"function",
"(",
"getUserErr",
",",
"user",
")",
"{",
"if",
"(",
"getUserErr",
")",
"{",
"return",
"done",
"(",
"getUserErr",
")",
";",
"}",
"if",
"(",
"!",
"user",
")",
"{",
"return",
"done",
"(",
"new",
"Error",
"(",
"`",
"${",
"username",
"}",
"`",
")",
")",
";",
"}",
"group",
"[",
"roles",
"]",
"[",
"action",
"]",
"(",
"user",
".",
"id",
")",
";",
"return",
"group",
".",
"save",
"(",
"done",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
";",
"}"
]
| Compose function for removing or adding user to group
@param {Boolean} [action="add"] | [
"Compose",
"function",
"for",
"removing",
"or",
"adding",
"user",
"to",
"group"
]
| 8c07c71d6423d1dbd4f903a032dea0bfec63894e | https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/db.js#L259-L291 | train |
forfuturellc/svc-fbr | src/lib/db.js | getUser | function getUser(username, done) {
return getModels(function(m) {
return m.collections.user.findOne({ username })
.populate("tokens")
.populate("groups")
.populate("leading")
.exec(done);
});
} | javascript | function getUser(username, done) {
return getModels(function(m) {
return m.collections.user.findOne({ username })
.populate("tokens")
.populate("groups")
.populate("leading")
.exec(done);
});
} | [
"function",
"getUser",
"(",
"username",
",",
"done",
")",
"{",
"return",
"getModels",
"(",
"function",
"(",
"m",
")",
"{",
"return",
"m",
".",
"collections",
".",
"user",
".",
"findOne",
"(",
"{",
"username",
"}",
")",
".",
"populate",
"(",
"\"tokens\"",
")",
".",
"populate",
"(",
"\"groups\"",
")",
".",
"populate",
"(",
"\"leading\"",
")",
".",
"exec",
"(",
"done",
")",
";",
"}",
")",
";",
"}"
]
| Get a single user. Automatically loads the tokens.
@param {String} username
@param {Function} done - done(err, user) | [
"Get",
"a",
"single",
"user",
".",
"Automatically",
"loads",
"the",
"tokens",
"."
]
| 8c07c71d6423d1dbd4f903a032dea0bfec63894e | https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/db.js#L300-L308 | train |
forfuturellc/svc-fbr | src/lib/db.js | deleteUser | function deleteUser(username, done) {
return getUser(username, function(getUserErr, user) {
if (getUserErr) {
return done(getUserErr);
}
if (!user) {
return done(new Error(`user '${username}' not found`));
}
user.tokens.forEach((token) => token.destroy());
user.groups.forEach((group) => { group.members.remove(user.id); group.save(); });
user.leading.forEach((group) => { group.leaders.remove(user.id); group.save(); });
user.destroy(done);
});
} | javascript | function deleteUser(username, done) {
return getUser(username, function(getUserErr, user) {
if (getUserErr) {
return done(getUserErr);
}
if (!user) {
return done(new Error(`user '${username}' not found`));
}
user.tokens.forEach((token) => token.destroy());
user.groups.forEach((group) => { group.members.remove(user.id); group.save(); });
user.leading.forEach((group) => { group.leaders.remove(user.id); group.save(); });
user.destroy(done);
});
} | [
"function",
"deleteUser",
"(",
"username",
",",
"done",
")",
"{",
"return",
"getUser",
"(",
"username",
",",
"function",
"(",
"getUserErr",
",",
"user",
")",
"{",
"if",
"(",
"getUserErr",
")",
"{",
"return",
"done",
"(",
"getUserErr",
")",
";",
"}",
"if",
"(",
"!",
"user",
")",
"{",
"return",
"done",
"(",
"new",
"Error",
"(",
"`",
"${",
"username",
"}",
"`",
")",
")",
";",
"}",
"user",
".",
"tokens",
".",
"forEach",
"(",
"(",
"token",
")",
"=>",
"token",
".",
"destroy",
"(",
")",
")",
";",
"user",
".",
"groups",
".",
"forEach",
"(",
"(",
"group",
")",
"=>",
"{",
"group",
".",
"members",
".",
"remove",
"(",
"user",
".",
"id",
")",
";",
"group",
".",
"save",
"(",
")",
";",
"}",
")",
";",
"user",
".",
"leading",
".",
"forEach",
"(",
"(",
"group",
")",
"=>",
"{",
"group",
".",
"leaders",
".",
"remove",
"(",
"user",
".",
"id",
")",
";",
"group",
".",
"save",
"(",
")",
";",
"}",
")",
";",
"user",
".",
"destroy",
"(",
"done",
")",
";",
"}",
")",
";",
"}"
]
| Destroy a user. This also deletes all the user's tokens.
@param {String} username
@param {Function} done - done(err) | [
"Destroy",
"a",
"user",
".",
"This",
"also",
"deletes",
"all",
"the",
"user",
"s",
"tokens",
"."
]
| 8c07c71d6423d1dbd4f903a032dea0bfec63894e | https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/db.js#L347-L362 | train |
forfuturellc/svc-fbr | src/lib/db.js | getUsers | function getUsers(done) {
return getModels(function(m) {
return m.collections.user.find().exec(done);
});
} | javascript | function getUsers(done) {
return getModels(function(m) {
return m.collections.user.find().exec(done);
});
} | [
"function",
"getUsers",
"(",
"done",
")",
"{",
"return",
"getModels",
"(",
"function",
"(",
"m",
")",
"{",
"return",
"m",
".",
"collections",
".",
"user",
".",
"find",
"(",
")",
".",
"exec",
"(",
"done",
")",
";",
"}",
")",
";",
"}"
]
| Get all users. Note that the tokens are not loaded. This is by design;
it might be very expensive to do so.
@param {Function} done - done(err, users) | [
"Get",
"all",
"users",
".",
"Note",
"that",
"the",
"tokens",
"are",
"not",
"loaded",
".",
"This",
"is",
"by",
"design",
";",
"it",
"might",
"be",
"very",
"expensive",
"to",
"do",
"so",
"."
]
| 8c07c71d6423d1dbd4f903a032dea0bfec63894e | https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/db.js#L371-L375 | train |
forfuturellc/svc-fbr | src/lib/db.js | hashToken | function hashToken(token, done) {
return bcrypt.genSalt(10, function(genSaltErr, salt) {
if (genSaltErr) {
return done(genSaltErr);
}
bcrypt.hash(token, salt, done);
});
} | javascript | function hashToken(token, done) {
return bcrypt.genSalt(10, function(genSaltErr, salt) {
if (genSaltErr) {
return done(genSaltErr);
}
bcrypt.hash(token, salt, done);
});
} | [
"function",
"hashToken",
"(",
"token",
",",
"done",
")",
"{",
"return",
"bcrypt",
".",
"genSalt",
"(",
"10",
",",
"function",
"(",
"genSaltErr",
",",
"salt",
")",
"{",
"if",
"(",
"genSaltErr",
")",
"{",
"return",
"done",
"(",
"genSaltErr",
")",
";",
"}",
"bcrypt",
".",
"hash",
"(",
"token",
",",
"salt",
",",
"done",
")",
";",
"}",
")",
";",
"}"
]
| Hash a token. We shall not store the token in plain text for security
purposes.
@param {String} token
@param {Function} done - done(err, hash) | [
"Hash",
"a",
"token",
".",
"We",
"shall",
"not",
"store",
"the",
"token",
"in",
"plain",
"text",
"for",
"security",
"purposes",
"."
]
| 8c07c71d6423d1dbd4f903a032dea0bfec63894e | https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/db.js#L385-L393 | train |
forfuturellc/svc-fbr | src/lib/db.js | createToken | function createToken(username, done) {
return getUser(username, function(getUserErr, user) {
if (getUserErr) {
return done(getUserErr);
}
if (!user) {
return done(new Error(`user '${username}' not found`));
}
const token = uuid.v4();
return hashToken(token, function(cryptErr, hash) {
if (cryptErr) {
return done(cryptErr);
}
return getModels(function(m) {
m.collections.token.create({
uuid: hash,
owner: user.id,
}, function(createTokenErr) {
if (createTokenErr) {
return done(createTokenErr);
}
return done(null, token);
}); // m.collections.token.create
}); // getModels
}); // hashToken
}); // getUser
} | javascript | function createToken(username, done) {
return getUser(username, function(getUserErr, user) {
if (getUserErr) {
return done(getUserErr);
}
if (!user) {
return done(new Error(`user '${username}' not found`));
}
const token = uuid.v4();
return hashToken(token, function(cryptErr, hash) {
if (cryptErr) {
return done(cryptErr);
}
return getModels(function(m) {
m.collections.token.create({
uuid: hash,
owner: user.id,
}, function(createTokenErr) {
if (createTokenErr) {
return done(createTokenErr);
}
return done(null, token);
}); // m.collections.token.create
}); // getModels
}); // hashToken
}); // getUser
} | [
"function",
"createToken",
"(",
"username",
",",
"done",
")",
"{",
"return",
"getUser",
"(",
"username",
",",
"function",
"(",
"getUserErr",
",",
"user",
")",
"{",
"if",
"(",
"getUserErr",
")",
"{",
"return",
"done",
"(",
"getUserErr",
")",
";",
"}",
"if",
"(",
"!",
"user",
")",
"{",
"return",
"done",
"(",
"new",
"Error",
"(",
"`",
"${",
"username",
"}",
"`",
")",
")",
";",
"}",
"const",
"token",
"=",
"uuid",
".",
"v4",
"(",
")",
";",
"return",
"hashToken",
"(",
"token",
",",
"function",
"(",
"cryptErr",
",",
"hash",
")",
"{",
"if",
"(",
"cryptErr",
")",
"{",
"return",
"done",
"(",
"cryptErr",
")",
";",
"}",
"return",
"getModels",
"(",
"function",
"(",
"m",
")",
"{",
"m",
".",
"collections",
".",
"token",
".",
"create",
"(",
"{",
"uuid",
":",
"hash",
",",
"owner",
":",
"user",
".",
"id",
",",
"}",
",",
"function",
"(",
"createTokenErr",
")",
"{",
"if",
"(",
"createTokenErr",
")",
"{",
"return",
"done",
"(",
"createTokenErr",
")",
";",
"}",
"return",
"done",
"(",
"null",
",",
"token",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Create a token for a user. A token is simply a v4 uuid.
@param {String} username
@param {Function} done - done(err, token) | [
"Create",
"a",
"token",
"for",
"a",
"user",
".",
"A",
"token",
"is",
"simply",
"a",
"v4",
"uuid",
"."
]
| 8c07c71d6423d1dbd4f903a032dea0bfec63894e | https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/db.js#L402-L433 | train |
forfuturellc/svc-fbr | src/lib/db.js | getTokenHashes | function getTokenHashes(username, done) {
return getUser(username, function(getUserErr, user) {
if (getUserErr) {
return done(getUserErr);
}
if (!user) {
return done(new Error(`user '${username}' not found`));
}
return done(null, user.tokens);
});
} | javascript | function getTokenHashes(username, done) {
return getUser(username, function(getUserErr, user) {
if (getUserErr) {
return done(getUserErr);
}
if (!user) {
return done(new Error(`user '${username}' not found`));
}
return done(null, user.tokens);
});
} | [
"function",
"getTokenHashes",
"(",
"username",
",",
"done",
")",
"{",
"return",
"getUser",
"(",
"username",
",",
"function",
"(",
"getUserErr",
",",
"user",
")",
"{",
"if",
"(",
"getUserErr",
")",
"{",
"return",
"done",
"(",
"getUserErr",
")",
";",
"}",
"if",
"(",
"!",
"user",
")",
"{",
"return",
"done",
"(",
"new",
"Error",
"(",
"`",
"${",
"username",
"}",
"`",
")",
")",
";",
"}",
"return",
"done",
"(",
"null",
",",
"user",
".",
"tokens",
")",
";",
"}",
")",
";",
"}"
]
| Retrieve users tokens
@param {String} username
@param {Function} done - done(err, hashes) | [
"Retrieve",
"users",
"tokens"
]
| 8c07c71d6423d1dbd4f903a032dea0bfec63894e | https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/db.js#L442-L454 | train |
forfuturellc/svc-fbr | src/lib/db.js | tokenExists | function tokenExists(username, token, done) {
return getTokenHashes(username, function(getTokensErr, hashes) {
if (getTokensErr) {
return done(getTokensErr);
}
if (!hashes || !hashes.length) {
return done(null, false);
}
let index = 0;
let found = false;
async.until(() => found || (index >= hashes.length), function(next) {
bcrypt.compare(token, hashes[index++].uuid, function(err, match) {
found = match;
return next(err);
});
}, (err) => done(err, found ? hashes[index - 1] : undefined));
});
} | javascript | function tokenExists(username, token, done) {
return getTokenHashes(username, function(getTokensErr, hashes) {
if (getTokensErr) {
return done(getTokensErr);
}
if (!hashes || !hashes.length) {
return done(null, false);
}
let index = 0;
let found = false;
async.until(() => found || (index >= hashes.length), function(next) {
bcrypt.compare(token, hashes[index++].uuid, function(err, match) {
found = match;
return next(err);
});
}, (err) => done(err, found ? hashes[index - 1] : undefined));
});
} | [
"function",
"tokenExists",
"(",
"username",
",",
"token",
",",
"done",
")",
"{",
"return",
"getTokenHashes",
"(",
"username",
",",
"function",
"(",
"getTokensErr",
",",
"hashes",
")",
"{",
"if",
"(",
"getTokensErr",
")",
"{",
"return",
"done",
"(",
"getTokensErr",
")",
";",
"}",
"if",
"(",
"!",
"hashes",
"||",
"!",
"hashes",
".",
"length",
")",
"{",
"return",
"done",
"(",
"null",
",",
"false",
")",
";",
"}",
"let",
"index",
"=",
"0",
";",
"let",
"found",
"=",
"false",
";",
"async",
".",
"until",
"(",
"(",
")",
"=>",
"found",
"||",
"(",
"index",
">=",
"hashes",
".",
"length",
")",
",",
"function",
"(",
"next",
")",
"{",
"bcrypt",
".",
"compare",
"(",
"token",
",",
"hashes",
"[",
"index",
"++",
"]",
".",
"uuid",
",",
"function",
"(",
"err",
",",
"match",
")",
"{",
"found",
"=",
"match",
";",
"return",
"next",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
",",
"(",
"err",
")",
"=>",
"done",
"(",
"err",
",",
"found",
"?",
"hashes",
"[",
"index",
"-",
"1",
"]",
":",
"undefined",
")",
")",
";",
"}",
")",
";",
"}"
]
| Check if token exists. If found it is returned.
@param {String} token
@param {Function} done - done(err, tokenObj) | [
"Check",
"if",
"token",
"exists",
".",
"If",
"found",
"it",
"is",
"returned",
"."
]
| 8c07c71d6423d1dbd4f903a032dea0bfec63894e | https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/db.js#L463-L483 | train |
forfuturellc/svc-fbr | src/lib/db.js | deleteToken | function deleteToken(username, token, done) {
return tokenExists(username, token, function(existsErr, tokenObj) {
if (existsErr) {
return done(existsErr);
}
if (!tokenObj) {
return done(new Error(`token '${token}' not found`));
}
return tokenObj.destroy(done);
});
} | javascript | function deleteToken(username, token, done) {
return tokenExists(username, token, function(existsErr, tokenObj) {
if (existsErr) {
return done(existsErr);
}
if (!tokenObj) {
return done(new Error(`token '${token}' not found`));
}
return tokenObj.destroy(done);
});
} | [
"function",
"deleteToken",
"(",
"username",
",",
"token",
",",
"done",
")",
"{",
"return",
"tokenExists",
"(",
"username",
",",
"token",
",",
"function",
"(",
"existsErr",
",",
"tokenObj",
")",
"{",
"if",
"(",
"existsErr",
")",
"{",
"return",
"done",
"(",
"existsErr",
")",
";",
"}",
"if",
"(",
"!",
"tokenObj",
")",
"{",
"return",
"done",
"(",
"new",
"Error",
"(",
"`",
"${",
"token",
"}",
"`",
")",
")",
";",
"}",
"return",
"tokenObj",
".",
"destroy",
"(",
"done",
")",
";",
"}",
")",
";",
"}"
]
| Destroy a token. Username is required as we use it to search through
tokens.
@param {String} username
@param {String} token
@param {Function} done - done(err) | [
"Destroy",
"a",
"token",
".",
"Username",
"is",
"required",
"as",
"we",
"use",
"it",
"to",
"search",
"through",
"tokens",
"."
]
| 8c07c71d6423d1dbd4f903a032dea0bfec63894e | https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/db.js#L494-L506 | train |
gtriggiano/dnsmq-messagebus | src/MasterElector.js | _onInboxMessage | function _onInboxMessage (sender, _, msgBuffer) {
let message = JSON.parse(msgBuffer)
masterBroker.setIP(message.toAddress)
switch (message.type) {
case 'voteRequest':
debug(`sending vote to ${node.name === message.from ? 'myself' : message.from}`)
_inbox.send([sender, _, JSON.stringify({
id: _advertiseId || node.id,
name: node.name,
endpoints: masterBroker.endpoints,
isMaster: masterBroker.isMaster,
candidate: !_advertiseId
})])
break
case 'masterRequest':
let connectedMaster = node.master
if (connectedMaster) {
debug(`sending master coordinates to ${message.from}`)
_inbox.send([sender, _, JSON.stringify(connectedMaster)])
} else {
debug(`unable to send master coordinates to ${message.from}`)
_inbox.send([sender, _, JSON.stringify(false)])
}
break
case 'masterElected':
_inbox.send([sender, _, ''])
debug(`received notice of master election: ${message.data.name}`)
resolver.emit('newmaster', message.data)
}
} | javascript | function _onInboxMessage (sender, _, msgBuffer) {
let message = JSON.parse(msgBuffer)
masterBroker.setIP(message.toAddress)
switch (message.type) {
case 'voteRequest':
debug(`sending vote to ${node.name === message.from ? 'myself' : message.from}`)
_inbox.send([sender, _, JSON.stringify({
id: _advertiseId || node.id,
name: node.name,
endpoints: masterBroker.endpoints,
isMaster: masterBroker.isMaster,
candidate: !_advertiseId
})])
break
case 'masterRequest':
let connectedMaster = node.master
if (connectedMaster) {
debug(`sending master coordinates to ${message.from}`)
_inbox.send([sender, _, JSON.stringify(connectedMaster)])
} else {
debug(`unable to send master coordinates to ${message.from}`)
_inbox.send([sender, _, JSON.stringify(false)])
}
break
case 'masterElected':
_inbox.send([sender, _, ''])
debug(`received notice of master election: ${message.data.name}`)
resolver.emit('newmaster', message.data)
}
} | [
"function",
"_onInboxMessage",
"(",
"sender",
",",
"_",
",",
"msgBuffer",
")",
"{",
"let",
"message",
"=",
"JSON",
".",
"parse",
"(",
"msgBuffer",
")",
"masterBroker",
".",
"setIP",
"(",
"message",
".",
"toAddress",
")",
"switch",
"(",
"message",
".",
"type",
")",
"{",
"case",
"'voteRequest'",
":",
"debug",
"(",
"`",
"${",
"node",
".",
"name",
"===",
"message",
".",
"from",
"?",
"'myself'",
":",
"message",
".",
"from",
"}",
"`",
")",
"_inbox",
".",
"send",
"(",
"[",
"sender",
",",
"_",
",",
"JSON",
".",
"stringify",
"(",
"{",
"id",
":",
"_advertiseId",
"||",
"node",
".",
"id",
",",
"name",
":",
"node",
".",
"name",
",",
"endpoints",
":",
"masterBroker",
".",
"endpoints",
",",
"isMaster",
":",
"masterBroker",
".",
"isMaster",
",",
"candidate",
":",
"!",
"_advertiseId",
"}",
")",
"]",
")",
"break",
"case",
"'masterRequest'",
":",
"let",
"connectedMaster",
"=",
"node",
".",
"master",
"if",
"(",
"connectedMaster",
")",
"{",
"debug",
"(",
"`",
"${",
"message",
".",
"from",
"}",
"`",
")",
"_inbox",
".",
"send",
"(",
"[",
"sender",
",",
"_",
",",
"JSON",
".",
"stringify",
"(",
"connectedMaster",
")",
"]",
")",
"}",
"else",
"{",
"debug",
"(",
"`",
"${",
"message",
".",
"from",
"}",
"`",
")",
"_inbox",
".",
"send",
"(",
"[",
"sender",
",",
"_",
",",
"JSON",
".",
"stringify",
"(",
"false",
")",
"]",
")",
"}",
"break",
"case",
"'masterElected'",
":",
"_inbox",
".",
"send",
"(",
"[",
"sender",
",",
"_",
",",
"''",
"]",
")",
"debug",
"(",
"`",
"${",
"message",
".",
"data",
".",
"name",
"}",
"`",
")",
"resolver",
".",
"emit",
"(",
"'newmaster'",
",",
"message",
".",
"data",
")",
"}",
"}"
]
| function receiving the messages from the coordination router
@param {buffer} sender
@param {void} _
@param {buffer} msgBuffer | [
"function",
"receiving",
"the",
"messages",
"from",
"the",
"coordination",
"router"
]
| ab935cae537f8a7e61a6ed6fba247661281c9374 | https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/MasterElector.js#L33-L63 | train |
gtriggiano/dnsmq-messagebus | src/MasterElector.js | _broadcastMessage | function _broadcastMessage (type, data) {
data = data || {}
let message = {type, data}
let { host, coordinationPort } = node.settings
dns.resolve4(host, (err, addresses) => {
if (err) {
debug(`cannot resolve host '${host}'. Check DNS infrastructure.`)
return
}
debug(`broadcasting message '${type}' to '${host}' nodes: ${addresses}`)
addresses.forEach(address => {
let messenger = zmq.socket('req')
messenger.connect(`tcp://${address}:${coordinationPort}`)
messenger.send(JSON.stringify({
...message,
toAddress: address
}))
let _end = false
function closeSocket () {
if (_end) return
_end = true
messenger.close()
}
messenger.on('message', closeSocket)
setTimeout(closeSocket, 300)
})
})
} | javascript | function _broadcastMessage (type, data) {
data = data || {}
let message = {type, data}
let { host, coordinationPort } = node.settings
dns.resolve4(host, (err, addresses) => {
if (err) {
debug(`cannot resolve host '${host}'. Check DNS infrastructure.`)
return
}
debug(`broadcasting message '${type}' to '${host}' nodes: ${addresses}`)
addresses.forEach(address => {
let messenger = zmq.socket('req')
messenger.connect(`tcp://${address}:${coordinationPort}`)
messenger.send(JSON.stringify({
...message,
toAddress: address
}))
let _end = false
function closeSocket () {
if (_end) return
_end = true
messenger.close()
}
messenger.on('message', closeSocket)
setTimeout(closeSocket, 300)
})
})
} | [
"function",
"_broadcastMessage",
"(",
"type",
",",
"data",
")",
"{",
"data",
"=",
"data",
"||",
"{",
"}",
"let",
"message",
"=",
"{",
"type",
",",
"data",
"}",
"let",
"{",
"host",
",",
"coordinationPort",
"}",
"=",
"node",
".",
"settings",
"dns",
".",
"resolve4",
"(",
"host",
",",
"(",
"err",
",",
"addresses",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"`",
"${",
"host",
"}",
"`",
")",
"return",
"}",
"debug",
"(",
"`",
"${",
"type",
"}",
"${",
"host",
"}",
"${",
"addresses",
"}",
"`",
")",
"addresses",
".",
"forEach",
"(",
"address",
"=>",
"{",
"let",
"messenger",
"=",
"zmq",
".",
"socket",
"(",
"'req'",
")",
"messenger",
".",
"connect",
"(",
"`",
"${",
"address",
"}",
"${",
"coordinationPort",
"}",
"`",
")",
"messenger",
".",
"send",
"(",
"JSON",
".",
"stringify",
"(",
"{",
"...",
"message",
",",
"toAddress",
":",
"address",
"}",
")",
")",
"let",
"_end",
"=",
"false",
"function",
"closeSocket",
"(",
")",
"{",
"if",
"(",
"_end",
")",
"return",
"_end",
"=",
"true",
"messenger",
".",
"close",
"(",
")",
"}",
"messenger",
".",
"on",
"(",
"'message'",
",",
"closeSocket",
")",
"setTimeout",
"(",
"closeSocket",
",",
"300",
")",
"}",
")",
"}",
")",
"}"
]
| broadcasts a message to the coordination socket of all the dnsNodes
@param {string} type - Type of message
@param {object} data - Payload of the message | [
"broadcasts",
"a",
"message",
"to",
"the",
"coordination",
"socket",
"of",
"all",
"the",
"dnsNodes"
]
| ab935cae537f8a7e61a6ed6fba247661281c9374 | https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/MasterElector.js#L69-L98 | train |
gtriggiano/dnsmq-messagebus | src/MasterElector.js | _requestVotes | function _requestVotes () {
let { host, coordinationPort } = node.settings
let message = {
type: 'voteRequest',
data: {}
}
return new Promise((resolve, reject) => {
let resolveStart = Date.now()
dns.resolve4(host, (err, addresses) => {
if (err) {
debug(`cannot resolve host '${host}'. Check DNS infrastructure.`)
return reject(err)
}
debug(`resolved ${addresses.length} IP(s) for host '${host}' in ${Date.now() - resolveStart} ms`)
debug(`requesting votes from ${addresses.length} nodes`)
Promise.all(
addresses.map(address => new Promise((resolve, reject) => {
let voteRequestTime = Date.now()
let messenger = zmq.socket('req')
messenger.connect(`tcp://${address}:${coordinationPort}`)
messenger.send(JSON.stringify({
...message,
toAddress: address,
from: node.name
}))
let _resolved = false
function onEnd (candidateBuffer) {
if (_resolved) return
_resolved = true
messenger.removeListener('message', onEnd)
messenger.close()
let candidate = candidateBuffer && JSON.parse(candidateBuffer)
if (candidate) {
let elapsed = Date.now() - voteRequestTime
candidate.candidate && debug(`received vote by ${candidate.name === node.name ? 'myself' : candidate.name}${candidate.isMaster ? ' (master)' : ''} in ${elapsed} ms`)
} else {
debug(`missed vote by peer at ${address}`)
}
resolve(candidate)
}
messenger.on('message', onEnd)
setTimeout(onEnd, node.settings.voteTimeout)
}))
)
.then(nodes => compact(nodes))
.then(nodes => resolve(nodes.filter(({candidate}) => candidate)))
})
})
} | javascript | function _requestVotes () {
let { host, coordinationPort } = node.settings
let message = {
type: 'voteRequest',
data: {}
}
return new Promise((resolve, reject) => {
let resolveStart = Date.now()
dns.resolve4(host, (err, addresses) => {
if (err) {
debug(`cannot resolve host '${host}'. Check DNS infrastructure.`)
return reject(err)
}
debug(`resolved ${addresses.length} IP(s) for host '${host}' in ${Date.now() - resolveStart} ms`)
debug(`requesting votes from ${addresses.length} nodes`)
Promise.all(
addresses.map(address => new Promise((resolve, reject) => {
let voteRequestTime = Date.now()
let messenger = zmq.socket('req')
messenger.connect(`tcp://${address}:${coordinationPort}`)
messenger.send(JSON.stringify({
...message,
toAddress: address,
from: node.name
}))
let _resolved = false
function onEnd (candidateBuffer) {
if (_resolved) return
_resolved = true
messenger.removeListener('message', onEnd)
messenger.close()
let candidate = candidateBuffer && JSON.parse(candidateBuffer)
if (candidate) {
let elapsed = Date.now() - voteRequestTime
candidate.candidate && debug(`received vote by ${candidate.name === node.name ? 'myself' : candidate.name}${candidate.isMaster ? ' (master)' : ''} in ${elapsed} ms`)
} else {
debug(`missed vote by peer at ${address}`)
}
resolve(candidate)
}
messenger.on('message', onEnd)
setTimeout(onEnd, node.settings.voteTimeout)
}))
)
.then(nodes => compact(nodes))
.then(nodes => resolve(nodes.filter(({candidate}) => candidate)))
})
})
} | [
"function",
"_requestVotes",
"(",
")",
"{",
"let",
"{",
"host",
",",
"coordinationPort",
"}",
"=",
"node",
".",
"settings",
"let",
"message",
"=",
"{",
"type",
":",
"'voteRequest'",
",",
"data",
":",
"{",
"}",
"}",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"let",
"resolveStart",
"=",
"Date",
".",
"now",
"(",
")",
"dns",
".",
"resolve4",
"(",
"host",
",",
"(",
"err",
",",
"addresses",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"`",
"${",
"host",
"}",
"`",
")",
"return",
"reject",
"(",
"err",
")",
"}",
"debug",
"(",
"`",
"${",
"addresses",
".",
"length",
"}",
"${",
"host",
"}",
"${",
"Date",
".",
"now",
"(",
")",
"-",
"resolveStart",
"}",
"`",
")",
"debug",
"(",
"`",
"${",
"addresses",
".",
"length",
"}",
"`",
")",
"Promise",
".",
"all",
"(",
"addresses",
".",
"map",
"(",
"address",
"=>",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"let",
"voteRequestTime",
"=",
"Date",
".",
"now",
"(",
")",
"let",
"messenger",
"=",
"zmq",
".",
"socket",
"(",
"'req'",
")",
"messenger",
".",
"connect",
"(",
"`",
"${",
"address",
"}",
"${",
"coordinationPort",
"}",
"`",
")",
"messenger",
".",
"send",
"(",
"JSON",
".",
"stringify",
"(",
"{",
"...",
"message",
",",
"toAddress",
":",
"address",
",",
"from",
":",
"node",
".",
"name",
"}",
")",
")",
"let",
"_resolved",
"=",
"false",
"function",
"onEnd",
"(",
"candidateBuffer",
")",
"{",
"if",
"(",
"_resolved",
")",
"return",
"_resolved",
"=",
"true",
"messenger",
".",
"removeListener",
"(",
"'message'",
",",
"onEnd",
")",
"messenger",
".",
"close",
"(",
")",
"let",
"candidate",
"=",
"candidateBuffer",
"&&",
"JSON",
".",
"parse",
"(",
"candidateBuffer",
")",
"if",
"(",
"candidate",
")",
"{",
"let",
"elapsed",
"=",
"Date",
".",
"now",
"(",
")",
"-",
"voteRequestTime",
"candidate",
".",
"candidate",
"&&",
"debug",
"(",
"`",
"${",
"candidate",
".",
"name",
"===",
"node",
".",
"name",
"?",
"'myself'",
":",
"candidate",
".",
"name",
"}",
"${",
"candidate",
".",
"isMaster",
"?",
"' (master)'",
":",
"''",
"}",
"${",
"elapsed",
"}",
"`",
")",
"}",
"else",
"{",
"debug",
"(",
"`",
"${",
"address",
"}",
"`",
")",
"}",
"resolve",
"(",
"candidate",
")",
"}",
"messenger",
".",
"on",
"(",
"'message'",
",",
"onEnd",
")",
"setTimeout",
"(",
"onEnd",
",",
"node",
".",
"settings",
".",
"voteTimeout",
")",
"}",
")",
")",
")",
".",
"then",
"(",
"nodes",
"=>",
"compact",
"(",
"nodes",
")",
")",
".",
"then",
"(",
"nodes",
"=>",
"resolve",
"(",
"nodes",
".",
"filter",
"(",
"(",
"{",
"candidate",
"}",
")",
"=>",
"candidate",
")",
")",
")",
"}",
")",
"}",
")",
"}"
]
| requests the voting identity of all the eligible dnsNodes
@return {promise} An list of objects representing nodes eligible as master | [
"requests",
"the",
"voting",
"identity",
"of",
"all",
"the",
"eligible",
"dnsNodes"
]
| ab935cae537f8a7e61a6ed6fba247661281c9374 | https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/MasterElector.js#L103-L154 | train |
gtriggiano/dnsmq-messagebus | src/MasterElector.js | bind | function bind () {
_inbox.bindSync(`tcp://0.0.0.0:${node.settings.coordinationPort}`)
_inbox.on('message', _onInboxMessage)
return resolver
} | javascript | function bind () {
_inbox.bindSync(`tcp://0.0.0.0:${node.settings.coordinationPort}`)
_inbox.on('message', _onInboxMessage)
return resolver
} | [
"function",
"bind",
"(",
")",
"{",
"_inbox",
".",
"bindSync",
"(",
"`",
"${",
"node",
".",
"settings",
".",
"coordinationPort",
"}",
"`",
")",
"_inbox",
".",
"on",
"(",
"'message'",
",",
"_onInboxMessage",
")",
"return",
"resolver",
"}"
]
| Binds the coordination router socket to all interfaces
@return {object} masterElector | [
"Binds",
"the",
"coordination",
"router",
"socket",
"to",
"all",
"interfaces"
]
| ab935cae537f8a7e61a6ed6fba247661281c9374 | https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/MasterElector.js#L160-L164 | train |
gtriggiano/dnsmq-messagebus | src/MasterElector.js | unbind | function unbind () {
_inbox.unbindSync(`tcp://0.0.0.0:${node.settings.coordinationPort}`)
_inbox.removeListener('message', _onInboxMessage)
return resolver
} | javascript | function unbind () {
_inbox.unbindSync(`tcp://0.0.0.0:${node.settings.coordinationPort}`)
_inbox.removeListener('message', _onInboxMessage)
return resolver
} | [
"function",
"unbind",
"(",
")",
"{",
"_inbox",
".",
"unbindSync",
"(",
"`",
"${",
"node",
".",
"settings",
".",
"coordinationPort",
"}",
"`",
")",
"_inbox",
".",
"removeListener",
"(",
"'message'",
",",
"_onInboxMessage",
")",
"return",
"resolver",
"}"
]
| Unbinds the coordination router socket from all interfaces
@return {object} masterElector | [
"Unbinds",
"the",
"coordination",
"router",
"socket",
"from",
"all",
"interfaces"
]
| ab935cae537f8a7e61a6ed6fba247661281c9374 | https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/MasterElector.js#L169-L173 | train |
gtriggiano/dnsmq-messagebus | src/MasterElector.js | electMaster | function electMaster (advertiseId) {
_advertiseId = advertiseId || null
if (_electingMaster) return _electingMaster
_electingMaster = _requestVotes()
.then(nodes => {
_electingMaster = false
_advertiseId = null
const masterNodes = nodes.filter(
({isMaster}) => isMaster)
nodes = masterNodes.length ? masterNodes : nodes
const electedMaster = sortBy(nodes, ({id}) => id)[0]
if (!electedMaster) throw new Error('could not elect a master')
debug(`elected master: ${electedMaster.name} ${JSON.stringify(electedMaster.endpoints)}`)
_broadcastMessage('masterElected', electedMaster)
return electedMaster
})
_electingMaster.catch(() => {
_electingMaster = false
_advertiseId = null
})
return _electingMaster
} | javascript | function electMaster (advertiseId) {
_advertiseId = advertiseId || null
if (_electingMaster) return _electingMaster
_electingMaster = _requestVotes()
.then(nodes => {
_electingMaster = false
_advertiseId = null
const masterNodes = nodes.filter(
({isMaster}) => isMaster)
nodes = masterNodes.length ? masterNodes : nodes
const electedMaster = sortBy(nodes, ({id}) => id)[0]
if (!electedMaster) throw new Error('could not elect a master')
debug(`elected master: ${electedMaster.name} ${JSON.stringify(electedMaster.endpoints)}`)
_broadcastMessage('masterElected', electedMaster)
return electedMaster
})
_electingMaster.catch(() => {
_electingMaster = false
_advertiseId = null
})
return _electingMaster
} | [
"function",
"electMaster",
"(",
"advertiseId",
")",
"{",
"_advertiseId",
"=",
"advertiseId",
"||",
"null",
"if",
"(",
"_electingMaster",
")",
"return",
"_electingMaster",
"_electingMaster",
"=",
"_requestVotes",
"(",
")",
".",
"then",
"(",
"nodes",
"=>",
"{",
"_electingMaster",
"=",
"false",
"_advertiseId",
"=",
"null",
"const",
"masterNodes",
"=",
"nodes",
".",
"filter",
"(",
"(",
"{",
"isMaster",
"}",
")",
"=>",
"isMaster",
")",
"nodes",
"=",
"masterNodes",
".",
"length",
"?",
"masterNodes",
":",
"nodes",
"const",
"electedMaster",
"=",
"sortBy",
"(",
"nodes",
",",
"(",
"{",
"id",
"}",
")",
"=>",
"id",
")",
"[",
"0",
"]",
"if",
"(",
"!",
"electedMaster",
")",
"throw",
"new",
"Error",
"(",
"'could not elect a master'",
")",
"debug",
"(",
"`",
"${",
"electedMaster",
".",
"name",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"electedMaster",
".",
"endpoints",
")",
"}",
"`",
")",
"_broadcastMessage",
"(",
"'masterElected'",
",",
"electedMaster",
")",
"return",
"electedMaster",
"}",
")",
"_electingMaster",
".",
"catch",
"(",
"(",
")",
"=>",
"{",
"_electingMaster",
"=",
"false",
"_advertiseId",
"=",
"null",
"}",
")",
"return",
"_electingMaster",
"}"
]
| Triggers a master election
@alias resolve
@param {string} [advertiseId] - A fake id to use for this node during the election
@return {promise} An object containing the name and the pub/sub endpoints of the master node | [
"Triggers",
"a",
"master",
"election"
]
| ab935cae537f8a7e61a6ed6fba247661281c9374 | https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/MasterElector.js#L180-L203 | train |
mnaamani/otr3-em | lib/bigint.js | millerRabin | function millerRabin(x,b) {
var i,j,k,s;
if (mr_x1.length!=x.length) {
mr_x1=dup(x);
mr_r=dup(x);
mr_a=dup(x);
}
copy_(mr_a,b);
copy_(mr_r,x);
copy_(mr_x1,x);
addInt_(mr_r,-1);
addInt_(mr_x1,-1);
//s=the highest power of two that divides mr_r
/*
k=0;
for (i=0;i<mr_r.length;i++)
for (j=1;j<mask;j<<=1)
if (x[i] & j) {
s=(k<mr_r.length+bpe ? k : 0);
i=mr_r.length;
j=mask;
} else
k++;
*/
/* http://www.javascripter.net/math/primes/millerrabinbug-bigint54.htm */
if (isZero(mr_r)) return 0;
for (k=0; mr_r[k]==0; k++);
for (i=1,j=2; mr_r[k]%j==0; j*=2,i++ );
s = k*bpe + i - 1;
/* end */
if (s)
rightShift_(mr_r,s);
powMod_(mr_a,mr_r,x);
if (!equalsInt(mr_a,1) && !equals(mr_a,mr_x1)) {
j=1;
while (j<=s-1 && !equals(mr_a,mr_x1)) {
squareMod_(mr_a,x);
if (equalsInt(mr_a,1)) {
return 0;
}
j++;
}
if (!equals(mr_a,mr_x1)) {
return 0;
}
}
return 1;
} | javascript | function millerRabin(x,b) {
var i,j,k,s;
if (mr_x1.length!=x.length) {
mr_x1=dup(x);
mr_r=dup(x);
mr_a=dup(x);
}
copy_(mr_a,b);
copy_(mr_r,x);
copy_(mr_x1,x);
addInt_(mr_r,-1);
addInt_(mr_x1,-1);
//s=the highest power of two that divides mr_r
/*
k=0;
for (i=0;i<mr_r.length;i++)
for (j=1;j<mask;j<<=1)
if (x[i] & j) {
s=(k<mr_r.length+bpe ? k : 0);
i=mr_r.length;
j=mask;
} else
k++;
*/
/* http://www.javascripter.net/math/primes/millerrabinbug-bigint54.htm */
if (isZero(mr_r)) return 0;
for (k=0; mr_r[k]==0; k++);
for (i=1,j=2; mr_r[k]%j==0; j*=2,i++ );
s = k*bpe + i - 1;
/* end */
if (s)
rightShift_(mr_r,s);
powMod_(mr_a,mr_r,x);
if (!equalsInt(mr_a,1) && !equals(mr_a,mr_x1)) {
j=1;
while (j<=s-1 && !equals(mr_a,mr_x1)) {
squareMod_(mr_a,x);
if (equalsInt(mr_a,1)) {
return 0;
}
j++;
}
if (!equals(mr_a,mr_x1)) {
return 0;
}
}
return 1;
} | [
"function",
"millerRabin",
"(",
"x",
",",
"b",
")",
"{",
"var",
"i",
",",
"j",
",",
"k",
",",
"s",
";",
"if",
"(",
"mr_x1",
".",
"length",
"!=",
"x",
".",
"length",
")",
"{",
"mr_x1",
"=",
"dup",
"(",
"x",
")",
";",
"mr_r",
"=",
"dup",
"(",
"x",
")",
";",
"mr_a",
"=",
"dup",
"(",
"x",
")",
";",
"}",
"copy_",
"(",
"mr_a",
",",
"b",
")",
";",
"copy_",
"(",
"mr_r",
",",
"x",
")",
";",
"copy_",
"(",
"mr_x1",
",",
"x",
")",
";",
"addInt_",
"(",
"mr_r",
",",
"-",
"1",
")",
";",
"addInt_",
"(",
"mr_x1",
",",
"-",
"1",
")",
";",
"if",
"(",
"isZero",
"(",
"mr_r",
")",
")",
"return",
"0",
";",
"for",
"(",
"k",
"=",
"0",
";",
"mr_r",
"[",
"k",
"]",
"==",
"0",
";",
"k",
"++",
")",
";",
"for",
"(",
"i",
"=",
"1",
",",
"j",
"=",
"2",
";",
"mr_r",
"[",
"k",
"]",
"%",
"j",
"==",
"0",
";",
"j",
"*=",
"2",
",",
"i",
"++",
")",
";",
"s",
"=",
"k",
"*",
"bpe",
"+",
"i",
"-",
"1",
";",
"if",
"(",
"s",
")",
"rightShift_",
"(",
"mr_r",
",",
"s",
")",
";",
"powMod_",
"(",
"mr_a",
",",
"mr_r",
",",
"x",
")",
";",
"if",
"(",
"!",
"equalsInt",
"(",
"mr_a",
",",
"1",
")",
"&&",
"!",
"equals",
"(",
"mr_a",
",",
"mr_x1",
")",
")",
"{",
"j",
"=",
"1",
";",
"while",
"(",
"j",
"<=",
"s",
"-",
"1",
"&&",
"!",
"equals",
"(",
"mr_a",
",",
"mr_x1",
")",
")",
"{",
"squareMod_",
"(",
"mr_a",
",",
"x",
")",
";",
"if",
"(",
"equalsInt",
"(",
"mr_a",
",",
"1",
")",
")",
"{",
"return",
"0",
";",
"}",
"j",
"++",
";",
"}",
"if",
"(",
"!",
"equals",
"(",
"mr_a",
",",
"mr_x1",
")",
")",
"{",
"return",
"0",
";",
"}",
"}",
"return",
"1",
";",
"}"
]
| does a single round of Miller-Rabin base b consider x to be a possible prime? x and b are bigInts with b<x | [
"does",
"a",
"single",
"round",
"of",
"Miller",
"-",
"Rabin",
"base",
"b",
"consider",
"x",
"to",
"be",
"a",
"possible",
"prime?",
"x",
"and",
"b",
"are",
"bigInts",
"with",
"b<x"
]
| f335c03d1be2c8c73a192908088a2dc366ba6a4e | https://github.com/mnaamani/otr3-em/blob/f335c03d1be2c8c73a192908088a2dc366ba6a4e/lib/bigint.js#L302-L358 | train |
mnaamani/otr3-em | lib/bigint.js | bigInt2str | function bigInt2str(x,base) {
var i,t,s="";
if (s6.length!=x.length)
s6=dup(x);
else
copy_(s6,x);
if (base==-1) { //return the list of array contents
for (i=x.length-1;i>0;i--)
s+=x[i]+',';
s+=x[0];
}
else { //return it in the given base
while (!isZero(s6)) {
t=divInt_(s6,base); //t=s6 % base; s6=floor(s6/base);
s=digitsStr.substring(t,t+1)+s;
}
}
if (s.length==0)
s="0";
return s;
} | javascript | function bigInt2str(x,base) {
var i,t,s="";
if (s6.length!=x.length)
s6=dup(x);
else
copy_(s6,x);
if (base==-1) { //return the list of array contents
for (i=x.length-1;i>0;i--)
s+=x[i]+',';
s+=x[0];
}
else { //return it in the given base
while (!isZero(s6)) {
t=divInt_(s6,base); //t=s6 % base; s6=floor(s6/base);
s=digitsStr.substring(t,t+1)+s;
}
}
if (s.length==0)
s="0";
return s;
} | [
"function",
"bigInt2str",
"(",
"x",
",",
"base",
")",
"{",
"var",
"i",
",",
"t",
",",
"s",
"=",
"\"\"",
";",
"if",
"(",
"s6",
".",
"length",
"!=",
"x",
".",
"length",
")",
"s6",
"=",
"dup",
"(",
"x",
")",
";",
"else",
"copy_",
"(",
"s6",
",",
"x",
")",
";",
"if",
"(",
"base",
"==",
"-",
"1",
")",
"{",
"for",
"(",
"i",
"=",
"x",
".",
"length",
"-",
"1",
";",
"i",
">",
"0",
";",
"i",
"--",
")",
"s",
"+=",
"x",
"[",
"i",
"]",
"+",
"','",
";",
"s",
"+=",
"x",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"while",
"(",
"!",
"isZero",
"(",
"s6",
")",
")",
"{",
"t",
"=",
"divInt_",
"(",
"s6",
",",
"base",
")",
";",
"s",
"=",
"digitsStr",
".",
"substring",
"(",
"t",
",",
"t",
"+",
"1",
")",
"+",
"s",
";",
"}",
"}",
"if",
"(",
"s",
".",
"length",
"==",
"0",
")",
"s",
"=",
"\"0\"",
";",
"return",
"s",
";",
"}"
]
| convert a bigInt into a string in a given base, from base 2 up to base 95. Base -1 prints the contents of the array representing the number. | [
"convert",
"a",
"bigInt",
"into",
"a",
"string",
"in",
"a",
"given",
"base",
"from",
"base",
"2",
"up",
"to",
"base",
"95",
".",
"Base",
"-",
"1",
"prints",
"the",
"contents",
"of",
"the",
"array",
"representing",
"the",
"number",
"."
]
| f335c03d1be2c8c73a192908088a2dc366ba6a4e | https://github.com/mnaamani/otr3-em/blob/f335c03d1be2c8c73a192908088a2dc366ba6a4e/lib/bigint.js#L1128-L1150 | train |
mnaamani/otr3-em | lib/bigint.js | dup | function dup(x) {
var i, buff;
buff=new Array(x.length);
copy_(buff,x);
return buff;
} | javascript | function dup(x) {
var i, buff;
buff=new Array(x.length);
copy_(buff,x);
return buff;
} | [
"function",
"dup",
"(",
"x",
")",
"{",
"var",
"i",
",",
"buff",
";",
"buff",
"=",
"new",
"Array",
"(",
"x",
".",
"length",
")",
";",
"copy_",
"(",
"buff",
",",
"x",
")",
";",
"return",
"buff",
";",
"}"
]
| returns a duplicate of bigInt x | [
"returns",
"a",
"duplicate",
"of",
"bigInt",
"x"
]
| f335c03d1be2c8c73a192908088a2dc366ba6a4e | https://github.com/mnaamani/otr3-em/blob/f335c03d1be2c8c73a192908088a2dc366ba6a4e/lib/bigint.js#L1153-L1158 | train |
mnaamani/otr3-em | lib/bigint.js | copyInt_ | function copyInt_(x,n) {
var i,c;
for (c=n,i=0;i<x.length;i++) {
x[i]=c & mask;
c>>=bpe;
}
} | javascript | function copyInt_(x,n) {
var i,c;
for (c=n,i=0;i<x.length;i++) {
x[i]=c & mask;
c>>=bpe;
}
} | [
"function",
"copyInt_",
"(",
"x",
",",
"n",
")",
"{",
"var",
"i",
",",
"c",
";",
"for",
"(",
"c",
"=",
"n",
",",
"i",
"=",
"0",
";",
"i",
"<",
"x",
".",
"length",
";",
"i",
"++",
")",
"{",
"x",
"[",
"i",
"]",
"=",
"c",
"&",
"mask",
";",
"c",
">>=",
"bpe",
";",
"}",
"}"
]
| do x=y on bigInt x and integer y. | [
"do",
"x",
"=",
"y",
"on",
"bigInt",
"x",
"and",
"integer",
"y",
"."
]
| f335c03d1be2c8c73a192908088a2dc366ba6a4e | https://github.com/mnaamani/otr3-em/blob/f335c03d1be2c8c73a192908088a2dc366ba6a4e/lib/bigint.js#L1171-L1177 | train |
zedgu/ovenware | lib/loader.js | pathParser | function pathParser(root, extname, subPath, paths) {
var dirPath = path.resolve(subPath || root);
var files;
paths = paths || {};
try {
files = fs.readdirSync(dirPath);
} catch(e) {
files = [];
}
files.forEach(function(file) {
file = path.join(dirPath, '/', file);
if (fs.statSync(file).isFile()) {
if (~extname.split('|').indexOf(path.extname(file).substr(1))) {
var rootPath = '^' + path.join(path.resolve(root), '/');
rootPath = rootPath.replace(/\\/g, '\\\\') + '(.*)\.(' + extname + ')$';
paths[file.match(new RegExp(rootPath))[1].toLowerCase()] = file;
}
} else if (fs.statSync(file).isDirectory()) {
pathParser(root, extname, file, paths);
}
});
return paths;
} | javascript | function pathParser(root, extname, subPath, paths) {
var dirPath = path.resolve(subPath || root);
var files;
paths = paths || {};
try {
files = fs.readdirSync(dirPath);
} catch(e) {
files = [];
}
files.forEach(function(file) {
file = path.join(dirPath, '/', file);
if (fs.statSync(file).isFile()) {
if (~extname.split('|').indexOf(path.extname(file).substr(1))) {
var rootPath = '^' + path.join(path.resolve(root), '/');
rootPath = rootPath.replace(/\\/g, '\\\\') + '(.*)\.(' + extname + ')$';
paths[file.match(new RegExp(rootPath))[1].toLowerCase()] = file;
}
} else if (fs.statSync(file).isDirectory()) {
pathParser(root, extname, file, paths);
}
});
return paths;
} | [
"function",
"pathParser",
"(",
"root",
",",
"extname",
",",
"subPath",
",",
"paths",
")",
"{",
"var",
"dirPath",
"=",
"path",
".",
"resolve",
"(",
"subPath",
"||",
"root",
")",
";",
"var",
"files",
";",
"paths",
"=",
"paths",
"||",
"{",
"}",
";",
"try",
"{",
"files",
"=",
"fs",
".",
"readdirSync",
"(",
"dirPath",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"files",
"=",
"[",
"]",
";",
"}",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"file",
"=",
"path",
".",
"join",
"(",
"dirPath",
",",
"'/'",
",",
"file",
")",
";",
"if",
"(",
"fs",
".",
"statSync",
"(",
"file",
")",
".",
"isFile",
"(",
")",
")",
"{",
"if",
"(",
"~",
"extname",
".",
"split",
"(",
"'|'",
")",
".",
"indexOf",
"(",
"path",
".",
"extname",
"(",
"file",
")",
".",
"substr",
"(",
"1",
")",
")",
")",
"{",
"var",
"rootPath",
"=",
"'^'",
"+",
"path",
".",
"join",
"(",
"path",
".",
"resolve",
"(",
"root",
")",
",",
"'/'",
")",
";",
"rootPath",
"=",
"rootPath",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'\\\\\\\\'",
")",
"+",
"\\\\",
"+",
"\\\\",
"+",
"'(.*)\\.('",
";",
"\\.",
"}",
"}",
"else",
"extname",
"}",
")",
";",
"')$'",
"}"
]
| to parse the paths of files
@param {String} root root path
@param {String} subPath sub dir path
@param {Object} paths dictionary of the paths
@return {Object} dictionary of the paths
@api private | [
"to",
"parse",
"the",
"paths",
"of",
"files"
]
| 0fa42d020ce303ee63c58b9d58774880fc2117d7 | https://github.com/zedgu/ovenware/blob/0fa42d020ce303ee63c58b9d58774880fc2117d7/lib/loader.js#L23-L46 | train |
byu-oit/fully-typed | bin/boolean.js | TypedBoolean | function TypedBoolean (config) {
const boolean = this;
// define properties
Object.defineProperties(boolean, {
strict: {
/**
* @property
* @name TypedBoolean#strict
* @type {boolean}
*/
value: config.hasOwnProperty('strict') ? !!config.strict : false,
writable: false
}
});
return boolean;
} | javascript | function TypedBoolean (config) {
const boolean = this;
// define properties
Object.defineProperties(boolean, {
strict: {
/**
* @property
* @name TypedBoolean#strict
* @type {boolean}
*/
value: config.hasOwnProperty('strict') ? !!config.strict : false,
writable: false
}
});
return boolean;
} | [
"function",
"TypedBoolean",
"(",
"config",
")",
"{",
"const",
"boolean",
"=",
"this",
";",
"Object",
".",
"defineProperties",
"(",
"boolean",
",",
"{",
"strict",
":",
"{",
"value",
":",
"config",
".",
"hasOwnProperty",
"(",
"'strict'",
")",
"?",
"!",
"!",
"config",
".",
"strict",
":",
"false",
",",
"writable",
":",
"false",
"}",
"}",
")",
";",
"return",
"boolean",
";",
"}"
]
| Create a TypedBoolean instance.
@param {object} config
@returns {TypedBoolean}
@augments Typed
@constructor | [
"Create",
"a",
"TypedBoolean",
"instance",
"."
]
| ed6b3ed88ffc72990acffb765232eaaee261afef | https://github.com/byu-oit/fully-typed/blob/ed6b3ed88ffc72990acffb765232eaaee261afef/bin/boolean.js#L29-L48 | train |
semibran/css-duration | index.js | duration | function duration (time) {
var number = parseFloat(time)
switch (unit(time)) {
case null:
case 'ms': return number
case 's': return number * 1000
case 'm': return number * 60000
case 'h': return number * 3600000
case 'd': return number * 86400000
case 'w': return number * 604800000
default: return null
}
} | javascript | function duration (time) {
var number = parseFloat(time)
switch (unit(time)) {
case null:
case 'ms': return number
case 's': return number * 1000
case 'm': return number * 60000
case 'h': return number * 3600000
case 'd': return number * 86400000
case 'w': return number * 604800000
default: return null
}
} | [
"function",
"duration",
"(",
"time",
")",
"{",
"var",
"number",
"=",
"parseFloat",
"(",
"time",
")",
"switch",
"(",
"unit",
"(",
"time",
")",
")",
"{",
"case",
"null",
":",
"case",
"'ms'",
":",
"return",
"number",
"case",
"'s'",
":",
"return",
"number",
"*",
"1000",
"case",
"'m'",
":",
"return",
"number",
"*",
"60000",
"case",
"'h'",
":",
"return",
"number",
"*",
"3600000",
"case",
"'d'",
":",
"return",
"number",
"*",
"86400000",
"case",
"'w'",
":",
"return",
"number",
"*",
"604800000",
"default",
":",
"return",
"null",
"}",
"}"
]
| Normalize duration value into milliseconds. | [
"Normalize",
"duration",
"value",
"into",
"milliseconds",
"."
]
| ca9b1a2f5a03630c034ec92b4f61561cc8013eae | https://github.com/semibran/css-duration/blob/ca9b1a2f5a03630c034ec92b4f61561cc8013eae/index.js#L8-L20 | train |
GeorP/js-ntc-logger | src/core/utils.js | mergeTags | function mergeTags(base, addition) {
Array.prototype.push.apply(base, addition);
return base;
} | javascript | function mergeTags(base, addition) {
Array.prototype.push.apply(base, addition);
return base;
} | [
"function",
"mergeTags",
"(",
"base",
",",
"addition",
")",
"{",
"Array",
".",
"prototype",
".",
"push",
".",
"apply",
"(",
"base",
",",
"addition",
")",
";",
"return",
"base",
";",
"}"
]
| Modify base array adding all tag from addition | [
"Modify",
"base",
"array",
"adding",
"all",
"tag",
"from",
"addition"
]
| 8eec0fc95794ae25d65b4424154ded72d7887ca2 | https://github.com/GeorP/js-ntc-logger/blob/8eec0fc95794ae25d65b4424154ded72d7887ca2/src/core/utils.js#L29-L32 | train |
GeorP/js-ntc-logger | src/core/utils.js | logLevelLabel | function logLevelLabel(logLevel) {
switch (logLevel) {
case exports.LOG_EMERGENCY: return 'emergency';
case exports.LOG_ALERT: return 'alert';
case exports.LOG_CRITICAL: return 'critical';
case exports.LOG_ERROR: return 'error';
case exports.LOG_WARNING: return 'warning';
case exports.LOG_NOTICE: return 'notice';
case exports.LOG_INFORMATIONAL: return 'info';
case exports.LOG_DEBUG: return 'debug';
default: return '';
}
} | javascript | function logLevelLabel(logLevel) {
switch (logLevel) {
case exports.LOG_EMERGENCY: return 'emergency';
case exports.LOG_ALERT: return 'alert';
case exports.LOG_CRITICAL: return 'critical';
case exports.LOG_ERROR: return 'error';
case exports.LOG_WARNING: return 'warning';
case exports.LOG_NOTICE: return 'notice';
case exports.LOG_INFORMATIONAL: return 'info';
case exports.LOG_DEBUG: return 'debug';
default: return '';
}
} | [
"function",
"logLevelLabel",
"(",
"logLevel",
")",
"{",
"switch",
"(",
"logLevel",
")",
"{",
"case",
"exports",
".",
"LOG_EMERGENCY",
":",
"return",
"'emergency'",
";",
"case",
"exports",
".",
"LOG_ALERT",
":",
"return",
"'alert'",
";",
"case",
"exports",
".",
"LOG_CRITICAL",
":",
"return",
"'critical'",
";",
"case",
"exports",
".",
"LOG_ERROR",
":",
"return",
"'error'",
";",
"case",
"exports",
".",
"LOG_WARNING",
":",
"return",
"'warning'",
";",
"case",
"exports",
".",
"LOG_NOTICE",
":",
"return",
"'notice'",
";",
"case",
"exports",
".",
"LOG_INFORMATIONAL",
":",
"return",
"'info'",
";",
"case",
"exports",
".",
"LOG_DEBUG",
":",
"return",
"'debug'",
";",
"default",
":",
"return",
"''",
";",
"}",
"}"
]
| Get label by syslog level tag | [
"Get",
"label",
"by",
"syslog",
"level",
"tag"
]
| 8eec0fc95794ae25d65b4424154ded72d7887ca2 | https://github.com/GeorP/js-ntc-logger/blob/8eec0fc95794ae25d65b4424154ded72d7887ca2/src/core/utils.js#L37-L49 | train |
GeorP/js-ntc-logger | src/core/utils.js | hasLogLevel | function hasLogLevel(tags, searchLogLevels) {
var logLevel = tags.filter(function (tag) { return searchLogLevels.indexOf(tag) !== -1; });
return logLevel.length ? logLevel[0] : '';
} | javascript | function hasLogLevel(tags, searchLogLevels) {
var logLevel = tags.filter(function (tag) { return searchLogLevels.indexOf(tag) !== -1; });
return logLevel.length ? logLevel[0] : '';
} | [
"function",
"hasLogLevel",
"(",
"tags",
",",
"searchLogLevels",
")",
"{",
"var",
"logLevel",
"=",
"tags",
".",
"filter",
"(",
"function",
"(",
"tag",
")",
"{",
"return",
"searchLogLevels",
".",
"indexOf",
"(",
"tag",
")",
"!==",
"-",
"1",
";",
"}",
")",
";",
"return",
"logLevel",
".",
"length",
"?",
"logLevel",
"[",
"0",
"]",
":",
"''",
";",
"}"
]
| Check if list of tags has log level from searchLogLevels array
Returns first met tag or empty string if log level not found | [
"Check",
"if",
"list",
"of",
"tags",
"has",
"log",
"level",
"from",
"searchLogLevels",
"array",
"Returns",
"first",
"met",
"tag",
"or",
"empty",
"string",
"if",
"log",
"level",
"not",
"found"
]
| 8eec0fc95794ae25d65b4424154ded72d7887ca2 | https://github.com/GeorP/js-ntc-logger/blob/8eec0fc95794ae25d65b4424154ded72d7887ca2/src/core/utils.js#L55-L58 | train |
smikodanic/angular-form-validator | src/factory/validateFact.js | function (scope, iAttrs, newValue) {
'use strict';
var ngModelArr = iAttrs.ngModel.split('.');
// console.log(JSON.stringify(ngModelArr, null, 2));
switch (ngModelArr.length) {
case 1:
scope.$apply(function () {scope[ngModelArr[0]] = newValue;});
break;
case 2:
scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]] = newValue;});
break;
case 3:
scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]][ngModelArr[2]] = newValue;});
break;
case 4:
scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]][ngModelArr[2]][ngModelArr[3]] = newValue;});
break;
case 5:
scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]][ngModelArr[2]][ngModelArr[3]][ngModelArr[4]] = newValue;});
break;
default:
scope.$apply(function () {scope[iAttrs.ngModel] = newValue;});
}
} | javascript | function (scope, iAttrs, newValue) {
'use strict';
var ngModelArr = iAttrs.ngModel.split('.');
// console.log(JSON.stringify(ngModelArr, null, 2));
switch (ngModelArr.length) {
case 1:
scope.$apply(function () {scope[ngModelArr[0]] = newValue;});
break;
case 2:
scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]] = newValue;});
break;
case 3:
scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]][ngModelArr[2]] = newValue;});
break;
case 4:
scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]][ngModelArr[2]][ngModelArr[3]] = newValue;});
break;
case 5:
scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]][ngModelArr[2]][ngModelArr[3]][ngModelArr[4]] = newValue;});
break;
default:
scope.$apply(function () {scope[iAttrs.ngModel] = newValue;});
}
} | [
"function",
"(",
"scope",
",",
"iAttrs",
",",
"newValue",
")",
"{",
"'use strict'",
";",
"var",
"ngModelArr",
"=",
"iAttrs",
".",
"ngModel",
".",
"split",
"(",
"'.'",
")",
";",
"switch",
"(",
"ngModelArr",
".",
"length",
")",
"{",
"case",
"1",
":",
"scope",
".",
"$apply",
"(",
"function",
"(",
")",
"{",
"scope",
"[",
"ngModelArr",
"[",
"0",
"]",
"]",
"=",
"newValue",
";",
"}",
")",
";",
"break",
";",
"case",
"2",
":",
"scope",
".",
"$apply",
"(",
"function",
"(",
")",
"{",
"scope",
"[",
"ngModelArr",
"[",
"0",
"]",
"]",
"[",
"ngModelArr",
"[",
"1",
"]",
"]",
"=",
"newValue",
";",
"}",
")",
";",
"break",
";",
"case",
"3",
":",
"scope",
".",
"$apply",
"(",
"function",
"(",
")",
"{",
"scope",
"[",
"ngModelArr",
"[",
"0",
"]",
"]",
"[",
"ngModelArr",
"[",
"1",
"]",
"]",
"[",
"ngModelArr",
"[",
"2",
"]",
"]",
"=",
"newValue",
";",
"}",
")",
";",
"break",
";",
"case",
"4",
":",
"scope",
".",
"$apply",
"(",
"function",
"(",
")",
"{",
"scope",
"[",
"ngModelArr",
"[",
"0",
"]",
"]",
"[",
"ngModelArr",
"[",
"1",
"]",
"]",
"[",
"ngModelArr",
"[",
"2",
"]",
"]",
"[",
"ngModelArr",
"[",
"3",
"]",
"]",
"=",
"newValue",
";",
"}",
")",
";",
"break",
";",
"case",
"5",
":",
"scope",
".",
"$apply",
"(",
"function",
"(",
")",
"{",
"scope",
"[",
"ngModelArr",
"[",
"0",
"]",
"]",
"[",
"ngModelArr",
"[",
"1",
"]",
"]",
"[",
"ngModelArr",
"[",
"2",
"]",
"]",
"[",
"ngModelArr",
"[",
"3",
"]",
"]",
"[",
"ngModelArr",
"[",
"4",
"]",
"]",
"=",
"newValue",
";",
"}",
")",
";",
"break",
";",
"default",
":",
"scope",
".",
"$apply",
"(",
"function",
"(",
")",
"{",
"scope",
"[",
"iAttrs",
".",
"ngModel",
"]",
"=",
"newValue",
";",
"}",
")",
";",
"}",
"}"
]
| Update scope value. Usually on autocorrection.
@param {Object} scope - angular $scope object
@param {Object} iAttrs - attribute object which contains HTML tag attributes
@param {Mixed} - new value | [
"Update",
"scope",
"value",
".",
"Usually",
"on",
"autocorrection",
"."
]
| 7030eacb4695e5f0a77a99f4234fe46d3357a4a3 | https://github.com/smikodanic/angular-form-validator/blob/7030eacb4695e5f0a77a99f4234fe46d3357a4a3/src/factory/validateFact.js#L27-L53 | train |
|
YusukeHirao/sceg | lib/fn/get.js | get | function get(path) {
var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var config = assignConfig_1.default(option, path);
return globElements_1.default(config).then(readElements_1.default(config)).then(optimize_1.default());
} | javascript | function get(path) {
var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var config = assignConfig_1.default(option, path);
return globElements_1.default(config).then(readElements_1.default(config)).then(optimize_1.default());
} | [
"function",
"get",
"(",
"path",
")",
"{",
"var",
"option",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"{",
"}",
";",
"var",
"config",
"=",
"assignConfig_1",
".",
"default",
"(",
"option",
",",
"path",
")",
";",
"return",
"globElements_1",
".",
"default",
"(",
"config",
")",
".",
"then",
"(",
"readElements_1",
".",
"default",
"(",
"config",
")",
")",
".",
"then",
"(",
"optimize_1",
".",
"default",
"(",
")",
")",
";",
"}"
]
| Create guide data from elements
@param path Paths of element files that glob pattern
@param option Optional configure
@return guide data object | [
"Create",
"guide",
"data",
"from",
"elements"
]
| 4cde1e56d48dd3b604cc2ddff36b2e9de3348771 | https://github.com/YusukeHirao/sceg/blob/4cde1e56d48dd3b604cc2ddff36b2e9de3348771/lib/fn/get.js#L15-L20 | train |
tniedbala/jxh | dist/jxh.js | jxh | function jxh(obj, indentStr = ' ', indentLevel = 0) {
let html = '';
switch (getType(obj)) {
case 'array':
for (let item of obj) {
html += jxh(item, indentStr, indentLevel);
}
break;
case 'object':
for (let tag in obj) {
let content = obj[tag];
html += routeTags(tag, content, indentStr, indentLevel);
}
break;
default:
objTypeError(obj);
break;
}
return html;
} | javascript | function jxh(obj, indentStr = ' ', indentLevel = 0) {
let html = '';
switch (getType(obj)) {
case 'array':
for (let item of obj) {
html += jxh(item, indentStr, indentLevel);
}
break;
case 'object':
for (let tag in obj) {
let content = obj[tag];
html += routeTags(tag, content, indentStr, indentLevel);
}
break;
default:
objTypeError(obj);
break;
}
return html;
} | [
"function",
"jxh",
"(",
"obj",
",",
"indentStr",
"=",
"' '",
",",
"indentLevel",
"=",
"0",
")",
"{",
"let",
"html",
"=",
"''",
";",
"switch",
"(",
"getType",
"(",
"obj",
")",
")",
"{",
"case",
"'array'",
":",
"for",
"(",
"let",
"item",
"of",
"obj",
")",
"{",
"html",
"+=",
"jxh",
"(",
"item",
",",
"indentStr",
",",
"indentLevel",
")",
";",
"}",
"break",
";",
"case",
"'object'",
":",
"for",
"(",
"let",
"tag",
"in",
"obj",
")",
"{",
"let",
"content",
"=",
"obj",
"[",
"tag",
"]",
";",
"html",
"+=",
"routeTags",
"(",
"tag",
",",
"content",
",",
"indentStr",
",",
"indentLevel",
")",
";",
"}",
"break",
";",
"default",
":",
"objTypeError",
"(",
"obj",
")",
";",
"break",
";",
"}",
"return",
"html",
";",
"}"
]
| main function - entry point for object & array arguments | [
"main",
"function",
"-",
"entry",
"point",
"for",
"object",
"&",
"array",
"arguments"
]
| 83d699b126c5c7099ffea1f86ccacf5ec50ee6a9 | https://github.com/tniedbala/jxh/blob/83d699b126c5c7099ffea1f86ccacf5ec50ee6a9/dist/jxh.js#L14-L33 | train |
tniedbala/jxh | dist/jxh.js | routeTags | function routeTags(tag, content, indentStr, indentLevel) {
if (COMPONENT.test(tag)) {
return jxh(content, indentStr, indentLevel);
} else {
let attrs = getType(content)==='object' ? getAttributes(content) : '';
switch (getType(content)) {
case 'null':
case 'undefined':
case 'NaN':
case 'string':
case 'number':
case 'boolean':
return renderElement(tag, attrs, content, indentStr, indentLevel);
break;
case 'array':
return parseArray(tag, attrs, content, indentStr, indentLevel);
break;
case 'object':
return parseObject(tag, attrs, content, indentStr, indentLevel);
break;
default:
objTypeError(content);
break;
}
}
} | javascript | function routeTags(tag, content, indentStr, indentLevel) {
if (COMPONENT.test(tag)) {
return jxh(content, indentStr, indentLevel);
} else {
let attrs = getType(content)==='object' ? getAttributes(content) : '';
switch (getType(content)) {
case 'null':
case 'undefined':
case 'NaN':
case 'string':
case 'number':
case 'boolean':
return renderElement(tag, attrs, content, indentStr, indentLevel);
break;
case 'array':
return parseArray(tag, attrs, content, indentStr, indentLevel);
break;
case 'object':
return parseObject(tag, attrs, content, indentStr, indentLevel);
break;
default:
objTypeError(content);
break;
}
}
} | [
"function",
"routeTags",
"(",
"tag",
",",
"content",
",",
"indentStr",
",",
"indentLevel",
")",
"{",
"if",
"(",
"COMPONENT",
".",
"test",
"(",
"tag",
")",
")",
"{",
"return",
"jxh",
"(",
"content",
",",
"indentStr",
",",
"indentLevel",
")",
";",
"}",
"else",
"{",
"let",
"attrs",
"=",
"getType",
"(",
"content",
")",
"===",
"'object'",
"?",
"getAttributes",
"(",
"content",
")",
":",
"''",
";",
"switch",
"(",
"getType",
"(",
"content",
")",
")",
"{",
"case",
"'null'",
":",
"case",
"'undefined'",
":",
"case",
"'NaN'",
":",
"case",
"'string'",
":",
"case",
"'number'",
":",
"case",
"'boolean'",
":",
"return",
"renderElement",
"(",
"tag",
",",
"attrs",
",",
"content",
",",
"indentStr",
",",
"indentLevel",
")",
";",
"break",
";",
"case",
"'array'",
":",
"return",
"parseArray",
"(",
"tag",
",",
"attrs",
",",
"content",
",",
"indentStr",
",",
"indentLevel",
")",
";",
"break",
";",
"case",
"'object'",
":",
"return",
"parseObject",
"(",
"tag",
",",
"attrs",
",",
"content",
",",
"indentStr",
",",
"indentLevel",
")",
";",
"break",
";",
"default",
":",
"objTypeError",
"(",
"content",
")",
";",
"break",
";",
"}",
"}",
"}"
]
| route object members to appropriate parsing function based on member type | [
"route",
"object",
"members",
"to",
"appropriate",
"parsing",
"function",
"based",
"on",
"member",
"type"
]
| 83d699b126c5c7099ffea1f86ccacf5ec50ee6a9 | https://github.com/tniedbala/jxh/blob/83d699b126c5c7099ffea1f86ccacf5ec50ee6a9/dist/jxh.js#L36-L61 | train |
ugate/releasebot | lib/cmd.js | execCmd | function execCmd(c, gcr) {
return shell.exec(gcr ? c.replace(regexGitCmd, gcr) : c, {
silent : true
});
} | javascript | function execCmd(c, gcr) {
return shell.exec(gcr ? c.replace(regexGitCmd, gcr) : c, {
silent : true
});
} | [
"function",
"execCmd",
"(",
"c",
",",
"gcr",
")",
"{",
"return",
"shell",
".",
"exec",
"(",
"gcr",
"?",
"c",
".",
"replace",
"(",
"regexGitCmd",
",",
"gcr",
")",
":",
"c",
",",
"{",
"silent",
":",
"true",
"}",
")",
";",
"}"
]
| Executes a shell command
@param c
the command to execute
@param gcr
the optional command replacement that will be substituted for the
"git" CLI (when applicable) | [
"Executes",
"a",
"shell",
"command"
]
| 1a2ff42796e77f47f9590992c014fee461aad80b | https://github.com/ugate/releasebot/blob/1a2ff42796e77f47f9590992c014fee461aad80b/lib/cmd.js#L162-L166 | train |
Industryswarm/isnode-mod-data | lib/mongodb/bson/lib/bson/regexp.js | BSONRegExp | function BSONRegExp(pattern, options) {
if (!(this instanceof BSONRegExp)) return new BSONRegExp();
// Execute
this._bsontype = 'BSONRegExp';
this.pattern = pattern || '';
this.options = options || '';
// Validate options
for (var i = 0; i < this.options.length; i++) {
if (
!(
this.options[i] === 'i' ||
this.options[i] === 'm' ||
this.options[i] === 'x' ||
this.options[i] === 'l' ||
this.options[i] === 's' ||
this.options[i] === 'u'
)
) {
throw new Error('the regular expression options [' + this.options[i] + '] is not supported');
}
}
} | javascript | function BSONRegExp(pattern, options) {
if (!(this instanceof BSONRegExp)) return new BSONRegExp();
// Execute
this._bsontype = 'BSONRegExp';
this.pattern = pattern || '';
this.options = options || '';
// Validate options
for (var i = 0; i < this.options.length; i++) {
if (
!(
this.options[i] === 'i' ||
this.options[i] === 'm' ||
this.options[i] === 'x' ||
this.options[i] === 'l' ||
this.options[i] === 's' ||
this.options[i] === 'u'
)
) {
throw new Error('the regular expression options [' + this.options[i] + '] is not supported');
}
}
} | [
"function",
"BSONRegExp",
"(",
"pattern",
",",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"BSONRegExp",
")",
")",
"return",
"new",
"BSONRegExp",
"(",
")",
";",
"this",
".",
"_bsontype",
"=",
"'BSONRegExp'",
";",
"this",
".",
"pattern",
"=",
"pattern",
"||",
"''",
";",
"this",
".",
"options",
"=",
"options",
"||",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"options",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"(",
"this",
".",
"options",
"[",
"i",
"]",
"===",
"'i'",
"||",
"this",
".",
"options",
"[",
"i",
"]",
"===",
"'m'",
"||",
"this",
".",
"options",
"[",
"i",
"]",
"===",
"'x'",
"||",
"this",
".",
"options",
"[",
"i",
"]",
"===",
"'l'",
"||",
"this",
".",
"options",
"[",
"i",
"]",
"===",
"'s'",
"||",
"this",
".",
"options",
"[",
"i",
"]",
"===",
"'u'",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'the regular expression options ['",
"+",
"this",
".",
"options",
"[",
"i",
"]",
"+",
"'] is not supported'",
")",
";",
"}",
"}",
"}"
]
| A class representation of the BSON RegExp type.
@class
@return {BSONRegExp} A MinKey instance | [
"A",
"class",
"representation",
"of",
"the",
"BSON",
"RegExp",
"type",
"."
]
| 5adc639b88a0d72cbeef23a6b5df7f4540745089 | https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/bson/lib/bson/regexp.js#L7-L30 | train |
meisterplayer/js-dev | gulp/watch.js | createWatcher | function createWatcher(inPath, callback) {
if (!inPath) {
throw new Error('Input path argument is required');
}
if (!callback) {
throw new Error('Callback argument is required');
}
return function watcher() {
watch(inPath, callback);
};
} | javascript | function createWatcher(inPath, callback) {
if (!inPath) {
throw new Error('Input path argument is required');
}
if (!callback) {
throw new Error('Callback argument is required');
}
return function watcher() {
watch(inPath, callback);
};
} | [
"function",
"createWatcher",
"(",
"inPath",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"inPath",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Input path argument is required'",
")",
";",
"}",
"if",
"(",
"!",
"callback",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Callback argument is required'",
")",
";",
"}",
"return",
"function",
"watcher",
"(",
")",
"{",
"watch",
"(",
"inPath",
",",
"callback",
")",
";",
"}",
";",
"}"
]
| Higher order function to create gulp function that watches files and calls a callback on changes.
@param {string|string[]} inPath The globs to the files that need to be watched.
@param {function} callback Callback to be called when the watched files change.
@return {function} Function that can be used as a gulp task | [
"Higher",
"order",
"function",
"to",
"create",
"gulp",
"function",
"that",
"watches",
"files",
"and",
"calls",
"a",
"callback",
"on",
"changes",
"."
]
| c2646678c49dcdaa120ba3f24824da52b0c63e31 | https://github.com/meisterplayer/js-dev/blob/c2646678c49dcdaa120ba3f24824da52b0c63e31/gulp/watch.js#L9-L21 | train |
sazze/node-eventsd-server | lib/consumers/amqp.js | stopAll | function stopAll(socket) {
if (_.isEmpty(this.consumers)) {
return;
}
_.forOwn(this.consumers[socket.id].routingKeys, function (consumer, routingKey) {
if (routingKey == '#') {
// this must be done to prevent infinite stop loop
routingKey = '##';
}
this.stopConsume(socket, {routingKey: routingKey});
}.bind(this));
} | javascript | function stopAll(socket) {
if (_.isEmpty(this.consumers)) {
return;
}
_.forOwn(this.consumers[socket.id].routingKeys, function (consumer, routingKey) {
if (routingKey == '#') {
// this must be done to prevent infinite stop loop
routingKey = '##';
}
this.stopConsume(socket, {routingKey: routingKey});
}.bind(this));
} | [
"function",
"stopAll",
"(",
"socket",
")",
"{",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"this",
".",
"consumers",
")",
")",
"{",
"return",
";",
"}",
"_",
".",
"forOwn",
"(",
"this",
".",
"consumers",
"[",
"socket",
".",
"id",
"]",
".",
"routingKeys",
",",
"function",
"(",
"consumer",
",",
"routingKey",
")",
"{",
"if",
"(",
"routingKey",
"==",
"'#'",
")",
"{",
"routingKey",
"=",
"'##'",
";",
"}",
"this",
".",
"stopConsume",
"(",
"socket",
",",
"{",
"routingKey",
":",
"routingKey",
"}",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
]
| Stop all consumers linked to a socket
@param socket | [
"Stop",
"all",
"consumers",
"linked",
"to",
"a",
"socket"
]
| a11ce6d4b3f002dab4c8692743cb6d59ad4b0abb | https://github.com/sazze/node-eventsd-server/blob/a11ce6d4b3f002dab4c8692743cb6d59ad4b0abb/lib/consumers/amqp.js#L136-L149 | train |
activethread/vulpejs | lib/utils/index.js | function(array, property, searchTerm) {
for (var i = 0, len = array.length; i < len; ++i) {
var value = array[i][property];
if (value === searchTerm || value.indexOf(searchTerm) !== -1) {
return i
};
}
return -1;
} | javascript | function(array, property, searchTerm) {
for (var i = 0, len = array.length; i < len; ++i) {
var value = array[i][property];
if (value === searchTerm || value.indexOf(searchTerm) !== -1) {
return i
};
}
return -1;
} | [
"function",
"(",
"array",
",",
"property",
",",
"searchTerm",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"array",
".",
"length",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"var",
"value",
"=",
"array",
"[",
"i",
"]",
"[",
"property",
"]",
";",
"if",
"(",
"value",
"===",
"searchTerm",
"||",
"value",
".",
"indexOf",
"(",
"searchTerm",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"i",
"}",
";",
"}",
"return",
"-",
"1",
";",
"}"
]
| Return index of array on search by term in specific property.
@param {Array} array
@param {String} property
@param {String} searchTerm
@return {Integer} Index | [
"Return",
"index",
"of",
"array",
"on",
"search",
"by",
"term",
"in",
"specific",
"property",
"."
]
| cba9529ebb13892b2c7d07219c7fa69137151fbd | https://github.com/activethread/vulpejs/blob/cba9529ebb13892b2c7d07219c7fa69137151fbd/lib/utils/index.js#L19-L27 | train |
|
antonycourtney/tabli-core | lib/js/components/NewTabPage.js | sendHelperMessage | function sendHelperMessage(msg) {
var port = chrome.runtime.connect({ name: 'popup' });
port.postMessage(msg);
port.onMessage.addListener(function (response) {
console.log('Got response message: ', response);
});
} | javascript | function sendHelperMessage(msg) {
var port = chrome.runtime.connect({ name: 'popup' });
port.postMessage(msg);
port.onMessage.addListener(function (response) {
console.log('Got response message: ', response);
});
} | [
"function",
"sendHelperMessage",
"(",
"msg",
")",
"{",
"var",
"port",
"=",
"chrome",
".",
"runtime",
".",
"connect",
"(",
"{",
"name",
":",
"'popup'",
"}",
")",
";",
"port",
".",
"postMessage",
"(",
"msg",
")",
";",
"port",
".",
"onMessage",
".",
"addListener",
"(",
"function",
"(",
"response",
")",
"{",
"console",
".",
"log",
"(",
"'Got response message: '",
",",
"response",
")",
";",
"}",
")",
";",
"}"
]
| send message to BGhelper | [
"send",
"message",
"to",
"BGhelper"
]
| 76cc540891421bc6c8bdcf00f277ebb6e716fdd9 | https://github.com/antonycourtney/tabli-core/blob/76cc540891421bc6c8bdcf00f277ebb6e716fdd9/lib/js/components/NewTabPage.js#L44-L50 | train |
scottyapp/node-scottyapp-api-client | lib/client.js | Client | function Client(key, secret, scope) {
this.key = key;
this.secret = secret;
this.scope = scope != null ? scope : "read write";
this._request = __bind(this._request, this);
this._delete = __bind(this._delete, this);
this._put = __bind(this._put, this);
this._post = __bind(this._post, this);
this._postAsForm = __bind(this._postAsForm, this);
this._get = __bind(this._get, this);
this.info = __bind(this.info, this);
this.deleteApp = __bind(this.deleteApp, this);
this.updateApp = __bind(this.updateApp, this);
this.app = __bind(this.app, this);
this.createApp = __bind(this.createApp, this);
this.appsForOrganization = __bind(this.appsForOrganization, this);
this.deleteOrganization = __bind(this.deleteOrganization, this);
this.createOrganization = __bind(this.createOrganization, this);
this.updateOrganization = __bind(this.updateOrganization, this);
this.organization = __bind(this.organization, this);
this.organizations = __bind(this.organizations, this);
this.organizationsForUser = __bind(this.organizationsForUser, this);
this.updateUser = __bind(this.updateUser, this);
this.createUser = __bind(this.createUser, this);
this.updateMe = __bind(this.updateMe, this);
this.me = __bind(this.me, this);
this.authenticate = __bind(this.authenticate, this);
this.setAccessToken = __bind(this.setAccessToken, this);
if (!(this.key && this.secret)) {
throw new Error("You need to pass a key and secret");
}
} | javascript | function Client(key, secret, scope) {
this.key = key;
this.secret = secret;
this.scope = scope != null ? scope : "read write";
this._request = __bind(this._request, this);
this._delete = __bind(this._delete, this);
this._put = __bind(this._put, this);
this._post = __bind(this._post, this);
this._postAsForm = __bind(this._postAsForm, this);
this._get = __bind(this._get, this);
this.info = __bind(this.info, this);
this.deleteApp = __bind(this.deleteApp, this);
this.updateApp = __bind(this.updateApp, this);
this.app = __bind(this.app, this);
this.createApp = __bind(this.createApp, this);
this.appsForOrganization = __bind(this.appsForOrganization, this);
this.deleteOrganization = __bind(this.deleteOrganization, this);
this.createOrganization = __bind(this.createOrganization, this);
this.updateOrganization = __bind(this.updateOrganization, this);
this.organization = __bind(this.organization, this);
this.organizations = __bind(this.organizations, this);
this.organizationsForUser = __bind(this.organizationsForUser, this);
this.updateUser = __bind(this.updateUser, this);
this.createUser = __bind(this.createUser, this);
this.updateMe = __bind(this.updateMe, this);
this.me = __bind(this.me, this);
this.authenticate = __bind(this.authenticate, this);
this.setAccessToken = __bind(this.setAccessToken, this);
if (!(this.key && this.secret)) {
throw new Error("You need to pass a key and secret");
}
} | [
"function",
"Client",
"(",
"key",
",",
"secret",
",",
"scope",
")",
"{",
"this",
".",
"key",
"=",
"key",
";",
"this",
".",
"secret",
"=",
"secret",
";",
"this",
".",
"scope",
"=",
"scope",
"!=",
"null",
"?",
"scope",
":",
"\"read write\"",
";",
"this",
".",
"_request",
"=",
"__bind",
"(",
"this",
".",
"_request",
",",
"this",
")",
";",
"this",
".",
"_delete",
"=",
"__bind",
"(",
"this",
".",
"_delete",
",",
"this",
")",
";",
"this",
".",
"_put",
"=",
"__bind",
"(",
"this",
".",
"_put",
",",
"this",
")",
";",
"this",
".",
"_post",
"=",
"__bind",
"(",
"this",
".",
"_post",
",",
"this",
")",
";",
"this",
".",
"_postAsForm",
"=",
"__bind",
"(",
"this",
".",
"_postAsForm",
",",
"this",
")",
";",
"this",
".",
"_get",
"=",
"__bind",
"(",
"this",
".",
"_get",
",",
"this",
")",
";",
"this",
".",
"info",
"=",
"__bind",
"(",
"this",
".",
"info",
",",
"this",
")",
";",
"this",
".",
"deleteApp",
"=",
"__bind",
"(",
"this",
".",
"deleteApp",
",",
"this",
")",
";",
"this",
".",
"updateApp",
"=",
"__bind",
"(",
"this",
".",
"updateApp",
",",
"this",
")",
";",
"this",
".",
"app",
"=",
"__bind",
"(",
"this",
".",
"app",
",",
"this",
")",
";",
"this",
".",
"createApp",
"=",
"__bind",
"(",
"this",
".",
"createApp",
",",
"this",
")",
";",
"this",
".",
"appsForOrganization",
"=",
"__bind",
"(",
"this",
".",
"appsForOrganization",
",",
"this",
")",
";",
"this",
".",
"deleteOrganization",
"=",
"__bind",
"(",
"this",
".",
"deleteOrganization",
",",
"this",
")",
";",
"this",
".",
"createOrganization",
"=",
"__bind",
"(",
"this",
".",
"createOrganization",
",",
"this",
")",
";",
"this",
".",
"updateOrganization",
"=",
"__bind",
"(",
"this",
".",
"updateOrganization",
",",
"this",
")",
";",
"this",
".",
"organization",
"=",
"__bind",
"(",
"this",
".",
"organization",
",",
"this",
")",
";",
"this",
".",
"organizations",
"=",
"__bind",
"(",
"this",
".",
"organizations",
",",
"this",
")",
";",
"this",
".",
"organizationsForUser",
"=",
"__bind",
"(",
"this",
".",
"organizationsForUser",
",",
"this",
")",
";",
"this",
".",
"updateUser",
"=",
"__bind",
"(",
"this",
".",
"updateUser",
",",
"this",
")",
";",
"this",
".",
"createUser",
"=",
"__bind",
"(",
"this",
".",
"createUser",
",",
"this",
")",
";",
"this",
".",
"updateMe",
"=",
"__bind",
"(",
"this",
".",
"updateMe",
",",
"this",
")",
";",
"this",
".",
"me",
"=",
"__bind",
"(",
"this",
".",
"me",
",",
"this",
")",
";",
"this",
".",
"authenticate",
"=",
"__bind",
"(",
"this",
".",
"authenticate",
",",
"this",
")",
";",
"this",
".",
"setAccessToken",
"=",
"__bind",
"(",
"this",
".",
"setAccessToken",
",",
"this",
")",
";",
"if",
"(",
"!",
"(",
"this",
".",
"key",
"&&",
"this",
".",
"secret",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"You need to pass a key and secret\"",
")",
";",
"}",
"}"
]
| Initializes a new instance of @see Client
@param (String) key the api key obtained from scottyapp.com/developers
@param (String) secret the api secret
@param (String) scope defaults to "read write". | [
"Initializes",
"a",
"new",
"instance",
"of"
]
| d63fe1cea2fa1cebcf8ad8332559ba0e86d9886e | https://github.com/scottyapp/node-scottyapp-api-client/blob/d63fe1cea2fa1cebcf8ad8332559ba0e86d9886e/lib/client.js#L21-L52 | train |
tfennelly/jenkins-js-logging | index.js | function (message) {
if (this.isEnabled(Level.LOG)) {
console.log.apply(console, logArgs(Level.LOG, this.category, arguments));
}
} | javascript | function (message) {
if (this.isEnabled(Level.LOG)) {
console.log.apply(console, logArgs(Level.LOG, this.category, arguments));
}
} | [
"function",
"(",
"message",
")",
"{",
"if",
"(",
"this",
".",
"isEnabled",
"(",
"Level",
".",
"LOG",
")",
")",
"{",
"console",
".",
"log",
".",
"apply",
"(",
"console",
",",
"logArgs",
"(",
"Level",
".",
"LOG",
",",
"this",
".",
"category",
",",
"arguments",
")",
")",
";",
"}",
"}"
]
| Log an "log" level message.
@param {...*} message Message arguments. | [
"Log",
"an",
"log",
"level",
"message",
"."
]
| 4bc37157f1b6e001b97f41ce53df301ed8d50df7 | https://github.com/tfennelly/jenkins-js-logging/blob/4bc37157f1b6e001b97f41ce53df301ed8d50df7/index.js#L213-L217 | train |
|
tfennelly/jenkins-js-logging | index.js | function (message) {
if (this.isEnabled(Level.INFO)) {
console.info.apply(console, logArgs(Level.INFO, this.category, arguments));
}
} | javascript | function (message) {
if (this.isEnabled(Level.INFO)) {
console.info.apply(console, logArgs(Level.INFO, this.category, arguments));
}
} | [
"function",
"(",
"message",
")",
"{",
"if",
"(",
"this",
".",
"isEnabled",
"(",
"Level",
".",
"INFO",
")",
")",
"{",
"console",
".",
"info",
".",
"apply",
"(",
"console",
",",
"logArgs",
"(",
"Level",
".",
"INFO",
",",
"this",
".",
"category",
",",
"arguments",
")",
")",
";",
"}",
"}"
]
| Log an info message.
@param {...*} message Message arguments. | [
"Log",
"an",
"info",
"message",
"."
]
| 4bc37157f1b6e001b97f41ce53df301ed8d50df7 | https://github.com/tfennelly/jenkins-js-logging/blob/4bc37157f1b6e001b97f41ce53df301ed8d50df7/index.js#L223-L227 | train |
|
tfennelly/jenkins-js-logging | index.js | function (message) {
if (this.isEnabled(Level.WARN)) {
console.warn.apply(console, logArgs(Level.WARN, this.category, arguments));
}
} | javascript | function (message) {
if (this.isEnabled(Level.WARN)) {
console.warn.apply(console, logArgs(Level.WARN, this.category, arguments));
}
} | [
"function",
"(",
"message",
")",
"{",
"if",
"(",
"this",
".",
"isEnabled",
"(",
"Level",
".",
"WARN",
")",
")",
"{",
"console",
".",
"warn",
".",
"apply",
"(",
"console",
",",
"logArgs",
"(",
"Level",
".",
"WARN",
",",
"this",
".",
"category",
",",
"arguments",
")",
")",
";",
"}",
"}"
]
| Log a warn message.
@param {...*} message Message arguments. | [
"Log",
"a",
"warn",
"message",
"."
]
| 4bc37157f1b6e001b97f41ce53df301ed8d50df7 | https://github.com/tfennelly/jenkins-js-logging/blob/4bc37157f1b6e001b97f41ce53df301ed8d50df7/index.js#L233-L237 | train |
|
acos-server/acos-kelmu | static/kelmu.js | function() {
annotationsDiv.children().remove();
container.find('.kelmu-arrow-handle').remove();
container.children('svg').first().remove();
container.find('audio.kelmu-annotation-sound').each(function() {
try {
this.pause();
} catch (err) {
// Ignore if stopping sounds raised any errors
}
});
} | javascript | function() {
annotationsDiv.children().remove();
container.find('.kelmu-arrow-handle').remove();
container.children('svg').first().remove();
container.find('audio.kelmu-annotation-sound').each(function() {
try {
this.pause();
} catch (err) {
// Ignore if stopping sounds raised any errors
}
});
} | [
"function",
"(",
")",
"{",
"annotationsDiv",
".",
"children",
"(",
")",
".",
"remove",
"(",
")",
";",
"container",
".",
"find",
"(",
"'.kelmu-arrow-handle'",
")",
".",
"remove",
"(",
")",
";",
"container",
".",
"children",
"(",
"'svg'",
")",
".",
"first",
"(",
")",
".",
"remove",
"(",
")",
";",
"container",
".",
"find",
"(",
"'audio.kelmu-annotation-sound'",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"try",
"{",
"this",
".",
"pause",
"(",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"}",
")",
";",
"}"
]
| default value which can be changed by sending animationLength message | [
"default",
"value",
"which",
"can",
"be",
"changed",
"by",
"sending",
"animationLength",
"message"
]
| 71105b5b43027c517a1da99d6cb0a7687fe253b9 | https://github.com/acos-server/acos-kelmu/blob/71105b5b43027c517a1da99d6cb0a7687fe253b9/static/kelmu.js#L71-L82 | train |
|
acos-server/acos-kelmu | static/kelmu.js | function(event) {
event.preventDefault();
if ((window.kelmu.data[id].definitions['step' + window.kelmu.data[id].stepNumber] || [null]).length - 1 === window.kelmu.data[id].subStepNumber) {
// Move to next step
clearAnnotations();
window.kelmu.data[id].stepNumber += 1;
window.kelmu.data[id].subStepNumber = 0;
if (window.kelmu.data[id].actions.updateEditor) {
window.kelmu.data[id].actions.updateEditor(true, true);
}
originalStep(event);
// If the animator is not able to report when the animation is ready,
// create the annotations for the next step after a delay
if (!window.kelmu.data[id].animationReadyAvailable) {
setTimeout(function() {
createAnnotations();
if (window.kelmu.data[id].actions.updateEditor) {
window.kelmu.data[id].actions.updateEditor(true, true);
}
}, window.kelmu.data[id].settings.animationLength);
}
} else {
// Move to next substep
window.kelmu.data[id].subStepNumber += 1;
window.kelmu.data[id].actions.setSubstep(window.kelmu.data[id].subStepNumber);
if (window.kelmu.data[id].actions.updateEditor) {
window.kelmu.data[id].actions.updateEditor(true, true);
}
}
if (window.kelmu.data[id].stepsToRun === 0) {
// Add the current state to the undo stack if there are no more steps to run
window.kelmu.data[id].undoStack.splice(window.kelmu.data[id].undoStackPointer + 1, window.kelmu.data[id].undoStack.length);
window.kelmu.data[id].undoStack.push([window.kelmu.data[id].stepNumber, window.kelmu.data[id].subStepNumber]);
window.kelmu.data[id].undoStackPointer += 1;
}
} | javascript | function(event) {
event.preventDefault();
if ((window.kelmu.data[id].definitions['step' + window.kelmu.data[id].stepNumber] || [null]).length - 1 === window.kelmu.data[id].subStepNumber) {
// Move to next step
clearAnnotations();
window.kelmu.data[id].stepNumber += 1;
window.kelmu.data[id].subStepNumber = 0;
if (window.kelmu.data[id].actions.updateEditor) {
window.kelmu.data[id].actions.updateEditor(true, true);
}
originalStep(event);
// If the animator is not able to report when the animation is ready,
// create the annotations for the next step after a delay
if (!window.kelmu.data[id].animationReadyAvailable) {
setTimeout(function() {
createAnnotations();
if (window.kelmu.data[id].actions.updateEditor) {
window.kelmu.data[id].actions.updateEditor(true, true);
}
}, window.kelmu.data[id].settings.animationLength);
}
} else {
// Move to next substep
window.kelmu.data[id].subStepNumber += 1;
window.kelmu.data[id].actions.setSubstep(window.kelmu.data[id].subStepNumber);
if (window.kelmu.data[id].actions.updateEditor) {
window.kelmu.data[id].actions.updateEditor(true, true);
}
}
if (window.kelmu.data[id].stepsToRun === 0) {
// Add the current state to the undo stack if there are no more steps to run
window.kelmu.data[id].undoStack.splice(window.kelmu.data[id].undoStackPointer + 1, window.kelmu.data[id].undoStack.length);
window.kelmu.data[id].undoStack.push([window.kelmu.data[id].stepNumber, window.kelmu.data[id].subStepNumber]);
window.kelmu.data[id].undoStackPointer += 1;
}
} | [
"function",
"(",
"event",
")",
"{",
"event",
".",
"preventDefault",
"(",
")",
";",
"if",
"(",
"(",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"definitions",
"[",
"'step'",
"+",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"stepNumber",
"]",
"||",
"[",
"null",
"]",
")",
".",
"length",
"-",
"1",
"===",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"subStepNumber",
")",
"{",
"clearAnnotations",
"(",
")",
";",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"stepNumber",
"+=",
"1",
";",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"subStepNumber",
"=",
"0",
";",
"if",
"(",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"actions",
".",
"updateEditor",
")",
"{",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"actions",
".",
"updateEditor",
"(",
"true",
",",
"true",
")",
";",
"}",
"originalStep",
"(",
"event",
")",
";",
"if",
"(",
"!",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"animationReadyAvailable",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"createAnnotations",
"(",
")",
";",
"if",
"(",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"actions",
".",
"updateEditor",
")",
"{",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"actions",
".",
"updateEditor",
"(",
"true",
",",
"true",
")",
";",
"}",
"}",
",",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"settings",
".",
"animationLength",
")",
";",
"}",
"}",
"else",
"{",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"subStepNumber",
"+=",
"1",
";",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"actions",
".",
"setSubstep",
"(",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"subStepNumber",
")",
";",
"if",
"(",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"actions",
".",
"updateEditor",
")",
"{",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"actions",
".",
"updateEditor",
"(",
"true",
",",
"true",
")",
";",
"}",
"}",
"if",
"(",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"stepsToRun",
"===",
"0",
")",
"{",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStack",
".",
"splice",
"(",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStackPointer",
"+",
"1",
",",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStack",
".",
"length",
")",
";",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStack",
".",
"push",
"(",
"[",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"stepNumber",
",",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"subStepNumber",
"]",
")",
";",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStackPointer",
"+=",
"1",
";",
"}",
"}"
]
| Functionality for step button. | [
"Functionality",
"for",
"step",
"button",
"."
]
| 71105b5b43027c517a1da99d6cb0a7687fe253b9 | https://github.com/acos-server/acos-kelmu/blob/71105b5b43027c517a1da99d6cb0a7687fe253b9/static/kelmu.js#L92-L134 | train |
|
acos-server/acos-kelmu | static/kelmu.js | function(event) {
event.preventDefault();
if (window.kelmu.data[id].undoStackPointer < window.kelmu.data[id].undoStack.length - 1) {
var sp = window.kelmu.data[id].undoStackPointer;
if (window.kelmu.data[id].undoStack[sp + 1][0] !== window.kelmu.data[id].stepNumber) {
originalRedo(event);
}
window.kelmu.data[id].undoStackPointer += 1;
sp = window.kelmu.data[id].undoStackPointer;
window.kelmu.data[id].stepNumber = window.kelmu.data[id].undoStack[sp][0];
window.kelmu.data[id].subStepNumber = window.kelmu.data[id].undoStack[sp][1];
createAnnotations();
if (window.kelmu.data[id].actions.updateEditor) {
window.kelmu.data[id].actions.updateEditor(true, true);
}
}
} | javascript | function(event) {
event.preventDefault();
if (window.kelmu.data[id].undoStackPointer < window.kelmu.data[id].undoStack.length - 1) {
var sp = window.kelmu.data[id].undoStackPointer;
if (window.kelmu.data[id].undoStack[sp + 1][0] !== window.kelmu.data[id].stepNumber) {
originalRedo(event);
}
window.kelmu.data[id].undoStackPointer += 1;
sp = window.kelmu.data[id].undoStackPointer;
window.kelmu.data[id].stepNumber = window.kelmu.data[id].undoStack[sp][0];
window.kelmu.data[id].subStepNumber = window.kelmu.data[id].undoStack[sp][1];
createAnnotations();
if (window.kelmu.data[id].actions.updateEditor) {
window.kelmu.data[id].actions.updateEditor(true, true);
}
}
} | [
"function",
"(",
"event",
")",
"{",
"event",
".",
"preventDefault",
"(",
")",
";",
"if",
"(",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStackPointer",
"<",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStack",
".",
"length",
"-",
"1",
")",
"{",
"var",
"sp",
"=",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStackPointer",
";",
"if",
"(",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStack",
"[",
"sp",
"+",
"1",
"]",
"[",
"0",
"]",
"!==",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"stepNumber",
")",
"{",
"originalRedo",
"(",
"event",
")",
";",
"}",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStackPointer",
"+=",
"1",
";",
"sp",
"=",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStackPointer",
";",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"stepNumber",
"=",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStack",
"[",
"sp",
"]",
"[",
"0",
"]",
";",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"subStepNumber",
"=",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStack",
"[",
"sp",
"]",
"[",
"1",
"]",
";",
"createAnnotations",
"(",
")",
";",
"if",
"(",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"actions",
".",
"updateEditor",
")",
"{",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"actions",
".",
"updateEditor",
"(",
"true",
",",
"true",
")",
";",
"}",
"}",
"}"
]
| Functionality for redo button. | [
"Functionality",
"for",
"redo",
"button",
"."
]
| 71105b5b43027c517a1da99d6cb0a7687fe253b9 | https://github.com/acos-server/acos-kelmu/blob/71105b5b43027c517a1da99d6cb0a7687fe253b9/static/kelmu.js#L139-L162 | train |
|
acos-server/acos-kelmu | static/kelmu.js | function(event) {
event.preventDefault();
if (window.kelmu.data[id].undoStack[0][0] !== window.kelmu.data[id].stepNumber) {
originalBegin(event);
}
window.kelmu.data[id].undoStackPointer = 0;
window.kelmu.data[id].stepNumber = 0;
window.kelmu.data[id].subStepNumber = 0;
createAnnotations();
if (window.kelmu.data[id].actions.updateEditor) {
window.kelmu.data[id].actions.updateEditor(true, true);
}
} | javascript | function(event) {
event.preventDefault();
if (window.kelmu.data[id].undoStack[0][0] !== window.kelmu.data[id].stepNumber) {
originalBegin(event);
}
window.kelmu.data[id].undoStackPointer = 0;
window.kelmu.data[id].stepNumber = 0;
window.kelmu.data[id].subStepNumber = 0;
createAnnotations();
if (window.kelmu.data[id].actions.updateEditor) {
window.kelmu.data[id].actions.updateEditor(true, true);
}
} | [
"function",
"(",
"event",
")",
"{",
"event",
".",
"preventDefault",
"(",
")",
";",
"if",
"(",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStack",
"[",
"0",
"]",
"[",
"0",
"]",
"!==",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"stepNumber",
")",
"{",
"originalBegin",
"(",
"event",
")",
";",
"}",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"undoStackPointer",
"=",
"0",
";",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"stepNumber",
"=",
"0",
";",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"subStepNumber",
"=",
"0",
";",
"createAnnotations",
"(",
")",
";",
"if",
"(",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"actions",
".",
"updateEditor",
")",
"{",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
".",
"actions",
".",
"updateEditor",
"(",
"true",
",",
"true",
")",
";",
"}",
"}"
]
| Functionality for begin button. | [
"Functionality",
"for",
"begin",
"button",
"."
]
| 71105b5b43027c517a1da99d6cb0a7687fe253b9 | https://github.com/acos-server/acos-kelmu/blob/71105b5b43027c517a1da99d6cb0a7687fe253b9/static/kelmu.js#L195-L212 | train |
|
acos-server/acos-kelmu | static/kelmu.js | function(event, showAction) {
var data = window.kelmu.data[id];
var count = Math.max(+showAction.parameter || 1, 1);
var action = function() {
forward(event);
};
if (!data.animationReadyAvailable) {
for (var i = 0; i < count; i++) {
setTimeout(action, i * (data.settings.animationLength + 300));
}
} else {
data.stepEvent = event;
data.stepsToRun = count - 1;
if (data.stepsToRun > 0) {
// Notify the animator that we are running multiple steps that should be combined into a single step
window.kelmu.sendMessage(id, 'showSequence');
}
forward(event);
}
} | javascript | function(event, showAction) {
var data = window.kelmu.data[id];
var count = Math.max(+showAction.parameter || 1, 1);
var action = function() {
forward(event);
};
if (!data.animationReadyAvailable) {
for (var i = 0; i < count; i++) {
setTimeout(action, i * (data.settings.animationLength + 300));
}
} else {
data.stepEvent = event;
data.stepsToRun = count - 1;
if (data.stepsToRun > 0) {
// Notify the animator that we are running multiple steps that should be combined into a single step
window.kelmu.sendMessage(id, 'showSequence');
}
forward(event);
}
} | [
"function",
"(",
"event",
",",
"showAction",
")",
"{",
"var",
"data",
"=",
"window",
".",
"kelmu",
".",
"data",
"[",
"id",
"]",
";",
"var",
"count",
"=",
"Math",
".",
"max",
"(",
"+",
"showAction",
".",
"parameter",
"||",
"1",
",",
"1",
")",
";",
"var",
"action",
"=",
"function",
"(",
")",
"{",
"forward",
"(",
"event",
")",
";",
"}",
";",
"if",
"(",
"!",
"data",
".",
"animationReadyAvailable",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"count",
";",
"i",
"++",
")",
"{",
"setTimeout",
"(",
"action",
",",
"i",
"*",
"(",
"data",
".",
"settings",
".",
"animationLength",
"+",
"300",
")",
")",
";",
"}",
"}",
"else",
"{",
"data",
".",
"stepEvent",
"=",
"event",
";",
"data",
".",
"stepsToRun",
"=",
"count",
"-",
"1",
";",
"if",
"(",
"data",
".",
"stepsToRun",
">",
"0",
")",
"{",
"window",
".",
"kelmu",
".",
"sendMessage",
"(",
"id",
",",
"'showSequence'",
")",
";",
"}",
"forward",
"(",
"event",
")",
";",
"}",
"}"
]
| Functionality for the `show` action. | [
"Functionality",
"for",
"the",
"show",
"action",
"."
]
| 71105b5b43027c517a1da99d6cb0a7687fe253b9 | https://github.com/acos-server/acos-kelmu/blob/71105b5b43027c517a1da99d6cb0a7687fe253b9/static/kelmu.js#L217-L240 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.