id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
50,700
|
Xotic750/util-x
|
lib/util-x.js
|
throwIfIsPrimitive
|
function throwIfIsPrimitive(inputArg) {
var type = typeof inputArg;
if (type === 'undefined' || inputArg === null || type === 'boolean' || type === 'string' || type === 'number') {
throw new CTypeError('called on non-object: ' + typeof inputArg);
}
return inputArg;
}
|
javascript
|
function throwIfIsPrimitive(inputArg) {
var type = typeof inputArg;
if (type === 'undefined' || inputArg === null || type === 'boolean' || type === 'string' || type === 'number') {
throw new CTypeError('called on non-object: ' + typeof inputArg);
}
return inputArg;
}
|
[
"function",
"throwIfIsPrimitive",
"(",
"inputArg",
")",
"{",
"var",
"type",
"=",
"typeof",
"inputArg",
";",
"if",
"(",
"type",
"===",
"'undefined'",
"||",
"inputArg",
"===",
"null",
"||",
"type",
"===",
"'boolean'",
"||",
"type",
"===",
"'string'",
"||",
"type",
"===",
"'number'",
")",
"{",
"throw",
"new",
"CTypeError",
"(",
"'called on non-object: '",
"+",
"typeof",
"inputArg",
")",
";",
"}",
"return",
"inputArg",
";",
"}"
] |
Throws a TypeError if the operand inputArg is not an object or not a function,
otherise returns the object.
@private
@function throwIfIsPrimitive
@param {*} inputArg
@throws {TypeError} if inputArg is not an object or a function.
@returns {(Object|Function)}
|
[
"Throws",
"a",
"TypeError",
"if",
"the",
"operand",
"inputArg",
"is",
"not",
"an",
"object",
"or",
"not",
"a",
"function",
"otherise",
"returns",
"the",
"object",
"."
] |
13b6a5ba6555f71c2b64032bdfdab8cfb8497aee
|
https://github.com/Xotic750/util-x/blob/13b6a5ba6555f71c2b64032bdfdab8cfb8497aee/lib/util-x.js#L2271-L2279
|
50,701
|
Xotic750/util-x
|
lib/util-x.js
|
isFunctionBasic
|
function isFunctionBasic(inputArg) {
var isFn = toClass(inputArg) === classFunction,
type;
if (!isFn && inputArg !== null) {
type = typeof inputArg;
if ((type === 'function' || type === 'object') &&
('constructor' in inputArg) &&
('call' in inputArg) &&
('apply' in inputArg) &&
('length' in inputArg) &&
typeof inputArg.length === 'number') {
isFn = true;
}
}
return isFn;
}
|
javascript
|
function isFunctionBasic(inputArg) {
var isFn = toClass(inputArg) === classFunction,
type;
if (!isFn && inputArg !== null) {
type = typeof inputArg;
if ((type === 'function' || type === 'object') &&
('constructor' in inputArg) &&
('call' in inputArg) &&
('apply' in inputArg) &&
('length' in inputArg) &&
typeof inputArg.length === 'number') {
isFn = true;
}
}
return isFn;
}
|
[
"function",
"isFunctionBasic",
"(",
"inputArg",
")",
"{",
"var",
"isFn",
"=",
"toClass",
"(",
"inputArg",
")",
"===",
"classFunction",
",",
"type",
";",
"if",
"(",
"!",
"isFn",
"&&",
"inputArg",
"!==",
"null",
")",
"{",
"type",
"=",
"typeof",
"inputArg",
";",
"if",
"(",
"(",
"type",
"===",
"'function'",
"||",
"type",
"===",
"'object'",
")",
"&&",
"(",
"'constructor'",
"in",
"inputArg",
")",
"&&",
"(",
"'call'",
"in",
"inputArg",
")",
"&&",
"(",
"'apply'",
"in",
"inputArg",
")",
"&&",
"(",
"'length'",
"in",
"inputArg",
")",
"&&",
"typeof",
"inputArg",
".",
"length",
"===",
"'number'",
")",
"{",
"isFn",
"=",
"true",
";",
"}",
"}",
"return",
"isFn",
";",
"}"
] |
Returns true if the operand inputArg is a Function. Used by Function.isFunction.
@private
@function isFunctionBasic
@param {*} inputArg
@returns {boolean}
|
[
"Returns",
"true",
"if",
"the",
"operand",
"inputArg",
"is",
"a",
"Function",
".",
"Used",
"by",
"Function",
".",
"isFunction",
"."
] |
13b6a5ba6555f71c2b64032bdfdab8cfb8497aee
|
https://github.com/Xotic750/util-x/blob/13b6a5ba6555f71c2b64032bdfdab8cfb8497aee/lib/util-x.js#L2928-L2946
|
50,702
|
Xotic750/util-x
|
lib/util-x.js
|
copyRegExp
|
function copyRegExp(regExpArg, options) {
var flags;
if (!isPlainObject(options)) {
options = {};
}
// Get native flags in use
flags = onlyCoercibleToString(pExec.call(getNativeFlags, $toString(regExpArg))[1]);
if (options.add) {
flags = pReplace.call(flags + options.add, clipDups, '');
}
if (options.remove) {
// Would need to escape `options.remove` if this was public
flags = pReplace.call(flags, new CRegExp('[' + options.remove + ']+', 'g'), '');
}
return new CRegExp(regExpArg.source, flags);
}
|
javascript
|
function copyRegExp(regExpArg, options) {
var flags;
if (!isPlainObject(options)) {
options = {};
}
// Get native flags in use
flags = onlyCoercibleToString(pExec.call(getNativeFlags, $toString(regExpArg))[1]);
if (options.add) {
flags = pReplace.call(flags + options.add, clipDups, '');
}
if (options.remove) {
// Would need to escape `options.remove` if this was public
flags = pReplace.call(flags, new CRegExp('[' + options.remove + ']+', 'g'), '');
}
return new CRegExp(regExpArg.source, flags);
}
|
[
"function",
"copyRegExp",
"(",
"regExpArg",
",",
"options",
")",
"{",
"var",
"flags",
";",
"if",
"(",
"!",
"isPlainObject",
"(",
"options",
")",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"// Get native flags in use",
"flags",
"=",
"onlyCoercibleToString",
"(",
"pExec",
".",
"call",
"(",
"getNativeFlags",
",",
"$toString",
"(",
"regExpArg",
")",
")",
"[",
"1",
"]",
")",
";",
"if",
"(",
"options",
".",
"add",
")",
"{",
"flags",
"=",
"pReplace",
".",
"call",
"(",
"flags",
"+",
"options",
".",
"add",
",",
"clipDups",
",",
"''",
")",
";",
"}",
"if",
"(",
"options",
".",
"remove",
")",
"{",
"// Would need to escape `options.remove` if this was public",
"flags",
"=",
"pReplace",
".",
"call",
"(",
"flags",
",",
"new",
"CRegExp",
"(",
"'['",
"+",
"options",
".",
"remove",
"+",
"']+'",
",",
"'g'",
")",
",",
"''",
")",
";",
"}",
"return",
"new",
"CRegExp",
"(",
"regExpArg",
".",
"source",
",",
"flags",
")",
";",
"}"
] |
Copies a regex object. Allows adding and removing native flags while copying the regex.
@private
@function copyRegExp
@param {RegExp} regex Regex to copy.
@param {Object} [options] Allows specifying native flags to add or remove while copying the regex.
@returns {RegExp} Copy of the provided regex, possibly with modified flags.
|
[
"Copies",
"a",
"regex",
"object",
".",
"Allows",
"adding",
"and",
"removing",
"native",
"flags",
"while",
"copying",
"the",
"regex",
"."
] |
13b6a5ba6555f71c2b64032bdfdab8cfb8497aee
|
https://github.com/Xotic750/util-x/blob/13b6a5ba6555f71c2b64032bdfdab8cfb8497aee/lib/util-x.js#L4210-L4229
|
50,703
|
Xotic750/util-x
|
lib/util-x.js
|
stringRepeatRep
|
function stringRepeatRep(s, times) {
var half,
val;
if (times < 1) {
val = '';
} else if (times % 2) {
val = stringRepeatRep(s, times - 1) + s;
} else {
half = stringRepeatRep(s, times / 2);
val = half + half;
}
return val;
}
|
javascript
|
function stringRepeatRep(s, times) {
var half,
val;
if (times < 1) {
val = '';
} else if (times % 2) {
val = stringRepeatRep(s, times - 1) + s;
} else {
half = stringRepeatRep(s, times / 2);
val = half + half;
}
return val;
}
|
[
"function",
"stringRepeatRep",
"(",
"s",
",",
"times",
")",
"{",
"var",
"half",
",",
"val",
";",
"if",
"(",
"times",
"<",
"1",
")",
"{",
"val",
"=",
"''",
";",
"}",
"else",
"if",
"(",
"times",
"%",
"2",
")",
"{",
"val",
"=",
"stringRepeatRep",
"(",
"s",
",",
"times",
"-",
"1",
")",
"+",
"s",
";",
"}",
"else",
"{",
"half",
"=",
"stringRepeatRep",
"(",
"s",
",",
"times",
"/",
"2",
")",
";",
"val",
"=",
"half",
"+",
"half",
";",
"}",
"return",
"val",
";",
"}"
] |
Repeat the current string several times, return the new string. Used by String.repeat
@private
@function stringRepeatRep
@param {string} s
@param {number} times
@returns {string}
|
[
"Repeat",
"the",
"current",
"string",
"several",
"times",
"return",
"the",
"new",
"string",
".",
"Used",
"by",
"String",
".",
"repeat"
] |
13b6a5ba6555f71c2b64032bdfdab8cfb8497aee
|
https://github.com/Xotic750/util-x/blob/13b6a5ba6555f71c2b64032bdfdab8cfb8497aee/lib/util-x.js#L4767-L4781
|
50,704
|
Xotic750/util-x
|
lib/util-x.js
|
checkV8StrictBug
|
function checkV8StrictBug(fn) {
var hasV8StrictBug = false;
if (isStrictMode) {
fn.call([1], function () {
hasV8StrictBug = this !== null && typeof this === 'object';
}, 'foo');
}
return hasV8StrictBug;
}
|
javascript
|
function checkV8StrictBug(fn) {
var hasV8StrictBug = false;
if (isStrictMode) {
fn.call([1], function () {
hasV8StrictBug = this !== null && typeof this === 'object';
}, 'foo');
}
return hasV8StrictBug;
}
|
[
"function",
"checkV8StrictBug",
"(",
"fn",
")",
"{",
"var",
"hasV8StrictBug",
"=",
"false",
";",
"if",
"(",
"isStrictMode",
")",
"{",
"fn",
".",
"call",
"(",
"[",
"1",
"]",
",",
"function",
"(",
")",
"{",
"hasV8StrictBug",
"=",
"this",
"!==",
"null",
"&&",
"typeof",
"this",
"===",
"'object'",
";",
"}",
",",
"'foo'",
")",
";",
"}",
"return",
"hasV8StrictBug",
";",
"}"
] |
Checks if the supplied function suffers from the V8 strict mode bug.
@private
@function checkV8StrictBug
@param {Function} fn
@returns {boolean}
|
[
"Checks",
"if",
"the",
"supplied",
"function",
"suffers",
"from",
"the",
"V8",
"strict",
"mode",
"bug",
"."
] |
13b6a5ba6555f71c2b64032bdfdab8cfb8497aee
|
https://github.com/Xotic750/util-x/blob/13b6a5ba6555f71c2b64032bdfdab8cfb8497aee/lib/util-x.js#L5352-L5362
|
50,705
|
Xotic750/util-x
|
lib/util-x.js
|
defaultComparison
|
function defaultComparison(left, right) {
var leftS = $toString(left),
rightS = $toString(right),
val = 1;
if (leftS === rightS) {
val = +0;
} else if (leftS < rightS) {
val = -1;
}
return val;
}
|
javascript
|
function defaultComparison(left, right) {
var leftS = $toString(left),
rightS = $toString(right),
val = 1;
if (leftS === rightS) {
val = +0;
} else if (leftS < rightS) {
val = -1;
}
return val;
}
|
[
"function",
"defaultComparison",
"(",
"left",
",",
"right",
")",
"{",
"var",
"leftS",
"=",
"$toString",
"(",
"left",
")",
",",
"rightS",
"=",
"$toString",
"(",
"right",
")",
",",
"val",
"=",
"1",
";",
"if",
"(",
"leftS",
"===",
"rightS",
")",
"{",
"val",
"=",
"+",
"0",
";",
"}",
"else",
"if",
"(",
"leftS",
"<",
"rightS",
")",
"{",
"val",
"=",
"-",
"1",
";",
"}",
"return",
"val",
";",
"}"
] |
Default compare function for stableSort.
@private
@function defaultComparison
@param {*} left
@param {*} right
@returns {number}
|
[
"Default",
"compare",
"function",
"for",
"stableSort",
"."
] |
13b6a5ba6555f71c2b64032bdfdab8cfb8497aee
|
https://github.com/Xotic750/util-x/blob/13b6a5ba6555f71c2b64032bdfdab8cfb8497aee/lib/util-x.js#L6125-L6137
|
50,706
|
Xotic750/util-x
|
lib/util-x.js
|
sortCompare
|
function sortCompare(left, right) {
var hasj = $hasOwn(left, 0),
hask = $hasOwn(right, 0),
typex,
typey,
val;
if (!hasj && !hask) {
val = +0;
} else if (!hasj) {
val = 1;
} else if (!hask) {
val = -1;
} else {
typex = typeof left[0];
typey = typeof right[0];
if (typex === 'undefined' && typey === 'undefined') {
val = +0;
} else if (typex === 'undefined') {
val = 1;
} else if (typey === 'undefined') {
val = -1;
}
}
return val;
}
|
javascript
|
function sortCompare(left, right) {
var hasj = $hasOwn(left, 0),
hask = $hasOwn(right, 0),
typex,
typey,
val;
if (!hasj && !hask) {
val = +0;
} else if (!hasj) {
val = 1;
} else if (!hask) {
val = -1;
} else {
typex = typeof left[0];
typey = typeof right[0];
if (typex === 'undefined' && typey === 'undefined') {
val = +0;
} else if (typex === 'undefined') {
val = 1;
} else if (typey === 'undefined') {
val = -1;
}
}
return val;
}
|
[
"function",
"sortCompare",
"(",
"left",
",",
"right",
")",
"{",
"var",
"hasj",
"=",
"$hasOwn",
"(",
"left",
",",
"0",
")",
",",
"hask",
"=",
"$hasOwn",
"(",
"right",
",",
"0",
")",
",",
"typex",
",",
"typey",
",",
"val",
";",
"if",
"(",
"!",
"hasj",
"&&",
"!",
"hask",
")",
"{",
"val",
"=",
"+",
"0",
";",
"}",
"else",
"if",
"(",
"!",
"hasj",
")",
"{",
"val",
"=",
"1",
";",
"}",
"else",
"if",
"(",
"!",
"hask",
")",
"{",
"val",
"=",
"-",
"1",
";",
"}",
"else",
"{",
"typex",
"=",
"typeof",
"left",
"[",
"0",
"]",
";",
"typey",
"=",
"typeof",
"right",
"[",
"0",
"]",
";",
"if",
"(",
"typex",
"===",
"'undefined'",
"&&",
"typey",
"===",
"'undefined'",
")",
"{",
"val",
"=",
"+",
"0",
";",
"}",
"else",
"if",
"(",
"typex",
"===",
"'undefined'",
")",
"{",
"val",
"=",
"1",
";",
"}",
"else",
"if",
"(",
"typey",
"===",
"'undefined'",
")",
"{",
"val",
"=",
"-",
"1",
";",
"}",
"}",
"return",
"val",
";",
"}"
] |
sortCompare function for stableSort.
@private
@function sortCompare
@param {*} object
@param {*} left
@param {*} right
@returns {number}
|
[
"sortCompare",
"function",
"for",
"stableSort",
"."
] |
13b6a5ba6555f71c2b64032bdfdab8cfb8497aee
|
https://github.com/Xotic750/util-x/blob/13b6a5ba6555f71c2b64032bdfdab8cfb8497aee/lib/util-x.js#L6148-L6174
|
50,707
|
Xotic750/util-x
|
lib/util-x.js
|
merge
|
function merge(left, right, comparison) {
var result = [],
next = 0,
sComp;
result.length = left.length + right.length;
while (left.length && right.length) {
sComp = sortCompare(left, right);
if (typeof sComp !== 'number') {
if (comparison(left[0], right[0]) <= 0) {
if ($hasOwn(left, 0)) {
result[next] = left[0];
}
pShift.call(left);
} else {
if ($hasOwn(right, 0)) {
result[next] = right[0];
}
pShift.call(right);
}
} else if (sComp <= 0) {
if ($hasOwn(left, 0)) {
result[next] = left[0];
}
pShift.call(left);
} else {
if ($hasOwn(right, 0)) {
result[next] = right[0];
}
pShift.call(right);
}
next += 1;
}
while (left.length) {
if ($hasOwn(left, 0)) {
result[next] = left[0];
}
pShift.call(left);
next += 1;
}
while (right.length) {
if ($hasOwn(right, 0)) {
result[next] = right[0];
}
pShift.call(right);
next += 1;
}
return result;
}
|
javascript
|
function merge(left, right, comparison) {
var result = [],
next = 0,
sComp;
result.length = left.length + right.length;
while (left.length && right.length) {
sComp = sortCompare(left, right);
if (typeof sComp !== 'number') {
if (comparison(left[0], right[0]) <= 0) {
if ($hasOwn(left, 0)) {
result[next] = left[0];
}
pShift.call(left);
} else {
if ($hasOwn(right, 0)) {
result[next] = right[0];
}
pShift.call(right);
}
} else if (sComp <= 0) {
if ($hasOwn(left, 0)) {
result[next] = left[0];
}
pShift.call(left);
} else {
if ($hasOwn(right, 0)) {
result[next] = right[0];
}
pShift.call(right);
}
next += 1;
}
while (left.length) {
if ($hasOwn(left, 0)) {
result[next] = left[0];
}
pShift.call(left);
next += 1;
}
while (right.length) {
if ($hasOwn(right, 0)) {
result[next] = right[0];
}
pShift.call(right);
next += 1;
}
return result;
}
|
[
"function",
"merge",
"(",
"left",
",",
"right",
",",
"comparison",
")",
"{",
"var",
"result",
"=",
"[",
"]",
",",
"next",
"=",
"0",
",",
"sComp",
";",
"result",
".",
"length",
"=",
"left",
".",
"length",
"+",
"right",
".",
"length",
";",
"while",
"(",
"left",
".",
"length",
"&&",
"right",
".",
"length",
")",
"{",
"sComp",
"=",
"sortCompare",
"(",
"left",
",",
"right",
")",
";",
"if",
"(",
"typeof",
"sComp",
"!==",
"'number'",
")",
"{",
"if",
"(",
"comparison",
"(",
"left",
"[",
"0",
"]",
",",
"right",
"[",
"0",
"]",
")",
"<=",
"0",
")",
"{",
"if",
"(",
"$hasOwn",
"(",
"left",
",",
"0",
")",
")",
"{",
"result",
"[",
"next",
"]",
"=",
"left",
"[",
"0",
"]",
";",
"}",
"pShift",
".",
"call",
"(",
"left",
")",
";",
"}",
"else",
"{",
"if",
"(",
"$hasOwn",
"(",
"right",
",",
"0",
")",
")",
"{",
"result",
"[",
"next",
"]",
"=",
"right",
"[",
"0",
"]",
";",
"}",
"pShift",
".",
"call",
"(",
"right",
")",
";",
"}",
"}",
"else",
"if",
"(",
"sComp",
"<=",
"0",
")",
"{",
"if",
"(",
"$hasOwn",
"(",
"left",
",",
"0",
")",
")",
"{",
"result",
"[",
"next",
"]",
"=",
"left",
"[",
"0",
"]",
";",
"}",
"pShift",
".",
"call",
"(",
"left",
")",
";",
"}",
"else",
"{",
"if",
"(",
"$hasOwn",
"(",
"right",
",",
"0",
")",
")",
"{",
"result",
"[",
"next",
"]",
"=",
"right",
"[",
"0",
"]",
";",
"}",
"pShift",
".",
"call",
"(",
"right",
")",
";",
"}",
"next",
"+=",
"1",
";",
"}",
"while",
"(",
"left",
".",
"length",
")",
"{",
"if",
"(",
"$hasOwn",
"(",
"left",
",",
"0",
")",
")",
"{",
"result",
"[",
"next",
"]",
"=",
"left",
"[",
"0",
"]",
";",
"}",
"pShift",
".",
"call",
"(",
"left",
")",
";",
"next",
"+=",
"1",
";",
"}",
"while",
"(",
"right",
".",
"length",
")",
"{",
"if",
"(",
"$hasOwn",
"(",
"right",
",",
"0",
")",
")",
"{",
"result",
"[",
"next",
"]",
"=",
"right",
"[",
"0",
"]",
";",
"}",
"pShift",
".",
"call",
"(",
"right",
")",
";",
"next",
"+=",
"1",
";",
"}",
"return",
"result",
";",
"}"
] |
merge function for stableSort.
@private
@function merge
@param {ArrayLike} left
@param {ArrayLike} right
@param {Function} comparison
@returns {Array}
|
[
"merge",
"function",
"for",
"stableSort",
"."
] |
13b6a5ba6555f71c2b64032bdfdab8cfb8497aee
|
https://github.com/Xotic750/util-x/blob/13b6a5ba6555f71c2b64032bdfdab8cfb8497aee/lib/util-x.js#L6185-L6243
|
50,708
|
Xotic750/util-x
|
lib/util-x.js
|
mergeSort
|
function mergeSort(array, comparefn) {
var length = array.length,
middle,
front,
back,
val;
if (length < 2) {
val = $slice(array);
} else {
middle = ceil(length / 2);
front = $slice(array, 0, middle);
back = $slice(array, middle);
val = merge(mergeSort(front, comparefn), mergeSort(back, comparefn), comparefn);
}
return val;
}
|
javascript
|
function mergeSort(array, comparefn) {
var length = array.length,
middle,
front,
back,
val;
if (length < 2) {
val = $slice(array);
} else {
middle = ceil(length / 2);
front = $slice(array, 0, middle);
back = $slice(array, middle);
val = merge(mergeSort(front, comparefn), mergeSort(back, comparefn), comparefn);
}
return val;
}
|
[
"function",
"mergeSort",
"(",
"array",
",",
"comparefn",
")",
"{",
"var",
"length",
"=",
"array",
".",
"length",
",",
"middle",
",",
"front",
",",
"back",
",",
"val",
";",
"if",
"(",
"length",
"<",
"2",
")",
"{",
"val",
"=",
"$slice",
"(",
"array",
")",
";",
"}",
"else",
"{",
"middle",
"=",
"ceil",
"(",
"length",
"/",
"2",
")",
";",
"front",
"=",
"$slice",
"(",
"array",
",",
"0",
",",
"middle",
")",
";",
"back",
"=",
"$slice",
"(",
"array",
",",
"middle",
")",
";",
"val",
"=",
"merge",
"(",
"mergeSort",
"(",
"front",
",",
"comparefn",
")",
",",
"mergeSort",
"(",
"back",
",",
"comparefn",
")",
",",
"comparefn",
")",
";",
"}",
"return",
"val",
";",
"}"
] |
mergeSort function for stableSort.
@private
@function mergeSort
@param {ArrayLike} array
@param {Function} comparefn
@returns {Array}
|
[
"mergeSort",
"function",
"for",
"stableSort",
"."
] |
13b6a5ba6555f71c2b64032bdfdab8cfb8497aee
|
https://github.com/Xotic750/util-x/blob/13b6a5ba6555f71c2b64032bdfdab8cfb8497aee/lib/util-x.js#L6253-L6270
|
50,709
|
ubenzer/metalsmith-rho
|
lib/index.js
|
plugin
|
function plugin(options) {
options = normalize(options);
return function(files, metalsmith, done) {
var tbConvertedFiles = _.filter(Object.keys(files), function(file) {
return minimatch(file, options.match);
});
var convertFns = _.map(tbConvertedFiles, function(file) {
debug("Asyncly converting file %s", file);
var data = files[file];
return function(cb) {
var NormalizedRho = null;
if (_.isPlainObject(options.blockCompiler)) {
NormalizedRho = options.blockCompiler;
} else if (_.isFunction(options.blockCompiler)) {
NormalizedRho = options.blockCompiler(files, file, data);
} else {
NormalizedRho = require("rho").BlockCompiler;
}
var html = (new NormalizedRho()).toHtml(data.contents.toString());
data.contents = new Buffer(html);
cb(null, html);
};
});
async.parallel(convertFns, function(err) {
if (err) {
debug("A file failed to compile: %s", err);
done(new Error());
}
_.forEach(tbConvertedFiles, function(file) {
var contents = files[file];
var extension = path.extname(file);
var fileNameWoExt = path.basename(file, extension);
var dirname = path.dirname(file);
var renamedFile = path.join(dirname, fileNameWoExt + "." + options.extension);
files[renamedFile] = contents;
delete files[file];
});
done();
});
};
}
|
javascript
|
function plugin(options) {
options = normalize(options);
return function(files, metalsmith, done) {
var tbConvertedFiles = _.filter(Object.keys(files), function(file) {
return minimatch(file, options.match);
});
var convertFns = _.map(tbConvertedFiles, function(file) {
debug("Asyncly converting file %s", file);
var data = files[file];
return function(cb) {
var NormalizedRho = null;
if (_.isPlainObject(options.blockCompiler)) {
NormalizedRho = options.blockCompiler;
} else if (_.isFunction(options.blockCompiler)) {
NormalizedRho = options.blockCompiler(files, file, data);
} else {
NormalizedRho = require("rho").BlockCompiler;
}
var html = (new NormalizedRho()).toHtml(data.contents.toString());
data.contents = new Buffer(html);
cb(null, html);
};
});
async.parallel(convertFns, function(err) {
if (err) {
debug("A file failed to compile: %s", err);
done(new Error());
}
_.forEach(tbConvertedFiles, function(file) {
var contents = files[file];
var extension = path.extname(file);
var fileNameWoExt = path.basename(file, extension);
var dirname = path.dirname(file);
var renamedFile = path.join(dirname, fileNameWoExt + "." + options.extension);
files[renamedFile] = contents;
delete files[file];
});
done();
});
};
}
|
[
"function",
"plugin",
"(",
"options",
")",
"{",
"options",
"=",
"normalize",
"(",
"options",
")",
";",
"return",
"function",
"(",
"files",
",",
"metalsmith",
",",
"done",
")",
"{",
"var",
"tbConvertedFiles",
"=",
"_",
".",
"filter",
"(",
"Object",
".",
"keys",
"(",
"files",
")",
",",
"function",
"(",
"file",
")",
"{",
"return",
"minimatch",
"(",
"file",
",",
"options",
".",
"match",
")",
";",
"}",
")",
";",
"var",
"convertFns",
"=",
"_",
".",
"map",
"(",
"tbConvertedFiles",
",",
"function",
"(",
"file",
")",
"{",
"debug",
"(",
"\"Asyncly converting file %s\"",
",",
"file",
")",
";",
"var",
"data",
"=",
"files",
"[",
"file",
"]",
";",
"return",
"function",
"(",
"cb",
")",
"{",
"var",
"NormalizedRho",
"=",
"null",
";",
"if",
"(",
"_",
".",
"isPlainObject",
"(",
"options",
".",
"blockCompiler",
")",
")",
"{",
"NormalizedRho",
"=",
"options",
".",
"blockCompiler",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isFunction",
"(",
"options",
".",
"blockCompiler",
")",
")",
"{",
"NormalizedRho",
"=",
"options",
".",
"blockCompiler",
"(",
"files",
",",
"file",
",",
"data",
")",
";",
"}",
"else",
"{",
"NormalizedRho",
"=",
"require",
"(",
"\"rho\"",
")",
".",
"BlockCompiler",
";",
"}",
"var",
"html",
"=",
"(",
"new",
"NormalizedRho",
"(",
")",
")",
".",
"toHtml",
"(",
"data",
".",
"contents",
".",
"toString",
"(",
")",
")",
";",
"data",
".",
"contents",
"=",
"new",
"Buffer",
"(",
"html",
")",
";",
"cb",
"(",
"null",
",",
"html",
")",
";",
"}",
";",
"}",
")",
";",
"async",
".",
"parallel",
"(",
"convertFns",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"\"A file failed to compile: %s\"",
",",
"err",
")",
";",
"done",
"(",
"new",
"Error",
"(",
")",
")",
";",
"}",
"_",
".",
"forEach",
"(",
"tbConvertedFiles",
",",
"function",
"(",
"file",
")",
"{",
"var",
"contents",
"=",
"files",
"[",
"file",
"]",
";",
"var",
"extension",
"=",
"path",
".",
"extname",
"(",
"file",
")",
";",
"var",
"fileNameWoExt",
"=",
"path",
".",
"basename",
"(",
"file",
",",
"extension",
")",
";",
"var",
"dirname",
"=",
"path",
".",
"dirname",
"(",
"file",
")",
";",
"var",
"renamedFile",
"=",
"path",
".",
"join",
"(",
"dirname",
",",
"fileNameWoExt",
"+",
"\".\"",
"+",
"options",
".",
"extension",
")",
";",
"files",
"[",
"renamedFile",
"]",
"=",
"contents",
";",
"delete",
"files",
"[",
"file",
"]",
";",
"}",
")",
";",
"done",
"(",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] |
Metalsmith plugin that renders rho files to HTML.
@param {Object} options
@return {Function}
|
[
"Metalsmith",
"plugin",
"that",
"renders",
"rho",
"files",
"to",
"HTML",
"."
] |
74703b8be2a8a051d4ac3c97caf7e78411dcf9d8
|
https://github.com/ubenzer/metalsmith-rho/blob/74703b8be2a8a051d4ac3c97caf7e78411dcf9d8/lib/index.js#L14-L61
|
50,710
|
noderaider/contextual
|
lib/theme/palettes/invert.js
|
invertPalette
|
function invertPalette(palette) {
return _extends({}, palette, { base03: palette.base3,
base02: palette.base2,
base01: palette.base1,
base00: palette.base0,
base0: palette.base00,
base1: palette.base01,
base2: palette.base02,
base3: palette.base03
});
}
|
javascript
|
function invertPalette(palette) {
return _extends({}, palette, { base03: palette.base3,
base02: palette.base2,
base01: palette.base1,
base00: palette.base0,
base0: palette.base00,
base1: palette.base01,
base2: palette.base02,
base3: palette.base03
});
}
|
[
"function",
"invertPalette",
"(",
"palette",
")",
"{",
"return",
"_extends",
"(",
"{",
"}",
",",
"palette",
",",
"{",
"base03",
":",
"palette",
".",
"base3",
",",
"base02",
":",
"palette",
".",
"base2",
",",
"base01",
":",
"palette",
".",
"base1",
",",
"base00",
":",
"palette",
".",
"base0",
",",
"base0",
":",
"palette",
".",
"base00",
",",
"base1",
":",
"palette",
".",
"base01",
",",
"base2",
":",
"palette",
".",
"base02",
",",
"base3",
":",
"palette",
".",
"base03",
"}",
")",
";",
"}"
] |
Inverts solarized style palette.
|
[
"Inverts",
"solarized",
"style",
"palette",
"."
] |
e3b8e12975eb3611483cf0adb4f9e7a388d12039
|
https://github.com/noderaider/contextual/blob/e3b8e12975eb3611483cf0adb4f9e7a388d12039/lib/theme/palettes/invert.js#L11-L21
|
50,711
|
danielhusar/grunt-file-replace
|
tasks/fileReplace.js
|
function(url, dest, cb) {
var get = request(url);
get.on('response', function (res) {
res.pipe(fs.createWriteStream(dest));
res.on('end', function () {
cb();
});
res.on('error', function (err) {
cb(err);
});
});
}
|
javascript
|
function(url, dest, cb) {
var get = request(url);
get.on('response', function (res) {
res.pipe(fs.createWriteStream(dest));
res.on('end', function () {
cb();
});
res.on('error', function (err) {
cb(err);
});
});
}
|
[
"function",
"(",
"url",
",",
"dest",
",",
"cb",
")",
"{",
"var",
"get",
"=",
"request",
"(",
"url",
")",
";",
"get",
".",
"on",
"(",
"'response'",
",",
"function",
"(",
"res",
")",
"{",
"res",
".",
"pipe",
"(",
"fs",
".",
"createWriteStream",
"(",
"dest",
")",
")",
";",
"res",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"cb",
"(",
")",
";",
"}",
")",
";",
"res",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Copy remote file to local hardrive
@param {string} url url of the remote file
@param {string} dest destination where to copy file
@param {Function} cb callback when file is copied
@return {void}
|
[
"Copy",
"remote",
"file",
"to",
"local",
"hardrive"
] |
bdbc0b428dddee6956fc9b09864133b3927a1c44
|
https://github.com/danielhusar/grunt-file-replace/blob/bdbc0b428dddee6956fc9b09864133b3927a1c44/tasks/fileReplace.js#L60-L71
|
|
50,712
|
Digznav/bilberry
|
changelog.js
|
changelog
|
function changelog(tagsList, prevTag, repoUrl, repoName) {
const writeLogFiles = [];
let logIndex;
let logDetailed;
let logContent;
let link;
let prevTagHolder = prevTag;
Object.keys(tagsList).forEach(majorVersion => {
logIndex = [];
logDetailed = [];
logContent = [
`\n# ${repoName} ${majorVersion} ChangeLog\n`,
`All changes commited to this repository will be documented in this file. It adheres to [Semantic Versioning](http://semver.org/).\n`,
'<details>',
`<summary>List of tags released on the ${majorVersion} range</summary>\n`
];
tagsList[majorVersion].forEach(info => {
link = `${info.tag}-${info.date}`;
logIndex.push(`- [${info.tag}](#${link.replace(/\./g, '')})`);
logDetailed.push(
`\n## [${info.tag}](${repoUrl}/tree/${info.tag}), ${info.date}\n` +
`- [Release notes](${repoUrl}/releases/tag/${info.tag})\n` +
`- [Full changelog](${repoUrl}/compare/${prevTagHolder}...${info.tag})\n`
);
prevTagHolder = info.tag;
});
logContent.push(logIndex.reverse().join('\n'), '\n</details>\n\n', logDetailed.reverse().join('\n'));
writeLogFiles.push(promiseWriteFile(`changelog/CHANGELOG-${majorVersion.toUpperCase()}.md`, logContent.join('\n')));
});
return Promise.all(writeLogFiles);
}
|
javascript
|
function changelog(tagsList, prevTag, repoUrl, repoName) {
const writeLogFiles = [];
let logIndex;
let logDetailed;
let logContent;
let link;
let prevTagHolder = prevTag;
Object.keys(tagsList).forEach(majorVersion => {
logIndex = [];
logDetailed = [];
logContent = [
`\n# ${repoName} ${majorVersion} ChangeLog\n`,
`All changes commited to this repository will be documented in this file. It adheres to [Semantic Versioning](http://semver.org/).\n`,
'<details>',
`<summary>List of tags released on the ${majorVersion} range</summary>\n`
];
tagsList[majorVersion].forEach(info => {
link = `${info.tag}-${info.date}`;
logIndex.push(`- [${info.tag}](#${link.replace(/\./g, '')})`);
logDetailed.push(
`\n## [${info.tag}](${repoUrl}/tree/${info.tag}), ${info.date}\n` +
`- [Release notes](${repoUrl}/releases/tag/${info.tag})\n` +
`- [Full changelog](${repoUrl}/compare/${prevTagHolder}...${info.tag})\n`
);
prevTagHolder = info.tag;
});
logContent.push(logIndex.reverse().join('\n'), '\n</details>\n\n', logDetailed.reverse().join('\n'));
writeLogFiles.push(promiseWriteFile(`changelog/CHANGELOG-${majorVersion.toUpperCase()}.md`, logContent.join('\n')));
});
return Promise.all(writeLogFiles);
}
|
[
"function",
"changelog",
"(",
"tagsList",
",",
"prevTag",
",",
"repoUrl",
",",
"repoName",
")",
"{",
"const",
"writeLogFiles",
"=",
"[",
"]",
";",
"let",
"logIndex",
";",
"let",
"logDetailed",
";",
"let",
"logContent",
";",
"let",
"link",
";",
"let",
"prevTagHolder",
"=",
"prevTag",
";",
"Object",
".",
"keys",
"(",
"tagsList",
")",
".",
"forEach",
"(",
"majorVersion",
"=>",
"{",
"logIndex",
"=",
"[",
"]",
";",
"logDetailed",
"=",
"[",
"]",
";",
"logContent",
"=",
"[",
"`",
"\\n",
"${",
"repoName",
"}",
"${",
"majorVersion",
"}",
"\\n",
"`",
",",
"`",
"\\n",
"`",
",",
"'<details>'",
",",
"`",
"${",
"majorVersion",
"}",
"\\n",
"`",
"]",
";",
"tagsList",
"[",
"majorVersion",
"]",
".",
"forEach",
"(",
"info",
"=>",
"{",
"link",
"=",
"`",
"${",
"info",
".",
"tag",
"}",
"${",
"info",
".",
"date",
"}",
"`",
";",
"logIndex",
".",
"push",
"(",
"`",
"${",
"info",
".",
"tag",
"}",
"${",
"link",
".",
"replace",
"(",
"/",
"\\.",
"/",
"g",
",",
"''",
")",
"}",
"`",
")",
";",
"logDetailed",
".",
"push",
"(",
"`",
"\\n",
"${",
"info",
".",
"tag",
"}",
"${",
"repoUrl",
"}",
"${",
"info",
".",
"tag",
"}",
"${",
"info",
".",
"date",
"}",
"\\n",
"`",
"+",
"`",
"${",
"repoUrl",
"}",
"${",
"info",
".",
"tag",
"}",
"\\n",
"`",
"+",
"`",
"${",
"repoUrl",
"}",
"${",
"prevTagHolder",
"}",
"${",
"info",
".",
"tag",
"}",
"\\n",
"`",
")",
";",
"prevTagHolder",
"=",
"info",
".",
"tag",
";",
"}",
")",
";",
"logContent",
".",
"push",
"(",
"logIndex",
".",
"reverse",
"(",
")",
".",
"join",
"(",
"'\\n'",
")",
",",
"'\\n</details>\\n\\n'",
",",
"logDetailed",
".",
"reverse",
"(",
")",
".",
"join",
"(",
"'\\n'",
")",
")",
";",
"writeLogFiles",
".",
"push",
"(",
"promiseWriteFile",
"(",
"`",
"${",
"majorVersion",
".",
"toUpperCase",
"(",
")",
"}",
"`",
",",
"logContent",
".",
"join",
"(",
"'\\n'",
")",
")",
")",
";",
"}",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"writeLogFiles",
")",
";",
"}"
] |
Create Changelog files.
@param {object} tagsList Tags info.
@param {string} prevTag Previous tag to compare with.
@param {string} repoUrl URL of the repository.
@param {string} repoName Name of the repository.
@return {promise} A promise to do it.
|
[
"Create",
"Changelog",
"files",
"."
] |
ef6db49de6c8b0d2f4f9d3e10e8a8153e39ffcc4
|
https://github.com/Digznav/bilberry/blob/ef6db49de6c8b0d2f4f9d3e10e8a8153e39ffcc4/changelog.js#L11-L48
|
50,713
|
redisjs/jsr-client
|
lib/client.js
|
Client
|
function Client(socket, options) {
options = options || {};
// hook up subcommand nested properties
var cmd, sub, method;
for(cmd in SubCommand) {
// we have defined the cluster slots subcommand
// but the cluster command is not returned in the
// command list, ignore this for the moment
if(!this[cmd]) continue;
// must re-define the command method
// so it is not shared across client instances
method = this[cmd] = this[cmd].bind(this);
function subcommand(cmd, sub) {
var args = [].slice.call(arguments, 1), cb;
if(typeof args[args.length - 1] === 'function') {
cb = args.pop();
}
this.execute(cmd, args, cb);
return this;
}
for(sub in SubCommand[cmd]) {
method[sub] = subcommand.bind(this, cmd, sub);
}
}
this.socket = socket;
this.socket.on('connect', this._connect.bind(this));
this.socket.on('data', this._data.bind(this));
this.socket.on('error', this._error.bind(this));
this.socket.on('close', this._close.bind(this));
this.tcp = (this.socket instanceof Socket);
// using a tcp socket connection
if(this.tcp) {
this.encoder = new Encoder(
{return_buffers: options.buffers});
this.encoder.pipe(this.socket);
this.decoder = new Decoder(
{
simple: options.simple,
return_buffers: options.buffers,
raw: options.raw
});
this.decoder.on('reply', this._reply.bind(this))
}
}
|
javascript
|
function Client(socket, options) {
options = options || {};
// hook up subcommand nested properties
var cmd, sub, method;
for(cmd in SubCommand) {
// we have defined the cluster slots subcommand
// but the cluster command is not returned in the
// command list, ignore this for the moment
if(!this[cmd]) continue;
// must re-define the command method
// so it is not shared across client instances
method = this[cmd] = this[cmd].bind(this);
function subcommand(cmd, sub) {
var args = [].slice.call(arguments, 1), cb;
if(typeof args[args.length - 1] === 'function') {
cb = args.pop();
}
this.execute(cmd, args, cb);
return this;
}
for(sub in SubCommand[cmd]) {
method[sub] = subcommand.bind(this, cmd, sub);
}
}
this.socket = socket;
this.socket.on('connect', this._connect.bind(this));
this.socket.on('data', this._data.bind(this));
this.socket.on('error', this._error.bind(this));
this.socket.on('close', this._close.bind(this));
this.tcp = (this.socket instanceof Socket);
// using a tcp socket connection
if(this.tcp) {
this.encoder = new Encoder(
{return_buffers: options.buffers});
this.encoder.pipe(this.socket);
this.decoder = new Decoder(
{
simple: options.simple,
return_buffers: options.buffers,
raw: options.raw
});
this.decoder.on('reply', this._reply.bind(this))
}
}
|
[
"function",
"Client",
"(",
"socket",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"// hook up subcommand nested properties",
"var",
"cmd",
",",
"sub",
",",
"method",
";",
"for",
"(",
"cmd",
"in",
"SubCommand",
")",
"{",
"// we have defined the cluster slots subcommand",
"// but the cluster command is not returned in the",
"// command list, ignore this for the moment",
"if",
"(",
"!",
"this",
"[",
"cmd",
"]",
")",
"continue",
";",
"// must re-define the command method",
"// so it is not shared across client instances",
"method",
"=",
"this",
"[",
"cmd",
"]",
"=",
"this",
"[",
"cmd",
"]",
".",
"bind",
"(",
"this",
")",
";",
"function",
"subcommand",
"(",
"cmd",
",",
"sub",
")",
"{",
"var",
"args",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
",",
"cb",
";",
"if",
"(",
"typeof",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
"===",
"'function'",
")",
"{",
"cb",
"=",
"args",
".",
"pop",
"(",
")",
";",
"}",
"this",
".",
"execute",
"(",
"cmd",
",",
"args",
",",
"cb",
")",
";",
"return",
"this",
";",
"}",
"for",
"(",
"sub",
"in",
"SubCommand",
"[",
"cmd",
"]",
")",
"{",
"method",
"[",
"sub",
"]",
"=",
"subcommand",
".",
"bind",
"(",
"this",
",",
"cmd",
",",
"sub",
")",
";",
"}",
"}",
"this",
".",
"socket",
"=",
"socket",
";",
"this",
".",
"socket",
".",
"on",
"(",
"'connect'",
",",
"this",
".",
"_connect",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"socket",
".",
"on",
"(",
"'data'",
",",
"this",
".",
"_data",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"socket",
".",
"on",
"(",
"'error'",
",",
"this",
".",
"_error",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"socket",
".",
"on",
"(",
"'close'",
",",
"this",
".",
"_close",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"tcp",
"=",
"(",
"this",
".",
"socket",
"instanceof",
"Socket",
")",
";",
"// using a tcp socket connection",
"if",
"(",
"this",
".",
"tcp",
")",
"{",
"this",
".",
"encoder",
"=",
"new",
"Encoder",
"(",
"{",
"return_buffers",
":",
"options",
".",
"buffers",
"}",
")",
";",
"this",
".",
"encoder",
".",
"pipe",
"(",
"this",
".",
"socket",
")",
";",
"this",
".",
"decoder",
"=",
"new",
"Decoder",
"(",
"{",
"simple",
":",
"options",
".",
"simple",
",",
"return_buffers",
":",
"options",
".",
"buffers",
",",
"raw",
":",
"options",
".",
"raw",
"}",
")",
";",
"this",
".",
"decoder",
".",
"on",
"(",
"'reply'",
",",
"this",
".",
"_reply",
".",
"bind",
"(",
"this",
")",
")",
"}",
"}"
] |
Represents a redis client connection.
@param socket The underlying socket.
@param options Client connection options.
|
[
"Represents",
"a",
"redis",
"client",
"connection",
"."
] |
be90dd5c062e4efb38d5b7f91d3ad9f43174cb3b
|
https://github.com/redisjs/jsr-client/blob/be90dd5c062e4efb38d5b7f91d3ad9f43174cb3b/lib/client.js#L21-L71
|
50,714
|
redisjs/jsr-client
|
lib/client.js
|
execute
|
function execute(cmd, args, cb) {
if(typeof args === 'function') {
cb = args;
args = null;
}
var arr = [cmd].concat(args || []);
if(typeof cb === 'function') {
this.once('reply', cb);
}
// sending over tcp
if(this.tcp) {
this.encoder.write(arr);
// connected to a server within this process
}else{
this.socket.write(arr);
}
}
|
javascript
|
function execute(cmd, args, cb) {
if(typeof args === 'function') {
cb = args;
args = null;
}
var arr = [cmd].concat(args || []);
if(typeof cb === 'function') {
this.once('reply', cb);
}
// sending over tcp
if(this.tcp) {
this.encoder.write(arr);
// connected to a server within this process
}else{
this.socket.write(arr);
}
}
|
[
"function",
"execute",
"(",
"cmd",
",",
"args",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"args",
"===",
"'function'",
")",
"{",
"cb",
"=",
"args",
";",
"args",
"=",
"null",
";",
"}",
"var",
"arr",
"=",
"[",
"cmd",
"]",
".",
"concat",
"(",
"args",
"||",
"[",
"]",
")",
";",
"if",
"(",
"typeof",
"cb",
"===",
"'function'",
")",
"{",
"this",
".",
"once",
"(",
"'reply'",
",",
"cb",
")",
";",
"}",
"// sending over tcp",
"if",
"(",
"this",
".",
"tcp",
")",
"{",
"this",
".",
"encoder",
".",
"write",
"(",
"arr",
")",
";",
"// connected to a server within this process",
"}",
"else",
"{",
"this",
".",
"socket",
".",
"write",
"(",
"arr",
")",
";",
"}",
"}"
] |
Execute a named command with arguments.
|
[
"Execute",
"a",
"named",
"command",
"with",
"arguments",
"."
] |
be90dd5c062e4efb38d5b7f91d3ad9f43174cb3b
|
https://github.com/redisjs/jsr-client/blob/be90dd5c062e4efb38d5b7f91d3ad9f43174cb3b/lib/client.js#L102-L119
|
50,715
|
redisjs/jsr-client
|
lib/client.js
|
multi
|
function multi(cb) {
// not chainable with a callback
if(typeof cb === 'function') {
return this.execute(Constants.MAP.multi.name, [], cb);
}
// chainable instance
return new Multi(this);
}
|
javascript
|
function multi(cb) {
// not chainable with a callback
if(typeof cb === 'function') {
return this.execute(Constants.MAP.multi.name, [], cb);
}
// chainable instance
return new Multi(this);
}
|
[
"function",
"multi",
"(",
"cb",
")",
"{",
"// not chainable with a callback",
"if",
"(",
"typeof",
"cb",
"===",
"'function'",
")",
"{",
"return",
"this",
".",
"execute",
"(",
"Constants",
".",
"MAP",
".",
"multi",
".",
"name",
",",
"[",
"]",
",",
"cb",
")",
";",
"}",
"// chainable instance",
"return",
"new",
"Multi",
"(",
"this",
")",
";",
"}"
] |
Get a chainable multi command builder.
|
[
"Get",
"a",
"chainable",
"multi",
"command",
"builder",
"."
] |
be90dd5c062e4efb38d5b7f91d3ad9f43174cb3b
|
https://github.com/redisjs/jsr-client/blob/be90dd5c062e4efb38d5b7f91d3ad9f43174cb3b/lib/client.js#L124-L132
|
50,716
|
redisjs/jsr-client
|
lib/client.js
|
_data
|
function _data(data) {
if(this.tcp) {
this.decoder.write(data);
// connected to an in-process server,
// emit the reply from the server socket
}else{
if(data instanceof Error) {
this.emit('reply', data, null);
}else{
this.emit('reply', null, data);
}
}
}
|
javascript
|
function _data(data) {
if(this.tcp) {
this.decoder.write(data);
// connected to an in-process server,
// emit the reply from the server socket
}else{
if(data instanceof Error) {
this.emit('reply', data, null);
}else{
this.emit('reply', null, data);
}
}
}
|
[
"function",
"_data",
"(",
"data",
")",
"{",
"if",
"(",
"this",
".",
"tcp",
")",
"{",
"this",
".",
"decoder",
".",
"write",
"(",
"data",
")",
";",
"// connected to an in-process server,",
"// emit the reply from the server socket",
"}",
"else",
"{",
"if",
"(",
"data",
"instanceof",
"Error",
")",
"{",
"this",
".",
"emit",
"(",
"'reply'",
",",
"data",
",",
"null",
")",
";",
"}",
"else",
"{",
"this",
".",
"emit",
"(",
"'reply'",
",",
"null",
",",
"data",
")",
";",
"}",
"}",
"}"
] |
Listener for the socket data event.
|
[
"Listener",
"for",
"the",
"socket",
"data",
"event",
"."
] |
be90dd5c062e4efb38d5b7f91d3ad9f43174cb3b
|
https://github.com/redisjs/jsr-client/blob/be90dd5c062e4efb38d5b7f91d3ad9f43174cb3b/lib/client.js#L156-L168
|
50,717
|
redisjs/jsr-client
|
lib/client.js
|
create
|
function create(sock, options) {
var socket;
if(!sock) {
sock = {port: PORT, host: HOST};
}
if(typeof sock.createConnection === 'function') {
socket = sock.createConnection();
}else{
socket = net.createConnection(sock);
}
return new Client(socket, options);
}
|
javascript
|
function create(sock, options) {
var socket;
if(!sock) {
sock = {port: PORT, host: HOST};
}
if(typeof sock.createConnection === 'function') {
socket = sock.createConnection();
}else{
socket = net.createConnection(sock);
}
return new Client(socket, options);
}
|
[
"function",
"create",
"(",
"sock",
",",
"options",
")",
"{",
"var",
"socket",
";",
"if",
"(",
"!",
"sock",
")",
"{",
"sock",
"=",
"{",
"port",
":",
"PORT",
",",
"host",
":",
"HOST",
"}",
";",
"}",
"if",
"(",
"typeof",
"sock",
".",
"createConnection",
"===",
"'function'",
")",
"{",
"socket",
"=",
"sock",
".",
"createConnection",
"(",
")",
";",
"}",
"else",
"{",
"socket",
"=",
"net",
".",
"createConnection",
"(",
"sock",
")",
";",
"}",
"return",
"new",
"Client",
"(",
"socket",
",",
"options",
")",
";",
"}"
] |
Create a new client.
When the first argument is a server reference
createConnection() is called on the server which returns
an object that mimics the socket event handling.
@param sock Options for the underlying TCP socket or
a server reference.
@param options Client connection options.
|
[
"Create",
"a",
"new",
"client",
"."
] |
be90dd5c062e4efb38d5b7f91d3ad9f43174cb3b
|
https://github.com/redisjs/jsr-client/blob/be90dd5c062e4efb38d5b7f91d3ad9f43174cb3b/lib/client.js#L224-L235
|
50,718
|
360fy/expressjs-boilerplate
|
src/server/ApiRequestHandler.js
|
buildRoutes
|
function buildRoutes(router, apiOrBuilder) {
// if it's a builder function, build it...
let pathPrefix = null;
let api = null;
let registry = null;
let instanceName = null;
if (_.isObject(apiOrBuilder)) {
pathPrefix = apiOrBuilder.path;
api = apiOrBuilder.api;
registry = apiOrBuilder.registry;
instanceName = apiOrBuilder.instanceName;
} else {
api = apiOrBuilder;
}
if (_.isFunction(api)) {
api = api();
}
if (!registry && _.isFunction(api.registry)) {
registry = api.registry();
}
if (!registry) {
// print errors here
return;
}
_.forEach(registry, (value, key) => {
if (_.isArray(value)) {
_.forEach(value, item => buildRoute(router, api, key, item, pathPrefix, instanceName));
} else {
buildRoute(router, api, key, value, pathPrefix, instanceName);
}
});
}
|
javascript
|
function buildRoutes(router, apiOrBuilder) {
// if it's a builder function, build it...
let pathPrefix = null;
let api = null;
let registry = null;
let instanceName = null;
if (_.isObject(apiOrBuilder)) {
pathPrefix = apiOrBuilder.path;
api = apiOrBuilder.api;
registry = apiOrBuilder.registry;
instanceName = apiOrBuilder.instanceName;
} else {
api = apiOrBuilder;
}
if (_.isFunction(api)) {
api = api();
}
if (!registry && _.isFunction(api.registry)) {
registry = api.registry();
}
if (!registry) {
// print errors here
return;
}
_.forEach(registry, (value, key) => {
if (_.isArray(value)) {
_.forEach(value, item => buildRoute(router, api, key, item, pathPrefix, instanceName));
} else {
buildRoute(router, api, key, value, pathPrefix, instanceName);
}
});
}
|
[
"function",
"buildRoutes",
"(",
"router",
",",
"apiOrBuilder",
")",
"{",
"// if it's a builder function, build it...",
"let",
"pathPrefix",
"=",
"null",
";",
"let",
"api",
"=",
"null",
";",
"let",
"registry",
"=",
"null",
";",
"let",
"instanceName",
"=",
"null",
";",
"if",
"(",
"_",
".",
"isObject",
"(",
"apiOrBuilder",
")",
")",
"{",
"pathPrefix",
"=",
"apiOrBuilder",
".",
"path",
";",
"api",
"=",
"apiOrBuilder",
".",
"api",
";",
"registry",
"=",
"apiOrBuilder",
".",
"registry",
";",
"instanceName",
"=",
"apiOrBuilder",
".",
"instanceName",
";",
"}",
"else",
"{",
"api",
"=",
"apiOrBuilder",
";",
"}",
"if",
"(",
"_",
".",
"isFunction",
"(",
"api",
")",
")",
"{",
"api",
"=",
"api",
"(",
")",
";",
"}",
"if",
"(",
"!",
"registry",
"&&",
"_",
".",
"isFunction",
"(",
"api",
".",
"registry",
")",
")",
"{",
"registry",
"=",
"api",
".",
"registry",
"(",
")",
";",
"}",
"if",
"(",
"!",
"registry",
")",
"{",
"// print errors here",
"return",
";",
"}",
"_",
".",
"forEach",
"(",
"registry",
",",
"(",
"value",
",",
"key",
")",
"=>",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"_",
".",
"forEach",
"(",
"value",
",",
"item",
"=>",
"buildRoute",
"(",
"router",
",",
"api",
",",
"key",
",",
"item",
",",
"pathPrefix",
",",
"instanceName",
")",
")",
";",
"}",
"else",
"{",
"buildRoute",
"(",
"router",
",",
"api",
",",
"key",
",",
"value",
",",
"pathPrefix",
",",
"instanceName",
")",
";",
"}",
"}",
")",
";",
"}"
] |
should build a catch all route for pathPrefix ??
|
[
"should",
"build",
"a",
"catch",
"all",
"route",
"for",
"pathPrefix",
"??"
] |
1953048bca726d2dbab6a44fedb8c0846c12f0b5
|
https://github.com/360fy/expressjs-boilerplate/blob/1953048bca726d2dbab6a44fedb8c0846c12f0b5/src/server/ApiRequestHandler.js#L122-L157
|
50,719
|
feedhenry/fh-mbaas-middleware
|
lib/util/responseTranslator.js
|
mapMongoAlertsToResponseObj
|
function mapMongoAlertsToResponseObj(alerts){
// Base response, regardless of whether we have alerts or not
var res = {"list":[],"status":"ok"};
// Filter and add alerts to response if we have them
if (alerts){
res.list = _.map(alerts, function(alert){
var al = alert.toJSON();
al.guid = alert._id;
al.enabled = alert.alertEnabled;
return al;
});
}
// Return the response
return res;
}
|
javascript
|
function mapMongoAlertsToResponseObj(alerts){
// Base response, regardless of whether we have alerts or not
var res = {"list":[],"status":"ok"};
// Filter and add alerts to response if we have them
if (alerts){
res.list = _.map(alerts, function(alert){
var al = alert.toJSON();
al.guid = alert._id;
al.enabled = alert.alertEnabled;
return al;
});
}
// Return the response
return res;
}
|
[
"function",
"mapMongoAlertsToResponseObj",
"(",
"alerts",
")",
"{",
"// Base response, regardless of whether we have alerts or not",
"var",
"res",
"=",
"{",
"\"list\"",
":",
"[",
"]",
",",
"\"status\"",
":",
"\"ok\"",
"}",
";",
"// Filter and add alerts to response if we have them",
"if",
"(",
"alerts",
")",
"{",
"res",
".",
"list",
"=",
"_",
".",
"map",
"(",
"alerts",
",",
"function",
"(",
"alert",
")",
"{",
"var",
"al",
"=",
"alert",
".",
"toJSON",
"(",
")",
";",
"al",
".",
"guid",
"=",
"alert",
".",
"_id",
";",
"al",
".",
"enabled",
"=",
"alert",
".",
"alertEnabled",
";",
"return",
"al",
";",
"}",
")",
";",
"}",
"// Return the response",
"return",
"res",
";",
"}"
] |
Alerts from Mongo should not be coupled to response format
Map query result Alerts to single response object as it is defined
@param alerts
@returns {{}}
|
[
"Alerts",
"from",
"Mongo",
"should",
"not",
"be",
"coupled",
"to",
"response",
"format",
"Map",
"query",
"result",
"Alerts",
"to",
"single",
"response",
"object",
"as",
"it",
"is",
"defined"
] |
f906e98efbb4b0963bf5137b34b5e0589ba24e69
|
https://github.com/feedhenry/fh-mbaas-middleware/blob/f906e98efbb4b0963bf5137b34b5e0589ba24e69/lib/util/responseTranslator.js#L9-L25
|
50,720
|
feedhenry/fh-mbaas-middleware
|
lib/util/responseTranslator.js
|
mapMongoNotificationsToResponseObj
|
function mapMongoNotificationsToResponseObj(notifications){
// Base response, regardless of whether we have alerts or not
var res = {"list":[],"status":"ok"};
// Filter and add alerts to response if we have them
if (notifications){
res.list = _.map(notifications, function(notification){
return notification.toJSON();
});
}
// Return the response
return res;
}
|
javascript
|
function mapMongoNotificationsToResponseObj(notifications){
// Base response, regardless of whether we have alerts or not
var res = {"list":[],"status":"ok"};
// Filter and add alerts to response if we have them
if (notifications){
res.list = _.map(notifications, function(notification){
return notification.toJSON();
});
}
// Return the response
return res;
}
|
[
"function",
"mapMongoNotificationsToResponseObj",
"(",
"notifications",
")",
"{",
"// Base response, regardless of whether we have alerts or not",
"var",
"res",
"=",
"{",
"\"list\"",
":",
"[",
"]",
",",
"\"status\"",
":",
"\"ok\"",
"}",
";",
"// Filter and add alerts to response if we have them",
"if",
"(",
"notifications",
")",
"{",
"res",
".",
"list",
"=",
"_",
".",
"map",
"(",
"notifications",
",",
"function",
"(",
"notification",
")",
"{",
"return",
"notification",
".",
"toJSON",
"(",
")",
";",
"}",
")",
";",
"}",
"// Return the response",
"return",
"res",
";",
"}"
] |
Notifications from Mongo should not be coupled to response format
Map query result Notifications to single response object as it is defined
@param alerts
@returns {{}}
|
[
"Notifications",
"from",
"Mongo",
"should",
"not",
"be",
"coupled",
"to",
"response",
"format",
"Map",
"query",
"result",
"Notifications",
"to",
"single",
"response",
"object",
"as",
"it",
"is",
"defined"
] |
f906e98efbb4b0963bf5137b34b5e0589ba24e69
|
https://github.com/feedhenry/fh-mbaas-middleware/blob/f906e98efbb4b0963bf5137b34b5e0589ba24e69/lib/util/responseTranslator.js#L33-L46
|
50,721
|
feedhenry/fh-mbaas-middleware
|
lib/util/responseTranslator.js
|
mapMongoEventsToResponseObj
|
function mapMongoEventsToResponseObj(events){
// Base response, regardless of whether we have alerts or not
var res = {"list":[],"status":"ok"};
// Filter and add alerts to response if we have them
if (events){
res.list = _.map(events, function(event){
var ev = event.toJSON();
ev.message = event.details ? event.details.message || " " : " ";
ev.category = event.eventClass;
ev.severity = event.eventLevel;
ev.guid = event._id;
ev.eventDetails = ev.details ||{};
return ev;
});
}
// Return the response
return res;
}
|
javascript
|
function mapMongoEventsToResponseObj(events){
// Base response, regardless of whether we have alerts or not
var res = {"list":[],"status":"ok"};
// Filter and add alerts to response if we have them
if (events){
res.list = _.map(events, function(event){
var ev = event.toJSON();
ev.message = event.details ? event.details.message || " " : " ";
ev.category = event.eventClass;
ev.severity = event.eventLevel;
ev.guid = event._id;
ev.eventDetails = ev.details ||{};
return ev;
});
}
// Return the response
return res;
}
|
[
"function",
"mapMongoEventsToResponseObj",
"(",
"events",
")",
"{",
"// Base response, regardless of whether we have alerts or not",
"var",
"res",
"=",
"{",
"\"list\"",
":",
"[",
"]",
",",
"\"status\"",
":",
"\"ok\"",
"}",
";",
"// Filter and add alerts to response if we have them",
"if",
"(",
"events",
")",
"{",
"res",
".",
"list",
"=",
"_",
".",
"map",
"(",
"events",
",",
"function",
"(",
"event",
")",
"{",
"var",
"ev",
"=",
"event",
".",
"toJSON",
"(",
")",
";",
"ev",
".",
"message",
"=",
"event",
".",
"details",
"?",
"event",
".",
"details",
".",
"message",
"||",
"\" \"",
":",
"\" \"",
";",
"ev",
".",
"category",
"=",
"event",
".",
"eventClass",
";",
"ev",
".",
"severity",
"=",
"event",
".",
"eventLevel",
";",
"ev",
".",
"guid",
"=",
"event",
".",
"_id",
";",
"ev",
".",
"eventDetails",
"=",
"ev",
".",
"details",
"||",
"{",
"}",
";",
"return",
"ev",
";",
"}",
")",
";",
"}",
"// Return the response",
"return",
"res",
";",
"}"
] |
Events from Mongo should not be coupled to response format
Map query result Events to single response object as it is defined
@param alerts
@returns {{}}
|
[
"Events",
"from",
"Mongo",
"should",
"not",
"be",
"coupled",
"to",
"response",
"format",
"Map",
"query",
"result",
"Events",
"to",
"single",
"response",
"object",
"as",
"it",
"is",
"defined"
] |
f906e98efbb4b0963bf5137b34b5e0589ba24e69
|
https://github.com/feedhenry/fh-mbaas-middleware/blob/f906e98efbb4b0963bf5137b34b5e0589ba24e69/lib/util/responseTranslator.js#L54-L74
|
50,722
|
Crafity/crafity-webserver
|
lib/fileserver.js
|
createListener
|
function createListener(virtualPath) {
return function listener(req, res, next) {
var paths = allPaths[virtualPath].slice();
function processRequest(paths) {
var physicalPath = paths.pop()
, synchronizer = new Synchronizer()
, uri = urlParser.parse(req.url).pathname
, filename = "";
if (virtualPath !== "/" && uri.indexOf(virtualPath) === 0) {
uri = uri.substr(virtualPath.length, uri.length - virtualPath.length);
}
uri = (physicalPath || "") + uri;
filename = fs.combine(process.cwd(), uri).replace(/\%20/gmi, ' ');
if (cache[filename]) {
console.log("\u001b[32mLoaded from Cache '" + filename + "\u001b[39m'");
if (cache[filename] === 404) {
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("Content not found");
res.end();
} else {
if (req.headers["If-Modified-Since"] === cache[filename].since) {
res.writeHead(304, {
'Content-Type': mime.lookup(filename),
'Last-Modified': cache[filename].since,
//'If-Modified-Since': cache[filename].since,
"Cache-Control": "max-age=31536000"
});
res.end();
} else {
res.writeHead(200, {
'Content-Type': mime.lookup(filename),
//'If-Modified-Since': cache[filename].since,
'Last-Modified': cache[filename].since,
"Cache-Control": "max-age=31536000"
});
res.write(cache[filename].data, "binary");
res.end();
}
}
return;
}
if (filename) {
fs.readFile(filename, "binary", synchronizer.register("file"));
}
synchronizer.onfinish(function (err, data) {
if (err) {
if (paths.length > 0) {
processRequest(paths);
} else if (next) {
next();
} else {
console.log("\u001b[31mStatic file not found '" + filename + "'\u001b[39m");
cache[filename] = 404;
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("Content not found");
res.end();
}
return;
}
console.error("\u001b[31mLoaded static file '" + filename + "'\u001b[39m");
cache[filename] = {
data: data.file,
since: new Date().toGMTString()
};
res.writeHead(200, {
'Content-Type': mime.lookup(filename),
//'If-Modified-Since': cache[filename].since,
'Last-Modified': cache[filename].since,
"Cache-Control": "max-age=31536000"
});
res.write(data.file, "binary");
res.end();
if (!settings.cacheEnabled) { cache[filename] = undefined; }
});
}
processRequest(paths);
};
}
|
javascript
|
function createListener(virtualPath) {
return function listener(req, res, next) {
var paths = allPaths[virtualPath].slice();
function processRequest(paths) {
var physicalPath = paths.pop()
, synchronizer = new Synchronizer()
, uri = urlParser.parse(req.url).pathname
, filename = "";
if (virtualPath !== "/" && uri.indexOf(virtualPath) === 0) {
uri = uri.substr(virtualPath.length, uri.length - virtualPath.length);
}
uri = (physicalPath || "") + uri;
filename = fs.combine(process.cwd(), uri).replace(/\%20/gmi, ' ');
if (cache[filename]) {
console.log("\u001b[32mLoaded from Cache '" + filename + "\u001b[39m'");
if (cache[filename] === 404) {
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("Content not found");
res.end();
} else {
if (req.headers["If-Modified-Since"] === cache[filename].since) {
res.writeHead(304, {
'Content-Type': mime.lookup(filename),
'Last-Modified': cache[filename].since,
//'If-Modified-Since': cache[filename].since,
"Cache-Control": "max-age=31536000"
});
res.end();
} else {
res.writeHead(200, {
'Content-Type': mime.lookup(filename),
//'If-Modified-Since': cache[filename].since,
'Last-Modified': cache[filename].since,
"Cache-Control": "max-age=31536000"
});
res.write(cache[filename].data, "binary");
res.end();
}
}
return;
}
if (filename) {
fs.readFile(filename, "binary", synchronizer.register("file"));
}
synchronizer.onfinish(function (err, data) {
if (err) {
if (paths.length > 0) {
processRequest(paths);
} else if (next) {
next();
} else {
console.log("\u001b[31mStatic file not found '" + filename + "'\u001b[39m");
cache[filename] = 404;
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("Content not found");
res.end();
}
return;
}
console.error("\u001b[31mLoaded static file '" + filename + "'\u001b[39m");
cache[filename] = {
data: data.file,
since: new Date().toGMTString()
};
res.writeHead(200, {
'Content-Type': mime.lookup(filename),
//'If-Modified-Since': cache[filename].since,
'Last-Modified': cache[filename].since,
"Cache-Control": "max-age=31536000"
});
res.write(data.file, "binary");
res.end();
if (!settings.cacheEnabled) { cache[filename] = undefined; }
});
}
processRequest(paths);
};
}
|
[
"function",
"createListener",
"(",
"virtualPath",
")",
"{",
"return",
"function",
"listener",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"paths",
"=",
"allPaths",
"[",
"virtualPath",
"]",
".",
"slice",
"(",
")",
";",
"function",
"processRequest",
"(",
"paths",
")",
"{",
"var",
"physicalPath",
"=",
"paths",
".",
"pop",
"(",
")",
",",
"synchronizer",
"=",
"new",
"Synchronizer",
"(",
")",
",",
"uri",
"=",
"urlParser",
".",
"parse",
"(",
"req",
".",
"url",
")",
".",
"pathname",
",",
"filename",
"=",
"\"\"",
";",
"if",
"(",
"virtualPath",
"!==",
"\"/\"",
"&&",
"uri",
".",
"indexOf",
"(",
"virtualPath",
")",
"===",
"0",
")",
"{",
"uri",
"=",
"uri",
".",
"substr",
"(",
"virtualPath",
".",
"length",
",",
"uri",
".",
"length",
"-",
"virtualPath",
".",
"length",
")",
";",
"}",
"uri",
"=",
"(",
"physicalPath",
"||",
"\"\"",
")",
"+",
"uri",
";",
"filename",
"=",
"fs",
".",
"combine",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"uri",
")",
".",
"replace",
"(",
"/",
"\\%20",
"/",
"gmi",
",",
"' '",
")",
";",
"if",
"(",
"cache",
"[",
"filename",
"]",
")",
"{",
"console",
".",
"log",
"(",
"\"\\u001b[32mLoaded from Cache '\"",
"+",
"filename",
"+",
"\"\\u001b[39m'\"",
")",
";",
"if",
"(",
"cache",
"[",
"filename",
"]",
"===",
"404",
")",
"{",
"res",
".",
"writeHead",
"(",
"404",
",",
"{",
"\"Content-Type\"",
":",
"\"text/plain\"",
"}",
")",
";",
"res",
".",
"write",
"(",
"\"Content not found\"",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"req",
".",
"headers",
"[",
"\"If-Modified-Since\"",
"]",
"===",
"cache",
"[",
"filename",
"]",
".",
"since",
")",
"{",
"res",
".",
"writeHead",
"(",
"304",
",",
"{",
"'Content-Type'",
":",
"mime",
".",
"lookup",
"(",
"filename",
")",
",",
"'Last-Modified'",
":",
"cache",
"[",
"filename",
"]",
".",
"since",
",",
"//'If-Modified-Since': cache[filename].since,",
"\"Cache-Control\"",
":",
"\"max-age=31536000\"",
"}",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"}",
"else",
"{",
"res",
".",
"writeHead",
"(",
"200",
",",
"{",
"'Content-Type'",
":",
"mime",
".",
"lookup",
"(",
"filename",
")",
",",
"//'If-Modified-Since': cache[filename].since,",
"'Last-Modified'",
":",
"cache",
"[",
"filename",
"]",
".",
"since",
",",
"\"Cache-Control\"",
":",
"\"max-age=31536000\"",
"}",
")",
";",
"res",
".",
"write",
"(",
"cache",
"[",
"filename",
"]",
".",
"data",
",",
"\"binary\"",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"}",
"}",
"return",
";",
"}",
"if",
"(",
"filename",
")",
"{",
"fs",
".",
"readFile",
"(",
"filename",
",",
"\"binary\"",
",",
"synchronizer",
".",
"register",
"(",
"\"file\"",
")",
")",
";",
"}",
"synchronizer",
".",
"onfinish",
"(",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"paths",
".",
"length",
">",
"0",
")",
"{",
"processRequest",
"(",
"paths",
")",
";",
"}",
"else",
"if",
"(",
"next",
")",
"{",
"next",
"(",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"\"\\u001b[31mStatic file not found '\"",
"+",
"filename",
"+",
"\"'\\u001b[39m\"",
")",
";",
"cache",
"[",
"filename",
"]",
"=",
"404",
";",
"res",
".",
"writeHead",
"(",
"404",
",",
"{",
"\"Content-Type\"",
":",
"\"text/plain\"",
"}",
")",
";",
"res",
".",
"write",
"(",
"\"Content not found\"",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"}",
"return",
";",
"}",
"console",
".",
"error",
"(",
"\"\\u001b[31mLoaded static file '\"",
"+",
"filename",
"+",
"\"'\\u001b[39m\"",
")",
";",
"cache",
"[",
"filename",
"]",
"=",
"{",
"data",
":",
"data",
".",
"file",
",",
"since",
":",
"new",
"Date",
"(",
")",
".",
"toGMTString",
"(",
")",
"}",
";",
"res",
".",
"writeHead",
"(",
"200",
",",
"{",
"'Content-Type'",
":",
"mime",
".",
"lookup",
"(",
"filename",
")",
",",
"//'If-Modified-Since': cache[filename].since,",
"'Last-Modified'",
":",
"cache",
"[",
"filename",
"]",
".",
"since",
",",
"\"Cache-Control\"",
":",
"\"max-age=31536000\"",
"}",
")",
";",
"res",
".",
"write",
"(",
"data",
".",
"file",
",",
"\"binary\"",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"if",
"(",
"!",
"settings",
".",
"cacheEnabled",
")",
"{",
"cache",
"[",
"filename",
"]",
"=",
"undefined",
";",
"}",
"}",
")",
";",
"}",
"processRequest",
"(",
"paths",
")",
";",
"}",
";",
"}"
] |
Create a new static file handler
@param virtualPath
@param physicalPath
|
[
"Create",
"a",
"new",
"static",
"file",
"handler"
] |
a4239c66966a64fe004ca6ef2d8920946c44f0b7
|
https://github.com/Crafity/crafity-webserver/blob/a4239c66966a64fe004ca6ef2d8920946c44f0b7/lib/fileserver.js#L195-L282
|
50,723
|
marcojonker/data-elevator
|
lib/logger/base-logger.js
|
function(error, verbose) {
var message = "";
//Some errors have a base error (in case of ElevatorError for example)
while(error) {
message += (verbose === true && error.stack) ? error.stack : error.message;
error = error.baseError;
if(error) {
message += "\r\n";
}
}
return message;
}
|
javascript
|
function(error, verbose) {
var message = "";
//Some errors have a base error (in case of ElevatorError for example)
while(error) {
message += (verbose === true && error.stack) ? error.stack : error.message;
error = error.baseError;
if(error) {
message += "\r\n";
}
}
return message;
}
|
[
"function",
"(",
"error",
",",
"verbose",
")",
"{",
"var",
"message",
"=",
"\"\"",
";",
"//Some errors have a base error (in case of ElevatorError for example)",
"while",
"(",
"error",
")",
"{",
"message",
"+=",
"(",
"verbose",
"===",
"true",
"&&",
"error",
".",
"stack",
")",
"?",
"error",
".",
"stack",
":",
"error",
".",
"message",
";",
"error",
"=",
"error",
".",
"baseError",
";",
"if",
"(",
"error",
")",
"{",
"message",
"+=",
"\"\\r\\n\"",
";",
"}",
"}",
"return",
"message",
";",
"}"
] |
Create a log string for an error
@param error
@param verbose
|
[
"Create",
"a",
"log",
"string",
"for",
"an",
"error"
] |
7d56e5b2e8ca24b9576066e5265713db6452f289
|
https://github.com/marcojonker/data-elevator/blob/7d56e5b2e8ca24b9576066e5265713db6452f289/lib/logger/base-logger.js#L10-L24
|
|
50,724
|
gethuman/pancakes-angular
|
lib/ngapp/casing.js
|
camelCase
|
function camelCase(str, delim) {
var delims = delim || ['_', '.', '-'];
if (!_.isArray(delims)) {
delims = [delims];
}
_.each(delims, function (adelim) {
var codeParts = str.split(adelim);
var i, codePart;
for (i = 1; i < codeParts.length; i++) {
codePart = codeParts[i];
codeParts[i] = codePart.substring(0, 1).toUpperCase() + codePart.substring(1);
}
str = codeParts.join('');
});
return str;
}
|
javascript
|
function camelCase(str, delim) {
var delims = delim || ['_', '.', '-'];
if (!_.isArray(delims)) {
delims = [delims];
}
_.each(delims, function (adelim) {
var codeParts = str.split(adelim);
var i, codePart;
for (i = 1; i < codeParts.length; i++) {
codePart = codeParts[i];
codeParts[i] = codePart.substring(0, 1).toUpperCase() + codePart.substring(1);
}
str = codeParts.join('');
});
return str;
}
|
[
"function",
"camelCase",
"(",
"str",
",",
"delim",
")",
"{",
"var",
"delims",
"=",
"delim",
"||",
"[",
"'_'",
",",
"'.'",
",",
"'-'",
"]",
";",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"delims",
")",
")",
"{",
"delims",
"=",
"[",
"delims",
"]",
";",
"}",
"_",
".",
"each",
"(",
"delims",
",",
"function",
"(",
"adelim",
")",
"{",
"var",
"codeParts",
"=",
"str",
".",
"split",
"(",
"adelim",
")",
";",
"var",
"i",
",",
"codePart",
";",
"for",
"(",
"i",
"=",
"1",
";",
"i",
"<",
"codeParts",
".",
"length",
";",
"i",
"++",
")",
"{",
"codePart",
"=",
"codeParts",
"[",
"i",
"]",
";",
"codeParts",
"[",
"i",
"]",
"=",
"codePart",
".",
"substring",
"(",
"0",
",",
"1",
")",
".",
"toUpperCase",
"(",
")",
"+",
"codePart",
".",
"substring",
"(",
"1",
")",
";",
"}",
"str",
"=",
"codeParts",
".",
"join",
"(",
"''",
")",
";",
"}",
")",
";",
"return",
"str",
";",
"}"
] |
Convert to camelCase
@param str
@param delim
|
[
"Convert",
"to",
"camelCase"
] |
9589b7ba09619843e271293088005c62ed23f355
|
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/ngapp/casing.js#L16-L36
|
50,725
|
philipbordallo/eslint-config
|
build.js
|
buildConfig
|
async function buildConfig(file) {
const { default: config } = await import(`${CONFIGS_PATH}/${file}`);
const { creator, name, packageName } = config;
creator
.then((data) => {
const stringifiedData = JSON.stringify(data);
const generatedData = TEMPLATE.replace(/{{ data }}/, stringifiedData);
const packageFile = path.resolve(PACKAGES_PATH, packageName, 'index.js');
fs.writeFileSync(packageFile, generatedData);
})
.then(
() => console.log(`Finished building ${name} config to ./packages/${packageName}`),
error => console.log(error),
);
}
|
javascript
|
async function buildConfig(file) {
const { default: config } = await import(`${CONFIGS_PATH}/${file}`);
const { creator, name, packageName } = config;
creator
.then((data) => {
const stringifiedData = JSON.stringify(data);
const generatedData = TEMPLATE.replace(/{{ data }}/, stringifiedData);
const packageFile = path.resolve(PACKAGES_PATH, packageName, 'index.js');
fs.writeFileSync(packageFile, generatedData);
})
.then(
() => console.log(`Finished building ${name} config to ./packages/${packageName}`),
error => console.log(error),
);
}
|
[
"async",
"function",
"buildConfig",
"(",
"file",
")",
"{",
"const",
"{",
"default",
":",
"config",
"}",
"=",
"await",
"import",
"(",
"`",
"${",
"CONFIGS_PATH",
"}",
"${",
"file",
"}",
"`",
")",
";",
"const",
"{",
"creator",
",",
"name",
",",
"packageName",
"}",
"=",
"config",
";",
"creator",
".",
"then",
"(",
"(",
"data",
")",
"=>",
"{",
"const",
"stringifiedData",
"=",
"JSON",
".",
"stringify",
"(",
"data",
")",
";",
"const",
"generatedData",
"=",
"TEMPLATE",
".",
"replace",
"(",
"/",
"{{ data }}",
"/",
",",
"stringifiedData",
")",
";",
"const",
"packageFile",
"=",
"path",
".",
"resolve",
"(",
"PACKAGES_PATH",
",",
"packageName",
",",
"'index.js'",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"packageFile",
",",
"generatedData",
")",
";",
"}",
")",
".",
"then",
"(",
"(",
")",
"=>",
"console",
".",
"log",
"(",
"`",
"${",
"name",
"}",
"${",
"packageName",
"}",
"`",
")",
",",
"error",
"=>",
"console",
".",
"log",
"(",
"error",
")",
",",
")",
";",
"}"
] |
Builds config file to packages folder
@param {string} file - Config file
|
[
"Builds",
"config",
"file",
"to",
"packages",
"folder"
] |
a2f1bff442fdb8ee622f842f075fa10d555302a4
|
https://github.com/philipbordallo/eslint-config/blob/a2f1bff442fdb8ee622f842f075fa10d555302a4/build.js#L14-L29
|
50,726
|
Nazariglez/perenquen
|
lib/pixi/src/mesh/Mesh.js
|
Mesh
|
function Mesh(texture, vertices, uvs, indices, drawMode)
{
core.Container.call(this);
/**
* The texture of the Mesh
*
* @member {Texture}
*/
this.texture = texture;
/**
* The Uvs of the Mesh
*
* @member {Float32Array}
*/
this.uvs = uvs || new Float32Array([0, 1,
1, 1,
1, 0,
0, 1]);
/**
* An array of vertices
*
* @member {Float32Array}
*/
this.vertices = vertices || new Float32Array([0, 0,
100, 0,
100, 100,
0, 100]);
/*
* @member {Uint16Array} An array containing the indices of the vertices
*/
// TODO auto generate this based on draw mode!
this.indices = indices || new Uint16Array([0, 1, 2, 3]);
/**
* Whether the Mesh is dirty or not
*
* @member {boolean}
*/
this.dirty = true;
/**
* The blend mode to be applied to the sprite. Set to blendModes.NORMAL to remove any blend mode.
*
* @member {number}
* @default CONST.BLEND_MODES.NORMAL;
*/
this.blendMode = core.BLEND_MODES.NORMAL;
/**
* Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other.
*
* @member {number}
*/
this.canvasPadding = 0;
/**
* The way the Mesh should be drawn, can be any of the Mesh.DRAW_MODES consts
*
* @member {number}
*/
this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH;
}
|
javascript
|
function Mesh(texture, vertices, uvs, indices, drawMode)
{
core.Container.call(this);
/**
* The texture of the Mesh
*
* @member {Texture}
*/
this.texture = texture;
/**
* The Uvs of the Mesh
*
* @member {Float32Array}
*/
this.uvs = uvs || new Float32Array([0, 1,
1, 1,
1, 0,
0, 1]);
/**
* An array of vertices
*
* @member {Float32Array}
*/
this.vertices = vertices || new Float32Array([0, 0,
100, 0,
100, 100,
0, 100]);
/*
* @member {Uint16Array} An array containing the indices of the vertices
*/
// TODO auto generate this based on draw mode!
this.indices = indices || new Uint16Array([0, 1, 2, 3]);
/**
* Whether the Mesh is dirty or not
*
* @member {boolean}
*/
this.dirty = true;
/**
* The blend mode to be applied to the sprite. Set to blendModes.NORMAL to remove any blend mode.
*
* @member {number}
* @default CONST.BLEND_MODES.NORMAL;
*/
this.blendMode = core.BLEND_MODES.NORMAL;
/**
* Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other.
*
* @member {number}
*/
this.canvasPadding = 0;
/**
* The way the Mesh should be drawn, can be any of the Mesh.DRAW_MODES consts
*
* @member {number}
*/
this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH;
}
|
[
"function",
"Mesh",
"(",
"texture",
",",
"vertices",
",",
"uvs",
",",
"indices",
",",
"drawMode",
")",
"{",
"core",
".",
"Container",
".",
"call",
"(",
"this",
")",
";",
"/**\n * The texture of the Mesh\n *\n * @member {Texture}\n */",
"this",
".",
"texture",
"=",
"texture",
";",
"/**\n * The Uvs of the Mesh\n *\n * @member {Float32Array}\n */",
"this",
".",
"uvs",
"=",
"uvs",
"||",
"new",
"Float32Array",
"(",
"[",
"0",
",",
"1",
",",
"1",
",",
"1",
",",
"1",
",",
"0",
",",
"0",
",",
"1",
"]",
")",
";",
"/**\n * An array of vertices\n *\n * @member {Float32Array}\n */",
"this",
".",
"vertices",
"=",
"vertices",
"||",
"new",
"Float32Array",
"(",
"[",
"0",
",",
"0",
",",
"100",
",",
"0",
",",
"100",
",",
"100",
",",
"0",
",",
"100",
"]",
")",
";",
"/*\n * @member {Uint16Array} An array containing the indices of the vertices\n */",
"// TODO auto generate this based on draw mode!",
"this",
".",
"indices",
"=",
"indices",
"||",
"new",
"Uint16Array",
"(",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
"]",
")",
";",
"/**\n * Whether the Mesh is dirty or not\n *\n * @member {boolean}\n */",
"this",
".",
"dirty",
"=",
"true",
";",
"/**\n * The blend mode to be applied to the sprite. Set to blendModes.NORMAL to remove any blend mode.\n *\n * @member {number}\n * @default CONST.BLEND_MODES.NORMAL;\n */",
"this",
".",
"blendMode",
"=",
"core",
".",
"BLEND_MODES",
".",
"NORMAL",
";",
"/**\n * Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other.\n *\n * @member {number}\n */",
"this",
".",
"canvasPadding",
"=",
"0",
";",
"/**\n * The way the Mesh should be drawn, can be any of the Mesh.DRAW_MODES consts\n *\n * @member {number}\n */",
"this",
".",
"drawMode",
"=",
"drawMode",
"||",
"Mesh",
".",
"DRAW_MODES",
".",
"TRIANGLE_MESH",
";",
"}"
] |
Base mesh class
@class
@extends Container
@memberof PIXI.mesh
@param texture {Texture} The texture to use
@param [vertices] {Float32Arrif you want to specify the vertices
@param [uvs] {Float32Array} if you want to specify the uvs
@param [indices] {Uint16Array} if you want to specify the indices
@param [drawMode] {number} the drawMode, can be any of the Mesh.DRAW_MODES consts
|
[
"Base",
"mesh",
"class"
] |
e023964d05afeefebdcac4e2044819fdfa3899ae
|
https://github.com/Nazariglez/perenquen/blob/e023964d05afeefebdcac4e2044819fdfa3899ae/lib/pixi/src/mesh/Mesh.js#L14-L79
|
50,727
|
gethuman/pancakes-recipe
|
utils/app.error.js
|
function (opts) {
this.isAppError = true;
this.code = opts.code;
this.message = this.msg = opts.msg;
this.type = opts.type;
this.err = opts.err;
this.stack = (new Error(opts.msg)).stack;
}
|
javascript
|
function (opts) {
this.isAppError = true;
this.code = opts.code;
this.message = this.msg = opts.msg;
this.type = opts.type;
this.err = opts.err;
this.stack = (new Error(opts.msg)).stack;
}
|
[
"function",
"(",
"opts",
")",
"{",
"this",
".",
"isAppError",
"=",
"true",
";",
"this",
".",
"code",
"=",
"opts",
".",
"code",
";",
"this",
".",
"message",
"=",
"this",
".",
"msg",
"=",
"opts",
".",
"msg",
";",
"this",
".",
"type",
"=",
"opts",
".",
"type",
";",
"this",
".",
"err",
"=",
"opts",
".",
"err",
";",
"this",
".",
"stack",
"=",
"(",
"new",
"Error",
"(",
"opts",
".",
"msg",
")",
")",
".",
"stack",
";",
"}"
] |
Constructor recieves a object with options that are used
to define values on the error. These values are used at the
middleware layer to translate into friendly messages
@param opts
@constructor
|
[
"Constructor",
"recieves",
"a",
"object",
"with",
"options",
"that",
"are",
"used",
"to",
"define",
"values",
"on",
"the",
"error",
".",
"These",
"values",
"are",
"used",
"at",
"the",
"middleware",
"layer",
"to",
"translate",
"into",
"friendly",
"messages"
] |
ea3feb8839e2edaf1b4577c052b8958953db4498
|
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/utils/app.error.js#L18-L25
|
|
50,728
|
christophehurpeau/springbokjs-dom
|
lib/prototypes/events.js
|
onDelayed
|
function onDelayed(delay, throttle, eventNames, selector, listener) {
if (typeof throttle !== 'boolean') {
listener = selector;
selector = eventNames;
eventNames = throttle;
throttle = false;
}
if (typeof selector === 'function') {
listener = selector;
selector = undefined;
}
var wait = undefined;
this.on(eventNames, selector, /** @function
* @param {...*} args */function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var _this = this;
if (!throttle) {
clearTimeout(wait);
wait = null;
}
if (!wait) {
wait = setTimeout(function () {
wait = null;
listener.apply(_this, args);
}, delay);
}
});
}
|
javascript
|
function onDelayed(delay, throttle, eventNames, selector, listener) {
if (typeof throttle !== 'boolean') {
listener = selector;
selector = eventNames;
eventNames = throttle;
throttle = false;
}
if (typeof selector === 'function') {
listener = selector;
selector = undefined;
}
var wait = undefined;
this.on(eventNames, selector, /** @function
* @param {...*} args */function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var _this = this;
if (!throttle) {
clearTimeout(wait);
wait = null;
}
if (!wait) {
wait = setTimeout(function () {
wait = null;
listener.apply(_this, args);
}, delay);
}
});
}
|
[
"function",
"onDelayed",
"(",
"delay",
",",
"throttle",
",",
"eventNames",
",",
"selector",
",",
"listener",
")",
"{",
"if",
"(",
"typeof",
"throttle",
"!==",
"'boolean'",
")",
"{",
"listener",
"=",
"selector",
";",
"selector",
"=",
"eventNames",
";",
"eventNames",
"=",
"throttle",
";",
"throttle",
"=",
"false",
";",
"}",
"if",
"(",
"typeof",
"selector",
"===",
"'function'",
")",
"{",
"listener",
"=",
"selector",
";",
"selector",
"=",
"undefined",
";",
"}",
"var",
"wait",
"=",
"undefined",
";",
"this",
".",
"on",
"(",
"eventNames",
",",
"selector",
",",
"/** @function \n * @param {...*} args */",
"function",
"(",
")",
"{",
"for",
"(",
"var",
"_len",
"=",
"arguments",
".",
"length",
",",
"args",
"=",
"Array",
"(",
"_len",
")",
",",
"_key",
"=",
"0",
";",
"_key",
"<",
"_len",
";",
"_key",
"++",
")",
"{",
"args",
"[",
"_key",
"]",
"=",
"arguments",
"[",
"_key",
"]",
";",
"}",
"var",
"_this",
"=",
"this",
";",
"if",
"(",
"!",
"throttle",
")",
"{",
"clearTimeout",
"(",
"wait",
")",
";",
"wait",
"=",
"null",
";",
"}",
"if",
"(",
"!",
"wait",
")",
"{",
"wait",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"wait",
"=",
"null",
";",
"listener",
".",
"apply",
"(",
"_this",
",",
"args",
")",
";",
"}",
",",
"delay",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Register a delayed listener for a space separated list of events
Usefull for key typing events
@example <caption>Example usage of onDelayed.</caption>
$('#input-search').onDelayed(200, 'keyup', (event) => {
console.log(event.$element.getValue()
}
@method Element#onDelayed
@param {Number} delay
@param {String} eventNames
@param {String=} selector
@param {Function} listener
Register a delayed listener for a space separated list of events
Usefull for key typing events
@example <caption>Example usage of onDelayed.</caption>
$('#input-search').onDelayed(200, 'keyup', (event) => {
console.log(event.$element.getValue()
}
@method ElementsArray#onDelayed
@param {Number} delay
@param {Number} [throttle=false]
@param {String} eventNames
@param {String} [selector]
@param {Function} listener
|
[
"Register",
"a",
"delayed",
"listener",
"for",
"a",
"space",
"separated",
"list",
"of",
"events"
] |
6e14a87fbe71124a0cbb68d1cb8626689c3b18a1
|
https://github.com/christophehurpeau/springbokjs-dom/blob/6e14a87fbe71124a0cbb68d1cb8626689c3b18a1/lib/prototypes/events.js#L330-L364
|
50,729
|
iceroad/baresoil-server
|
lib/sysapp/server/api/authenticated/account/get.js
|
get
|
function get(ignored, cb) {
assert(this.$session);
const ugRequest = {
userId: this.$session.userId,
};
this.syscall('UserManager', 'get', ugRequest, (err, userInfo, curVersion) => {
if (err) return cb(err);
// Strip security-sensitive information.
delete userInfo.hashedPassword;
_.forEach(userInfo.securityEvents, (secEvt) => {
if (secEvt.eventType === 'password_reset_requested') {
delete secEvt.data.resetCode;
}
});
return cb(null, userInfo, curVersion);
});
}
|
javascript
|
function get(ignored, cb) {
assert(this.$session);
const ugRequest = {
userId: this.$session.userId,
};
this.syscall('UserManager', 'get', ugRequest, (err, userInfo, curVersion) => {
if (err) return cb(err);
// Strip security-sensitive information.
delete userInfo.hashedPassword;
_.forEach(userInfo.securityEvents, (secEvt) => {
if (secEvt.eventType === 'password_reset_requested') {
delete secEvt.data.resetCode;
}
});
return cb(null, userInfo, curVersion);
});
}
|
[
"function",
"get",
"(",
"ignored",
",",
"cb",
")",
"{",
"assert",
"(",
"this",
".",
"$session",
")",
";",
"const",
"ugRequest",
"=",
"{",
"userId",
":",
"this",
".",
"$session",
".",
"userId",
",",
"}",
";",
"this",
".",
"syscall",
"(",
"'UserManager'",
",",
"'get'",
",",
"ugRequest",
",",
"(",
"err",
",",
"userInfo",
",",
"curVersion",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"// Strip security-sensitive information.",
"delete",
"userInfo",
".",
"hashedPassword",
";",
"_",
".",
"forEach",
"(",
"userInfo",
".",
"securityEvents",
",",
"(",
"secEvt",
")",
"=>",
"{",
"if",
"(",
"secEvt",
".",
"eventType",
"===",
"'password_reset_requested'",
")",
"{",
"delete",
"secEvt",
".",
"data",
".",
"resetCode",
";",
"}",
"}",
")",
";",
"return",
"cb",
"(",
"null",
",",
"userInfo",
",",
"curVersion",
")",
";",
"}",
")",
";",
"}"
] |
Get logged-in user information.
|
[
"Get",
"logged",
"-",
"in",
"user",
"information",
"."
] |
8285f1647a81eb935331ea24491b38002b51278d
|
https://github.com/iceroad/baresoil-server/blob/8285f1647a81eb935331ea24491b38002b51278d/lib/sysapp/server/api/authenticated/account/get.js#L6-L24
|
50,730
|
AppAndFlow/anf
|
packages/scripts/deploy.js
|
safeExec
|
function safeExec(command, options) {
const result = exec(command, options);
if (result.code !== 0) {
exit(result.code);
return null;
}
return result;
}
|
javascript
|
function safeExec(command, options) {
const result = exec(command, options);
if (result.code !== 0) {
exit(result.code);
return null;
}
return result;
}
|
[
"function",
"safeExec",
"(",
"command",
",",
"options",
")",
"{",
"const",
"result",
"=",
"exec",
"(",
"command",
",",
"options",
")",
";",
"if",
"(",
"result",
".",
"code",
"!==",
"0",
")",
"{",
"exit",
"(",
"result",
".",
"code",
")",
";",
"return",
"null",
";",
"}",
"return",
"result",
";",
"}"
] |
Exec that exits on non 0 exit code.
|
[
"Exec",
"that",
"exits",
"on",
"non",
"0",
"exit",
"code",
"."
] |
82a50bcab9f85a3c1b5c22c1f127f67d04810c89
|
https://github.com/AppAndFlow/anf/blob/82a50bcab9f85a3c1b5c22c1f127f67d04810c89/packages/scripts/deploy.js#L6-L13
|
50,731
|
AppAndFlow/anf
|
packages/scripts/deploy.js
|
deploy
|
function deploy({
containerName,
containerRepository,
clusterName,
serviceName,
accessKeyId,
secretAccessKey,
region = 'us-west-2',
}) {
AWS.config.update({ accessKeyId, secretAccessKey, region });
cd('C:\\Users\\janic\\Developer\\pikapik\\th3rdwave-api');
const commitSHA = env.CIRCLE_SHA1 || safeExec('git rev-parse HEAD').stdout.trim();
echo(`Deploying commit ${commitSHA}...`);
echo('Loging in to docker registry...');
const loginCmd = safeExec('aws ecr get-login', { silent: true }).stdout;
safeExec(loginCmd);
echo('Building docker image...');
safeExec(`docker build -t ${containerName} .`);
echo('Uploading docker image...');
safeExec(`docker tag ${containerName} ${containerRepository}:${commitSHA}`);
safeExec(`docker tag ${containerName} ${containerRepository}:latest`);
safeExec(`docker push ${containerRepository}`);
echo('Updating service...');
const ecs = new AWS.ECS();
ecs.describeServices({
cluster: clusterName,
services: [serviceName],
}).promise()
.then((data) => {
const taskDefinition = data.services[0].taskDefinition;
return ecs.describeTaskDefinition({
taskDefinition,
}).promise();
})
.then((data) => {
const { taskDefinition } = data;
return ecs.registerTaskDefinition({
containerDefinitions: taskDefinition.containerDefinitions.map(def => {
const newImage = `${def.image.split(':')[0]}:${commitSHA}`;
return Object.assign({}, def, { image: newImage });
}),
family: taskDefinition.family,
networkMode: taskDefinition.networkMode,
taskRoleArn: taskDefinition.taskRoleArn,
volumes: taskDefinition.volumes,
}).promise();
})
.then((data) => {
echo(`Created new revision ${data.taskDefinition.revision}.`);
return ecs.updateService({
service: serviceName,
cluster: clusterName,
taskDefinition: data.taskDefinition.taskDefinitionArn,
}).promise();
})
.then(() => {
echo('Service updated successfully.');
})
.catch((err) => {
echo(err);
exit(1);
});
}
|
javascript
|
function deploy({
containerName,
containerRepository,
clusterName,
serviceName,
accessKeyId,
secretAccessKey,
region = 'us-west-2',
}) {
AWS.config.update({ accessKeyId, secretAccessKey, region });
cd('C:\\Users\\janic\\Developer\\pikapik\\th3rdwave-api');
const commitSHA = env.CIRCLE_SHA1 || safeExec('git rev-parse HEAD').stdout.trim();
echo(`Deploying commit ${commitSHA}...`);
echo('Loging in to docker registry...');
const loginCmd = safeExec('aws ecr get-login', { silent: true }).stdout;
safeExec(loginCmd);
echo('Building docker image...');
safeExec(`docker build -t ${containerName} .`);
echo('Uploading docker image...');
safeExec(`docker tag ${containerName} ${containerRepository}:${commitSHA}`);
safeExec(`docker tag ${containerName} ${containerRepository}:latest`);
safeExec(`docker push ${containerRepository}`);
echo('Updating service...');
const ecs = new AWS.ECS();
ecs.describeServices({
cluster: clusterName,
services: [serviceName],
}).promise()
.then((data) => {
const taskDefinition = data.services[0].taskDefinition;
return ecs.describeTaskDefinition({
taskDefinition,
}).promise();
})
.then((data) => {
const { taskDefinition } = data;
return ecs.registerTaskDefinition({
containerDefinitions: taskDefinition.containerDefinitions.map(def => {
const newImage = `${def.image.split(':')[0]}:${commitSHA}`;
return Object.assign({}, def, { image: newImage });
}),
family: taskDefinition.family,
networkMode: taskDefinition.networkMode,
taskRoleArn: taskDefinition.taskRoleArn,
volumes: taskDefinition.volumes,
}).promise();
})
.then((data) => {
echo(`Created new revision ${data.taskDefinition.revision}.`);
return ecs.updateService({
service: serviceName,
cluster: clusterName,
taskDefinition: data.taskDefinition.taskDefinitionArn,
}).promise();
})
.then(() => {
echo('Service updated successfully.');
})
.catch((err) => {
echo(err);
exit(1);
});
}
|
[
"function",
"deploy",
"(",
"{",
"containerName",
",",
"containerRepository",
",",
"clusterName",
",",
"serviceName",
",",
"accessKeyId",
",",
"secretAccessKey",
",",
"region",
"=",
"'us-west-2'",
",",
"}",
")",
"{",
"AWS",
".",
"config",
".",
"update",
"(",
"{",
"accessKeyId",
",",
"secretAccessKey",
",",
"region",
"}",
")",
";",
"cd",
"(",
"'C:\\\\Users\\\\janic\\\\Developer\\\\pikapik\\\\th3rdwave-api'",
")",
";",
"const",
"commitSHA",
"=",
"env",
".",
"CIRCLE_SHA1",
"||",
"safeExec",
"(",
"'git rev-parse HEAD'",
")",
".",
"stdout",
".",
"trim",
"(",
")",
";",
"echo",
"(",
"`",
"${",
"commitSHA",
"}",
"`",
")",
";",
"echo",
"(",
"'Loging in to docker registry...'",
")",
";",
"const",
"loginCmd",
"=",
"safeExec",
"(",
"'aws ecr get-login'",
",",
"{",
"silent",
":",
"true",
"}",
")",
".",
"stdout",
";",
"safeExec",
"(",
"loginCmd",
")",
";",
"echo",
"(",
"'Building docker image...'",
")",
";",
"safeExec",
"(",
"`",
"${",
"containerName",
"}",
"`",
")",
";",
"echo",
"(",
"'Uploading docker image...'",
")",
";",
"safeExec",
"(",
"`",
"${",
"containerName",
"}",
"${",
"containerRepository",
"}",
"${",
"commitSHA",
"}",
"`",
")",
";",
"safeExec",
"(",
"`",
"${",
"containerName",
"}",
"${",
"containerRepository",
"}",
"`",
")",
";",
"safeExec",
"(",
"`",
"${",
"containerRepository",
"}",
"`",
")",
";",
"echo",
"(",
"'Updating service...'",
")",
";",
"const",
"ecs",
"=",
"new",
"AWS",
".",
"ECS",
"(",
")",
";",
"ecs",
".",
"describeServices",
"(",
"{",
"cluster",
":",
"clusterName",
",",
"services",
":",
"[",
"serviceName",
"]",
",",
"}",
")",
".",
"promise",
"(",
")",
".",
"then",
"(",
"(",
"data",
")",
"=>",
"{",
"const",
"taskDefinition",
"=",
"data",
".",
"services",
"[",
"0",
"]",
".",
"taskDefinition",
";",
"return",
"ecs",
".",
"describeTaskDefinition",
"(",
"{",
"taskDefinition",
",",
"}",
")",
".",
"promise",
"(",
")",
";",
"}",
")",
".",
"then",
"(",
"(",
"data",
")",
"=>",
"{",
"const",
"{",
"taskDefinition",
"}",
"=",
"data",
";",
"return",
"ecs",
".",
"registerTaskDefinition",
"(",
"{",
"containerDefinitions",
":",
"taskDefinition",
".",
"containerDefinitions",
".",
"map",
"(",
"def",
"=>",
"{",
"const",
"newImage",
"=",
"`",
"${",
"def",
".",
"image",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"}",
"${",
"commitSHA",
"}",
"`",
";",
"return",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"def",
",",
"{",
"image",
":",
"newImage",
"}",
")",
";",
"}",
")",
",",
"family",
":",
"taskDefinition",
".",
"family",
",",
"networkMode",
":",
"taskDefinition",
".",
"networkMode",
",",
"taskRoleArn",
":",
"taskDefinition",
".",
"taskRoleArn",
",",
"volumes",
":",
"taskDefinition",
".",
"volumes",
",",
"}",
")",
".",
"promise",
"(",
")",
";",
"}",
")",
".",
"then",
"(",
"(",
"data",
")",
"=>",
"{",
"echo",
"(",
"`",
"${",
"data",
".",
"taskDefinition",
".",
"revision",
"}",
"`",
")",
";",
"return",
"ecs",
".",
"updateService",
"(",
"{",
"service",
":",
"serviceName",
",",
"cluster",
":",
"clusterName",
",",
"taskDefinition",
":",
"data",
".",
"taskDefinition",
".",
"taskDefinitionArn",
",",
"}",
")",
".",
"promise",
"(",
")",
";",
"}",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"echo",
"(",
"'Service updated successfully.'",
")",
";",
"}",
")",
".",
"catch",
"(",
"(",
"err",
")",
"=>",
"{",
"echo",
"(",
"err",
")",
";",
"exit",
"(",
"1",
")",
";",
"}",
")",
";",
"}"
] |
Build and deploy a new image and update the service on AWS ECS.
|
[
"Build",
"and",
"deploy",
"a",
"new",
"image",
"and",
"update",
"the",
"service",
"on",
"AWS",
"ECS",
"."
] |
82a50bcab9f85a3c1b5c22c1f127f67d04810c89
|
https://github.com/AppAndFlow/anf/blob/82a50bcab9f85a3c1b5c22c1f127f67d04810c89/packages/scripts/deploy.js#L18-L88
|
50,732
|
aliaksandr-master/grunt-process
|
Gruntfile.js
|
function (src, dest, content, fileObject) {
var files = {};
_.each(content, function (v, k) {
var file = fileObject.orig.dest + '/' + k + '.json';
files[file] = JSON.stringify(v);
});
return files;
}
|
javascript
|
function (src, dest, content, fileObject) {
var files = {};
_.each(content, function (v, k) {
var file = fileObject.orig.dest + '/' + k + '.json';
files[file] = JSON.stringify(v);
});
return files;
}
|
[
"function",
"(",
"src",
",",
"dest",
",",
"content",
",",
"fileObject",
")",
"{",
"var",
"files",
"=",
"{",
"}",
";",
"_",
".",
"each",
"(",
"content",
",",
"function",
"(",
"v",
",",
"k",
")",
"{",
"var",
"file",
"=",
"fileObject",
".",
"orig",
".",
"dest",
"+",
"'/'",
"+",
"k",
"+",
"'.json'",
";",
"files",
"[",
"file",
"]",
"=",
"JSON",
".",
"stringify",
"(",
"v",
")",
";",
"}",
")",
";",
"return",
"files",
";",
"}"
] |
split json by object key
|
[
"split",
"json",
"by",
"object",
"key"
] |
1e9f87b85a1a6ec1549027d5a07f57e21a7a3710
|
https://github.com/aliaksandr-master/grunt-process/blob/1e9f87b85a1a6ec1549027d5a07f57e21a7a3710/Gruntfile.js#L71-L81
|
|
50,733
|
emeryrose/noisegen
|
lib/random-stream.js
|
RandomStream
|
function RandomStream(options) {
if (!(this instanceof RandomStream)) {
return new RandomStream(options);
}
this._options = merge(Object.create(RandomStream.DEFAULTS), options);
assert(typeof this._options.length === 'number', 'Invalid length supplied');
assert(typeof this._options.size === 'number', 'Invalid size supplied');
assert(typeof this._options.hash === 'string', 'Invalid hash alg supplied');
this.hash = crypto.createHash(this._options.hash);
this.bytes = 0;
ReadableStream.call(this);
}
|
javascript
|
function RandomStream(options) {
if (!(this instanceof RandomStream)) {
return new RandomStream(options);
}
this._options = merge(Object.create(RandomStream.DEFAULTS), options);
assert(typeof this._options.length === 'number', 'Invalid length supplied');
assert(typeof this._options.size === 'number', 'Invalid size supplied');
assert(typeof this._options.hash === 'string', 'Invalid hash alg supplied');
this.hash = crypto.createHash(this._options.hash);
this.bytes = 0;
ReadableStream.call(this);
}
|
[
"function",
"RandomStream",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"RandomStream",
")",
")",
"{",
"return",
"new",
"RandomStream",
"(",
"options",
")",
";",
"}",
"this",
".",
"_options",
"=",
"merge",
"(",
"Object",
".",
"create",
"(",
"RandomStream",
".",
"DEFAULTS",
")",
",",
"options",
")",
";",
"assert",
"(",
"typeof",
"this",
".",
"_options",
".",
"length",
"===",
"'number'",
",",
"'Invalid length supplied'",
")",
";",
"assert",
"(",
"typeof",
"this",
".",
"_options",
".",
"size",
"===",
"'number'",
",",
"'Invalid size supplied'",
")",
";",
"assert",
"(",
"typeof",
"this",
".",
"_options",
".",
"hash",
"===",
"'string'",
",",
"'Invalid hash alg supplied'",
")",
";",
"this",
".",
"hash",
"=",
"crypto",
".",
"createHash",
"(",
"this",
".",
"_options",
".",
"hash",
")",
";",
"this",
".",
"bytes",
"=",
"0",
";",
"ReadableStream",
".",
"call",
"(",
"this",
")",
";",
"}"
] |
Create a readable stream of random data
@extends {ReadableStream}
@constructor
@param {Object} options
@param {Number} options.length - The total length of the stream in bytes
@param {Number} options.size - The number of bytes in each data chunk
@param {String} options.hash - The hash algorithm to use
|
[
"Create",
"a",
"readable",
"stream",
"of",
"random",
"data"
] |
aa0f27b080c97922824f281c6614a03455ed418e
|
https://github.com/emeryrose/noisegen/blob/aa0f27b080c97922824f281c6614a03455ed418e/lib/random-stream.js#L18-L33
|
50,734
|
aleclarson/persec
|
index.js
|
psec
|
function psec(name, run) {
const test = { name, run, before: null, after: null }
ctx.tests.push(test)
ctx.run()
return {
beforeEach(fn) {
test.before = fn
return this
},
afterEach(fn) {
test.after = fn
return this
},
}
}
|
javascript
|
function psec(name, run) {
const test = { name, run, before: null, after: null }
ctx.tests.push(test)
ctx.run()
return {
beforeEach(fn) {
test.before = fn
return this
},
afterEach(fn) {
test.after = fn
return this
},
}
}
|
[
"function",
"psec",
"(",
"name",
",",
"run",
")",
"{",
"const",
"test",
"=",
"{",
"name",
",",
"run",
",",
"before",
":",
"null",
",",
"after",
":",
"null",
"}",
"ctx",
".",
"tests",
".",
"push",
"(",
"test",
")",
"ctx",
".",
"run",
"(",
")",
"return",
"{",
"beforeEach",
"(",
"fn",
")",
"{",
"test",
".",
"before",
"=",
"fn",
"return",
"this",
"}",
",",
"afterEach",
"(",
"fn",
")",
"{",
"test",
".",
"after",
"=",
"fn",
"return",
"this",
"}",
",",
"}",
"}"
] |
Register a test to cycle
|
[
"Register",
"a",
"test",
"to",
"cycle"
] |
c9da078c485319f536c88a39f366e692c67e831f
|
https://github.com/aleclarson/persec/blob/c9da078c485319f536c88a39f366e692c67e831f/index.js#L37-L51
|
50,735
|
aleclarson/persec
|
index.js
|
flush
|
function flush() {
if (queue.length) {
let bench = queue[0]
process.nextTick(() => {
run(bench).then(() => {
queue.shift()
flush()
}, console.error)
})
}
}
|
javascript
|
function flush() {
if (queue.length) {
let bench = queue[0]
process.nextTick(() => {
run(bench).then(() => {
queue.shift()
flush()
}, console.error)
})
}
}
|
[
"function",
"flush",
"(",
")",
"{",
"if",
"(",
"queue",
".",
"length",
")",
"{",
"let",
"bench",
"=",
"queue",
"[",
"0",
"]",
"process",
".",
"nextTick",
"(",
"(",
")",
"=>",
"{",
"run",
"(",
"bench",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"queue",
".",
"shift",
"(",
")",
"flush",
"(",
")",
"}",
",",
"console",
".",
"error",
")",
"}",
")",
"}",
"}"
] |
Internal
Flush the benchmark queue
|
[
"Internal",
"Flush",
"the",
"benchmark",
"queue"
] |
c9da078c485319f536c88a39f366e692c67e831f
|
https://github.com/aleclarson/persec/blob/c9da078c485319f536c88a39f366e692c67e831f/index.js#L124-L134
|
50,736
|
aleclarson/persec
|
index.js
|
run
|
async function run(bench) {
let { tests, config } = bench
if (tests.length == 0) {
throw Error('Benchmark has no test cycles')
}
// Find the longest test name.
config.width = tests.reduce(longest, 0)
let cycles = {}
for (let i = 0; i < tests.length; i++) {
const test = tests[i]
try {
cycles[test.name] = await measure(test, bench)
} catch (e) {
config.onError(e)
}
}
// all done!
config.onFinish(cycles)
bench.done(cycles)
}
|
javascript
|
async function run(bench) {
let { tests, config } = bench
if (tests.length == 0) {
throw Error('Benchmark has no test cycles')
}
// Find the longest test name.
config.width = tests.reduce(longest, 0)
let cycles = {}
for (let i = 0; i < tests.length; i++) {
const test = tests[i]
try {
cycles[test.name] = await measure(test, bench)
} catch (e) {
config.onError(e)
}
}
// all done!
config.onFinish(cycles)
bench.done(cycles)
}
|
[
"async",
"function",
"run",
"(",
"bench",
")",
"{",
"let",
"{",
"tests",
",",
"config",
"}",
"=",
"bench",
"if",
"(",
"tests",
".",
"length",
"==",
"0",
")",
"{",
"throw",
"Error",
"(",
"'Benchmark has no test cycles'",
")",
"}",
"// Find the longest test name.",
"config",
".",
"width",
"=",
"tests",
".",
"reduce",
"(",
"longest",
",",
"0",
")",
"let",
"cycles",
"=",
"{",
"}",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"tests",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"test",
"=",
"tests",
"[",
"i",
"]",
"try",
"{",
"cycles",
"[",
"test",
".",
"name",
"]",
"=",
"await",
"measure",
"(",
"test",
",",
"bench",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"config",
".",
"onError",
"(",
"e",
")",
"}",
"}",
"// all done!",
"config",
".",
"onFinish",
"(",
"cycles",
")",
"bench",
".",
"done",
"(",
"cycles",
")",
"}"
] |
Run a benchmark
|
[
"Run",
"a",
"benchmark"
] |
c9da078c485319f536c88a39f366e692c67e831f
|
https://github.com/aleclarson/persec/blob/c9da078c485319f536c88a39f366e692c67e831f/index.js#L137-L160
|
50,737
|
aleclarson/persec
|
index.js
|
measure
|
async function measure(test, bench) {
let {
delay,
minTime,
minSamples,
minWarmups,
onCycle,
onSample,
} = bench.config
let { name, run } = test
delay *= 1e3
minTime *= 1e3
let samples = []
let cycle = {
name, // test name
hz: null, // samples per second
size: null, // number of samples
time: null, // elapsed time (including delays)
stats: null,
}
let n = 0
let t = process.hrtime()
let warmups = -1
// synchronous test
if (run.length == 0) {
let start
while (true) {
bench.before.forEach(call)
if (test.before) test.before()
start = process.hrtime()
run()
let sample = clock(start)
if (test.after) test.after()
bench.after.forEach(call)
if (warmups == -1) {
warmups = Math.max(minWarmups, sample > 100 ? 1 : sample > 10 ? 5 : 50)
}
if (warmups > 0) {
warmups--
} else {
samples[n++] = sample
onSample(samples[n - 1], cycle)
if (minTime <= clock(t) && minSamples <= n) {
break // all done!
}
}
// wait then repeat
await wait(delay)
}
}
// asynchronous test
else {
let start
const next = function() {
bench.before.forEach(call)
if (test.before) test.before()
start = process.hrtime()
run(done)
}
// called by the test function for every sample
const done = function() {
let sample = clock(start)
if (test.after) test.after()
bench.after.forEach(call)
if (warmups == -1) {
warmups = Math.max(minWarmups, sample > 100 ? 1 : sample > 10 ? 5 : 50)
}
if (warmups > 0) {
warmups--
} else {
samples[n++] = sample
onSample(samples[n - 1], cycle)
if (minTime <= clock(t) && minSamples <= n) {
return cycle.done() // all done!
}
}
// wait then repeat
wait(delay).then(next)
}
defer(cycle) // wrap cycle with a promise
next() // get the first sample
// wait for samples
await cycle.promise
}
const time = clock(t)
const stats = analyze(samples)
cycle.hz = 1000 / stats.mean
cycle.size = n
cycle.time = time
cycle.stats = stats
onCycle(cycle, bench.config)
}
|
javascript
|
async function measure(test, bench) {
let {
delay,
minTime,
minSamples,
minWarmups,
onCycle,
onSample,
} = bench.config
let { name, run } = test
delay *= 1e3
minTime *= 1e3
let samples = []
let cycle = {
name, // test name
hz: null, // samples per second
size: null, // number of samples
time: null, // elapsed time (including delays)
stats: null,
}
let n = 0
let t = process.hrtime()
let warmups = -1
// synchronous test
if (run.length == 0) {
let start
while (true) {
bench.before.forEach(call)
if (test.before) test.before()
start = process.hrtime()
run()
let sample = clock(start)
if (test.after) test.after()
bench.after.forEach(call)
if (warmups == -1) {
warmups = Math.max(minWarmups, sample > 100 ? 1 : sample > 10 ? 5 : 50)
}
if (warmups > 0) {
warmups--
} else {
samples[n++] = sample
onSample(samples[n - 1], cycle)
if (minTime <= clock(t) && minSamples <= n) {
break // all done!
}
}
// wait then repeat
await wait(delay)
}
}
// asynchronous test
else {
let start
const next = function() {
bench.before.forEach(call)
if (test.before) test.before()
start = process.hrtime()
run(done)
}
// called by the test function for every sample
const done = function() {
let sample = clock(start)
if (test.after) test.after()
bench.after.forEach(call)
if (warmups == -1) {
warmups = Math.max(minWarmups, sample > 100 ? 1 : sample > 10 ? 5 : 50)
}
if (warmups > 0) {
warmups--
} else {
samples[n++] = sample
onSample(samples[n - 1], cycle)
if (minTime <= clock(t) && minSamples <= n) {
return cycle.done() // all done!
}
}
// wait then repeat
wait(delay).then(next)
}
defer(cycle) // wrap cycle with a promise
next() // get the first sample
// wait for samples
await cycle.promise
}
const time = clock(t)
const stats = analyze(samples)
cycle.hz = 1000 / stats.mean
cycle.size = n
cycle.time = time
cycle.stats = stats
onCycle(cycle, bench.config)
}
|
[
"async",
"function",
"measure",
"(",
"test",
",",
"bench",
")",
"{",
"let",
"{",
"delay",
",",
"minTime",
",",
"minSamples",
",",
"minWarmups",
",",
"onCycle",
",",
"onSample",
",",
"}",
"=",
"bench",
".",
"config",
"let",
"{",
"name",
",",
"run",
"}",
"=",
"test",
"delay",
"*=",
"1e3",
"minTime",
"*=",
"1e3",
"let",
"samples",
"=",
"[",
"]",
"let",
"cycle",
"=",
"{",
"name",
",",
"// test name",
"hz",
":",
"null",
",",
"// samples per second",
"size",
":",
"null",
",",
"// number of samples",
"time",
":",
"null",
",",
"// elapsed time (including delays)",
"stats",
":",
"null",
",",
"}",
"let",
"n",
"=",
"0",
"let",
"t",
"=",
"process",
".",
"hrtime",
"(",
")",
"let",
"warmups",
"=",
"-",
"1",
"// synchronous test",
"if",
"(",
"run",
".",
"length",
"==",
"0",
")",
"{",
"let",
"start",
"while",
"(",
"true",
")",
"{",
"bench",
".",
"before",
".",
"forEach",
"(",
"call",
")",
"if",
"(",
"test",
".",
"before",
")",
"test",
".",
"before",
"(",
")",
"start",
"=",
"process",
".",
"hrtime",
"(",
")",
"run",
"(",
")",
"let",
"sample",
"=",
"clock",
"(",
"start",
")",
"if",
"(",
"test",
".",
"after",
")",
"test",
".",
"after",
"(",
")",
"bench",
".",
"after",
".",
"forEach",
"(",
"call",
")",
"if",
"(",
"warmups",
"==",
"-",
"1",
")",
"{",
"warmups",
"=",
"Math",
".",
"max",
"(",
"minWarmups",
",",
"sample",
">",
"100",
"?",
"1",
":",
"sample",
">",
"10",
"?",
"5",
":",
"50",
")",
"}",
"if",
"(",
"warmups",
">",
"0",
")",
"{",
"warmups",
"--",
"}",
"else",
"{",
"samples",
"[",
"n",
"++",
"]",
"=",
"sample",
"onSample",
"(",
"samples",
"[",
"n",
"-",
"1",
"]",
",",
"cycle",
")",
"if",
"(",
"minTime",
"<=",
"clock",
"(",
"t",
")",
"&&",
"minSamples",
"<=",
"n",
")",
"{",
"break",
"// all done!",
"}",
"}",
"// wait then repeat",
"await",
"wait",
"(",
"delay",
")",
"}",
"}",
"// asynchronous test",
"else",
"{",
"let",
"start",
"const",
"next",
"=",
"function",
"(",
")",
"{",
"bench",
".",
"before",
".",
"forEach",
"(",
"call",
")",
"if",
"(",
"test",
".",
"before",
")",
"test",
".",
"before",
"(",
")",
"start",
"=",
"process",
".",
"hrtime",
"(",
")",
"run",
"(",
"done",
")",
"}",
"// called by the test function for every sample",
"const",
"done",
"=",
"function",
"(",
")",
"{",
"let",
"sample",
"=",
"clock",
"(",
"start",
")",
"if",
"(",
"test",
".",
"after",
")",
"test",
".",
"after",
"(",
")",
"bench",
".",
"after",
".",
"forEach",
"(",
"call",
")",
"if",
"(",
"warmups",
"==",
"-",
"1",
")",
"{",
"warmups",
"=",
"Math",
".",
"max",
"(",
"minWarmups",
",",
"sample",
">",
"100",
"?",
"1",
":",
"sample",
">",
"10",
"?",
"5",
":",
"50",
")",
"}",
"if",
"(",
"warmups",
">",
"0",
")",
"{",
"warmups",
"--",
"}",
"else",
"{",
"samples",
"[",
"n",
"++",
"]",
"=",
"sample",
"onSample",
"(",
"samples",
"[",
"n",
"-",
"1",
"]",
",",
"cycle",
")",
"if",
"(",
"minTime",
"<=",
"clock",
"(",
"t",
")",
"&&",
"minSamples",
"<=",
"n",
")",
"{",
"return",
"cycle",
".",
"done",
"(",
")",
"// all done!",
"}",
"}",
"// wait then repeat",
"wait",
"(",
"delay",
")",
".",
"then",
"(",
"next",
")",
"}",
"defer",
"(",
"cycle",
")",
"// wrap cycle with a promise",
"next",
"(",
")",
"// get the first sample",
"// wait for samples",
"await",
"cycle",
".",
"promise",
"}",
"const",
"time",
"=",
"clock",
"(",
"t",
")",
"const",
"stats",
"=",
"analyze",
"(",
"samples",
")",
"cycle",
".",
"hz",
"=",
"1000",
"/",
"stats",
".",
"mean",
"cycle",
".",
"size",
"=",
"n",
"cycle",
".",
"time",
"=",
"time",
"cycle",
".",
"stats",
"=",
"stats",
"onCycle",
"(",
"cycle",
",",
"bench",
".",
"config",
")",
"}"
] |
Measure a performance test
|
[
"Measure",
"a",
"performance",
"test"
] |
c9da078c485319f536c88a39f366e692c67e831f
|
https://github.com/aleclarson/persec/blob/c9da078c485319f536c88a39f366e692c67e831f/index.js#L163-L274
|
50,738
|
aleclarson/persec
|
index.js
|
function() {
let sample = clock(start)
if (test.after) test.after()
bench.after.forEach(call)
if (warmups == -1) {
warmups = Math.max(minWarmups, sample > 100 ? 1 : sample > 10 ? 5 : 50)
}
if (warmups > 0) {
warmups--
} else {
samples[n++] = sample
onSample(samples[n - 1], cycle)
if (minTime <= clock(t) && minSamples <= n) {
return cycle.done() // all done!
}
}
// wait then repeat
wait(delay).then(next)
}
|
javascript
|
function() {
let sample = clock(start)
if (test.after) test.after()
bench.after.forEach(call)
if (warmups == -1) {
warmups = Math.max(minWarmups, sample > 100 ? 1 : sample > 10 ? 5 : 50)
}
if (warmups > 0) {
warmups--
} else {
samples[n++] = sample
onSample(samples[n - 1], cycle)
if (minTime <= clock(t) && minSamples <= n) {
return cycle.done() // all done!
}
}
// wait then repeat
wait(delay).then(next)
}
|
[
"function",
"(",
")",
"{",
"let",
"sample",
"=",
"clock",
"(",
"start",
")",
"if",
"(",
"test",
".",
"after",
")",
"test",
".",
"after",
"(",
")",
"bench",
".",
"after",
".",
"forEach",
"(",
"call",
")",
"if",
"(",
"warmups",
"==",
"-",
"1",
")",
"{",
"warmups",
"=",
"Math",
".",
"max",
"(",
"minWarmups",
",",
"sample",
">",
"100",
"?",
"1",
":",
"sample",
">",
"10",
"?",
"5",
":",
"50",
")",
"}",
"if",
"(",
"warmups",
">",
"0",
")",
"{",
"warmups",
"--",
"}",
"else",
"{",
"samples",
"[",
"n",
"++",
"]",
"=",
"sample",
"onSample",
"(",
"samples",
"[",
"n",
"-",
"1",
"]",
",",
"cycle",
")",
"if",
"(",
"minTime",
"<=",
"clock",
"(",
"t",
")",
"&&",
"minSamples",
"<=",
"n",
")",
"{",
"return",
"cycle",
".",
"done",
"(",
")",
"// all done!",
"}",
"}",
"// wait then repeat",
"wait",
"(",
"delay",
")",
".",
"then",
"(",
"next",
")",
"}"
] |
called by the test function for every sample
|
[
"called",
"by",
"the",
"test",
"function",
"for",
"every",
"sample"
] |
c9da078c485319f536c88a39f366e692c67e831f
|
https://github.com/aleclarson/persec/blob/c9da078c485319f536c88a39f366e692c67e831f/index.js#L235-L257
|
|
50,739
|
aleclarson/persec
|
index.js
|
onCycle
|
function onCycle(cycle, opts) {
let hz = Math.round(cycle.hz).toLocaleString()
let rme = '\xb1' + cycle.stats.rme.toFixed(2) + '%'
// add colors
hz = color(34) + hz + color(0)
rme = color(33) + rme + color(0)
const padding = ' '.repeat(opts.width - cycle.name.length)
console.log(`${cycle.name}${padding} ${hz} ops/sec ${rme}`)
}
|
javascript
|
function onCycle(cycle, opts) {
let hz = Math.round(cycle.hz).toLocaleString()
let rme = '\xb1' + cycle.stats.rme.toFixed(2) + '%'
// add colors
hz = color(34) + hz + color(0)
rme = color(33) + rme + color(0)
const padding = ' '.repeat(opts.width - cycle.name.length)
console.log(`${cycle.name}${padding} ${hz} ops/sec ${rme}`)
}
|
[
"function",
"onCycle",
"(",
"cycle",
",",
"opts",
")",
"{",
"let",
"hz",
"=",
"Math",
".",
"round",
"(",
"cycle",
".",
"hz",
")",
".",
"toLocaleString",
"(",
")",
"let",
"rme",
"=",
"'\\xb1'",
"+",
"cycle",
".",
"stats",
".",
"rme",
".",
"toFixed",
"(",
"2",
")",
"+",
"'%'",
"// add colors",
"hz",
"=",
"color",
"(",
"34",
")",
"+",
"hz",
"+",
"color",
"(",
"0",
")",
"rme",
"=",
"color",
"(",
"33",
")",
"+",
"rme",
"+",
"color",
"(",
"0",
")",
"const",
"padding",
"=",
"' '",
".",
"repeat",
"(",
"opts",
".",
"width",
"-",
"cycle",
".",
"name",
".",
"length",
")",
"console",
".",
"log",
"(",
"`",
"${",
"cycle",
".",
"name",
"}",
"${",
"padding",
"}",
"${",
"hz",
"}",
"${",
"rme",
"}",
"`",
")",
"}"
] |
default cycle reporter
|
[
"default",
"cycle",
"reporter"
] |
c9da078c485319f536c88a39f366e692c67e831f
|
https://github.com/aleclarson/persec/blob/c9da078c485319f536c88a39f366e692c67e831f/index.js#L387-L397
|
50,740
|
antoniobrandao/mongoose3-bsonfix-bson
|
lib/bson/binary.js
|
Binary
|
function Binary(buffer, subType) {
if(!(this instanceof Binary)) return new Binary(buffer, subType);
this._bsontype = 'Binary';
if(buffer instanceof Number) {
this.sub_type = buffer;
this.position = 0;
} else {
this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType;
this.position = 0;
}
if(buffer != null && !(buffer instanceof Number)) {
// Only accept Buffer, Uint8Array or Arrays
if(typeof buffer == 'string') {
// Different ways of writing the length of the string for the different types
if(typeof Buffer != 'undefined') {
this.buffer = new Buffer(buffer);
} else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) {
this.buffer = writeStringToArray(buffer);
} else {
throw new Error("only String, Buffer, Uint8Array or Array accepted");
}
} else {
this.buffer = buffer;
}
this.position = buffer.length;
} else {
if(typeof Buffer != 'undefined') {
this.buffer = new Buffer(Binary.BUFFER_SIZE);
} else if(typeof Uint8Array != 'undefined'){
this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE));
} else {
this.buffer = new Array(Binary.BUFFER_SIZE);
}
// Set position to start of buffer
this.position = 0;
}
}
|
javascript
|
function Binary(buffer, subType) {
if(!(this instanceof Binary)) return new Binary(buffer, subType);
this._bsontype = 'Binary';
if(buffer instanceof Number) {
this.sub_type = buffer;
this.position = 0;
} else {
this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType;
this.position = 0;
}
if(buffer != null && !(buffer instanceof Number)) {
// Only accept Buffer, Uint8Array or Arrays
if(typeof buffer == 'string') {
// Different ways of writing the length of the string for the different types
if(typeof Buffer != 'undefined') {
this.buffer = new Buffer(buffer);
} else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) {
this.buffer = writeStringToArray(buffer);
} else {
throw new Error("only String, Buffer, Uint8Array or Array accepted");
}
} else {
this.buffer = buffer;
}
this.position = buffer.length;
} else {
if(typeof Buffer != 'undefined') {
this.buffer = new Buffer(Binary.BUFFER_SIZE);
} else if(typeof Uint8Array != 'undefined'){
this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE));
} else {
this.buffer = new Array(Binary.BUFFER_SIZE);
}
// Set position to start of buffer
this.position = 0;
}
}
|
[
"function",
"Binary",
"(",
"buffer",
",",
"subType",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Binary",
")",
")",
"return",
"new",
"Binary",
"(",
"buffer",
",",
"subType",
")",
";",
"this",
".",
"_bsontype",
"=",
"'Binary'",
";",
"if",
"(",
"buffer",
"instanceof",
"Number",
")",
"{",
"this",
".",
"sub_type",
"=",
"buffer",
";",
"this",
".",
"position",
"=",
"0",
";",
"}",
"else",
"{",
"this",
".",
"sub_type",
"=",
"subType",
"==",
"null",
"?",
"BSON_BINARY_SUBTYPE_DEFAULT",
":",
"subType",
";",
"this",
".",
"position",
"=",
"0",
";",
"}",
"if",
"(",
"buffer",
"!=",
"null",
"&&",
"!",
"(",
"buffer",
"instanceof",
"Number",
")",
")",
"{",
"// Only accept Buffer, Uint8Array or Arrays",
"if",
"(",
"typeof",
"buffer",
"==",
"'string'",
")",
"{",
"// Different ways of writing the length of the string for the different types",
"if",
"(",
"typeof",
"Buffer",
"!=",
"'undefined'",
")",
"{",
"this",
".",
"buffer",
"=",
"new",
"Buffer",
"(",
"buffer",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"Uint8Array",
"!=",
"'undefined'",
"||",
"(",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"buffer",
")",
"==",
"'[object Array]'",
")",
")",
"{",
"this",
".",
"buffer",
"=",
"writeStringToArray",
"(",
"buffer",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"only String, Buffer, Uint8Array or Array accepted\"",
")",
";",
"}",
"}",
"else",
"{",
"this",
".",
"buffer",
"=",
"buffer",
";",
"}",
"this",
".",
"position",
"=",
"buffer",
".",
"length",
";",
"}",
"else",
"{",
"if",
"(",
"typeof",
"Buffer",
"!=",
"'undefined'",
")",
"{",
"this",
".",
"buffer",
"=",
"new",
"Buffer",
"(",
"Binary",
".",
"BUFFER_SIZE",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"Uint8Array",
"!=",
"'undefined'",
")",
"{",
"this",
".",
"buffer",
"=",
"new",
"Uint8Array",
"(",
"new",
"ArrayBuffer",
"(",
"Binary",
".",
"BUFFER_SIZE",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"buffer",
"=",
"new",
"Array",
"(",
"Binary",
".",
"BUFFER_SIZE",
")",
";",
"}",
"// Set position to start of buffer",
"this",
".",
"position",
"=",
"0",
";",
"}",
"}"
] |
A class representation of the BSON Binary type.
Sub types
- **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type.
- **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type.
- **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type.
- **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type.
- **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type.
- **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type.
@class
@param {Buffer} buffer a buffer object containing the binary data.
@param {Number} [subType] the option binary type.
@return {Binary}
|
[
"A",
"class",
"representation",
"of",
"the",
"BSON",
"Binary",
"type",
"."
] |
b0eae261710704de70f6f282669cf020dbd6a490
|
https://github.com/antoniobrandao/mongoose3-bsonfix-bson/blob/b0eae261710704de70f6f282669cf020dbd6a490/lib/bson/binary.js#L25-L64
|
50,741
|
jmjuanes/minsql
|
lib/query/update.js
|
QueryUpdate
|
function QueryUpdate(data)
{
//Initialize the set
var set = '';
//Get all data
for(var key in data)
{
//Save data value
var value = data[key];
//Check the data type
if(typeof value === 'string' || value instanceof String)
{
//Add the quotes
value = '"' + value + '"';
}
//Check if is necessary add the comma
if(set !== '')
{
//Add the comma
set = set + ' , ';
}
//Add the key=value
set = set + key + '=' + value;
}
//Return
return set;
}
|
javascript
|
function QueryUpdate(data)
{
//Initialize the set
var set = '';
//Get all data
for(var key in data)
{
//Save data value
var value = data[key];
//Check the data type
if(typeof value === 'string' || value instanceof String)
{
//Add the quotes
value = '"' + value + '"';
}
//Check if is necessary add the comma
if(set !== '')
{
//Add the comma
set = set + ' , ';
}
//Add the key=value
set = set + key + '=' + value;
}
//Return
return set;
}
|
[
"function",
"QueryUpdate",
"(",
"data",
")",
"{",
"//Initialize the set\r",
"var",
"set",
"=",
"''",
";",
"//Get all data\r",
"for",
"(",
"var",
"key",
"in",
"data",
")",
"{",
"//Save data value\r",
"var",
"value",
"=",
"data",
"[",
"key",
"]",
";",
"//Check the data type\r",
"if",
"(",
"typeof",
"value",
"===",
"'string'",
"||",
"value",
"instanceof",
"String",
")",
"{",
"//Add the quotes\r",
"value",
"=",
"'\"'",
"+",
"value",
"+",
"'\"'",
";",
"}",
"//Check if is necessary add the comma\r",
"if",
"(",
"set",
"!==",
"''",
")",
"{",
"//Add the comma\r",
"set",
"=",
"set",
"+",
"' , '",
";",
"}",
"//Add the key=value\r",
"set",
"=",
"set",
"+",
"key",
"+",
"'='",
"+",
"value",
";",
"}",
"//Return\r",
"return",
"set",
";",
"}"
] |
Query for update
|
[
"Query",
"for",
"update"
] |
80eddd97e858545997b30e3c9bc067d5fc2df5a0
|
https://github.com/jmjuanes/minsql/blob/80eddd97e858545997b30e3c9bc067d5fc2df5a0/lib/query/update.js#L2-L33
|
50,742
|
Nazariglez/perenquen
|
lib/pixi/src/filters/color/ColorMatrixFilter.js
|
ColorMatrixFilter
|
function ColorMatrixFilter()
{
core.AbstractFilter.call(this,
// vertex shader
null,
// fragment shader
fs.readFileSync(__dirname + '/colorMatrix.frag', 'utf8'),
// custom uniforms
{
m: { type: '1fv', value: [1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1] },
}
);
}
|
javascript
|
function ColorMatrixFilter()
{
core.AbstractFilter.call(this,
// vertex shader
null,
// fragment shader
fs.readFileSync(__dirname + '/colorMatrix.frag', 'utf8'),
// custom uniforms
{
m: { type: '1fv', value: [1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1] },
}
);
}
|
[
"function",
"ColorMatrixFilter",
"(",
")",
"{",
"core",
".",
"AbstractFilter",
".",
"call",
"(",
"this",
",",
"// vertex shader",
"null",
",",
"// fragment shader",
"fs",
".",
"readFileSync",
"(",
"__dirname",
"+",
"'/colorMatrix.frag'",
",",
"'utf8'",
")",
",",
"// custom uniforms",
"{",
"m",
":",
"{",
"type",
":",
"'1fv'",
",",
"value",
":",
"[",
"1",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"1",
"]",
"}",
",",
"}",
")",
";",
"}"
] |
The ColorMatrixFilter class lets you apply a 5x5 matrix transformation on the RGBA
color and alpha values of every pixel on your displayObject to produce a result
with a new set of RGBA color and alpha values. It's pretty powerful!
```js
var colorMatrix = new PIXI.ColorMatrixFilter();
container.filters = [colorMatrix];
colorMatrix.contrast(2);
```
@author Clément Chenebault <clement@goodboydigital.com>
@class
@extends AbstractFilter
@memberof PIXI.filters
|
[
"The",
"ColorMatrixFilter",
"class",
"lets",
"you",
"apply",
"a",
"5x5",
"matrix",
"transformation",
"on",
"the",
"RGBA",
"color",
"and",
"alpha",
"values",
"of",
"every",
"pixel",
"on",
"your",
"displayObject",
"to",
"produce",
"a",
"result",
"with",
"a",
"new",
"set",
"of",
"RGBA",
"color",
"and",
"alpha",
"values",
".",
"It",
"s",
"pretty",
"powerful!"
] |
e023964d05afeefebdcac4e2044819fdfa3899ae
|
https://github.com/Nazariglez/perenquen/blob/e023964d05afeefebdcac4e2044819fdfa3899ae/lib/pixi/src/filters/color/ColorMatrixFilter.js#L20-L36
|
50,743
|
redsift/ui-rs-core
|
src/js/xkcd/index.js
|
smooth
|
function smooth(d, w) {
let result = [];
for (let i = 0, l = d.length; i < l; ++i) {
let mn = Math.max(0, i - 5 * w),
mx = Math.min(d.length - 1, i + 5 * w),
s = 0.0;
result[i] = 0.0;
for (let j = mn; j < mx; ++j) {
let wd = Math.exp(-0.5 * (i - j) * (i - j) / w / w);
result[i] += wd * d[j];
s += wd;
}
result[i] /= s;
}
return result;
}
|
javascript
|
function smooth(d, w) {
let result = [];
for (let i = 0, l = d.length; i < l; ++i) {
let mn = Math.max(0, i - 5 * w),
mx = Math.min(d.length - 1, i + 5 * w),
s = 0.0;
result[i] = 0.0;
for (let j = mn; j < mx; ++j) {
let wd = Math.exp(-0.5 * (i - j) * (i - j) / w / w);
result[i] += wd * d[j];
s += wd;
}
result[i] /= s;
}
return result;
}
|
[
"function",
"smooth",
"(",
"d",
",",
"w",
")",
"{",
"let",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"l",
"=",
"d",
".",
"length",
";",
"i",
"<",
"l",
";",
"++",
"i",
")",
"{",
"let",
"mn",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"i",
"-",
"5",
"*",
"w",
")",
",",
"mx",
"=",
"Math",
".",
"min",
"(",
"d",
".",
"length",
"-",
"1",
",",
"i",
"+",
"5",
"*",
"w",
")",
",",
"s",
"=",
"0.0",
";",
"result",
"[",
"i",
"]",
"=",
"0.0",
";",
"for",
"(",
"let",
"j",
"=",
"mn",
";",
"j",
"<",
"mx",
";",
"++",
"j",
")",
"{",
"let",
"wd",
"=",
"Math",
".",
"exp",
"(",
"-",
"0.5",
"*",
"(",
"i",
"-",
"j",
")",
"*",
"(",
"i",
"-",
"j",
")",
"/",
"w",
"/",
"w",
")",
";",
"result",
"[",
"i",
"]",
"+=",
"wd",
"*",
"d",
"[",
"j",
"]",
";",
"s",
"+=",
"wd",
";",
"}",
"result",
"[",
"i",
"]",
"/=",
"s",
";",
"}",
"return",
"result",
";",
"}"
] |
Smooth some data with a given window size.
|
[
"Smooth",
"some",
"data",
"with",
"a",
"given",
"window",
"size",
"."
] |
9b126fd50ad7ae757303734fc290868ea49c9620
|
https://github.com/redsift/ui-rs-core/blob/9b126fd50ad7ae757303734fc290868ea49c9620/src/js/xkcd/index.js#L2-L17
|
50,744
|
biggora/trinte-creator
|
app/bin/router.js
|
TrinteBridge
|
function TrinteBridge(namespace, controller, action) {
var responseHandler;
if (typeof action === 'function') {
return action;
}
try {
if (/\//.test(controller)) {
var cnts = controller.split('/');
namespace = cnts[0] + '/';
controller = cnts[1];
}
namespace = typeof namespace === 'string' ? namespace.toString().toLowerCase() : '';
controller = controller.pluralize().capitalize();
var crtRoot = './../app/controllers/';
['', 'es', 'ses'].forEach(function (prf) {
var ctlFile = crtRoot + namespace + controller + prf + 'Controller';
if (fileExists(path.resolve(__dirname, ctlFile) + '.js')) {
responseHandler = require(ctlFile)[action];
}
});
} catch (e) {
// console.log( 'Error Route Action: ' + action );
console.log(e);
}
if (!responseHandler) console.log('Bridge not found for ' + namespace + controller + '#' + action);
return responseHandler || function (req, res) {
res.send('Bridge not found for ' + namespace + controller + '#' + action);
};
}
|
javascript
|
function TrinteBridge(namespace, controller, action) {
var responseHandler;
if (typeof action === 'function') {
return action;
}
try {
if (/\//.test(controller)) {
var cnts = controller.split('/');
namespace = cnts[0] + '/';
controller = cnts[1];
}
namespace = typeof namespace === 'string' ? namespace.toString().toLowerCase() : '';
controller = controller.pluralize().capitalize();
var crtRoot = './../app/controllers/';
['', 'es', 'ses'].forEach(function (prf) {
var ctlFile = crtRoot + namespace + controller + prf + 'Controller';
if (fileExists(path.resolve(__dirname, ctlFile) + '.js')) {
responseHandler = require(ctlFile)[action];
}
});
} catch (e) {
// console.log( 'Error Route Action: ' + action );
console.log(e);
}
if (!responseHandler) console.log('Bridge not found for ' + namespace + controller + '#' + action);
return responseHandler || function (req, res) {
res.send('Bridge not found for ' + namespace + controller + '#' + action);
};
}
|
[
"function",
"TrinteBridge",
"(",
"namespace",
",",
"controller",
",",
"action",
")",
"{",
"var",
"responseHandler",
";",
"if",
"(",
"typeof",
"action",
"===",
"'function'",
")",
"{",
"return",
"action",
";",
"}",
"try",
"{",
"if",
"(",
"/",
"\\/",
"/",
".",
"test",
"(",
"controller",
")",
")",
"{",
"var",
"cnts",
"=",
"controller",
".",
"split",
"(",
"'/'",
")",
";",
"namespace",
"=",
"cnts",
"[",
"0",
"]",
"+",
"'/'",
";",
"controller",
"=",
"cnts",
"[",
"1",
"]",
";",
"}",
"namespace",
"=",
"typeof",
"namespace",
"===",
"'string'",
"?",
"namespace",
".",
"toString",
"(",
")",
".",
"toLowerCase",
"(",
")",
":",
"''",
";",
"controller",
"=",
"controller",
".",
"pluralize",
"(",
")",
".",
"capitalize",
"(",
")",
";",
"var",
"crtRoot",
"=",
"'./../app/controllers/'",
";",
"[",
"''",
",",
"'es'",
",",
"'ses'",
"]",
".",
"forEach",
"(",
"function",
"(",
"prf",
")",
"{",
"var",
"ctlFile",
"=",
"crtRoot",
"+",
"namespace",
"+",
"controller",
"+",
"prf",
"+",
"'Controller'",
";",
"if",
"(",
"fileExists",
"(",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"ctlFile",
")",
"+",
"'.js'",
")",
")",
"{",
"responseHandler",
"=",
"require",
"(",
"ctlFile",
")",
"[",
"action",
"]",
";",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// console.log( 'Error Route Action: ' + action );",
"console",
".",
"log",
"(",
"e",
")",
";",
"}",
"if",
"(",
"!",
"responseHandler",
")",
"console",
".",
"log",
"(",
"'Bridge not found for '",
"+",
"namespace",
"+",
"controller",
"+",
"'#'",
"+",
"action",
")",
";",
"return",
"responseHandler",
"||",
"function",
"(",
"req",
",",
"res",
")",
"{",
"res",
".",
"send",
"(",
"'Bridge not found for '",
"+",
"namespace",
"+",
"controller",
"+",
"'#'",
"+",
"action",
")",
";",
"}",
";",
"}"
] |
Some TrinteBridge method that will server requests from
routing map to application
@param {String} namespace
@param {String} controller
@param {String} action
@return {Function} responseHandler
|
[
"Some",
"TrinteBridge",
"method",
"that",
"will",
"server",
"requests",
"from",
"routing",
"map",
"to",
"application"
] |
fdd723405418967ca8a690867940863fd77e636b
|
https://github.com/biggora/trinte-creator/blob/fdd723405418967ca8a690867940863fd77e636b/app/bin/router.js#L16-L44
|
50,745
|
biggora/trinte-creator
|
app/bin/router.js
|
getActiveRoutes
|
function getActiveRoutes(params) {
var activeRoutes = {},
availableRoutes =
{
'index': 'GET /',
'create': 'POST /',
'new': 'GET /new',
'edit': 'GET /:id/edit',
'destroy': 'DELETE /:id',
'update': 'PUT /:id',
'show': 'GET /:id',
'destroyall': 'DELETE /'
},
availableRoutesSingleton =
{
'show': 'GET /show',
'create': 'POST /',
'new': 'GET /new',
'edit': 'GET /edit',
'destroy': 'DELETE /',
'update': 'PUT /',
'destroyall': 'DELETE /'
};
if (params.singleton) {
availableRoutes = availableRoutesSingleton;
}
// 1. only
if (params.only) {
if (typeof params.only === 'string') {
params.only = [params.only];
}
params.only.forEach(function (action) {
if (action in availableRoutes) {
activeRoutes[action] = availableRoutes[action];
}
});
}
// 2. except
else if (params.except) {
if (typeof params.except === 'string') {
params.except = [params.except];
}
for (var action1 in availableRoutes) {
if (params.except.indexOf(action1) === -1) {
activeRoutes[action1] = availableRoutes[action1];
}
}
}
// 3. all
else {
for (var action2 in availableRoutes) {
activeRoutes[action2] = availableRoutes[action2];
}
}
return activeRoutes;
}
|
javascript
|
function getActiveRoutes(params) {
var activeRoutes = {},
availableRoutes =
{
'index': 'GET /',
'create': 'POST /',
'new': 'GET /new',
'edit': 'GET /:id/edit',
'destroy': 'DELETE /:id',
'update': 'PUT /:id',
'show': 'GET /:id',
'destroyall': 'DELETE /'
},
availableRoutesSingleton =
{
'show': 'GET /show',
'create': 'POST /',
'new': 'GET /new',
'edit': 'GET /edit',
'destroy': 'DELETE /',
'update': 'PUT /',
'destroyall': 'DELETE /'
};
if (params.singleton) {
availableRoutes = availableRoutesSingleton;
}
// 1. only
if (params.only) {
if (typeof params.only === 'string') {
params.only = [params.only];
}
params.only.forEach(function (action) {
if (action in availableRoutes) {
activeRoutes[action] = availableRoutes[action];
}
});
}
// 2. except
else if (params.except) {
if (typeof params.except === 'string') {
params.except = [params.except];
}
for (var action1 in availableRoutes) {
if (params.except.indexOf(action1) === -1) {
activeRoutes[action1] = availableRoutes[action1];
}
}
}
// 3. all
else {
for (var action2 in availableRoutes) {
activeRoutes[action2] = availableRoutes[action2];
}
}
return activeRoutes;
}
|
[
"function",
"getActiveRoutes",
"(",
"params",
")",
"{",
"var",
"activeRoutes",
"=",
"{",
"}",
",",
"availableRoutes",
"=",
"{",
"'index'",
":",
"'GET /'",
",",
"'create'",
":",
"'POST /'",
",",
"'new'",
":",
"'GET /new'",
",",
"'edit'",
":",
"'GET /:id/edit'",
",",
"'destroy'",
":",
"'DELETE /:id'",
",",
"'update'",
":",
"'PUT /:id'",
",",
"'show'",
":",
"'GET /:id'",
",",
"'destroyall'",
":",
"'DELETE /'",
"}",
",",
"availableRoutesSingleton",
"=",
"{",
"'show'",
":",
"'GET /show'",
",",
"'create'",
":",
"'POST /'",
",",
"'new'",
":",
"'GET /new'",
",",
"'edit'",
":",
"'GET /edit'",
",",
"'destroy'",
":",
"'DELETE /'",
",",
"'update'",
":",
"'PUT /'",
",",
"'destroyall'",
":",
"'DELETE /'",
"}",
";",
"if",
"(",
"params",
".",
"singleton",
")",
"{",
"availableRoutes",
"=",
"availableRoutesSingleton",
";",
"}",
"// 1. only",
"if",
"(",
"params",
".",
"only",
")",
"{",
"if",
"(",
"typeof",
"params",
".",
"only",
"===",
"'string'",
")",
"{",
"params",
".",
"only",
"=",
"[",
"params",
".",
"only",
"]",
";",
"}",
"params",
".",
"only",
".",
"forEach",
"(",
"function",
"(",
"action",
")",
"{",
"if",
"(",
"action",
"in",
"availableRoutes",
")",
"{",
"activeRoutes",
"[",
"action",
"]",
"=",
"availableRoutes",
"[",
"action",
"]",
";",
"}",
"}",
")",
";",
"}",
"// 2. except",
"else",
"if",
"(",
"params",
".",
"except",
")",
"{",
"if",
"(",
"typeof",
"params",
".",
"except",
"===",
"'string'",
")",
"{",
"params",
".",
"except",
"=",
"[",
"params",
".",
"except",
"]",
";",
"}",
"for",
"(",
"var",
"action1",
"in",
"availableRoutes",
")",
"{",
"if",
"(",
"params",
".",
"except",
".",
"indexOf",
"(",
"action1",
")",
"===",
"-",
"1",
")",
"{",
"activeRoutes",
"[",
"action1",
"]",
"=",
"availableRoutes",
"[",
"action1",
"]",
";",
"}",
"}",
"}",
"// 3. all",
"else",
"{",
"for",
"(",
"var",
"action2",
"in",
"availableRoutes",
")",
"{",
"activeRoutes",
"[",
"action2",
"]",
"=",
"availableRoutes",
"[",
"action2",
"]",
";",
"}",
"}",
"return",
"activeRoutes",
";",
"}"
] |
calculate set of routes based on params.only and params.except
|
[
"calculate",
"set",
"of",
"routes",
"based",
"on",
"params",
".",
"only",
"and",
"params",
".",
"except"
] |
fdd723405418967ca8a690867940863fd77e636b
|
https://github.com/biggora/trinte-creator/blob/fdd723405418967ca8a690867940863fd77e636b/app/bin/router.js#L392-L450
|
50,746
|
angelozerr/tern-yui3
|
generator/yuidoc2tern.js
|
function(yuiType, c) {
var index = yuiType.indexOf(c);
if (index != -1) {
yuiType = yuiType.substring(0, index);
yuiType = yuiType.trim();
}
return yuiType;
}
|
javascript
|
function(yuiType, c) {
var index = yuiType.indexOf(c);
if (index != -1) {
yuiType = yuiType.substring(0, index);
yuiType = yuiType.trim();
}
return yuiType;
}
|
[
"function",
"(",
"yuiType",
",",
"c",
")",
"{",
"var",
"index",
"=",
"yuiType",
".",
"indexOf",
"(",
"c",
")",
";",
"if",
"(",
"index",
"!=",
"-",
"1",
")",
"{",
"yuiType",
"=",
"yuiType",
".",
"substring",
"(",
"0",
",",
"index",
")",
";",
"yuiType",
"=",
"yuiType",
".",
"trim",
"(",
")",
";",
"}",
"return",
"yuiType",
";",
"}"
] |
YUI -> Tern type
|
[
"YUI",
"-",
">",
"Tern",
"type"
] |
9fc454aa0e426cd2eb713d8320c1d9ecd019bd1a
|
https://github.com/angelozerr/tern-yui3/blob/9fc454aa0e426cd2eb713d8320c1d9ecd019bd1a/generator/yuidoc2tern.js#L287-L294
|
|
50,747
|
AndreasMadsen/thintalk
|
lib/core/requester.js
|
request
|
function request(ipc, name, args) {
// check online
if (!ipc.root.online) {
ipc.root.emit('error', new Error("Could not make a request, channel is offline"));
return;
}
// store callback for later
var callback = args.pop();
// check that a callback is set
if (typeof callback !== 'function') {
ipc.root.emit('error', new TypeError("No callback specified"));
return;
}
// send request to remote
ipc.send('call', [name, args], function (sucess, content) {
if (sucess) {
callback.apply({
error: null
}, content);
} else {
callback.apply({
error: helpers.object2error(content)
}, []);
}
});
}
|
javascript
|
function request(ipc, name, args) {
// check online
if (!ipc.root.online) {
ipc.root.emit('error', new Error("Could not make a request, channel is offline"));
return;
}
// store callback for later
var callback = args.pop();
// check that a callback is set
if (typeof callback !== 'function') {
ipc.root.emit('error', new TypeError("No callback specified"));
return;
}
// send request to remote
ipc.send('call', [name, args], function (sucess, content) {
if (sucess) {
callback.apply({
error: null
}, content);
} else {
callback.apply({
error: helpers.object2error(content)
}, []);
}
});
}
|
[
"function",
"request",
"(",
"ipc",
",",
"name",
",",
"args",
")",
"{",
"// check online",
"if",
"(",
"!",
"ipc",
".",
"root",
".",
"online",
")",
"{",
"ipc",
".",
"root",
".",
"emit",
"(",
"'error'",
",",
"new",
"Error",
"(",
"\"Could not make a request, channel is offline\"",
")",
")",
";",
"return",
";",
"}",
"// store callback for later",
"var",
"callback",
"=",
"args",
".",
"pop",
"(",
")",
";",
"// check that a callback is set",
"if",
"(",
"typeof",
"callback",
"!==",
"'function'",
")",
"{",
"ipc",
".",
"root",
".",
"emit",
"(",
"'error'",
",",
"new",
"TypeError",
"(",
"\"No callback specified\"",
")",
")",
";",
"return",
";",
"}",
"// send request to remote",
"ipc",
".",
"send",
"(",
"'call'",
",",
"[",
"name",
",",
"args",
"]",
",",
"function",
"(",
"sucess",
",",
"content",
")",
"{",
"if",
"(",
"sucess",
")",
"{",
"callback",
".",
"apply",
"(",
"{",
"error",
":",
"null",
"}",
",",
"content",
")",
";",
"}",
"else",
"{",
"callback",
".",
"apply",
"(",
"{",
"error",
":",
"helpers",
".",
"object2error",
"(",
"content",
")",
"}",
",",
"[",
"]",
")",
";",
"}",
"}",
")",
";",
"}"
] |
request a method from the listener
|
[
"request",
"a",
"method",
"from",
"the",
"listener"
] |
1ea0c2703d303874fc50d8efb2013ee4d7dadeb1
|
https://github.com/AndreasMadsen/thintalk/blob/1ea0c2703d303874fc50d8efb2013ee4d7dadeb1/lib/core/requester.js#L121-L150
|
50,748
|
Aniket965/emojifylogs
|
app.js
|
setEmoji
|
function setEmoji(type,emojiDefault, emojiInfo, emojiError, emojiWarn) {
let icon = emojiDefault
switch (type) {
case 'info':
icon = emojiInfo
break
case 'error':
icon = emojiError
break
case 'warn':
icon = emojiWarn
break
default:
}
return icon
}
|
javascript
|
function setEmoji(type,emojiDefault, emojiInfo, emojiError, emojiWarn) {
let icon = emojiDefault
switch (type) {
case 'info':
icon = emojiInfo
break
case 'error':
icon = emojiError
break
case 'warn':
icon = emojiWarn
break
default:
}
return icon
}
|
[
"function",
"setEmoji",
"(",
"type",
",",
"emojiDefault",
",",
"emojiInfo",
",",
"emojiError",
",",
"emojiWarn",
")",
"{",
"let",
"icon",
"=",
"emojiDefault",
"switch",
"(",
"type",
")",
"{",
"case",
"'info'",
":",
"icon",
"=",
"emojiInfo",
"break",
"case",
"'error'",
":",
"icon",
"=",
"emojiError",
"break",
"case",
"'warn'",
":",
"icon",
"=",
"emojiWarn",
"break",
"default",
":",
"}",
"return",
"icon",
"}"
] |
map icon to Given Type
@param {string} type
@param {*} emojiDefault
@param {*} emojiInfo
@param {*} emojiError
@param {*} emojiWarn
|
[
"map",
"icon",
"to",
"Given",
"Type"
] |
eeb4adad01ed102725368676a605ebbc59b9cd83
|
https://github.com/Aniket965/emojifylogs/blob/eeb4adad01ed102725368676a605ebbc59b9cd83/app.js#L9-L24
|
50,749
|
iceroad/baresoil-server
|
lib/util/setupCLI.js
|
ShowVersion
|
function ShowVersion(packageJson) {
const pkgName = packageJson.name;
let latestVer = spawnSync(`npm show ${pkgName} version`, {
shell: true,
stdio: ['inherit', 'pipe', 'inherit'],
}).stdout;
let latestVerStr = '';
if (latestVer) {
latestVer = latestVer.toString('utf-8').replace(/\s/gm, '');
if (latestVer !== packageJson.version) {
const osType = os.type();
const sudo = (osType === 'Linux' || osType === 'Darwin') ? 'sudo ' : '';
latestVerStr = `Latest version on npm: ${col.warning(latestVer).bold}
Run "${col.warning(`${sudo}npm install -g ${pkgName}@latest`)}" to upgrade.`;
} else {
latestVerStr = `${col.success('up-to-date!')}`;
}
}
return `${packageJson.version}\n${latestVerStr}`;
}
|
javascript
|
function ShowVersion(packageJson) {
const pkgName = packageJson.name;
let latestVer = spawnSync(`npm show ${pkgName} version`, {
shell: true,
stdio: ['inherit', 'pipe', 'inherit'],
}).stdout;
let latestVerStr = '';
if (latestVer) {
latestVer = latestVer.toString('utf-8').replace(/\s/gm, '');
if (latestVer !== packageJson.version) {
const osType = os.type();
const sudo = (osType === 'Linux' || osType === 'Darwin') ? 'sudo ' : '';
latestVerStr = `Latest version on npm: ${col.warning(latestVer).bold}
Run "${col.warning(`${sudo}npm install -g ${pkgName}@latest`)}" to upgrade.`;
} else {
latestVerStr = `${col.success('up-to-date!')}`;
}
}
return `${packageJson.version}\n${latestVerStr}`;
}
|
[
"function",
"ShowVersion",
"(",
"packageJson",
")",
"{",
"const",
"pkgName",
"=",
"packageJson",
".",
"name",
";",
"let",
"latestVer",
"=",
"spawnSync",
"(",
"`",
"${",
"pkgName",
"}",
"`",
",",
"{",
"shell",
":",
"true",
",",
"stdio",
":",
"[",
"'inherit'",
",",
"'pipe'",
",",
"'inherit'",
"]",
",",
"}",
")",
".",
"stdout",
";",
"let",
"latestVerStr",
"=",
"''",
";",
"if",
"(",
"latestVer",
")",
"{",
"latestVer",
"=",
"latestVer",
".",
"toString",
"(",
"'utf-8'",
")",
".",
"replace",
"(",
"/",
"\\s",
"/",
"gm",
",",
"''",
")",
";",
"if",
"(",
"latestVer",
"!==",
"packageJson",
".",
"version",
")",
"{",
"const",
"osType",
"=",
"os",
".",
"type",
"(",
")",
";",
"const",
"sudo",
"=",
"(",
"osType",
"===",
"'Linux'",
"||",
"osType",
"===",
"'Darwin'",
")",
"?",
"'sudo '",
":",
"''",
";",
"latestVerStr",
"=",
"`",
"${",
"col",
".",
"warning",
"(",
"latestVer",
")",
".",
"bold",
"}",
"${",
"col",
".",
"warning",
"(",
"`",
"${",
"sudo",
"}",
"${",
"pkgName",
"}",
"`",
")",
"}",
"`",
";",
"}",
"else",
"{",
"latestVerStr",
"=",
"`",
"${",
"col",
".",
"success",
"(",
"'up-to-date!'",
")",
"}",
"`",
";",
"}",
"}",
"return",
"`",
"${",
"packageJson",
".",
"version",
"}",
"\\n",
"${",
"latestVerStr",
"}",
"`",
";",
"}"
] |
Check for latest package version on npm, return warning on outdated version.
|
[
"Check",
"for",
"latest",
"package",
"version",
"on",
"npm",
"return",
"warning",
"on",
"outdated",
"version",
"."
] |
8285f1647a81eb935331ea24491b38002b51278d
|
https://github.com/iceroad/baresoil-server/blob/8285f1647a81eb935331ea24491b38002b51278d/lib/util/setupCLI.js#L12-L32
|
50,750
|
iceroad/baresoil-server
|
lib/util/setupCLI.js
|
GetCommandList
|
function GetCommandList(execName, packageJson, Commands) {
const header = `\
${packageJson.title || packageJson.name || execName} ${packageJson.version}
Usage: ${execName} ${col.bold('<command>')} [options]
Commands:`;
const grouped = _.groupBy(Commands, 'helpGroup');
const sorted = _.mapValues(grouped, arr => _.sortBy(arr, 'helpPriority'));
const sortedGroups = _.sortBy(sorted, grp => grp[0].helpPriority);
const longestCmd = _.max(_.map(Commands, cmd => cmd.name.length));
const commandListStr = _.map(sortedGroups, (helpGroup) => {
const groupName = _.first(helpGroup).helpGroup;
return _.flatten([
`\n * ${col.primary(groupName)}`,
_.map(helpGroup, (cmd) => {
const cmdName = _.padEnd(cmd.name, longestCmd);
return ` ${col.bold(cmdName)} ${cmd.desc}`;
}),
]).join('\n');
}).join('\n');
return `\
${header}
${commandListStr}
Use ${col.bold(`${execName} <command> -h`)} for command-specific help.`;
}
|
javascript
|
function GetCommandList(execName, packageJson, Commands) {
const header = `\
${packageJson.title || packageJson.name || execName} ${packageJson.version}
Usage: ${execName} ${col.bold('<command>')} [options]
Commands:`;
const grouped = _.groupBy(Commands, 'helpGroup');
const sorted = _.mapValues(grouped, arr => _.sortBy(arr, 'helpPriority'));
const sortedGroups = _.sortBy(sorted, grp => grp[0].helpPriority);
const longestCmd = _.max(_.map(Commands, cmd => cmd.name.length));
const commandListStr = _.map(sortedGroups, (helpGroup) => {
const groupName = _.first(helpGroup).helpGroup;
return _.flatten([
`\n * ${col.primary(groupName)}`,
_.map(helpGroup, (cmd) => {
const cmdName = _.padEnd(cmd.name, longestCmd);
return ` ${col.bold(cmdName)} ${cmd.desc}`;
}),
]).join('\n');
}).join('\n');
return `\
${header}
${commandListStr}
Use ${col.bold(`${execName} <command> -h`)} for command-specific help.`;
}
|
[
"function",
"GetCommandList",
"(",
"execName",
",",
"packageJson",
",",
"Commands",
")",
"{",
"const",
"header",
"=",
"`",
"\\\n",
"${",
"packageJson",
".",
"title",
"||",
"packageJson",
".",
"name",
"||",
"execName",
"}",
"${",
"packageJson",
".",
"version",
"}",
"${",
"execName",
"}",
"${",
"col",
".",
"bold",
"(",
"'<command>'",
")",
"}",
"`",
";",
"const",
"grouped",
"=",
"_",
".",
"groupBy",
"(",
"Commands",
",",
"'helpGroup'",
")",
";",
"const",
"sorted",
"=",
"_",
".",
"mapValues",
"(",
"grouped",
",",
"arr",
"=>",
"_",
".",
"sortBy",
"(",
"arr",
",",
"'helpPriority'",
")",
")",
";",
"const",
"sortedGroups",
"=",
"_",
".",
"sortBy",
"(",
"sorted",
",",
"grp",
"=>",
"grp",
"[",
"0",
"]",
".",
"helpPriority",
")",
";",
"const",
"longestCmd",
"=",
"_",
".",
"max",
"(",
"_",
".",
"map",
"(",
"Commands",
",",
"cmd",
"=>",
"cmd",
".",
"name",
".",
"length",
")",
")",
";",
"const",
"commandListStr",
"=",
"_",
".",
"map",
"(",
"sortedGroups",
",",
"(",
"helpGroup",
")",
"=>",
"{",
"const",
"groupName",
"=",
"_",
".",
"first",
"(",
"helpGroup",
")",
".",
"helpGroup",
";",
"return",
"_",
".",
"flatten",
"(",
"[",
"`",
"\\n",
"${",
"col",
".",
"primary",
"(",
"groupName",
")",
"}",
"`",
",",
"_",
".",
"map",
"(",
"helpGroup",
",",
"(",
"cmd",
")",
"=>",
"{",
"const",
"cmdName",
"=",
"_",
".",
"padEnd",
"(",
"cmd",
".",
"name",
",",
"longestCmd",
")",
";",
"return",
"`",
"${",
"col",
".",
"bold",
"(",
"cmdName",
")",
"}",
"${",
"cmd",
".",
"desc",
"}",
"`",
";",
"}",
")",
",",
"]",
")",
".",
"join",
"(",
"'\\n'",
")",
";",
"}",
")",
".",
"join",
"(",
"'\\n'",
")",
";",
"return",
"`",
"\\\n",
"${",
"header",
"}",
"${",
"commandListStr",
"}",
"${",
"col",
".",
"bold",
"(",
"`",
"${",
"execName",
"}",
"`",
")",
"}",
"`",
";",
"}"
] |
Get list of available sub-commands for package.
|
[
"Get",
"list",
"of",
"available",
"sub",
"-",
"commands",
"for",
"package",
"."
] |
8285f1647a81eb935331ea24491b38002b51278d
|
https://github.com/iceroad/baresoil-server/blob/8285f1647a81eb935331ea24491b38002b51278d/lib/util/setupCLI.js#L37-L63
|
50,751
|
iceroad/baresoil-server
|
lib/util/setupCLI.js
|
GetCommandUsage
|
function GetCommandUsage(execName, packageJson, cmdSpec, args) {
const argSpec = cmdSpec.argSpec || [];
const optStr = argSpec.length ? ' [options]' : '';
const header = `\
Usage: ${execName} ${cmdSpec.name}${optStr}
Purpose: ${cmdSpec.desc}
Options: ${argSpec.length ? '' : 'none.'}`;
const usageTableRows = _.map(cmdSpec.argSpec, (argDef) => {
const dashify = flag => (flag.length === 1 ? `-${col.primary(flag)}` : `--${col.primary(flag)}`);
const lhs = _.map(argDef.flags, dashify).join(', ');
const rhs = argDef.desc || '';
return [lhs, rhs, argDef];
});
const firstColWidth = _.max(
_.map(usageTableRows, row => stripAnsi(row[0]).length)) + 1;
const body = _.map(usageTableRows, (row) => {
const rhsLines = row[1].split(/\n/mg);
const firstRhsLine = rhsLines[0];
rhsLines.splice(0, 1);
const lhsSpacer = new Array((firstColWidth - stripAnsi(row[0]).length) + 1).join(' ');
const paddedLhs = `${lhsSpacer}${row[0]}`;
const firstLine = `${paddedLhs}: ${firstRhsLine}`;
const skipLeft = new Array(firstColWidth + 1).join(' ');
const paddedRhs = rhsLines.length ? _.map(rhsLines, line => `${skipLeft}${line}`).join('\n') : '';
const argDef = row[2];
let curVal = _.find(argDef.flags, flag => (flag in args ? args[flag] : null));
if (!curVal) curVal = argDef.defVal || argDef.default || '';
if (curVal) {
curVal = `${skipLeft} ${col.dim('Current:')} "${col.primary(curVal)}"`;
}
return _.filter([
firstLine,
paddedRhs,
curVal,
]).join('\n');
}).join('\n\n');
return `\
${header}
${body}
`;
}
|
javascript
|
function GetCommandUsage(execName, packageJson, cmdSpec, args) {
const argSpec = cmdSpec.argSpec || [];
const optStr = argSpec.length ? ' [options]' : '';
const header = `\
Usage: ${execName} ${cmdSpec.name}${optStr}
Purpose: ${cmdSpec.desc}
Options: ${argSpec.length ? '' : 'none.'}`;
const usageTableRows = _.map(cmdSpec.argSpec, (argDef) => {
const dashify = flag => (flag.length === 1 ? `-${col.primary(flag)}` : `--${col.primary(flag)}`);
const lhs = _.map(argDef.flags, dashify).join(', ');
const rhs = argDef.desc || '';
return [lhs, rhs, argDef];
});
const firstColWidth = _.max(
_.map(usageTableRows, row => stripAnsi(row[0]).length)) + 1;
const body = _.map(usageTableRows, (row) => {
const rhsLines = row[1].split(/\n/mg);
const firstRhsLine = rhsLines[0];
rhsLines.splice(0, 1);
const lhsSpacer = new Array((firstColWidth - stripAnsi(row[0]).length) + 1).join(' ');
const paddedLhs = `${lhsSpacer}${row[0]}`;
const firstLine = `${paddedLhs}: ${firstRhsLine}`;
const skipLeft = new Array(firstColWidth + 1).join(' ');
const paddedRhs = rhsLines.length ? _.map(rhsLines, line => `${skipLeft}${line}`).join('\n') : '';
const argDef = row[2];
let curVal = _.find(argDef.flags, flag => (flag in args ? args[flag] : null));
if (!curVal) curVal = argDef.defVal || argDef.default || '';
if (curVal) {
curVal = `${skipLeft} ${col.dim('Current:')} "${col.primary(curVal)}"`;
}
return _.filter([
firstLine,
paddedRhs,
curVal,
]).join('\n');
}).join('\n\n');
return `\
${header}
${body}
`;
}
|
[
"function",
"GetCommandUsage",
"(",
"execName",
",",
"packageJson",
",",
"cmdSpec",
",",
"args",
")",
"{",
"const",
"argSpec",
"=",
"cmdSpec",
".",
"argSpec",
"||",
"[",
"]",
";",
"const",
"optStr",
"=",
"argSpec",
".",
"length",
"?",
"' [options]'",
":",
"''",
";",
"const",
"header",
"=",
"`",
"\\\n",
"${",
"execName",
"}",
"${",
"cmdSpec",
".",
"name",
"}",
"${",
"optStr",
"}",
"${",
"cmdSpec",
".",
"desc",
"}",
"${",
"argSpec",
".",
"length",
"?",
"''",
":",
"'none.'",
"}",
"`",
";",
"const",
"usageTableRows",
"=",
"_",
".",
"map",
"(",
"cmdSpec",
".",
"argSpec",
",",
"(",
"argDef",
")",
"=>",
"{",
"const",
"dashify",
"=",
"flag",
"=>",
"(",
"flag",
".",
"length",
"===",
"1",
"?",
"`",
"${",
"col",
".",
"primary",
"(",
"flag",
")",
"}",
"`",
":",
"`",
"${",
"col",
".",
"primary",
"(",
"flag",
")",
"}",
"`",
")",
";",
"const",
"lhs",
"=",
"_",
".",
"map",
"(",
"argDef",
".",
"flags",
",",
"dashify",
")",
".",
"join",
"(",
"', '",
")",
";",
"const",
"rhs",
"=",
"argDef",
".",
"desc",
"||",
"''",
";",
"return",
"[",
"lhs",
",",
"rhs",
",",
"argDef",
"]",
";",
"}",
")",
";",
"const",
"firstColWidth",
"=",
"_",
".",
"max",
"(",
"_",
".",
"map",
"(",
"usageTableRows",
",",
"row",
"=>",
"stripAnsi",
"(",
"row",
"[",
"0",
"]",
")",
".",
"length",
")",
")",
"+",
"1",
";",
"const",
"body",
"=",
"_",
".",
"map",
"(",
"usageTableRows",
",",
"(",
"row",
")",
"=>",
"{",
"const",
"rhsLines",
"=",
"row",
"[",
"1",
"]",
".",
"split",
"(",
"/",
"\\n",
"/",
"mg",
")",
";",
"const",
"firstRhsLine",
"=",
"rhsLines",
"[",
"0",
"]",
";",
"rhsLines",
".",
"splice",
"(",
"0",
",",
"1",
")",
";",
"const",
"lhsSpacer",
"=",
"new",
"Array",
"(",
"(",
"firstColWidth",
"-",
"stripAnsi",
"(",
"row",
"[",
"0",
"]",
")",
".",
"length",
")",
"+",
"1",
")",
".",
"join",
"(",
"' '",
")",
";",
"const",
"paddedLhs",
"=",
"`",
"${",
"lhsSpacer",
"}",
"${",
"row",
"[",
"0",
"]",
"}",
"`",
";",
"const",
"firstLine",
"=",
"`",
"${",
"paddedLhs",
"}",
"${",
"firstRhsLine",
"}",
"`",
";",
"const",
"skipLeft",
"=",
"new",
"Array",
"(",
"firstColWidth",
"+",
"1",
")",
".",
"join",
"(",
"' '",
")",
";",
"const",
"paddedRhs",
"=",
"rhsLines",
".",
"length",
"?",
"_",
".",
"map",
"(",
"rhsLines",
",",
"line",
"=>",
"`",
"${",
"skipLeft",
"}",
"${",
"line",
"}",
"`",
")",
".",
"join",
"(",
"'\\n'",
")",
":",
"''",
";",
"const",
"argDef",
"=",
"row",
"[",
"2",
"]",
";",
"let",
"curVal",
"=",
"_",
".",
"find",
"(",
"argDef",
".",
"flags",
",",
"flag",
"=>",
"(",
"flag",
"in",
"args",
"?",
"args",
"[",
"flag",
"]",
":",
"null",
")",
")",
";",
"if",
"(",
"!",
"curVal",
")",
"curVal",
"=",
"argDef",
".",
"defVal",
"||",
"argDef",
".",
"default",
"||",
"''",
";",
"if",
"(",
"curVal",
")",
"{",
"curVal",
"=",
"`",
"${",
"skipLeft",
"}",
"${",
"col",
".",
"dim",
"(",
"'Current:'",
")",
"}",
"${",
"col",
".",
"primary",
"(",
"curVal",
")",
"}",
"`",
";",
"}",
"return",
"_",
".",
"filter",
"(",
"[",
"firstLine",
",",
"paddedRhs",
",",
"curVal",
",",
"]",
")",
".",
"join",
"(",
"'\\n'",
")",
";",
"}",
")",
".",
"join",
"(",
"'\\n\\n'",
")",
";",
"return",
"`",
"\\\n",
"${",
"header",
"}",
"${",
"body",
"}",
"`",
";",
"}"
] |
Get command-specific help.
|
[
"Get",
"command",
"-",
"specific",
"help",
"."
] |
8285f1647a81eb935331ea24491b38002b51278d
|
https://github.com/iceroad/baresoil-server/blob/8285f1647a81eb935331ea24491b38002b51278d/lib/util/setupCLI.js#L68-L115
|
50,752
|
iceroad/baresoil-server
|
lib/util/setupCLI.js
|
ParseArguments
|
function ParseArguments(cmd, args) {
assert(_.isObject(cmd), 'require an object argument for "cmd".');
assert(_.isObject(args), 'require an object argument for "args".');
const argSpec = cmd.argSpec || [];
const cmdName = cmd.name;
//
// Build a map of all flag aliases.
//
const allAliases = _.fromPairs(_.map(_.flatten(_.map(argSpec, 'flags')), (flagAlias) => {
return [flagAlias, true];
}));
//
// Make sure all provided flags are specified in the argSpec.
//
_.forEach(args, (argVal, argKey) => {
if (argKey === '_') return; // ignore positional arguments
if (!(argKey in allAliases)) {
const d = argKey.length === 1 ? '-' : '--';
throw new Error(
`Unknown command-line option "${col.bold(d + argKey)}" specified ` +
`for command "${col.bold(cmdName)}".`);
}
});
//
// Handle boolean flags specified as string values on the command line.
//
args = _.mapValues(args, (flagVal) => {
if (_.isString(flagVal)) {
if (flagVal === 'true') {
return true;
}
if (flagVal === 'false') {
return false;
}
}
return flagVal;
});
//
// For each flag in the argSpec, see if any alias of the flag is
// present in `args`. If it is, then assign that value to *all*
// aliases of the flag. If it is not present, then assign the
// default value. Throw on unspecified required flags.
//
const finalFlags = {};
_.forEach(argSpec, (aspec, idx) => {
// Find the first alias of this flag that is specified in args, if at all.
const foundAlias = _.find(aspec.flags, (flagAlias) => {
return flagAlias && (flagAlias in args);
});
let assignValue = foundAlias ? args[foundAlias] : (aspec.defVal || aspec.default);
// If defVal is an object, then we need to execute a function to get the
// default value.
if (_.isObject(assignValue)) {
assert(
_.isFunction(assignValue.fn),
`Argspec entry ${idx} has an invalid 'defVal'/'default' property.`);
assignValue = assignValue.fn.call(argSpec);
}
if (!_.isUndefined(assignValue)) {
// Assign value to all aliases of flag.
_.forEach(aspec.flags, (flagAlias) => {
finalFlags[flagAlias] = assignValue;
});
}
});
// Copy positional arguments to finalFlags.
finalFlags._ = args._;
return finalFlags;
}
|
javascript
|
function ParseArguments(cmd, args) {
assert(_.isObject(cmd), 'require an object argument for "cmd".');
assert(_.isObject(args), 'require an object argument for "args".');
const argSpec = cmd.argSpec || [];
const cmdName = cmd.name;
//
// Build a map of all flag aliases.
//
const allAliases = _.fromPairs(_.map(_.flatten(_.map(argSpec, 'flags')), (flagAlias) => {
return [flagAlias, true];
}));
//
// Make sure all provided flags are specified in the argSpec.
//
_.forEach(args, (argVal, argKey) => {
if (argKey === '_') return; // ignore positional arguments
if (!(argKey in allAliases)) {
const d = argKey.length === 1 ? '-' : '--';
throw new Error(
`Unknown command-line option "${col.bold(d + argKey)}" specified ` +
`for command "${col.bold(cmdName)}".`);
}
});
//
// Handle boolean flags specified as string values on the command line.
//
args = _.mapValues(args, (flagVal) => {
if (_.isString(flagVal)) {
if (flagVal === 'true') {
return true;
}
if (flagVal === 'false') {
return false;
}
}
return flagVal;
});
//
// For each flag in the argSpec, see if any alias of the flag is
// present in `args`. If it is, then assign that value to *all*
// aliases of the flag. If it is not present, then assign the
// default value. Throw on unspecified required flags.
//
const finalFlags = {};
_.forEach(argSpec, (aspec, idx) => {
// Find the first alias of this flag that is specified in args, if at all.
const foundAlias = _.find(aspec.flags, (flagAlias) => {
return flagAlias && (flagAlias in args);
});
let assignValue = foundAlias ? args[foundAlias] : (aspec.defVal || aspec.default);
// If defVal is an object, then we need to execute a function to get the
// default value.
if (_.isObject(assignValue)) {
assert(
_.isFunction(assignValue.fn),
`Argspec entry ${idx} has an invalid 'defVal'/'default' property.`);
assignValue = assignValue.fn.call(argSpec);
}
if (!_.isUndefined(assignValue)) {
// Assign value to all aliases of flag.
_.forEach(aspec.flags, (flagAlias) => {
finalFlags[flagAlias] = assignValue;
});
}
});
// Copy positional arguments to finalFlags.
finalFlags._ = args._;
return finalFlags;
}
|
[
"function",
"ParseArguments",
"(",
"cmd",
",",
"args",
")",
"{",
"assert",
"(",
"_",
".",
"isObject",
"(",
"cmd",
")",
",",
"'require an object argument for \"cmd\".'",
")",
";",
"assert",
"(",
"_",
".",
"isObject",
"(",
"args",
")",
",",
"'require an object argument for \"args\".'",
")",
";",
"const",
"argSpec",
"=",
"cmd",
".",
"argSpec",
"||",
"[",
"]",
";",
"const",
"cmdName",
"=",
"cmd",
".",
"name",
";",
"//",
"// Build a map of all flag aliases.",
"//",
"const",
"allAliases",
"=",
"_",
".",
"fromPairs",
"(",
"_",
".",
"map",
"(",
"_",
".",
"flatten",
"(",
"_",
".",
"map",
"(",
"argSpec",
",",
"'flags'",
")",
")",
",",
"(",
"flagAlias",
")",
"=>",
"{",
"return",
"[",
"flagAlias",
",",
"true",
"]",
";",
"}",
")",
")",
";",
"//",
"// Make sure all provided flags are specified in the argSpec.",
"//",
"_",
".",
"forEach",
"(",
"args",
",",
"(",
"argVal",
",",
"argKey",
")",
"=>",
"{",
"if",
"(",
"argKey",
"===",
"'_'",
")",
"return",
";",
"// ignore positional arguments",
"if",
"(",
"!",
"(",
"argKey",
"in",
"allAliases",
")",
")",
"{",
"const",
"d",
"=",
"argKey",
".",
"length",
"===",
"1",
"?",
"'-'",
":",
"'--'",
";",
"throw",
"new",
"Error",
"(",
"`",
"${",
"col",
".",
"bold",
"(",
"d",
"+",
"argKey",
")",
"}",
"`",
"+",
"`",
"${",
"col",
".",
"bold",
"(",
"cmdName",
")",
"}",
"`",
")",
";",
"}",
"}",
")",
";",
"//",
"// Handle boolean flags specified as string values on the command line.",
"//",
"args",
"=",
"_",
".",
"mapValues",
"(",
"args",
",",
"(",
"flagVal",
")",
"=>",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"flagVal",
")",
")",
"{",
"if",
"(",
"flagVal",
"===",
"'true'",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"flagVal",
"===",
"'false'",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"flagVal",
";",
"}",
")",
";",
"//",
"// For each flag in the argSpec, see if any alias of the flag is",
"// present in `args`. If it is, then assign that value to *all*",
"// aliases of the flag. If it is not present, then assign the",
"// default value. Throw on unspecified required flags.",
"//",
"const",
"finalFlags",
"=",
"{",
"}",
";",
"_",
".",
"forEach",
"(",
"argSpec",
",",
"(",
"aspec",
",",
"idx",
")",
"=>",
"{",
"// Find the first alias of this flag that is specified in args, if at all.",
"const",
"foundAlias",
"=",
"_",
".",
"find",
"(",
"aspec",
".",
"flags",
",",
"(",
"flagAlias",
")",
"=>",
"{",
"return",
"flagAlias",
"&&",
"(",
"flagAlias",
"in",
"args",
")",
";",
"}",
")",
";",
"let",
"assignValue",
"=",
"foundAlias",
"?",
"args",
"[",
"foundAlias",
"]",
":",
"(",
"aspec",
".",
"defVal",
"||",
"aspec",
".",
"default",
")",
";",
"// If defVal is an object, then we need to execute a function to get the",
"// default value.",
"if",
"(",
"_",
".",
"isObject",
"(",
"assignValue",
")",
")",
"{",
"assert",
"(",
"_",
".",
"isFunction",
"(",
"assignValue",
".",
"fn",
")",
",",
"`",
"${",
"idx",
"}",
"`",
")",
";",
"assignValue",
"=",
"assignValue",
".",
"fn",
".",
"call",
"(",
"argSpec",
")",
";",
"}",
"if",
"(",
"!",
"_",
".",
"isUndefined",
"(",
"assignValue",
")",
")",
"{",
"// Assign value to all aliases of flag.",
"_",
".",
"forEach",
"(",
"aspec",
".",
"flags",
",",
"(",
"flagAlias",
")",
"=>",
"{",
"finalFlags",
"[",
"flagAlias",
"]",
"=",
"assignValue",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"// Copy positional arguments to finalFlags.",
"finalFlags",
".",
"_",
"=",
"args",
".",
"_",
";",
"return",
"finalFlags",
";",
"}"
] |
Parse command-line arguments.
|
[
"Parse",
"command",
"-",
"line",
"arguments",
"."
] |
8285f1647a81eb935331ea24491b38002b51278d
|
https://github.com/iceroad/baresoil-server/blob/8285f1647a81eb935331ea24491b38002b51278d/lib/util/setupCLI.js#L120-L196
|
50,753
|
xiamidaxia/xiami
|
meteor/minimongo/selector.js
|
function (selector) {
var self = this;
// you can pass a literal function instead of a selector
if (_.isFunction(selector)) {
self._isSimple = false;
self._selector = selector;
self._recordPathUsed('');
return function (doc) {
return {result: !!selector.call(doc)};
};
}
// shorthand -- scalars match _id
if (LocalCollection._selectorIsId(selector)) {
self._selector = {_id: selector};
self._recordPathUsed('_id');
return function (doc) {
return {result: EJSON.equals(doc._id, selector)};
};
}
// protect against dangerous selectors. falsey and {_id: falsey} are both
// likely programmer error, and not what you want, particularly for
// destructive operations.
if (!selector || (('_id' in selector) && !selector._id)) {
self._isSimple = false;
return nothingMatcher;
}
// Top level can't be an array or true or binary.
if (typeof(selector) === 'boolean' || isArray(selector) ||
EJSON.isBinary(selector))
throw new Error("Invalid selector: " + selector);
self._selector = EJSON.clone(selector);
return compileDocumentSelector(selector, self, {isRoot: true});
}
|
javascript
|
function (selector) {
var self = this;
// you can pass a literal function instead of a selector
if (_.isFunction(selector)) {
self._isSimple = false;
self._selector = selector;
self._recordPathUsed('');
return function (doc) {
return {result: !!selector.call(doc)};
};
}
// shorthand -- scalars match _id
if (LocalCollection._selectorIsId(selector)) {
self._selector = {_id: selector};
self._recordPathUsed('_id');
return function (doc) {
return {result: EJSON.equals(doc._id, selector)};
};
}
// protect against dangerous selectors. falsey and {_id: falsey} are both
// likely programmer error, and not what you want, particularly for
// destructive operations.
if (!selector || (('_id' in selector) && !selector._id)) {
self._isSimple = false;
return nothingMatcher;
}
// Top level can't be an array or true or binary.
if (typeof(selector) === 'boolean' || isArray(selector) ||
EJSON.isBinary(selector))
throw new Error("Invalid selector: " + selector);
self._selector = EJSON.clone(selector);
return compileDocumentSelector(selector, self, {isRoot: true});
}
|
[
"function",
"(",
"selector",
")",
"{",
"var",
"self",
"=",
"this",
";",
"// you can pass a literal function instead of a selector",
"if",
"(",
"_",
".",
"isFunction",
"(",
"selector",
")",
")",
"{",
"self",
".",
"_isSimple",
"=",
"false",
";",
"self",
".",
"_selector",
"=",
"selector",
";",
"self",
".",
"_recordPathUsed",
"(",
"''",
")",
";",
"return",
"function",
"(",
"doc",
")",
"{",
"return",
"{",
"result",
":",
"!",
"!",
"selector",
".",
"call",
"(",
"doc",
")",
"}",
";",
"}",
";",
"}",
"// shorthand -- scalars match _id",
"if",
"(",
"LocalCollection",
".",
"_selectorIsId",
"(",
"selector",
")",
")",
"{",
"self",
".",
"_selector",
"=",
"{",
"_id",
":",
"selector",
"}",
";",
"self",
".",
"_recordPathUsed",
"(",
"'_id'",
")",
";",
"return",
"function",
"(",
"doc",
")",
"{",
"return",
"{",
"result",
":",
"EJSON",
".",
"equals",
"(",
"doc",
".",
"_id",
",",
"selector",
")",
"}",
";",
"}",
";",
"}",
"// protect against dangerous selectors. falsey and {_id: falsey} are both",
"// likely programmer error, and not what you want, particularly for",
"// destructive operations.",
"if",
"(",
"!",
"selector",
"||",
"(",
"(",
"'_id'",
"in",
"selector",
")",
"&&",
"!",
"selector",
".",
"_id",
")",
")",
"{",
"self",
".",
"_isSimple",
"=",
"false",
";",
"return",
"nothingMatcher",
";",
"}",
"// Top level can't be an array or true or binary.",
"if",
"(",
"typeof",
"(",
"selector",
")",
"===",
"'boolean'",
"||",
"isArray",
"(",
"selector",
")",
"||",
"EJSON",
".",
"isBinary",
"(",
"selector",
")",
")",
"throw",
"new",
"Error",
"(",
"\"Invalid selector: \"",
"+",
"selector",
")",
";",
"self",
".",
"_selector",
"=",
"EJSON",
".",
"clone",
"(",
"selector",
")",
";",
"return",
"compileDocumentSelector",
"(",
"selector",
",",
"self",
",",
"{",
"isRoot",
":",
"true",
"}",
")",
";",
"}"
] |
Given a selector, return a function that takes one argument, a document. It returns a result object.
|
[
"Given",
"a",
"selector",
"return",
"a",
"function",
"that",
"takes",
"one",
"argument",
"a",
"document",
".",
"It",
"returns",
"a",
"result",
"object",
"."
] |
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
|
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/minimongo/selector.js#L82-L118
|
|
50,754
|
xiamidaxia/xiami
|
meteor/minimongo/selector.js
|
function (v) {
if (typeof v === "number")
return 1;
if (typeof v === "string")
return 2;
if (typeof v === "boolean")
return 8;
if (isArray(v))
return 4;
if (v === null)
return 10;
if (_.isRegExp(v))
// note that typeof(/x/) === "object"
return 11;
if (typeof v === "function")
return 13;
if (_.isDate(v))
return 9;
if (EJSON.isBinary(v))
return 5;
if (v instanceof LocalCollection._ObjectID)
return 7;
return 3; // object
// XXX support some/all of these:
// 14, symbol
// 15, javascript code with scope
// 16, 18: 32-bit/64-bit integer
// 17, timestamp
// 255, minkey
// 127, maxkey
}
|
javascript
|
function (v) {
if (typeof v === "number")
return 1;
if (typeof v === "string")
return 2;
if (typeof v === "boolean")
return 8;
if (isArray(v))
return 4;
if (v === null)
return 10;
if (_.isRegExp(v))
// note that typeof(/x/) === "object"
return 11;
if (typeof v === "function")
return 13;
if (_.isDate(v))
return 9;
if (EJSON.isBinary(v))
return 5;
if (v instanceof LocalCollection._ObjectID)
return 7;
return 3; // object
// XXX support some/all of these:
// 14, symbol
// 15, javascript code with scope
// 16, 18: 32-bit/64-bit integer
// 17, timestamp
// 255, minkey
// 127, maxkey
}
|
[
"function",
"(",
"v",
")",
"{",
"if",
"(",
"typeof",
"v",
"===",
"\"number\"",
")",
"return",
"1",
";",
"if",
"(",
"typeof",
"v",
"===",
"\"string\"",
")",
"return",
"2",
";",
"if",
"(",
"typeof",
"v",
"===",
"\"boolean\"",
")",
"return",
"8",
";",
"if",
"(",
"isArray",
"(",
"v",
")",
")",
"return",
"4",
";",
"if",
"(",
"v",
"===",
"null",
")",
"return",
"10",
";",
"if",
"(",
"_",
".",
"isRegExp",
"(",
"v",
")",
")",
"// note that typeof(/x/) === \"object\"",
"return",
"11",
";",
"if",
"(",
"typeof",
"v",
"===",
"\"function\"",
")",
"return",
"13",
";",
"if",
"(",
"_",
".",
"isDate",
"(",
"v",
")",
")",
"return",
"9",
";",
"if",
"(",
"EJSON",
".",
"isBinary",
"(",
"v",
")",
")",
"return",
"5",
";",
"if",
"(",
"v",
"instanceof",
"LocalCollection",
".",
"_ObjectID",
")",
"return",
"7",
";",
"return",
"3",
";",
"// object",
"// XXX support some/all of these:",
"// 14, symbol",
"// 15, javascript code with scope",
"// 16, 18: 32-bit/64-bit integer",
"// 17, timestamp",
"// 255, minkey",
"// 127, maxkey",
"}"
] |
XXX for _all and _in, consider building 'inquery' at compile time..
|
[
"XXX",
"for",
"_all",
"and",
"_in",
"consider",
"building",
"inquery",
"at",
"compile",
"time",
".."
] |
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
|
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/minimongo/selector.js#L975-L1006
|
|
50,755
|
brentlintner/arctor
|
deps/browser-require/require.js
|
normalizeArray
|
function normalizeArray (v, keepBlanks) {
var L = v.length, dst = new Array(L), dsti = 0,
i = 0, part, negatives = 0,
isRelative = (L && v[0] !== '');
for (; i<L; ++i) {
part = v[i];
if (part === '..') {
if (dsti > 1) {
--dsti;
} else if (isRelative) {
++negatives;
} else {
dst[0] = '';
}
} else if (part !== '.' && (dsti === 0 || keepBlanks || part !== '')) {
dst[dsti++] = part;
}
}
if (negatives) {
dst[--negatives] = dst[dsti-1];
dsti = negatives + 1;
while (negatives--) { dst[negatives] = '..'; }
}
dst.length = dsti;
return dst;
}
|
javascript
|
function normalizeArray (v, keepBlanks) {
var L = v.length, dst = new Array(L), dsti = 0,
i = 0, part, negatives = 0,
isRelative = (L && v[0] !== '');
for (; i<L; ++i) {
part = v[i];
if (part === '..') {
if (dsti > 1) {
--dsti;
} else if (isRelative) {
++negatives;
} else {
dst[0] = '';
}
} else if (part !== '.' && (dsti === 0 || keepBlanks || part !== '')) {
dst[dsti++] = part;
}
}
if (negatives) {
dst[--negatives] = dst[dsti-1];
dsti = negatives + 1;
while (negatives--) { dst[negatives] = '..'; }
}
dst.length = dsti;
return dst;
}
|
[
"function",
"normalizeArray",
"(",
"v",
",",
"keepBlanks",
")",
"{",
"var",
"L",
"=",
"v",
".",
"length",
",",
"dst",
"=",
"new",
"Array",
"(",
"L",
")",
",",
"dsti",
"=",
"0",
",",
"i",
"=",
"0",
",",
"part",
",",
"negatives",
"=",
"0",
",",
"isRelative",
"=",
"(",
"L",
"&&",
"v",
"[",
"0",
"]",
"!==",
"''",
")",
";",
"for",
"(",
";",
"i",
"<",
"L",
";",
"++",
"i",
")",
"{",
"part",
"=",
"v",
"[",
"i",
"]",
";",
"if",
"(",
"part",
"===",
"'..'",
")",
"{",
"if",
"(",
"dsti",
">",
"1",
")",
"{",
"--",
"dsti",
";",
"}",
"else",
"if",
"(",
"isRelative",
")",
"{",
"++",
"negatives",
";",
"}",
"else",
"{",
"dst",
"[",
"0",
"]",
"=",
"''",
";",
"}",
"}",
"else",
"if",
"(",
"part",
"!==",
"'.'",
"&&",
"(",
"dsti",
"===",
"0",
"||",
"keepBlanks",
"||",
"part",
"!==",
"''",
")",
")",
"{",
"dst",
"[",
"dsti",
"++",
"]",
"=",
"part",
";",
"}",
"}",
"if",
"(",
"negatives",
")",
"{",
"dst",
"[",
"--",
"negatives",
"]",
"=",
"dst",
"[",
"dsti",
"-",
"1",
"]",
";",
"dsti",
"=",
"negatives",
"+",
"1",
";",
"while",
"(",
"negatives",
"--",
")",
"{",
"dst",
"[",
"negatives",
"]",
"=",
"'..'",
";",
"}",
"}",
"dst",
".",
"length",
"=",
"dsti",
";",
"return",
"dst",
";",
"}"
] |
normalize an array of path components
|
[
"normalize",
"an",
"array",
"of",
"path",
"components"
] |
557110f0bde85f23a3af8a03d9bfc01cd9ecf4dd
|
https://github.com/brentlintner/arctor/blob/557110f0bde85f23a3af8a03d9bfc01cd9ecf4dd/deps/browser-require/require.js#L5-L30
|
50,756
|
brentlintner/arctor
|
deps/browser-require/require.js
|
normalizeId
|
function normalizeId(id, parentId) {
id = id.replace(/\/+$/g, '');
return normalizeArray((parentId ? parentId + '/../' + id : id).split('/'))
.join('/');
}
|
javascript
|
function normalizeId(id, parentId) {
id = id.replace(/\/+$/g, '');
return normalizeArray((parentId ? parentId + '/../' + id : id).split('/'))
.join('/');
}
|
[
"function",
"normalizeId",
"(",
"id",
",",
"parentId",
")",
"{",
"id",
"=",
"id",
".",
"replace",
"(",
"/",
"\\/+$",
"/",
"g",
",",
"''",
")",
";",
"return",
"normalizeArray",
"(",
"(",
"parentId",
"?",
"parentId",
"+",
"'/../'",
"+",
"id",
":",
"id",
")",
".",
"split",
"(",
"'/'",
")",
")",
".",
"join",
"(",
"'/'",
")",
";",
"}"
] |
normalize an id
|
[
"normalize",
"an",
"id"
] |
557110f0bde85f23a3af8a03d9bfc01cd9ecf4dd
|
https://github.com/brentlintner/arctor/blob/557110f0bde85f23a3af8a03d9bfc01cd9ecf4dd/deps/browser-require/require.js#L32-L36
|
50,757
|
brentlintner/arctor
|
deps/browser-require/require.js
|
normalizeUrl
|
function normalizeUrl(url, baseLocation) {
if (!(/^\w+:/).test(url)) {
var u = baseLocation.protocol+'//'+baseLocation.hostname;
if (baseLocation.port && baseLocation.port !== 80) {
u += ':'+baseLocation.port;
}
var path = baseLocation.pathname;
if (url.charAt(0) === '/') {
url = u + normalizeArray(url.split('/')).join('/');
} else {
path += ((path.charAt(path.length-1) === '/') ? '' : '/../') + url;
url = u + normalizeArray(path.split('/')).join('/');
}
}
return url;
}
|
javascript
|
function normalizeUrl(url, baseLocation) {
if (!(/^\w+:/).test(url)) {
var u = baseLocation.protocol+'//'+baseLocation.hostname;
if (baseLocation.port && baseLocation.port !== 80) {
u += ':'+baseLocation.port;
}
var path = baseLocation.pathname;
if (url.charAt(0) === '/') {
url = u + normalizeArray(url.split('/')).join('/');
} else {
path += ((path.charAt(path.length-1) === '/') ? '' : '/../') + url;
url = u + normalizeArray(path.split('/')).join('/');
}
}
return url;
}
|
[
"function",
"normalizeUrl",
"(",
"url",
",",
"baseLocation",
")",
"{",
"if",
"(",
"!",
"(",
"/",
"^\\w+:",
"/",
")",
".",
"test",
"(",
"url",
")",
")",
"{",
"var",
"u",
"=",
"baseLocation",
".",
"protocol",
"+",
"'//'",
"+",
"baseLocation",
".",
"hostname",
";",
"if",
"(",
"baseLocation",
".",
"port",
"&&",
"baseLocation",
".",
"port",
"!==",
"80",
")",
"{",
"u",
"+=",
"':'",
"+",
"baseLocation",
".",
"port",
";",
"}",
"var",
"path",
"=",
"baseLocation",
".",
"pathname",
";",
"if",
"(",
"url",
".",
"charAt",
"(",
"0",
")",
"===",
"'/'",
")",
"{",
"url",
"=",
"u",
"+",
"normalizeArray",
"(",
"url",
".",
"split",
"(",
"'/'",
")",
")",
".",
"join",
"(",
"'/'",
")",
";",
"}",
"else",
"{",
"path",
"+=",
"(",
"(",
"path",
".",
"charAt",
"(",
"path",
".",
"length",
"-",
"1",
")",
"===",
"'/'",
")",
"?",
"''",
":",
"'/../'",
")",
"+",
"url",
";",
"url",
"=",
"u",
"+",
"normalizeArray",
"(",
"path",
".",
"split",
"(",
"'/'",
")",
")",
".",
"join",
"(",
"'/'",
")",
";",
"}",
"}",
"return",
"url",
";",
"}"
] |
normalize a url
|
[
"normalize",
"a",
"url"
] |
557110f0bde85f23a3af8a03d9bfc01cd9ecf4dd
|
https://github.com/brentlintner/arctor/blob/557110f0bde85f23a3af8a03d9bfc01cd9ecf4dd/deps/browser-require/require.js#L38-L53
|
50,758
|
JohnnieFucker/dreamix-monitor
|
lib/processMonitor.js
|
format
|
function format(param, data, cb) {
const time = util.formatTime(new Date());
const outArray = data.toString().replace(/^\s+|\s+$/g, '').split(/\s+/);
let outValueArray = [];
for (let i = 0; i < outArray.length; i++) {
if ((!isNaN(outArray[i]))) {
outValueArray.push(outArray[i]);
}
}
const ps = {};
ps.time = time;
ps.serverId = param.serverId;
ps.serverType = ps.serverId.split('-')[0];
ps.pid = param.pid;
const pid = ps.pid;
ps.cpuAvg = outValueArray[1];
ps.memAvg = outValueArray[2];
ps.vsz = outValueArray[3];
ps.rss = outValueArray[4];
outValueArray = [];
if (process.platform === 'darwin') {
ps.usr = 0;
ps.sys = 0;
ps.gue = 0;
cb(null, ps);
return;
}
exec(`pidstat -p ${pid}`, (err, output) => {
if (err) {
console.error('the command pidstat failed! ', err.stack);
return;
}
const _outArray = output.toString().replace(/^\s+|\s+$/g, '').split(/\s+/);
for (let i = 0; i < _outArray.length; i++) {
if ((!isNaN(_outArray[i]))) {
outValueArray.push(_outArray[i]);
}
}
ps.usr = outValueArray[1];
ps.sys = outValueArray[2];
ps.gue = outValueArray[3];
cb(null, ps);
});
}
|
javascript
|
function format(param, data, cb) {
const time = util.formatTime(new Date());
const outArray = data.toString().replace(/^\s+|\s+$/g, '').split(/\s+/);
let outValueArray = [];
for (let i = 0; i < outArray.length; i++) {
if ((!isNaN(outArray[i]))) {
outValueArray.push(outArray[i]);
}
}
const ps = {};
ps.time = time;
ps.serverId = param.serverId;
ps.serverType = ps.serverId.split('-')[0];
ps.pid = param.pid;
const pid = ps.pid;
ps.cpuAvg = outValueArray[1];
ps.memAvg = outValueArray[2];
ps.vsz = outValueArray[3];
ps.rss = outValueArray[4];
outValueArray = [];
if (process.platform === 'darwin') {
ps.usr = 0;
ps.sys = 0;
ps.gue = 0;
cb(null, ps);
return;
}
exec(`pidstat -p ${pid}`, (err, output) => {
if (err) {
console.error('the command pidstat failed! ', err.stack);
return;
}
const _outArray = output.toString().replace(/^\s+|\s+$/g, '').split(/\s+/);
for (let i = 0; i < _outArray.length; i++) {
if ((!isNaN(_outArray[i]))) {
outValueArray.push(_outArray[i]);
}
}
ps.usr = outValueArray[1];
ps.sys = outValueArray[2];
ps.gue = outValueArray[3];
cb(null, ps);
});
}
|
[
"function",
"format",
"(",
"param",
",",
"data",
",",
"cb",
")",
"{",
"const",
"time",
"=",
"util",
".",
"formatTime",
"(",
"new",
"Date",
"(",
")",
")",
";",
"const",
"outArray",
"=",
"data",
".",
"toString",
"(",
")",
".",
"replace",
"(",
"/",
"^\\s+|\\s+$",
"/",
"g",
",",
"''",
")",
".",
"split",
"(",
"/",
"\\s+",
"/",
")",
";",
"let",
"outValueArray",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"outArray",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"(",
"!",
"isNaN",
"(",
"outArray",
"[",
"i",
"]",
")",
")",
")",
"{",
"outValueArray",
".",
"push",
"(",
"outArray",
"[",
"i",
"]",
")",
";",
"}",
"}",
"const",
"ps",
"=",
"{",
"}",
";",
"ps",
".",
"time",
"=",
"time",
";",
"ps",
".",
"serverId",
"=",
"param",
".",
"serverId",
";",
"ps",
".",
"serverType",
"=",
"ps",
".",
"serverId",
".",
"split",
"(",
"'-'",
")",
"[",
"0",
"]",
";",
"ps",
".",
"pid",
"=",
"param",
".",
"pid",
";",
"const",
"pid",
"=",
"ps",
".",
"pid",
";",
"ps",
".",
"cpuAvg",
"=",
"outValueArray",
"[",
"1",
"]",
";",
"ps",
".",
"memAvg",
"=",
"outValueArray",
"[",
"2",
"]",
";",
"ps",
".",
"vsz",
"=",
"outValueArray",
"[",
"3",
"]",
";",
"ps",
".",
"rss",
"=",
"outValueArray",
"[",
"4",
"]",
";",
"outValueArray",
"=",
"[",
"]",
";",
"if",
"(",
"process",
".",
"platform",
"===",
"'darwin'",
")",
"{",
"ps",
".",
"usr",
"=",
"0",
";",
"ps",
".",
"sys",
"=",
"0",
";",
"ps",
".",
"gue",
"=",
"0",
";",
"cb",
"(",
"null",
",",
"ps",
")",
";",
"return",
";",
"}",
"exec",
"(",
"`",
"${",
"pid",
"}",
"`",
",",
"(",
"err",
",",
"output",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"'the command pidstat failed! '",
",",
"err",
".",
"stack",
")",
";",
"return",
";",
"}",
"const",
"_outArray",
"=",
"output",
".",
"toString",
"(",
")",
".",
"replace",
"(",
"/",
"^\\s+|\\s+$",
"/",
"g",
",",
"''",
")",
".",
"split",
"(",
"/",
"\\s+",
"/",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"_outArray",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"(",
"!",
"isNaN",
"(",
"_outArray",
"[",
"i",
"]",
")",
")",
")",
"{",
"outValueArray",
".",
"push",
"(",
"_outArray",
"[",
"i",
"]",
")",
";",
"}",
"}",
"ps",
".",
"usr",
"=",
"outValueArray",
"[",
"1",
"]",
";",
"ps",
".",
"sys",
"=",
"outValueArray",
"[",
"2",
"]",
";",
"ps",
".",
"gue",
"=",
"outValueArray",
"[",
"3",
"]",
";",
"cb",
"(",
"null",
",",
"ps",
")",
";",
"}",
")",
";",
"}"
] |
convert serverInfo to required format, and the callback will handle the serverInfo
@param {Object} param, contains serverId etc
@param {String} data, the output if the command 'ps'
@param {Function} cb
@api private
|
[
"convert",
"serverInfo",
"to",
"required",
"format",
"and",
"the",
"callback",
"will",
"handle",
"the",
"serverInfo"
] |
c9e18d386f48a9bfca9dcb6211229cea3a0eed0e
|
https://github.com/JohnnieFucker/dreamix-monitor/blob/c9e18d386f48a9bfca9dcb6211229cea3a0eed0e/lib/processMonitor.js#L18-L62
|
50,759
|
eliranmal/npm-package-env
|
lib/namespace.js
|
slice
|
function slice(toToken) {
if (has(toToken) && !isLast(toToken)) {
_tokens = _tokens.slice(0, _tokens.lastIndexOf(toToken) + 1);
}
}
|
javascript
|
function slice(toToken) {
if (has(toToken) && !isLast(toToken)) {
_tokens = _tokens.slice(0, _tokens.lastIndexOf(toToken) + 1);
}
}
|
[
"function",
"slice",
"(",
"toToken",
")",
"{",
"if",
"(",
"has",
"(",
"toToken",
")",
"&&",
"!",
"isLast",
"(",
"toToken",
")",
")",
"{",
"_tokens",
"=",
"_tokens",
".",
"slice",
"(",
"0",
",",
"_tokens",
".",
"lastIndexOf",
"(",
"toToken",
")",
"+",
"1",
")",
";",
"}",
"}"
] |
removes last tokens, up to and not including the specified token.
@param toToken the token to back into (exclusive!)
|
[
"removes",
"last",
"tokens",
"up",
"to",
"and",
"not",
"including",
"the",
"specified",
"token",
"."
] |
4af33e9e388f72b895b27c00bbbe29407715b7b5
|
https://github.com/eliranmal/npm-package-env/blob/4af33e9e388f72b895b27c00bbbe29407715b7b5/lib/namespace.js#L39-L43
|
50,760
|
vkiding/judpack-lib
|
src/plugman/fetch.js
|
checkID
|
function checkID(expectedIdAndVersion, pinfo) {
if (!expectedIdAndVersion) return;
var parsedSpec = pluginSpec.parse(expectedIdAndVersion);
if (parsedSpec.id != pinfo.id) {
var alias = parsedSpec.scope ? null : pluginMappernto[parsedSpec.id] || pluginMapperotn[parsedSpec.id];
if (alias !== pinfo.id) {
throw new Error('Expected plugin to have ID "' + parsedSpec.id + '" but got "' + pinfo.id + '".');
}
}
if (parsedSpec.version && !semver.satisfies(pinfo.version, parsedSpec.version)) {
throw new Error('Expected plugin ' + pinfo.id + ' to satisfy version "' + parsedSpec.version + '" but got "' + pinfo.version + '".');
}
}
|
javascript
|
function checkID(expectedIdAndVersion, pinfo) {
if (!expectedIdAndVersion) return;
var parsedSpec = pluginSpec.parse(expectedIdAndVersion);
if (parsedSpec.id != pinfo.id) {
var alias = parsedSpec.scope ? null : pluginMappernto[parsedSpec.id] || pluginMapperotn[parsedSpec.id];
if (alias !== pinfo.id) {
throw new Error('Expected plugin to have ID "' + parsedSpec.id + '" but got "' + pinfo.id + '".');
}
}
if (parsedSpec.version && !semver.satisfies(pinfo.version, parsedSpec.version)) {
throw new Error('Expected plugin ' + pinfo.id + ' to satisfy version "' + parsedSpec.version + '" but got "' + pinfo.version + '".');
}
}
|
[
"function",
"checkID",
"(",
"expectedIdAndVersion",
",",
"pinfo",
")",
"{",
"if",
"(",
"!",
"expectedIdAndVersion",
")",
"return",
";",
"var",
"parsedSpec",
"=",
"pluginSpec",
".",
"parse",
"(",
"expectedIdAndVersion",
")",
";",
"if",
"(",
"parsedSpec",
".",
"id",
"!=",
"pinfo",
".",
"id",
")",
"{",
"var",
"alias",
"=",
"parsedSpec",
".",
"scope",
"?",
"null",
":",
"pluginMappernto",
"[",
"parsedSpec",
".",
"id",
"]",
"||",
"pluginMapperotn",
"[",
"parsedSpec",
".",
"id",
"]",
";",
"if",
"(",
"alias",
"!==",
"pinfo",
".",
"id",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Expected plugin to have ID \"'",
"+",
"parsedSpec",
".",
"id",
"+",
"'\" but got \"'",
"+",
"pinfo",
".",
"id",
"+",
"'\".'",
")",
";",
"}",
"}",
"if",
"(",
"parsedSpec",
".",
"version",
"&&",
"!",
"semver",
".",
"satisfies",
"(",
"pinfo",
".",
"version",
",",
"parsedSpec",
".",
"version",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Expected plugin '",
"+",
"pinfo",
".",
"id",
"+",
"' to satisfy version \"'",
"+",
"parsedSpec",
".",
"version",
"+",
"'\" but got \"'",
"+",
"pinfo",
".",
"version",
"+",
"'\".'",
")",
";",
"}",
"}"
] |
Helper function for checking expected plugin IDs against reality.
|
[
"Helper",
"function",
"for",
"checking",
"expected",
"plugin",
"IDs",
"against",
"reality",
"."
] |
8657cecfec68221109279106adca8dbc81f430f4
|
https://github.com/vkiding/judpack-lib/blob/8657cecfec68221109279106adca8dbc81f430f4/src/plugman/fetch.js#L217-L229
|
50,761
|
bholloway/gulp-track-filenames
|
index.js
|
function() {
return through.obj(function(file, encode, done){
addBefore(file.path);
this.push(file);
done();
});
}
|
javascript
|
function() {
return through.obj(function(file, encode, done){
addBefore(file.path);
this.push(file);
done();
});
}
|
[
"function",
"(",
")",
"{",
"return",
"through",
".",
"obj",
"(",
"function",
"(",
"file",
",",
"encode",
",",
"done",
")",
"{",
"addBefore",
"(",
"file",
".",
"path",
")",
";",
"this",
".",
"push",
"(",
"file",
")",
";",
"done",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Consider file names from the input stream as those before transformation.
Outputs a stream of the same files.
@returns {stream.Through} A through stream that performs the operation of a gulp stream
|
[
"Consider",
"file",
"names",
"from",
"the",
"input",
"stream",
"as",
"those",
"before",
"transformation",
".",
"Outputs",
"a",
"stream",
"of",
"the",
"same",
"files",
"."
] |
12b2410061ab4d3be51e0966cc1578b1d0a8eeb3
|
https://github.com/bholloway/gulp-track-filenames/blob/12b2410061ab4d3be51e0966cc1578b1d0a8eeb3/index.js#L38-L44
|
|
50,762
|
bholloway/gulp-track-filenames
|
index.js
|
function() {
return through.obj(function(file, encode, done){
addAfter(file.path);
this.push(file);
done();
});
}
|
javascript
|
function() {
return through.obj(function(file, encode, done){
addAfter(file.path);
this.push(file);
done();
});
}
|
[
"function",
"(",
")",
"{",
"return",
"through",
".",
"obj",
"(",
"function",
"(",
"file",
",",
"encode",
",",
"done",
")",
"{",
"addAfter",
"(",
"file",
".",
"path",
")",
";",
"this",
".",
"push",
"(",
"file",
")",
";",
"done",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Consider file names from the input stream as those after transformation.
Order must be preserved so as to correctly match the corresponding before files.
Outputs a stream of the same files.
@returns {stream.Through} A through stream that performs the operation of a gulp stream
|
[
"Consider",
"file",
"names",
"from",
"the",
"input",
"stream",
"as",
"those",
"after",
"transformation",
".",
"Order",
"must",
"be",
"preserved",
"so",
"as",
"to",
"correctly",
"match",
"the",
"corresponding",
"before",
"files",
".",
"Outputs",
"a",
"stream",
"of",
"the",
"same",
"files",
"."
] |
12b2410061ab4d3be51e0966cc1578b1d0a8eeb3
|
https://github.com/bholloway/gulp-track-filenames/blob/12b2410061ab4d3be51e0966cc1578b1d0a8eeb3/index.js#L52-L58
|
|
50,763
|
subfuzion/snapfinder-lib
|
lib/snapdb.js
|
connect
|
function connect(uri, callback) {
console.log('connecting to database (' + uri + ')');
mongo.MongoClient.connect(uri, {safe: true}, function (err, client) {
if (err) return callback(err);
db = client;
db.addListener("error", function (error) {
console.log("mongo client error: " + error);
});
callback(null, db);
});
}
|
javascript
|
function connect(uri, callback) {
console.log('connecting to database (' + uri + ')');
mongo.MongoClient.connect(uri, {safe: true}, function (err, client) {
if (err) return callback(err);
db = client;
db.addListener("error", function (error) {
console.log("mongo client error: " + error);
});
callback(null, db);
});
}
|
[
"function",
"connect",
"(",
"uri",
",",
"callback",
")",
"{",
"console",
".",
"log",
"(",
"'connecting to database ('",
"+",
"uri",
"+",
"')'",
")",
";",
"mongo",
".",
"MongoClient",
".",
"connect",
"(",
"uri",
",",
"{",
"safe",
":",
"true",
"}",
",",
"function",
"(",
"err",
",",
"client",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"db",
"=",
"client",
";",
"db",
".",
"addListener",
"(",
"\"error\"",
",",
"function",
"(",
"error",
")",
"{",
"console",
".",
"log",
"(",
"\"mongo client error: \"",
"+",
"error",
")",
";",
"}",
")",
";",
"callback",
"(",
"null",
",",
"db",
")",
";",
"}",
")",
";",
"}"
] |
Connect to snapdb mongo database.
|
[
"Connect",
"to",
"snapdb",
"mongo",
"database",
"."
] |
121172f10a9ec64bc5f3d749fba97662b336caae
|
https://github.com/subfuzion/snapfinder-lib/blob/121172f10a9ec64bc5f3d749fba97662b336caae/lib/snapdb.js#L17-L29
|
50,764
|
subfuzion/snapfinder-lib
|
lib/snapdb.js
|
findStoresInZip
|
function findStoresInZip(zip, callback) {
var zip5 = typeof(zip) == 'string' ? parseInt(zip, 10) : zip;
db.collection(stores, function(err, collection) {
if (err) return callback(err);
collection.find({zip5:zip5}).toArray(function(err, docs) {
if (err) return callback(err);
callback(null, docs);
})
})
}
|
javascript
|
function findStoresInZip(zip, callback) {
var zip5 = typeof(zip) == 'string' ? parseInt(zip, 10) : zip;
db.collection(stores, function(err, collection) {
if (err) return callback(err);
collection.find({zip5:zip5}).toArray(function(err, docs) {
if (err) return callback(err);
callback(null, docs);
})
})
}
|
[
"function",
"findStoresInZip",
"(",
"zip",
",",
"callback",
")",
"{",
"var",
"zip5",
"=",
"typeof",
"(",
"zip",
")",
"==",
"'string'",
"?",
"parseInt",
"(",
"zip",
",",
"10",
")",
":",
"zip",
";",
"db",
".",
"collection",
"(",
"stores",
",",
"function",
"(",
"err",
",",
"collection",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"collection",
".",
"find",
"(",
"{",
"zip5",
":",
"zip5",
"}",
")",
".",
"toArray",
"(",
"function",
"(",
"err",
",",
"docs",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"callback",
"(",
"null",
",",
"docs",
")",
";",
"}",
")",
"}",
")",
"}"
] |
Find all the stores within a zip code.
|
[
"Find",
"all",
"the",
"stores",
"within",
"a",
"zip",
"code",
"."
] |
121172f10a9ec64bc5f3d749fba97662b336caae
|
https://github.com/subfuzion/snapfinder-lib/blob/121172f10a9ec64bc5f3d749fba97662b336caae/lib/snapdb.js#L80-L91
|
50,765
|
Wizcorp/component-hint
|
lib/component-hint.js
|
ComponentHint
|
function ComponentHint(options) {
// Make this an event emitter
EventEmitter.call(this);
// List of all components that have been checked, we keep this list so that the same components
// are not checked twice.
this.lintedComponents = [];
// Object holding all external dependencies and their versions
this.dependencyVersions = {};
// Set linting options from given options or defaults
options = options || {};
this.depPaths = options.depPaths || [];
this.lookupPaths = options.lookupPaths || [];
this.recursive = options.recursive || false;
this.verbose = options.verbose || false;
this.quiet = options.quiet || false;
this.silent = options.silent || false;
this.ignorePaths = options.ignorePaths || [];
this.warnPaths = options.warnPaths || [];
// Inject default dep path if it exists
if (!this.depPaths.length && fs.existsSync('./components')) {
this.depPaths.push('./components');
}
// Keep a count of total errors and warnings
this.totalErrors = 0;
this.on('lint.error', function () {
this.totalErrors += 1;
});
this.totalWarnings = 0;
this.on('lint.warning', function () {
this.totalWarnings += 1;
});
}
|
javascript
|
function ComponentHint(options) {
// Make this an event emitter
EventEmitter.call(this);
// List of all components that have been checked, we keep this list so that the same components
// are not checked twice.
this.lintedComponents = [];
// Object holding all external dependencies and their versions
this.dependencyVersions = {};
// Set linting options from given options or defaults
options = options || {};
this.depPaths = options.depPaths || [];
this.lookupPaths = options.lookupPaths || [];
this.recursive = options.recursive || false;
this.verbose = options.verbose || false;
this.quiet = options.quiet || false;
this.silent = options.silent || false;
this.ignorePaths = options.ignorePaths || [];
this.warnPaths = options.warnPaths || [];
// Inject default dep path if it exists
if (!this.depPaths.length && fs.existsSync('./components')) {
this.depPaths.push('./components');
}
// Keep a count of total errors and warnings
this.totalErrors = 0;
this.on('lint.error', function () {
this.totalErrors += 1;
});
this.totalWarnings = 0;
this.on('lint.warning', function () {
this.totalWarnings += 1;
});
}
|
[
"function",
"ComponentHint",
"(",
"options",
")",
"{",
"// Make this an event emitter",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"// List of all components that have been checked, we keep this list so that the same components",
"// are not checked twice.",
"this",
".",
"lintedComponents",
"=",
"[",
"]",
";",
"// Object holding all external dependencies and their versions",
"this",
".",
"dependencyVersions",
"=",
"{",
"}",
";",
"// Set linting options from given options or defaults",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"depPaths",
"=",
"options",
".",
"depPaths",
"||",
"[",
"]",
";",
"this",
".",
"lookupPaths",
"=",
"options",
".",
"lookupPaths",
"||",
"[",
"]",
";",
"this",
".",
"recursive",
"=",
"options",
".",
"recursive",
"||",
"false",
";",
"this",
".",
"verbose",
"=",
"options",
".",
"verbose",
"||",
"false",
";",
"this",
".",
"quiet",
"=",
"options",
".",
"quiet",
"||",
"false",
";",
"this",
".",
"silent",
"=",
"options",
".",
"silent",
"||",
"false",
";",
"this",
".",
"ignorePaths",
"=",
"options",
".",
"ignorePaths",
"||",
"[",
"]",
";",
"this",
".",
"warnPaths",
"=",
"options",
".",
"warnPaths",
"||",
"[",
"]",
";",
"// Inject default dep path if it exists",
"if",
"(",
"!",
"this",
".",
"depPaths",
".",
"length",
"&&",
"fs",
".",
"existsSync",
"(",
"'./components'",
")",
")",
"{",
"this",
".",
"depPaths",
".",
"push",
"(",
"'./components'",
")",
";",
"}",
"// Keep a count of total errors and warnings",
"this",
".",
"totalErrors",
"=",
"0",
";",
"this",
".",
"on",
"(",
"'lint.error'",
",",
"function",
"(",
")",
"{",
"this",
".",
"totalErrors",
"+=",
"1",
";",
"}",
")",
";",
"this",
".",
"totalWarnings",
"=",
"0",
";",
"this",
".",
"on",
"(",
"'lint.warning'",
",",
"function",
"(",
")",
"{",
"this",
".",
"totalWarnings",
"+=",
"1",
";",
"}",
")",
";",
"}"
] |
Component Hint event emitter object.
@param {Object} options
@returns {ComponentHint}
|
[
"Component",
"Hint",
"event",
"emitter",
"object",
"."
] |
ccd314a9af5dc5b7cb24dc06227c4b95f2034b19
|
https://github.com/Wizcorp/component-hint/blob/ccd314a9af5dc5b7cb24dc06227c4b95f2034b19/lib/component-hint.js#L57-L94
|
50,766
|
copress/copress-component-oauth2
|
lib/oauth2-helper.js
|
isScopeAllowed
|
function isScopeAllowed(allowedScopes, tokenScopes) {
allowedScopes = normalizeScope(allowedScopes);
tokenScopes = normalizeScope(tokenScopes);
if (allowedScopes.length === 0) {
return true;
}
for (var i = 0, n = allowedScopes.length; i < n; i++) {
if (tokenScopes.indexOf(allowedScopes[i]) !== -1) {
return true;
}
}
return false;
}
|
javascript
|
function isScopeAllowed(allowedScopes, tokenScopes) {
allowedScopes = normalizeScope(allowedScopes);
tokenScopes = normalizeScope(tokenScopes);
if (allowedScopes.length === 0) {
return true;
}
for (var i = 0, n = allowedScopes.length; i < n; i++) {
if (tokenScopes.indexOf(allowedScopes[i]) !== -1) {
return true;
}
}
return false;
}
|
[
"function",
"isScopeAllowed",
"(",
"allowedScopes",
",",
"tokenScopes",
")",
"{",
"allowedScopes",
"=",
"normalizeScope",
"(",
"allowedScopes",
")",
";",
"tokenScopes",
"=",
"normalizeScope",
"(",
"tokenScopes",
")",
";",
"if",
"(",
"allowedScopes",
".",
"length",
"===",
"0",
")",
"{",
"return",
"true",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"allowedScopes",
".",
"length",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"if",
"(",
"tokenScopes",
".",
"indexOf",
"(",
"allowedScopes",
"[",
"i",
"]",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Check if one of the scopes is in the allowedScopes array
@param {String[]} allowedScopes An array of required scopes
@param {String[]} scopes An array of granted scopes
@returns {boolean}
|
[
"Check",
"if",
"one",
"of",
"the",
"scopes",
"is",
"in",
"the",
"allowedScopes",
"array"
] |
4819f379a0d42753bfd51e237c5c3aaddee37544
|
https://github.com/copress/copress-component-oauth2/blob/4819f379a0d42753bfd51e237c5c3aaddee37544/lib/oauth2-helper.js#L66-L78
|
50,767
|
copress/copress-component-oauth2
|
lib/oauth2-helper.js
|
isScopeAuthorized
|
function isScopeAuthorized(requestedScopes, authorizedScopes) {
requestedScopes = normalizeScope(requestedScopes);
authorizedScopes = normalizeScope(authorizedScopes);
if (requestedScopes.length === 0) {
return true;
}
for (var i = 0, n = requestedScopes.length; i < n; i++) {
if (authorizedScopes.indexOf(requestedScopes[i]) === -1) {
return false;
}
}
return true;
}
|
javascript
|
function isScopeAuthorized(requestedScopes, authorizedScopes) {
requestedScopes = normalizeScope(requestedScopes);
authorizedScopes = normalizeScope(authorizedScopes);
if (requestedScopes.length === 0) {
return true;
}
for (var i = 0, n = requestedScopes.length; i < n; i++) {
if (authorizedScopes.indexOf(requestedScopes[i]) === -1) {
return false;
}
}
return true;
}
|
[
"function",
"isScopeAuthorized",
"(",
"requestedScopes",
",",
"authorizedScopes",
")",
"{",
"requestedScopes",
"=",
"normalizeScope",
"(",
"requestedScopes",
")",
";",
"authorizedScopes",
"=",
"normalizeScope",
"(",
"authorizedScopes",
")",
";",
"if",
"(",
"requestedScopes",
".",
"length",
"===",
"0",
")",
"{",
"return",
"true",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"requestedScopes",
".",
"length",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"if",
"(",
"authorizedScopes",
".",
"indexOf",
"(",
"requestedScopes",
"[",
"i",
"]",
")",
"===",
"-",
"1",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
Check if the requested scopes are covered by authorized scopes
@param {String|String[]) requestedScopes
@param {String|String[]) authorizedScopes
@returns {boolean}
|
[
"Check",
"if",
"the",
"requested",
"scopes",
"are",
"covered",
"by",
"authorized",
"scopes"
] |
4819f379a0d42753bfd51e237c5c3aaddee37544
|
https://github.com/copress/copress-component-oauth2/blob/4819f379a0d42753bfd51e237c5c3aaddee37544/lib/oauth2-helper.js#L86-L98
|
50,768
|
muniere/node-behalter
|
lib/behalter.js
|
Behalter
|
function Behalter(parent, options) {
// normalize arguments for the case of `new Behalter(options)`
if (arguments.length === 1 && !(parent instanceof Behalter) && _.isPlainObject(parent)) {
options = parent;
parent = void 0;
}
// for hierarchical search, validate type of parent
if (parent && !(parent instanceof Behalter)) {
throw new TypeError('parent must be an instance of Behalter');
}
// construct this with super constructor
EventEmitter2.call(this, options);
// configure default properties
this.__parent = parent;
this.__values = {};
this.__factories = {};
// configure options: to INHERIT options, configure only for root
if (!parent) {
this.__options = {
useGetter: true,
useSetter: false
};
} else {
this.__options = {};
}
}
|
javascript
|
function Behalter(parent, options) {
// normalize arguments for the case of `new Behalter(options)`
if (arguments.length === 1 && !(parent instanceof Behalter) && _.isPlainObject(parent)) {
options = parent;
parent = void 0;
}
// for hierarchical search, validate type of parent
if (parent && !(parent instanceof Behalter)) {
throw new TypeError('parent must be an instance of Behalter');
}
// construct this with super constructor
EventEmitter2.call(this, options);
// configure default properties
this.__parent = parent;
this.__values = {};
this.__factories = {};
// configure options: to INHERIT options, configure only for root
if (!parent) {
this.__options = {
useGetter: true,
useSetter: false
};
} else {
this.__options = {};
}
}
|
[
"function",
"Behalter",
"(",
"parent",
",",
"options",
")",
"{",
"// normalize arguments for the case of `new Behalter(options)`",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
"&&",
"!",
"(",
"parent",
"instanceof",
"Behalter",
")",
"&&",
"_",
".",
"isPlainObject",
"(",
"parent",
")",
")",
"{",
"options",
"=",
"parent",
";",
"parent",
"=",
"void",
"0",
";",
"}",
"// for hierarchical search, validate type of parent",
"if",
"(",
"parent",
"&&",
"!",
"(",
"parent",
"instanceof",
"Behalter",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'parent must be an instance of Behalter'",
")",
";",
"}",
"// construct this with super constructor",
"EventEmitter2",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"// configure default properties",
"this",
".",
"__parent",
"=",
"parent",
";",
"this",
".",
"__values",
"=",
"{",
"}",
";",
"this",
".",
"__factories",
"=",
"{",
"}",
";",
"// configure options: to INHERIT options, configure only for root",
"if",
"(",
"!",
"parent",
")",
"{",
"this",
".",
"__options",
"=",
"{",
"useGetter",
":",
"true",
",",
"useSetter",
":",
"false",
"}",
";",
"}",
"else",
"{",
"this",
".",
"__options",
"=",
"{",
"}",
";",
"}",
"}"
] |
Create a new behalter.
@param {(Behalter|Object)} [parent]
@param {Object} [options={}]
@constructor
|
[
"Create",
"a",
"new",
"behalter",
"."
] |
e991c9cad610f1268c6012c3042fbc3fa9802fee
|
https://github.com/muniere/node-behalter/blob/e991c9cad610f1268c6012c3042fbc3fa9802fee/lib/behalter.js#L16-L46
|
50,769
|
muniere/node-behalter
|
lib/behalter.js
|
reserved
|
function reserved(name) {
if (!_.isString(name)) {
return false;
}
return _.contains(RESERVED, name);
}
|
javascript
|
function reserved(name) {
if (!_.isString(name)) {
return false;
}
return _.contains(RESERVED, name);
}
|
[
"function",
"reserved",
"(",
"name",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isString",
"(",
"name",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"_",
".",
"contains",
"(",
"RESERVED",
",",
"name",
")",
";",
"}"
] |
Judge if name is reserved word or not.
@param {string} name
@returns {boolean} true if reserved
|
[
"Judge",
"if",
"name",
"is",
"reserved",
"word",
"or",
"not",
"."
] |
e991c9cad610f1268c6012c3042fbc3fa9802fee
|
https://github.com/muniere/node-behalter/blob/e991c9cad610f1268c6012c3042fbc3fa9802fee/lib/behalter.js#L427-L433
|
50,770
|
muniere/node-behalter
|
lib/behalter.js
|
annotate
|
function annotate(fn) {
var matched = /function +[^\(]*\(([^\)]*)\).*/.exec(fn.toString());
var names = _.reject(matched[1].split(',') || [], _.isEmpty);
return _.map(names, function(name) {
return name.replace(/\s+/g, '');
});
}
|
javascript
|
function annotate(fn) {
var matched = /function +[^\(]*\(([^\)]*)\).*/.exec(fn.toString());
var names = _.reject(matched[1].split(',') || [], _.isEmpty);
return _.map(names, function(name) {
return name.replace(/\s+/g, '');
});
}
|
[
"function",
"annotate",
"(",
"fn",
")",
"{",
"var",
"matched",
"=",
"/",
"function +[^\\(]*\\(([^\\)]*)\\).*",
"/",
".",
"exec",
"(",
"fn",
".",
"toString",
"(",
")",
")",
";",
"var",
"names",
"=",
"_",
".",
"reject",
"(",
"matched",
"[",
"1",
"]",
".",
"split",
"(",
"','",
")",
"||",
"[",
"]",
",",
"_",
".",
"isEmpty",
")",
";",
"return",
"_",
".",
"map",
"(",
"names",
",",
"function",
"(",
"name",
")",
"{",
"return",
"name",
".",
"replace",
"(",
"/",
"\\s+",
"/",
"g",
",",
"''",
")",
";",
"}",
")",
";",
"}"
] |
Extract names of arguments for function.
@param {function} fn
@returns {string[]} names of arguments
|
[
"Extract",
"names",
"of",
"arguments",
"for",
"function",
"."
] |
e991c9cad610f1268c6012c3042fbc3fa9802fee
|
https://github.com/muniere/node-behalter/blob/e991c9cad610f1268c6012c3042fbc3fa9802fee/lib/behalter.js#L441-L448
|
50,771
|
ex-machine/express-ko
|
lib/index.js
|
ko
|
function ko(fn, isParamHandler) {
// handlers and middlewares may have safeguard properties to be skipped
if ('$$koified' in fn) {
return fn;
}
let handler = function (req, res, next) {
let argsLength = arguments.length;
let args = new Array(argsLength);
for (let i = 0; i < argsLength; i++) {
args[i] = arguments[i];
}
return ko.ifyHandler(fn, args);
};
let errHandler = function (err, req, res, next) {
let argsLength = arguments.length;
let args = new Array(argsLength);
for (let i = 0; i < argsLength; i++) {
args[i] = arguments[i];
}
return ko.ifyHandler(fn, args, true);
};
let paramHandler = function (req, res, next, val) {
let argsLength = arguments.length;
let args = new Array(argsLength);
for (let i = 0; i < argsLength; i++) {
args[i] = arguments[i];
}
return ko.ifyHandler(fn, args);
};
let wrapper;
// the way Express distinguishes error handlers from regular ones
if (fn.length === 4) {
wrapper = isParamHandler ? paramHandler : errHandler;
} else {
wrapper = handler;
}
// safeguard
Object.defineProperty(wrapper, '$$koified', {
configurable: true,
writable: true,
value: true
});
return wrapper;
}
|
javascript
|
function ko(fn, isParamHandler) {
// handlers and middlewares may have safeguard properties to be skipped
if ('$$koified' in fn) {
return fn;
}
let handler = function (req, res, next) {
let argsLength = arguments.length;
let args = new Array(argsLength);
for (let i = 0; i < argsLength; i++) {
args[i] = arguments[i];
}
return ko.ifyHandler(fn, args);
};
let errHandler = function (err, req, res, next) {
let argsLength = arguments.length;
let args = new Array(argsLength);
for (let i = 0; i < argsLength; i++) {
args[i] = arguments[i];
}
return ko.ifyHandler(fn, args, true);
};
let paramHandler = function (req, res, next, val) {
let argsLength = arguments.length;
let args = new Array(argsLength);
for (let i = 0; i < argsLength; i++) {
args[i] = arguments[i];
}
return ko.ifyHandler(fn, args);
};
let wrapper;
// the way Express distinguishes error handlers from regular ones
if (fn.length === 4) {
wrapper = isParamHandler ? paramHandler : errHandler;
} else {
wrapper = handler;
}
// safeguard
Object.defineProperty(wrapper, '$$koified', {
configurable: true,
writable: true,
value: true
});
return wrapper;
}
|
[
"function",
"ko",
"(",
"fn",
",",
"isParamHandler",
")",
"{",
"// handlers and middlewares may have safeguard properties to be skipped\r",
"if",
"(",
"'$$koified'",
"in",
"fn",
")",
"{",
"return",
"fn",
";",
"}",
"let",
"handler",
"=",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"let",
"argsLength",
"=",
"arguments",
".",
"length",
";",
"let",
"args",
"=",
"new",
"Array",
"(",
"argsLength",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"argsLength",
";",
"i",
"++",
")",
"{",
"args",
"[",
"i",
"]",
"=",
"arguments",
"[",
"i",
"]",
";",
"}",
"return",
"ko",
".",
"ifyHandler",
"(",
"fn",
",",
"args",
")",
";",
"}",
";",
"let",
"errHandler",
"=",
"function",
"(",
"err",
",",
"req",
",",
"res",
",",
"next",
")",
"{",
"let",
"argsLength",
"=",
"arguments",
".",
"length",
";",
"let",
"args",
"=",
"new",
"Array",
"(",
"argsLength",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"argsLength",
";",
"i",
"++",
")",
"{",
"args",
"[",
"i",
"]",
"=",
"arguments",
"[",
"i",
"]",
";",
"}",
"return",
"ko",
".",
"ifyHandler",
"(",
"fn",
",",
"args",
",",
"true",
")",
";",
"}",
";",
"let",
"paramHandler",
"=",
"function",
"(",
"req",
",",
"res",
",",
"next",
",",
"val",
")",
"{",
"let",
"argsLength",
"=",
"arguments",
".",
"length",
";",
"let",
"args",
"=",
"new",
"Array",
"(",
"argsLength",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"argsLength",
";",
"i",
"++",
")",
"{",
"args",
"[",
"i",
"]",
"=",
"arguments",
"[",
"i",
"]",
";",
"}",
"return",
"ko",
".",
"ifyHandler",
"(",
"fn",
",",
"args",
")",
";",
"}",
";",
"let",
"wrapper",
";",
"// the way Express distinguishes error handlers from regular ones\r",
"if",
"(",
"fn",
".",
"length",
"===",
"4",
")",
"{",
"wrapper",
"=",
"isParamHandler",
"?",
"paramHandler",
":",
"errHandler",
";",
"}",
"else",
"{",
"wrapper",
"=",
"handler",
";",
"}",
"// safeguard\r",
"Object",
".",
"defineProperty",
"(",
"wrapper",
",",
"'$$koified'",
",",
"{",
"configurable",
":",
"true",
",",
"writable",
":",
"true",
",",
"value",
":",
"true",
"}",
")",
";",
"return",
"wrapper",
";",
"}"
] |
Wraps a generator or promise-returning callback function
|
[
"Wraps",
"a",
"generator",
"or",
"promise",
"-",
"returning",
"callback",
"function"
] |
e45a2959274ab52e52b96933545fa5491d4a05a2
|
https://github.com/ex-machine/express-ko/blob/e45a2959274ab52e52b96933545fa5491d4a05a2/lib/index.js#L24-L80
|
50,772
|
ex-machine/express-ko
|
lib/index.js
|
koifyHandler
|
function koifyHandler(fn, args, isErrHandler) {
let fnResult;
if (isGeneratorFunction(fn)) {
fnResult = co(function* () {
return yield* fn(...args);
});
} else {
fnResult = fn(...args);
}
if (!isPromise(fnResult)) {
return fnResult;
}
let req, res, next;
if (isErrHandler) {
req = args[1];
res = args[2];
next = args[3];
} else {
req = args[0];
res = args[1];
next = args[2];
}
return fnResult.then((result) => {
// implicit 'next'
if ((result === req) || (result === res)) {
next();
// explicit 'next'
} else if ((isFunction(next) && (result === next)) || (result === ko.NEXT)) {
next();
} else if (result === ko.NEXT_ROUTE) {
next('route');
} else if (isError(result)) {
next(result);
} else if (result !== undefined) {
if (isNumber(result)) {
res.sendStatus(result);
} else {
res.send(result);
}
}
// exposed for testing
return result;
}, (err) => {
next(err);
return err;
});
}
|
javascript
|
function koifyHandler(fn, args, isErrHandler) {
let fnResult;
if (isGeneratorFunction(fn)) {
fnResult = co(function* () {
return yield* fn(...args);
});
} else {
fnResult = fn(...args);
}
if (!isPromise(fnResult)) {
return fnResult;
}
let req, res, next;
if (isErrHandler) {
req = args[1];
res = args[2];
next = args[3];
} else {
req = args[0];
res = args[1];
next = args[2];
}
return fnResult.then((result) => {
// implicit 'next'
if ((result === req) || (result === res)) {
next();
// explicit 'next'
} else if ((isFunction(next) && (result === next)) || (result === ko.NEXT)) {
next();
} else if (result === ko.NEXT_ROUTE) {
next('route');
} else if (isError(result)) {
next(result);
} else if (result !== undefined) {
if (isNumber(result)) {
res.sendStatus(result);
} else {
res.send(result);
}
}
// exposed for testing
return result;
}, (err) => {
next(err);
return err;
});
}
|
[
"function",
"koifyHandler",
"(",
"fn",
",",
"args",
",",
"isErrHandler",
")",
"{",
"let",
"fnResult",
";",
"if",
"(",
"isGeneratorFunction",
"(",
"fn",
")",
")",
"{",
"fnResult",
"=",
"co",
"(",
"function",
"*",
"(",
")",
"{",
"return",
"yield",
"*",
"fn",
"(",
"...",
"args",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"fnResult",
"=",
"fn",
"(",
"...",
"args",
")",
";",
"}",
"if",
"(",
"!",
"isPromise",
"(",
"fnResult",
")",
")",
"{",
"return",
"fnResult",
";",
"}",
"let",
"req",
",",
"res",
",",
"next",
";",
"if",
"(",
"isErrHandler",
")",
"{",
"req",
"=",
"args",
"[",
"1",
"]",
";",
"res",
"=",
"args",
"[",
"2",
"]",
";",
"next",
"=",
"args",
"[",
"3",
"]",
";",
"}",
"else",
"{",
"req",
"=",
"args",
"[",
"0",
"]",
";",
"res",
"=",
"args",
"[",
"1",
"]",
";",
"next",
"=",
"args",
"[",
"2",
"]",
";",
"}",
"return",
"fnResult",
".",
"then",
"(",
"(",
"result",
")",
"=>",
"{",
"// implicit 'next'\r",
"if",
"(",
"(",
"result",
"===",
"req",
")",
"||",
"(",
"result",
"===",
"res",
")",
")",
"{",
"next",
"(",
")",
";",
"// explicit 'next'\r",
"}",
"else",
"if",
"(",
"(",
"isFunction",
"(",
"next",
")",
"&&",
"(",
"result",
"===",
"next",
")",
")",
"||",
"(",
"result",
"===",
"ko",
".",
"NEXT",
")",
")",
"{",
"next",
"(",
")",
";",
"}",
"else",
"if",
"(",
"result",
"===",
"ko",
".",
"NEXT_ROUTE",
")",
"{",
"next",
"(",
"'route'",
")",
";",
"}",
"else",
"if",
"(",
"isError",
"(",
"result",
")",
")",
"{",
"next",
"(",
"result",
")",
";",
"}",
"else",
"if",
"(",
"result",
"!==",
"undefined",
")",
"{",
"if",
"(",
"isNumber",
"(",
"result",
")",
")",
"{",
"res",
".",
"sendStatus",
"(",
"result",
")",
";",
"}",
"else",
"{",
"res",
".",
"send",
"(",
"result",
")",
";",
"}",
"}",
"// exposed for testing\r",
"return",
"result",
";",
"}",
",",
"(",
"err",
")",
"=>",
"{",
"next",
"(",
"err",
")",
";",
"return",
"err",
";",
"}",
")",
";",
"}"
] |
Optionally co-ifies a generator, then chains a promise
|
[
"Optionally",
"co",
"-",
"ifies",
"a",
"generator",
"then",
"chains",
"a",
"promise"
] |
e45a2959274ab52e52b96933545fa5491d4a05a2
|
https://github.com/ex-machine/express-ko/blob/e45a2959274ab52e52b96933545fa5491d4a05a2/lib/index.js#L85-L137
|
50,773
|
ex-machine/express-ko
|
lib/index.js
|
koify
|
function koify() {
let args = slice.call(arguments);
let Router;
let Route;
if ((args.length === 1) && ('Router' in args[0]) && ('Route' in args[0])) {
let express = args[0];
Router = express.Router;
Route = express.Route;
} else {
Router = args[0];
Route = args[1];
}
if (Router) {
ko.ifyRouter(Router);
}
if (Route) {
ko.ifyRoute(Route);
}
return Router;
}
|
javascript
|
function koify() {
let args = slice.call(arguments);
let Router;
let Route;
if ((args.length === 1) && ('Router' in args[0]) && ('Route' in args[0])) {
let express = args[0];
Router = express.Router;
Route = express.Route;
} else {
Router = args[0];
Route = args[1];
}
if (Router) {
ko.ifyRouter(Router);
}
if (Route) {
ko.ifyRoute(Route);
}
return Router;
}
|
[
"function",
"koify",
"(",
")",
"{",
"let",
"args",
"=",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"let",
"Router",
";",
"let",
"Route",
";",
"if",
"(",
"(",
"args",
".",
"length",
"===",
"1",
")",
"&&",
"(",
"'Router'",
"in",
"args",
"[",
"0",
"]",
")",
"&&",
"(",
"'Route'",
"in",
"args",
"[",
"0",
"]",
")",
")",
"{",
"let",
"express",
"=",
"args",
"[",
"0",
"]",
";",
"Router",
"=",
"express",
".",
"Router",
";",
"Route",
"=",
"express",
".",
"Route",
";",
"}",
"else",
"{",
"Router",
"=",
"args",
"[",
"0",
"]",
";",
"Route",
"=",
"args",
"[",
"1",
"]",
";",
"}",
"if",
"(",
"Router",
")",
"{",
"ko",
".",
"ifyRouter",
"(",
"Router",
")",
";",
"}",
"if",
"(",
"Route",
")",
"{",
"ko",
".",
"ifyRoute",
"(",
"Route",
")",
";",
"}",
"return",
"Router",
";",
"}"
] |
Patches Express router
|
[
"Patches",
"Express",
"router"
] |
e45a2959274ab52e52b96933545fa5491d4a05a2
|
https://github.com/ex-machine/express-ko/blob/e45a2959274ab52e52b96933545fa5491d4a05a2/lib/index.js#L142-L166
|
50,774
|
ex-machine/express-ko
|
lib/index.js
|
koifyRouter
|
function koifyRouter(Router) {
// router factory function is the prototype
let routerPrototype = Router;
// original router methods
let routerPrototype_ = {};
// router duck testing
let routerMethods = Object.keys(routerPrototype).sort();
function isRouter(someRouter) {
let someRouterPrototype = Object.getPrototypeOf(someRouter);
let someRouterMethods = Object.keys(someRouterPrototype).sort();
return arrayEqual(someRouterMethods, routerMethods) && (typeof someRouterPrototype === 'function');
}
routerPrototype_.use = routerPrototype.use;
routerPrototype.use = function () {
let args = slice.call(arguments);
for (let i = 0; i < args.length; i++) {
let handler = args[i];
// don't wrap router instances
if (isFunction(handler) && !isRouter(handler)) {
args[i] = ko.ko(handler);
}
}
return routerPrototype_.use.apply(this, args);
};
routerPrototype_.param = routerPrototype.param;
routerPrototype.param = function () {
let args = slice.call(arguments);
let handler = args[1];
if (isFunction(handler)) {
// additional argument to indicate param handler
args[1] = ko.ko(handler, true);
}
return routerPrototype_.param.apply(this, args);
};
// safeguard
Object.defineProperty(routerPrototype, '$$koified', {
configurable: true,
writable: true,
value: false
});
return Router;
}
|
javascript
|
function koifyRouter(Router) {
// router factory function is the prototype
let routerPrototype = Router;
// original router methods
let routerPrototype_ = {};
// router duck testing
let routerMethods = Object.keys(routerPrototype).sort();
function isRouter(someRouter) {
let someRouterPrototype = Object.getPrototypeOf(someRouter);
let someRouterMethods = Object.keys(someRouterPrototype).sort();
return arrayEqual(someRouterMethods, routerMethods) && (typeof someRouterPrototype === 'function');
}
routerPrototype_.use = routerPrototype.use;
routerPrototype.use = function () {
let args = slice.call(arguments);
for (let i = 0; i < args.length; i++) {
let handler = args[i];
// don't wrap router instances
if (isFunction(handler) && !isRouter(handler)) {
args[i] = ko.ko(handler);
}
}
return routerPrototype_.use.apply(this, args);
};
routerPrototype_.param = routerPrototype.param;
routerPrototype.param = function () {
let args = slice.call(arguments);
let handler = args[1];
if (isFunction(handler)) {
// additional argument to indicate param handler
args[1] = ko.ko(handler, true);
}
return routerPrototype_.param.apply(this, args);
};
// safeguard
Object.defineProperty(routerPrototype, '$$koified', {
configurable: true,
writable: true,
value: false
});
return Router;
}
|
[
"function",
"koifyRouter",
"(",
"Router",
")",
"{",
"// router factory function is the prototype\r",
"let",
"routerPrototype",
"=",
"Router",
";",
"// original router methods\r",
"let",
"routerPrototype_",
"=",
"{",
"}",
";",
"// router duck testing\r",
"let",
"routerMethods",
"=",
"Object",
".",
"keys",
"(",
"routerPrototype",
")",
".",
"sort",
"(",
")",
";",
"function",
"isRouter",
"(",
"someRouter",
")",
"{",
"let",
"someRouterPrototype",
"=",
"Object",
".",
"getPrototypeOf",
"(",
"someRouter",
")",
";",
"let",
"someRouterMethods",
"=",
"Object",
".",
"keys",
"(",
"someRouterPrototype",
")",
".",
"sort",
"(",
")",
";",
"return",
"arrayEqual",
"(",
"someRouterMethods",
",",
"routerMethods",
")",
"&&",
"(",
"typeof",
"someRouterPrototype",
"===",
"'function'",
")",
";",
"}",
"routerPrototype_",
".",
"use",
"=",
"routerPrototype",
".",
"use",
";",
"routerPrototype",
".",
"use",
"=",
"function",
"(",
")",
"{",
"let",
"args",
"=",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"args",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"handler",
"=",
"args",
"[",
"i",
"]",
";",
"// don't wrap router instances\r",
"if",
"(",
"isFunction",
"(",
"handler",
")",
"&&",
"!",
"isRouter",
"(",
"handler",
")",
")",
"{",
"args",
"[",
"i",
"]",
"=",
"ko",
".",
"ko",
"(",
"handler",
")",
";",
"}",
"}",
"return",
"routerPrototype_",
".",
"use",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
";",
"routerPrototype_",
".",
"param",
"=",
"routerPrototype",
".",
"param",
";",
"routerPrototype",
".",
"param",
"=",
"function",
"(",
")",
"{",
"let",
"args",
"=",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"let",
"handler",
"=",
"args",
"[",
"1",
"]",
";",
"if",
"(",
"isFunction",
"(",
"handler",
")",
")",
"{",
"// additional argument to indicate param handler\r",
"args",
"[",
"1",
"]",
"=",
"ko",
".",
"ko",
"(",
"handler",
",",
"true",
")",
";",
"}",
"return",
"routerPrototype_",
".",
"param",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
";",
"// safeguard\r",
"Object",
".",
"defineProperty",
"(",
"routerPrototype",
",",
"'$$koified'",
",",
"{",
"configurable",
":",
"true",
",",
"writable",
":",
"true",
",",
"value",
":",
"false",
"}",
")",
";",
"return",
"Router",
";",
"}"
] |
Patches router methods
|
[
"Patches",
"router",
"methods"
] |
e45a2959274ab52e52b96933545fa5491d4a05a2
|
https://github.com/ex-machine/express-ko/blob/e45a2959274ab52e52b96933545fa5491d4a05a2/lib/index.js#L172-L227
|
50,775
|
ex-machine/express-ko
|
lib/index.js
|
koifyRoute
|
function koifyRoute(Route) {
let routePrototype = Route.prototype;
let routePrototype_ = {};
for (let method of [...methods, 'all']) {
routePrototype_[method] = routePrototype[method];
routePrototype[method] = function () {
let args = slice.call(arguments);
for (let i = 0; i < args.length; i++) {
let handler = args[i];
if (isFunction(handler)) {
args[i] = ko.ko(handler);
}
}
return routePrototype_[method].apply(this, args);
};
}
return Route;
}
|
javascript
|
function koifyRoute(Route) {
let routePrototype = Route.prototype;
let routePrototype_ = {};
for (let method of [...methods, 'all']) {
routePrototype_[method] = routePrototype[method];
routePrototype[method] = function () {
let args = slice.call(arguments);
for (let i = 0; i < args.length; i++) {
let handler = args[i];
if (isFunction(handler)) {
args[i] = ko.ko(handler);
}
}
return routePrototype_[method].apply(this, args);
};
}
return Route;
}
|
[
"function",
"koifyRoute",
"(",
"Route",
")",
"{",
"let",
"routePrototype",
"=",
"Route",
".",
"prototype",
";",
"let",
"routePrototype_",
"=",
"{",
"}",
";",
"for",
"(",
"let",
"method",
"of",
"[",
"...",
"methods",
",",
"'all'",
"]",
")",
"{",
"routePrototype_",
"[",
"method",
"]",
"=",
"routePrototype",
"[",
"method",
"]",
";",
"routePrototype",
"[",
"method",
"]",
"=",
"function",
"(",
")",
"{",
"let",
"args",
"=",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"args",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"handler",
"=",
"args",
"[",
"i",
"]",
";",
"if",
"(",
"isFunction",
"(",
"handler",
")",
")",
"{",
"args",
"[",
"i",
"]",
"=",
"ko",
".",
"ko",
"(",
"handler",
")",
";",
"}",
"}",
"return",
"routePrototype_",
"[",
"method",
"]",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
";",
"}",
"return",
"Route",
";",
"}"
] |
Patches route HTTP methods
|
[
"Patches",
"route",
"HTTP",
"methods"
] |
e45a2959274ab52e52b96933545fa5491d4a05a2
|
https://github.com/ex-machine/express-ko/blob/e45a2959274ab52e52b96933545fa5491d4a05a2/lib/index.js#L232-L254
|
50,776
|
gethuman/pancakes-recipe
|
utils/obj.utils.js
|
matchesCriteria
|
function matchesCriteria(data, criteria) {
data = data || {};
criteria = criteria || {};
var match = true;
_.each(criteria, function (val, key) {
var hasNotOperand = false;
if (_.isObject(val) && val['$ne'] ) {
hasNotOperand = true;
val = val['$ne'];
}
var dataValue = getNestedValue(data, key);
if (_.isString(val) && _.isArray(dataValue)) { // allows you to check if an array contains a value
match = (dataValue.indexOf(val) > -1);
}
else {
var vals = _.isArray(val) ? val : [val];
if (vals.indexOf(dataValue) < 0) {
match = false;
}
if ( hasNotOperand ) {
match = !match;
}
}
});
return match;
}
|
javascript
|
function matchesCriteria(data, criteria) {
data = data || {};
criteria = criteria || {};
var match = true;
_.each(criteria, function (val, key) {
var hasNotOperand = false;
if (_.isObject(val) && val['$ne'] ) {
hasNotOperand = true;
val = val['$ne'];
}
var dataValue = getNestedValue(data, key);
if (_.isString(val) && _.isArray(dataValue)) { // allows you to check if an array contains a value
match = (dataValue.indexOf(val) > -1);
}
else {
var vals = _.isArray(val) ? val : [val];
if (vals.indexOf(dataValue) < 0) {
match = false;
}
if ( hasNotOperand ) {
match = !match;
}
}
});
return match;
}
|
[
"function",
"matchesCriteria",
"(",
"data",
",",
"criteria",
")",
"{",
"data",
"=",
"data",
"||",
"{",
"}",
";",
"criteria",
"=",
"criteria",
"||",
"{",
"}",
";",
"var",
"match",
"=",
"true",
";",
"_",
".",
"each",
"(",
"criteria",
",",
"function",
"(",
"val",
",",
"key",
")",
"{",
"var",
"hasNotOperand",
"=",
"false",
";",
"if",
"(",
"_",
".",
"isObject",
"(",
"val",
")",
"&&",
"val",
"[",
"'$ne'",
"]",
")",
"{",
"hasNotOperand",
"=",
"true",
";",
"val",
"=",
"val",
"[",
"'$ne'",
"]",
";",
"}",
"var",
"dataValue",
"=",
"getNestedValue",
"(",
"data",
",",
"key",
")",
";",
"if",
"(",
"_",
".",
"isString",
"(",
"val",
")",
"&&",
"_",
".",
"isArray",
"(",
"dataValue",
")",
")",
"{",
"// allows you to check if an array contains a value",
"match",
"=",
"(",
"dataValue",
".",
"indexOf",
"(",
"val",
")",
">",
"-",
"1",
")",
";",
"}",
"else",
"{",
"var",
"vals",
"=",
"_",
".",
"isArray",
"(",
"val",
")",
"?",
"val",
":",
"[",
"val",
"]",
";",
"if",
"(",
"vals",
".",
"indexOf",
"(",
"dataValue",
")",
"<",
"0",
")",
"{",
"match",
"=",
"false",
";",
"}",
"if",
"(",
"hasNotOperand",
")",
"{",
"match",
"=",
"!",
"match",
";",
"}",
"}",
"}",
")",
";",
"return",
"match",
";",
"}"
] |
True if the given data matches the criteria. If criteria empty,
then always true
Examples
Obj: { a: 'monday', b: 'tuesday' } Criteria: { a: 'monday' } // true
Obj: { a: 'monday', b: 'tuesday' } Criteria: { a: 'tuesday' } // false
Obj: { a: 'monday', b: 'tuesday' } Criteria: { c: 'monday' } // false
Obj: { a: 'monday', b: 'tuesday' } Criteria: { a: { '$ne' : tuesday' } } // true
@param data
@param criteria
@returns {Boolean}
|
[
"True",
"if",
"the",
"given",
"data",
"matches",
"the",
"criteria",
".",
"If",
"criteria",
"empty",
"then",
"always",
"true"
] |
ea3feb8839e2edaf1b4577c052b8958953db4498
|
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/utils/obj.utils.js#L151-L179
|
50,777
|
vergeplayer/vQ
|
src/js/module/event.js
|
function (element, type, handler, context) {
var own = this;
//非Dom元素不处理
if (!(1 == element.nodeType || element.nodeType == 9 || element === window)|| !vQ.isFunction(handler)) {
return;
}
//获取传入参数
var args = slice.call(arguments);
//批量绑定事件处理
if (vQ.isArray(type)) {
return own._handleMultipleEvents.apply(own, [own.one].concat(args));
//return own._handleMultipleEvents(own.one, element, type, handler);
}
var func = function () {
own.unbind(element, type, func);
handler.apply(context || element, arguments);
};
// copy the guid to the new function so it can removed using the original function's ID
func.$$guid = handler.$$guid = handler.$$guid || own._guid++;
own.bind(element, type, func);
//var func = function(){
// own.unbind.apply(own,args);
// handler.apply(context || element, arguments);
//};
////args = [type, func].concat(args.slice(2));//更换fun 这样支持不定个数的参数
//
//// copy the guid to the new function so it can removed using the original function's ID
//func.$$guid = handler.$$guid = handler.$$guid || own._guid++;
////own.observe(element, type, func);
//own.bind.apply(own,args);
}
|
javascript
|
function (element, type, handler, context) {
var own = this;
//非Dom元素不处理
if (!(1 == element.nodeType || element.nodeType == 9 || element === window)|| !vQ.isFunction(handler)) {
return;
}
//获取传入参数
var args = slice.call(arguments);
//批量绑定事件处理
if (vQ.isArray(type)) {
return own._handleMultipleEvents.apply(own, [own.one].concat(args));
//return own._handleMultipleEvents(own.one, element, type, handler);
}
var func = function () {
own.unbind(element, type, func);
handler.apply(context || element, arguments);
};
// copy the guid to the new function so it can removed using the original function's ID
func.$$guid = handler.$$guid = handler.$$guid || own._guid++;
own.bind(element, type, func);
//var func = function(){
// own.unbind.apply(own,args);
// handler.apply(context || element, arguments);
//};
////args = [type, func].concat(args.slice(2));//更换fun 这样支持不定个数的参数
//
//// copy the guid to the new function so it can removed using the original function's ID
//func.$$guid = handler.$$guid = handler.$$guid || own._guid++;
////own.observe(element, type, func);
//own.bind.apply(own,args);
}
|
[
"function",
"(",
"element",
",",
"type",
",",
"handler",
",",
"context",
")",
"{",
"var",
"own",
"=",
"this",
";",
"//非Dom元素不处理",
"if",
"(",
"!",
"(",
"1",
"==",
"element",
".",
"nodeType",
"||",
"element",
".",
"nodeType",
"==",
"9",
"||",
"element",
"===",
"window",
")",
"||",
"!",
"vQ",
".",
"isFunction",
"(",
"handler",
")",
")",
"{",
"return",
";",
"}",
"//获取传入参数",
"var",
"args",
"=",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"//批量绑定事件处理",
"if",
"(",
"vQ",
".",
"isArray",
"(",
"type",
")",
")",
"{",
"return",
"own",
".",
"_handleMultipleEvents",
".",
"apply",
"(",
"own",
",",
"[",
"own",
".",
"one",
"]",
".",
"concat",
"(",
"args",
")",
")",
";",
"//return own._handleMultipleEvents(own.one, element, type, handler);",
"}",
"var",
"func",
"=",
"function",
"(",
")",
"{",
"own",
".",
"unbind",
"(",
"element",
",",
"type",
",",
"func",
")",
";",
"handler",
".",
"apply",
"(",
"context",
"||",
"element",
",",
"arguments",
")",
";",
"}",
";",
"// copy the guid to the new function so it can removed using the original function's ID",
"func",
".",
"$$guid",
"=",
"handler",
".",
"$$guid",
"=",
"handler",
".",
"$$guid",
"||",
"own",
".",
"_guid",
"++",
";",
"own",
".",
"bind",
"(",
"element",
",",
"type",
",",
"func",
")",
";",
"//var func = function(){",
"// own.unbind.apply(own,args);",
"// handler.apply(context || element, arguments);",
"//};",
"////args = [type, func].concat(args.slice(2));//更换fun 这样支持不定个数的参数",
"//",
"//// copy the guid to the new function so it can removed using the original function's ID",
"//func.$$guid = handler.$$guid = handler.$$guid || own._guid++;",
"////own.observe(element, type, func);",
"//own.bind.apply(own,args);",
"}"
] |
Trigger a listener only once for an event
@param {Element|Object} elem Element or object to
@param {String|Array} type
@param {Function} fn
@private
|
[
"Trigger",
"a",
"listener",
"only",
"once",
"for",
"an",
"event"
] |
6a84635efb6fbf5c47c41cf05931ab53207024ca
|
https://github.com/vergeplayer/vQ/blob/6a84635efb6fbf5c47c41cf05931ab53207024ca/src/js/module/event.js#L124-L159
|
|
50,778
|
mathieudutour/nplint
|
lib/JSON-parser.js
|
makeError
|
function makeError(e) {
return {
fatal: true,
severity: 2,
message: (e.message || '').split('\n', 1)[0],
line: parser.line,
column: parser.column
};
}
|
javascript
|
function makeError(e) {
return {
fatal: true,
severity: 2,
message: (e.message || '').split('\n', 1)[0],
line: parser.line,
column: parser.column
};
}
|
[
"function",
"makeError",
"(",
"e",
")",
"{",
"return",
"{",
"fatal",
":",
"true",
",",
"severity",
":",
"2",
",",
"message",
":",
"(",
"e",
".",
"message",
"||",
"''",
")",
".",
"split",
"(",
"'\\n'",
",",
"1",
")",
"[",
"0",
"]",
",",
"line",
":",
"parser",
".",
"line",
",",
"column",
":",
"parser",
".",
"column",
"}",
";",
"}"
] |
generate a detailed error using the parser's state
|
[
"generate",
"a",
"detailed",
"error",
"using",
"the",
"parser",
"s",
"state"
] |
ef444abcc6dd08fb61d5fc8ce618598d4455e08e
|
https://github.com/mathieudutour/nplint/blob/ef444abcc6dd08fb61d5fc8ce618598d4455e08e/lib/JSON-parser.js#L20-L28
|
50,779
|
wenwuwu/events-es5
|
events.js
|
function (eventNames) {
var events = this._events;
for (var i = 0; i < arguments.length; i++) {
var eventName = arguments[i];
this._validateName(eventName);
if (typeof events[eventName] === 'undefined') {
events[eventName] = [];
}
}
return this;
}
|
javascript
|
function (eventNames) {
var events = this._events;
for (var i = 0; i < arguments.length; i++) {
var eventName = arguments[i];
this._validateName(eventName);
if (typeof events[eventName] === 'undefined') {
events[eventName] = [];
}
}
return this;
}
|
[
"function",
"(",
"eventNames",
")",
"{",
"var",
"events",
"=",
"this",
".",
"_events",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"eventName",
"=",
"arguments",
"[",
"i",
"]",
";",
"this",
".",
"_validateName",
"(",
"eventName",
")",
";",
"if",
"(",
"typeof",
"events",
"[",
"eventName",
"]",
"===",
"'undefined'",
")",
"{",
"events",
"[",
"eventName",
"]",
"=",
"[",
"]",
";",
"}",
"}",
"return",
"this",
";",
"}"
] |
Defines a list of events.
@param eventNames {String...}
@returns {Events}
|
[
"Defines",
"a",
"list",
"of",
"events",
"."
] |
86c7d54102dafe725f57d0278479aa5bf8234ebc
|
https://github.com/wenwuwu/events-es5/blob/86c7d54102dafe725f57d0278479aa5bf8234ebc/events.js#L43-L57
|
|
50,780
|
wenwuwu/events-es5
|
events.js
|
function (eventName, fn) {
if (typeof eventName === 'object') {
if (eventName === null) {
throw "IllegalArgumentException: eventName must be a String, or an Object.";
}
for (var name in eventName) {
if (eventName.hasOwnProperty(name)) {
this.bind(name, eventName[name]);
}
}
return this;
}
if (!this.isSupported(eventName)) {
throw "IllegalArgumentException: unrecognized event name (" + eventName + ").";
}
if (typeof fn !== 'function') {
throw "IllegalArgumentException: fn must be a Function.";
}
this._events[eventName].push(fn);
if (this.numListeners(eventName) === 1) {
this._sendActivation('_activate', eventName);
}
return this;
}
|
javascript
|
function (eventName, fn) {
if (typeof eventName === 'object') {
if (eventName === null) {
throw "IllegalArgumentException: eventName must be a String, or an Object.";
}
for (var name in eventName) {
if (eventName.hasOwnProperty(name)) {
this.bind(name, eventName[name]);
}
}
return this;
}
if (!this.isSupported(eventName)) {
throw "IllegalArgumentException: unrecognized event name (" + eventName + ").";
}
if (typeof fn !== 'function') {
throw "IllegalArgumentException: fn must be a Function.";
}
this._events[eventName].push(fn);
if (this.numListeners(eventName) === 1) {
this._sendActivation('_activate', eventName);
}
return this;
}
|
[
"function",
"(",
"eventName",
",",
"fn",
")",
"{",
"if",
"(",
"typeof",
"eventName",
"===",
"'object'",
")",
"{",
"if",
"(",
"eventName",
"===",
"null",
")",
"{",
"throw",
"\"IllegalArgumentException: eventName must be a String, or an Object.\"",
";",
"}",
"for",
"(",
"var",
"name",
"in",
"eventName",
")",
"{",
"if",
"(",
"eventName",
".",
"hasOwnProperty",
"(",
"name",
")",
")",
"{",
"this",
".",
"bind",
"(",
"name",
",",
"eventName",
"[",
"name",
"]",
")",
";",
"}",
"}",
"return",
"this",
";",
"}",
"if",
"(",
"!",
"this",
".",
"isSupported",
"(",
"eventName",
")",
")",
"{",
"throw",
"\"IllegalArgumentException: unrecognized event name (\"",
"+",
"eventName",
"+",
"\").\"",
";",
"}",
"if",
"(",
"typeof",
"fn",
"!==",
"'function'",
")",
"{",
"throw",
"\"IllegalArgumentException: fn must be a Function.\"",
";",
"}",
"this",
".",
"_events",
"[",
"eventName",
"]",
".",
"push",
"(",
"fn",
")",
";",
"if",
"(",
"this",
".",
"numListeners",
"(",
"eventName",
")",
"===",
"1",
")",
"{",
"this",
".",
"_sendActivation",
"(",
"'_activate'",
",",
"eventName",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Binds a listener to an event.
@param eventName {String or Object}
@param fn {Function} - Not required if 1st argument is an Object.
@returns {Events} A pointer to this instance, allowing call chaining.
|
[
"Binds",
"a",
"listener",
"to",
"an",
"event",
"."
] |
86c7d54102dafe725f57d0278479aa5bf8234ebc
|
https://github.com/wenwuwu/events-es5/blob/86c7d54102dafe725f57d0278479aa5bf8234ebc/events.js#L74-L103
|
|
50,781
|
wenwuwu/events-es5
|
events.js
|
function (eventName, fn) {
if (typeof fn !== 'function') {
throw "IllegalArgumentException: fn must be a Function.";
}
var fns = this._events[eventName];
if (fns instanceof Array) {
var len = fns.length;
for (var i = len - 1; i >= 0; i--) {
if (fns[i] === fn) {
fns.splice(i, 1);
}
}
if ( fns.length !== len
&& fns.length === 0 ) {
this._sendActivation('_deactivate', eventName);
}
}
return this;
}
|
javascript
|
function (eventName, fn) {
if (typeof fn !== 'function') {
throw "IllegalArgumentException: fn must be a Function.";
}
var fns = this._events[eventName];
if (fns instanceof Array) {
var len = fns.length;
for (var i = len - 1; i >= 0; i--) {
if (fns[i] === fn) {
fns.splice(i, 1);
}
}
if ( fns.length !== len
&& fns.length === 0 ) {
this._sendActivation('_deactivate', eventName);
}
}
return this;
}
|
[
"function",
"(",
"eventName",
",",
"fn",
")",
"{",
"if",
"(",
"typeof",
"fn",
"!==",
"'function'",
")",
"{",
"throw",
"\"IllegalArgumentException: fn must be a Function.\"",
";",
"}",
"var",
"fns",
"=",
"this",
".",
"_events",
"[",
"eventName",
"]",
";",
"if",
"(",
"fns",
"instanceof",
"Array",
")",
"{",
"var",
"len",
"=",
"fns",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"len",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"if",
"(",
"fns",
"[",
"i",
"]",
"===",
"fn",
")",
"{",
"fns",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"}",
"}",
"if",
"(",
"fns",
".",
"length",
"!==",
"len",
"&&",
"fns",
".",
"length",
"===",
"0",
")",
"{",
"this",
".",
"_sendActivation",
"(",
"'_deactivate'",
",",
"eventName",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
] |
Removes the bind between a listener and an event.
@param eventName {String}
@param fn {Function}
@returns {Events} A pointer to this instance, allowing call chaining.
|
[
"Removes",
"the",
"bind",
"between",
"a",
"listener",
"and",
"an",
"event",
"."
] |
86c7d54102dafe725f57d0278479aa5bf8234ebc
|
https://github.com/wenwuwu/events-es5/blob/86c7d54102dafe725f57d0278479aa5bf8234ebc/events.js#L111-L134
|
|
50,782
|
wenwuwu/events-es5
|
events.js
|
function (eventName) {
var fns = this._events[eventName];
if (typeof fns === 'undefined') {
throw "IllegalArgumentException: unsupported eventName (" + eventName + ")";
}
if (fns.length > 0) {
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
var hasFoundFalse = false;
for ( var i = 0;
i < fns.length && !hasFoundFalse;
i++ ) {
if (fns[i].apply(this, args) === false) {
hasFoundFalse = true;
}
}
if (hasFoundFalse) {
return false;
}
}
return true;
}
|
javascript
|
function (eventName) {
var fns = this._events[eventName];
if (typeof fns === 'undefined') {
throw "IllegalArgumentException: unsupported eventName (" + eventName + ")";
}
if (fns.length > 0) {
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
var hasFoundFalse = false;
for ( var i = 0;
i < fns.length && !hasFoundFalse;
i++ ) {
if (fns[i].apply(this, args) === false) {
hasFoundFalse = true;
}
}
if (hasFoundFalse) {
return false;
}
}
return true;
}
|
[
"function",
"(",
"eventName",
")",
"{",
"var",
"fns",
"=",
"this",
".",
"_events",
"[",
"eventName",
"]",
";",
"if",
"(",
"typeof",
"fns",
"===",
"'undefined'",
")",
"{",
"throw",
"\"IllegalArgumentException: unsupported eventName (\"",
"+",
"eventName",
"+",
"\")\"",
";",
"}",
"if",
"(",
"fns",
".",
"length",
">",
"0",
")",
"{",
"var",
"args",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"args",
".",
"push",
"(",
"arguments",
"[",
"i",
"]",
")",
";",
"}",
"var",
"hasFoundFalse",
"=",
"false",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"fns",
".",
"length",
"&&",
"!",
"hasFoundFalse",
";",
"i",
"++",
")",
"{",
"if",
"(",
"fns",
"[",
"i",
"]",
".",
"apply",
"(",
"this",
",",
"args",
")",
"===",
"false",
")",
"{",
"hasFoundFalse",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"hasFoundFalse",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
Sends an event to all listeners.
This method returns <code>false</code> if any of the
listeners returned <code>false</code>. If there are
no listeners to this event, or if none of them
returned <code>false</code>, this method returns <code>true</code>.
Typically, a listener will return <code>false</code> to indicate
that a browser event should not continue to bubble up the DOM; callers
can look for a return value equals to <code>false</code> to
recognize those cases.
@param eventName {String}
@returns {Boolean}
|
[
"Sends",
"an",
"event",
"to",
"all",
"listeners",
"."
] |
86c7d54102dafe725f57d0278479aa5bf8234ebc
|
https://github.com/wenwuwu/events-es5/blob/86c7d54102dafe725f57d0278479aa5bf8234ebc/events.js#L180-L207
|
|
50,783
|
taoyuan/lwim
|
lib/bitmap.js
|
Bitmap
|
function Bitmap(width, height, bytesPerPixel, endianness) {
if (!(this instanceof Bitmap)) {
return new Bitmap(width, height, bytesPerPixel, endianness);
}
// Validate bytes per pixel
if (bytesPerPixel === undefined) {
bytesPerPixel = 1;
}
if (bytesPerPixel !== 1 && bytesPerPixel !== 2 && bytesPerPixel !== 4) {
throw new Error("Invalid number of bytes per pixel: " + bytesPerPixel);
}
this._width = width;
this._height = height;
this._bytesPerPixel = bytesPerPixel;
this._endianness = endianness === undefined ? Endianness.BIG : endianness;
this._palette = bytesPerPixel === 1 ? [].concat(DEFAULT_PALETTE) : [];
this._data = new Buffer(width * height * bytesPerPixel);
saveReadAndWriteFunction.call(this);
// Initialize to white
this.clear(0xFF);
}
|
javascript
|
function Bitmap(width, height, bytesPerPixel, endianness) {
if (!(this instanceof Bitmap)) {
return new Bitmap(width, height, bytesPerPixel, endianness);
}
// Validate bytes per pixel
if (bytesPerPixel === undefined) {
bytesPerPixel = 1;
}
if (bytesPerPixel !== 1 && bytesPerPixel !== 2 && bytesPerPixel !== 4) {
throw new Error("Invalid number of bytes per pixel: " + bytesPerPixel);
}
this._width = width;
this._height = height;
this._bytesPerPixel = bytesPerPixel;
this._endianness = endianness === undefined ? Endianness.BIG : endianness;
this._palette = bytesPerPixel === 1 ? [].concat(DEFAULT_PALETTE) : [];
this._data = new Buffer(width * height * bytesPerPixel);
saveReadAndWriteFunction.call(this);
// Initialize to white
this.clear(0xFF);
}
|
[
"function",
"Bitmap",
"(",
"width",
",",
"height",
",",
"bytesPerPixel",
",",
"endianness",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Bitmap",
")",
")",
"{",
"return",
"new",
"Bitmap",
"(",
"width",
",",
"height",
",",
"bytesPerPixel",
",",
"endianness",
")",
";",
"}",
"// Validate bytes per pixel",
"if",
"(",
"bytesPerPixel",
"===",
"undefined",
")",
"{",
"bytesPerPixel",
"=",
"1",
";",
"}",
"if",
"(",
"bytesPerPixel",
"!==",
"1",
"&&",
"bytesPerPixel",
"!==",
"2",
"&&",
"bytesPerPixel",
"!==",
"4",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Invalid number of bytes per pixel: \"",
"+",
"bytesPerPixel",
")",
";",
"}",
"this",
".",
"_width",
"=",
"width",
";",
"this",
".",
"_height",
"=",
"height",
";",
"this",
".",
"_bytesPerPixel",
"=",
"bytesPerPixel",
";",
"this",
".",
"_endianness",
"=",
"endianness",
"===",
"undefined",
"?",
"Endianness",
".",
"BIG",
":",
"endianness",
";",
"this",
".",
"_palette",
"=",
"bytesPerPixel",
"===",
"1",
"?",
"[",
"]",
".",
"concat",
"(",
"DEFAULT_PALETTE",
")",
":",
"[",
"]",
";",
"this",
".",
"_data",
"=",
"new",
"Buffer",
"(",
"width",
"*",
"height",
"*",
"bytesPerPixel",
")",
";",
"saveReadAndWriteFunction",
".",
"call",
"(",
"this",
")",
";",
"// Initialize to white",
"this",
".",
"clear",
"(",
"0xFF",
")",
";",
"}"
] |
Creates an in-memory bitmap. Bitmaps with 1 byte per pixel are handled in conjunction with a
palette.
@class
@param {number} width
@param {number} height
@param {number} [bytesPerPixel=1] Possible values: <code>1</code>, <code>2</code>,
<code>4</code>
@param {Endianness} [endianness=BIG] Use big- or little-endian when storing multiple bytes per
pixel
@constructor
|
[
"Creates",
"an",
"in",
"-",
"memory",
"bitmap",
".",
"Bitmaps",
"with",
"1",
"byte",
"per",
"pixel",
"are",
"handled",
"in",
"conjunction",
"with",
"a",
"palette",
"."
] |
90014f5d058bb514768df24caa6605437ec586e2
|
https://github.com/taoyuan/lwim/blob/90014f5d058bb514768df24caa6605437ec586e2/lib/bitmap.js#L87-L110
|
50,784
|
taoyuan/impack
|
lib/download/git.js
|
normalize
|
function normalize(repo) {
const regex = /^((github|gitlab|bitbucket|oschina):)?((.+):)?([^/]+)\/([^#]+)(#(.+))?$/;
const match = regex.exec(repo);
const type = match[2] || 'github';
let host = match[4] || null;
const owner = match[5];
const name = match[6];
const checkout = match[8] || 'master';
if (host === null) {
if (type === 'github') {
host = 'github.com';
} else if (type === 'gitlab') {
host = 'gitlab.com';
} else if (type === 'bitbucket') {
host = 'bitbucket.com';
} else if (type === 'oschina') {
host = 'git.oschina.net';
}
}
return {
type,
host,
owner,
name,
checkout
};
}
|
javascript
|
function normalize(repo) {
const regex = /^((github|gitlab|bitbucket|oschina):)?((.+):)?([^/]+)\/([^#]+)(#(.+))?$/;
const match = regex.exec(repo);
const type = match[2] || 'github';
let host = match[4] || null;
const owner = match[5];
const name = match[6];
const checkout = match[8] || 'master';
if (host === null) {
if (type === 'github') {
host = 'github.com';
} else if (type === 'gitlab') {
host = 'gitlab.com';
} else if (type === 'bitbucket') {
host = 'bitbucket.com';
} else if (type === 'oschina') {
host = 'git.oschina.net';
}
}
return {
type,
host,
owner,
name,
checkout
};
}
|
[
"function",
"normalize",
"(",
"repo",
")",
"{",
"const",
"regex",
"=",
"/",
"^((github|gitlab|bitbucket|oschina):)?((.+):)?([^/]+)\\/([^#]+)(#(.+))?$",
"/",
";",
"const",
"match",
"=",
"regex",
".",
"exec",
"(",
"repo",
")",
";",
"const",
"type",
"=",
"match",
"[",
"2",
"]",
"||",
"'github'",
";",
"let",
"host",
"=",
"match",
"[",
"4",
"]",
"||",
"null",
";",
"const",
"owner",
"=",
"match",
"[",
"5",
"]",
";",
"const",
"name",
"=",
"match",
"[",
"6",
"]",
";",
"const",
"checkout",
"=",
"match",
"[",
"8",
"]",
"||",
"'master'",
";",
"if",
"(",
"host",
"===",
"null",
")",
"{",
"if",
"(",
"type",
"===",
"'github'",
")",
"{",
"host",
"=",
"'github.com'",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'gitlab'",
")",
"{",
"host",
"=",
"'gitlab.com'",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'bitbucket'",
")",
"{",
"host",
"=",
"'bitbucket.com'",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'oschina'",
")",
"{",
"host",
"=",
"'git.oschina.net'",
";",
"}",
"}",
"return",
"{",
"type",
",",
"host",
",",
"owner",
",",
"name",
",",
"checkout",
"}",
";",
"}"
] |
Normalize a repo string.
@param {String} repo
@return {Object}
|
[
"Normalize",
"a",
"repo",
"string",
"."
] |
4dba8e91b9d2c8785eda5db634943ec00683bff7
|
https://github.com/taoyuan/impack/blob/4dba8e91b9d2c8785eda5db634943ec00683bff7/lib/download/git.js#L59-L87
|
50,785
|
taoyuan/impack
|
lib/download/git.js
|
getUrl
|
function getUrl(repo, clone) {
let url;
if (repo.type === 'github') {
url = github(repo, clone);
} else if (repo.type === 'gitlab') {
url = gitlab(repo, clone);
} else if (repo.type === 'bitbucket') {
url = bitbucket(repo, clone);
} else if (repo.type === 'oschina') {
url = oschina(repo, clone);
} else {
url = github(repo, clone);
}
return url;
}
|
javascript
|
function getUrl(repo, clone) {
let url;
if (repo.type === 'github') {
url = github(repo, clone);
} else if (repo.type === 'gitlab') {
url = gitlab(repo, clone);
} else if (repo.type === 'bitbucket') {
url = bitbucket(repo, clone);
} else if (repo.type === 'oschina') {
url = oschina(repo, clone);
} else {
url = github(repo, clone);
}
return url;
}
|
[
"function",
"getUrl",
"(",
"repo",
",",
"clone",
")",
"{",
"let",
"url",
";",
"if",
"(",
"repo",
".",
"type",
"===",
"'github'",
")",
"{",
"url",
"=",
"github",
"(",
"repo",
",",
"clone",
")",
";",
"}",
"else",
"if",
"(",
"repo",
".",
"type",
"===",
"'gitlab'",
")",
"{",
"url",
"=",
"gitlab",
"(",
"repo",
",",
"clone",
")",
";",
"}",
"else",
"if",
"(",
"repo",
".",
"type",
"===",
"'bitbucket'",
")",
"{",
"url",
"=",
"bitbucket",
"(",
"repo",
",",
"clone",
")",
";",
"}",
"else",
"if",
"(",
"repo",
".",
"type",
"===",
"'oschina'",
")",
"{",
"url",
"=",
"oschina",
"(",
"repo",
",",
"clone",
")",
";",
"}",
"else",
"{",
"url",
"=",
"github",
"(",
"repo",
",",
"clone",
")",
";",
"}",
"return",
"url",
";",
"}"
] |
Return a zip or git url for a given `repo`.
@param {Object} repo
@param {Boolean} [clone]
@return {String|Object}
|
[
"Return",
"a",
"zip",
"or",
"git",
"url",
"for",
"a",
"given",
"repo",
"."
] |
4dba8e91b9d2c8785eda5db634943ec00683bff7
|
https://github.com/taoyuan/impack/blob/4dba8e91b9d2c8785eda5db634943ec00683bff7/lib/download/git.js#L111-L127
|
50,786
|
taoyuan/impack
|
lib/download/git.js
|
github
|
function github(repo, clone) {
let url;
if (clone)
url = 'git@' + repo.host + ':' + repo.owner + '/' + repo.name + '.git';
else
url = addProtocol(repo.host) + '/' + repo.owner + '/' + repo.name + '/archive/' + repo.checkout + '.zip';
return url;
}
|
javascript
|
function github(repo, clone) {
let url;
if (clone)
url = 'git@' + repo.host + ':' + repo.owner + '/' + repo.name + '.git';
else
url = addProtocol(repo.host) + '/' + repo.owner + '/' + repo.name + '/archive/' + repo.checkout + '.zip';
return url;
}
|
[
"function",
"github",
"(",
"repo",
",",
"clone",
")",
"{",
"let",
"url",
";",
"if",
"(",
"clone",
")",
"url",
"=",
"'git@'",
"+",
"repo",
".",
"host",
"+",
"':'",
"+",
"repo",
".",
"owner",
"+",
"'/'",
"+",
"repo",
".",
"name",
"+",
"'.git'",
";",
"else",
"url",
"=",
"addProtocol",
"(",
"repo",
".",
"host",
")",
"+",
"'/'",
"+",
"repo",
".",
"owner",
"+",
"'/'",
"+",
"repo",
".",
"name",
"+",
"'/archive/'",
"+",
"repo",
".",
"checkout",
"+",
"'.zip'",
";",
"return",
"url",
";",
"}"
] |
Return a GitHub url for a given `repo` object.
@param {Object} repo
@param {Boolean} [clone]
@return {String}
|
[
"Return",
"a",
"GitHub",
"url",
"for",
"a",
"given",
"repo",
"object",
"."
] |
4dba8e91b9d2c8785eda5db634943ec00683bff7
|
https://github.com/taoyuan/impack/blob/4dba8e91b9d2c8785eda5db634943ec00683bff7/lib/download/git.js#L137-L146
|
50,787
|
taoyuan/impack
|
lib/download/git.js
|
oschina
|
function oschina(repo, clone) {
let url;
// oschina canceled download directly
clone = true;
if (clone)
url = addProtocol(repo.host) + '/' + repo.owner + '/' + repo.name;
// url = 'git@' + repo.host + ':' + repo.owner + '/' + repo.name + '.git';
else
url = addProtocol(repo.host) + '/' + repo.owner + '/' + repo.name + '/repository/archive/' + repo.checkout;
return {url, clone};
}
|
javascript
|
function oschina(repo, clone) {
let url;
// oschina canceled download directly
clone = true;
if (clone)
url = addProtocol(repo.host) + '/' + repo.owner + '/' + repo.name;
// url = 'git@' + repo.host + ':' + repo.owner + '/' + repo.name + '.git';
else
url = addProtocol(repo.host) + '/' + repo.owner + '/' + repo.name + '/repository/archive/' + repo.checkout;
return {url, clone};
}
|
[
"function",
"oschina",
"(",
"repo",
",",
"clone",
")",
"{",
"let",
"url",
";",
"// oschina canceled download directly",
"clone",
"=",
"true",
";",
"if",
"(",
"clone",
")",
"url",
"=",
"addProtocol",
"(",
"repo",
".",
"host",
")",
"+",
"'/'",
"+",
"repo",
".",
"owner",
"+",
"'/'",
"+",
"repo",
".",
"name",
";",
"// url = 'git@' + repo.host + ':' + repo.owner + '/' + repo.name + '.git';",
"else",
"url",
"=",
"addProtocol",
"(",
"repo",
".",
"host",
")",
"+",
"'/'",
"+",
"repo",
".",
"owner",
"+",
"'/'",
"+",
"repo",
".",
"name",
"+",
"'/repository/archive/'",
"+",
"repo",
".",
"checkout",
";",
"return",
"{",
"url",
",",
"clone",
"}",
";",
"}"
] |
Return a GitLab url for a given `repo` object.
@param {Object} repo
@param {Boolean} [clone]
@return {Object}
|
[
"Return",
"a",
"GitLab",
"url",
"for",
"a",
"given",
"repo",
"object",
"."
] |
4dba8e91b9d2c8785eda5db634943ec00683bff7
|
https://github.com/taoyuan/impack/blob/4dba8e91b9d2c8785eda5db634943ec00683bff7/lib/download/git.js#L194-L207
|
50,788
|
ryanramage/schema-couch-boilerplate
|
jam/ractive/build/Ractive.runtime.js
|
function () {
var str, i, len;
// TODO void tags
str = '' +
'<' + this.descriptor.e;
len = this.attributes.length;
for ( i=0; i<len; i+=1 ) {
str += ' ' + this.attributes[i].toString();
}
str += '>';
if ( this.html ) {
str += this.html;
} else if ( this.fragment ) {
str += this.fragment.toString();
}
str += '</' + this.descriptor.e + '>';
return str;
}
|
javascript
|
function () {
var str, i, len;
// TODO void tags
str = '' +
'<' + this.descriptor.e;
len = this.attributes.length;
for ( i=0; i<len; i+=1 ) {
str += ' ' + this.attributes[i].toString();
}
str += '>';
if ( this.html ) {
str += this.html;
} else if ( this.fragment ) {
str += this.fragment.toString();
}
str += '</' + this.descriptor.e + '>';
return str;
}
|
[
"function",
"(",
")",
"{",
"var",
"str",
",",
"i",
",",
"len",
";",
"// TODO void tags",
"str",
"=",
"''",
"+",
"'<'",
"+",
"this",
".",
"descriptor",
".",
"e",
";",
"len",
"=",
"this",
".",
"attributes",
".",
"length",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"str",
"+=",
"' '",
"+",
"this",
".",
"attributes",
"[",
"i",
"]",
".",
"toString",
"(",
")",
";",
"}",
"str",
"+=",
"'>'",
";",
"if",
"(",
"this",
".",
"html",
")",
"{",
"str",
"+=",
"this",
".",
"html",
";",
"}",
"else",
"if",
"(",
"this",
".",
"fragment",
")",
"{",
"str",
"+=",
"this",
".",
"fragment",
".",
"toString",
"(",
")",
";",
"}",
"str",
"+=",
"'</'",
"+",
"this",
".",
"descriptor",
".",
"e",
"+",
"'>'",
";",
"return",
"str",
";",
"}"
] |
just so event proxy and transition fragments have something to call!
|
[
"just",
"so",
"event",
"proxy",
"and",
"transition",
"fragments",
"have",
"something",
"to",
"call!"
] |
c323516f02c90101aa6b21592bfdd2a6f2e47680
|
https://github.com/ryanramage/schema-couch-boilerplate/blob/c323516f02c90101aa6b21592bfdd2a6f2e47680/jam/ractive/build/Ractive.runtime.js#L6040-L6063
|
|
50,789
|
tgi-io/tgi-core
|
lib/models/tgi-core-model-session.spec.js
|
userStored
|
function userStored(model, error) {
if (typeof error != 'undefined') {
callback(error);
return;
}
if (user1.get('id') && user2.get('id')) {
// users added to store now log them both in and also generate 2 errors
self.goodCount = 0;
self.badCount = 0;
session1.startSession(store, name1, 'badpassword', ip1, usersStarted);
session1.startSession(store, name1, pass1, ip1, usersStarted);
session2.startSession(store, 'john', pass2, ip2, usersStarted);
session2.startSession(store, name2, pass2, ip2, usersStarted);
}
}
|
javascript
|
function userStored(model, error) {
if (typeof error != 'undefined') {
callback(error);
return;
}
if (user1.get('id') && user2.get('id')) {
// users added to store now log them both in and also generate 2 errors
self.goodCount = 0;
self.badCount = 0;
session1.startSession(store, name1, 'badpassword', ip1, usersStarted);
session1.startSession(store, name1, pass1, ip1, usersStarted);
session2.startSession(store, 'john', pass2, ip2, usersStarted);
session2.startSession(store, name2, pass2, ip2, usersStarted);
}
}
|
[
"function",
"userStored",
"(",
"model",
",",
"error",
")",
"{",
"if",
"(",
"typeof",
"error",
"!=",
"'undefined'",
")",
"{",
"callback",
"(",
"error",
")",
";",
"return",
";",
"}",
"if",
"(",
"user1",
".",
"get",
"(",
"'id'",
")",
"&&",
"user2",
".",
"get",
"(",
"'id'",
")",
")",
"{",
"// users added to store now log them both in and also generate 2 errors",
"self",
".",
"goodCount",
"=",
"0",
";",
"self",
".",
"badCount",
"=",
"0",
";",
"session1",
".",
"startSession",
"(",
"store",
",",
"name1",
",",
"'badpassword'",
",",
"ip1",
",",
"usersStarted",
")",
";",
"session1",
".",
"startSession",
"(",
"store",
",",
"name1",
",",
"pass1",
",",
"ip1",
",",
"usersStarted",
")",
";",
"session2",
".",
"startSession",
"(",
"store",
",",
"'john'",
",",
"pass2",
",",
"ip2",
",",
"usersStarted",
")",
";",
"session2",
".",
"startSession",
"(",
"store",
",",
"name2",
",",
"pass2",
",",
"ip2",
",",
"usersStarted",
")",
";",
"}",
"}"
] |
callback after users stored
|
[
"callback",
"after",
"users",
"stored"
] |
d965f11e9b168d5a401d9e2627f2786b5e4bcf30
|
https://github.com/tgi-io/tgi-core/blob/d965f11e9b168d5a401d9e2627f2786b5e4bcf30/lib/models/tgi-core-model-session.spec.js#L100-L114
|
50,790
|
tgi-io/tgi-core
|
lib/models/tgi-core-model-session.spec.js
|
usersStarted
|
function usersStarted(err, session) {
if (err)
self.badCount++;
else
self.goodCount++;
if (self.badCount == 2 && self.goodCount == 2) {
// Resume session1 correctly
new Session().resumeSession(store, ip1, session1.get('passCode'), sessionResumed_Test1);
}
}
|
javascript
|
function usersStarted(err, session) {
if (err)
self.badCount++;
else
self.goodCount++;
if (self.badCount == 2 && self.goodCount == 2) {
// Resume session1 correctly
new Session().resumeSession(store, ip1, session1.get('passCode'), sessionResumed_Test1);
}
}
|
[
"function",
"usersStarted",
"(",
"err",
",",
"session",
")",
"{",
"if",
"(",
"err",
")",
"self",
".",
"badCount",
"++",
";",
"else",
"self",
".",
"goodCount",
"++",
";",
"if",
"(",
"self",
".",
"badCount",
"==",
"2",
"&&",
"self",
".",
"goodCount",
"==",
"2",
")",
"{",
"// Resume session1 correctly",
"new",
"Session",
"(",
")",
".",
"resumeSession",
"(",
"store",
",",
"ip1",
",",
"session1",
".",
"get",
"(",
"'passCode'",
")",
",",
"sessionResumed_Test1",
")",
";",
"}",
"}"
] |
callback after session started called
|
[
"callback",
"after",
"session",
"started",
"called"
] |
d965f11e9b168d5a401d9e2627f2786b5e4bcf30
|
https://github.com/tgi-io/tgi-core/blob/d965f11e9b168d5a401d9e2627f2786b5e4bcf30/lib/models/tgi-core-model-session.spec.js#L117-L127
|
50,791
|
solick/xbee-helper
|
src/xbee-helper.js
|
function(debug, milliseconds)
{
if(debug == null)
{
this_debug = false;
}
else
{
this._debug = debug;
}
if(milliseconds == null)
{
this._milliseconds = false;
}
else
{
this._milliseconds = true;
}
}
|
javascript
|
function(debug, milliseconds)
{
if(debug == null)
{
this_debug = false;
}
else
{
this._debug = debug;
}
if(milliseconds == null)
{
this._milliseconds = false;
}
else
{
this._milliseconds = true;
}
}
|
[
"function",
"(",
"debug",
",",
"milliseconds",
")",
"{",
"if",
"(",
"debug",
"==",
"null",
")",
"{",
"this_debug",
"=",
"false",
";",
"}",
"else",
"{",
"this",
".",
"_debug",
"=",
"debug",
";",
"}",
"if",
"(",
"milliseconds",
"==",
"null",
")",
"{",
"this",
".",
"_milliseconds",
"=",
"false",
";",
"}",
"else",
"{",
"this",
".",
"_milliseconds",
"=",
"true",
";",
"}",
"}"
] |
Class with several helper function for communication and work with xbee-api
@param debug
@constructor
|
[
"Class",
"with",
"several",
"helper",
"function",
"for",
"communication",
"and",
"work",
"with",
"xbee",
"-",
"api"
] |
e2783b88b049cf7e227df683c86ae934b4c54cc6
|
https://github.com/solick/xbee-helper/blob/e2783b88b049cf7e227df683c86ae934b4c54cc6/src/xbee-helper.js#L19-L41
|
|
50,792
|
feedhenry/fh-mbaas-middleware
|
lib/util/requestTranslator.js
|
parseCreateAlertRequest
|
function parseCreateAlertRequest(req){
var reqObj = {};
reqObj.originalUrl = req.originalUrl;
reqObj.alertName = req.body.alertName;
reqObj.emails = req.body.emails;
reqObj.eventCategories = req.body.eventCategories.split(',');
reqObj.eventNames = req.body.eventNames.split(',');
reqObj.eventSeverities = req.body.eventSeverities.split(',');
reqObj.uid = req.body.uid;
reqObj.env = req.body.env;
reqObj.alertEnabled = req.body.enabled;
reqObj._id = new Mongoose.Types.ObjectId();
reqObj.domain = req.params.domain;
return reqObj;
}
|
javascript
|
function parseCreateAlertRequest(req){
var reqObj = {};
reqObj.originalUrl = req.originalUrl;
reqObj.alertName = req.body.alertName;
reqObj.emails = req.body.emails;
reqObj.eventCategories = req.body.eventCategories.split(',');
reqObj.eventNames = req.body.eventNames.split(',');
reqObj.eventSeverities = req.body.eventSeverities.split(',');
reqObj.uid = req.body.uid;
reqObj.env = req.body.env;
reqObj.alertEnabled = req.body.enabled;
reqObj._id = new Mongoose.Types.ObjectId();
reqObj.domain = req.params.domain;
return reqObj;
}
|
[
"function",
"parseCreateAlertRequest",
"(",
"req",
")",
"{",
"var",
"reqObj",
"=",
"{",
"}",
";",
"reqObj",
".",
"originalUrl",
"=",
"req",
".",
"originalUrl",
";",
"reqObj",
".",
"alertName",
"=",
"req",
".",
"body",
".",
"alertName",
";",
"reqObj",
".",
"emails",
"=",
"req",
".",
"body",
".",
"emails",
";",
"reqObj",
".",
"eventCategories",
"=",
"req",
".",
"body",
".",
"eventCategories",
".",
"split",
"(",
"','",
")",
";",
"reqObj",
".",
"eventNames",
"=",
"req",
".",
"body",
".",
"eventNames",
".",
"split",
"(",
"','",
")",
";",
"reqObj",
".",
"eventSeverities",
"=",
"req",
".",
"body",
".",
"eventSeverities",
".",
"split",
"(",
"','",
")",
";",
"reqObj",
".",
"uid",
"=",
"req",
".",
"body",
".",
"uid",
";",
"reqObj",
".",
"env",
"=",
"req",
".",
"body",
".",
"env",
";",
"reqObj",
".",
"alertEnabled",
"=",
"req",
".",
"body",
".",
"enabled",
";",
"reqObj",
".",
"_id",
"=",
"new",
"Mongoose",
".",
"Types",
".",
"ObjectId",
"(",
")",
";",
"reqObj",
".",
"domain",
"=",
"req",
".",
"params",
".",
"domain",
";",
"return",
"reqObj",
";",
"}"
] |
Parse the incoming Create Alert Request into a common object
|
[
"Parse",
"the",
"incoming",
"Create",
"Alert",
"Request",
"into",
"a",
"common",
"object"
] |
f906e98efbb4b0963bf5137b34b5e0589ba24e69
|
https://github.com/feedhenry/fh-mbaas-middleware/blob/f906e98efbb4b0963bf5137b34b5e0589ba24e69/lib/util/requestTranslator.js#L15-L30
|
50,793
|
feedhenry/fh-mbaas-middleware
|
lib/util/requestTranslator.js
|
parseUpdateAlertRequest
|
function parseUpdateAlertRequest(req){
var reqObj = {};
reqObj.originalUrl = req.originalUrl;
reqObj.alertName = req.body.alertName;
reqObj.emails = req.body.emails.split(',');
reqObj.eventCategories = req.body.eventCategories.split(',');
reqObj.eventNames = req.body.eventNames.split(',');
reqObj.eventSeverities = req.body.eventSeverities.split(',');
reqObj.uid = req.body.uid;
reqObj.env = req.body.env;
reqObj.alertEnabled = req.body.enabled;
reqObj._id = req.params.id;
reqObj.domain = req.params.domain;
return reqObj;
}
|
javascript
|
function parseUpdateAlertRequest(req){
var reqObj = {};
reqObj.originalUrl = req.originalUrl;
reqObj.alertName = req.body.alertName;
reqObj.emails = req.body.emails.split(',');
reqObj.eventCategories = req.body.eventCategories.split(',');
reqObj.eventNames = req.body.eventNames.split(',');
reqObj.eventSeverities = req.body.eventSeverities.split(',');
reqObj.uid = req.body.uid;
reqObj.env = req.body.env;
reqObj.alertEnabled = req.body.enabled;
reqObj._id = req.params.id;
reqObj.domain = req.params.domain;
return reqObj;
}
|
[
"function",
"parseUpdateAlertRequest",
"(",
"req",
")",
"{",
"var",
"reqObj",
"=",
"{",
"}",
";",
"reqObj",
".",
"originalUrl",
"=",
"req",
".",
"originalUrl",
";",
"reqObj",
".",
"alertName",
"=",
"req",
".",
"body",
".",
"alertName",
";",
"reqObj",
".",
"emails",
"=",
"req",
".",
"body",
".",
"emails",
".",
"split",
"(",
"','",
")",
";",
"reqObj",
".",
"eventCategories",
"=",
"req",
".",
"body",
".",
"eventCategories",
".",
"split",
"(",
"','",
")",
";",
"reqObj",
".",
"eventNames",
"=",
"req",
".",
"body",
".",
"eventNames",
".",
"split",
"(",
"','",
")",
";",
"reqObj",
".",
"eventSeverities",
"=",
"req",
".",
"body",
".",
"eventSeverities",
".",
"split",
"(",
"','",
")",
";",
"reqObj",
".",
"uid",
"=",
"req",
".",
"body",
".",
"uid",
";",
"reqObj",
".",
"env",
"=",
"req",
".",
"body",
".",
"env",
";",
"reqObj",
".",
"alertEnabled",
"=",
"req",
".",
"body",
".",
"enabled",
";",
"reqObj",
".",
"_id",
"=",
"req",
".",
"params",
".",
"id",
";",
"reqObj",
".",
"domain",
"=",
"req",
".",
"params",
".",
"domain",
";",
"return",
"reqObj",
";",
"}"
] |
Parse the incoming Update Alert Request into a common object
|
[
"Parse",
"the",
"incoming",
"Update",
"Alert",
"Request",
"into",
"a",
"common",
"object"
] |
f906e98efbb4b0963bf5137b34b5e0589ba24e69
|
https://github.com/feedhenry/fh-mbaas-middleware/blob/f906e98efbb4b0963bf5137b34b5e0589ba24e69/lib/util/requestTranslator.js#L76-L90
|
50,794
|
feedhenry/fh-mbaas-middleware
|
lib/util/requestTranslator.js
|
parseListRequest
|
function parseListRequest(req){
var reqObj = {};
reqObj.originalUrl = req.originalUrl;
reqObj.uid = req.params.guid;
reqObj.env = req.params.environment;
reqObj.domain = req.params.domain;
return reqObj;
}
|
javascript
|
function parseListRequest(req){
var reqObj = {};
reqObj.originalUrl = req.originalUrl;
reqObj.uid = req.params.guid;
reqObj.env = req.params.environment;
reqObj.domain = req.params.domain;
return reqObj;
}
|
[
"function",
"parseListRequest",
"(",
"req",
")",
"{",
"var",
"reqObj",
"=",
"{",
"}",
";",
"reqObj",
".",
"originalUrl",
"=",
"req",
".",
"originalUrl",
";",
"reqObj",
".",
"uid",
"=",
"req",
".",
"params",
".",
"guid",
";",
"reqObj",
".",
"env",
"=",
"req",
".",
"params",
".",
"environment",
";",
"reqObj",
".",
"domain",
"=",
"req",
".",
"params",
".",
"domain",
";",
"return",
"reqObj",
";",
"}"
] |
Parse the incoming List Alert Request into a common object
|
[
"Parse",
"the",
"incoming",
"List",
"Alert",
"Request",
"into",
"a",
"common",
"object"
] |
f906e98efbb4b0963bf5137b34b5e0589ba24e69
|
https://github.com/feedhenry/fh-mbaas-middleware/blob/f906e98efbb4b0963bf5137b34b5e0589ba24e69/lib/util/requestTranslator.js#L95-L102
|
50,795
|
feedhenry/fh-mbaas-middleware
|
lib/util/requestTranslator.js
|
parseDeleteRequest
|
function parseDeleteRequest(req){
var reqObj = {};
reqObj.originalUrl = req.originalUrl;
reqObj.uid = req.params.guid;
reqObj.env =req.params.environment;
reqObj.domain = req.params.domain;
reqObj._id = req.params.id;
return reqObj;
}
|
javascript
|
function parseDeleteRequest(req){
var reqObj = {};
reqObj.originalUrl = req.originalUrl;
reqObj.uid = req.params.guid;
reqObj.env =req.params.environment;
reqObj.domain = req.params.domain;
reqObj._id = req.params.id;
return reqObj;
}
|
[
"function",
"parseDeleteRequest",
"(",
"req",
")",
"{",
"var",
"reqObj",
"=",
"{",
"}",
";",
"reqObj",
".",
"originalUrl",
"=",
"req",
".",
"originalUrl",
";",
"reqObj",
".",
"uid",
"=",
"req",
".",
"params",
".",
"guid",
";",
"reqObj",
".",
"env",
"=",
"req",
".",
"params",
".",
"environment",
";",
"reqObj",
".",
"domain",
"=",
"req",
".",
"params",
".",
"domain",
";",
"reqObj",
".",
"_id",
"=",
"req",
".",
"params",
".",
"id",
";",
"return",
"reqObj",
";",
"}"
] |
Parse the incoming Delete Alert Request into a common object
|
[
"Parse",
"the",
"incoming",
"Delete",
"Alert",
"Request",
"into",
"a",
"common",
"object"
] |
f906e98efbb4b0963bf5137b34b5e0589ba24e69
|
https://github.com/feedhenry/fh-mbaas-middleware/blob/f906e98efbb4b0963bf5137b34b5e0589ba24e69/lib/util/requestTranslator.js#L107-L115
|
50,796
|
wait1/wait1.js
|
lib/connection.js
|
parseAuth
|
function parseAuth(auth) {
var parts = auth.split(':');
if (parts[0] && !parts[1]) return ['wait1|t' + parts[0]];
if (!parts[0] && parts[1]) return ['wait1|t' + parts[1]];
if (!parts[0] && !parts[1]) return [];
return ['wait1|b' + (new Buffer(auth)).toString('base64')];
}
|
javascript
|
function parseAuth(auth) {
var parts = auth.split(':');
if (parts[0] && !parts[1]) return ['wait1|t' + parts[0]];
if (!parts[0] && parts[1]) return ['wait1|t' + parts[1]];
if (!parts[0] && !parts[1]) return [];
return ['wait1|b' + (new Buffer(auth)).toString('base64')];
}
|
[
"function",
"parseAuth",
"(",
"auth",
")",
"{",
"var",
"parts",
"=",
"auth",
".",
"split",
"(",
"':'",
")",
";",
"if",
"(",
"parts",
"[",
"0",
"]",
"&&",
"!",
"parts",
"[",
"1",
"]",
")",
"return",
"[",
"'wait1|t'",
"+",
"parts",
"[",
"0",
"]",
"]",
";",
"if",
"(",
"!",
"parts",
"[",
"0",
"]",
"&&",
"parts",
"[",
"1",
"]",
")",
"return",
"[",
"'wait1|t'",
"+",
"parts",
"[",
"1",
"]",
"]",
";",
"if",
"(",
"!",
"parts",
"[",
"0",
"]",
"&&",
"!",
"parts",
"[",
"1",
"]",
")",
"return",
"[",
"]",
";",
"return",
"[",
"'wait1|b'",
"+",
"(",
"new",
"Buffer",
"(",
"auth",
")",
")",
".",
"toString",
"(",
"'base64'",
")",
"]",
";",
"}"
] |
Parse an auth string
|
[
"Parse",
"an",
"auth",
"string"
] |
4d3739a787c7b62414a049df7d88dde61a03ab32
|
https://github.com/wait1/wait1.js/blob/4d3739a787c7b62414a049df7d88dde61a03ab32/lib/connection.js#L134-L140
|
50,797
|
tolokoban/ToloFrameWork
|
ker/com/x-img2css/x-img2css.com.js
|
zipSVG
|
function zipSVG(libs, svgContent, src) {
svgContent = svgContent
// Remove space between two tags.
.replace(/>[ \t\n\r]+</g, '><')
// Replace double quotes with single quotes.
.replace(/"/g, "'")
// Replace many spaces by one single space.
.replace(/[ \t\n\r]+/g, ' ');
var svgTree = libs.parseHTML(svgContent);
// We want to remove unused `id`attributes.
// Such an attribute is used as long as there is a `xlink:href` attribute referencing it.
var idsToKeep = {};
// Remove Inkscape tags and <image>.
libs.Tree.walk(svgTree, function(node) {
if (node.type !== libs.Tree.TAG) return;
var name = node.name.toLowerCase();
if (name == 'flowroot') {
libs.warning(
"Please don't use <flowRoot> nor <flowRegion> in your SVG (\"" + src + "\")!\n"
+ "If it was created with Inkscape, convert it in SVG 1.1 by opening the `Text` menu\n"
+ "and selecting \"Convert to Text\".",
src,
svgContent,
node.pos
);
}
var nodeToDelete = startsWith(
name,
"metadata", "inkscape:", "sodipodi:", "image", "dc:", "cc:", "rdf:",
"flowroot", "flowregion"
);
if (nodeToDelete) {
node.type = libs.Tree.VOID;
delete node.children;
} else if (node.attribs) {
var attribsToDelete = [];
var attribName, attribValue;
for (attribName in node.attribs) {
if (
startsWith(
attribName,
'inkscape:', 'sodipodi:', 'xmlns:inkscape', 'xmlns:sodipodi',
'xmlns:dc', 'xmlns:cc', 'xmlns:rdf'
)
) {
// This is an attribute to delete.
attribsToDelete.push(attribName);
} else {
// Look for references (`xlink:href`).
attribValue = node.attribs[attribName].trim();
if (attribName.toLowerCase() == 'xlink:href') {
if (attribValue.charAt(0) == '#') {
// Remember that this ID must not be deleted.
idsToKeep[attribValue.substr(1)] = 1;
}
} else {
// Look for local URLs: `url(#idToKeep)`.
var match;
while ((match = RX_LOCAL_URL.exec(attribValue))) {
idsToKeep[match[1]] = 1;
}
}
}
}
attribsToDelete.forEach(function (attribName) {
delete node.attribs[attribName];
});
}
});
// Removing emtpy <g> and <defs>.
libs.Tree.walk(svgTree, function(node) {
if (node.type != libs.Tree.TAG) return;
var name = node.name.toLowerCase();
if (node.attribs && node.attribs.id) {
// Try to remove unused ID.
if (!idsToKeep[node.attribs.id]) {
delete node.attribs.id;
}
}
if (['g', 'defs'].indexOf(name) > -1) {
// If this tag has no child, we must delete it.
var childrenCount = 0;
(node.children || []).forEach(function (child) {
if (child.type == libs.Tree.TEXT || child.type == libs.Tree.TAG) {
childrenCount++;
}
});
if (childrenCount == 0) {
// This tag is empty, remove it.
delete node.children;
node.type = libs.Tree.VOID;
}
}
});
var svg = libs.Tree.toString(svgTree);
return svg;
// The following code was used when we embeded the SVG in Data URI form.
/*
console.log(svg);
console.log();
console.log("Base64: " + (new Buffer(svg)).toString('base64').length);
console.log("UTF-8: " + encodeURIComponent(svg).length);
console.log();
var encodedSVG_base64 = (new Buffer(svg)).toString('base64');
var encodedSVG_utf8 = encodeURIComponent(svg);
if (encodedSVG_base64 < encodedSVG_utf8) {
return '"data:image/svg+xml;base64,' + encodedSVG_base64 + '"';
} else {
return '"data:image/svg+xml;utf8,' + encodedSVG_utf8 + '"';
}
*/
}
|
javascript
|
function zipSVG(libs, svgContent, src) {
svgContent = svgContent
// Remove space between two tags.
.replace(/>[ \t\n\r]+</g, '><')
// Replace double quotes with single quotes.
.replace(/"/g, "'")
// Replace many spaces by one single space.
.replace(/[ \t\n\r]+/g, ' ');
var svgTree = libs.parseHTML(svgContent);
// We want to remove unused `id`attributes.
// Such an attribute is used as long as there is a `xlink:href` attribute referencing it.
var idsToKeep = {};
// Remove Inkscape tags and <image>.
libs.Tree.walk(svgTree, function(node) {
if (node.type !== libs.Tree.TAG) return;
var name = node.name.toLowerCase();
if (name == 'flowroot') {
libs.warning(
"Please don't use <flowRoot> nor <flowRegion> in your SVG (\"" + src + "\")!\n"
+ "If it was created with Inkscape, convert it in SVG 1.1 by opening the `Text` menu\n"
+ "and selecting \"Convert to Text\".",
src,
svgContent,
node.pos
);
}
var nodeToDelete = startsWith(
name,
"metadata", "inkscape:", "sodipodi:", "image", "dc:", "cc:", "rdf:",
"flowroot", "flowregion"
);
if (nodeToDelete) {
node.type = libs.Tree.VOID;
delete node.children;
} else if (node.attribs) {
var attribsToDelete = [];
var attribName, attribValue;
for (attribName in node.attribs) {
if (
startsWith(
attribName,
'inkscape:', 'sodipodi:', 'xmlns:inkscape', 'xmlns:sodipodi',
'xmlns:dc', 'xmlns:cc', 'xmlns:rdf'
)
) {
// This is an attribute to delete.
attribsToDelete.push(attribName);
} else {
// Look for references (`xlink:href`).
attribValue = node.attribs[attribName].trim();
if (attribName.toLowerCase() == 'xlink:href') {
if (attribValue.charAt(0) == '#') {
// Remember that this ID must not be deleted.
idsToKeep[attribValue.substr(1)] = 1;
}
} else {
// Look for local URLs: `url(#idToKeep)`.
var match;
while ((match = RX_LOCAL_URL.exec(attribValue))) {
idsToKeep[match[1]] = 1;
}
}
}
}
attribsToDelete.forEach(function (attribName) {
delete node.attribs[attribName];
});
}
});
// Removing emtpy <g> and <defs>.
libs.Tree.walk(svgTree, function(node) {
if (node.type != libs.Tree.TAG) return;
var name = node.name.toLowerCase();
if (node.attribs && node.attribs.id) {
// Try to remove unused ID.
if (!idsToKeep[node.attribs.id]) {
delete node.attribs.id;
}
}
if (['g', 'defs'].indexOf(name) > -1) {
// If this tag has no child, we must delete it.
var childrenCount = 0;
(node.children || []).forEach(function (child) {
if (child.type == libs.Tree.TEXT || child.type == libs.Tree.TAG) {
childrenCount++;
}
});
if (childrenCount == 0) {
// This tag is empty, remove it.
delete node.children;
node.type = libs.Tree.VOID;
}
}
});
var svg = libs.Tree.toString(svgTree);
return svg;
// The following code was used when we embeded the SVG in Data URI form.
/*
console.log(svg);
console.log();
console.log("Base64: " + (new Buffer(svg)).toString('base64').length);
console.log("UTF-8: " + encodeURIComponent(svg).length);
console.log();
var encodedSVG_base64 = (new Buffer(svg)).toString('base64');
var encodedSVG_utf8 = encodeURIComponent(svg);
if (encodedSVG_base64 < encodedSVG_utf8) {
return '"data:image/svg+xml;base64,' + encodedSVG_base64 + '"';
} else {
return '"data:image/svg+xml;utf8,' + encodedSVG_utf8 + '"';
}
*/
}
|
[
"function",
"zipSVG",
"(",
"libs",
",",
"svgContent",
",",
"src",
")",
"{",
"svgContent",
"=",
"svgContent",
"// Remove space between two tags.",
".",
"replace",
"(",
"/",
">[ \\t\\n\\r]+<",
"/",
"g",
",",
"'><'",
")",
"// Replace double quotes with single quotes.",
".",
"replace",
"(",
"/",
"\"",
"/",
"g",
",",
"\"'\"",
")",
"// Replace many spaces by one single space.",
".",
"replace",
"(",
"/",
"[ \\t\\n\\r]+",
"/",
"g",
",",
"' '",
")",
";",
"var",
"svgTree",
"=",
"libs",
".",
"parseHTML",
"(",
"svgContent",
")",
";",
"// We want to remove unused `id`attributes.",
"// Such an attribute is used as long as there is a `xlink:href` attribute referencing it.",
"var",
"idsToKeep",
"=",
"{",
"}",
";",
"// Remove Inkscape tags and <image>.",
"libs",
".",
"Tree",
".",
"walk",
"(",
"svgTree",
",",
"function",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"type",
"!==",
"libs",
".",
"Tree",
".",
"TAG",
")",
"return",
";",
"var",
"name",
"=",
"node",
".",
"name",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"name",
"==",
"'flowroot'",
")",
"{",
"libs",
".",
"warning",
"(",
"\"Please don't use <flowRoot> nor <flowRegion> in your SVG (\\\"\"",
"+",
"src",
"+",
"\"\\\")!\\n\"",
"+",
"\"If it was created with Inkscape, convert it in SVG 1.1 by opening the `Text` menu\\n\"",
"+",
"\"and selecting \\\"Convert to Text\\\".\"",
",",
"src",
",",
"svgContent",
",",
"node",
".",
"pos",
")",
";",
"}",
"var",
"nodeToDelete",
"=",
"startsWith",
"(",
"name",
",",
"\"metadata\"",
",",
"\"inkscape:\"",
",",
"\"sodipodi:\"",
",",
"\"image\"",
",",
"\"dc:\"",
",",
"\"cc:\"",
",",
"\"rdf:\"",
",",
"\"flowroot\"",
",",
"\"flowregion\"",
")",
";",
"if",
"(",
"nodeToDelete",
")",
"{",
"node",
".",
"type",
"=",
"libs",
".",
"Tree",
".",
"VOID",
";",
"delete",
"node",
".",
"children",
";",
"}",
"else",
"if",
"(",
"node",
".",
"attribs",
")",
"{",
"var",
"attribsToDelete",
"=",
"[",
"]",
";",
"var",
"attribName",
",",
"attribValue",
";",
"for",
"(",
"attribName",
"in",
"node",
".",
"attribs",
")",
"{",
"if",
"(",
"startsWith",
"(",
"attribName",
",",
"'inkscape:'",
",",
"'sodipodi:'",
",",
"'xmlns:inkscape'",
",",
"'xmlns:sodipodi'",
",",
"'xmlns:dc'",
",",
"'xmlns:cc'",
",",
"'xmlns:rdf'",
")",
")",
"{",
"// This is an attribute to delete.",
"attribsToDelete",
".",
"push",
"(",
"attribName",
")",
";",
"}",
"else",
"{",
"// Look for references (`xlink:href`).",
"attribValue",
"=",
"node",
".",
"attribs",
"[",
"attribName",
"]",
".",
"trim",
"(",
")",
";",
"if",
"(",
"attribName",
".",
"toLowerCase",
"(",
")",
"==",
"'xlink:href'",
")",
"{",
"if",
"(",
"attribValue",
".",
"charAt",
"(",
"0",
")",
"==",
"'#'",
")",
"{",
"// Remember that this ID must not be deleted.",
"idsToKeep",
"[",
"attribValue",
".",
"substr",
"(",
"1",
")",
"]",
"=",
"1",
";",
"}",
"}",
"else",
"{",
"// Look for local URLs: `url(#idToKeep)`.",
"var",
"match",
";",
"while",
"(",
"(",
"match",
"=",
"RX_LOCAL_URL",
".",
"exec",
"(",
"attribValue",
")",
")",
")",
"{",
"idsToKeep",
"[",
"match",
"[",
"1",
"]",
"]",
"=",
"1",
";",
"}",
"}",
"}",
"}",
"attribsToDelete",
".",
"forEach",
"(",
"function",
"(",
"attribName",
")",
"{",
"delete",
"node",
".",
"attribs",
"[",
"attribName",
"]",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"// Removing emtpy <g> and <defs>.",
"libs",
".",
"Tree",
".",
"walk",
"(",
"svgTree",
",",
"function",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"type",
"!=",
"libs",
".",
"Tree",
".",
"TAG",
")",
"return",
";",
"var",
"name",
"=",
"node",
".",
"name",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"node",
".",
"attribs",
"&&",
"node",
".",
"attribs",
".",
"id",
")",
"{",
"// Try to remove unused ID.",
"if",
"(",
"!",
"idsToKeep",
"[",
"node",
".",
"attribs",
".",
"id",
"]",
")",
"{",
"delete",
"node",
".",
"attribs",
".",
"id",
";",
"}",
"}",
"if",
"(",
"[",
"'g'",
",",
"'defs'",
"]",
".",
"indexOf",
"(",
"name",
")",
">",
"-",
"1",
")",
"{",
"// If this tag has no child, we must delete it.",
"var",
"childrenCount",
"=",
"0",
";",
"(",
"node",
".",
"children",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"child",
")",
"{",
"if",
"(",
"child",
".",
"type",
"==",
"libs",
".",
"Tree",
".",
"TEXT",
"||",
"child",
".",
"type",
"==",
"libs",
".",
"Tree",
".",
"TAG",
")",
"{",
"childrenCount",
"++",
";",
"}",
"}",
")",
";",
"if",
"(",
"childrenCount",
"==",
"0",
")",
"{",
"// This tag is empty, remove it.",
"delete",
"node",
".",
"children",
";",
"node",
".",
"type",
"=",
"libs",
".",
"Tree",
".",
"VOID",
";",
"}",
"}",
"}",
")",
";",
"var",
"svg",
"=",
"libs",
".",
"Tree",
".",
"toString",
"(",
"svgTree",
")",
";",
"return",
"svg",
";",
"// The following code was used when we embeded the SVG in Data URI form.",
"/*\n console.log(svg);\n console.log();\n console.log(\"Base64: \" + (new Buffer(svg)).toString('base64').length);\n console.log(\"UTF-8: \" + encodeURIComponent(svg).length);\n console.log();\n var encodedSVG_base64 = (new Buffer(svg)).toString('base64');\n var encodedSVG_utf8 = encodeURIComponent(svg);\n if (encodedSVG_base64 < encodedSVG_utf8) {\n return '\"data:image/svg+xml;base64,' + encodedSVG_base64 + '\"';\n } else {\n return '\"data:image/svg+xml;utf8,' + encodedSVG_utf8 + '\"';\n }\n */",
"}"
] |
Return the lightest SVG possible.
|
[
"Return",
"the",
"lightest",
"SVG",
"possible",
"."
] |
730845a833a9660ebfdb60ad027ebaab5ac871b6
|
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/com/x-img2css/x-img2css.com.js#L83-L197
|
50,798
|
tolokoban/ToloFrameWork
|
ker/com/x-img2css/x-img2css.com.js
|
startsWith
|
function startsWith(text) {
var i, arg;
for (i = 1 ; i < arguments.length ; i++) {
arg = arguments[i];
if (text.substr(0, arg.length) == arg) return true;
}
return false;
}
|
javascript
|
function startsWith(text) {
var i, arg;
for (i = 1 ; i < arguments.length ; i++) {
arg = arguments[i];
if (text.substr(0, arg.length) == arg) return true;
}
return false;
}
|
[
"function",
"startsWith",
"(",
"text",
")",
"{",
"var",
"i",
",",
"arg",
";",
"for",
"(",
"i",
"=",
"1",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"arg",
"=",
"arguments",
"[",
"i",
"]",
";",
"if",
"(",
"text",
".",
"substr",
"(",
"0",
",",
"arg",
".",
"length",
")",
"==",
"arg",
")",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Return True if `text` starts by at least one of the remaining arguments.
|
[
"Return",
"True",
"if",
"text",
"starts",
"by",
"at",
"least",
"one",
"of",
"the",
"remaining",
"arguments",
"."
] |
730845a833a9660ebfdb60ad027ebaab5ac871b6
|
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/com/x-img2css/x-img2css.com.js#L203-L210
|
50,799
|
Amberlamps/object-subset
|
dist/objectSubset.js
|
createSubset
|
function createSubset(keywords, doc) {
if (!keywords || Object.prototype.toString.call(keywords) !== '[object Array]') {
return doc;
}
var lookup = createLookUp(keywords);
return traverseThroughObject(lookup, doc);
}
|
javascript
|
function createSubset(keywords, doc) {
if (!keywords || Object.prototype.toString.call(keywords) !== '[object Array]') {
return doc;
}
var lookup = createLookUp(keywords);
return traverseThroughObject(lookup, doc);
}
|
[
"function",
"createSubset",
"(",
"keywords",
",",
"doc",
")",
"{",
"if",
"(",
"!",
"keywords",
"||",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"keywords",
")",
"!==",
"'[object Array]'",
")",
"{",
"return",
"doc",
";",
"}",
"var",
"lookup",
"=",
"createLookUp",
"(",
"keywords",
")",
";",
"return",
"traverseThroughObject",
"(",
"lookup",
",",
"doc",
")",
";",
"}"
] |
createSubset is initializing the creation of the subset.
If keywords is not an array return doc immediately.
|
[
"createSubset",
"is",
"initializing",
"the",
"creation",
"of",
"the",
"subset",
".",
"If",
"keywords",
"is",
"not",
"an",
"array",
"return",
"doc",
"immediately",
"."
] |
c96436360381a4e0c662531c18a82afc6290ea0c
|
https://github.com/Amberlamps/object-subset/blob/c96436360381a4e0c662531c18a82afc6290ea0c/dist/objectSubset.js#L23-L33
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.