id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
54,500 | Colingo/populate | examples/complex.js | function (value, elem) {
var tmpl = elem.firstElementChild
elem.removeChild(tmpl)
value.forEach(function (text) {
var clone = tmpl.cloneNode(true)
clone.textContent = text
elem.appendChild(clone)
})
} | javascript | function (value, elem) {
var tmpl = elem.firstElementChild
elem.removeChild(tmpl)
value.forEach(function (text) {
var clone = tmpl.cloneNode(true)
clone.textContent = text
elem.appendChild(clone)
})
} | [
"function",
"(",
"value",
",",
"elem",
")",
"{",
"var",
"tmpl",
"=",
"elem",
".",
"firstElementChild",
"elem",
".",
"removeChild",
"(",
"tmpl",
")",
"value",
".",
"forEach",
"(",
"function",
"(",
"text",
")",
"{",
"var",
"clone",
"=",
"tmpl",
".",
"cloneNode",
"(",
"true",
")",
"clone",
".",
"textContent",
"=",
"text",
"elem",
".",
"appendChild",
"(",
"clone",
")",
"}",
")",
"}"
] | Custom logic. Mappings are just functions, do anything you want! | [
"Custom",
"logic",
".",
"Mappings",
"are",
"just",
"functions",
"do",
"anything",
"you",
"want!"
] | a5244b9d72ac96c3a090b5efb6d23801f9afc3a0 | https://github.com/Colingo/populate/blob/a5244b9d72ac96c3a090b5efb6d23801f9afc3a0/examples/complex.js#L26-L35 |
|
54,501 | opsmezzo/composer-api | node.js/lib/client/client.js | isOk | function isOk(err, res, body) {
if (err) {
return callback(err);
}
var statusCode = res.statusCode.toString(),
error;
//
// Emit response for debug purpose
//
self.emit('debug::response', { statusCode: statusCode, result: body });
if (Object.keys(self.failCodes).indexOf(statusCode) !== -1) {
error = new Error('composer Error (' + statusCode + '): ' + self.failCodes[statusCode]);
if (body) {
try { error.result = JSON.parse(body) }
catch (ex) {}
}
error.status = res.statusCode;
callback(error);
return false
}
return true;
} | javascript | function isOk(err, res, body) {
if (err) {
return callback(err);
}
var statusCode = res.statusCode.toString(),
error;
//
// Emit response for debug purpose
//
self.emit('debug::response', { statusCode: statusCode, result: body });
if (Object.keys(self.failCodes).indexOf(statusCode) !== -1) {
error = new Error('composer Error (' + statusCode + '): ' + self.failCodes[statusCode]);
if (body) {
try { error.result = JSON.parse(body) }
catch (ex) {}
}
error.status = res.statusCode;
callback(error);
return false
}
return true;
} | [
"function",
"isOk",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"var",
"statusCode",
"=",
"res",
".",
"statusCode",
".",
"toString",
"(",
")",
",",
"error",
";",
"//",
"// Emit response for debug purpose",
"//",
"self",
".",
"emit",
"(",
"'debug::response'",
",",
"{",
"statusCode",
":",
"statusCode",
",",
"result",
":",
"body",
"}",
")",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"self",
".",
"failCodes",
")",
".",
"indexOf",
"(",
"statusCode",
")",
"!==",
"-",
"1",
")",
"{",
"error",
"=",
"new",
"Error",
"(",
"'composer Error ('",
"+",
"statusCode",
"+",
"'): '",
"+",
"self",
".",
"failCodes",
"[",
"statusCode",
"]",
")",
";",
"if",
"(",
"body",
")",
"{",
"try",
"{",
"error",
".",
"result",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
"}",
"catch",
"(",
"ex",
")",
"{",
"}",
"}",
"error",
".",
"status",
"=",
"res",
".",
"statusCode",
";",
"callback",
"(",
"error",
")",
";",
"return",
"false",
"}",
"return",
"true",
";",
"}"
] | Helper function for checking response codes | [
"Helper",
"function",
"for",
"checking",
"response",
"codes"
] | 85d595a4046a0fd39c30afe564628882994926f7 | https://github.com/opsmezzo/composer-api/blob/85d595a4046a0fd39c30afe564628882994926f7/node.js/lib/client/client.js#L133-L158 |
54,502 | schahriar/herb | lib/super.js | function(attributes, isPermanent) {
if(isPermanent) attributes.permanent = true;
if(attributes === 'reset') this.markerAttributes = {
background: undefined,
color: undefined,
style: undefined,
verbosity: undefined
}; else _.defaults(this.__super__.markerAttributes, attributes);
return this;
} | javascript | function(attributes, isPermanent) {
if(isPermanent) attributes.permanent = true;
if(attributes === 'reset') this.markerAttributes = {
background: undefined,
color: undefined,
style: undefined,
verbosity: undefined
}; else _.defaults(this.__super__.markerAttributes, attributes);
return this;
} | [
"function",
"(",
"attributes",
",",
"isPermanent",
")",
"{",
"if",
"(",
"isPermanent",
")",
"attributes",
".",
"permanent",
"=",
"true",
";",
"if",
"(",
"attributes",
"===",
"'reset'",
")",
"this",
".",
"markerAttributes",
"=",
"{",
"background",
":",
"undefined",
",",
"color",
":",
"undefined",
",",
"style",
":",
"undefined",
",",
"verbosity",
":",
"undefined",
"}",
";",
"else",
"_",
".",
"defaults",
"(",
"this",
".",
"__super__",
".",
"markerAttributes",
",",
"attributes",
")",
";",
"return",
"this",
";",
"}"
] | Marker allows for modification of each log | [
"Marker",
"allows",
"for",
"modification",
"of",
"each",
"log"
] | 76239befbe59bc040298be56d3b0889bd6342ca1 | https://github.com/schahriar/herb/blob/76239befbe59bc040298be56d3b0889bd6342ca1/lib/super.js#L36-L46 |
|
54,503 | rkusa/swac-odm | lib/observable.js | binarySearch | function binarySearch(o, v, i, compareFunction){
var h = o.length, l = -1, m
while(h - l > 1)
if(compareFunction(o[m = h + l >> 1], v) < 1) l = m
else h = m
return o[h] != v ? i ? h : -1 : h
} | javascript | function binarySearch(o, v, i, compareFunction){
var h = o.length, l = -1, m
while(h - l > 1)
if(compareFunction(o[m = h + l >> 1], v) < 1) l = m
else h = m
return o[h] != v ? i ? h : -1 : h
} | [
"function",
"binarySearch",
"(",
"o",
",",
"v",
",",
"i",
",",
"compareFunction",
")",
"{",
"var",
"h",
"=",
"o",
".",
"length",
",",
"l",
"=",
"-",
"1",
",",
"m",
"while",
"(",
"h",
"-",
"l",
">",
"1",
")",
"if",
"(",
"compareFunction",
"(",
"o",
"[",
"m",
"=",
"h",
"+",
"l",
">>",
"1",
"]",
",",
"v",
")",
"<",
"1",
")",
"l",
"=",
"m",
"else",
"h",
"=",
"m",
"return",
"o",
"[",
"h",
"]",
"!=",
"v",
"?",
"i",
"?",
"h",
":",
"-",
"1",
":",
"h",
"}"
] | modified version of + Carlos R. L. Rodrigues @ http://jsfromhell.com/array/search [rev. #2] o: array that will be looked up v: object that will be searched b: if true, the function will return the index where the value should be inserted to keep the array ordered, otherwise returns the index where the value was found or -1 if it wasn't found | [
"modified",
"version",
"of",
"+",
"Carlos",
"R",
".",
"L",
".",
"Rodrigues"
] | a1df9a2e78098cc4f17be2a37afc32ff7f8bf54f | https://github.com/rkusa/swac-odm/blob/a1df9a2e78098cc4f17be2a37afc32ff7f8bf54f/lib/observable.js#L575-L581 |
54,504 | wenwuwu/number-es5 | lib/number.js | function (n1, n2) {
var isOk1 = _isNumber(n1),
isOk2 = _isNumber(n2);
if (isOk1 && isOk2) {
// both are finite numbers
return (n1 - n2);
}
else if (isOk1)
return -1;
else if (isOk2)
return 1;
else
return 0;
} | javascript | function (n1, n2) {
var isOk1 = _isNumber(n1),
isOk2 = _isNumber(n2);
if (isOk1 && isOk2) {
// both are finite numbers
return (n1 - n2);
}
else if (isOk1)
return -1;
else if (isOk2)
return 1;
else
return 0;
} | [
"function",
"(",
"n1",
",",
"n2",
")",
"{",
"var",
"isOk1",
"=",
"_isNumber",
"(",
"n1",
")",
",",
"isOk2",
"=",
"_isNumber",
"(",
"n2",
")",
";",
"if",
"(",
"isOk1",
"&&",
"isOk2",
")",
"{",
"// both are finite numbers\r",
"return",
"(",
"n1",
"-",
"n2",
")",
";",
"}",
"else",
"if",
"(",
"isOk1",
")",
"return",
"-",
"1",
";",
"else",
"if",
"(",
"isOk2",
")",
"return",
"1",
";",
"else",
"return",
"0",
";",
"}"
] | Compare two numbers. | [
"Compare",
"two",
"numbers",
"."
] | f59fae84690f011e758a19107fbe5282aef757b4 | https://github.com/wenwuwu/number-es5/blob/f59fae84690f011e758a19107fbe5282aef757b4/lib/number.js#L263-L277 |
|
54,505 | wenwuwu/number-es5 | lib/number.js | function (itr, noError) {
if ( typeof itr.hasNext !== 'function'
|| typeof itr.next !== 'function' )
throw "IllegalArgumentException: itr must implement methods hasNext() and next().";
var prec = 0;
while (itr.hasNext()) {
var p = _getPrecision(itr.next(), noError);
if (p > prec)
prec = p;
}
return prec;
} | javascript | function (itr, noError) {
if ( typeof itr.hasNext !== 'function'
|| typeof itr.next !== 'function' )
throw "IllegalArgumentException: itr must implement methods hasNext() and next().";
var prec = 0;
while (itr.hasNext()) {
var p = _getPrecision(itr.next(), noError);
if (p > prec)
prec = p;
}
return prec;
} | [
"function",
"(",
"itr",
",",
"noError",
")",
"{",
"if",
"(",
"typeof",
"itr",
".",
"hasNext",
"!==",
"'function'",
"||",
"typeof",
"itr",
".",
"next",
"!==",
"'function'",
")",
"throw",
"\"IllegalArgumentException: itr must implement methods hasNext() and next().\"",
";",
"var",
"prec",
"=",
"0",
";",
"while",
"(",
"itr",
".",
"hasNext",
"(",
")",
")",
"{",
"var",
"p",
"=",
"_getPrecision",
"(",
"itr",
".",
"next",
"(",
")",
",",
"noError",
")",
";",
"if",
"(",
"p",
">",
"prec",
")",
"prec",
"=",
"p",
";",
"}",
"return",
"prec",
";",
"}"
] | Returns the max precision within an Iterator of numbers.
If this is a float, this method returns the number of decimals.
If this is an integer, this method returns a negative number.
@param itr {Arrays.Iterator}
@param noError {Boolean} Optional. Whether throw exception when encountering a
non-numeric value. Default is 'false'.
@return {Number} Integer
@see Number.precision | [
"Returns",
"the",
"max",
"precision",
"within",
"an",
"Iterator",
"of",
"numbers",
".",
"If",
"this",
"is",
"a",
"float",
"this",
"method",
"returns",
"the",
"number",
"of",
"decimals",
".",
"If",
"this",
"is",
"an",
"integer",
"this",
"method",
"returns",
"a",
"negative",
"number",
"."
] | f59fae84690f011e758a19107fbe5282aef757b4 | https://github.com/wenwuwu/number-es5/blob/f59fae84690f011e758a19107fbe5282aef757b4/lib/number.js#L419-L433 |
|
54,506 | wenwuwu/number-es5 | lib/number.js | function (num) {
if (typeof num !== 'number')
throw "TypeMismatch: num: Number";
else if (!isFinite(num))
return num.toString();
else {
var p = _getPrecision(num);
return num.toFixed(Math.max(0, p));
}
} | javascript | function (num) {
if (typeof num !== 'number')
throw "TypeMismatch: num: Number";
else if (!isFinite(num))
return num.toString();
else {
var p = _getPrecision(num);
return num.toFixed(Math.max(0, p));
}
} | [
"function",
"(",
"num",
")",
"{",
"if",
"(",
"typeof",
"num",
"!==",
"'number'",
")",
"throw",
"\"TypeMismatch: num: Number\"",
";",
"else",
"if",
"(",
"!",
"isFinite",
"(",
"num",
")",
")",
"return",
"num",
".",
"toString",
"(",
")",
";",
"else",
"{",
"var",
"p",
"=",
"_getPrecision",
"(",
"num",
")",
";",
"return",
"num",
".",
"toFixed",
"(",
"Math",
".",
"max",
"(",
"0",
",",
"p",
")",
")",
";",
"}",
"}"
] | Converts a number to a String.
This function covers the problem of the IEEE weirdness.
This function is useful when converting a number to String
without knowing how many decimals a number has.
Note that if caller knows how many decimals it wants then
it should use Number.toFixed() instead.
( Because inside this method it calls _getPrecision(num) to
get a number's precision first. )
@param num {Number}
@return {String} | [
"Converts",
"a",
"number",
"to",
"a",
"String",
".",
"This",
"function",
"covers",
"the",
"problem",
"of",
"the",
"IEEE",
"weirdness",
"."
] | f59fae84690f011e758a19107fbe5282aef757b4 | https://github.com/wenwuwu/number-es5/blob/f59fae84690f011e758a19107fbe5282aef757b4/lib/number.js#L476-L488 |
|
54,507 | wenwuwu/number-es5 | lib/number.js | function (format) {
_validFormat(format);
var fn = null;
if (_formatFnAll.hasOwnProperty(format))
fn = _formatFnAll[format];
else {
var m = _regexDecFormat.exec(format);
if (m !== null)
fn = _getDecFormatter( ( (typeof m[3] === 'string')
? m[3].length
: 0 ),
(m[1] === '+'),
(m[4] === '%') );
else {
m = _regexFracFormat.exec(format);
if (m !== null)
fn = _getFractFormatter( parseInt(m[2], 10),
(m[1] === '+') ); // isPlus
}
_formatFnAll[format] = fn;
}
if (fn !== null)
return fn;
else // Throw an exception every time
throw "IllegalArgumentException: unsupported number format (" + format + ")";
} | javascript | function (format) {
_validFormat(format);
var fn = null;
if (_formatFnAll.hasOwnProperty(format))
fn = _formatFnAll[format];
else {
var m = _regexDecFormat.exec(format);
if (m !== null)
fn = _getDecFormatter( ( (typeof m[3] === 'string')
? m[3].length
: 0 ),
(m[1] === '+'),
(m[4] === '%') );
else {
m = _regexFracFormat.exec(format);
if (m !== null)
fn = _getFractFormatter( parseInt(m[2], 10),
(m[1] === '+') ); // isPlus
}
_formatFnAll[format] = fn;
}
if (fn !== null)
return fn;
else // Throw an exception every time
throw "IllegalArgumentException: unsupported number format (" + format + ")";
} | [
"function",
"(",
"format",
")",
"{",
"_validFormat",
"(",
"format",
")",
";",
"var",
"fn",
"=",
"null",
";",
"if",
"(",
"_formatFnAll",
".",
"hasOwnProperty",
"(",
"format",
")",
")",
"fn",
"=",
"_formatFnAll",
"[",
"format",
"]",
";",
"else",
"{",
"var",
"m",
"=",
"_regexDecFormat",
".",
"exec",
"(",
"format",
")",
";",
"if",
"(",
"m",
"!==",
"null",
")",
"fn",
"=",
"_getDecFormatter",
"(",
"(",
"(",
"typeof",
"m",
"[",
"3",
"]",
"===",
"'string'",
")",
"?",
"m",
"[",
"3",
"]",
".",
"length",
":",
"0",
")",
",",
"(",
"m",
"[",
"1",
"]",
"===",
"'+'",
")",
",",
"(",
"m",
"[",
"4",
"]",
"===",
"'%'",
")",
")",
";",
"else",
"{",
"m",
"=",
"_regexFracFormat",
".",
"exec",
"(",
"format",
")",
";",
"if",
"(",
"m",
"!==",
"null",
")",
"fn",
"=",
"_getFractFormatter",
"(",
"parseInt",
"(",
"m",
"[",
"2",
"]",
",",
"10",
")",
",",
"(",
"m",
"[",
"1",
"]",
"===",
"'+'",
")",
")",
";",
"// isPlus\r",
"}",
"_formatFnAll",
"[",
"format",
"]",
"=",
"fn",
";",
"}",
"if",
"(",
"fn",
"!==",
"null",
")",
"return",
"fn",
";",
"else",
"// Throw an exception every time\r",
"throw",
"\"IllegalArgumentException: unsupported number format (\"",
"+",
"format",
"+",
"\")\"",
";",
"}"
] | Returns a Function that formats numbers
into a 'string' value.
Examples:
Number.getFormatter("0.00")(5.125) == "5.13"
Number.getFormatter("0.0000")(5.125) == "5.1250"
Number.getFormatter("0'1/8")(5.125) == "5'1"
@param format {String}
@return {Function} A function that takes one 'number'
argument and converts it into a String value. | [
"Returns",
"a",
"Function",
"that",
"formats",
"numbers",
"into",
"a",
"string",
"value",
"."
] | f59fae84690f011e758a19107fbe5282aef757b4 | https://github.com/wenwuwu/number-es5/blob/f59fae84690f011e758a19107fbe5282aef757b4/lib/number.js#L538-L570 |
|
54,508 | wenwuwu/number-es5 | lib/number.js | function (format) {
_validFormat(format);
var m = _regexDecFormat.exec(format);
if (m !== null)
return ( (typeof m[3] === 'string') ? m[3].length : 0 )
+ ( (m[4] === '%') ? 2 : 0 );
else {
m = _regexFracFormat.exec(format);
if (m !== null)
return _getPrecision(1 / parseInt(m[2], 10));
}
throw "IllegalArgumentException: format is not recognized (" + format + ")";
} | javascript | function (format) {
_validFormat(format);
var m = _regexDecFormat.exec(format);
if (m !== null)
return ( (typeof m[3] === 'string') ? m[3].length : 0 )
+ ( (m[4] === '%') ? 2 : 0 );
else {
m = _regexFracFormat.exec(format);
if (m !== null)
return _getPrecision(1 / parseInt(m[2], 10));
}
throw "IllegalArgumentException: format is not recognized (" + format + ")";
} | [
"function",
"(",
"format",
")",
"{",
"_validFormat",
"(",
"format",
")",
";",
"var",
"m",
"=",
"_regexDecFormat",
".",
"exec",
"(",
"format",
")",
";",
"if",
"(",
"m",
"!==",
"null",
")",
"return",
"(",
"(",
"typeof",
"m",
"[",
"3",
"]",
"===",
"'string'",
")",
"?",
"m",
"[",
"3",
"]",
".",
"length",
":",
"0",
")",
"+",
"(",
"(",
"m",
"[",
"4",
"]",
"===",
"'%'",
")",
"?",
"2",
":",
"0",
")",
";",
"else",
"{",
"m",
"=",
"_regexFracFormat",
".",
"exec",
"(",
"format",
")",
";",
"if",
"(",
"m",
"!==",
"null",
")",
"return",
"_getPrecision",
"(",
"1",
"/",
"parseInt",
"(",
"m",
"[",
"2",
"]",
",",
"10",
")",
")",
";",
"}",
"throw",
"\"IllegalArgumentException: format is not recognized (\"",
"+",
"format",
"+",
"\")\"",
";",
"}"
] | Returns the number of decimals necessary to do
math operations accurately with specified 'format'.
@param format {String}
@return {Integer} Number of decimals, >= 0 | [
"Returns",
"the",
"number",
"of",
"decimals",
"necessary",
"to",
"do",
"math",
"operations",
"accurately",
"with",
"specified",
"format",
"."
] | f59fae84690f011e758a19107fbe5282aef757b4 | https://github.com/wenwuwu/number-es5/blob/f59fae84690f011e758a19107fbe5282aef757b4/lib/number.js#L579-L594 |
|
54,509 | Magneds/hapi-plugin-barcode | source/Barcode.js | unify | function unify(options) {
const map = {
height: 'barHeight',
background: 'bgColor',
text: 'showHRI'
};
return Object.keys(options).reduce(
(carry, key) => ({
...carry,
[key in map ? map[key] : key]: options[key]
}),
{}
);
} | javascript | function unify(options) {
const map = {
height: 'barHeight',
background: 'bgColor',
text: 'showHRI'
};
return Object.keys(options).reduce(
(carry, key) => ({
...carry,
[key in map ? map[key] : key]: options[key]
}),
{}
);
} | [
"function",
"unify",
"(",
"options",
")",
"{",
"const",
"map",
"=",
"{",
"height",
":",
"'barHeight'",
",",
"background",
":",
"'bgColor'",
",",
"text",
":",
"'showHRI'",
"}",
";",
"return",
"Object",
".",
"keys",
"(",
"options",
")",
".",
"reduce",
"(",
"(",
"carry",
",",
"key",
")",
"=>",
"(",
"{",
"...",
"carry",
",",
"[",
"key",
"in",
"map",
"?",
"map",
"[",
"key",
"]",
":",
"key",
"]",
":",
"options",
"[",
"key",
"]",
"}",
")",
",",
"{",
"}",
")",
";",
"}"
] | Unify the parameters for the barcode plugin
@param {object} options
@returns {object} options | [
"Unify",
"the",
"parameters",
"for",
"the",
"barcode",
"plugin"
] | 4822bd2d1aa327a752a9573151396496c080424d | https://github.com/Magneds/hapi-plugin-barcode/blob/4822bd2d1aa327a752a9573151396496c080424d/source/Barcode.js#L17-L31 |
54,510 | Industryswarm/isnode-mod-data | lib/mongodb/mongodb-core/lib/topologies/mongos.js | applyAuth | function applyAuth(authContexts, server, callback) {
if (authContexts.length === 0) return callback();
// Get the first auth context
var authContext = authContexts.shift();
// Copy the params
var customAuthContext = authContext.slice(0);
// Push our callback handler
customAuthContext.push(function(/* err */) {
applyAuth(authContexts, server, callback);
});
// Attempt authentication
server.auth.apply(server, customAuthContext);
} | javascript | function applyAuth(authContexts, server, callback) {
if (authContexts.length === 0) return callback();
// Get the first auth context
var authContext = authContexts.shift();
// Copy the params
var customAuthContext = authContext.slice(0);
// Push our callback handler
customAuthContext.push(function(/* err */) {
applyAuth(authContexts, server, callback);
});
// Attempt authentication
server.auth.apply(server, customAuthContext);
} | [
"function",
"applyAuth",
"(",
"authContexts",
",",
"server",
",",
"callback",
")",
"{",
"if",
"(",
"authContexts",
".",
"length",
"===",
"0",
")",
"return",
"callback",
"(",
")",
";",
"// Get the first auth context",
"var",
"authContext",
"=",
"authContexts",
".",
"shift",
"(",
")",
";",
"// Copy the params",
"var",
"customAuthContext",
"=",
"authContext",
".",
"slice",
"(",
"0",
")",
";",
"// Push our callback handler",
"customAuthContext",
".",
"push",
"(",
"function",
"(",
"/* err */",
")",
"{",
"applyAuth",
"(",
"authContexts",
",",
"server",
",",
"callback",
")",
";",
"}",
")",
";",
"// Attempt authentication",
"server",
".",
"auth",
".",
"apply",
"(",
"server",
",",
"customAuthContext",
")",
";",
"}"
] | Apply one of the contexts | [
"Apply",
"one",
"of",
"the",
"contexts"
] | 5adc639b88a0d72cbeef23a6b5df7f4540745089 | https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/topologies/mongos.js#L660-L673 |
54,511 | Industryswarm/isnode-mod-data | lib/mongodb/mongodb-core/lib/topologies/mongos.js | function(self, op, ns, ops, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Pick a server
let server = pickProxy(self);
// No server found error out
if (!server) return callback(new MongoError('no mongos proxy available'));
if (!options.retryWrites || !options.session || !isRetryableWritesSupported(self)) {
// Execute the command
return server[op](ns, ops, options, callback);
}
// increment and assign txnNumber
options.willRetryWrite = true;
options.session.incrementTransactionNumber();
server[op](ns, ops, options, (err, result) => {
if (!err) return callback(null, result);
if (!isRetryableError(err)) {
return callback(err);
}
// Pick another server
server = pickProxy(self);
// No server found error out with original error
if (!server || !isRetryableWritesSupported(server)) {
return callback(err);
}
// rerun the operation
server[op](ns, ops, options, callback);
});
} | javascript | function(self, op, ns, ops, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Pick a server
let server = pickProxy(self);
// No server found error out
if (!server) return callback(new MongoError('no mongos proxy available'));
if (!options.retryWrites || !options.session || !isRetryableWritesSupported(self)) {
// Execute the command
return server[op](ns, ops, options, callback);
}
// increment and assign txnNumber
options.willRetryWrite = true;
options.session.incrementTransactionNumber();
server[op](ns, ops, options, (err, result) => {
if (!err) return callback(null, result);
if (!isRetryableError(err)) {
return callback(err);
}
// Pick another server
server = pickProxy(self);
// No server found error out with original error
if (!server || !isRetryableWritesSupported(server)) {
return callback(err);
}
// rerun the operation
server[op](ns, ops, options, callback);
});
} | [
"function",
"(",
"self",
",",
"op",
",",
"ns",
",",
"ops",
",",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"(",
"callback",
"=",
"options",
")",
",",
"(",
"options",
"=",
"{",
"}",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"// Pick a server",
"let",
"server",
"=",
"pickProxy",
"(",
"self",
")",
";",
"// No server found error out",
"if",
"(",
"!",
"server",
")",
"return",
"callback",
"(",
"new",
"MongoError",
"(",
"'no mongos proxy available'",
")",
")",
";",
"if",
"(",
"!",
"options",
".",
"retryWrites",
"||",
"!",
"options",
".",
"session",
"||",
"!",
"isRetryableWritesSupported",
"(",
"self",
")",
")",
"{",
"// Execute the command",
"return",
"server",
"[",
"op",
"]",
"(",
"ns",
",",
"ops",
",",
"options",
",",
"callback",
")",
";",
"}",
"// increment and assign txnNumber",
"options",
".",
"willRetryWrite",
"=",
"true",
";",
"options",
".",
"session",
".",
"incrementTransactionNumber",
"(",
")",
";",
"server",
"[",
"op",
"]",
"(",
"ns",
",",
"ops",
",",
"options",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"!",
"err",
")",
"return",
"callback",
"(",
"null",
",",
"result",
")",
";",
"if",
"(",
"!",
"isRetryableError",
"(",
"err",
")",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Pick another server",
"server",
"=",
"pickProxy",
"(",
"self",
")",
";",
"// No server found error out with original error",
"if",
"(",
"!",
"server",
"||",
"!",
"isRetryableWritesSupported",
"(",
"server",
")",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// rerun the operation",
"server",
"[",
"op",
"]",
"(",
"ns",
",",
"ops",
",",
"options",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] | Operations Execute write operation | [
"Operations",
"Execute",
"write",
"operation"
] | 5adc639b88a0d72cbeef23a6b5df7f4540745089 | https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/topologies/mongos.js#L885-L920 |
|
54,512 | soldair/node-mocktimers | index.js | ordered | function ordered (ondelay) {
var clk = 0
var queue = []
var checking = 0
function check () {
if (checking++) return
setImmediate(function () {
var o = queue.shift()
clk = o[1]
ondelay(function () {
checking = 0
if (queue.length) check()
o[0]()
}, o[2])
})
}
function delay (fn, ms) {
var len = queue.length, i = 0
while (queue.length === len) {
if (queue[i]) {
if (queue[i][1] > clk + ms) {
queue.splice(i, 0, [fn, clk + ms, ms])
}
} else queue.push([fn, clk + ms, ms])
++i
}
check()
}
return delay
} | javascript | function ordered (ondelay) {
var clk = 0
var queue = []
var checking = 0
function check () {
if (checking++) return
setImmediate(function () {
var o = queue.shift()
clk = o[1]
ondelay(function () {
checking = 0
if (queue.length) check()
o[0]()
}, o[2])
})
}
function delay (fn, ms) {
var len = queue.length, i = 0
while (queue.length === len) {
if (queue[i]) {
if (queue[i][1] > clk + ms) {
queue.splice(i, 0, [fn, clk + ms, ms])
}
} else queue.push([fn, clk + ms, ms])
++i
}
check()
}
return delay
} | [
"function",
"ordered",
"(",
"ondelay",
")",
"{",
"var",
"clk",
"=",
"0",
"var",
"queue",
"=",
"[",
"]",
"var",
"checking",
"=",
"0",
"function",
"check",
"(",
")",
"{",
"if",
"(",
"checking",
"++",
")",
"return",
"setImmediate",
"(",
"function",
"(",
")",
"{",
"var",
"o",
"=",
"queue",
".",
"shift",
"(",
")",
"clk",
"=",
"o",
"[",
"1",
"]",
"ondelay",
"(",
"function",
"(",
")",
"{",
"checking",
"=",
"0",
"if",
"(",
"queue",
".",
"length",
")",
"check",
"(",
")",
"o",
"[",
"0",
"]",
"(",
")",
"}",
",",
"o",
"[",
"2",
"]",
")",
"}",
")",
"}",
"function",
"delay",
"(",
"fn",
",",
"ms",
")",
"{",
"var",
"len",
"=",
"queue",
".",
"length",
",",
"i",
"=",
"0",
"while",
"(",
"queue",
".",
"length",
"===",
"len",
")",
"{",
"if",
"(",
"queue",
"[",
"i",
"]",
")",
"{",
"if",
"(",
"queue",
"[",
"i",
"]",
"[",
"1",
"]",
">",
"clk",
"+",
"ms",
")",
"{",
"queue",
".",
"splice",
"(",
"i",
",",
"0",
",",
"[",
"fn",
",",
"clk",
"+",
"ms",
",",
"ms",
"]",
")",
"}",
"}",
"else",
"queue",
".",
"push",
"(",
"[",
"fn",
",",
"clk",
"+",
"ms",
",",
"ms",
"]",
")",
"++",
"i",
"}",
"check",
"(",
")",
"}",
"return",
"delay",
"}"
] | one call gets run each turn on setImmediate until none are left. | [
"one",
"call",
"gets",
"run",
"each",
"turn",
"on",
"setImmediate",
"until",
"none",
"are",
"left",
"."
] | ee3f3e66dd962da060bc8ce2ecc35a6afea469d3 | https://github.com/soldair/node-mocktimers/blob/ee3f3e66dd962da060bc8ce2ecc35a6afea469d3/index.js#L71-L104 |
54,513 | nopnop/docflux | lib/markdown.js | markdown | function markdown(options) {
options = _.extend({
depth: 1,
indent: true
}, options || {})
var isFirst = true;
return through2.obj(function(doc, encoding, done) {
var out = [];
if(isFirst) { isFirst = false } else { out.push('\n\n') }
var depth = options.depth;
if(options.indent && !doc.isClass && !doc.isFunction && !doc.isExport) {
depth++;
}
out.push(repeat('#',depth) + ' ' + doc.signature + '')
out.push('> ' + doc.summary)
if(doc.body) {
out.push('\n' + doc.body)
}
// Parameters
if(~doc.flags.indexOf('param')) {
out.push('')
out.push('**Parameters:**\n')
var isFirstParam = true;
doc.tags.forEach(function(tag) {
if(tag.type != 'param') return;
if(isFirstParam) { isFirstParam = false } else { out.push('') }
var description = '\n' + tag.description.trim().split('\n').map(function(line) {
return line.trim() == '' ? '' : ' ' + line
}).join('\n')
var types = tag.types ? ' {' + tag.types.map(function(type) { return '`' + type + '`' }).join('|') + '}' : '';
out.push(sprintf(' - **%s**%s%s', tag.token, types, description))
})
}
var isFirstTag = true;
doc.tags.forEach(function(tag) {
if(~['param', 'memberOf'].indexOf(tag.type)) return;
out.push('')
var types = tag.types ? ' {' + tag.types.map(function(type) { return '`' + type + '`' }).join('|') + '}' : '';
var description = '\n' + tag.description.trim()
out.push(sprintf('**%s**%s%s', tag.type, types, description))
})
done(null, out.join('\n'))
})
} | javascript | function markdown(options) {
options = _.extend({
depth: 1,
indent: true
}, options || {})
var isFirst = true;
return through2.obj(function(doc, encoding, done) {
var out = [];
if(isFirst) { isFirst = false } else { out.push('\n\n') }
var depth = options.depth;
if(options.indent && !doc.isClass && !doc.isFunction && !doc.isExport) {
depth++;
}
out.push(repeat('#',depth) + ' ' + doc.signature + '')
out.push('> ' + doc.summary)
if(doc.body) {
out.push('\n' + doc.body)
}
// Parameters
if(~doc.flags.indexOf('param')) {
out.push('')
out.push('**Parameters:**\n')
var isFirstParam = true;
doc.tags.forEach(function(tag) {
if(tag.type != 'param') return;
if(isFirstParam) { isFirstParam = false } else { out.push('') }
var description = '\n' + tag.description.trim().split('\n').map(function(line) {
return line.trim() == '' ? '' : ' ' + line
}).join('\n')
var types = tag.types ? ' {' + tag.types.map(function(type) { return '`' + type + '`' }).join('|') + '}' : '';
out.push(sprintf(' - **%s**%s%s', tag.token, types, description))
})
}
var isFirstTag = true;
doc.tags.forEach(function(tag) {
if(~['param', 'memberOf'].indexOf(tag.type)) return;
out.push('')
var types = tag.types ? ' {' + tag.types.map(function(type) { return '`' + type + '`' }).join('|') + '}' : '';
var description = '\n' + tag.description.trim()
out.push(sprintf('**%s**%s%s', tag.type, types, description))
})
done(null, out.join('\n'))
})
} | [
"function",
"markdown",
"(",
"options",
")",
"{",
"options",
"=",
"_",
".",
"extend",
"(",
"{",
"depth",
":",
"1",
",",
"indent",
":",
"true",
"}",
",",
"options",
"||",
"{",
"}",
")",
"var",
"isFirst",
"=",
"true",
";",
"return",
"through2",
".",
"obj",
"(",
"function",
"(",
"doc",
",",
"encoding",
",",
"done",
")",
"{",
"var",
"out",
"=",
"[",
"]",
";",
"if",
"(",
"isFirst",
")",
"{",
"isFirst",
"=",
"false",
"}",
"else",
"{",
"out",
".",
"push",
"(",
"'\\n\\n'",
")",
"}",
"var",
"depth",
"=",
"options",
".",
"depth",
";",
"if",
"(",
"options",
".",
"indent",
"&&",
"!",
"doc",
".",
"isClass",
"&&",
"!",
"doc",
".",
"isFunction",
"&&",
"!",
"doc",
".",
"isExport",
")",
"{",
"depth",
"++",
";",
"}",
"out",
".",
"push",
"(",
"repeat",
"(",
"'#'",
",",
"depth",
")",
"+",
"' '",
"+",
"doc",
".",
"signature",
"+",
"''",
")",
"out",
".",
"push",
"(",
"'> '",
"+",
"doc",
".",
"summary",
")",
"if",
"(",
"doc",
".",
"body",
")",
"{",
"out",
".",
"push",
"(",
"'\\n'",
"+",
"doc",
".",
"body",
")",
"}",
"// Parameters",
"if",
"(",
"~",
"doc",
".",
"flags",
".",
"indexOf",
"(",
"'param'",
")",
")",
"{",
"out",
".",
"push",
"(",
"''",
")",
"out",
".",
"push",
"(",
"'**Parameters:**\\n'",
")",
"var",
"isFirstParam",
"=",
"true",
";",
"doc",
".",
"tags",
".",
"forEach",
"(",
"function",
"(",
"tag",
")",
"{",
"if",
"(",
"tag",
".",
"type",
"!=",
"'param'",
")",
"return",
";",
"if",
"(",
"isFirstParam",
")",
"{",
"isFirstParam",
"=",
"false",
"}",
"else",
"{",
"out",
".",
"push",
"(",
"''",
")",
"}",
"var",
"description",
"=",
"'\\n'",
"+",
"tag",
".",
"description",
".",
"trim",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
".",
"map",
"(",
"function",
"(",
"line",
")",
"{",
"return",
"line",
".",
"trim",
"(",
")",
"==",
"''",
"?",
"''",
":",
"' '",
"+",
"line",
"}",
")",
".",
"join",
"(",
"'\\n'",
")",
"var",
"types",
"=",
"tag",
".",
"types",
"?",
"' {'",
"+",
"tag",
".",
"types",
".",
"map",
"(",
"function",
"(",
"type",
")",
"{",
"return",
"'`'",
"+",
"type",
"+",
"'`'",
"}",
")",
".",
"join",
"(",
"'|'",
")",
"+",
"'}'",
":",
"''",
";",
"out",
".",
"push",
"(",
"sprintf",
"(",
"' - **%s**%s%s'",
",",
"tag",
".",
"token",
",",
"types",
",",
"description",
")",
")",
"}",
")",
"}",
"var",
"isFirstTag",
"=",
"true",
";",
"doc",
".",
"tags",
".",
"forEach",
"(",
"function",
"(",
"tag",
")",
"{",
"if",
"(",
"~",
"[",
"'param'",
",",
"'memberOf'",
"]",
".",
"indexOf",
"(",
"tag",
".",
"type",
")",
")",
"return",
";",
"out",
".",
"push",
"(",
"''",
")",
"var",
"types",
"=",
"tag",
".",
"types",
"?",
"' {'",
"+",
"tag",
".",
"types",
".",
"map",
"(",
"function",
"(",
"type",
")",
"{",
"return",
"'`'",
"+",
"type",
"+",
"'`'",
"}",
")",
".",
"join",
"(",
"'|'",
")",
"+",
"'}'",
":",
"''",
";",
"var",
"description",
"=",
"'\\n'",
"+",
"tag",
".",
"description",
".",
"trim",
"(",
")",
"out",
".",
"push",
"(",
"sprintf",
"(",
"'**%s**%s%s'",
",",
"tag",
".",
"type",
",",
"types",
",",
"description",
")",
")",
"}",
")",
"done",
"(",
"null",
",",
"out",
".",
"join",
"(",
"'\\n'",
")",
")",
"}",
")",
"}"
] | Transform a docflux stream to a markdown stream
This is more a docflux's usage example than a full featured tool
Example:
```javascript
var docflux = require('docflux');
process.stdin(docflux())
.pipe(docflux.markdown())
.pipe(process.stdout)
```
@param {Object} [options]
Some rendering options
- `depth`: The base header size in term of `#` chars (default: 1)
- `indent`: Use one more header char for methods (default is true)
- Class and function will have `options.depth` repeat of `#`
- If true, other will have `options.depth + 1` repeat of `#`
@returns {Stream} | [
"Transform",
"a",
"docflux",
"stream",
"to",
"a",
"markdown",
"stream"
] | 3929fdac9d1e959946fb48f3e8a269d338841902 | https://github.com/nopnop/docflux/blob/3929fdac9d1e959946fb48f3e8a269d338841902/lib/markdown.js#L34-L86 |
54,514 | melvincarvalho/rdf-shell | lib/post.js | post | function post(argv, callback) {
if (!argv[2]) {
console.error("url is required");
console.error("Usage : post <url> <data>");
process.exit(-1);
}
if (!argv[3]) {
console.error("data is required");
console.error("Usage : post <url> <data>");
process.exit(-1);
}
util.post(argv[2], argv[3], function(err, val) {
if (!err) {
callback(null, argv[2]);
} else {
callback(err);
}
});
} | javascript | function post(argv, callback) {
if (!argv[2]) {
console.error("url is required");
console.error("Usage : post <url> <data>");
process.exit(-1);
}
if (!argv[3]) {
console.error("data is required");
console.error("Usage : post <url> <data>");
process.exit(-1);
}
util.post(argv[2], argv[3], function(err, val) {
if (!err) {
callback(null, argv[2]);
} else {
callback(err);
}
});
} | [
"function",
"post",
"(",
"argv",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"argv",
"[",
"2",
"]",
")",
"{",
"console",
".",
"error",
"(",
"\"url is required\"",
")",
";",
"console",
".",
"error",
"(",
"\"Usage : post <url> <data>\"",
")",
";",
"process",
".",
"exit",
"(",
"-",
"1",
")",
";",
"}",
"if",
"(",
"!",
"argv",
"[",
"3",
"]",
")",
"{",
"console",
".",
"error",
"(",
"\"data is required\"",
")",
";",
"console",
".",
"error",
"(",
"\"Usage : post <url> <data>\"",
")",
";",
"process",
".",
"exit",
"(",
"-",
"1",
")",
";",
"}",
"util",
".",
"post",
"(",
"argv",
"[",
"2",
"]",
",",
"argv",
"[",
"3",
"]",
",",
"function",
"(",
"err",
",",
"val",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"callback",
"(",
"null",
",",
"argv",
"[",
"2",
"]",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}"
] | post gets list of files for a given container
@param {String} argv[2] url
@param {String} argv[3] data
@callback {bin~cb} callback | [
"post",
"gets",
"list",
"of",
"files",
"for",
"a",
"given",
"container"
] | bf2015f6f333855e69a18ce3ec9e917bbddfb425 | https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/lib/post.js#L14-L32 |
54,515 | andrewffff/node-webmon | node-webmon.js | DbWriter | function DbWriter(db,errorLogObject,successLogObject) {
this.db = db;
this.errorLogObject = errorLogObject;
this.successLogObject = successLogObject;
} | javascript | function DbWriter(db,errorLogObject,successLogObject) {
this.db = db;
this.errorLogObject = errorLogObject;
this.successLogObject = successLogObject;
} | [
"function",
"DbWriter",
"(",
"db",
",",
"errorLogObject",
",",
"successLogObject",
")",
"{",
"this",
".",
"db",
"=",
"db",
";",
"this",
".",
"errorLogObject",
"=",
"errorLogObject",
";",
"this",
".",
"successLogObject",
"=",
"successLogObject",
";",
"}"
] | Stuff to log content and errors into the database | [
"Stuff",
"to",
"log",
"content",
"and",
"errors",
"into",
"the",
"database"
] | 3f9a7b7a3a0a1209fe0408d20c6f5f61f48923bc | https://github.com/andrewffff/node-webmon/blob/3f9a7b7a3a0a1209fe0408d20c6f5f61f48923bc/node-webmon.js#L20-L24 |
54,516 | andrewffff/node-webmon | node-webmon.js | handleError | function handleError(note,needsReconnect) {
writer.logError({
src_id: streamConfig.src_id,
ts: Date.now(),
error: note
});
if(needsReconnect) {
setTimeout(function() { doIoStream(streamConfig); }, 1000*streamConfig.error_wait_secs);
}
} | javascript | function handleError(note,needsReconnect) {
writer.logError({
src_id: streamConfig.src_id,
ts: Date.now(),
error: note
});
if(needsReconnect) {
setTimeout(function() { doIoStream(streamConfig); }, 1000*streamConfig.error_wait_secs);
}
} | [
"function",
"handleError",
"(",
"note",
",",
"needsReconnect",
")",
"{",
"writer",
".",
"logError",
"(",
"{",
"src_id",
":",
"streamConfig",
".",
"src_id",
",",
"ts",
":",
"Date",
".",
"now",
"(",
")",
",",
"error",
":",
"note",
"}",
")",
";",
"if",
"(",
"needsReconnect",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"doIoStream",
"(",
"streamConfig",
")",
";",
"}",
",",
"1000",
"*",
"streamConfig",
".",
"error_wait_secs",
")",
";",
"}",
"}"
] | we regard disconnection as an "error" for logging purposes, and a reconnect to be a "new connection". we use the "normal wait" time for the reconnection attempts that socket.io itself performs. when socket.io gives up after a few attempts, we use the "error wait" time before forcing a retry | [
"we",
"regard",
"disconnection",
"as",
"an",
"error",
"for",
"logging",
"purposes",
"and",
"a",
"reconnect",
"to",
"be",
"a",
"new",
"connection",
".",
"we",
"use",
"the",
"normal",
"wait",
"time",
"for",
"the",
"reconnection",
"attempts",
"that",
"socket",
".",
"io",
"itself",
"performs",
".",
"when",
"socket",
".",
"io",
"gives",
"up",
"after",
"a",
"few",
"attempts",
"we",
"use",
"the",
"error",
"wait",
"time",
"before",
"forcing",
"a",
"retry"
] | 3f9a7b7a3a0a1209fe0408d20c6f5f61f48923bc | https://github.com/andrewffff/node-webmon/blob/3f9a7b7a3a0a1209fe0408d20c6f5f61f48923bc/node-webmon.js#L211-L221 |
54,517 | Ma3Route/node-sdk | lib/utils.js | setup | function setup(settings) {
if (!settings) {
return _.cloneDeep(SETTINGS);
}
_.merge(SETTINGS, settings);
return _.cloneDeep(SETTINGS);
} | javascript | function setup(settings) {
if (!settings) {
return _.cloneDeep(SETTINGS);
}
_.merge(SETTINGS, settings);
return _.cloneDeep(SETTINGS);
} | [
"function",
"setup",
"(",
"settings",
")",
"{",
"if",
"(",
"!",
"settings",
")",
"{",
"return",
"_",
".",
"cloneDeep",
"(",
"SETTINGS",
")",
";",
"}",
"_",
".",
"merge",
"(",
"SETTINGS",
",",
"settings",
")",
";",
"return",
"_",
".",
"cloneDeep",
"(",
"SETTINGS",
")",
";",
"}"
] | Set the SDK settings
@public
@param {SETTINGS} settings - new SDK settings
@return {Object} the newly-set SDK settings | [
"Set",
"the",
"SDK",
"settings"
] | a2769d97d77d6f762d23e743bf4c749e2bad0d8a | https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/utils.js#L76-L82 |
54,518 | Ma3Route/node-sdk | lib/utils.js | parseResponse | function parseResponse(response) {
var code = response.statusCode;
var type = code / 100 | 0;
response.type = type;
// basics
switch (type) {
case 1:
response.info = type;
break;
case 2:
response.ok = type;
break;
case 3:
// ???
break;
case 4:
response.clientError = type;
response.error = type;
response.ErrorClass = errors.HttpStatusError;
break;
case 5:
response.serverError = type;
response.error = type;
response.ErrorClass = errors.HttpStatusError;
break;
}
// error classes and sugar
switch (code) {
case 201:
response.created = code;
break;
case 202:
response.accepted = code;
break;
case 204:
response.noContent = code;
break;
case 400:
response.badRequest = code;
break;
case 401:
response.unauthorized = code;
response.ErrorClass = errors.AuthenticationRequiredError;
break;
case 403:
response.forbidden = code;
response.ErrorClass = errors.NotPermittedError;
break;
case 404:
response.notFound = code;
response.ErrorClass = errors.NotFoundError;
break;
case 406:
response.notAcceptable = code;
break;
case 500:
response.internalServerError = code;
break;
}
// using body (and not status code)
if (response.body && response.body.success === false) {
if (!response.error) {
response.error = 4; // assume is client error
response.ErrorClass = errors.HttpStatusError;
}
}
// null bodies
if (_.includes([null, undefined, ""], response.body)) {
if (!response.error) {
response.error = 5; // assume the server fucked up
response.ErrorClass = errors.HttpStatusError;
}
}
return response;
} | javascript | function parseResponse(response) {
var code = response.statusCode;
var type = code / 100 | 0;
response.type = type;
// basics
switch (type) {
case 1:
response.info = type;
break;
case 2:
response.ok = type;
break;
case 3:
// ???
break;
case 4:
response.clientError = type;
response.error = type;
response.ErrorClass = errors.HttpStatusError;
break;
case 5:
response.serverError = type;
response.error = type;
response.ErrorClass = errors.HttpStatusError;
break;
}
// error classes and sugar
switch (code) {
case 201:
response.created = code;
break;
case 202:
response.accepted = code;
break;
case 204:
response.noContent = code;
break;
case 400:
response.badRequest = code;
break;
case 401:
response.unauthorized = code;
response.ErrorClass = errors.AuthenticationRequiredError;
break;
case 403:
response.forbidden = code;
response.ErrorClass = errors.NotPermittedError;
break;
case 404:
response.notFound = code;
response.ErrorClass = errors.NotFoundError;
break;
case 406:
response.notAcceptable = code;
break;
case 500:
response.internalServerError = code;
break;
}
// using body (and not status code)
if (response.body && response.body.success === false) {
if (!response.error) {
response.error = 4; // assume is client error
response.ErrorClass = errors.HttpStatusError;
}
}
// null bodies
if (_.includes([null, undefined, ""], response.body)) {
if (!response.error) {
response.error = 5; // assume the server fucked up
response.ErrorClass = errors.HttpStatusError;
}
}
return response;
} | [
"function",
"parseResponse",
"(",
"response",
")",
"{",
"var",
"code",
"=",
"response",
".",
"statusCode",
";",
"var",
"type",
"=",
"code",
"/",
"100",
"|",
"0",
";",
"response",
".",
"type",
"=",
"type",
";",
"// basics",
"switch",
"(",
"type",
")",
"{",
"case",
"1",
":",
"response",
".",
"info",
"=",
"type",
";",
"break",
";",
"case",
"2",
":",
"response",
".",
"ok",
"=",
"type",
";",
"break",
";",
"case",
"3",
":",
"// ???",
"break",
";",
"case",
"4",
":",
"response",
".",
"clientError",
"=",
"type",
";",
"response",
".",
"error",
"=",
"type",
";",
"response",
".",
"ErrorClass",
"=",
"errors",
".",
"HttpStatusError",
";",
"break",
";",
"case",
"5",
":",
"response",
".",
"serverError",
"=",
"type",
";",
"response",
".",
"error",
"=",
"type",
";",
"response",
".",
"ErrorClass",
"=",
"errors",
".",
"HttpStatusError",
";",
"break",
";",
"}",
"// error classes and sugar",
"switch",
"(",
"code",
")",
"{",
"case",
"201",
":",
"response",
".",
"created",
"=",
"code",
";",
"break",
";",
"case",
"202",
":",
"response",
".",
"accepted",
"=",
"code",
";",
"break",
";",
"case",
"204",
":",
"response",
".",
"noContent",
"=",
"code",
";",
"break",
";",
"case",
"400",
":",
"response",
".",
"badRequest",
"=",
"code",
";",
"break",
";",
"case",
"401",
":",
"response",
".",
"unauthorized",
"=",
"code",
";",
"response",
".",
"ErrorClass",
"=",
"errors",
".",
"AuthenticationRequiredError",
";",
"break",
";",
"case",
"403",
":",
"response",
".",
"forbidden",
"=",
"code",
";",
"response",
".",
"ErrorClass",
"=",
"errors",
".",
"NotPermittedError",
";",
"break",
";",
"case",
"404",
":",
"response",
".",
"notFound",
"=",
"code",
";",
"response",
".",
"ErrorClass",
"=",
"errors",
".",
"NotFoundError",
";",
"break",
";",
"case",
"406",
":",
"response",
".",
"notAcceptable",
"=",
"code",
";",
"break",
";",
"case",
"500",
":",
"response",
".",
"internalServerError",
"=",
"code",
";",
"break",
";",
"}",
"// using body (and not status code)",
"if",
"(",
"response",
".",
"body",
"&&",
"response",
".",
"body",
".",
"success",
"===",
"false",
")",
"{",
"if",
"(",
"!",
"response",
".",
"error",
")",
"{",
"response",
".",
"error",
"=",
"4",
";",
"// assume is client error",
"response",
".",
"ErrorClass",
"=",
"errors",
".",
"HttpStatusError",
";",
"}",
"}",
"// null bodies",
"if",
"(",
"_",
".",
"includes",
"(",
"[",
"null",
",",
"undefined",
",",
"\"\"",
"]",
",",
"response",
".",
"body",
")",
")",
"{",
"if",
"(",
"!",
"response",
".",
"error",
")",
"{",
"response",
".",
"error",
"=",
"5",
";",
"// assume the server fucked up",
"response",
".",
"ErrorClass",
"=",
"errors",
".",
"HttpStatusError",
";",
"}",
"}",
"return",
"response",
";",
"}"
] | Add properties to response
@private
@see {@link http://visionmedia.github.io/superagent/#response-properties}
@param {Object} response - as from the `request` module
@return {Object} the originally passed but modified reponse | [
"Add",
"properties",
"to",
"response"
] | a2769d97d77d6f762d23e743bf4c749e2bad0d8a | https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/utils.js#L239-L318 |
54,519 | Ma3Route/node-sdk | lib/utils.js | passResponse | function passResponse(callback, options) {
options = options || {};
return function handleResponse(error, response, body) {
if (error) {
return callback(new errors.io.IOError(error.mesage, error));
}
response = parseResponse(response);
body = body || { };
if (response.error) {
var message = response.body ? response.body.message : "received an empty body";
var err = new response.ErrorClass(response.statusCode, message);
if (options.post || options.put) return callback(err, body, response);
return callback(err, body.data, body.meta, response);
}
if (options.post || options.put) return callback(null, body, response);
return callback(null, body.data, body.meta, response);
};
} | javascript | function passResponse(callback, options) {
options = options || {};
return function handleResponse(error, response, body) {
if (error) {
return callback(new errors.io.IOError(error.mesage, error));
}
response = parseResponse(response);
body = body || { };
if (response.error) {
var message = response.body ? response.body.message : "received an empty body";
var err = new response.ErrorClass(response.statusCode, message);
if (options.post || options.put) return callback(err, body, response);
return callback(err, body.data, body.meta, response);
}
if (options.post || options.put) return callback(null, body, response);
return callback(null, body.data, body.meta, response);
};
} | [
"function",
"passResponse",
"(",
"callback",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"return",
"function",
"handleResponse",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"callback",
"(",
"new",
"errors",
".",
"io",
".",
"IOError",
"(",
"error",
".",
"mesage",
",",
"error",
")",
")",
";",
"}",
"response",
"=",
"parseResponse",
"(",
"response",
")",
";",
"body",
"=",
"body",
"||",
"{",
"}",
";",
"if",
"(",
"response",
".",
"error",
")",
"{",
"var",
"message",
"=",
"response",
".",
"body",
"?",
"response",
".",
"body",
".",
"message",
":",
"\"received an empty body\"",
";",
"var",
"err",
"=",
"new",
"response",
".",
"ErrorClass",
"(",
"response",
".",
"statusCode",
",",
"message",
")",
";",
"if",
"(",
"options",
".",
"post",
"||",
"options",
".",
"put",
")",
"return",
"callback",
"(",
"err",
",",
"body",
",",
"response",
")",
";",
"return",
"callback",
"(",
"err",
",",
"body",
".",
"data",
",",
"body",
".",
"meta",
",",
"response",
")",
";",
"}",
"if",
"(",
"options",
".",
"post",
"||",
"options",
".",
"put",
")",
"return",
"callback",
"(",
"null",
",",
"body",
",",
"response",
")",
";",
"return",
"callback",
"(",
"null",
",",
"body",
".",
"data",
",",
"body",
".",
"meta",
",",
"response",
")",
";",
"}",
";",
"}"
] | Parse response then pass to callback
@public
@param {Function} callback - user's callback
@param {Object} [options]
@param {Boolean} [options.post] - callback is for a POST request
@param {Boolean} [options.put] - callback is for a PUT request
@return {Function} function to handle responses from `request` calls | [
"Parse",
"response",
"then",
"pass",
"to",
"callback"
] | a2769d97d77d6f762d23e743bf4c749e2bad0d8a | https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/utils.js#L332-L349 |
54,520 | Ma3Route/node-sdk | lib/utils.js | allowOptionalParams | function allowOptionalParams(params, callback) {
if (!callback) {
callback = params;
params = { };
}
return {
params: params,
callback: callback,
};
} | javascript | function allowOptionalParams(params, callback) {
if (!callback) {
callback = params;
params = { };
}
return {
params: params,
callback: callback,
};
} | [
"function",
"allowOptionalParams",
"(",
"params",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"callback",
")",
"{",
"callback",
"=",
"params",
";",
"params",
"=",
"{",
"}",
";",
"}",
"return",
"{",
"params",
":",
"params",
",",
"callback",
":",
"callback",
",",
"}",
";",
"}"
] | Allow 'params' to be optional, thus user can pass 'callback' in its place.
@public
@param {*} params - user's params
@param {Function} [callback] - user's callback
@return {Object} args
@return {Function} args.callback
@return {Function} args.params | [
"Allow",
"params",
"to",
"be",
"optional",
"thus",
"user",
"can",
"pass",
"callback",
"in",
"its",
"place",
"."
] | a2769d97d77d6f762d23e743bf4c749e2bad0d8a | https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/utils.js#L395-L404 |
54,521 | Ma3Route/node-sdk | lib/utils.js | getOptions | function getOptions(sources, keys, dest) {
var options = dest || { };
// allow source be an array
if (!_.isArray(sources)) {
sources = [ sources ];
}
// using the keys for lookup
keys.forEach(function(key) {
// from each source
sources.forEach(function(source) {
if (source && source[key]) {
options[key] = source[key];
}
});
});
return options;
} | javascript | function getOptions(sources, keys, dest) {
var options = dest || { };
// allow source be an array
if (!_.isArray(sources)) {
sources = [ sources ];
}
// using the keys for lookup
keys.forEach(function(key) {
// from each source
sources.forEach(function(source) {
if (source && source[key]) {
options[key] = source[key];
}
});
});
return options;
} | [
"function",
"getOptions",
"(",
"sources",
",",
"keys",
",",
"dest",
")",
"{",
"var",
"options",
"=",
"dest",
"||",
"{",
"}",
";",
"// allow source be an array",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"sources",
")",
")",
"{",
"sources",
"=",
"[",
"sources",
"]",
";",
"}",
"// using the keys for lookup",
"keys",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"// from each source",
"sources",
".",
"forEach",
"(",
"function",
"(",
"source",
")",
"{",
"if",
"(",
"source",
"&&",
"source",
"[",
"key",
"]",
")",
"{",
"options",
"[",
"key",
"]",
"=",
"source",
"[",
"key",
"]",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"return",
"options",
";",
"}"
] | Return an object with key-value pairs, using keys, from an object
@param {Object|Object[]} sources - object(s) to look for the properties
@param {Array} keys - an array of keys of the properties to look up
@param {Object} [dest] - destination object
@return {Object} options | [
"Return",
"an",
"object",
"with",
"key",
"-",
"value",
"pairs",
"using",
"keys",
"from",
"an",
"object"
] | a2769d97d77d6f762d23e743bf4c749e2bad0d8a | https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/utils.js#L415-L434 |
54,522 | Ma3Route/node-sdk | lib/utils.js | removeOptions | function removeOptions(args, keys) {
if (!_.isArray(keys)) {
keys = [ keys ];
}
for (var index = 0; index < args.length; index++) {
var arg = args[index];
for (var key in arg) {
if (_.includes(keys, key)) {
delete arg[key];
}
}
}
} | javascript | function removeOptions(args, keys) {
if (!_.isArray(keys)) {
keys = [ keys ];
}
for (var index = 0; index < args.length; index++) {
var arg = args[index];
for (var key in arg) {
if (_.includes(keys, key)) {
delete arg[key];
}
}
}
} | [
"function",
"removeOptions",
"(",
"args",
",",
"keys",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"keys",
")",
")",
"{",
"keys",
"=",
"[",
"keys",
"]",
";",
"}",
"for",
"(",
"var",
"index",
"=",
"0",
";",
"index",
"<",
"args",
".",
"length",
";",
"index",
"++",
")",
"{",
"var",
"arg",
"=",
"args",
"[",
"index",
"]",
";",
"for",
"(",
"var",
"key",
"in",
"arg",
")",
"{",
"if",
"(",
"_",
".",
"includes",
"(",
"keys",
",",
"key",
")",
")",
"{",
"delete",
"arg",
"[",
"key",
"]",
";",
"}",
"}",
"}",
"}"
] | Delete keys from objects
@param {Object[]} args
@param {String|String[]} keys | [
"Delete",
"keys",
"from",
"objects"
] | a2769d97d77d6f762d23e743bf4c749e2bad0d8a | https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/utils.js#L455-L467 |
54,523 | Ma3Route/node-sdk | lib/utils.js | pickParams | function pickParams(params, keys) {
params = _.cloneDeep(params);
// decamelize all options
for (var key in params) {
var value = params[key];
delete params[key];
// TODO: handle this inconsistency consistently in the library :(
// 'base64String': introduced by 'image.upload()'
if (["base64String"].indexOf(key) === -1) {
key = decamelize(key, "_");
}
params[key] = value;
}
if (SETTINGS.enforce_params_filter) {
return _.pick(params, keys);
}
return params;
} | javascript | function pickParams(params, keys) {
params = _.cloneDeep(params);
// decamelize all options
for (var key in params) {
var value = params[key];
delete params[key];
// TODO: handle this inconsistency consistently in the library :(
// 'base64String': introduced by 'image.upload()'
if (["base64String"].indexOf(key) === -1) {
key = decamelize(key, "_");
}
params[key] = value;
}
if (SETTINGS.enforce_params_filter) {
return _.pick(params, keys);
}
return params;
} | [
"function",
"pickParams",
"(",
"params",
",",
"keys",
")",
"{",
"params",
"=",
"_",
".",
"cloneDeep",
"(",
"params",
")",
";",
"// decamelize all options",
"for",
"(",
"var",
"key",
"in",
"params",
")",
"{",
"var",
"value",
"=",
"params",
"[",
"key",
"]",
";",
"delete",
"params",
"[",
"key",
"]",
";",
"// TODO: handle this inconsistency consistently in the library :(",
"// 'base64String': introduced by 'image.upload()'",
"if",
"(",
"[",
"\"base64String\"",
"]",
".",
"indexOf",
"(",
"key",
")",
"===",
"-",
"1",
")",
"{",
"key",
"=",
"decamelize",
"(",
"key",
",",
"\"_\"",
")",
";",
"}",
"params",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"if",
"(",
"SETTINGS",
".",
"enforce_params_filter",
")",
"{",
"return",
"_",
".",
"pick",
"(",
"params",
",",
"keys",
")",
";",
"}",
"return",
"params",
";",
"}"
] | Pick out parameters
@param {Object} params
@return {Object} cleaner params | [
"Pick",
"out",
"parameters"
] | a2769d97d77d6f762d23e743bf4c749e2bad0d8a | https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/utils.js#L520-L537 |
54,524 | Ma3Route/node-sdk | lib/utils.js | collectPages | function collectPages(func, callback) {
var items = [];
var lastReadId = 0;
function __collect() {
return func(lastReadId, function(error, page) {
if (error) {
return callback(error);
}
if (!page.length) {
return callback(null, items);
}
items = items.concat(page);
lastReadId = page[page.length - 1].id;
return __collect();
});
}
return __collect();
} | javascript | function collectPages(func, callback) {
var items = [];
var lastReadId = 0;
function __collect() {
return func(lastReadId, function(error, page) {
if (error) {
return callback(error);
}
if (!page.length) {
return callback(null, items);
}
items = items.concat(page);
lastReadId = page[page.length - 1].id;
return __collect();
});
}
return __collect();
} | [
"function",
"collectPages",
"(",
"func",
",",
"callback",
")",
"{",
"var",
"items",
"=",
"[",
"]",
";",
"var",
"lastReadId",
"=",
"0",
";",
"function",
"__collect",
"(",
")",
"{",
"return",
"func",
"(",
"lastReadId",
",",
"function",
"(",
"error",
",",
"page",
")",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"callback",
"(",
"error",
")",
";",
"}",
"if",
"(",
"!",
"page",
".",
"length",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"items",
")",
";",
"}",
"items",
"=",
"items",
".",
"concat",
"(",
"page",
")",
";",
"lastReadId",
"=",
"page",
"[",
"page",
".",
"length",
"-",
"1",
"]",
".",
"id",
";",
"return",
"__collect",
"(",
")",
";",
"}",
")",
";",
"}",
"return",
"__collect",
"(",
")",
";",
"}"
] | Helper function for collecting all pages of items.
@param {Function} func(lastReadId, next) Function invoked to fetch requests
@param {Object} callback(error, items) Function invoked once all pages have been fetched | [
"Helper",
"function",
"for",
"collecting",
"all",
"pages",
"of",
"items",
"."
] | a2769d97d77d6f762d23e743bf4c749e2bad0d8a | https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/utils.js#L546-L563 |
54,525 | IonicaBizau/node-levdist | lib/index.js | LevDist | function LevDist (s, t) {
var d = []
, n = s.length
, m = t.length
, i
, j
, s_i
, t_j
, cost
, mi
, b
, c
;
if (n == 0) return m;
if (m == 0) return n;
// Step 1
for (i = n; i >= 0; --i) { d[i] = []; }
// Step 2
for (i = n; i >= 0; --i) { d[i][0] = i; }
for (j = m; j >= 0; --j) { d[0][j] = j; }
// Step 3
for (i = 1; i <= n; ++i) {
s_i = s.charAt(i - 1);
// Step 4
for (j = 1; j <= m; ++j) {
// Check the jagged ld total so far
if (i == j && d[i][j] > 4) { return n; }
t_j = t.charAt(j - 1);
// Step 5
cost = (s_i == t_j) ? 0 : 1;
//Calculate the minimum
mi = d[i - 1][j] + 1;
b = d[i][j - 1] + 1;
c = d[i - 1][j - 1] + cost;
if (b < mi) { mi = b; }
if (c < mi) { mi = c; }
// Step 6
d[i][j] = mi;
//Damerau transposition
if (i > 1 && j > 1 && s_i == t.charAt(j - 2) && s.charAt(i - 2) == t_j) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
}
}
}
// Step 7
return d[n][m];
} | javascript | function LevDist (s, t) {
var d = []
, n = s.length
, m = t.length
, i
, j
, s_i
, t_j
, cost
, mi
, b
, c
;
if (n == 0) return m;
if (m == 0) return n;
// Step 1
for (i = n; i >= 0; --i) { d[i] = []; }
// Step 2
for (i = n; i >= 0; --i) { d[i][0] = i; }
for (j = m; j >= 0; --j) { d[0][j] = j; }
// Step 3
for (i = 1; i <= n; ++i) {
s_i = s.charAt(i - 1);
// Step 4
for (j = 1; j <= m; ++j) {
// Check the jagged ld total so far
if (i == j && d[i][j] > 4) { return n; }
t_j = t.charAt(j - 1);
// Step 5
cost = (s_i == t_j) ? 0 : 1;
//Calculate the minimum
mi = d[i - 1][j] + 1;
b = d[i][j - 1] + 1;
c = d[i - 1][j - 1] + cost;
if (b < mi) { mi = b; }
if (c < mi) { mi = c; }
// Step 6
d[i][j] = mi;
//Damerau transposition
if (i > 1 && j > 1 && s_i == t.charAt(j - 2) && s.charAt(i - 2) == t_j) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
}
}
}
// Step 7
return d[n][m];
} | [
"function",
"LevDist",
"(",
"s",
",",
"t",
")",
"{",
"var",
"d",
"=",
"[",
"]",
",",
"n",
"=",
"s",
".",
"length",
",",
"m",
"=",
"t",
".",
"length",
",",
"i",
",",
"j",
",",
"s_i",
",",
"t_j",
",",
"cost",
",",
"mi",
",",
"b",
",",
"c",
";",
"if",
"(",
"n",
"==",
"0",
")",
"return",
"m",
";",
"if",
"(",
"m",
"==",
"0",
")",
"return",
"n",
";",
"// Step 1",
"for",
"(",
"i",
"=",
"n",
";",
"i",
">=",
"0",
";",
"--",
"i",
")",
"{",
"d",
"[",
"i",
"]",
"=",
"[",
"]",
";",
"}",
"// Step 2",
"for",
"(",
"i",
"=",
"n",
";",
"i",
">=",
"0",
";",
"--",
"i",
")",
"{",
"d",
"[",
"i",
"]",
"[",
"0",
"]",
"=",
"i",
";",
"}",
"for",
"(",
"j",
"=",
"m",
";",
"j",
">=",
"0",
";",
"--",
"j",
")",
"{",
"d",
"[",
"0",
"]",
"[",
"j",
"]",
"=",
"j",
";",
"}",
"// Step 3",
"for",
"(",
"i",
"=",
"1",
";",
"i",
"<=",
"n",
";",
"++",
"i",
")",
"{",
"s_i",
"=",
"s",
".",
"charAt",
"(",
"i",
"-",
"1",
")",
";",
"// Step 4",
"for",
"(",
"j",
"=",
"1",
";",
"j",
"<=",
"m",
";",
"++",
"j",
")",
"{",
"// Check the jagged ld total so far",
"if",
"(",
"i",
"==",
"j",
"&&",
"d",
"[",
"i",
"]",
"[",
"j",
"]",
">",
"4",
")",
"{",
"return",
"n",
";",
"}",
"t_j",
"=",
"t",
".",
"charAt",
"(",
"j",
"-",
"1",
")",
";",
"// Step 5",
"cost",
"=",
"(",
"s_i",
"==",
"t_j",
")",
"?",
"0",
":",
"1",
";",
"//Calculate the minimum",
"mi",
"=",
"d",
"[",
"i",
"-",
"1",
"]",
"[",
"j",
"]",
"+",
"1",
";",
"b",
"=",
"d",
"[",
"i",
"]",
"[",
"j",
"-",
"1",
"]",
"+",
"1",
";",
"c",
"=",
"d",
"[",
"i",
"-",
"1",
"]",
"[",
"j",
"-",
"1",
"]",
"+",
"cost",
";",
"if",
"(",
"b",
"<",
"mi",
")",
"{",
"mi",
"=",
"b",
";",
"}",
"if",
"(",
"c",
"<",
"mi",
")",
"{",
"mi",
"=",
"c",
";",
"}",
"// Step 6",
"d",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"mi",
";",
"//Damerau transposition",
"if",
"(",
"i",
">",
"1",
"&&",
"j",
">",
"1",
"&&",
"s_i",
"==",
"t",
".",
"charAt",
"(",
"j",
"-",
"2",
")",
"&&",
"s",
".",
"charAt",
"(",
"i",
"-",
"2",
")",
"==",
"t_j",
")",
"{",
"d",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"Math",
".",
"min",
"(",
"d",
"[",
"i",
"]",
"[",
"j",
"]",
",",
"d",
"[",
"i",
"-",
"2",
"]",
"[",
"j",
"-",
"2",
"]",
"+",
"cost",
")",
";",
"}",
"}",
"}",
"// Step 7",
"return",
"d",
"[",
"n",
"]",
"[",
"m",
"]",
";",
"}"
] | LevDist
Calculates the Levenshtein distance.
@name LevDist
@function
@param {String} s The first string.
@param {String} t The second string.
@return {Number} The Levenshtein distance value. | [
"LevDist",
"Calculates",
"the",
"Levenshtein",
"distance",
"."
] | 9a869f98504cf02bcd37c2900e6b71d2245d3a76 | https://github.com/IonicaBizau/node-levdist/blob/9a869f98504cf02bcd37c2900e6b71d2245d3a76/lib/index.js#L11-L70 |
54,526 | craiglonsdale/repohelper | lib/githubAuthentication.js | readTokenFile | function readTokenFile(tokenFile) {
return new Promise((resolve, reject) => {
fs.readFile(tokenFile, 'utf8', (err, token) => {
if (err) {
reject(err);
}
resolve(token.slice(0, 40));
});
});
} | javascript | function readTokenFile(tokenFile) {
return new Promise((resolve, reject) => {
fs.readFile(tokenFile, 'utf8', (err, token) => {
if (err) {
reject(err);
}
resolve(token.slice(0, 40));
});
});
} | [
"function",
"readTokenFile",
"(",
"tokenFile",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"readFile",
"(",
"tokenFile",
",",
"'utf8'",
",",
"(",
"err",
",",
"token",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
"resolve",
"(",
"token",
".",
"slice",
"(",
"0",
",",
"40",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Read the token string from a file
@param {String} tokenFile The name of a file to read
@return {Promise} Resolves to the 40-char token | [
"Read",
"the",
"token",
"string",
"from",
"a",
"file"
] | 9685a71e0d2cfc78df76280b9b1a8e66d0001587 | https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/githubAuthentication.js#L34-L43 |
54,527 | craiglonsdale/repohelper | lib/githubAuthentication.js | createGithubCredentials | function createGithubCredentials(token) {
return new Promise((resolve, reject) => {
if (token) {
resolve({ type: 'oauth', token: token });
}
else {
reject('Missing token');
}
});
} | javascript | function createGithubCredentials(token) {
return new Promise((resolve, reject) => {
if (token) {
resolve({ type: 'oauth', token: token });
}
else {
reject('Missing token');
}
});
} | [
"function",
"createGithubCredentials",
"(",
"token",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"if",
"(",
"token",
")",
"{",
"resolve",
"(",
"{",
"type",
":",
"'oauth'",
",",
"token",
":",
"token",
"}",
")",
";",
"}",
"else",
"{",
"reject",
"(",
"'Missing token'",
")",
";",
"}",
"}",
")",
";",
"}"
] | Takes a token and returns an object used for authenticating with the Github API.
@param {String} token 40-char token string
@return {Promise} Resolves to an Object containing the token | [
"Takes",
"a",
"token",
"and",
"returns",
"an",
"object",
"used",
"for",
"authenticating",
"with",
"the",
"Github",
"API",
"."
] | 9685a71e0d2cfc78df76280b9b1a8e66d0001587 | https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/githubAuthentication.js#L50-L59 |
54,528 | craiglonsdale/repohelper | lib/githubAuthentication.js | getUserCredentials | function getUserCredentials() {
return new Promise((resolve) => {
print(clc.bold('Sign in to authorize this app to find open pull-requests'), true);
gitUser.email((err, email) => {
prompt.message = '';
prompt.delimiter = '';
prompt.start();
prompt.get({
properties: {
username: {
description: 'Github username',
default: email,
message: 'Name must be only letters, spaces, or dashes',
required: true
},
password: {
description: 'Github password',
hidden: true
}
}
}, (err, result) => {
resolve(result);
});
});
});
} | javascript | function getUserCredentials() {
return new Promise((resolve) => {
print(clc.bold('Sign in to authorize this app to find open pull-requests'), true);
gitUser.email((err, email) => {
prompt.message = '';
prompt.delimiter = '';
prompt.start();
prompt.get({
properties: {
username: {
description: 'Github username',
default: email,
message: 'Name must be only letters, spaces, or dashes',
required: true
},
password: {
description: 'Github password',
hidden: true
}
}
}, (err, result) => {
resolve(result);
});
});
});
} | [
"function",
"getUserCredentials",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
")",
"=>",
"{",
"print",
"(",
"clc",
".",
"bold",
"(",
"'Sign in to authorize this app to find open pull-requests'",
")",
",",
"true",
")",
";",
"gitUser",
".",
"email",
"(",
"(",
"err",
",",
"email",
")",
"=>",
"{",
"prompt",
".",
"message",
"=",
"''",
";",
"prompt",
".",
"delimiter",
"=",
"''",
";",
"prompt",
".",
"start",
"(",
")",
";",
"prompt",
".",
"get",
"(",
"{",
"properties",
":",
"{",
"username",
":",
"{",
"description",
":",
"'Github username'",
",",
"default",
":",
"email",
",",
"message",
":",
"'Name must be only letters, spaces, or dashes'",
",",
"required",
":",
"true",
"}",
",",
"password",
":",
"{",
"description",
":",
"'Github password'",
",",
"hidden",
":",
"true",
"}",
"}",
"}",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"resolve",
"(",
"result",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Prompts the user to enter their Github login details.
@return {Promise} Resolves to an object containin a username and password | [
"Prompts",
"the",
"user",
"to",
"enter",
"their",
"Github",
"login",
"details",
"."
] | 9685a71e0d2cfc78df76280b9b1a8e66d0001587 | https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/githubAuthentication.js#L65-L90 |
54,529 | craiglonsdale/repohelper | lib/githubAuthentication.js | authorizeApp | function authorizeApp(user, tokenName, scope) {
return new Promise((resolve, reject) => {
request.post('https://api.github.com/authorizations', {
auth: {
user: user.username,
pass: user.password,
sendImmediately: true
},
headers: {
'content-type': 'application/x-www-form-urlencoded',
'User-Agent': tokenName
},
body: JSON.stringify({
scopes: scope,
note: tokenName
})
}, (err, response, body) => {
if (err) {
reject(err);
}
const returnBody = JSON.parse(body);
if (returnBody.token) {
resolve(returnBody.token);
}
else if (returnBody.errors) {
console.log(returnBody.errors);
reject(returnBody.errors);
}
});
});
} | javascript | function authorizeApp(user, tokenName, scope) {
return new Promise((resolve, reject) => {
request.post('https://api.github.com/authorizations', {
auth: {
user: user.username,
pass: user.password,
sendImmediately: true
},
headers: {
'content-type': 'application/x-www-form-urlencoded',
'User-Agent': tokenName
},
body: JSON.stringify({
scopes: scope,
note: tokenName
})
}, (err, response, body) => {
if (err) {
reject(err);
}
const returnBody = JSON.parse(body);
if (returnBody.token) {
resolve(returnBody.token);
}
else if (returnBody.errors) {
console.log(returnBody.errors);
reject(returnBody.errors);
}
});
});
} | [
"function",
"authorizeApp",
"(",
"user",
",",
"tokenName",
",",
"scope",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"request",
".",
"post",
"(",
"'https://api.github.com/authorizations'",
",",
"{",
"auth",
":",
"{",
"user",
":",
"user",
".",
"username",
",",
"pass",
":",
"user",
".",
"password",
",",
"sendImmediately",
":",
"true",
"}",
",",
"headers",
":",
"{",
"'content-type'",
":",
"'application/x-www-form-urlencoded'",
",",
"'User-Agent'",
":",
"tokenName",
"}",
",",
"body",
":",
"JSON",
".",
"stringify",
"(",
"{",
"scopes",
":",
"scope",
",",
"note",
":",
"tokenName",
"}",
")",
"}",
",",
"(",
"err",
",",
"response",
",",
"body",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
"const",
"returnBody",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"if",
"(",
"returnBody",
".",
"token",
")",
"{",
"resolve",
"(",
"returnBody",
".",
"token",
")",
";",
"}",
"else",
"if",
"(",
"returnBody",
".",
"errors",
")",
"{",
"console",
".",
"log",
"(",
"returnBody",
".",
"errors",
")",
";",
"reject",
"(",
"returnBody",
".",
"errors",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | Attempt to create a new Personal Access Token with the Github API.
@param {Object} user Object containing the username and password
@param {String} tokenName Name of the token to be created_at
@param {Array} scope List of priviledges to allow the token (See
https://developer.github.com/v3/oauth/#scopes)
@return {Promise} Resolves to a 40-char token string | [
"Attempt",
"to",
"create",
"a",
"new",
"Personal",
"Access",
"Token",
"with",
"the",
"Github",
"API",
"."
] | 9685a71e0d2cfc78df76280b9b1a8e66d0001587 | https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/githubAuthentication.js#L100-L130 |
54,530 | craiglonsdale/repohelper | lib/githubAuthentication.js | createTokenFile | function createTokenFile(token, tokenFile) {
return new Promise((resolve, reject) => {
fs.writeFile(tokenFile, token, (err) => {
if (err) {
reject(err);
}
resolve(token);
});
});
} | javascript | function createTokenFile(token, tokenFile) {
return new Promise((resolve, reject) => {
fs.writeFile(tokenFile, token, (err) => {
if (err) {
reject(err);
}
resolve(token);
});
});
} | [
"function",
"createTokenFile",
"(",
"token",
",",
"tokenFile",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"writeFile",
"(",
"tokenFile",
",",
"token",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
"resolve",
"(",
"token",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Write a token to a given file.
@param {String} token The token to save to a file
@param {String} tokenFile Name of the file to create
@return {Promise} Resolves back the token that was passed in | [
"Write",
"a",
"token",
"to",
"a",
"given",
"file",
"."
] | 9685a71e0d2cfc78df76280b9b1a8e66d0001587 | https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/githubAuthentication.js#L138-L147 |
54,531 | kengz/reqscraper | scraper.js | scrape | function scrape(dyn, url, scope, selector) {
return new Promise(function(dresolve, dreject) {
var scraper = dyn ? dx : x;
scraper(url, scope, selector)(function(err, res) {
dresolve(res);
})
})
} | javascript | function scrape(dyn, url, scope, selector) {
return new Promise(function(dresolve, dreject) {
var scraper = dyn ? dx : x;
scraper(url, scope, selector)(function(err, res) {
dresolve(res);
})
})
} | [
"function",
"scrape",
"(",
"dyn",
",",
"url",
",",
"scope",
",",
"selector",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"dresolve",
",",
"dreject",
")",
"{",
"var",
"scraper",
"=",
"dyn",
"?",
"dx",
":",
"x",
";",
"scraper",
"(",
"url",
",",
"scope",
",",
"selector",
")",
"(",
"function",
"(",
"err",
",",
"res",
")",
"{",
"dresolve",
"(",
"res",
")",
";",
"}",
")",
"}",
")",
"}"
] | Scrapes a url with html selectors. If dyn == true, use a dynamic scraper dx. Returns a promise. | [
"Scrapes",
"a",
"url",
"with",
"html",
"selectors",
".",
"If",
"dyn",
"==",
"true",
"use",
"a",
"dynamic",
"scraper",
"dx",
".",
"Returns",
"a",
"promise",
"."
] | 62950eaa4995ba9ae187ab4a803c4dcff0fa667a | https://github.com/kengz/reqscraper/blob/62950eaa4995ba9ae187ab4a803c4dcff0fa667a/scraper.js#L91-L98 |
54,532 | TempoIQ/tempoiq-node-js | lib/models/sensor.js | Sensor | function Sensor(key, params) {
var p = params || {};
// The sensor primary key [String]
this.key = key;
// Human readable name of the sensor [String] EG - "Thermometer 1"
this.name = p.name || "";
// Indexable attributes. Useful for grouping related sensors.
// EG - {unit: "F", model: 'FHZ343'}
this.attributes = p.attributes || {};
} | javascript | function Sensor(key, params) {
var p = params || {};
// The sensor primary key [String]
this.key = key;
// Human readable name of the sensor [String] EG - "Thermometer 1"
this.name = p.name || "";
// Indexable attributes. Useful for grouping related sensors.
// EG - {unit: "F", model: 'FHZ343'}
this.attributes = p.attributes || {};
} | [
"function",
"Sensor",
"(",
"key",
",",
"params",
")",
"{",
"var",
"p",
"=",
"params",
"||",
"{",
"}",
";",
"// The sensor primary key [String]",
"this",
".",
"key",
"=",
"key",
";",
"// Human readable name of the sensor [String] EG - \"Thermometer 1\"",
"this",
".",
"name",
"=",
"p",
".",
"name",
"||",
"\"\"",
";",
"// Indexable attributes. Useful for grouping related sensors.",
"// EG - {unit: \"F\", model: 'FHZ343'}",
"this",
".",
"attributes",
"=",
"p",
".",
"attributes",
"||",
"{",
"}",
";",
"}"
] | The container for a stream of time series DataPoints. | [
"The",
"container",
"for",
"a",
"stream",
"of",
"time",
"series",
"DataPoints",
"."
] | b3ab72f9d7760a54df9ef75093d349b28a29864c | https://github.com/TempoIQ/tempoiq-node-js/blob/b3ab72f9d7760a54df9ef75093d349b28a29864c/lib/models/sensor.js#L4-L15 |
54,533 | mucbuc/flukeJS | fluke.js | splitNext | function splitNext(source, cb, rules) {
var matchPos = source.search( makeRegExp( joinProperties( rules ) ) );
if (matchPos != -1) {
var match = source.substr( 0, matchPos + 1 )
for (property in rules) {
var rule = rules[property]
, re = makeRegExp( rule );
if (source.search(re) == matchPos) {
var token = source.match( re )
, response = {
lhs: source.substr( 0, matchPos ),
rhs: source.substr( matchPos + token[0].length ),
token: token[0]
};
cb( property, response );
return;
}
}
}
cb( 'end', { lhs: source } );
function makeRegExp( rules ) {
return new RegExp( '(' + rules + ')' );
}
function joinProperties(properties) {
var result = [];
for(property in properties) {
result.push( properties[property] );
}
return result.join( '|' );
}
} | javascript | function splitNext(source, cb, rules) {
var matchPos = source.search( makeRegExp( joinProperties( rules ) ) );
if (matchPos != -1) {
var match = source.substr( 0, matchPos + 1 )
for (property in rules) {
var rule = rules[property]
, re = makeRegExp( rule );
if (source.search(re) == matchPos) {
var token = source.match( re )
, response = {
lhs: source.substr( 0, matchPos ),
rhs: source.substr( matchPos + token[0].length ),
token: token[0]
};
cb( property, response );
return;
}
}
}
cb( 'end', { lhs: source } );
function makeRegExp( rules ) {
return new RegExp( '(' + rules + ')' );
}
function joinProperties(properties) {
var result = [];
for(property in properties) {
result.push( properties[property] );
}
return result.join( '|' );
}
} | [
"function",
"splitNext",
"(",
"source",
",",
"cb",
",",
"rules",
")",
"{",
"var",
"matchPos",
"=",
"source",
".",
"search",
"(",
"makeRegExp",
"(",
"joinProperties",
"(",
"rules",
")",
")",
")",
";",
"if",
"(",
"matchPos",
"!=",
"-",
"1",
")",
"{",
"var",
"match",
"=",
"source",
".",
"substr",
"(",
"0",
",",
"matchPos",
"+",
"1",
")",
"for",
"(",
"property",
"in",
"rules",
")",
"{",
"var",
"rule",
"=",
"rules",
"[",
"property",
"]",
",",
"re",
"=",
"makeRegExp",
"(",
"rule",
")",
";",
"if",
"(",
"source",
".",
"search",
"(",
"re",
")",
"==",
"matchPos",
")",
"{",
"var",
"token",
"=",
"source",
".",
"match",
"(",
"re",
")",
",",
"response",
"=",
"{",
"lhs",
":",
"source",
".",
"substr",
"(",
"0",
",",
"matchPos",
")",
",",
"rhs",
":",
"source",
".",
"substr",
"(",
"matchPos",
"+",
"token",
"[",
"0",
"]",
".",
"length",
")",
",",
"token",
":",
"token",
"[",
"0",
"]",
"}",
";",
"cb",
"(",
"property",
",",
"response",
")",
";",
"return",
";",
"}",
"}",
"}",
"cb",
"(",
"'end'",
",",
"{",
"lhs",
":",
"source",
"}",
")",
";",
"function",
"makeRegExp",
"(",
"rules",
")",
"{",
"return",
"new",
"RegExp",
"(",
"'('",
"+",
"rules",
"+",
"')'",
")",
";",
"}",
"function",
"joinProperties",
"(",
"properties",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"property",
"in",
"properties",
")",
"{",
"result",
".",
"push",
"(",
"properties",
"[",
"property",
"]",
")",
";",
"}",
"return",
"result",
".",
"join",
"(",
"'|'",
")",
";",
"}",
"}"
] | process next token in source | [
"process",
"next",
"token",
"in",
"source"
] | 45f4643c3fa5b9e2f3240ee8af214a4e545dd3fb | https://github.com/mucbuc/flukeJS/blob/45f4643c3fa5b9e2f3240ee8af214a4e545dd3fb/fluke.js#L3-L36 |
54,534 | mucbuc/flukeJS | fluke.js | splitAll | function splitAll(source, cb, rules) {
var done = false
, stash = '';
do {
splitNext( source, function(event, response) {
response.stash = stash;
if (event == 'end') done = true;
else {
source = response.rhs;
stash += response.lhs + response.token;
response.consume = function(length) {
stash += source.substr( 0, length );
source = source.substr( length, source.length );
};
response.resetStash = function() {
stash = '';
};
response.break = function() {
done = true;
};
}
cb( event, response );
},
rules );
}
while(!done);
} | javascript | function splitAll(source, cb, rules) {
var done = false
, stash = '';
do {
splitNext( source, function(event, response) {
response.stash = stash;
if (event == 'end') done = true;
else {
source = response.rhs;
stash += response.lhs + response.token;
response.consume = function(length) {
stash += source.substr( 0, length );
source = source.substr( length, source.length );
};
response.resetStash = function() {
stash = '';
};
response.break = function() {
done = true;
};
}
cb( event, response );
},
rules );
}
while(!done);
} | [
"function",
"splitAll",
"(",
"source",
",",
"cb",
",",
"rules",
")",
"{",
"var",
"done",
"=",
"false",
",",
"stash",
"=",
"''",
";",
"do",
"{",
"splitNext",
"(",
"source",
",",
"function",
"(",
"event",
",",
"response",
")",
"{",
"response",
".",
"stash",
"=",
"stash",
";",
"if",
"(",
"event",
"==",
"'end'",
")",
"done",
"=",
"true",
";",
"else",
"{",
"source",
"=",
"response",
".",
"rhs",
";",
"stash",
"+=",
"response",
".",
"lhs",
"+",
"response",
".",
"token",
";",
"response",
".",
"consume",
"=",
"function",
"(",
"length",
")",
"{",
"stash",
"+=",
"source",
".",
"substr",
"(",
"0",
",",
"length",
")",
";",
"source",
"=",
"source",
".",
"substr",
"(",
"length",
",",
"source",
".",
"length",
")",
";",
"}",
";",
"response",
".",
"resetStash",
"=",
"function",
"(",
")",
"{",
"stash",
"=",
"''",
";",
"}",
";",
"response",
".",
"break",
"=",
"function",
"(",
")",
"{",
"done",
"=",
"true",
";",
"}",
";",
"}",
"cb",
"(",
"event",
",",
"response",
")",
";",
"}",
",",
"rules",
")",
";",
"}",
"while",
"(",
"!",
"done",
")",
";",
"}"
] | process all tokens in tokens | [
"process",
"all",
"tokens",
"in",
"tokens"
] | 45f4643c3fa5b9e2f3240ee8af214a4e545dd3fb | https://github.com/mucbuc/flukeJS/blob/45f4643c3fa5b9e2f3240ee8af214a4e545dd3fb/fluke.js#L39-L69 |
54,535 | jbaylina/ethconnector | eth_connector.js | send | function send(method, params, callback) {
if (typeof params === "function") {
callback = params;
params = [];
}
self.web3.currentProvider.sendAsync({
jsonrpc: "2.0",
method,
params: params || [],
id: new Date().getTime(),
}, callback);
} | javascript | function send(method, params, callback) {
if (typeof params === "function") {
callback = params;
params = [];
}
self.web3.currentProvider.sendAsync({
jsonrpc: "2.0",
method,
params: params || [],
id: new Date().getTime(),
}, callback);
} | [
"function",
"send",
"(",
"method",
",",
"params",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"params",
"===",
"\"function\"",
")",
"{",
"callback",
"=",
"params",
";",
"params",
"=",
"[",
"]",
";",
"}",
"self",
".",
"web3",
".",
"currentProvider",
".",
"sendAsync",
"(",
"{",
"jsonrpc",
":",
"\"2.0\"",
",",
"method",
",",
"params",
":",
"params",
"||",
"[",
"]",
",",
"id",
":",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
",",
"}",
",",
"callback",
")",
";",
"}"
] | CALL a low level rpc | [
"CALL",
"a",
"low",
"level",
"rpc"
] | f9b4640ac002eccfbf9f371d9cf6c7bee72c55c2 | https://github.com/jbaylina/ethconnector/blob/f9b4640ac002eccfbf9f371d9cf6c7bee72c55c2/eth_connector.js#L244-L256 |
54,536 | jpitts/rapt-modelrizerly | lib/modelrizerly.js | underscoreToCamel | function underscoreToCamel (str) {
str = str.charAt(0).toUpperCase() + str.slice(1);
return str.replace(/\_(.)/g, function (x, chr) {
return chr.toUpperCase();
})
} | javascript | function underscoreToCamel (str) {
str = str.charAt(0).toUpperCase() + str.slice(1);
return str.replace(/\_(.)/g, function (x, chr) {
return chr.toUpperCase();
})
} | [
"function",
"underscoreToCamel",
"(",
"str",
")",
"{",
"str",
"=",
"str",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"str",
".",
"slice",
"(",
"1",
")",
";",
"return",
"str",
".",
"replace",
"(",
"/",
"\\_(.)",
"/",
"g",
",",
"function",
"(",
"x",
",",
"chr",
")",
"{",
"return",
"chr",
".",
"toUpperCase",
"(",
")",
";",
"}",
")",
"}"
] | convert the underscore convention to camelized | [
"convert",
"the",
"underscore",
"convention",
"to",
"camelized"
] | 4b6b5bd0e7838c05029e7c20d500c9f4f7b0cc92 | https://github.com/jpitts/rapt-modelrizerly/blob/4b6b5bd0e7838c05029e7c20d500c9f4f7b0cc92/lib/modelrizerly.js#L205-L210 |
54,537 | GTDev87/tuber-deploy | lib/index.js | find3rdPartyCaveatParts | function find3rdPartyCaveatParts(macaroonWithCaveat, secretPem) {
var macaroonSerialized = macaroonWithCaveat.macaroon;
var discharge = macaroonWithCaveat.discharge;
var key = new NodeRSA();
key.importKey(secretPem);
var macaroon = MacaroonsBuilder.deserialize(macaroonSerialized);
var getDischargeParts = getMacPartsFn(" = ");
var macObj = macaroonPairsToObj(key.decrypt(discharge).toString('utf8'), getDischargeParts);
var caveatKey = macObj.caveat_key;
var message = macObj.message;
var macaroon = MacaroonsBuilder.deserialize(macaroonSerialized);
var getMacaroonParts = getMacPartsFn(" ");
var stringMacPairs = macStringToPairs(macaroon.inspect(), getMacaroonParts);
var identifierLoc = _.findIndex(stringMacPairs, function (pair) {
return pair[0] === "cid" && pair[1] === "enc = " + discharge;
});
var caveatIdentifier = stringMacPairs[identifierLoc][1];
var caveatLocation = stringMacPairs[identifierLoc + 2][1];//kind of a hack
return {
caveatKey: caveatKey,
macRaw: macaroonSerialized,
thirdParty: {
messageObj: macaroonPairsToObj(macObj.message, getDischargeParts),
identifier: caveatIdentifier,
location: caveatLocation
}
};
} | javascript | function find3rdPartyCaveatParts(macaroonWithCaveat, secretPem) {
var macaroonSerialized = macaroonWithCaveat.macaroon;
var discharge = macaroonWithCaveat.discharge;
var key = new NodeRSA();
key.importKey(secretPem);
var macaroon = MacaroonsBuilder.deserialize(macaroonSerialized);
var getDischargeParts = getMacPartsFn(" = ");
var macObj = macaroonPairsToObj(key.decrypt(discharge).toString('utf8'), getDischargeParts);
var caveatKey = macObj.caveat_key;
var message = macObj.message;
var macaroon = MacaroonsBuilder.deserialize(macaroonSerialized);
var getMacaroonParts = getMacPartsFn(" ");
var stringMacPairs = macStringToPairs(macaroon.inspect(), getMacaroonParts);
var identifierLoc = _.findIndex(stringMacPairs, function (pair) {
return pair[0] === "cid" && pair[1] === "enc = " + discharge;
});
var caveatIdentifier = stringMacPairs[identifierLoc][1];
var caveatLocation = stringMacPairs[identifierLoc + 2][1];//kind of a hack
return {
caveatKey: caveatKey,
macRaw: macaroonSerialized,
thirdParty: {
messageObj: macaroonPairsToObj(macObj.message, getDischargeParts),
identifier: caveatIdentifier,
location: caveatLocation
}
};
} | [
"function",
"find3rdPartyCaveatParts",
"(",
"macaroonWithCaveat",
",",
"secretPem",
")",
"{",
"var",
"macaroonSerialized",
"=",
"macaroonWithCaveat",
".",
"macaroon",
";",
"var",
"discharge",
"=",
"macaroonWithCaveat",
".",
"discharge",
";",
"var",
"key",
"=",
"new",
"NodeRSA",
"(",
")",
";",
"key",
".",
"importKey",
"(",
"secretPem",
")",
";",
"var",
"macaroon",
"=",
"MacaroonsBuilder",
".",
"deserialize",
"(",
"macaroonSerialized",
")",
";",
"var",
"getDischargeParts",
"=",
"getMacPartsFn",
"(",
"\" = \"",
")",
";",
"var",
"macObj",
"=",
"macaroonPairsToObj",
"(",
"key",
".",
"decrypt",
"(",
"discharge",
")",
".",
"toString",
"(",
"'utf8'",
")",
",",
"getDischargeParts",
")",
";",
"var",
"caveatKey",
"=",
"macObj",
".",
"caveat_key",
";",
"var",
"message",
"=",
"macObj",
".",
"message",
";",
"var",
"macaroon",
"=",
"MacaroonsBuilder",
".",
"deserialize",
"(",
"macaroonSerialized",
")",
";",
"var",
"getMacaroonParts",
"=",
"getMacPartsFn",
"(",
"\" \"",
")",
";",
"var",
"stringMacPairs",
"=",
"macStringToPairs",
"(",
"macaroon",
".",
"inspect",
"(",
")",
",",
"getMacaroonParts",
")",
";",
"var",
"identifierLoc",
"=",
"_",
".",
"findIndex",
"(",
"stringMacPairs",
",",
"function",
"(",
"pair",
")",
"{",
"return",
"pair",
"[",
"0",
"]",
"===",
"\"cid\"",
"&&",
"pair",
"[",
"1",
"]",
"===",
"\"enc = \"",
"+",
"discharge",
";",
"}",
")",
";",
"var",
"caveatIdentifier",
"=",
"stringMacPairs",
"[",
"identifierLoc",
"]",
"[",
"1",
"]",
";",
"var",
"caveatLocation",
"=",
"stringMacPairs",
"[",
"identifierLoc",
"+",
"2",
"]",
"[",
"1",
"]",
";",
"//kind of a hack",
"return",
"{",
"caveatKey",
":",
"caveatKey",
",",
"macRaw",
":",
"macaroonSerialized",
",",
"thirdParty",
":",
"{",
"messageObj",
":",
"macaroonPairsToObj",
"(",
"macObj",
".",
"message",
",",
"getDischargeParts",
")",
",",
"identifier",
":",
"caveatIdentifier",
",",
"location",
":",
"caveatLocation",
"}",
"}",
";",
"}"
] | this needs to be separated into own library separate from 3rd party macaroons. | [
"this",
"needs",
"to",
"be",
"separated",
"into",
"own",
"library",
"separate",
"from",
"3rd",
"party",
"macaroons",
"."
] | 6d519bebf4afb451d8d8f88dfd7453bbbfe1650f | https://github.com/GTDev87/tuber-deploy/blob/6d519bebf4afb451d8d8f88dfd7453bbbfe1650f/lib/index.js#L12-L49 |
54,538 | webinverters/robust-ioc | index.js | function() {
serviceFactory.optionalDeps = {}
_.each(arguments, function(depName) {
serviceFactory.optionalDeps[depName] = true
})
} | javascript | function() {
serviceFactory.optionalDeps = {}
_.each(arguments, function(depName) {
serviceFactory.optionalDeps[depName] = true
})
} | [
"function",
"(",
")",
"{",
"serviceFactory",
".",
"optionalDeps",
"=",
"{",
"}",
"_",
".",
"each",
"(",
"arguments",
",",
"function",
"(",
"depName",
")",
"{",
"serviceFactory",
".",
"optionalDeps",
"[",
"depName",
"]",
"=",
"true",
"}",
")",
"}"
] | use this chain method to mark optional dependencies to suppress warnings. | [
"use",
"this",
"chain",
"method",
"to",
"mark",
"optional",
"dependencies",
"to",
"suppress",
"warnings",
"."
] | 497b92e9f14b63cb01cc41f48716d15a2f39cb1f | https://github.com/webinverters/robust-ioc/blob/497b92e9f14b63cb01cc41f48716d15a2f39cb1f/index.js#L135-L140 |
|
54,539 | cliffano/bagofholding | lib/obj.js | value | function value(dsv, obj) {
dsv = dsv || '';
obj = obj || {};
var props = dsv.split('.'),
_value;
for (var i = 0, ln = props.length; i < ln; i += 1) {
_value = (_value) ? _value[props[i]] : obj[props[i]];
if (_value === undefined) {
break;
}
}
return _value;
} | javascript | function value(dsv, obj) {
dsv = dsv || '';
obj = obj || {};
var props = dsv.split('.'),
_value;
for (var i = 0, ln = props.length; i < ln; i += 1) {
_value = (_value) ? _value[props[i]] : obj[props[i]];
if (_value === undefined) {
break;
}
}
return _value;
} | [
"function",
"value",
"(",
"dsv",
",",
"obj",
")",
"{",
"dsv",
"=",
"dsv",
"||",
"''",
";",
"obj",
"=",
"obj",
"||",
"{",
"}",
";",
"var",
"props",
"=",
"dsv",
".",
"split",
"(",
"'.'",
")",
",",
"_value",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"ln",
"=",
"props",
".",
"length",
";",
"i",
"<",
"ln",
";",
"i",
"+=",
"1",
")",
"{",
"_value",
"=",
"(",
"_value",
")",
"?",
"_value",
"[",
"props",
"[",
"i",
"]",
"]",
":",
"obj",
"[",
"props",
"[",
"i",
"]",
"]",
";",
"if",
"(",
"_value",
"===",
"undefined",
")",
"{",
"break",
";",
"}",
"}",
"return",
"_value",
";",
"}"
] | Retrieve the value of nested properties within an object.
@param {String} dsv: dot-separated nested properties name
@param {Object} obj: the object to find the nested properties from
@return {?} value of the nested properties | [
"Retrieve",
"the",
"value",
"of",
"nested",
"properties",
"within",
"an",
"object",
"."
] | da36a914f85dcc34c375ef08046b2968df2f17c1 | https://github.com/cliffano/bagofholding/blob/da36a914f85dcc34c375ef08046b2968df2f17c1/lib/obj.js#L20-L36 |
54,540 | torworx/ovy | ovy.js | function (value) {
var type = typeof value,
checkLength = false;
if (value && type != 'string') {
// Functions have a length property, so we need to filter them out
if (type == 'function') {
// In Safari, NodeList/HTMLCollection both return "function" when using typeof, so we need
// to explicitly check them here.
// if (Ext.isSafari) {
// checkLength = value instanceof NodeList || value instanceof HTMLCollection;
// }
} else {
checkLength = true;
}
}
return checkLength ? value.length !== undefined : false;
} | javascript | function (value) {
var type = typeof value,
checkLength = false;
if (value && type != 'string') {
// Functions have a length property, so we need to filter them out
if (type == 'function') {
// In Safari, NodeList/HTMLCollection both return "function" when using typeof, so we need
// to explicitly check them here.
// if (Ext.isSafari) {
// checkLength = value instanceof NodeList || value instanceof HTMLCollection;
// }
} else {
checkLength = true;
}
}
return checkLength ? value.length !== undefined : false;
} | [
"function",
"(",
"value",
")",
"{",
"var",
"type",
"=",
"typeof",
"value",
",",
"checkLength",
"=",
"false",
";",
"if",
"(",
"value",
"&&",
"type",
"!=",
"'string'",
")",
"{",
"// Functions have a length property, so we need to filter them out",
"if",
"(",
"type",
"==",
"'function'",
")",
"{",
"// In Safari, NodeList/HTMLCollection both return \"function\" when using typeof, so we need",
"// to explicitly check them here.",
"// if (Ext.isSafari) {",
"// checkLength = value instanceof NodeList || value instanceof HTMLCollection;",
"// }",
"}",
"else",
"{",
"checkLength",
"=",
"true",
";",
"}",
"}",
"return",
"checkLength",
"?",
"value",
".",
"length",
"!==",
"undefined",
":",
"false",
";",
"}"
] | Returns true if the passed value is iterable, false otherwise
@param {Object} value The value to test
@return {Boolean} | [
"Returns",
"true",
"if",
"the",
"passed",
"value",
"is",
"iterable",
"false",
"otherwise"
] | 18e9727305ab37acee1954a3facdd65b3a3526ab | https://github.com/torworx/ovy/blob/18e9727305ab37acee1954a3facdd65b3a3526ab/ovy.js#L84-L100 |
|
54,541 | OctaveWealth/passy | lib/identity.js | _getDateMillis | function _getDateMillis (epoc) {
// Use highres time if available as JS date is +- 15ms
try {
var microtime = require('microtime');
// Time in microsecs, convert to ms
return (Math.round(microtime.now() / 1000) - epoc.getTime()).toString(2);
} catch (err) {}
return ((new Date()) - epoc).toString(2);
} | javascript | function _getDateMillis (epoc) {
// Use highres time if available as JS date is +- 15ms
try {
var microtime = require('microtime');
// Time in microsecs, convert to ms
return (Math.round(microtime.now() / 1000) - epoc.getTime()).toString(2);
} catch (err) {}
return ((new Date()) - epoc).toString(2);
} | [
"function",
"_getDateMillis",
"(",
"epoc",
")",
"{",
"// Use highres time if available as JS date is +- 15ms",
"try",
"{",
"var",
"microtime",
"=",
"require",
"(",
"'microtime'",
")",
";",
"// Time in microsecs, convert to ms",
"return",
"(",
"Math",
".",
"round",
"(",
"microtime",
".",
"now",
"(",
")",
"/",
"1000",
")",
"-",
"epoc",
".",
"getTime",
"(",
")",
")",
".",
"toString",
"(",
"2",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"return",
"(",
"(",
"new",
"Date",
"(",
")",
")",
"-",
"epoc",
")",
".",
"toString",
"(",
"2",
")",
";",
"}"
] | Get Milliseconds since supplied epoc, using
highres timers if available
@private
@param {Date} epoc The epoc to use
@return {string} Milliseconds encoded as bitstring | [
"Get",
"Milliseconds",
"since",
"supplied",
"epoc",
"using",
"highres",
"timers",
"if",
"available"
] | 6e357b018952f73e8570b89eda95393780328fab | https://github.com/OctaveWealth/passy/blob/6e357b018952f73e8570b89eda95393780328fab/lib/identity.js#L62-L71 |
54,542 | OctaveWealth/passy | lib/identity.js | _identity | function _identity (ndate, nrandom, nchecksum, epoc) {
// ms since EPOC (1 Jan 1970)
var since = _getDateMillis(epoc);
// Max of ndate
if (since.length > ndate) {
throw new Error('Date too big');
}
// Pad to ndate
since = bitString.pad(since, ndate);
// Add nrandom Random bits
since += bitString.randomBits(nrandom);
// Add checksum bits
since += bitString.checksum(since, nchecksum);
// Convert to BaseURL
return baseURL.encode(since);
} | javascript | function _identity (ndate, nrandom, nchecksum, epoc) {
// ms since EPOC (1 Jan 1970)
var since = _getDateMillis(epoc);
// Max of ndate
if (since.length > ndate) {
throw new Error('Date too big');
}
// Pad to ndate
since = bitString.pad(since, ndate);
// Add nrandom Random bits
since += bitString.randomBits(nrandom);
// Add checksum bits
since += bitString.checksum(since, nchecksum);
// Convert to BaseURL
return baseURL.encode(since);
} | [
"function",
"_identity",
"(",
"ndate",
",",
"nrandom",
",",
"nchecksum",
",",
"epoc",
")",
"{",
"// ms since EPOC (1 Jan 1970)",
"var",
"since",
"=",
"_getDateMillis",
"(",
"epoc",
")",
";",
"// Max of ndate",
"if",
"(",
"since",
".",
"length",
">",
"ndate",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Date too big'",
")",
";",
"}",
"// Pad to ndate",
"since",
"=",
"bitString",
".",
"pad",
"(",
"since",
",",
"ndate",
")",
";",
"// Add nrandom Random bits",
"since",
"+=",
"bitString",
".",
"randomBits",
"(",
"nrandom",
")",
";",
"// Add checksum bits",
"since",
"+=",
"bitString",
".",
"checksum",
"(",
"since",
",",
"nchecksum",
")",
";",
"// Convert to BaseURL",
"return",
"baseURL",
".",
"encode",
"(",
"since",
")",
";",
"}"
] | Build an identity function
@private
@param {integer} ndate Size of date bits
@param {integer} nrandom Size of random bits
@param {integer} nchecksum Size of checksum bits
@param {Date} epoc Epoc to use
@return {string} BaseURL encoded id | [
"Build",
"an",
"identity",
"function"
] | 6e357b018952f73e8570b89eda95393780328fab | https://github.com/OctaveWealth/passy/blob/6e357b018952f73e8570b89eda95393780328fab/lib/identity.js#L82-L102 |
54,543 | OctaveWealth/passy | lib/identity.js | _isValid | function _isValid (ndate, nrandom, nchecksum, id) {
// Guard
if (!baseURL.isValid(id)) return false;
if (id.length !== (ndate + nrandom + nchecksum) / 6) return false;
// Test
var bits = baseURL.decode(id),
main = bits.slice(0, bits.length - nchecksum),
check = bits.slice(bits.length - nchecksum, bits.length);
return bitString.checksum(main, nchecksum) === check;
} | javascript | function _isValid (ndate, nrandom, nchecksum, id) {
// Guard
if (!baseURL.isValid(id)) return false;
if (id.length !== (ndate + nrandom + nchecksum) / 6) return false;
// Test
var bits = baseURL.decode(id),
main = bits.slice(0, bits.length - nchecksum),
check = bits.slice(bits.length - nchecksum, bits.length);
return bitString.checksum(main, nchecksum) === check;
} | [
"function",
"_isValid",
"(",
"ndate",
",",
"nrandom",
",",
"nchecksum",
",",
"id",
")",
"{",
"// Guard",
"if",
"(",
"!",
"baseURL",
".",
"isValid",
"(",
"id",
")",
")",
"return",
"false",
";",
"if",
"(",
"id",
".",
"length",
"!==",
"(",
"ndate",
"+",
"nrandom",
"+",
"nchecksum",
")",
"/",
"6",
")",
"return",
"false",
";",
"// Test",
"var",
"bits",
"=",
"baseURL",
".",
"decode",
"(",
"id",
")",
",",
"main",
"=",
"bits",
".",
"slice",
"(",
"0",
",",
"bits",
".",
"length",
"-",
"nchecksum",
")",
",",
"check",
"=",
"bits",
".",
"slice",
"(",
"bits",
".",
"length",
"-",
"nchecksum",
",",
"bits",
".",
"length",
")",
";",
"return",
"bitString",
".",
"checksum",
"(",
"main",
",",
"nchecksum",
")",
"===",
"check",
";",
"}"
] | Check if a id is valid
@private
@param {integer} ndate Size of date bits
@param {integer} nrandom Size of random bits
@param {integer} nchecksum Size of checksum bits
@param {string} id BaseURL encoded Id to test
@return {Boolean} [description] | [
"Check",
"if",
"a",
"id",
"is",
"valid"
] | 6e357b018952f73e8570b89eda95393780328fab | https://github.com/OctaveWealth/passy/blob/6e357b018952f73e8570b89eda95393780328fab/lib/identity.js#L113-L124 |
54,544 | OctaveWealth/passy | lib/identity.js | _toDate | function _toDate (ndate, nrandom, nchecksum, epoc, id) {
// Guard
if (!_isValid(ndate, nrandom, nchecksum, id)) throw new Error('identity#toDate: Invalid Id');
// Calculate
var bits = baseURL.decode(id),
dateBits = bits.slice(0, ndate);
return new Date(parseInt(dateBits, 2) + epoc.getTime());
} | javascript | function _toDate (ndate, nrandom, nchecksum, epoc, id) {
// Guard
if (!_isValid(ndate, nrandom, nchecksum, id)) throw new Error('identity#toDate: Invalid Id');
// Calculate
var bits = baseURL.decode(id),
dateBits = bits.slice(0, ndate);
return new Date(parseInt(dateBits, 2) + epoc.getTime());
} | [
"function",
"_toDate",
"(",
"ndate",
",",
"nrandom",
",",
"nchecksum",
",",
"epoc",
",",
"id",
")",
"{",
"// Guard",
"if",
"(",
"!",
"_isValid",
"(",
"ndate",
",",
"nrandom",
",",
"nchecksum",
",",
"id",
")",
")",
"throw",
"new",
"Error",
"(",
"'identity#toDate: Invalid Id'",
")",
";",
"// Calculate",
"var",
"bits",
"=",
"baseURL",
".",
"decode",
"(",
"id",
")",
",",
"dateBits",
"=",
"bits",
".",
"slice",
"(",
"0",
",",
"ndate",
")",
";",
"return",
"new",
"Date",
"(",
"parseInt",
"(",
"dateBits",
",",
"2",
")",
"+",
"epoc",
".",
"getTime",
"(",
")",
")",
";",
"}"
] | Get date from id
@private
@param {integer} ndate Size of date bits
@param {integer} nrandom Size of random bits
@param {integer} nchecksum Size of checksum bits
@param {Date} epoc Epoc to use
@param {string} id BaseURL encoded Id to test
@return {Date} The date of id creation | [
"Get",
"date",
"from",
"id"
] | 6e357b018952f73e8570b89eda95393780328fab | https://github.com/OctaveWealth/passy/blob/6e357b018952f73e8570b89eda95393780328fab/lib/identity.js#L136-L144 |
54,545 | OctaveWealth/passy | lib/identity.js | createIdentity | function createIdentity (ndate, nrandom, nchecksum, epoc) {
var def = function identity () {
return _identity(ndate, nrandom, nchecksum, epoc);
};
def.EPOC = epoc;
def.dateLength = ndate;
def.randomLength = nrandom;
def.checksumLength = nchecksum;
def.size = ndate + nrandom + nchecksum;
def.isValid = function isValid(id) {
return _isValid(ndate, nrandom, nchecksum, id);
};
def.toDate = function toDate(id) {
return _toDate(ndate, nrandom, nchecksum, epoc, id);
};
return def;
} | javascript | function createIdentity (ndate, nrandom, nchecksum, epoc) {
var def = function identity () {
return _identity(ndate, nrandom, nchecksum, epoc);
};
def.EPOC = epoc;
def.dateLength = ndate;
def.randomLength = nrandom;
def.checksumLength = nchecksum;
def.size = ndate + nrandom + nchecksum;
def.isValid = function isValid(id) {
return _isValid(ndate, nrandom, nchecksum, id);
};
def.toDate = function toDate(id) {
return _toDate(ndate, nrandom, nchecksum, epoc, id);
};
return def;
} | [
"function",
"createIdentity",
"(",
"ndate",
",",
"nrandom",
",",
"nchecksum",
",",
"epoc",
")",
"{",
"var",
"def",
"=",
"function",
"identity",
"(",
")",
"{",
"return",
"_identity",
"(",
"ndate",
",",
"nrandom",
",",
"nchecksum",
",",
"epoc",
")",
";",
"}",
";",
"def",
".",
"EPOC",
"=",
"epoc",
";",
"def",
".",
"dateLength",
"=",
"ndate",
";",
"def",
".",
"randomLength",
"=",
"nrandom",
";",
"def",
".",
"checksumLength",
"=",
"nchecksum",
";",
"def",
".",
"size",
"=",
"ndate",
"+",
"nrandom",
"+",
"nchecksum",
";",
"def",
".",
"isValid",
"=",
"function",
"isValid",
"(",
"id",
")",
"{",
"return",
"_isValid",
"(",
"ndate",
",",
"nrandom",
",",
"nchecksum",
",",
"id",
")",
";",
"}",
";",
"def",
".",
"toDate",
"=",
"function",
"toDate",
"(",
"id",
")",
"{",
"return",
"_toDate",
"(",
"ndate",
",",
"nrandom",
",",
"nchecksum",
",",
"epoc",
",",
"id",
")",
";",
"}",
";",
"return",
"def",
";",
"}"
] | Build a identity function by currying
@private
@param {integer} ndate Size of date bits
@param {integer} nrandom Size of random bits
@param {integer} nchecksum Size of checksum bits
@param {Date} epoc Epoc to use
@return {Function} A identity function | [
"Build",
"a",
"identity",
"function",
"by",
"currying"
] | 6e357b018952f73e8570b89eda95393780328fab | https://github.com/OctaveWealth/passy/blob/6e357b018952f73e8570b89eda95393780328fab/lib/identity.js#L155-L174 |
54,546 | nodesource/gather-dependencies | gather-dependencies.js | rpt_cb | function rpt_cb (err, data) {
if (err) return logger.error(err)
if (data.error) return logger.error(data.error)
if (!data.package) {
logger.warn('`data.package` not defined. Initializing placeholder.')
data.package = {}
}
var dependencyReport = {}
if (!data.package || !data.package.name) logger.warn('`data.package.name` missing')
dependencyReport.name = data.package.name
if (!data.package || !data.package.version) logger.warn('`data.package.version` missing')
dependencyReport.version = data.package.version
if (options.meta) {
dependencyReport.meta = {
nodeVersions: process.versions,
date: Date.now()
}
}
buildDependencyReport(dependencyReport, data, options, 0)
// Finally, return gatherDependencies callback
callback(null, dependencyReport)
} | javascript | function rpt_cb (err, data) {
if (err) return logger.error(err)
if (data.error) return logger.error(data.error)
if (!data.package) {
logger.warn('`data.package` not defined. Initializing placeholder.')
data.package = {}
}
var dependencyReport = {}
if (!data.package || !data.package.name) logger.warn('`data.package.name` missing')
dependencyReport.name = data.package.name
if (!data.package || !data.package.version) logger.warn('`data.package.version` missing')
dependencyReport.version = data.package.version
if (options.meta) {
dependencyReport.meta = {
nodeVersions: process.versions,
date: Date.now()
}
}
buildDependencyReport(dependencyReport, data, options, 0)
// Finally, return gatherDependencies callback
callback(null, dependencyReport)
} | [
"function",
"rpt_cb",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"return",
"logger",
".",
"error",
"(",
"err",
")",
"if",
"(",
"data",
".",
"error",
")",
"return",
"logger",
".",
"error",
"(",
"data",
".",
"error",
")",
"if",
"(",
"!",
"data",
".",
"package",
")",
"{",
"logger",
".",
"warn",
"(",
"'`data.package` not defined. Initializing placeholder.'",
")",
"data",
".",
"package",
"=",
"{",
"}",
"}",
"var",
"dependencyReport",
"=",
"{",
"}",
"if",
"(",
"!",
"data",
".",
"package",
"||",
"!",
"data",
".",
"package",
".",
"name",
")",
"logger",
".",
"warn",
"(",
"'`data.package.name` missing'",
")",
"dependencyReport",
".",
"name",
"=",
"data",
".",
"package",
".",
"name",
"if",
"(",
"!",
"data",
".",
"package",
"||",
"!",
"data",
".",
"package",
".",
"version",
")",
"logger",
".",
"warn",
"(",
"'`data.package.version` missing'",
")",
"dependencyReport",
".",
"version",
"=",
"data",
".",
"package",
".",
"version",
"if",
"(",
"options",
".",
"meta",
")",
"{",
"dependencyReport",
".",
"meta",
"=",
"{",
"nodeVersions",
":",
"process",
".",
"versions",
",",
"date",
":",
"Date",
".",
"now",
"(",
")",
"}",
"}",
"buildDependencyReport",
"(",
"dependencyReport",
",",
"data",
",",
"options",
",",
"0",
")",
"// Finally, return gatherDependencies callback",
"callback",
"(",
"null",
",",
"dependencyReport",
")",
"}"
] | read-package-tree callback
@param {error} err read-package-tree error
@param {object} data read-package-tree blob (contains cyclical refrences) | [
"read",
"-",
"package",
"-",
"tree",
"callback"
] | 383e3b867423293501688e26ef462121cc9452d5 | https://github.com/nodesource/gather-dependencies/blob/383e3b867423293501688e26ef462121cc9452d5/gather-dependencies.js#L64-L91 |
54,547 | nodesource/gather-dependencies | gather-dependencies.js | buildDependencyReport | function buildDependencyReport (report, data, options, depth) {
if (!report) report = {}
if (!data) data = {}
if (!options) options = {}
if (!depth) depth = 0
var lookup = {}
var npmDependencyTypes = depth ? depthNpmDependencyTypes : topLevelNpmDependencyTypes
// build list of all dependencies
npmDependencyTypes.forEach(function types (type) {
if (data.package[type] && Object.keys(data.package[type]).length) {
report[type] = data.package[type]
// remap versions as objects instead of a string
Object.keys(report[type]).forEach(function dep (name) {
// build lookup to reference back to build off of
lookup[name] = type
report[type][name] = { requestedVersion: report[type][name] }
})
}
})
data.children.forEach(function childDeps (depData) {
if (!lookup[depData.package.name]) return // not a relevant dependency (probably devDep)
var entry = report[lookup[depData.package.name]][depData.package.name]
entry.version = depData.package.version
entry.from = depData.package._from
entry.realpath = depData.realpath
buildDependencyReport(entry, depData, options, depth + 1)
})
return report
} | javascript | function buildDependencyReport (report, data, options, depth) {
if (!report) report = {}
if (!data) data = {}
if (!options) options = {}
if (!depth) depth = 0
var lookup = {}
var npmDependencyTypes = depth ? depthNpmDependencyTypes : topLevelNpmDependencyTypes
// build list of all dependencies
npmDependencyTypes.forEach(function types (type) {
if (data.package[type] && Object.keys(data.package[type]).length) {
report[type] = data.package[type]
// remap versions as objects instead of a string
Object.keys(report[type]).forEach(function dep (name) {
// build lookup to reference back to build off of
lookup[name] = type
report[type][name] = { requestedVersion: report[type][name] }
})
}
})
data.children.forEach(function childDeps (depData) {
if (!lookup[depData.package.name]) return // not a relevant dependency (probably devDep)
var entry = report[lookup[depData.package.name]][depData.package.name]
entry.version = depData.package.version
entry.from = depData.package._from
entry.realpath = depData.realpath
buildDependencyReport(entry, depData, options, depth + 1)
})
return report
} | [
"function",
"buildDependencyReport",
"(",
"report",
",",
"data",
",",
"options",
",",
"depth",
")",
"{",
"if",
"(",
"!",
"report",
")",
"report",
"=",
"{",
"}",
"if",
"(",
"!",
"data",
")",
"data",
"=",
"{",
"}",
"if",
"(",
"!",
"options",
")",
"options",
"=",
"{",
"}",
"if",
"(",
"!",
"depth",
")",
"depth",
"=",
"0",
"var",
"lookup",
"=",
"{",
"}",
"var",
"npmDependencyTypes",
"=",
"depth",
"?",
"depthNpmDependencyTypes",
":",
"topLevelNpmDependencyTypes",
"// build list of all dependencies",
"npmDependencyTypes",
".",
"forEach",
"(",
"function",
"types",
"(",
"type",
")",
"{",
"if",
"(",
"data",
".",
"package",
"[",
"type",
"]",
"&&",
"Object",
".",
"keys",
"(",
"data",
".",
"package",
"[",
"type",
"]",
")",
".",
"length",
")",
"{",
"report",
"[",
"type",
"]",
"=",
"data",
".",
"package",
"[",
"type",
"]",
"// remap versions as objects instead of a string",
"Object",
".",
"keys",
"(",
"report",
"[",
"type",
"]",
")",
".",
"forEach",
"(",
"function",
"dep",
"(",
"name",
")",
"{",
"// build lookup to reference back to build off of",
"lookup",
"[",
"name",
"]",
"=",
"type",
"report",
"[",
"type",
"]",
"[",
"name",
"]",
"=",
"{",
"requestedVersion",
":",
"report",
"[",
"type",
"]",
"[",
"name",
"]",
"}",
"}",
")",
"}",
"}",
")",
"data",
".",
"children",
".",
"forEach",
"(",
"function",
"childDeps",
"(",
"depData",
")",
"{",
"if",
"(",
"!",
"lookup",
"[",
"depData",
".",
"package",
".",
"name",
"]",
")",
"return",
"// not a relevant dependency (probably devDep)",
"var",
"entry",
"=",
"report",
"[",
"lookup",
"[",
"depData",
".",
"package",
".",
"name",
"]",
"]",
"[",
"depData",
".",
"package",
".",
"name",
"]",
"entry",
".",
"version",
"=",
"depData",
".",
"package",
".",
"version",
"entry",
".",
"from",
"=",
"depData",
".",
"package",
".",
"_from",
"entry",
".",
"realpath",
"=",
"depData",
".",
"realpath",
"buildDependencyReport",
"(",
"entry",
",",
"depData",
",",
"options",
",",
"depth",
"+",
"1",
")",
"}",
")",
"return",
"report",
"}"
] | Build dependency report
@param {object} report report object being operated on
@param {object} data npm dependency tree data
@param {object} options
@param {number} depth Depth to evaluate. 0 is top level only.
@return {object} Completed report object. | [
"Build",
"dependency",
"report"
] | 383e3b867423293501688e26ef462121cc9452d5 | https://github.com/nodesource/gather-dependencies/blob/383e3b867423293501688e26ef462121cc9452d5/gather-dependencies.js#L116-L151 |
54,548 | timshadel/smd | index.js | SmD | function SmD(ms_per_unit, range) {
this.ms_per_unit = ms_per_unit;
this.range = range;
this.range_in_ms = ms_per_unit * range;
} | javascript | function SmD(ms_per_unit, range) {
this.ms_per_unit = ms_per_unit;
this.range = range;
this.range_in_ms = ms_per_unit * range;
} | [
"function",
"SmD",
"(",
"ms_per_unit",
",",
"range",
")",
"{",
"this",
".",
"ms_per_unit",
"=",
"ms_per_unit",
";",
"this",
".",
"range",
"=",
"range",
";",
"this",
".",
"range_in_ms",
"=",
"ms_per_unit",
"*",
"range",
";",
"}"
] | Create a smd
@param {String} name
@return {Type}
@api public | [
"Create",
"a",
"smd"
] | 86de2ffbe1b0e760b3a53a959233bddb8cd4e2c6 | https://github.com/timshadel/smd/blob/86de2ffbe1b0e760b3a53a959233bddb8cd4e2c6/index.js#L47-L51 |
54,549 | jhermsmeier/node-json-web-algorithms | lib/signature.js | function( digest ) {
var signature = ECDSASignature.decode( digest, 'der' )
var length = ( this.bits / 8 | 0 ) + ( this.bits % 8 !== 0 ? 1 : 0 )
var r = Buffer.from( signature.r.toString( 'hex', length ), 'hex' )
var s = Buffer.from( signature.s.toString( 'hex', length ), 'hex' )
return Buffer.concat([ r, s ], r.length + s.length )
} | javascript | function( digest ) {
var signature = ECDSASignature.decode( digest, 'der' )
var length = ( this.bits / 8 | 0 ) + ( this.bits % 8 !== 0 ? 1 : 0 )
var r = Buffer.from( signature.r.toString( 'hex', length ), 'hex' )
var s = Buffer.from( signature.s.toString( 'hex', length ), 'hex' )
return Buffer.concat([ r, s ], r.length + s.length )
} | [
"function",
"(",
"digest",
")",
"{",
"var",
"signature",
"=",
"ECDSASignature",
".",
"decode",
"(",
"digest",
",",
"'der'",
")",
"var",
"length",
"=",
"(",
"this",
".",
"bits",
"/",
"8",
"|",
"0",
")",
"+",
"(",
"this",
".",
"bits",
"%",
"8",
"!==",
"0",
"?",
"1",
":",
"0",
")",
"var",
"r",
"=",
"Buffer",
".",
"from",
"(",
"signature",
".",
"r",
".",
"toString",
"(",
"'hex'",
",",
"length",
")",
",",
"'hex'",
")",
"var",
"s",
"=",
"Buffer",
".",
"from",
"(",
"signature",
".",
"s",
".",
"toString",
"(",
"'hex'",
",",
"length",
")",
",",
"'hex'",
")",
"return",
"Buffer",
".",
"concat",
"(",
"[",
"r",
",",
"s",
"]",
",",
"r",
".",
"length",
"+",
"s",
".",
"length",
")",
"}"
] | Create a ECDSA signature for a given digest
@internal used by `.sign()`
@param {Buffer} digest
@return {Buffer} | [
"Create",
"a",
"ECDSA",
"signature",
"for",
"a",
"given",
"digest"
] | 3a98e12c9c33ea7bcd39f9a6bbcff0ec3f1265c6 | https://github.com/jhermsmeier/node-json-web-algorithms/blob/3a98e12c9c33ea7bcd39f9a6bbcff0ec3f1265c6/lib/signature.js#L70-L80 |
|
54,550 | jhermsmeier/node-json-web-algorithms | lib/signature.js | function( input, key ) {
if( !Buffer.isBuffer( input ) )
throw new TypeError( 'Input must be a buffer' )
if( this.type === 'PLAIN' )
return Buffer.allocUnsafe(0)
if( !Buffer.isBuffer( key ) )
throw new TypeError( 'Key must be a buffer' )
var signature = this.type === 'HS' ?
crypto.createHmac( this.algorithm + this.bits, key ) :
crypto.createSign( this.algorithm + this.bits )
signature.update( input )
var digest = this.type === 'HS' ?
signature.digest() :
signature.sign( key )
if( this.type === 'ES' )
digest = this._signECDSA( digest )
return digest
} | javascript | function( input, key ) {
if( !Buffer.isBuffer( input ) )
throw new TypeError( 'Input must be a buffer' )
if( this.type === 'PLAIN' )
return Buffer.allocUnsafe(0)
if( !Buffer.isBuffer( key ) )
throw new TypeError( 'Key must be a buffer' )
var signature = this.type === 'HS' ?
crypto.createHmac( this.algorithm + this.bits, key ) :
crypto.createSign( this.algorithm + this.bits )
signature.update( input )
var digest = this.type === 'HS' ?
signature.digest() :
signature.sign( key )
if( this.type === 'ES' )
digest = this._signECDSA( digest )
return digest
} | [
"function",
"(",
"input",
",",
"key",
")",
"{",
"if",
"(",
"!",
"Buffer",
".",
"isBuffer",
"(",
"input",
")",
")",
"throw",
"new",
"TypeError",
"(",
"'Input must be a buffer'",
")",
"if",
"(",
"this",
".",
"type",
"===",
"'PLAIN'",
")",
"return",
"Buffer",
".",
"allocUnsafe",
"(",
"0",
")",
"if",
"(",
"!",
"Buffer",
".",
"isBuffer",
"(",
"key",
")",
")",
"throw",
"new",
"TypeError",
"(",
"'Key must be a buffer'",
")",
"var",
"signature",
"=",
"this",
".",
"type",
"===",
"'HS'",
"?",
"crypto",
".",
"createHmac",
"(",
"this",
".",
"algorithm",
"+",
"this",
".",
"bits",
",",
"key",
")",
":",
"crypto",
".",
"createSign",
"(",
"this",
".",
"algorithm",
"+",
"this",
".",
"bits",
")",
"signature",
".",
"update",
"(",
"input",
")",
"var",
"digest",
"=",
"this",
".",
"type",
"===",
"'HS'",
"?",
"signature",
".",
"digest",
"(",
")",
":",
"signature",
".",
"sign",
"(",
"key",
")",
"if",
"(",
"this",
".",
"type",
"===",
"'ES'",
")",
"digest",
"=",
"this",
".",
"_signECDSA",
"(",
"digest",
")",
"return",
"digest",
"}"
] | Sign an input with a given key
@param {Buffer} input
@param {Buffer} key
@return {Buffer} | [
"Sign",
"an",
"input",
"with",
"a",
"given",
"key"
] | 3a98e12c9c33ea7bcd39f9a6bbcff0ec3f1265c6 | https://github.com/jhermsmeier/node-json-web-algorithms/blob/3a98e12c9c33ea7bcd39f9a6bbcff0ec3f1265c6/lib/signature.js#L88-L114 |
|
54,551 | jhermsmeier/node-json-web-algorithms | lib/signature.js | function( signature, input, key ) {
var check = this.sign( input, key )
return signature.toString( 'hex' ) ===
check.toString( 'hex' )
} | javascript | function( signature, input, key ) {
var check = this.sign( input, key )
return signature.toString( 'hex' ) ===
check.toString( 'hex' )
} | [
"function",
"(",
"signature",
",",
"input",
",",
"key",
")",
"{",
"var",
"check",
"=",
"this",
".",
"sign",
"(",
"input",
",",
"key",
")",
"return",
"signature",
".",
"toString",
"(",
"'hex'",
")",
"===",
"check",
".",
"toString",
"(",
"'hex'",
")",
"}"
] | Verify an HMAC signature
@internal used by `.verify()`
@param {Buffer} signature
@param {Buffer} input
@param {Buffer} key
@return {Boolean} | [
"Verify",
"an",
"HMAC",
"signature"
] | 3a98e12c9c33ea7bcd39f9a6bbcff0ec3f1265c6 | https://github.com/jhermsmeier/node-json-web-algorithms/blob/3a98e12c9c33ea7bcd39f9a6bbcff0ec3f1265c6/lib/signature.js#L124-L131 |
|
54,552 | jhermsmeier/node-json-web-algorithms | lib/signature.js | function( signature, input, key ) {
var verifier = crypto.createVerify( this.algorithm + this.bits )
return verifier.update( input )
.verify( key, signature )
} | javascript | function( signature, input, key ) {
var verifier = crypto.createVerify( this.algorithm + this.bits )
return verifier.update( input )
.verify( key, signature )
} | [
"function",
"(",
"signature",
",",
"input",
",",
"key",
")",
"{",
"var",
"verifier",
"=",
"crypto",
".",
"createVerify",
"(",
"this",
".",
"algorithm",
"+",
"this",
".",
"bits",
")",
"return",
"verifier",
".",
"update",
"(",
"input",
")",
".",
"verify",
"(",
"key",
",",
"signature",
")",
"}"
] | Verify an RSA signature
@internal used by `.verify()`
@param {Buffer} signature
@param {Buffer} input
@param {Buffer} key
@return {Boolean} | [
"Verify",
"an",
"RSA",
"signature"
] | 3a98e12c9c33ea7bcd39f9a6bbcff0ec3f1265c6 | https://github.com/jhermsmeier/node-json-web-algorithms/blob/3a98e12c9c33ea7bcd39f9a6bbcff0ec3f1265c6/lib/signature.js#L141-L148 |
|
54,553 | jhermsmeier/node-json-web-algorithms | lib/signature.js | function( signature, input, key ) {
var length = ( this.bits / 8 | 0 ) + ( this.bits % 8 !== 0 ? 1 : 0 )
if( signature.length !== length * 2 )
return false
var sig = ECDSASignature.encode({
r: new BigNum( signature.slice( 0, length ), 10, 'be' ).iabs(),
s: new BigNum( signature.slice( length ), 10, 'be' ).iabs(),
}, 'der' )
return crypto.createVerify( this.algorithm + this.bits )
.update( input )
.verify( key, sig, 'base64' )
} | javascript | function( signature, input, key ) {
var length = ( this.bits / 8 | 0 ) + ( this.bits % 8 !== 0 ? 1 : 0 )
if( signature.length !== length * 2 )
return false
var sig = ECDSASignature.encode({
r: new BigNum( signature.slice( 0, length ), 10, 'be' ).iabs(),
s: new BigNum( signature.slice( length ), 10, 'be' ).iabs(),
}, 'der' )
return crypto.createVerify( this.algorithm + this.bits )
.update( input )
.verify( key, sig, 'base64' )
} | [
"function",
"(",
"signature",
",",
"input",
",",
"key",
")",
"{",
"var",
"length",
"=",
"(",
"this",
".",
"bits",
"/",
"8",
"|",
"0",
")",
"+",
"(",
"this",
".",
"bits",
"%",
"8",
"!==",
"0",
"?",
"1",
":",
"0",
")",
"if",
"(",
"signature",
".",
"length",
"!==",
"length",
"*",
"2",
")",
"return",
"false",
"var",
"sig",
"=",
"ECDSASignature",
".",
"encode",
"(",
"{",
"r",
":",
"new",
"BigNum",
"(",
"signature",
".",
"slice",
"(",
"0",
",",
"length",
")",
",",
"10",
",",
"'be'",
")",
".",
"iabs",
"(",
")",
",",
"s",
":",
"new",
"BigNum",
"(",
"signature",
".",
"slice",
"(",
"length",
")",
",",
"10",
",",
"'be'",
")",
".",
"iabs",
"(",
")",
",",
"}",
",",
"'der'",
")",
"return",
"crypto",
".",
"createVerify",
"(",
"this",
".",
"algorithm",
"+",
"this",
".",
"bits",
")",
".",
"update",
"(",
"input",
")",
".",
"verify",
"(",
"key",
",",
"sig",
",",
"'base64'",
")",
"}"
] | Verify an ECDSA signature
@internal used by `.verify()`
@param {Buffer} signature
@param {Buffer} input
@param {Buffer} key
@return {Boolean} | [
"Verify",
"an",
"ECDSA",
"signature"
] | 3a98e12c9c33ea7bcd39f9a6bbcff0ec3f1265c6 | https://github.com/jhermsmeier/node-json-web-algorithms/blob/3a98e12c9c33ea7bcd39f9a6bbcff0ec3f1265c6/lib/signature.js#L158-L173 |
|
54,554 | jhermsmeier/node-json-web-algorithms | lib/signature.js | function( signature, input, key ) {
if( !Buffer.isBuffer( input ) )
throw new TypeError( 'Input must be a buffer' )
if( !Buffer.isBuffer( signature ) )
throw new TypeError( 'Signature must be a buffer' )
if( this.type === 'PLAIN' )
return signature.length === 0
if( !Buffer.isBuffer( key ) )
throw new TypeError( 'Key must be a buffer' )
switch( this.type ) {
case 'HS': return this._verifyHMAC( signature, input, key )
case 'RS': return this._verifyRSA( signature, input, key )
case 'ES': return this._verifyECDSA( signature, input, key )
default:
throw new Error( 'Unsupported type "' + this.type + '"' )
}
} | javascript | function( signature, input, key ) {
if( !Buffer.isBuffer( input ) )
throw new TypeError( 'Input must be a buffer' )
if( !Buffer.isBuffer( signature ) )
throw new TypeError( 'Signature must be a buffer' )
if( this.type === 'PLAIN' )
return signature.length === 0
if( !Buffer.isBuffer( key ) )
throw new TypeError( 'Key must be a buffer' )
switch( this.type ) {
case 'HS': return this._verifyHMAC( signature, input, key )
case 'RS': return this._verifyRSA( signature, input, key )
case 'ES': return this._verifyECDSA( signature, input, key )
default:
throw new Error( 'Unsupported type "' + this.type + '"' )
}
} | [
"function",
"(",
"signature",
",",
"input",
",",
"key",
")",
"{",
"if",
"(",
"!",
"Buffer",
".",
"isBuffer",
"(",
"input",
")",
")",
"throw",
"new",
"TypeError",
"(",
"'Input must be a buffer'",
")",
"if",
"(",
"!",
"Buffer",
".",
"isBuffer",
"(",
"signature",
")",
")",
"throw",
"new",
"TypeError",
"(",
"'Signature must be a buffer'",
")",
"if",
"(",
"this",
".",
"type",
"===",
"'PLAIN'",
")",
"return",
"signature",
".",
"length",
"===",
"0",
"if",
"(",
"!",
"Buffer",
".",
"isBuffer",
"(",
"key",
")",
")",
"throw",
"new",
"TypeError",
"(",
"'Key must be a buffer'",
")",
"switch",
"(",
"this",
".",
"type",
")",
"{",
"case",
"'HS'",
":",
"return",
"this",
".",
"_verifyHMAC",
"(",
"signature",
",",
"input",
",",
"key",
")",
"case",
"'RS'",
":",
"return",
"this",
".",
"_verifyRSA",
"(",
"signature",
",",
"input",
",",
"key",
")",
"case",
"'ES'",
":",
"return",
"this",
".",
"_verifyECDSA",
"(",
"signature",
",",
"input",
",",
"key",
")",
"default",
":",
"throw",
"new",
"Error",
"(",
"'Unsupported type \"'",
"+",
"this",
".",
"type",
"+",
"'\"'",
")",
"}",
"}"
] | Verify a signature against an input & key
@param {Buffer} signature
@param {Buffer} input
@param {Buffer} key
@return {Boolean} | [
"Verify",
"a",
"signature",
"against",
"an",
"input",
"&",
"key"
] | 3a98e12c9c33ea7bcd39f9a6bbcff0ec3f1265c6 | https://github.com/jhermsmeier/node-json-web-algorithms/blob/3a98e12c9c33ea7bcd39f9a6bbcff0ec3f1265c6/lib/signature.js#L182-L204 |
|
54,555 | pinyin/outline | vendor/transformation-matrix/isAffineMatrix.js | isAffineMatrix | function isAffineMatrix(object) {
return isObject(object) && object.hasOwnProperty('a') && isNumeric(object.a) && object.hasOwnProperty('b') && isNumeric(object.b) && object.hasOwnProperty('c') && isNumeric(object.c) && object.hasOwnProperty('d') && isNumeric(object.d) && object.hasOwnProperty('e') && isNumeric(object.e) && object.hasOwnProperty('f') && isNumeric(object.f);
} | javascript | function isAffineMatrix(object) {
return isObject(object) && object.hasOwnProperty('a') && isNumeric(object.a) && object.hasOwnProperty('b') && isNumeric(object.b) && object.hasOwnProperty('c') && isNumeric(object.c) && object.hasOwnProperty('d') && isNumeric(object.d) && object.hasOwnProperty('e') && isNumeric(object.e) && object.hasOwnProperty('f') && isNumeric(object.f);
} | [
"function",
"isAffineMatrix",
"(",
"object",
")",
"{",
"return",
"isObject",
"(",
"object",
")",
"&&",
"object",
".",
"hasOwnProperty",
"(",
"'a'",
")",
"&&",
"isNumeric",
"(",
"object",
".",
"a",
")",
"&&",
"object",
".",
"hasOwnProperty",
"(",
"'b'",
")",
"&&",
"isNumeric",
"(",
"object",
".",
"b",
")",
"&&",
"object",
".",
"hasOwnProperty",
"(",
"'c'",
")",
"&&",
"isNumeric",
"(",
"object",
".",
"c",
")",
"&&",
"object",
".",
"hasOwnProperty",
"(",
"'d'",
")",
"&&",
"isNumeric",
"(",
"object",
".",
"d",
")",
"&&",
"object",
".",
"hasOwnProperty",
"(",
"'e'",
")",
"&&",
"isNumeric",
"(",
"object",
".",
"e",
")",
"&&",
"object",
".",
"hasOwnProperty",
"(",
"'f'",
")",
"&&",
"isNumeric",
"(",
"object",
".",
"f",
")",
";",
"}"
] | Check if the object contain an affine matrix
@param object
@return {boolean} | [
"Check",
"if",
"the",
"object",
"contain",
"an",
"affine",
"matrix"
] | e49f05d2f8ab384f5b1d71b2b10875cd48d41051 | https://github.com/pinyin/outline/blob/e49f05d2f8ab384f5b1d71b2b10875cd48d41051/vendor/transformation-matrix/isAffineMatrix.js#L26-L28 |
54,556 | jgable/broccoli-es6-import-validate | lib/BroccoliES6ModuleFile.js | function (filePath) {
var name = ES6ModuleFile.prototype.getModuleName.apply(this, arguments);
if (_.isFunction(this.opts.moduleName)) {
name = this.opts.moduleName(name, filePath);
}
return name;
} | javascript | function (filePath) {
var name = ES6ModuleFile.prototype.getModuleName.apply(this, arguments);
if (_.isFunction(this.opts.moduleName)) {
name = this.opts.moduleName(name, filePath);
}
return name;
} | [
"function",
"(",
"filePath",
")",
"{",
"var",
"name",
"=",
"ES6ModuleFile",
".",
"prototype",
".",
"getModuleName",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"if",
"(",
"_",
".",
"isFunction",
"(",
"this",
".",
"opts",
".",
"moduleName",
")",
")",
"{",
"name",
"=",
"this",
".",
"opts",
".",
"moduleName",
"(",
"name",
",",
"filePath",
")",
";",
"}",
"return",
"name",
";",
"}"
] | Broken out to let the moduleName options override | [
"Broken",
"out",
"to",
"let",
"the",
"moduleName",
"options",
"override"
] | ffbc9e66698f0a8399d63d7123a03c30808bf902 | https://github.com/jgable/broccoli-es6-import-validate/blob/ffbc9e66698f0a8399d63d7123a03c30808bf902/lib/BroccoliES6ModuleFile.js#L14-L22 |
|
54,557 | travism/solid-logger-js | lib/adapters/loggly.js | init | function init(config){
var logger = new LogglyLogger(config);
logger.validateConfig();
logger.config = config;
logger.client = loggly.createClient({
token: config.token,
subdomain: config.application,
auth: config.auth,
// TOOD: pushing more tags onto this array, or not using them, should be configurable
tags: [
config.domain,
config.machine
]
// Loggly docs say it uses json stringify if json:true
// JSON stringify does not handle Errors or circulare references well
// Logger.createEntry handles them well
});
return logger;
} | javascript | function init(config){
var logger = new LogglyLogger(config);
logger.validateConfig();
logger.config = config;
logger.client = loggly.createClient({
token: config.token,
subdomain: config.application,
auth: config.auth,
// TOOD: pushing more tags onto this array, or not using them, should be configurable
tags: [
config.domain,
config.machine
]
// Loggly docs say it uses json stringify if json:true
// JSON stringify does not handle Errors or circulare references well
// Logger.createEntry handles them well
});
return logger;
} | [
"function",
"init",
"(",
"config",
")",
"{",
"var",
"logger",
"=",
"new",
"LogglyLogger",
"(",
"config",
")",
";",
"logger",
".",
"validateConfig",
"(",
")",
";",
"logger",
".",
"config",
"=",
"config",
";",
"logger",
".",
"client",
"=",
"loggly",
".",
"createClient",
"(",
"{",
"token",
":",
"config",
".",
"token",
",",
"subdomain",
":",
"config",
".",
"application",
",",
"auth",
":",
"config",
".",
"auth",
",",
"// TOOD: pushing more tags onto this array, or not using them, should be configurable",
"tags",
":",
"[",
"config",
".",
"domain",
",",
"config",
".",
"machine",
"]",
"// Loggly docs say it uses json stringify if json:true",
"// JSON stringify does not handle Errors or circulare references well",
"// Logger.createEntry handles them well",
"}",
")",
";",
"return",
"logger",
";",
"}"
] | The init function should be called at the beginning of the object life cycle. This method will be responsible
for doing all of the setup for the adapter.
@param config Object that will contain the path to write the log file and the type of adapter. | [
"The",
"init",
"function",
"should",
"be",
"called",
"at",
"the",
"beginning",
"of",
"the",
"object",
"life",
"cycle",
".",
"This",
"method",
"will",
"be",
"responsible",
"for",
"doing",
"all",
"of",
"the",
"setup",
"for",
"the",
"adapter",
"."
] | e5287dcfc680fcfa3eb449dd29bc8c92106184a9 | https://github.com/travism/solid-logger-js/blob/e5287dcfc680fcfa3eb449dd29bc8c92106184a9/lib/adapters/loggly.js#L33-L54 |
54,558 | travism/solid-logger-js | lib/adapters/loggly.js | writeLog | function writeLog(type, category){
return function(messages) {
var funcs = [];
_.each(messages, function(message){
funcs.push(this.client.logAsync(message, [type, category]));
}.bind(this));
return BB.all(funcs);
};
} | javascript | function writeLog(type, category){
return function(messages) {
var funcs = [];
_.each(messages, function(message){
funcs.push(this.client.logAsync(message, [type, category]));
}.bind(this));
return BB.all(funcs);
};
} | [
"function",
"writeLog",
"(",
"type",
",",
"category",
")",
"{",
"return",
"function",
"(",
"messages",
")",
"{",
"var",
"funcs",
"=",
"[",
"]",
";",
"_",
".",
"each",
"(",
"messages",
",",
"function",
"(",
"message",
")",
"{",
"funcs",
".",
"push",
"(",
"this",
".",
"client",
".",
"logAsync",
"(",
"message",
",",
"[",
"type",
",",
"category",
"]",
")",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"return",
"BB",
".",
"all",
"(",
"funcs",
")",
";",
"}",
";",
"}"
] | Internal method to append our log entry to loggly.
@param type Type of entry (debug, info, error, warn, trace)
@param category User defined label for the entry
@returns {function} | [
"Internal",
"method",
"to",
"append",
"our",
"log",
"entry",
"to",
"loggly",
"."
] | e5287dcfc680fcfa3eb449dd29bc8c92106184a9 | https://github.com/travism/solid-logger-js/blob/e5287dcfc680fcfa3eb449dd29bc8c92106184a9/lib/adapters/loggly.js#L86-L97 |
54,559 | trevorparscal/node-palo | lib/resources/FileResource.js | FileResource | function FileResource( pkg, config ) {
var key,
resource = this,
dir = pkg.getDirectory(),
cfg = { files: [] };
// Normalize configuration
if ( typeof config === 'string' ) {
cfg.files.push( config );
} else if ( Array.isArray( config ) ) {
cfg.files = cfg.files.concat( config );
} else {
for ( key in config ) {
if ( key === 'file' || key === 'files' ) {
cfg.files = cfg.files.concat(
Array.isArray( config[key] ) ? config[key] : [ config[key] ]
);
} else {
cfg[key] = config[key];
}
}
}
cfg.files = cfg.files.map( function ( file ) {
return path.join( dir, file );
} );
// Parent constructor
FileResource.super.call( this, pkg, cfg );
// Properties
this.versionGenerator = function *() {
return yield ay( cfg.files )
.reduce( resource.reduceFileToMaximumModifiedTime, 1 );
};
this.contentGenerator = function *( options ) {
return yield ay( cfg.files )
.map( function *( file ) {
return yield resource.mapFileToContent( file, options );
} )
.reduce( resource.reduceContentToConcatenatedContent, '' );
};
} | javascript | function FileResource( pkg, config ) {
var key,
resource = this,
dir = pkg.getDirectory(),
cfg = { files: [] };
// Normalize configuration
if ( typeof config === 'string' ) {
cfg.files.push( config );
} else if ( Array.isArray( config ) ) {
cfg.files = cfg.files.concat( config );
} else {
for ( key in config ) {
if ( key === 'file' || key === 'files' ) {
cfg.files = cfg.files.concat(
Array.isArray( config[key] ) ? config[key] : [ config[key] ]
);
} else {
cfg[key] = config[key];
}
}
}
cfg.files = cfg.files.map( function ( file ) {
return path.join( dir, file );
} );
// Parent constructor
FileResource.super.call( this, pkg, cfg );
// Properties
this.versionGenerator = function *() {
return yield ay( cfg.files )
.reduce( resource.reduceFileToMaximumModifiedTime, 1 );
};
this.contentGenerator = function *( options ) {
return yield ay( cfg.files )
.map( function *( file ) {
return yield resource.mapFileToContent( file, options );
} )
.reduce( resource.reduceContentToConcatenatedContent, '' );
};
} | [
"function",
"FileResource",
"(",
"pkg",
",",
"config",
")",
"{",
"var",
"key",
",",
"resource",
"=",
"this",
",",
"dir",
"=",
"pkg",
".",
"getDirectory",
"(",
")",
",",
"cfg",
"=",
"{",
"files",
":",
"[",
"]",
"}",
";",
"// Normalize configuration",
"if",
"(",
"typeof",
"config",
"===",
"'string'",
")",
"{",
"cfg",
".",
"files",
".",
"push",
"(",
"config",
")",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"config",
")",
")",
"{",
"cfg",
".",
"files",
"=",
"cfg",
".",
"files",
".",
"concat",
"(",
"config",
")",
";",
"}",
"else",
"{",
"for",
"(",
"key",
"in",
"config",
")",
"{",
"if",
"(",
"key",
"===",
"'file'",
"||",
"key",
"===",
"'files'",
")",
"{",
"cfg",
".",
"files",
"=",
"cfg",
".",
"files",
".",
"concat",
"(",
"Array",
".",
"isArray",
"(",
"config",
"[",
"key",
"]",
")",
"?",
"config",
"[",
"key",
"]",
":",
"[",
"config",
"[",
"key",
"]",
"]",
")",
";",
"}",
"else",
"{",
"cfg",
"[",
"key",
"]",
"=",
"config",
"[",
"key",
"]",
";",
"}",
"}",
"}",
"cfg",
".",
"files",
"=",
"cfg",
".",
"files",
".",
"map",
"(",
"function",
"(",
"file",
")",
"{",
"return",
"path",
".",
"join",
"(",
"dir",
",",
"file",
")",
";",
"}",
")",
";",
"// Parent constructor",
"FileResource",
".",
"super",
".",
"call",
"(",
"this",
",",
"pkg",
",",
"cfg",
")",
";",
"// Properties",
"this",
".",
"versionGenerator",
"=",
"function",
"*",
"(",
")",
"{",
"return",
"yield",
"ay",
"(",
"cfg",
".",
"files",
")",
".",
"reduce",
"(",
"resource",
".",
"reduceFileToMaximumModifiedTime",
",",
"1",
")",
";",
"}",
";",
"this",
".",
"contentGenerator",
"=",
"function",
"*",
"(",
"options",
")",
"{",
"return",
"yield",
"ay",
"(",
"cfg",
".",
"files",
")",
".",
"map",
"(",
"function",
"*",
"(",
"file",
")",
"{",
"return",
"yield",
"resource",
".",
"mapFileToContent",
"(",
"file",
",",
"options",
")",
";",
"}",
")",
".",
"reduce",
"(",
"resource",
".",
"reduceContentToConcatenatedContent",
",",
"''",
")",
";",
"}",
";",
"}"
] | File resource.
Resources can be configured with either a string, an array of strings, or an object with a `file`
or `files` properties, each a string or array of strings. The normalized configuration will
never have a `file` property and always have a `files` property which is an array of file paths.
If the configuration is an object, all properties other than `file` and `files` will be passed
through without modification.
@class
@extends {Resource}
@constructor
@param {Package} pkg Package this resource is part of
@param {Object|string[]|string} config Resource configuration or one or more resource file paths
@param {string|string[]} [config.file] One or more resource file paths
@param {string|string[]} [config.files] One or more resource file paths | [
"File",
"resource",
"."
] | 425efdcf027c71296c732765afdf5cacae6a1a3e | https://github.com/trevorparscal/node-palo/blob/425efdcf027c71296c732765afdf5cacae6a1a3e/lib/resources/FileResource.js#L25-L66 |
54,560 | robojones/smart-promisify | index.js | promisify | function promisify(original, self = null) {
if (typeof original !== 'function') {
throw new TypeError('original must be a function')
}
/**
* Wrapped original function.
* @typedef {function} wrapper
* @param {...*} args - Arguments to apply to the original function.
* @returns {Promise.<*>} - Promise that gets resolved when the original function calls the callback.
*/
function wrapper(...args) {
let thisArg = self
if (this !== global) {
// called with bound this object
thisArg = this
}
if (typeof args[args.length - 1] === 'function') {
// called with callback
return original.call(thisArg, ...args)
}
// promisified
return new Promise((resolve, reject) => {
/**
* Callback for the original function.
* @typedef {function} cb
* @param {?Error} error - Error if one occured.
* @param {*} result - Result of the original function.
*/
function cb(error, result) {
if (error) {
return reject(error)
}
resolve(result)
}
args.push(cb)
original.call(thisArg, ...args)
})
}
return wrapper
} | javascript | function promisify(original, self = null) {
if (typeof original !== 'function') {
throw new TypeError('original must be a function')
}
/**
* Wrapped original function.
* @typedef {function} wrapper
* @param {...*} args - Arguments to apply to the original function.
* @returns {Promise.<*>} - Promise that gets resolved when the original function calls the callback.
*/
function wrapper(...args) {
let thisArg = self
if (this !== global) {
// called with bound this object
thisArg = this
}
if (typeof args[args.length - 1] === 'function') {
// called with callback
return original.call(thisArg, ...args)
}
// promisified
return new Promise((resolve, reject) => {
/**
* Callback for the original function.
* @typedef {function} cb
* @param {?Error} error - Error if one occured.
* @param {*} result - Result of the original function.
*/
function cb(error, result) {
if (error) {
return reject(error)
}
resolve(result)
}
args.push(cb)
original.call(thisArg, ...args)
})
}
return wrapper
} | [
"function",
"promisify",
"(",
"original",
",",
"self",
"=",
"null",
")",
"{",
"if",
"(",
"typeof",
"original",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'original must be a function'",
")",
"}",
"/**\n * Wrapped original function.\n * @typedef {function} wrapper\n * @param {...*} args - Arguments to apply to the original function.\n * @returns {Promise.<*>} - Promise that gets resolved when the original function calls the callback.\n */",
"function",
"wrapper",
"(",
"...",
"args",
")",
"{",
"let",
"thisArg",
"=",
"self",
"if",
"(",
"this",
"!==",
"global",
")",
"{",
"// called with bound this object",
"thisArg",
"=",
"this",
"}",
"if",
"(",
"typeof",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
"===",
"'function'",
")",
"{",
"// called with callback",
"return",
"original",
".",
"call",
"(",
"thisArg",
",",
"...",
"args",
")",
"}",
"// promisified",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"/**\n * Callback for the original function.\n * @typedef {function} cb\n * @param {?Error} error - Error if one occured.\n * @param {*} result - Result of the original function.\n */",
"function",
"cb",
"(",
"error",
",",
"result",
")",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"reject",
"(",
"error",
")",
"}",
"resolve",
"(",
"result",
")",
"}",
"args",
".",
"push",
"(",
"cb",
")",
"original",
".",
"call",
"(",
"thisArg",
",",
"...",
"args",
")",
"}",
")",
"}",
"return",
"wrapper",
"}"
] | Promisify the original function.
@param {original} original - Function that gets promisified.
@param {?Object} self - Object that gets applied as this-object when the original function is called.
@returns {wrapper} | [
"Promisify",
"the",
"original",
"function",
"."
] | b01c845f7539f99efd7bfabf940dd99035cfdb94 | https://github.com/robojones/smart-promisify/blob/b01c845f7539f99efd7bfabf940dd99035cfdb94/index.js#L7-L52 |
54,561 | UXFoundry/hashdo | lib/card.js | generateCardDocument | function generateCardDocument(options, callback) {
var DB = require('../index').db,
elementId = Cuid();
// defaults
options = _.defaultsDeep(options, {
directory: '.',
css: true,
js: false,
clientStateSupport: false,
clientProxySupport: false,
clientAnalyticsSupport: false,
viewModel: {
link: options.link,
card: {
id: elementId,
name: options.cardName,
pack: options.packName
}
},
clientLocals: {
title: options.title,
card: {
id: elementId,
key: options.key,
name: options.cardName,
pack: options.packName,
url: options.url
}
}
});
Async.waterfall([
function (cb) {
stylesToString(options, function (css) {
cb(null, css);
});
},
function (css, cb) {
if (options.clientStateSupport || options.clientAnalyticsSupport || options.clientProxySupport) {
// generate a one-time #Do API key.
DB.issueAPIKey(options.key, function (err, apiKey) {
if (apiKey) {
options.clientLocals.card.apiKey = apiKey;
}
cb(null, css);
});
}
else {
cb(null, css);
}
},
function (css, cb) {
jsToString(options, function (js) {
cb(null, css, js);
});
},
function (css, js, cb) {
viewToString(css, js, options, function (html) {
cb(null, html || '');
});
}
],
// done
function (err, html) {
callback && callback(Minify(html, {
collapseWhitespace: true,
removeComments: true,
removeCommentsFromCDATA: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
removeEmptyAttributes: true,
minifyJS: process.env.NODE_ENV === 'production',
minifyCSS: process.env.NODE_ENV === 'production'
}));
}
);
} | javascript | function generateCardDocument(options, callback) {
var DB = require('../index').db,
elementId = Cuid();
// defaults
options = _.defaultsDeep(options, {
directory: '.',
css: true,
js: false,
clientStateSupport: false,
clientProxySupport: false,
clientAnalyticsSupport: false,
viewModel: {
link: options.link,
card: {
id: elementId,
name: options.cardName,
pack: options.packName
}
},
clientLocals: {
title: options.title,
card: {
id: elementId,
key: options.key,
name: options.cardName,
pack: options.packName,
url: options.url
}
}
});
Async.waterfall([
function (cb) {
stylesToString(options, function (css) {
cb(null, css);
});
},
function (css, cb) {
if (options.clientStateSupport || options.clientAnalyticsSupport || options.clientProxySupport) {
// generate a one-time #Do API key.
DB.issueAPIKey(options.key, function (err, apiKey) {
if (apiKey) {
options.clientLocals.card.apiKey = apiKey;
}
cb(null, css);
});
}
else {
cb(null, css);
}
},
function (css, cb) {
jsToString(options, function (js) {
cb(null, css, js);
});
},
function (css, js, cb) {
viewToString(css, js, options, function (html) {
cb(null, html || '');
});
}
],
// done
function (err, html) {
callback && callback(Minify(html, {
collapseWhitespace: true,
removeComments: true,
removeCommentsFromCDATA: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
removeEmptyAttributes: true,
minifyJS: process.env.NODE_ENV === 'production',
minifyCSS: process.env.NODE_ENV === 'production'
}));
}
);
} | [
"function",
"generateCardDocument",
"(",
"options",
",",
"callback",
")",
"{",
"var",
"DB",
"=",
"require",
"(",
"'../index'",
")",
".",
"db",
",",
"elementId",
"=",
"Cuid",
"(",
")",
";",
"// defaults",
"options",
"=",
"_",
".",
"defaultsDeep",
"(",
"options",
",",
"{",
"directory",
":",
"'.'",
",",
"css",
":",
"true",
",",
"js",
":",
"false",
",",
"clientStateSupport",
":",
"false",
",",
"clientProxySupport",
":",
"false",
",",
"clientAnalyticsSupport",
":",
"false",
",",
"viewModel",
":",
"{",
"link",
":",
"options",
".",
"link",
",",
"card",
":",
"{",
"id",
":",
"elementId",
",",
"name",
":",
"options",
".",
"cardName",
",",
"pack",
":",
"options",
".",
"packName",
"}",
"}",
",",
"clientLocals",
":",
"{",
"title",
":",
"options",
".",
"title",
",",
"card",
":",
"{",
"id",
":",
"elementId",
",",
"key",
":",
"options",
".",
"key",
",",
"name",
":",
"options",
".",
"cardName",
",",
"pack",
":",
"options",
".",
"packName",
",",
"url",
":",
"options",
".",
"url",
"}",
"}",
"}",
")",
";",
"Async",
".",
"waterfall",
"(",
"[",
"function",
"(",
"cb",
")",
"{",
"stylesToString",
"(",
"options",
",",
"function",
"(",
"css",
")",
"{",
"cb",
"(",
"null",
",",
"css",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"css",
",",
"cb",
")",
"{",
"if",
"(",
"options",
".",
"clientStateSupport",
"||",
"options",
".",
"clientAnalyticsSupport",
"||",
"options",
".",
"clientProxySupport",
")",
"{",
"// generate a one-time #Do API key.",
"DB",
".",
"issueAPIKey",
"(",
"options",
".",
"key",
",",
"function",
"(",
"err",
",",
"apiKey",
")",
"{",
"if",
"(",
"apiKey",
")",
"{",
"options",
".",
"clientLocals",
".",
"card",
".",
"apiKey",
"=",
"apiKey",
";",
"}",
"cb",
"(",
"null",
",",
"css",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"null",
",",
"css",
")",
";",
"}",
"}",
",",
"function",
"(",
"css",
",",
"cb",
")",
"{",
"jsToString",
"(",
"options",
",",
"function",
"(",
"js",
")",
"{",
"cb",
"(",
"null",
",",
"css",
",",
"js",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"css",
",",
"js",
",",
"cb",
")",
"{",
"viewToString",
"(",
"css",
",",
"js",
",",
"options",
",",
"function",
"(",
"html",
")",
"{",
"cb",
"(",
"null",
",",
"html",
"||",
"''",
")",
";",
"}",
")",
";",
"}",
"]",
",",
"// done",
"function",
"(",
"err",
",",
"html",
")",
"{",
"callback",
"&&",
"callback",
"(",
"Minify",
"(",
"html",
",",
"{",
"collapseWhitespace",
":",
"true",
",",
"removeComments",
":",
"true",
",",
"removeCommentsFromCDATA",
":",
"true",
",",
"removeAttributeQuotes",
":",
"true",
",",
"removeRedundantAttributes",
":",
"true",
",",
"removeEmptyAttributes",
":",
"true",
",",
"minifyJS",
":",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"'production'",
",",
"minifyCSS",
":",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"'production'",
"}",
")",
")",
";",
"}",
")",
";",
"}"
] | Generate the full HTML document to render a card.
The document will be optimized in a production environment.
@method generateCardDocument
@async
@param {Object} options Rendering options object.
directory: The directory where the pack and card can be found.
packName: The pack name.
cardName: The card name.
url: the card url.
title: The card's title.
key: The card's unique key which is based on URL.
link: The card's external link.
css: Boolean to determine whether the card CSS will be included.
js: Boolean to determine whether the card JavaScript will be included.
clientStateSupport: Boolean to determine whether client state code needs to be included.
clientProxySupport: Boolean to determin whether client proxy code needs to be included.
clientAnalyticsSupport: Boolean to determine whether client analytics support JavaScript needs to be included.
viewModel: JSON view data object used to render server-side template.
clientLocals: JSON object with any local values that need to be accessible in client JavaScript.
@param {Function} [callback] Optional callback function to retrieve the fully rendered card. | [
"Generate",
"the",
"full",
"HTML",
"document",
"to",
"render",
"a",
"card",
".",
"The",
"document",
"will",
"be",
"optimized",
"in",
"a",
"production",
"environment",
"."
] | c2a0adcba0cca26d6ebe56bba17017b177609057 | https://github.com/UXFoundry/hashdo/blob/c2a0adcba0cca26d6ebe56bba17017b177609057/lib/card.js#L178-L260 |
54,562 | UXFoundry/hashdo | lib/card.js | function (packName, cardName, inputValues, callback) {
var DB = require('../index').db;
// Go through the input values and base64 them if they aren't already.
var allBase64 = true;
_.each(_.keys(inputValues), function (key) {
if (!/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/.test(inputValues[key])) {
allBase64 = false;
}
});
// If not all inputs are base64, then we'll convert them for the user (backward compatibility).
if (!allBase64) {
_.each(_.keys(inputValues), function (key) {
inputValues[key] = Base64.encode(inputValues[key]);
});
}
DB.lock(packName, cardName, inputValues, process.env.LOCK_KEY, function (err, token) {
if (!err) {
callback && callback(null, token);
}
else {
callback && callback(err);
}
});
} | javascript | function (packName, cardName, inputValues, callback) {
var DB = require('../index').db;
// Go through the input values and base64 them if they aren't already.
var allBase64 = true;
_.each(_.keys(inputValues), function (key) {
if (!/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/.test(inputValues[key])) {
allBase64 = false;
}
});
// If not all inputs are base64, then we'll convert them for the user (backward compatibility).
if (!allBase64) {
_.each(_.keys(inputValues), function (key) {
inputValues[key] = Base64.encode(inputValues[key]);
});
}
DB.lock(packName, cardName, inputValues, process.env.LOCK_KEY, function (err, token) {
if (!err) {
callback && callback(null, token);
}
else {
callback && callback(err);
}
});
} | [
"function",
"(",
"packName",
",",
"cardName",
",",
"inputValues",
",",
"callback",
")",
"{",
"var",
"DB",
"=",
"require",
"(",
"'../index'",
")",
".",
"db",
";",
"// Go through the input values and base64 them if they aren't already.",
"var",
"allBase64",
"=",
"true",
";",
"_",
".",
"each",
"(",
"_",
".",
"keys",
"(",
"inputValues",
")",
",",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"!",
"/",
"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$",
"/",
".",
"test",
"(",
"inputValues",
"[",
"key",
"]",
")",
")",
"{",
"allBase64",
"=",
"false",
";",
"}",
"}",
")",
";",
"// If not all inputs are base64, then we'll convert them for the user (backward compatibility). ",
"if",
"(",
"!",
"allBase64",
")",
"{",
"_",
".",
"each",
"(",
"_",
".",
"keys",
"(",
"inputValues",
")",
",",
"function",
"(",
"key",
")",
"{",
"inputValues",
"[",
"key",
"]",
"=",
"Base64",
".",
"encode",
"(",
"inputValues",
"[",
"key",
"]",
")",
";",
"}",
")",
";",
"}",
"DB",
".",
"lock",
"(",
"packName",
",",
"cardName",
",",
"inputValues",
",",
"process",
".",
"env",
".",
"LOCK_KEY",
",",
"function",
"(",
"err",
",",
"token",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"callback",
"&&",
"callback",
"(",
"null",
",",
"token",
")",
";",
"}",
"else",
"{",
"callback",
"&&",
"callback",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}"
] | Secure card inputs such as passwords and API keys sop they cannot be read by users.
@method secureInputs
@async
@param {String} packName The pack this data belongs to.
@param {String} cardName The card this data belongs to.
@param {Object} inputValues The values that you want to be secured.
@param {Function} [callback] Optional callback function to retrieve the secure token that can be used to render a card. | [
"Secure",
"card",
"inputs",
"such",
"as",
"passwords",
"and",
"API",
"keys",
"sop",
"they",
"cannot",
"be",
"read",
"by",
"users",
"."
] | c2a0adcba0cca26d6ebe56bba17017b177609057 | https://github.com/UXFoundry/hashdo/blob/c2a0adcba0cca26d6ebe56bba17017b177609057/lib/card.js#L273-L299 |
|
54,563 | UXFoundry/hashdo | lib/card.js | function (cb) {
// card key
var url = options.url.replace(/light=true/i, ''),
params = {
legacyCardKey: Utils.getLegacyCardKey(url, process.env.CARD_SECRET),
cardKey: Utils.getCardKey(url, process.env.CARD_SECRET)
};
// extract input values
_.each(_.keys(options.inputValues), function (key) {
params[key] = options.inputValues[key];
});
if (options.inputValues.token) {
// retrieve previously saved parameters. Add or replace params
DB.unlock(options.packName, options.cardName, options.inputValues.token, process.env.LOCK_KEY, function (err, payload) {
if (err) {
// Ignore error and just return the params.
cb(null, params);
}
else {
if (payload && _.isObject(payload)) {
_.each(_.keys(Card.inputs), function (key) {
if (payload[key]) {
params[key] = Base64.decode(payload[key]);
}
});
}
cb(null, params);
}
});
}
else {
cb(null, params);
}
} | javascript | function (cb) {
// card key
var url = options.url.replace(/light=true/i, ''),
params = {
legacyCardKey: Utils.getLegacyCardKey(url, process.env.CARD_SECRET),
cardKey: Utils.getCardKey(url, process.env.CARD_SECRET)
};
// extract input values
_.each(_.keys(options.inputValues), function (key) {
params[key] = options.inputValues[key];
});
if (options.inputValues.token) {
// retrieve previously saved parameters. Add or replace params
DB.unlock(options.packName, options.cardName, options.inputValues.token, process.env.LOCK_KEY, function (err, payload) {
if (err) {
// Ignore error and just return the params.
cb(null, params);
}
else {
if (payload && _.isObject(payload)) {
_.each(_.keys(Card.inputs), function (key) {
if (payload[key]) {
params[key] = Base64.decode(payload[key]);
}
});
}
cb(null, params);
}
});
}
else {
cb(null, params);
}
} | [
"function",
"(",
"cb",
")",
"{",
"// card key",
"var",
"url",
"=",
"options",
".",
"url",
".",
"replace",
"(",
"/",
"light=true",
"/",
"i",
",",
"''",
")",
",",
"params",
"=",
"{",
"legacyCardKey",
":",
"Utils",
".",
"getLegacyCardKey",
"(",
"url",
",",
"process",
".",
"env",
".",
"CARD_SECRET",
")",
",",
"cardKey",
":",
"Utils",
".",
"getCardKey",
"(",
"url",
",",
"process",
".",
"env",
".",
"CARD_SECRET",
")",
"}",
";",
"// extract input values",
"_",
".",
"each",
"(",
"_",
".",
"keys",
"(",
"options",
".",
"inputValues",
")",
",",
"function",
"(",
"key",
")",
"{",
"params",
"[",
"key",
"]",
"=",
"options",
".",
"inputValues",
"[",
"key",
"]",
";",
"}",
")",
";",
"if",
"(",
"options",
".",
"inputValues",
".",
"token",
")",
"{",
"// retrieve previously saved parameters. Add or replace params",
"DB",
".",
"unlock",
"(",
"options",
".",
"packName",
",",
"options",
".",
"cardName",
",",
"options",
".",
"inputValues",
".",
"token",
",",
"process",
".",
"env",
".",
"LOCK_KEY",
",",
"function",
"(",
"err",
",",
"payload",
")",
"{",
"if",
"(",
"err",
")",
"{",
"// Ignore error and just return the params.",
"cb",
"(",
"null",
",",
"params",
")",
";",
"}",
"else",
"{",
"if",
"(",
"payload",
"&&",
"_",
".",
"isObject",
"(",
"payload",
")",
")",
"{",
"_",
".",
"each",
"(",
"_",
".",
"keys",
"(",
"Card",
".",
"inputs",
")",
",",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"payload",
"[",
"key",
"]",
")",
"{",
"params",
"[",
"key",
"]",
"=",
"Base64",
".",
"decode",
"(",
"payload",
"[",
"key",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
"cb",
"(",
"null",
",",
"params",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"null",
",",
"params",
")",
";",
"}",
"}"
] | get required params | [
"get",
"required",
"params"
] | c2a0adcba0cca26d6ebe56bba17017b177609057 | https://github.com/UXFoundry/hashdo/blob/c2a0adcba0cca26d6ebe56bba17017b177609057/lib/card.js#L354-L391 |
|
54,564 | UXFoundry/hashdo | lib/card.js | function (params, cb) {
// validate input requirements vs what came back in params
var errorMessage = null;
_.forEach(Card.inputs, function (input, key) {
if (input.required && !params[key]) {
if (!errorMessage) {
errorMessage = '';
}
else {
errorMessage += ' | ';
}
errorMessage += 'No value provided for required input: ' + key;
}
});
cb(errorMessage, params);
} | javascript | function (params, cb) {
// validate input requirements vs what came back in params
var errorMessage = null;
_.forEach(Card.inputs, function (input, key) {
if (input.required && !params[key]) {
if (!errorMessage) {
errorMessage = '';
}
else {
errorMessage += ' | ';
}
errorMessage += 'No value provided for required input: ' + key;
}
});
cb(errorMessage, params);
} | [
"function",
"(",
"params",
",",
"cb",
")",
"{",
"// validate input requirements vs what came back in params",
"var",
"errorMessage",
"=",
"null",
";",
"_",
".",
"forEach",
"(",
"Card",
".",
"inputs",
",",
"function",
"(",
"input",
",",
"key",
")",
"{",
"if",
"(",
"input",
".",
"required",
"&&",
"!",
"params",
"[",
"key",
"]",
")",
"{",
"if",
"(",
"!",
"errorMessage",
")",
"{",
"errorMessage",
"=",
"''",
";",
"}",
"else",
"{",
"errorMessage",
"+=",
"' | '",
";",
"}",
"errorMessage",
"+=",
"'No value provided for required input: '",
"+",
"key",
";",
"}",
"}",
")",
";",
"cb",
"(",
"errorMessage",
",",
"params",
")",
";",
"}"
] | check for input validation errors | [
"check",
"for",
"input",
"validation",
"errors"
] | c2a0adcba0cca26d6ebe56bba17017b177609057 | https://github.com/UXFoundry/hashdo/blob/c2a0adcba0cca26d6ebe56bba17017b177609057/lib/card.js#L394-L412 |
|
54,565 | UXFoundry/hashdo | lib/card.js | function (err, params) {
if (!err) {
callback && callback(null, params);
}
else {
callback && callback(err.message || err);
}
} | javascript | function (err, params) {
if (!err) {
callback && callback(null, params);
}
else {
callback && callback(err.message || err);
}
} | [
"function",
"(",
"err",
",",
"params",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"callback",
"&&",
"callback",
"(",
"null",
",",
"params",
")",
";",
"}",
"else",
"{",
"callback",
"&&",
"callback",
"(",
"err",
".",
"message",
"||",
"err",
")",
";",
"}",
"}"
] | done - respond with params | [
"done",
"-",
"respond",
"with",
"params"
] | c2a0adcba0cca26d6ebe56bba17017b177609057 | https://github.com/UXFoundry/hashdo/blob/c2a0adcba0cca26d6ebe56bba17017b177609057/lib/card.js#L416-L423 |
|
54,566 | UXFoundry/hashdo | lib/card.js | function (params, cb) {
DB.getCardState(params.cardKey, params.legacyCardKey, function (err, state) {
cb(null, params, state);
});
} | javascript | function (params, cb) {
DB.getCardState(params.cardKey, params.legacyCardKey, function (err, state) {
cb(null, params, state);
});
} | [
"function",
"(",
"params",
",",
"cb",
")",
"{",
"DB",
".",
"getCardState",
"(",
"params",
".",
"cardKey",
",",
"params",
".",
"legacyCardKey",
",",
"function",
"(",
"err",
",",
"state",
")",
"{",
"cb",
"(",
"null",
",",
"params",
",",
"state",
")",
";",
"}",
")",
";",
"}"
] | load previously saved state | [
"load",
"previously",
"saved",
"state"
] | c2a0adcba0cca26d6ebe56bba17017b177609057 | https://github.com/UXFoundry/hashdo/blob/c2a0adcba0cca26d6ebe56bba17017b177609057/lib/card.js#L553-L557 |
|
54,567 | UXFoundry/hashdo | lib/card.js | function (params, state, cb) {
state = state || {};
if (Card.getCardData) {
Card.getCardData(params, state, function (err, viewModel, clientLocals) {
cb(err, params, state, viewModel, clientLocals);
});
}
else {
cb(null, params, state, null, null);
}
} | javascript | function (params, state, cb) {
state = state || {};
if (Card.getCardData) {
Card.getCardData(params, state, function (err, viewModel, clientLocals) {
cb(err, params, state, viewModel, clientLocals);
});
}
else {
cb(null, params, state, null, null);
}
} | [
"function",
"(",
"params",
",",
"state",
",",
"cb",
")",
"{",
"state",
"=",
"state",
"||",
"{",
"}",
";",
"if",
"(",
"Card",
".",
"getCardData",
")",
"{",
"Card",
".",
"getCardData",
"(",
"params",
",",
"state",
",",
"function",
"(",
"err",
",",
"viewModel",
",",
"clientLocals",
")",
"{",
"cb",
"(",
"err",
",",
"params",
",",
"state",
",",
"viewModel",
",",
"clientLocals",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"null",
",",
"params",
",",
"state",
",",
"null",
",",
"null",
")",
";",
"}",
"}"
] | get view model data from the card | [
"get",
"view",
"model",
"data",
"from",
"the",
"card"
] | c2a0adcba0cca26d6ebe56bba17017b177609057 | https://github.com/UXFoundry/hashdo/blob/c2a0adcba0cca26d6ebe56bba17017b177609057/lib/card.js#L560-L571 |
|
54,568 | UXFoundry/hashdo | lib/card.js | function (params, state, viewModel, clientLocals, cb) {
// don't save if nothing came back, just forward the call
if (!_.isEmpty(state)) {
DB.saveCardState(params.cardKey, state, function (err) {
cb(err, params, viewModel, clientLocals);
});
}
else {
cb(null, params, viewModel, clientLocals);
}
} | javascript | function (params, state, viewModel, clientLocals, cb) {
// don't save if nothing came back, just forward the call
if (!_.isEmpty(state)) {
DB.saveCardState(params.cardKey, state, function (err) {
cb(err, params, viewModel, clientLocals);
});
}
else {
cb(null, params, viewModel, clientLocals);
}
} | [
"function",
"(",
"params",
",",
"state",
",",
"viewModel",
",",
"clientLocals",
",",
"cb",
")",
"{",
"// don't save if nothing came back, just forward the call",
"if",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"state",
")",
")",
"{",
"DB",
".",
"saveCardState",
"(",
"params",
".",
"cardKey",
",",
"state",
",",
"function",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
",",
"params",
",",
"viewModel",
",",
"clientLocals",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"null",
",",
"params",
",",
"viewModel",
",",
"clientLocals",
")",
";",
"}",
"}"
] | save any state changes made during getCardData | [
"save",
"any",
"state",
"changes",
"made",
"during",
"getCardData"
] | c2a0adcba0cca26d6ebe56bba17017b177609057 | https://github.com/UXFoundry/hashdo/blob/c2a0adcba0cca26d6ebe56bba17017b177609057/lib/card.js#L574-L584 |
|
54,569 | UXFoundry/hashdo | lib/card.js | function (params, viewModel, clientLocals, cb) {
viewModel = viewModel || {};
clientLocals = clientLocals || {};
var generateOptions = {
directory: options.directory,
packName: options.packName,
cardName: options.cardName,
url: options.url,
key: params.cardKey,
title: viewModel.title || '',
link: viewModel.link,
css: params.light !== true,
client$Support: Card.client$Support || false,
clientStateSupport: Card.clientStateSupport || false,
clientProxySupport: Card.clientProxySupport || false,
clientAnalyticsSupport: Card.clientAnalyticsSupport || false,
viewModel: viewModel,
clientLocals: clientLocals
};
generateCardDocument(generateOptions, function (html) {
cb(null, html);
});
} | javascript | function (params, viewModel, clientLocals, cb) {
viewModel = viewModel || {};
clientLocals = clientLocals || {};
var generateOptions = {
directory: options.directory,
packName: options.packName,
cardName: options.cardName,
url: options.url,
key: params.cardKey,
title: viewModel.title || '',
link: viewModel.link,
css: params.light !== true,
client$Support: Card.client$Support || false,
clientStateSupport: Card.clientStateSupport || false,
clientProxySupport: Card.clientProxySupport || false,
clientAnalyticsSupport: Card.clientAnalyticsSupport || false,
viewModel: viewModel,
clientLocals: clientLocals
};
generateCardDocument(generateOptions, function (html) {
cb(null, html);
});
} | [
"function",
"(",
"params",
",",
"viewModel",
",",
"clientLocals",
",",
"cb",
")",
"{",
"viewModel",
"=",
"viewModel",
"||",
"{",
"}",
";",
"clientLocals",
"=",
"clientLocals",
"||",
"{",
"}",
";",
"var",
"generateOptions",
"=",
"{",
"directory",
":",
"options",
".",
"directory",
",",
"packName",
":",
"options",
".",
"packName",
",",
"cardName",
":",
"options",
".",
"cardName",
",",
"url",
":",
"options",
".",
"url",
",",
"key",
":",
"params",
".",
"cardKey",
",",
"title",
":",
"viewModel",
".",
"title",
"||",
"''",
",",
"link",
":",
"viewModel",
".",
"link",
",",
"css",
":",
"params",
".",
"light",
"!==",
"true",
",",
"client$Support",
":",
"Card",
".",
"client$Support",
"||",
"false",
",",
"clientStateSupport",
":",
"Card",
".",
"clientStateSupport",
"||",
"false",
",",
"clientProxySupport",
":",
"Card",
".",
"clientProxySupport",
"||",
"false",
",",
"clientAnalyticsSupport",
":",
"Card",
".",
"clientAnalyticsSupport",
"||",
"false",
",",
"viewModel",
":",
"viewModel",
",",
"clientLocals",
":",
"clientLocals",
"}",
";",
"generateCardDocument",
"(",
"generateOptions",
",",
"function",
"(",
"html",
")",
"{",
"cb",
"(",
"null",
",",
"html",
")",
";",
"}",
")",
";",
"}"
] | render the options | [
"render",
"the",
"options"
] | c2a0adcba0cca26d6ebe56bba17017b177609057 | https://github.com/UXFoundry/hashdo/blob/c2a0adcba0cca26d6ebe56bba17017b177609057/lib/card.js#L587-L611 |
|
54,570 | UXFoundry/hashdo | lib/card.js | function (err, html) {
if (!err) {
callback && callback(null, html);
}
else {
console.log('CARD: Error rendering HashDo card ' + options.packName + '-' + options.cardName + '.', err);
callback && callback(err.message || err);
}
} | javascript | function (err, html) {
if (!err) {
callback && callback(null, html);
}
else {
console.log('CARD: Error rendering HashDo card ' + options.packName + '-' + options.cardName + '.', err);
callback && callback(err.message || err);
}
} | [
"function",
"(",
"err",
",",
"html",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"callback",
"&&",
"callback",
"(",
"null",
",",
"html",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'CARD: Error rendering HashDo card '",
"+",
"options",
".",
"packName",
"+",
"'-'",
"+",
"options",
".",
"cardName",
"+",
"'.'",
",",
"err",
")",
";",
"callback",
"&&",
"callback",
"(",
"err",
".",
"message",
"||",
"err",
")",
";",
"}",
"}"
] | done - respond with HTML | [
"done",
"-",
"respond",
"with",
"HTML"
] | c2a0adcba0cca26d6ebe56bba17017b177609057 | https://github.com/UXFoundry/hashdo/blob/c2a0adcba0cca26d6ebe56bba17017b177609057/lib/card.js#L615-L623 |
|
54,571 | UXFoundry/hashdo | lib/card.js | function (options, callback) {
if (!options) {
throw new Error('You must provide an options object to .');
}
if (!options.packName) {
throw new Error('You must provide a pack name the card belongs to.');
}
if (!options.cardName) {
throw new Error('You must provide a card name of the card to render.');
}
var packPath = Path.join(options.directory, 'hashdo-' + options.packName.replace('hashdo-', '')),
cardFile = Path.join(packPath, options.cardName) + '.js';
// check for card pack
FS.stat(packPath, function (err) {
if (!err) {
// check for card
FS.stat(cardFile, function (err) {
if (!err) {
// Remove card from cache to ease development by reloading from disk each time.
if (process.env.NODE_ENV !== 'production') {
delete require.cache[require.resolve(Path.join(packPath, options.cardName))];
}
var Card = require(Path.join(packPath, options.cardName));
// If this card has a web hook function then let's call it.
if (Card.webHook) {
var DB = require('../index').db;
Card.webHook(options.payload, function (err, urlParams, state) {
if (!err) {
if (state) {
var cardKey = Utils.getCardKey('/' + options.packName + '/' + options.cardName + objectToQueryString(urlParams), process.env.CARD_SECRET),
firebaseUrl = 'card/' + cardKey;
if (Card.clientStateSupport && process.env.FIREBASE_URL) {
Firebase.set(firebaseUrl, state);
}
DB.getCardState(cardKey, null, function (err, currentCardState) {
DB.saveCardState(cardKey, Utils.deepMerge(true, true, currentCardState || {}, state));
});
}
}
callback && callback(null);
});
}
else {
// No web hook function.
callback && callback('Web hook not available.');
}
}
else {
callback && callback('No card found.');
}
});
}
else {
// No card pack.
callback && callback('Pack not found.');
}
});
} | javascript | function (options, callback) {
if (!options) {
throw new Error('You must provide an options object to .');
}
if (!options.packName) {
throw new Error('You must provide a pack name the card belongs to.');
}
if (!options.cardName) {
throw new Error('You must provide a card name of the card to render.');
}
var packPath = Path.join(options.directory, 'hashdo-' + options.packName.replace('hashdo-', '')),
cardFile = Path.join(packPath, options.cardName) + '.js';
// check for card pack
FS.stat(packPath, function (err) {
if (!err) {
// check for card
FS.stat(cardFile, function (err) {
if (!err) {
// Remove card from cache to ease development by reloading from disk each time.
if (process.env.NODE_ENV !== 'production') {
delete require.cache[require.resolve(Path.join(packPath, options.cardName))];
}
var Card = require(Path.join(packPath, options.cardName));
// If this card has a web hook function then let's call it.
if (Card.webHook) {
var DB = require('../index').db;
Card.webHook(options.payload, function (err, urlParams, state) {
if (!err) {
if (state) {
var cardKey = Utils.getCardKey('/' + options.packName + '/' + options.cardName + objectToQueryString(urlParams), process.env.CARD_SECRET),
firebaseUrl = 'card/' + cardKey;
if (Card.clientStateSupport && process.env.FIREBASE_URL) {
Firebase.set(firebaseUrl, state);
}
DB.getCardState(cardKey, null, function (err, currentCardState) {
DB.saveCardState(cardKey, Utils.deepMerge(true, true, currentCardState || {}, state));
});
}
}
callback && callback(null);
});
}
else {
// No web hook function.
callback && callback('Web hook not available.');
}
}
else {
callback && callback('No card found.');
}
});
}
else {
// No card pack.
callback && callback('Pack not found.');
}
});
} | [
"function",
"(",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"options",
")",
"{",
"throw",
"new",
"Error",
"(",
"'You must provide an options object to .'",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"packName",
")",
"{",
"throw",
"new",
"Error",
"(",
"'You must provide a pack name the card belongs to.'",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"cardName",
")",
"{",
"throw",
"new",
"Error",
"(",
"'You must provide a card name of the card to render.'",
")",
";",
"}",
"var",
"packPath",
"=",
"Path",
".",
"join",
"(",
"options",
".",
"directory",
",",
"'hashdo-'",
"+",
"options",
".",
"packName",
".",
"replace",
"(",
"'hashdo-'",
",",
"''",
")",
")",
",",
"cardFile",
"=",
"Path",
".",
"join",
"(",
"packPath",
",",
"options",
".",
"cardName",
")",
"+",
"'.js'",
";",
"// check for card pack",
"FS",
".",
"stat",
"(",
"packPath",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"// check for card",
"FS",
".",
"stat",
"(",
"cardFile",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"// Remove card from cache to ease development by reloading from disk each time.",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
")",
"{",
"delete",
"require",
".",
"cache",
"[",
"require",
".",
"resolve",
"(",
"Path",
".",
"join",
"(",
"packPath",
",",
"options",
".",
"cardName",
")",
")",
"]",
";",
"}",
"var",
"Card",
"=",
"require",
"(",
"Path",
".",
"join",
"(",
"packPath",
",",
"options",
".",
"cardName",
")",
")",
";",
"// If this card has a web hook function then let's call it.",
"if",
"(",
"Card",
".",
"webHook",
")",
"{",
"var",
"DB",
"=",
"require",
"(",
"'../index'",
")",
".",
"db",
";",
"Card",
".",
"webHook",
"(",
"options",
".",
"payload",
",",
"function",
"(",
"err",
",",
"urlParams",
",",
"state",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"if",
"(",
"state",
")",
"{",
"var",
"cardKey",
"=",
"Utils",
".",
"getCardKey",
"(",
"'/'",
"+",
"options",
".",
"packName",
"+",
"'/'",
"+",
"options",
".",
"cardName",
"+",
"objectToQueryString",
"(",
"urlParams",
")",
",",
"process",
".",
"env",
".",
"CARD_SECRET",
")",
",",
"firebaseUrl",
"=",
"'card/'",
"+",
"cardKey",
";",
"if",
"(",
"Card",
".",
"clientStateSupport",
"&&",
"process",
".",
"env",
".",
"FIREBASE_URL",
")",
"{",
"Firebase",
".",
"set",
"(",
"firebaseUrl",
",",
"state",
")",
";",
"}",
"DB",
".",
"getCardState",
"(",
"cardKey",
",",
"null",
",",
"function",
"(",
"err",
",",
"currentCardState",
")",
"{",
"DB",
".",
"saveCardState",
"(",
"cardKey",
",",
"Utils",
".",
"deepMerge",
"(",
"true",
",",
"true",
",",
"currentCardState",
"||",
"{",
"}",
",",
"state",
")",
")",
";",
"}",
")",
";",
"}",
"}",
"callback",
"&&",
"callback",
"(",
"null",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"// No web hook function.",
"callback",
"&&",
"callback",
"(",
"'Web hook not available.'",
")",
";",
"}",
"}",
"else",
"{",
"callback",
"&&",
"callback",
"(",
"'No card found.'",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"// No card pack.",
"callback",
"&&",
"callback",
"(",
"'Pack not found.'",
")",
";",
"}",
"}",
")",
";",
"}"
] | Provides the functionality to call a card's web hook functionality and save the state.
@method webHook
@async
@param {Object} options Hooking options object.
directory: The directory where the pack and card code can be found.
packName: The pack name.
cardName: The card name.
payload: The values necessary to create new card state.
@param {Function} [callback] Optional callback function to retrieve the card HTML. | [
"Provides",
"the",
"functionality",
"to",
"call",
"a",
"card",
"s",
"web",
"hook",
"functionality",
"and",
"save",
"the",
"state",
"."
] | c2a0adcba0cca26d6ebe56bba17017b177609057 | https://github.com/UXFoundry/hashdo/blob/c2a0adcba0cca26d6ebe56bba17017b177609057/lib/card.js#L652-L721 |
|
54,572 | commenthol/connect-composer | lib/compose.js | nextTick | function nextTick (next, err) {
return process.nextTick(function () {
try {
next(err)
} catch (e) {
// istanbul ignore next
next(e)
}
})
} | javascript | function nextTick (next, err) {
return process.nextTick(function () {
try {
next(err)
} catch (e) {
// istanbul ignore next
next(e)
}
})
} | [
"function",
"nextTick",
"(",
"next",
",",
"err",
")",
"{",
"return",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"try",
"{",
"next",
"(",
"err",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"// istanbul ignore next",
"next",
"(",
"e",
")",
"}",
"}",
")",
"}"
] | Safety wrapper around nextTick
@api private
@param {Function} next - next function on the stack
@param {Object} [err] - error value from previous middleware | [
"Safety",
"wrapper",
"around",
"nextTick"
] | 810dbd1c7d3095598ec4a4fa771b9d55e037fb57 | https://github.com/commenthol/connect-composer/blob/810dbd1c7d3095598ec4a4fa771b9d55e037fb57/lib/compose.js#L14-L23 |
54,573 | commenthol/connect-composer | lib/compose.js | compose | function compose () {
// the function required by the server
function middlewareF (req, res, end) {
var index = 0
// inject stats middleware
if (middlewareF.options && middlewareF.options.stats) {
middlewareF.stack = middlewareF.stack.map(function (mw) {
var fn
if (typeof mw === 'object') {
var key = Object.keys(mw)[0]
if (!mw[key].stats) {
fn = {}
fn[key] = middlewareF.options.stats(mw[key])
}
} else {
if (!mw.stats) {
fn = middlewareF.options.stats(mw)
}
}
return fn
})
}
// looping over all middleware functions defined by stack
;(function next (err) {
var arity
var middleware = middlewareF.stack[index++] // obtain the current middleware from the stack
if (!middleware) {
// we are at the end of the stack
end && end(err)
return
} else {
// extract middleware from object
if (typeof (middleware) === 'object') {
var name = Object.keys(middleware)[0]
if (typeof (middleware[name]) === 'function') {
middleware = middleware[name]
} else {
middleware = function (req, res, next) {
next(new Error('missing middleware'))
}
}
}
try {
arity = middleware.length // number of arguments function middleware requires
// handle errors
if (err) {
// If the middleware function contains 4 arguments than this will act as an "error trap"
if (arity === 4) {
middleware(err, req, res, function (err) {
nextTick(next, err)
})
} else {
// otherwise check the next middleware
next(err)
}
} else if (arity < 4) {
// process non "error trap" stack
middleware(req, res, function (err) {
nextTick(next, err)
})
} else {
// loop over "error traps" if no error `err` is set.
next()
}
} catch (e) {
next(e)
}
}
})()
}
middlewareF.stack = []
middlewareF.options = compose.options || {}
;[].slice.call(arguments).forEach(function (a) {
middlewareF.stack = middlewareF.stack.concat(compose.decompose(a))
})
// extends
;[ 'before', 'after', 'replace', 'remove', 'push', 'unshift', 'clone' ].forEach(function (p) {
middlewareF[p] = compose[p]
})
// inject stats middleware
if (compose.options.stats) {
middlewareF.options = {}
middlewareF.options.stats = compose.options.stats
}
return middlewareF
} | javascript | function compose () {
// the function required by the server
function middlewareF (req, res, end) {
var index = 0
// inject stats middleware
if (middlewareF.options && middlewareF.options.stats) {
middlewareF.stack = middlewareF.stack.map(function (mw) {
var fn
if (typeof mw === 'object') {
var key = Object.keys(mw)[0]
if (!mw[key].stats) {
fn = {}
fn[key] = middlewareF.options.stats(mw[key])
}
} else {
if (!mw.stats) {
fn = middlewareF.options.stats(mw)
}
}
return fn
})
}
// looping over all middleware functions defined by stack
;(function next (err) {
var arity
var middleware = middlewareF.stack[index++] // obtain the current middleware from the stack
if (!middleware) {
// we are at the end of the stack
end && end(err)
return
} else {
// extract middleware from object
if (typeof (middleware) === 'object') {
var name = Object.keys(middleware)[0]
if (typeof (middleware[name]) === 'function') {
middleware = middleware[name]
} else {
middleware = function (req, res, next) {
next(new Error('missing middleware'))
}
}
}
try {
arity = middleware.length // number of arguments function middleware requires
// handle errors
if (err) {
// If the middleware function contains 4 arguments than this will act as an "error trap"
if (arity === 4) {
middleware(err, req, res, function (err) {
nextTick(next, err)
})
} else {
// otherwise check the next middleware
next(err)
}
} else if (arity < 4) {
// process non "error trap" stack
middleware(req, res, function (err) {
nextTick(next, err)
})
} else {
// loop over "error traps" if no error `err` is set.
next()
}
} catch (e) {
next(e)
}
}
})()
}
middlewareF.stack = []
middlewareF.options = compose.options || {}
;[].slice.call(arguments).forEach(function (a) {
middlewareF.stack = middlewareF.stack.concat(compose.decompose(a))
})
// extends
;[ 'before', 'after', 'replace', 'remove', 'push', 'unshift', 'clone' ].forEach(function (p) {
middlewareF[p] = compose[p]
})
// inject stats middleware
if (compose.options.stats) {
middlewareF.options = {}
middlewareF.options.stats = compose.options.stats
}
return middlewareF
} | [
"function",
"compose",
"(",
")",
"{",
"// the function required by the server",
"function",
"middlewareF",
"(",
"req",
",",
"res",
",",
"end",
")",
"{",
"var",
"index",
"=",
"0",
"// inject stats middleware",
"if",
"(",
"middlewareF",
".",
"options",
"&&",
"middlewareF",
".",
"options",
".",
"stats",
")",
"{",
"middlewareF",
".",
"stack",
"=",
"middlewareF",
".",
"stack",
".",
"map",
"(",
"function",
"(",
"mw",
")",
"{",
"var",
"fn",
"if",
"(",
"typeof",
"mw",
"===",
"'object'",
")",
"{",
"var",
"key",
"=",
"Object",
".",
"keys",
"(",
"mw",
")",
"[",
"0",
"]",
"if",
"(",
"!",
"mw",
"[",
"key",
"]",
".",
"stats",
")",
"{",
"fn",
"=",
"{",
"}",
"fn",
"[",
"key",
"]",
"=",
"middlewareF",
".",
"options",
".",
"stats",
"(",
"mw",
"[",
"key",
"]",
")",
"}",
"}",
"else",
"{",
"if",
"(",
"!",
"mw",
".",
"stats",
")",
"{",
"fn",
"=",
"middlewareF",
".",
"options",
".",
"stats",
"(",
"mw",
")",
"}",
"}",
"return",
"fn",
"}",
")",
"}",
"// looping over all middleware functions defined by stack",
";",
"(",
"function",
"next",
"(",
"err",
")",
"{",
"var",
"arity",
"var",
"middleware",
"=",
"middlewareF",
".",
"stack",
"[",
"index",
"++",
"]",
"// obtain the current middleware from the stack",
"if",
"(",
"!",
"middleware",
")",
"{",
"// we are at the end of the stack",
"end",
"&&",
"end",
"(",
"err",
")",
"return",
"}",
"else",
"{",
"// extract middleware from object",
"if",
"(",
"typeof",
"(",
"middleware",
")",
"===",
"'object'",
")",
"{",
"var",
"name",
"=",
"Object",
".",
"keys",
"(",
"middleware",
")",
"[",
"0",
"]",
"if",
"(",
"typeof",
"(",
"middleware",
"[",
"name",
"]",
")",
"===",
"'function'",
")",
"{",
"middleware",
"=",
"middleware",
"[",
"name",
"]",
"}",
"else",
"{",
"middleware",
"=",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"next",
"(",
"new",
"Error",
"(",
"'missing middleware'",
")",
")",
"}",
"}",
"}",
"try",
"{",
"arity",
"=",
"middleware",
".",
"length",
"// number of arguments function middleware requires",
"// handle errors",
"if",
"(",
"err",
")",
"{",
"// If the middleware function contains 4 arguments than this will act as an \"error trap\"",
"if",
"(",
"arity",
"===",
"4",
")",
"{",
"middleware",
"(",
"err",
",",
"req",
",",
"res",
",",
"function",
"(",
"err",
")",
"{",
"nextTick",
"(",
"next",
",",
"err",
")",
"}",
")",
"}",
"else",
"{",
"// otherwise check the next middleware",
"next",
"(",
"err",
")",
"}",
"}",
"else",
"if",
"(",
"arity",
"<",
"4",
")",
"{",
"// process non \"error trap\" stack",
"middleware",
"(",
"req",
",",
"res",
",",
"function",
"(",
"err",
")",
"{",
"nextTick",
"(",
"next",
",",
"err",
")",
"}",
")",
"}",
"else",
"{",
"// loop over \"error traps\" if no error `err` is set.",
"next",
"(",
")",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"next",
"(",
"e",
")",
"}",
"}",
"}",
")",
"(",
")",
"}",
"middlewareF",
".",
"stack",
"=",
"[",
"]",
"middlewareF",
".",
"options",
"=",
"compose",
".",
"options",
"||",
"{",
"}",
";",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
".",
"forEach",
"(",
"function",
"(",
"a",
")",
"{",
"middlewareF",
".",
"stack",
"=",
"middlewareF",
".",
"stack",
".",
"concat",
"(",
"compose",
".",
"decompose",
"(",
"a",
")",
")",
"}",
")",
"// extends",
";",
"[",
"'before'",
",",
"'after'",
",",
"'replace'",
",",
"'remove'",
",",
"'push'",
",",
"'unshift'",
",",
"'clone'",
"]",
".",
"forEach",
"(",
"function",
"(",
"p",
")",
"{",
"middlewareF",
"[",
"p",
"]",
"=",
"compose",
"[",
"p",
"]",
"}",
")",
"// inject stats middleware",
"if",
"(",
"compose",
".",
"options",
".",
"stats",
")",
"{",
"middlewareF",
".",
"options",
"=",
"{",
"}",
"middlewareF",
".",
"options",
".",
"stats",
"=",
"compose",
".",
"options",
".",
"stats",
"}",
"return",
"middlewareF",
"}"
] | compose a new middleware function from multiple middlewares
@param {Function|Array|Object}
@return {Function} middleware function | [
"compose",
"a",
"new",
"middleware",
"function",
"from",
"multiple",
"middlewares"
] | 810dbd1c7d3095598ec4a4fa771b9d55e037fb57 | https://github.com/commenthol/connect-composer/blob/810dbd1c7d3095598ec4a4fa771b9d55e037fb57/lib/compose.js#L31-L125 |
54,574 | commenthol/connect-composer | lib/compose.js | middlewareF | function middlewareF (req, res, end) {
var index = 0
// inject stats middleware
if (middlewareF.options && middlewareF.options.stats) {
middlewareF.stack = middlewareF.stack.map(function (mw) {
var fn
if (typeof mw === 'object') {
var key = Object.keys(mw)[0]
if (!mw[key].stats) {
fn = {}
fn[key] = middlewareF.options.stats(mw[key])
}
} else {
if (!mw.stats) {
fn = middlewareF.options.stats(mw)
}
}
return fn
})
}
// looping over all middleware functions defined by stack
;(function next (err) {
var arity
var middleware = middlewareF.stack[index++] // obtain the current middleware from the stack
if (!middleware) {
// we are at the end of the stack
end && end(err)
return
} else {
// extract middleware from object
if (typeof (middleware) === 'object') {
var name = Object.keys(middleware)[0]
if (typeof (middleware[name]) === 'function') {
middleware = middleware[name]
} else {
middleware = function (req, res, next) {
next(new Error('missing middleware'))
}
}
}
try {
arity = middleware.length // number of arguments function middleware requires
// handle errors
if (err) {
// If the middleware function contains 4 arguments than this will act as an "error trap"
if (arity === 4) {
middleware(err, req, res, function (err) {
nextTick(next, err)
})
} else {
// otherwise check the next middleware
next(err)
}
} else if (arity < 4) {
// process non "error trap" stack
middleware(req, res, function (err) {
nextTick(next, err)
})
} else {
// loop over "error traps" if no error `err` is set.
next()
}
} catch (e) {
next(e)
}
}
})()
} | javascript | function middlewareF (req, res, end) {
var index = 0
// inject stats middleware
if (middlewareF.options && middlewareF.options.stats) {
middlewareF.stack = middlewareF.stack.map(function (mw) {
var fn
if (typeof mw === 'object') {
var key = Object.keys(mw)[0]
if (!mw[key].stats) {
fn = {}
fn[key] = middlewareF.options.stats(mw[key])
}
} else {
if (!mw.stats) {
fn = middlewareF.options.stats(mw)
}
}
return fn
})
}
// looping over all middleware functions defined by stack
;(function next (err) {
var arity
var middleware = middlewareF.stack[index++] // obtain the current middleware from the stack
if (!middleware) {
// we are at the end of the stack
end && end(err)
return
} else {
// extract middleware from object
if (typeof (middleware) === 'object') {
var name = Object.keys(middleware)[0]
if (typeof (middleware[name]) === 'function') {
middleware = middleware[name]
} else {
middleware = function (req, res, next) {
next(new Error('missing middleware'))
}
}
}
try {
arity = middleware.length // number of arguments function middleware requires
// handle errors
if (err) {
// If the middleware function contains 4 arguments than this will act as an "error trap"
if (arity === 4) {
middleware(err, req, res, function (err) {
nextTick(next, err)
})
} else {
// otherwise check the next middleware
next(err)
}
} else if (arity < 4) {
// process non "error trap" stack
middleware(req, res, function (err) {
nextTick(next, err)
})
} else {
// loop over "error traps" if no error `err` is set.
next()
}
} catch (e) {
next(e)
}
}
})()
} | [
"function",
"middlewareF",
"(",
"req",
",",
"res",
",",
"end",
")",
"{",
"var",
"index",
"=",
"0",
"// inject stats middleware",
"if",
"(",
"middlewareF",
".",
"options",
"&&",
"middlewareF",
".",
"options",
".",
"stats",
")",
"{",
"middlewareF",
".",
"stack",
"=",
"middlewareF",
".",
"stack",
".",
"map",
"(",
"function",
"(",
"mw",
")",
"{",
"var",
"fn",
"if",
"(",
"typeof",
"mw",
"===",
"'object'",
")",
"{",
"var",
"key",
"=",
"Object",
".",
"keys",
"(",
"mw",
")",
"[",
"0",
"]",
"if",
"(",
"!",
"mw",
"[",
"key",
"]",
".",
"stats",
")",
"{",
"fn",
"=",
"{",
"}",
"fn",
"[",
"key",
"]",
"=",
"middlewareF",
".",
"options",
".",
"stats",
"(",
"mw",
"[",
"key",
"]",
")",
"}",
"}",
"else",
"{",
"if",
"(",
"!",
"mw",
".",
"stats",
")",
"{",
"fn",
"=",
"middlewareF",
".",
"options",
".",
"stats",
"(",
"mw",
")",
"}",
"}",
"return",
"fn",
"}",
")",
"}",
"// looping over all middleware functions defined by stack",
";",
"(",
"function",
"next",
"(",
"err",
")",
"{",
"var",
"arity",
"var",
"middleware",
"=",
"middlewareF",
".",
"stack",
"[",
"index",
"++",
"]",
"// obtain the current middleware from the stack",
"if",
"(",
"!",
"middleware",
")",
"{",
"// we are at the end of the stack",
"end",
"&&",
"end",
"(",
"err",
")",
"return",
"}",
"else",
"{",
"// extract middleware from object",
"if",
"(",
"typeof",
"(",
"middleware",
")",
"===",
"'object'",
")",
"{",
"var",
"name",
"=",
"Object",
".",
"keys",
"(",
"middleware",
")",
"[",
"0",
"]",
"if",
"(",
"typeof",
"(",
"middleware",
"[",
"name",
"]",
")",
"===",
"'function'",
")",
"{",
"middleware",
"=",
"middleware",
"[",
"name",
"]",
"}",
"else",
"{",
"middleware",
"=",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"next",
"(",
"new",
"Error",
"(",
"'missing middleware'",
")",
")",
"}",
"}",
"}",
"try",
"{",
"arity",
"=",
"middleware",
".",
"length",
"// number of arguments function middleware requires",
"// handle errors",
"if",
"(",
"err",
")",
"{",
"// If the middleware function contains 4 arguments than this will act as an \"error trap\"",
"if",
"(",
"arity",
"===",
"4",
")",
"{",
"middleware",
"(",
"err",
",",
"req",
",",
"res",
",",
"function",
"(",
"err",
")",
"{",
"nextTick",
"(",
"next",
",",
"err",
")",
"}",
")",
"}",
"else",
"{",
"// otherwise check the next middleware",
"next",
"(",
"err",
")",
"}",
"}",
"else",
"if",
"(",
"arity",
"<",
"4",
")",
"{",
"// process non \"error trap\" stack",
"middleware",
"(",
"req",
",",
"res",
",",
"function",
"(",
"err",
")",
"{",
"nextTick",
"(",
"next",
",",
"err",
")",
"}",
")",
"}",
"else",
"{",
"// loop over \"error traps\" if no error `err` is set.",
"next",
"(",
")",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"next",
"(",
"e",
")",
"}",
"}",
"}",
")",
"(",
")",
"}"
] | the function required by the server | [
"the",
"function",
"required",
"by",
"the",
"server"
] | 810dbd1c7d3095598ec4a4fa771b9d55e037fb57 | https://github.com/commenthol/connect-composer/blob/810dbd1c7d3095598ec4a4fa771b9d55e037fb57/lib/compose.js#L33-L104 |
54,575 | okramolis/dirio | lib/dirio.js | _write | function _write(dest, source, callback) {
var itemPath = path.join(dest, source.name);
// switch according to type of the current root item
switch(source.type) {
case TYPE_FILE:
if (source.data instanceof stream.Readable) {
// stream data => pipe it to destination stream
source.data.pipe(fs.createWriteStream(itemPath));
source.data.on('end', callback);
return;
}
// write data to the file as a string or a buffer
return fs.writeFile(
itemPath,
(typeof source.data === 'undefined' || source.data === null) ? '' : source.data,
callback
);
case TYPE_FOLDER:
return fs.mkdir(itemPath, _folderWritten.bind(null, itemPath, source, callback));
case TYPE_ALIAS:
return fs.symlink(source.orig, itemPath, callback);
default:
// ignore unknown type
return callback();
}
} | javascript | function _write(dest, source, callback) {
var itemPath = path.join(dest, source.name);
// switch according to type of the current root item
switch(source.type) {
case TYPE_FILE:
if (source.data instanceof stream.Readable) {
// stream data => pipe it to destination stream
source.data.pipe(fs.createWriteStream(itemPath));
source.data.on('end', callback);
return;
}
// write data to the file as a string or a buffer
return fs.writeFile(
itemPath,
(typeof source.data === 'undefined' || source.data === null) ? '' : source.data,
callback
);
case TYPE_FOLDER:
return fs.mkdir(itemPath, _folderWritten.bind(null, itemPath, source, callback));
case TYPE_ALIAS:
return fs.symlink(source.orig, itemPath, callback);
default:
// ignore unknown type
return callback();
}
} | [
"function",
"_write",
"(",
"dest",
",",
"source",
",",
"callback",
")",
"{",
"var",
"itemPath",
"=",
"path",
".",
"join",
"(",
"dest",
",",
"source",
".",
"name",
")",
";",
"// switch according to type of the current root item",
"switch",
"(",
"source",
".",
"type",
")",
"{",
"case",
"TYPE_FILE",
":",
"if",
"(",
"source",
".",
"data",
"instanceof",
"stream",
".",
"Readable",
")",
"{",
"// stream data => pipe it to destination stream",
"source",
".",
"data",
".",
"pipe",
"(",
"fs",
".",
"createWriteStream",
"(",
"itemPath",
")",
")",
";",
"source",
".",
"data",
".",
"on",
"(",
"'end'",
",",
"callback",
")",
";",
"return",
";",
"}",
"// write data to the file as a string or a buffer",
"return",
"fs",
".",
"writeFile",
"(",
"itemPath",
",",
"(",
"typeof",
"source",
".",
"data",
"===",
"'undefined'",
"||",
"source",
".",
"data",
"===",
"null",
")",
"?",
"''",
":",
"source",
".",
"data",
",",
"callback",
")",
";",
"case",
"TYPE_FOLDER",
":",
"return",
"fs",
".",
"mkdir",
"(",
"itemPath",
",",
"_folderWritten",
".",
"bind",
"(",
"null",
",",
"itemPath",
",",
"source",
",",
"callback",
")",
")",
";",
"case",
"TYPE_ALIAS",
":",
"return",
"fs",
".",
"symlink",
"(",
"source",
".",
"orig",
",",
"itemPath",
",",
"callback",
")",
";",
"default",
":",
"// ignore unknown type",
"return",
"callback",
"(",
")",
";",
"}",
"}"
] | Writes fs structure according to provided source object.
@param {String} dest - Path to destination location on file system.
@param {Object} source - Description of the structure to be created.
@param {Function} callback - Callback that expects only a possible
error. | [
"Writes",
"fs",
"structure",
"according",
"to",
"provided",
"source",
"object",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L30-L55 |
54,576 | okramolis/dirio | lib/dirio.js | _folderWritten | function _folderWritten(dest, source, callback, err) {
if (err) return callback(err);
async.each(source.children, _write.bind(null, dest), callback);
} | javascript | function _folderWritten(dest, source, callback, err) {
if (err) return callback(err);
async.each(source.children, _write.bind(null, dest), callback);
} | [
"function",
"_folderWritten",
"(",
"dest",
",",
"source",
",",
"callback",
",",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"async",
".",
"each",
"(",
"source",
".",
"children",
",",
"_write",
".",
"bind",
"(",
"null",
",",
"dest",
")",
",",
"callback",
")",
";",
"}"
] | Ensures each child of source object may write its data.
@param {String} dest - Path of current directory from the child's
point of view.
@param {Object} source - Description of the current structure to
be created.
@param {Function} callback - Callback that expects only a possible
error.
@param {*} err - Possible error passed by caller. | [
"Ensures",
"each",
"child",
"of",
"source",
"object",
"may",
"write",
"its",
"data",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L67-L70 |
54,577 | okramolis/dirio | lib/dirio.js | _read | function _read(stat, source, callback) {
stat(source, _pathStated.bind(null, {}, stat, source, callback));
} | javascript | function _read(stat, source, callback) {
stat(source, _pathStated.bind(null, {}, stat, source, callback));
} | [
"function",
"_read",
"(",
"stat",
",",
"source",
",",
"callback",
")",
"{",
"stat",
"(",
"source",
",",
"_pathStated",
".",
"bind",
"(",
"null",
",",
"{",
"}",
",",
"stat",
",",
"source",
",",
"callback",
")",
")",
";",
"}"
] | Reads path and builds json-comaptible object representing content
of the path.
@param {Function} stat - Function of fs module fs.stat or fs.lstat.
@param {String} source - Path to source location on file system.
@param {Function} callback - Callback that expects a possible error
and the result. | [
"Reads",
"path",
"and",
"builds",
"json",
"-",
"comaptible",
"object",
"representing",
"content",
"of",
"the",
"path",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L80-L82 |
54,578 | okramolis/dirio | lib/dirio.js | _pathStated | function _pathStated(item, stat, stated, callback, err, stats) {
if (err) return callback(err);
item.name = path.basename(stated);
if (stats.isFile()) {
item.type = TYPE_FILE;
// TODO set encoding according to the read file content or user preferences
return fs.readFile(stated, {encoding: 'utf8'}, _fileRead.bind(null, item, callback));
}
if (stats.isDirectory()) {
item.type = TYPE_FOLDER;
return fs.readdir(stated, _folderRead.bind(null, item, stat, stated, callback));
}
if (stats.isSymbolicLink()) {
item.type = TYPE_ALIAS;
return fs.readlink(stated, _aliasRead.bind(null, item, callback));
}
// not supported type
item.type = TYPE_UNKNOWN;
callback(null, item);
} | javascript | function _pathStated(item, stat, stated, callback, err, stats) {
if (err) return callback(err);
item.name = path.basename(stated);
if (stats.isFile()) {
item.type = TYPE_FILE;
// TODO set encoding according to the read file content or user preferences
return fs.readFile(stated, {encoding: 'utf8'}, _fileRead.bind(null, item, callback));
}
if (stats.isDirectory()) {
item.type = TYPE_FOLDER;
return fs.readdir(stated, _folderRead.bind(null, item, stat, stated, callback));
}
if (stats.isSymbolicLink()) {
item.type = TYPE_ALIAS;
return fs.readlink(stated, _aliasRead.bind(null, item, callback));
}
// not supported type
item.type = TYPE_UNKNOWN;
callback(null, item);
} | [
"function",
"_pathStated",
"(",
"item",
",",
"stat",
",",
"stated",
",",
"callback",
",",
"err",
",",
"stats",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"item",
".",
"name",
"=",
"path",
".",
"basename",
"(",
"stated",
")",
";",
"if",
"(",
"stats",
".",
"isFile",
"(",
")",
")",
"{",
"item",
".",
"type",
"=",
"TYPE_FILE",
";",
"// TODO set encoding according to the read file content or user preferences",
"return",
"fs",
".",
"readFile",
"(",
"stated",
",",
"{",
"encoding",
":",
"'utf8'",
"}",
",",
"_fileRead",
".",
"bind",
"(",
"null",
",",
"item",
",",
"callback",
")",
")",
";",
"}",
"if",
"(",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"item",
".",
"type",
"=",
"TYPE_FOLDER",
";",
"return",
"fs",
".",
"readdir",
"(",
"stated",
",",
"_folderRead",
".",
"bind",
"(",
"null",
",",
"item",
",",
"stat",
",",
"stated",
",",
"callback",
")",
")",
";",
"}",
"if",
"(",
"stats",
".",
"isSymbolicLink",
"(",
")",
")",
"{",
"item",
".",
"type",
"=",
"TYPE_ALIAS",
";",
"return",
"fs",
".",
"readlink",
"(",
"stated",
",",
"_aliasRead",
".",
"bind",
"(",
"null",
",",
"item",
",",
"callback",
")",
")",
";",
"}",
"// not supported type",
"item",
".",
"type",
"=",
"TYPE_UNKNOWN",
";",
"callback",
"(",
"null",
",",
"item",
")",
";",
"}"
] | Investigates stats of a path and continues according to stats type.
Supported types are file, directory, symbolic link.
@param {Object} item - Object that is supposed to be updated with
discovered data.
@param {Function} stat - Function of fs module fs.stat or fs.lstat.
@param {String} stated - The investigated path on file system.
@param {Function} callback - Callback that expects a possible error
and the result.
@param {*} err - Possible error passed by caller.
@param {fs.Stats} stats - Metadata of the path. | [
"Investigates",
"stats",
"of",
"a",
"path",
"and",
"continues",
"according",
"to",
"stats",
"type",
".",
"Supported",
"types",
"are",
"file",
"directory",
"symbolic",
"link",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L96-L117 |
54,579 | okramolis/dirio | lib/dirio.js | _fileRead | function _fileRead(item, callback, err, data) {
if (err) return callback(err);
item.data = data;
callback(null, item);
} | javascript | function _fileRead(item, callback, err, data) {
if (err) return callback(err);
item.data = data;
callback(null, item);
} | [
"function",
"_fileRead",
"(",
"item",
",",
"callback",
",",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"item",
".",
"data",
"=",
"data",
";",
"callback",
"(",
"null",
",",
"item",
")",
";",
"}"
] | Updates the item with content of the file.
@param {Object} item - Object representing investigated file.
@param {Function} callback - Callback that expects a possible
error and the item.
@param {*} err - Possible error passed by caller.
@param {Buffer} file - Content of the file. | [
"Updates",
"the",
"item",
"with",
"content",
"of",
"the",
"file",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L127-L131 |
54,580 | okramolis/dirio | lib/dirio.js | _folderRead | function _folderRead(item, stat, dirpath, callback, err, files) {
if (err) return callback(err);
async.map(
files,
_readChild.bind(null, stat, dirpath),
_childrenRead.bind(null, item, callback)
);
} | javascript | function _folderRead(item, stat, dirpath, callback, err, files) {
if (err) return callback(err);
async.map(
files,
_readChild.bind(null, stat, dirpath),
_childrenRead.bind(null, item, callback)
);
} | [
"function",
"_folderRead",
"(",
"item",
",",
"stat",
",",
"dirpath",
",",
"callback",
",",
"err",
",",
"files",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"async",
".",
"map",
"(",
"files",
",",
"_readChild",
".",
"bind",
"(",
"null",
",",
"stat",
",",
"dirpath",
")",
",",
"_childrenRead",
".",
"bind",
"(",
"null",
",",
"item",
",",
"callback",
")",
")",
";",
"}"
] | Ensures each child of the read directory may provide its data.
@param {Object} item - Object that is supposed to be updated with
discovered data.
@param {Function} stat - Function of fs module fs.stat or fs.lstat.
@param {String} dirpath - Path of the read directory on file system.
@param {Function} callback - Callback that expects a possible error
and array of child data.
@param {*} err - Possible error passed by caller.
@param {String[]} files - List of file names contained in the
directory. | [
"Ensures",
"each",
"child",
"of",
"the",
"read",
"directory",
"may",
"provide",
"its",
"data",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L145-L152 |
54,581 | okramolis/dirio | lib/dirio.js | _readChild | function _readChild(stat, dirpath, name, callback) {
_read(stat, path.join(dirpath, name), callback);
} | javascript | function _readChild(stat, dirpath, name, callback) {
_read(stat, path.join(dirpath, name), callback);
} | [
"function",
"_readChild",
"(",
"stat",
",",
"dirpath",
",",
"name",
",",
"callback",
")",
"{",
"_read",
"(",
"stat",
",",
"path",
".",
"join",
"(",
"dirpath",
",",
"name",
")",
",",
"callback",
")",
";",
"}"
] | Ensures the child of the parent directory may provide its data.
@param {Function} stat - Function of fs module fs.stat or fs.lstat.
@param {String} dirpath - Path of the parent directory on file system.
@param {String} name - File name of the child.
@param {Function} callback - Callback that expects a possible error
and child data. | [
"Ensures",
"the",
"child",
"of",
"the",
"parent",
"directory",
"may",
"provide",
"its",
"data",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L162-L164 |
54,582 | okramolis/dirio | lib/dirio.js | _aliasRead | function _aliasRead(item, callback, err, orig) {
if (err) return callback(err);
item.orig = orig;
callback(null, item);
} | javascript | function _aliasRead(item, callback, err, orig) {
if (err) return callback(err);
item.orig = orig;
callback(null, item);
} | [
"function",
"_aliasRead",
"(",
"item",
",",
"callback",
",",
"err",
",",
"orig",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"item",
".",
"orig",
"=",
"orig",
";",
"callback",
"(",
"null",
",",
"item",
")",
";",
"}"
] | Updates the item with path to its original file.
@param {Object} item - Object representing investigated symbolic link.
@param {Function} callback - Callback that expects a possible error
and the item.
@param {*} err - Possible error passed by caller.
@param {String} orig - Content of the symbolic link. | [
"Updates",
"the",
"item",
"with",
"path",
"to",
"its",
"original",
"file",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L188-L192 |
54,583 | okramolis/dirio | lib/dirio.js | _store | function _store(dest, source, callback) {
fs.writeFile(dest, JSON.stringify(source), callback);
} | javascript | function _store(dest, source, callback) {
fs.writeFile(dest, JSON.stringify(source), callback);
} | [
"function",
"_store",
"(",
"dest",
",",
"source",
",",
"callback",
")",
"{",
"fs",
".",
"writeFile",
"(",
"dest",
",",
"JSON",
".",
"stringify",
"(",
"source",
")",
",",
"callback",
")",
";",
"}"
] | Stores json-compatible object on file system at provided path as
a json file.
@param {String} dest - File system path of the new file.
@param {Object} source - The object to be stored.
@param {Function} callback - Callback that expects only a possible error. | [
"Stores",
"json",
"-",
"compatible",
"object",
"on",
"file",
"system",
"at",
"provided",
"path",
"as",
"a",
"json",
"file",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L201-L203 |
54,584 | okramolis/dirio | lib/dirio.js | _load | function _load(source, callback) {
fs.readFile(source, {encoding: 'utf8'}, _jsonLoaded.bind(null, callback));
} | javascript | function _load(source, callback) {
fs.readFile(source, {encoding: 'utf8'}, _jsonLoaded.bind(null, callback));
} | [
"function",
"_load",
"(",
"source",
",",
"callback",
")",
"{",
"fs",
".",
"readFile",
"(",
"source",
",",
"{",
"encoding",
":",
"'utf8'",
"}",
",",
"_jsonLoaded",
".",
"bind",
"(",
"null",
",",
"callback",
")",
")",
";",
"}"
] | Reads json file and parses its data.
@param {String} source - File system path of the source json file.
@param {Function} callback - Callback that expects a possible error
and the result. | [
"Reads",
"json",
"file",
"and",
"parses",
"its",
"data",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L211-L213 |
54,585 | okramolis/dirio | lib/dirio.js | _jsonLoaded | function _jsonLoaded(callback, err, data) {
if (err) return callback(err);
var parsed;
try {
parsed = JSON.parse(data);
} catch(jerr) {
return callback(jerr);
}
callback(null, parsed);
} | javascript | function _jsonLoaded(callback, err, data) {
if (err) return callback(err);
var parsed;
try {
parsed = JSON.parse(data);
} catch(jerr) {
return callback(jerr);
}
callback(null, parsed);
} | [
"function",
"_jsonLoaded",
"(",
"callback",
",",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"var",
"parsed",
";",
"try",
"{",
"parsed",
"=",
"JSON",
".",
"parse",
"(",
"data",
")",
";",
"}",
"catch",
"(",
"jerr",
")",
"{",
"return",
"callback",
"(",
"jerr",
")",
";",
"}",
"callback",
"(",
"null",
",",
"parsed",
")",
";",
"}"
] | Parses content of a json file.
@param {Function} callback - Callback that expects a possible error
and the result.
@param {*} err - Possible error passed by caller.
@param {String} data - Content of the file. | [
"Parses",
"content",
"of",
"a",
"json",
"file",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L222-L231 |
54,586 | okramolis/dirio | lib/dirio.js | _load2write | function _load2write(dest, source, callback) {
_load(source, _pipe.bind(null, _write.bind(null, dest), callback));
} | javascript | function _load2write(dest, source, callback) {
_load(source, _pipe.bind(null, _write.bind(null, dest), callback));
} | [
"function",
"_load2write",
"(",
"dest",
",",
"source",
",",
"callback",
")",
"{",
"_load",
"(",
"source",
",",
"_pipe",
".",
"bind",
"(",
"null",
",",
"_write",
".",
"bind",
"(",
"null",
",",
"dest",
")",
",",
"callback",
")",
")",
";",
"}"
] | Loads json source file and creates fs structure according to the
loaded data.
This is high level utility. It pipes result of _load to _write.
@param {String} dest - Path to destination location on file system.
@param {String} source - File system path of the source json file.
@param {Function} callback - Callback that expects only a possible
error. | [
"Loads",
"json",
"source",
"file",
"and",
"creates",
"fs",
"structure",
"according",
"to",
"the",
"loaded",
"data",
".",
"This",
"is",
"high",
"level",
"utility",
".",
"It",
"pipes",
"result",
"of",
"_load",
"to",
"_write",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L242-L244 |
54,587 | okramolis/dirio | lib/dirio.js | _read2store | function _read2store(stat, dest, source, callback) {
_read(stat, source, _pipe.bind(null, _store.bind(null, dest), callback));
} | javascript | function _read2store(stat, dest, source, callback) {
_read(stat, source, _pipe.bind(null, _store.bind(null, dest), callback));
} | [
"function",
"_read2store",
"(",
"stat",
",",
"dest",
",",
"source",
",",
"callback",
")",
"{",
"_read",
"(",
"stat",
",",
"source",
",",
"_pipe",
".",
"bind",
"(",
"null",
",",
"_store",
".",
"bind",
"(",
"null",
",",
"dest",
")",
",",
"callback",
")",
")",
";",
"}"
] | Analyzes fs structure and stores the data in json file.
This is high level utility. It pipes result of _read to _store.
@param {Function} stat - Function of fs module fs.stat or fs.lstat.
@param {String} dest - File system path of the new file.
@param {String} source - Path to source location on file system.
@param {Function} callback - Callback that expects only a possible
error. | [
"Analyzes",
"fs",
"structure",
"and",
"stores",
"the",
"data",
"in",
"json",
"file",
".",
"This",
"is",
"high",
"level",
"utility",
".",
"It",
"pipes",
"result",
"of",
"_read",
"to",
"_store",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L255-L257 |
54,588 | okramolis/dirio | lib/dirio.js | _pipe | function _pipe(out, callback, err, iresult) {
if (err) return callback(err);
out(iresult, callback);
} | javascript | function _pipe(out, callback, err, iresult) {
if (err) return callback(err);
out(iresult, callback);
} | [
"function",
"_pipe",
"(",
"out",
",",
"callback",
",",
"err",
",",
"iresult",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"out",
"(",
"iresult",
",",
"callback",
")",
";",
"}"
] | Used to pipe input operation to output operation.
@param {Function} out - Output operation.
@param {Function} callback - Callback that expects only
a possible error.
@param {*} err - Possible error passed by caller.
@param {Object} iresult - Result of the input operation. | [
"Used",
"to",
"pipe",
"input",
"operation",
"to",
"output",
"operation",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L267-L270 |
54,589 | okramolis/dirio | lib/dirio.js | _handleConvert | function _handleConvert(stat, dest, source, callback) {
// "dest" arg is optional
if (typeof source === 'function') {
callback = source;
source = dest;
dest = null;
}
// assert input params
assert.ok(
dest === null || typeof dest === 'string',
'Invalid type of argument "dest", expected "null" or "string", ' +
'but is "' + (typeof dest) + '"'
);
assert.equal(
typeof(callback),
'function',
'Invalid type of argument "callback", expected "function", ' +
'but is "' + (typeof callback) + '"'
);
// perform an action according to "source" and "dest"
switch(typeof source) {
case 'string':
// source is a path
if (_isJsonPath(source)) {
// source is meant to be a json file
if (typeof dest === 'string') {
// destination is meant to be a directory
return _load2write(dest, source, callback);
}
// destination is meant to be a local object
return _load(source, callback);
}
// source is meant to be a directory
if (typeof dest === 'string') {
// destination is meant to be a json file
return _read2store(stat, dest, source, callback);
}
// destination is meant to be a local object
return _read(stat, source, callback);
case 'object':
// source is an object
if (_isJsonPath(dest)) {
// destination is meant to be a json file
return _store(dest, source, callback);
}
// destination is meant to be a directory
return _write(dest, source, callback);
default:
// invalid source
assert.ok(
false,
'Invalid type of argument "source", expected "string" or "object", ' +
'but is "' + (typeof source) + '"'
);
}
} | javascript | function _handleConvert(stat, dest, source, callback) {
// "dest" arg is optional
if (typeof source === 'function') {
callback = source;
source = dest;
dest = null;
}
// assert input params
assert.ok(
dest === null || typeof dest === 'string',
'Invalid type of argument "dest", expected "null" or "string", ' +
'but is "' + (typeof dest) + '"'
);
assert.equal(
typeof(callback),
'function',
'Invalid type of argument "callback", expected "function", ' +
'but is "' + (typeof callback) + '"'
);
// perform an action according to "source" and "dest"
switch(typeof source) {
case 'string':
// source is a path
if (_isJsonPath(source)) {
// source is meant to be a json file
if (typeof dest === 'string') {
// destination is meant to be a directory
return _load2write(dest, source, callback);
}
// destination is meant to be a local object
return _load(source, callback);
}
// source is meant to be a directory
if (typeof dest === 'string') {
// destination is meant to be a json file
return _read2store(stat, dest, source, callback);
}
// destination is meant to be a local object
return _read(stat, source, callback);
case 'object':
// source is an object
if (_isJsonPath(dest)) {
// destination is meant to be a json file
return _store(dest, source, callback);
}
// destination is meant to be a directory
return _write(dest, source, callback);
default:
// invalid source
assert.ok(
false,
'Invalid type of argument "source", expected "string" or "object", ' +
'but is "' + (typeof source) + '"'
);
}
} | [
"function",
"_handleConvert",
"(",
"stat",
",",
"dest",
",",
"source",
",",
"callback",
")",
"{",
"// \"dest\" arg is optional",
"if",
"(",
"typeof",
"source",
"===",
"'function'",
")",
"{",
"callback",
"=",
"source",
";",
"source",
"=",
"dest",
";",
"dest",
"=",
"null",
";",
"}",
"// assert input params",
"assert",
".",
"ok",
"(",
"dest",
"===",
"null",
"||",
"typeof",
"dest",
"===",
"'string'",
",",
"'Invalid type of argument \"dest\", expected \"null\" or \"string\", '",
"+",
"'but is \"'",
"+",
"(",
"typeof",
"dest",
")",
"+",
"'\"'",
")",
";",
"assert",
".",
"equal",
"(",
"typeof",
"(",
"callback",
")",
",",
"'function'",
",",
"'Invalid type of argument \"callback\", expected \"function\", '",
"+",
"'but is \"'",
"+",
"(",
"typeof",
"callback",
")",
"+",
"'\"'",
")",
";",
"// perform an action according to \"source\" and \"dest\"",
"switch",
"(",
"typeof",
"source",
")",
"{",
"case",
"'string'",
":",
"// source is a path",
"if",
"(",
"_isJsonPath",
"(",
"source",
")",
")",
"{",
"// source is meant to be a json file",
"if",
"(",
"typeof",
"dest",
"===",
"'string'",
")",
"{",
"// destination is meant to be a directory",
"return",
"_load2write",
"(",
"dest",
",",
"source",
",",
"callback",
")",
";",
"}",
"// destination is meant to be a local object",
"return",
"_load",
"(",
"source",
",",
"callback",
")",
";",
"}",
"// source is meant to be a directory",
"if",
"(",
"typeof",
"dest",
"===",
"'string'",
")",
"{",
"// destination is meant to be a json file",
"return",
"_read2store",
"(",
"stat",
",",
"dest",
",",
"source",
",",
"callback",
")",
";",
"}",
"// destination is meant to be a local object",
"return",
"_read",
"(",
"stat",
",",
"source",
",",
"callback",
")",
";",
"case",
"'object'",
":",
"// source is an object",
"if",
"(",
"_isJsonPath",
"(",
"dest",
")",
")",
"{",
"// destination is meant to be a json file",
"return",
"_store",
"(",
"dest",
",",
"source",
",",
"callback",
")",
";",
"}",
"// destination is meant to be a directory",
"return",
"_write",
"(",
"dest",
",",
"source",
",",
"callback",
")",
";",
"default",
":",
"// invalid source",
"assert",
".",
"ok",
"(",
"false",
",",
"'Invalid type of argument \"source\", expected \"string\" or \"object\", '",
"+",
"'but is \"'",
"+",
"(",
"typeof",
"source",
")",
"+",
"'\"'",
")",
";",
"}",
"}"
] | Asserts user input and calls appropriate lower level function to
complete the desired task.
@param {Function} stat - Function of fs module fs.stat or fs.lstat.
@param {String} [dest] - Path to destination location on file system.
@param {String | Object} source - Path to source location on file system
or object directly provided by user.
@param {Function} callback - Callback that expects a possible error
and possible result. | [
"Asserts",
"user",
"input",
"and",
"calls",
"appropriate",
"lower",
"level",
"function",
"to",
"complete",
"the",
"desired",
"task",
"."
] | fe2419e6b0a4e9116f4ae028959b6f0e3a514d21 | https://github.com/okramolis/dirio/blob/fe2419e6b0a4e9116f4ae028959b6f0e3a514d21/lib/dirio.js#L292-L349 |
54,590 | deniszatsepin/rotor-entity | lib/entity.js | Entity | function Entity(param) {
EventEmitter2.apply(this, arguments);
Entity.prototype.init.apply(this, arguments);
} | javascript | function Entity(param) {
EventEmitter2.apply(this, arguments);
Entity.prototype.init.apply(this, arguments);
} | [
"function",
"Entity",
"(",
"param",
")",
"{",
"EventEmitter2",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"Entity",
".",
"prototype",
".",
"init",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}"
] | Entity, basic element in rotor-web engine.
@param {object} param
@param {string} param.name - Entity name. If undefined, name will be 'Entity:id'
@constructor | [
"Entity",
"basic",
"element",
"in",
"rotor",
"-",
"web",
"engine",
"."
] | ec48b4b459452d7361f91042a420c144225788b4 | https://github.com/deniszatsepin/rotor-entity/blob/ec48b4b459452d7361f91042a420c144225788b4/lib/entity.js#L10-L13 |
54,591 | tether/isokay | index.js | validator | function validator (data, schema) {
const result = Object.assign({}, data)
Object.keys(schema).map(key => {
let value = schema[key]
const type = typeof value
if (type !== 'object') {
value = {
transform: value
}
}
validate(value, result, key)
})
return result
} | javascript | function validator (data, schema) {
const result = Object.assign({}, data)
Object.keys(schema).map(key => {
let value = schema[key]
const type = typeof value
if (type !== 'object') {
value = {
transform: value
}
}
validate(value, result, key)
})
return result
} | [
"function",
"validator",
"(",
"data",
",",
"schema",
")",
"{",
"const",
"result",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"data",
")",
"Object",
".",
"keys",
"(",
"schema",
")",
".",
"map",
"(",
"key",
"=>",
"{",
"let",
"value",
"=",
"schema",
"[",
"key",
"]",
"const",
"type",
"=",
"typeof",
"value",
"if",
"(",
"type",
"!==",
"'object'",
")",
"{",
"value",
"=",
"{",
"transform",
":",
"value",
"}",
"}",
"validate",
"(",
"value",
",",
"result",
",",
"key",
")",
"}",
")",
"return",
"result",
"}"
] | Validate object against schema.
@param {Object} data
@param {Object} schema
@return {Object}
@api public | [
"Validate",
"object",
"against",
"schema",
"."
] | 3d40832806712267a213c489db3efde57f21f588 | https://github.com/tether/isokay/blob/3d40832806712267a213c489db3efde57f21f588/index.js#L26-L39 |
54,592 | tether/isokay | index.js | coerce | function coerce (type, field, value) {
let result
if (type === 'string') {
result = String(value).trim()
} else if (type === 'number') {
result = Number(value)
if (isNaN(result)) throw new Error(`field ${field} can not be converted to a number`)
} else if (type === 'array') {
result = [].concat(value)
} else if (type === 'date') {
result = Date.parse(value)
if (isNaN(result)) throw new Error(`field ${field} can not be converted into a date`)
} else if (type === 'boolean') {
result = Boolean(value)
} else if (type === 'object') {
if (typeof value !== 'object') throw new Error(`field ${field} is not an object`)
result = value
}
return result
} | javascript | function coerce (type, field, value) {
let result
if (type === 'string') {
result = String(value).trim()
} else if (type === 'number') {
result = Number(value)
if (isNaN(result)) throw new Error(`field ${field} can not be converted to a number`)
} else if (type === 'array') {
result = [].concat(value)
} else if (type === 'date') {
result = Date.parse(value)
if (isNaN(result)) throw new Error(`field ${field} can not be converted into a date`)
} else if (type === 'boolean') {
result = Boolean(value)
} else if (type === 'object') {
if (typeof value !== 'object') throw new Error(`field ${field} is not an object`)
result = value
}
return result
} | [
"function",
"coerce",
"(",
"type",
",",
"field",
",",
"value",
")",
"{",
"let",
"result",
"if",
"(",
"type",
"===",
"'string'",
")",
"{",
"result",
"=",
"String",
"(",
"value",
")",
".",
"trim",
"(",
")",
"}",
"else",
"if",
"(",
"type",
"===",
"'number'",
")",
"{",
"result",
"=",
"Number",
"(",
"value",
")",
"if",
"(",
"isNaN",
"(",
"result",
")",
")",
"throw",
"new",
"Error",
"(",
"`",
"${",
"field",
"}",
"`",
")",
"}",
"else",
"if",
"(",
"type",
"===",
"'array'",
")",
"{",
"result",
"=",
"[",
"]",
".",
"concat",
"(",
"value",
")",
"}",
"else",
"if",
"(",
"type",
"===",
"'date'",
")",
"{",
"result",
"=",
"Date",
".",
"parse",
"(",
"value",
")",
"if",
"(",
"isNaN",
"(",
"result",
")",
")",
"throw",
"new",
"Error",
"(",
"`",
"${",
"field",
"}",
"`",
")",
"}",
"else",
"if",
"(",
"type",
"===",
"'boolean'",
")",
"{",
"result",
"=",
"Boolean",
"(",
"value",
")",
"}",
"else",
"if",
"(",
"type",
"===",
"'object'",
")",
"{",
"if",
"(",
"typeof",
"value",
"!==",
"'object'",
")",
"throw",
"new",
"Error",
"(",
"`",
"${",
"field",
"}",
"`",
")",
"result",
"=",
"value",
"}",
"return",
"result",
"}"
] | Coerce value.
Trigger
@param {String} type
@param {String} field name
@param {Any} value
@api private | [
"Coerce",
"value",
"."
] | 3d40832806712267a213c489db3efde57f21f588 | https://github.com/tether/isokay/blob/3d40832806712267a213c489db3efde57f21f588/index.js#L109-L128 |
54,593 | commenthol/streamss | lib/splitline.js | SplitLine | function SplitLine (options) {
if (!(this instanceof SplitLine)) {
return new SplitLine(options)
}
this.options = options || {}
Transform.call(this, _omit(this.options, ['matcher', 'chomp']))
this.offset = 0
this.options.matcher = (typeof this.options.matcher === 'string'
? this.options.matcher.charCodeAt(0)
: this.options.matcher || 0x0a)
this.options.chomp = (this.options.chomp === true ? 0 : 1) // chomp newline
this.buffer = Buffer.from('') // this.unshift cannot be used if options.highWaterMark is quite low!
// That's why an own buffer is required here :/
return this
} | javascript | function SplitLine (options) {
if (!(this instanceof SplitLine)) {
return new SplitLine(options)
}
this.options = options || {}
Transform.call(this, _omit(this.options, ['matcher', 'chomp']))
this.offset = 0
this.options.matcher = (typeof this.options.matcher === 'string'
? this.options.matcher.charCodeAt(0)
: this.options.matcher || 0x0a)
this.options.chomp = (this.options.chomp === true ? 0 : 1) // chomp newline
this.buffer = Buffer.from('') // this.unshift cannot be used if options.highWaterMark is quite low!
// That's why an own buffer is required here :/
return this
} | [
"function",
"SplitLine",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"SplitLine",
")",
")",
"{",
"return",
"new",
"SplitLine",
"(",
"options",
")",
"}",
"this",
".",
"options",
"=",
"options",
"||",
"{",
"}",
"Transform",
".",
"call",
"(",
"this",
",",
"_omit",
"(",
"this",
".",
"options",
",",
"[",
"'matcher'",
",",
"'chomp'",
"]",
")",
")",
"this",
".",
"offset",
"=",
"0",
"this",
".",
"options",
".",
"matcher",
"=",
"(",
"typeof",
"this",
".",
"options",
".",
"matcher",
"===",
"'string'",
"?",
"this",
".",
"options",
".",
"matcher",
".",
"charCodeAt",
"(",
"0",
")",
":",
"this",
".",
"options",
".",
"matcher",
"||",
"0x0a",
")",
"this",
".",
"options",
".",
"chomp",
"=",
"(",
"this",
".",
"options",
".",
"chomp",
"===",
"true",
"?",
"0",
":",
"1",
")",
"// chomp newline",
"this",
".",
"buffer",
"=",
"Buffer",
".",
"from",
"(",
"''",
")",
"// this.unshift cannot be used if options.highWaterMark is quite low!",
"// That's why an own buffer is required here :/",
"return",
"this",
"}"
] | Split a stream by a single char
@constructor
@param {Object} [options] - Stream Options `{encoding, highWaterMark, decodeStrings, ...}`
@param {Boolean} options.chomp - Do not emit the matching char. Default=false
@param {String} options.matcher - String use for splitting up the stream. Default=0x0a
@return {Transform} A transform stream | [
"Split",
"a",
"stream",
"by",
"a",
"single",
"char"
] | cfef5d0ed30c7efe002018886e2e843c91d3558f | https://github.com/commenthol/streamss/blob/cfef5d0ed30c7efe002018886e2e843c91d3558f/lib/splitline.js#L21-L37 |
54,594 | brianloveswords/gogo | lib/migration.js | lookup | function lookup(version, migrations) {
var regex = RegExp('^' + version + '.*$');
for (var m in migrations)
if (migrations.hasOwnProperty(m) && m.match(regex)) return m;
return null;
} | javascript | function lookup(version, migrations) {
var regex = RegExp('^' + version + '.*$');
for (var m in migrations)
if (migrations.hasOwnProperty(m) && m.match(regex)) return m;
return null;
} | [
"function",
"lookup",
"(",
"version",
",",
"migrations",
")",
"{",
"var",
"regex",
"=",
"RegExp",
"(",
"'^'",
"+",
"version",
"+",
"'.*$'",
")",
";",
"for",
"(",
"var",
"m",
"in",
"migrations",
")",
"if",
"(",
"migrations",
".",
"hasOwnProperty",
"(",
"m",
")",
"&&",
"m",
".",
"match",
"(",
"regex",
")",
")",
"return",
"m",
";",
"return",
"null",
";",
"}"
] | We need to be able to look up migrations by their numeric identifier without concerning ourselves with the description. | [
"We",
"need",
"to",
"be",
"able",
"to",
"look",
"up",
"migrations",
"by",
"their",
"numeric",
"identifier",
"without",
"concerning",
"ourselves",
"with",
"the",
"description",
"."
] | f17ee794e0439ed961907f52b91bcb74dcca351a | https://github.com/brianloveswords/gogo/blob/f17ee794e0439ed961907f52b91bcb74dcca351a/lib/migration.js#L12-L17 |
54,595 | jkroso/rel-svg-path | index.js | relative | function relative(path){
var startX = 0
var startY = 0
var x = 0
var y = 0
return path.map(function(seg){
seg = seg.slice()
var type = seg[0]
var command = type.toLowerCase()
// is absolute
if (type != command) {
seg[0] = command
switch (type) {
case 'A':
seg[6] -= x
seg[7] -= y
break
case 'V':
seg[1] -= y
break
case 'H':
seg[1] -= x
break
default:
for (var i = 1; i < seg.length;) {
seg[i++] -= x
seg[i++] -= y
}
}
}
// update cursor state
switch (command) {
case 'z':
x = startX
y = startY
break
case 'h':
x += seg[1]
break
case 'v':
y += seg[1]
break
case 'm':
x += seg[1]
y += seg[2]
startX += seg[1]
startY += seg[2]
break
default:
x += seg[seg.length - 2]
y += seg[seg.length - 1]
}
return seg
})
} | javascript | function relative(path){
var startX = 0
var startY = 0
var x = 0
var y = 0
return path.map(function(seg){
seg = seg.slice()
var type = seg[0]
var command = type.toLowerCase()
// is absolute
if (type != command) {
seg[0] = command
switch (type) {
case 'A':
seg[6] -= x
seg[7] -= y
break
case 'V':
seg[1] -= y
break
case 'H':
seg[1] -= x
break
default:
for (var i = 1; i < seg.length;) {
seg[i++] -= x
seg[i++] -= y
}
}
}
// update cursor state
switch (command) {
case 'z':
x = startX
y = startY
break
case 'h':
x += seg[1]
break
case 'v':
y += seg[1]
break
case 'm':
x += seg[1]
y += seg[2]
startX += seg[1]
startY += seg[2]
break
default:
x += seg[seg.length - 2]
y += seg[seg.length - 1]
}
return seg
})
} | [
"function",
"relative",
"(",
"path",
")",
"{",
"var",
"startX",
"=",
"0",
"var",
"startY",
"=",
"0",
"var",
"x",
"=",
"0",
"var",
"y",
"=",
"0",
"return",
"path",
".",
"map",
"(",
"function",
"(",
"seg",
")",
"{",
"seg",
"=",
"seg",
".",
"slice",
"(",
")",
"var",
"type",
"=",
"seg",
"[",
"0",
"]",
"var",
"command",
"=",
"type",
".",
"toLowerCase",
"(",
")",
"// is absolute",
"if",
"(",
"type",
"!=",
"command",
")",
"{",
"seg",
"[",
"0",
"]",
"=",
"command",
"switch",
"(",
"type",
")",
"{",
"case",
"'A'",
":",
"seg",
"[",
"6",
"]",
"-=",
"x",
"seg",
"[",
"7",
"]",
"-=",
"y",
"break",
"case",
"'V'",
":",
"seg",
"[",
"1",
"]",
"-=",
"y",
"break",
"case",
"'H'",
":",
"seg",
"[",
"1",
"]",
"-=",
"x",
"break",
"default",
":",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"seg",
".",
"length",
";",
")",
"{",
"seg",
"[",
"i",
"++",
"]",
"-=",
"x",
"seg",
"[",
"i",
"++",
"]",
"-=",
"y",
"}",
"}",
"}",
"// update cursor state",
"switch",
"(",
"command",
")",
"{",
"case",
"'z'",
":",
"x",
"=",
"startX",
"y",
"=",
"startY",
"break",
"case",
"'h'",
":",
"x",
"+=",
"seg",
"[",
"1",
"]",
"break",
"case",
"'v'",
":",
"y",
"+=",
"seg",
"[",
"1",
"]",
"break",
"case",
"'m'",
":",
"x",
"+=",
"seg",
"[",
"1",
"]",
"y",
"+=",
"seg",
"[",
"2",
"]",
"startX",
"+=",
"seg",
"[",
"1",
"]",
"startY",
"+=",
"seg",
"[",
"2",
"]",
"break",
"default",
":",
"x",
"+=",
"seg",
"[",
"seg",
".",
"length",
"-",
"2",
"]",
"y",
"+=",
"seg",
"[",
"seg",
".",
"length",
"-",
"1",
"]",
"}",
"return",
"seg",
"}",
")",
"}"
] | define `path` using relative points
@param {Array} path
@return {Array} | [
"define",
"path",
"using",
"relative",
"points"
] | faf6f268f31ecd9177191c918634fd8096bb4845 | https://github.com/jkroso/rel-svg-path/blob/faf6f268f31ecd9177191c918634fd8096bb4845/index.js#L11-L69 |
54,596 | shinuza/captain-core | lib/models/posts_tags.js | postGetTags | function postGetTags(id, cb) {
var q =
'SELECT * FROM tags t ' +
'JOIN posts_tags pt ON t.id = pt.tag_id AND pt.post_id = $1';
db.getClient(function(err, client, done) {
client.query(q, [id], function(err, r) {
if(err) {
cb(err);
done(err);
} else {
cb(null, r.rows);
done();
}
});
});
} | javascript | function postGetTags(id, cb) {
var q =
'SELECT * FROM tags t ' +
'JOIN posts_tags pt ON t.id = pt.tag_id AND pt.post_id = $1';
db.getClient(function(err, client, done) {
client.query(q, [id], function(err, r) {
if(err) {
cb(err);
done(err);
} else {
cb(null, r.rows);
done();
}
});
});
} | [
"function",
"postGetTags",
"(",
"id",
",",
"cb",
")",
"{",
"var",
"q",
"=",
"'SELECT * FROM tags t '",
"+",
"'JOIN posts_tags pt ON t.id = pt.tag_id AND pt.post_id = $1'",
";",
"db",
".",
"getClient",
"(",
"function",
"(",
"err",
",",
"client",
",",
"done",
")",
"{",
"client",
".",
"query",
"(",
"q",
",",
"[",
"id",
"]",
",",
"function",
"(",
"err",
",",
"r",
")",
"{",
"if",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"done",
"(",
"err",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"null",
",",
"r",
".",
"rows",
")",
";",
"done",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | Gets tags associated with posts with id `id`
@param {Number} id
@param {Function} cb | [
"Gets",
"tags",
"associated",
"with",
"posts",
"with",
"id",
"id"
] | 02f3a404cdfca608e8726bbacc33e32fec484b21 | https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/posts_tags.js#L106-L122 |
54,597 | shinuza/captain-core | lib/models/posts_tags.js | postSetTags | function postSetTags(post_id, tags, cb) {
var ids = _.pluck(tags, 'id')
, q1 = 'DELETE FROM posts_tags WHERE post_id = $1'
, q2 = 'INSERT INTO posts_tags (post_id, tag_id) VALUES ' +
ids.map(function(id) {
return '(' + post_id + ',' + id + ')';
}).join(', ');
db.getClient(function(err, client, done) {
client.query(q1, [post_id], function(err, r) {
if(err) { return cb(err); }
client.query(q2, function(err, r) {
if(err) {
cb(err);
done(err);
} else {
cb(null, r.rowCount);
done();
}
});
});
});
} | javascript | function postSetTags(post_id, tags, cb) {
var ids = _.pluck(tags, 'id')
, q1 = 'DELETE FROM posts_tags WHERE post_id = $1'
, q2 = 'INSERT INTO posts_tags (post_id, tag_id) VALUES ' +
ids.map(function(id) {
return '(' + post_id + ',' + id + ')';
}).join(', ');
db.getClient(function(err, client, done) {
client.query(q1, [post_id], function(err, r) {
if(err) { return cb(err); }
client.query(q2, function(err, r) {
if(err) {
cb(err);
done(err);
} else {
cb(null, r.rowCount);
done();
}
});
});
});
} | [
"function",
"postSetTags",
"(",
"post_id",
",",
"tags",
",",
"cb",
")",
"{",
"var",
"ids",
"=",
"_",
".",
"pluck",
"(",
"tags",
",",
"'id'",
")",
",",
"q1",
"=",
"'DELETE FROM posts_tags WHERE post_id = $1'",
",",
"q2",
"=",
"'INSERT INTO posts_tags (post_id, tag_id) VALUES '",
"+",
"ids",
".",
"map",
"(",
"function",
"(",
"id",
")",
"{",
"return",
"'('",
"+",
"post_id",
"+",
"','",
"+",
"id",
"+",
"')'",
";",
"}",
")",
".",
"join",
"(",
"', '",
")",
";",
"db",
".",
"getClient",
"(",
"function",
"(",
"err",
",",
"client",
",",
"done",
")",
"{",
"client",
".",
"query",
"(",
"q1",
",",
"[",
"post_id",
"]",
",",
"function",
"(",
"err",
",",
"r",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"client",
".",
"query",
"(",
"q2",
",",
"function",
"(",
"err",
",",
"r",
")",
"{",
"if",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"done",
"(",
"err",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"null",
",",
"r",
".",
"rowCount",
")",
";",
"done",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Removes existing association and associates `tags` with post with id `post_id`
@param {Number} post_id
@param {Array} tags
@param {Function} cb | [
"Removes",
"existing",
"association",
"and",
"associates",
"tags",
"with",
"post",
"with",
"id",
"post_id"
] | 02f3a404cdfca608e8726bbacc33e32fec484b21 | https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/posts_tags.js#L133-L155 |
54,598 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/plugins/magicline/plugin.js | checkMouse | function checkMouse( mouse ) {
that.debug.groupStart( 'CheckMouse' ); // %REMOVE_LINE%
that.debug.startTimer(); // %REMOVE_LINE%
that.mouse = mouse;
that.trigger = null;
checkMouseTimer = null;
updateWindowSize( that );
if ( checkMouseTimeoutPending // -> There must be an event pending.
&& !that.hiddenMode // -> Can't be in hidden mode.
&& editor.focusManager.hasFocus // -> Editor must have focus.
&& !that.line.mouseNear() // -> Mouse pointer can't be close to the box.
&& ( that.element = elementFromMouse( that, true ) ) ) // -> There must be valid element.
{
// If trigger exists, and trigger is correct -> show the box.
// Don't show the line if trigger is a descendant of some tabu-list element.
if ( ( that.trigger = triggerEditable( that ) || triggerEdge( that ) || triggerExpand( that ) ) &&
!isInTabu( that, that.trigger.upper || that.trigger.lower ) ) {
that.line.attach().place();
}
// Otherwise remove the box
else {
that.trigger = null;
that.line.detach();
}
that.debug.showTrigger( that.trigger ); // %REMOVE_LINE%
that.debug.mousePos( mouse.y, that.element ); // %REMOVE_LINE%
checkMouseTimeoutPending = false;
}
that.debug.stopTimer(); // %REMOVE_LINE%
that.debug.groupEnd(); // %REMOVE_LINE%
} | javascript | function checkMouse( mouse ) {
that.debug.groupStart( 'CheckMouse' ); // %REMOVE_LINE%
that.debug.startTimer(); // %REMOVE_LINE%
that.mouse = mouse;
that.trigger = null;
checkMouseTimer = null;
updateWindowSize( that );
if ( checkMouseTimeoutPending // -> There must be an event pending.
&& !that.hiddenMode // -> Can't be in hidden mode.
&& editor.focusManager.hasFocus // -> Editor must have focus.
&& !that.line.mouseNear() // -> Mouse pointer can't be close to the box.
&& ( that.element = elementFromMouse( that, true ) ) ) // -> There must be valid element.
{
// If trigger exists, and trigger is correct -> show the box.
// Don't show the line if trigger is a descendant of some tabu-list element.
if ( ( that.trigger = triggerEditable( that ) || triggerEdge( that ) || triggerExpand( that ) ) &&
!isInTabu( that, that.trigger.upper || that.trigger.lower ) ) {
that.line.attach().place();
}
// Otherwise remove the box
else {
that.trigger = null;
that.line.detach();
}
that.debug.showTrigger( that.trigger ); // %REMOVE_LINE%
that.debug.mousePos( mouse.y, that.element ); // %REMOVE_LINE%
checkMouseTimeoutPending = false;
}
that.debug.stopTimer(); // %REMOVE_LINE%
that.debug.groupEnd(); // %REMOVE_LINE%
} | [
"function",
"checkMouse",
"(",
"mouse",
")",
"{",
"that",
".",
"debug",
".",
"groupStart",
"(",
"'CheckMouse'",
")",
";",
"// %REMOVE_LINE%\r",
"that",
".",
"debug",
".",
"startTimer",
"(",
")",
";",
"// %REMOVE_LINE%\r",
"that",
".",
"mouse",
"=",
"mouse",
";",
"that",
".",
"trigger",
"=",
"null",
";",
"checkMouseTimer",
"=",
"null",
";",
"updateWindowSize",
"(",
"that",
")",
";",
"if",
"(",
"checkMouseTimeoutPending",
"//\t-> There must be an event pending.\r",
"&&",
"!",
"that",
".",
"hiddenMode",
"// \t-> Can't be in hidden mode.\r",
"&&",
"editor",
".",
"focusManager",
".",
"hasFocus",
"// \t-> Editor must have focus.\r",
"&&",
"!",
"that",
".",
"line",
".",
"mouseNear",
"(",
")",
"// \t-> Mouse pointer can't be close to the box.\r",
"&&",
"(",
"that",
".",
"element",
"=",
"elementFromMouse",
"(",
"that",
",",
"true",
")",
")",
")",
"// \t-> There must be valid element.\r",
"{",
"// If trigger exists, and trigger is correct -> show the box.\r",
"// Don't show the line if trigger is a descendant of some tabu-list element.\r",
"if",
"(",
"(",
"that",
".",
"trigger",
"=",
"triggerEditable",
"(",
"that",
")",
"||",
"triggerEdge",
"(",
"that",
")",
"||",
"triggerExpand",
"(",
"that",
")",
")",
"&&",
"!",
"isInTabu",
"(",
"that",
",",
"that",
".",
"trigger",
".",
"upper",
"||",
"that",
".",
"trigger",
".",
"lower",
")",
")",
"{",
"that",
".",
"line",
".",
"attach",
"(",
")",
".",
"place",
"(",
")",
";",
"}",
"// Otherwise remove the box\r",
"else",
"{",
"that",
".",
"trigger",
"=",
"null",
";",
"that",
".",
"line",
".",
"detach",
"(",
")",
";",
"}",
"that",
".",
"debug",
".",
"showTrigger",
"(",
"that",
".",
"trigger",
")",
";",
"// %REMOVE_LINE%\r",
"that",
".",
"debug",
".",
"mousePos",
"(",
"mouse",
".",
"y",
",",
"that",
".",
"element",
")",
";",
"// %REMOVE_LINE%\r",
"checkMouseTimeoutPending",
"=",
"false",
";",
"}",
"that",
".",
"debug",
".",
"stopTimer",
"(",
")",
";",
"// %REMOVE_LINE%\r",
"that",
".",
"debug",
".",
"groupEnd",
"(",
")",
";",
"// %REMOVE_LINE%\r",
"}"
] | This method handles mousemove mouse for box toggling. It uses mouse position to determine underlying element, then it tries to use different trigger type in order to place the box in correct place. The following procedure is executed periodically. | [
"This",
"method",
"handles",
"mousemove",
"mouse",
"for",
"box",
"toggling",
".",
"It",
"uses",
"mouse",
"position",
"to",
"determine",
"underlying",
"element",
"then",
"it",
"tries",
"to",
"use",
"different",
"trigger",
"type",
"in",
"order",
"to",
"place",
"the",
"box",
"in",
"correct",
"place",
".",
"The",
"following",
"procedure",
"is",
"executed",
"periodically",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/magicline/plugin.js#L304-L341 |
54,599 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/plugins/magicline/plugin.js | boxTrigger | function boxTrigger( triggerSetup ) {
this.upper = triggerSetup[ 0 ];
this.lower = triggerSetup[ 1 ];
this.set.apply( this, triggerSetup.slice( 2 ) );
} | javascript | function boxTrigger( triggerSetup ) {
this.upper = triggerSetup[ 0 ];
this.lower = triggerSetup[ 1 ];
this.set.apply( this, triggerSetup.slice( 2 ) );
} | [
"function",
"boxTrigger",
"(",
"triggerSetup",
")",
"{",
"this",
".",
"upper",
"=",
"triggerSetup",
"[",
"0",
"]",
";",
"this",
".",
"lower",
"=",
"triggerSetup",
"[",
"1",
"]",
";",
"this",
".",
"set",
".",
"apply",
"(",
"this",
",",
"triggerSetup",
".",
"slice",
"(",
"2",
")",
")",
";",
"}"
] | boxTrigger is an abstract type which describes the relationship between elements that may result in showing the box. The following type is used by numerous methods to share information about the hypothetical box placement and look by referring to boxTrigger properties. | [
"boxTrigger",
"is",
"an",
"abstract",
"type",
"which",
"describes",
"the",
"relationship",
"between",
"elements",
"that",
"may",
"result",
"in",
"showing",
"the",
"box",
".",
"The",
"following",
"type",
"is",
"used",
"by",
"numerous",
"methods",
"to",
"share",
"information",
"about",
"the",
"hypothetical",
"box",
"placement",
"and",
"look",
"by",
"referring",
"to",
"boxTrigger",
"properties",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/magicline/plugin.js#L412-L416 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.