id int32 0 58k | repo stringlengths 5 67 | path stringlengths 4 116 | func_name stringlengths 0 58 | original_string stringlengths 52 373k | language stringclasses 1 value | code stringlengths 52 373k | code_tokens list | docstring stringlengths 4 11.8k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 86 226 |
|---|---|---|---|---|---|---|---|---|---|---|---|
22,500 | ArnaudValensi/node-jsencrypt | index.js | function () {
if ((i = x.getLowestSetBit()) > 0) {
x.rShiftTo(i, x);
}
if ((i = y.getLowestSetBit()) > 0) {
y.rShiftTo(i, y);
}
if (x.compareTo(y) >= 0) {
x.subTo(y, x);
x.rShiftTo(1, x);
} else {
y.subTo(x, y);
y.rShiftTo(1, y);
}
if (!(x.signum() > 0)) {
if (g > 0) y.lShiftTo(g, y);
setTimeout(function () {
callback(y)
}, 0); // escape
} else {
setTimeout(gcda1, 0);
}
} | javascript | function () {
if ((i = x.getLowestSetBit()) > 0) {
x.rShiftTo(i, x);
}
if ((i = y.getLowestSetBit()) > 0) {
y.rShiftTo(i, y);
}
if (x.compareTo(y) >= 0) {
x.subTo(y, x);
x.rShiftTo(1, x);
} else {
y.subTo(x, y);
y.rShiftTo(1, y);
}
if (!(x.signum() > 0)) {
if (g > 0) y.lShiftTo(g, y);
setTimeout(function () {
callback(y)
}, 0); // escape
} else {
setTimeout(gcda1, 0);
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"(",
"i",
"=",
"x",
".",
"getLowestSetBit",
"(",
")",
")",
">",
"0",
")",
"{",
"x",
".",
"rShiftTo",
"(",
"i",
",",
"x",
")",
";",
"}",
"if",
"(",
"(",
"i",
"=",
"y",
".",
"getLowestSetBit",
"(",
")",
")",
">",
"0",
")",
"{",
"y",
".",
"rShiftTo",
"(",
"i",
",",
"y",
")",
";",
"}",
"if",
"(",
"x",
".",
"compareTo",
"(",
"y",
")",
">=",
"0",
")",
"{",
"x",
".",
"subTo",
"(",
"y",
",",
"x",
")",
";",
"x",
".",
"rShiftTo",
"(",
"1",
",",
"x",
")",
";",
"}",
"else",
"{",
"y",
".",
"subTo",
"(",
"x",
",",
"y",
")",
";",
"y",
".",
"rShiftTo",
"(",
"1",
",",
"y",
")",
";",
"}",
"if",
"(",
"!",
"(",
"x",
".",
"signum",
"(",
")",
">",
"0",
")",
")",
"{",
"if",
"(",
"g",
">",
"0",
")",
"y",
".",
"lShiftTo",
"(",
"g",
",",
"y",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"callback",
"(",
"y",
")",
"}",
",",
"0",
")",
";",
"// escape",
"}",
"else",
"{",
"setTimeout",
"(",
"gcda1",
",",
"0",
")",
";",
"}",
"}"
] | Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen. | [
"Workhorse",
"of",
"the",
"algorithm",
"gets",
"called",
"200",
"-",
"800",
"times",
"per",
"512",
"bit",
"keygen",
"."
] | ddea7f3a5ac4635bd462327f0005caba10cc0870 | https://github.com/ArnaudValensi/node-jsencrypt/blob/ddea7f3a5ac4635bd462327f0005caba10cc0870/index.js#L2514-L2536 | |
22,501 | ArnaudValensi/node-jsencrypt | index.js | b64tohex | function b64tohex(s) {
var ret = ""
var i;
var k = 0; // b64 state, 0-3
var slop;
for (i = 0; i < s.length; ++i) {
if (s.charAt(i) == b64pad) break;
v = b64map.indexOf(s.charAt(i));
if (v < 0) continue;
if (k == 0) {
ret += int2char(v >> 2);
slop = v & 3;
k = 1;
}
else if (k == 1) {
ret += int2char((slop << 2) | (v >> 4));
slop = v & 0xf;
k = 2;
}
else if (k == 2) {
ret += int2char(slop);
ret += int2char(v >> 2);
slop = v & 3;
k = 3;
}
else {
ret += int2char((slop << 2) | (v >> 4));
ret += int2char(v & 0xf);
k = 0;
}
}
if (k == 1)
ret += int2char(slop << 2);
return ret;
} | javascript | function b64tohex(s) {
var ret = ""
var i;
var k = 0; // b64 state, 0-3
var slop;
for (i = 0; i < s.length; ++i) {
if (s.charAt(i) == b64pad) break;
v = b64map.indexOf(s.charAt(i));
if (v < 0) continue;
if (k == 0) {
ret += int2char(v >> 2);
slop = v & 3;
k = 1;
}
else if (k == 1) {
ret += int2char((slop << 2) | (v >> 4));
slop = v & 0xf;
k = 2;
}
else if (k == 2) {
ret += int2char(slop);
ret += int2char(v >> 2);
slop = v & 3;
k = 3;
}
else {
ret += int2char((slop << 2) | (v >> 4));
ret += int2char(v & 0xf);
k = 0;
}
}
if (k == 1)
ret += int2char(slop << 2);
return ret;
} | [
"function",
"b64tohex",
"(",
"s",
")",
"{",
"var",
"ret",
"=",
"\"\"",
"var",
"i",
";",
"var",
"k",
"=",
"0",
";",
"// b64 state, 0-3",
"var",
"slop",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"s",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"s",
".",
"charAt",
"(",
"i",
")",
"==",
"b64pad",
")",
"break",
";",
"v",
"=",
"b64map",
".",
"indexOf",
"(",
"s",
".",
"charAt",
"(",
"i",
")",
")",
";",
"if",
"(",
"v",
"<",
"0",
")",
"continue",
";",
"if",
"(",
"k",
"==",
"0",
")",
"{",
"ret",
"+=",
"int2char",
"(",
"v",
">>",
"2",
")",
";",
"slop",
"=",
"v",
"&",
"3",
";",
"k",
"=",
"1",
";",
"}",
"else",
"if",
"(",
"k",
"==",
"1",
")",
"{",
"ret",
"+=",
"int2char",
"(",
"(",
"slop",
"<<",
"2",
")",
"|",
"(",
"v",
">>",
"4",
")",
")",
";",
"slop",
"=",
"v",
"&",
"0xf",
";",
"k",
"=",
"2",
";",
"}",
"else",
"if",
"(",
"k",
"==",
"2",
")",
"{",
"ret",
"+=",
"int2char",
"(",
"slop",
")",
";",
"ret",
"+=",
"int2char",
"(",
"v",
">>",
"2",
")",
";",
"slop",
"=",
"v",
"&",
"3",
";",
"k",
"=",
"3",
";",
"}",
"else",
"{",
"ret",
"+=",
"int2char",
"(",
"(",
"slop",
"<<",
"2",
")",
"|",
"(",
"v",
">>",
"4",
")",
")",
";",
"ret",
"+=",
"int2char",
"(",
"v",
"&",
"0xf",
")",
";",
"k",
"=",
"0",
";",
"}",
"}",
"if",
"(",
"k",
"==",
"1",
")",
"ret",
"+=",
"int2char",
"(",
"slop",
"<<",
"2",
")",
";",
"return",
"ret",
";",
"}"
] | convert a base64 string to hex | [
"convert",
"a",
"base64",
"string",
"to",
"hex"
] | ddea7f3a5ac4635bd462327f0005caba10cc0870 | https://github.com/ArnaudValensi/node-jsencrypt/blob/ddea7f3a5ac4635bd462327f0005caba10cc0870/index.js#L2603-L2637 |
22,502 | ArnaudValensi/node-jsencrypt | index.js | function (key) {
// Call the super constructor.
RSAKey.call(this);
// If a key key was provided.
if (key) {
// If this is a string...
if (typeof key === 'string') {
this.parseKey(key);
}
else if (
this.hasPrivateKeyProperty(key) ||
this.hasPublicKeyProperty(key)
) {
// Set the values for the key.
this.parsePropertiesFrom(key);
}
}
} | javascript | function (key) {
// Call the super constructor.
RSAKey.call(this);
// If a key key was provided.
if (key) {
// If this is a string...
if (typeof key === 'string') {
this.parseKey(key);
}
else if (
this.hasPrivateKeyProperty(key) ||
this.hasPublicKeyProperty(key)
) {
// Set the values for the key.
this.parsePropertiesFrom(key);
}
}
} | [
"function",
"(",
"key",
")",
"{",
"// Call the super constructor.",
"RSAKey",
".",
"call",
"(",
"this",
")",
";",
"// If a key key was provided.",
"if",
"(",
"key",
")",
"{",
"// If this is a string...",
"if",
"(",
"typeof",
"key",
"===",
"'string'",
")",
"{",
"this",
".",
"parseKey",
"(",
"key",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"hasPrivateKeyProperty",
"(",
"key",
")",
"||",
"this",
".",
"hasPublicKeyProperty",
"(",
"key",
")",
")",
"{",
"// Set the values for the key.",
"this",
".",
"parsePropertiesFrom",
"(",
"key",
")",
";",
"}",
"}",
"}"
] | Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object.
This object is just a decorator for parsing the key parameter
@param {string|Object} key - The key in string format, or an object containing
the parameters needed to build a RSAKey object.
@constructor | [
"Create",
"a",
"new",
"JSEncryptRSAKey",
"that",
"extends",
"Tom",
"Wu",
"s",
"RSA",
"key",
"object",
".",
"This",
"object",
"is",
"just",
"a",
"decorator",
"for",
"parsing",
"the",
"key",
"parameter"
] | ddea7f3a5ac4635bd462327f0005caba10cc0870 | https://github.com/ArnaudValensi/node-jsencrypt/blob/ddea7f3a5ac4635bd462327f0005caba10cc0870/index.js#L4386-L4403 | |
22,503 | dasmoth/dalliance | js/das.js | DASSequence | function DASSequence(name, start, end, alpha, seq) {
this.name = name;
this.start = start;
this.end = end;
this.alphabet = alpha;
this.seq = seq;
} | javascript | function DASSequence(name, start, end, alpha, seq) {
this.name = name;
this.start = start;
this.end = end;
this.alphabet = alpha;
this.seq = seq;
} | [
"function",
"DASSequence",
"(",
"name",
",",
"start",
",",
"end",
",",
"alpha",
",",
"seq",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"start",
"=",
"start",
";",
"this",
".",
"end",
"=",
"end",
";",
"this",
".",
"alphabet",
"=",
"alpha",
";",
"this",
".",
"seq",
"=",
"seq",
";",
"}"
] | DAS 1.6 sequence command Do we need an option to fall back to the dna command? | [
"DAS",
"1",
".",
"6",
"sequence",
"command",
"Do",
"we",
"need",
"an",
"option",
"to",
"fall",
"back",
"to",
"the",
"dna",
"command?"
] | 64565abc974433a5dcd5406d17fa0a202e1e55fc | https://github.com/dasmoth/dalliance/blob/64565abc974433a5dcd5406d17fa0a202e1e55fc/js/das.js#L140-L146 |
22,504 | thlorenz/flamegraph | index.js | flamegraph | function flamegraph(arr, opts) {
var profile
if (!Array.isArray(arr)) throw new TypeError('First arg needs to be an array of lines.')
opts = opts || {}
try {
profile = cpuprofilify().convert(arr, opts.profile)
} catch (err) {
// not a valid input to cpuprofilify -- maybe it's an actual cpuprofile already?
try {
profile = JSON.parse(arr.join('\n'))
} catch (parseErr) {
// if not throw the original cpuprofilify error
throw err
}
}
// at this point we have a cpuprofile
return fromCpuProfile(profile, opts)
} | javascript | function flamegraph(arr, opts) {
var profile
if (!Array.isArray(arr)) throw new TypeError('First arg needs to be an array of lines.')
opts = opts || {}
try {
profile = cpuprofilify().convert(arr, opts.profile)
} catch (err) {
// not a valid input to cpuprofilify -- maybe it's an actual cpuprofile already?
try {
profile = JSON.parse(arr.join('\n'))
} catch (parseErr) {
// if not throw the original cpuprofilify error
throw err
}
}
// at this point we have a cpuprofile
return fromCpuProfile(profile, opts)
} | [
"function",
"flamegraph",
"(",
"arr",
",",
"opts",
")",
"{",
"var",
"profile",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"arr",
")",
")",
"throw",
"new",
"TypeError",
"(",
"'First arg needs to be an array of lines.'",
")",
"opts",
"=",
"opts",
"||",
"{",
"}",
"try",
"{",
"profile",
"=",
"cpuprofilify",
"(",
")",
".",
"convert",
"(",
"arr",
",",
"opts",
".",
"profile",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"// not a valid input to cpuprofilify -- maybe it's an actual cpuprofile already?",
"try",
"{",
"profile",
"=",
"JSON",
".",
"parse",
"(",
"arr",
".",
"join",
"(",
"'\\n'",
")",
")",
"}",
"catch",
"(",
"parseErr",
")",
"{",
"// if not throw the original cpuprofilify error",
"throw",
"err",
"}",
"}",
"// at this point we have a cpuprofile",
"return",
"fromCpuProfile",
"(",
"profile",
",",
"opts",
")",
"}"
] | Converts an array of call graph lines into an svg document.
@name flamegraph
@function
@param {Array.<string>} arr input lines to render svg for
@param {Object} opts objects that affect the visualization
@param {Object} opts.profile options passed to cpuprofilify @see [cpuprofilify.convert params](https://github.com/thlorenz/cpuprofilify#parameters)
@param {string} opts.fonttype type of font to use default: `'Verdana'`
@param {number} opts.fontsize base text size default: `12`
@param {number} opts.imagewidth max width, pixels default: `1200`
@param {number} opts.frameheight max height is dynamic default: `16.0`
@param {number} opts.fontwidth avg width relative to fontsize default: `0.59`
@param {number} opts.minwidth min function width, pixels default: `0.1`
@param {string} opts.countname what are the counts in the data? default: `'samples'`
@param {string} opts.colors color theme default: `'hot'`
@param {string} opts.bgcolor1 background color gradient start default: `'#eeeeee'`
@param {string} opts.bgcolor2 background color gradient stop default: `'#eeeeb0'`
@param {number} opts.timemax (override the) sum of the counts default: `Infinity`
@param {number} opts.factor factor to scale counts by default: `1`
@param {boolean} opts.hash color by function name default: `true`
@param {string} opts.titletext centered heading default: `'Flame Graph'`
@param {string} opts.nametype what are the names in the data? default: `'Function:'`
@return {string} svg the rendered svg | [
"Converts",
"an",
"array",
"of",
"call",
"graph",
"lines",
"into",
"an",
"svg",
"document",
"."
] | 2871eabaef5e8de1941a09077d83d41e24baca85 | https://github.com/thlorenz/flamegraph/blob/2871eabaef5e8de1941a09077d83d41e24baca85/index.js#L43-L62 |
22,505 | thlorenz/flamegraph | from-stream.js | fromStream | function fromStream(stream, opts) {
opts = opts || {}
var out = through()
function ondata(res) {
try {
var svg = flamegraph(res.toString().split('\n'), opts)
out.write(svg)
} catch (err) {
out.emit('error', err)
}
}
// Once memory becomes an issue we need to make this truly streaming
stream.pipe(concatStream(ondata))
return out
} | javascript | function fromStream(stream, opts) {
opts = opts || {}
var out = through()
function ondata(res) {
try {
var svg = flamegraph(res.toString().split('\n'), opts)
out.write(svg)
} catch (err) {
out.emit('error', err)
}
}
// Once memory becomes an issue we need to make this truly streaming
stream.pipe(concatStream(ondata))
return out
} | [
"function",
"fromStream",
"(",
"stream",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
"var",
"out",
"=",
"through",
"(",
")",
"function",
"ondata",
"(",
"res",
")",
"{",
"try",
"{",
"var",
"svg",
"=",
"flamegraph",
"(",
"res",
".",
"toString",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
",",
"opts",
")",
"out",
".",
"write",
"(",
"svg",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"out",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
"}",
"}",
"// Once memory becomes an issue we need to make this truly streaming",
"stream",
".",
"pipe",
"(",
"concatStream",
"(",
"ondata",
")",
")",
"return",
"out",
"}"
] | Converts a stream of call graph lines into an svg document.
Not truly streaming, concats all lines before processing.
**Example**:
```js
var fromStream = require('flamegraph/from-stream')
fromStream(process.stdin, opts).pipe(process.stdout)
```
@name flamegraph::fromStream
@function
@param {ReadableStream} stream that will emit the call graph lines to be parsed
@param {Object} opts same as `flamegraph`
@return {ReadableStream} stream that emits the lines of generated svg | [
"Converts",
"a",
"stream",
"of",
"call",
"graph",
"lines",
"into",
"an",
"svg",
"document",
".",
"Not",
"truly",
"streaming",
"concats",
"all",
"lines",
"before",
"processing",
"."
] | 2871eabaef5e8de1941a09077d83d41e24baca85 | https://github.com/thlorenz/flamegraph/blob/2871eabaef5e8de1941a09077d83d41e24baca85/from-stream.js#L29-L45 |
22,506 | ralucas/node-zillow | lib/helpers.js | httpRequest | function httpRequest(url) {
var deferred = Q.defer();
request(url, function(err, response, body) {
if (err) {
deferred.reject(new Error(err));
} else if (!err && response.statusCode !== 200) {
deferred.reject(new Error(response.statusCode));
} else {
deferred.resolve(body);
}
});
return deferred.promise;
} | javascript | function httpRequest(url) {
var deferred = Q.defer();
request(url, function(err, response, body) {
if (err) {
deferred.reject(new Error(err));
} else if (!err && response.statusCode !== 200) {
deferred.reject(new Error(response.statusCode));
} else {
deferred.resolve(body);
}
});
return deferred.promise;
} | [
"function",
"httpRequest",
"(",
"url",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"request",
"(",
"url",
",",
"function",
"(",
"err",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"deferred",
".",
"reject",
"(",
"new",
"Error",
"(",
"err",
")",
")",
";",
"}",
"else",
"if",
"(",
"!",
"err",
"&&",
"response",
".",
"statusCode",
"!==",
"200",
")",
"{",
"deferred",
".",
"reject",
"(",
"new",
"Error",
"(",
"response",
".",
"statusCode",
")",
")",
";",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
"body",
")",
";",
"}",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] | Helper function that handles the http request
@param {string} url | [
"Helper",
"function",
"that",
"handles",
"the",
"http",
"request"
] | 236aa710b60fd3713bf1245be163cd64c2045985 | https://github.com/ralucas/node-zillow/blob/236aa710b60fd3713bf1245be163cd64c2045985/lib/helpers.js#L17-L29 |
22,507 | ralucas/node-zillow | lib/helpers.js | toJson | function toJson(xml) {
var deferred = Q.defer();
xml2js.parseString(xml, function(err, result) {
if (err) {
deferred.reject(new Error(err));
} else {
deferred.resolve(result);
}
});
return deferred.promise;
} | javascript | function toJson(xml) {
var deferred = Q.defer();
xml2js.parseString(xml, function(err, result) {
if (err) {
deferred.reject(new Error(err));
} else {
deferred.resolve(result);
}
});
return deferred.promise;
} | [
"function",
"toJson",
"(",
"xml",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"xml2js",
".",
"parseString",
"(",
"xml",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"deferred",
".",
"reject",
"(",
"new",
"Error",
"(",
"err",
")",
")",
";",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
"result",
")",
";",
"}",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] | Helper function that converts xml to json
@param {xml} xml | [
"Helper",
"function",
"that",
"converts",
"xml",
"to",
"json"
] | 236aa710b60fd3713bf1245be163cd64c2045985 | https://github.com/ralucas/node-zillow/blob/236aa710b60fd3713bf1245be163cd64c2045985/lib/helpers.js#L36-L46 |
22,508 | ralucas/node-zillow | lib/helpers.js | toQueryString | function toQueryString(params, id) {
var paramsString = '';
for (var key in params) {
if (params.hasOwnProperty(key)) {
paramsString += '&' + key + '=' + encodeURIComponent(params[key]);
}
}
return 'zws-id=' + id + paramsString;
} | javascript | function toQueryString(params, id) {
var paramsString = '';
for (var key in params) {
if (params.hasOwnProperty(key)) {
paramsString += '&' + key + '=' + encodeURIComponent(params[key]);
}
}
return 'zws-id=' + id + paramsString;
} | [
"function",
"toQueryString",
"(",
"params",
",",
"id",
")",
"{",
"var",
"paramsString",
"=",
"''",
";",
"for",
"(",
"var",
"key",
"in",
"params",
")",
"{",
"if",
"(",
"params",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"paramsString",
"+=",
"'&'",
"+",
"key",
"+",
"'='",
"+",
"encodeURIComponent",
"(",
"params",
"[",
"key",
"]",
")",
";",
"}",
"}",
"return",
"'zws-id='",
"+",
"id",
"+",
"paramsString",
";",
"}"
] | Helper function that takes params hash and converts it into query string
@param {object} params
@param {Number} id | [
"Helper",
"function",
"that",
"takes",
"params",
"hash",
"and",
"converts",
"it",
"into",
"query",
"string"
] | 236aa710b60fd3713bf1245be163cd64c2045985 | https://github.com/ralucas/node-zillow/blob/236aa710b60fd3713bf1245be163cd64c2045985/lib/helpers.js#L54-L62 |
22,509 | ralucas/node-zillow | lib/helpers.js | checkParams | function checkParams(params, reqParams) {
if ( reqParams.length < 1 ) {
return;
}
if ( (_.isEmpty(params) || !params) && (reqParams.length > 0) ) {
throw new Error('Missing parameters: ' + reqParams.join(', '));
}
var paramsKeys = _.keys(params);
_.each(reqParams, function(reqParam) {
if ( paramsKeys.indexOf(reqParam) === -1 ) {
throw new Error('Missing parameter: ' + reqParam);
}
});
} | javascript | function checkParams(params, reqParams) {
if ( reqParams.length < 1 ) {
return;
}
if ( (_.isEmpty(params) || !params) && (reqParams.length > 0) ) {
throw new Error('Missing parameters: ' + reqParams.join(', '));
}
var paramsKeys = _.keys(params);
_.each(reqParams, function(reqParam) {
if ( paramsKeys.indexOf(reqParam) === -1 ) {
throw new Error('Missing parameter: ' + reqParam);
}
});
} | [
"function",
"checkParams",
"(",
"params",
",",
"reqParams",
")",
"{",
"if",
"(",
"reqParams",
".",
"length",
"<",
"1",
")",
"{",
"return",
";",
"}",
"if",
"(",
"(",
"_",
".",
"isEmpty",
"(",
"params",
")",
"||",
"!",
"params",
")",
"&&",
"(",
"reqParams",
".",
"length",
">",
"0",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing parameters: '",
"+",
"reqParams",
".",
"join",
"(",
"', '",
")",
")",
";",
"}",
"var",
"paramsKeys",
"=",
"_",
".",
"keys",
"(",
"params",
")",
";",
"_",
".",
"each",
"(",
"reqParams",
",",
"function",
"(",
"reqParam",
")",
"{",
"if",
"(",
"paramsKeys",
".",
"indexOf",
"(",
"reqParam",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing parameter: '",
"+",
"reqParam",
")",
";",
"}",
"}",
")",
";",
"}"
] | Helper function that checks for the required params
@param {object} params
@param {array} reqParams -- required parameters | [
"Helper",
"function",
"that",
"checks",
"for",
"the",
"required",
"params"
] | 236aa710b60fd3713bf1245be163cd64c2045985 | https://github.com/ralucas/node-zillow/blob/236aa710b60fd3713bf1245be163cd64c2045985/lib/helpers.js#L70-L86 |
22,510 | gosquared/mmdb-reader | src/Reader.js | Reader | function Reader(buf, filePath) {
// Allow instantiating without `new`
if (!(this instanceof Reader)) {
return new Reader(buf);
}
// Allow passing either a path to a file or a raw buffer
if (typeof buf === 'string') {
filePath = buf;
buf = fs.readFileSync(buf);
}
// LRU cache that'll hold objects we read from the data section.
// 5000 seems to be roughly the sweet spot between mem vs hit-rate
this._pointerCache = new LRU(LRU_SIZE);
this._buf = buf;
// Stash the file path for if we want to reload it later
this.filePath = filePath;
this.setup();
} | javascript | function Reader(buf, filePath) {
// Allow instantiating without `new`
if (!(this instanceof Reader)) {
return new Reader(buf);
}
// Allow passing either a path to a file or a raw buffer
if (typeof buf === 'string') {
filePath = buf;
buf = fs.readFileSync(buf);
}
// LRU cache that'll hold objects we read from the data section.
// 5000 seems to be roughly the sweet spot between mem vs hit-rate
this._pointerCache = new LRU(LRU_SIZE);
this._buf = buf;
// Stash the file path for if we want to reload it later
this.filePath = filePath;
this.setup();
} | [
"function",
"Reader",
"(",
"buf",
",",
"filePath",
")",
"{",
"// Allow instantiating without `new`",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Reader",
")",
")",
"{",
"return",
"new",
"Reader",
"(",
"buf",
")",
";",
"}",
"// Allow passing either a path to a file or a raw buffer",
"if",
"(",
"typeof",
"buf",
"===",
"'string'",
")",
"{",
"filePath",
"=",
"buf",
";",
"buf",
"=",
"fs",
".",
"readFileSync",
"(",
"buf",
")",
";",
"}",
"// LRU cache that'll hold objects we read from the data section.",
"// 5000 seems to be roughly the sweet spot between mem vs hit-rate",
"this",
".",
"_pointerCache",
"=",
"new",
"LRU",
"(",
"LRU_SIZE",
")",
";",
"this",
".",
"_buf",
"=",
"buf",
";",
"// Stash the file path for if we want to reload it later",
"this",
".",
"filePath",
"=",
"filePath",
";",
"this",
".",
"setup",
"(",
")",
";",
"}"
] | Main reader constructor | [
"Main",
"reader",
"constructor"
] | 65adbb40709020a3b13ec5619b83efae75b77a5e | https://github.com/gosquared/mmdb-reader/blob/65adbb40709020a3b13ec5619b83efae75b77a5e/src/Reader.js#L26-L48 |
22,511 | vacuumlabs/data-provider | src/config.js | changeCfgOption | function changeCfgOption(options, key) {
if (expectKey(options, key, typeof cfg[key])) {
cfg[key] = options[key]
}
} | javascript | function changeCfgOption(options, key) {
if (expectKey(options, key, typeof cfg[key])) {
cfg[key] = options[key]
}
} | [
"function",
"changeCfgOption",
"(",
"options",
",",
"key",
")",
"{",
"if",
"(",
"expectKey",
"(",
"options",
",",
"key",
",",
"typeof",
"cfg",
"[",
"key",
"]",
")",
")",
"{",
"cfg",
"[",
"key",
"]",
"=",
"options",
"[",
"key",
"]",
"}",
"}"
] | if supplied options contain given field, override its value in global cfg | [
"if",
"supplied",
"options",
"contain",
"given",
"field",
"override",
"its",
"value",
"in",
"global",
"cfg"
] | 2acbd4698a3d5050dd15d25d023409dee126cc41 | https://github.com/vacuumlabs/data-provider/blob/2acbd4698a3d5050dd15d25d023409dee126cc41/src/config.js#L38-L42 |
22,512 | vacuumlabs/data-provider | src/config.js | expectKey | function expectKey(options, key, type) {
if (key in options) {
if (typeof options[key] === type) {
return true
}
// eslint-disable-next-line no-console
console.warn(`Ignoring options key '${key}' - ` +
`expected type '${type}', received '${typeof options[key]}'`)
}
return false
} | javascript | function expectKey(options, key, type) {
if (key in options) {
if (typeof options[key] === type) {
return true
}
// eslint-disable-next-line no-console
console.warn(`Ignoring options key '${key}' - ` +
`expected type '${type}', received '${typeof options[key]}'`)
}
return false
} | [
"function",
"expectKey",
"(",
"options",
",",
"key",
",",
"type",
")",
"{",
"if",
"(",
"key",
"in",
"options",
")",
"{",
"if",
"(",
"typeof",
"options",
"[",
"key",
"]",
"===",
"type",
")",
"{",
"return",
"true",
"}",
"// eslint-disable-next-line no-console",
"console",
".",
"warn",
"(",
"`",
"${",
"key",
"}",
"`",
"+",
"`",
"${",
"type",
"}",
"${",
"typeof",
"options",
"[",
"key",
"]",
"}",
"`",
")",
"}",
"return",
"false",
"}"
] | check whether options contain given key and that it is the same type as in cfg | [
"check",
"whether",
"options",
"contain",
"given",
"key",
"and",
"that",
"it",
"is",
"the",
"same",
"type",
"as",
"in",
"cfg"
] | 2acbd4698a3d5050dd15d25d023409dee126cc41 | https://github.com/vacuumlabs/data-provider/blob/2acbd4698a3d5050dd15d25d023409dee126cc41/src/config.js#L45-L55 |
22,513 | kmi/node-red-contrib-noble | noble/node-red-contrib-noble.js | startScan | function startScan(stateChange, error) {
if (!node.scanning) {
// send status message
var msg = {
statusUpdate: true,
error: error,
stateChange: stateChange,
state: noble.state
};
node.send(msg);
// start the scan
noble.startScanning(node.uuids, node.duplicates, function() {
node.log("Scanning for BLEs started. UUIDs: " + node.uuids + " - Duplicates allowed: " + node.duplicates);
node.status({fill:"green",shape:"dot",text:"started"});
node.scanning = true;
});
}
} | javascript | function startScan(stateChange, error) {
if (!node.scanning) {
// send status message
var msg = {
statusUpdate: true,
error: error,
stateChange: stateChange,
state: noble.state
};
node.send(msg);
// start the scan
noble.startScanning(node.uuids, node.duplicates, function() {
node.log("Scanning for BLEs started. UUIDs: " + node.uuids + " - Duplicates allowed: " + node.duplicates);
node.status({fill:"green",shape:"dot",text:"started"});
node.scanning = true;
});
}
} | [
"function",
"startScan",
"(",
"stateChange",
",",
"error",
")",
"{",
"if",
"(",
"!",
"node",
".",
"scanning",
")",
"{",
"// send status message",
"var",
"msg",
"=",
"{",
"statusUpdate",
":",
"true",
",",
"error",
":",
"error",
",",
"stateChange",
":",
"stateChange",
",",
"state",
":",
"noble",
".",
"state",
"}",
";",
"node",
".",
"send",
"(",
"msg",
")",
";",
"// start the scan",
"noble",
".",
"startScanning",
"(",
"node",
".",
"uuids",
",",
"node",
".",
"duplicates",
",",
"function",
"(",
")",
"{",
"node",
".",
"log",
"(",
"\"Scanning for BLEs started. UUIDs: \"",
"+",
"node",
".",
"uuids",
"+",
"\" - Duplicates allowed: \"",
"+",
"node",
".",
"duplicates",
")",
";",
"node",
".",
"status",
"(",
"{",
"fill",
":",
"\"green\"",
",",
"shape",
":",
"\"dot\"",
",",
"text",
":",
"\"started\"",
"}",
")",
";",
"node",
".",
"scanning",
"=",
"true",
";",
"}",
")",
";",
"}",
"}"
] | Take care of starting the scan and sending the status message | [
"Take",
"care",
"of",
"starting",
"the",
"scan",
"and",
"sending",
"the",
"status",
"message"
] | 9f30d0928df8e4b432891820c6ff97d4c18f49f4 | https://github.com/kmi/node-red-contrib-noble/blob/9f30d0928df8e4b432891820c6ff97d4c18f49f4/noble/node-red-contrib-noble.js#L90-L107 |
22,514 | kmi/node-red-contrib-noble | noble/node-red-contrib-noble.js | stopScan | function stopScan(stateChange, error) {
if (node.scanning) {
// send status message
var msg = {
statusUpdate: true,
error: error,
stateChange: stateChange,
state: noble.state
};
node.send(msg);
// stop the scan
noble.stopScanning(function() {
node.log('BLE scanning stopped.');
node.status({fill:"red",shape:"ring",text:"stopped"});
node.scanning = false;
});
if (error) {
node.warn('BLE scanning stopped due to change in adapter state.');
}
}
} | javascript | function stopScan(stateChange, error) {
if (node.scanning) {
// send status message
var msg = {
statusUpdate: true,
error: error,
stateChange: stateChange,
state: noble.state
};
node.send(msg);
// stop the scan
noble.stopScanning(function() {
node.log('BLE scanning stopped.');
node.status({fill:"red",shape:"ring",text:"stopped"});
node.scanning = false;
});
if (error) {
node.warn('BLE scanning stopped due to change in adapter state.');
}
}
} | [
"function",
"stopScan",
"(",
"stateChange",
",",
"error",
")",
"{",
"if",
"(",
"node",
".",
"scanning",
")",
"{",
"// send status message",
"var",
"msg",
"=",
"{",
"statusUpdate",
":",
"true",
",",
"error",
":",
"error",
",",
"stateChange",
":",
"stateChange",
",",
"state",
":",
"noble",
".",
"state",
"}",
";",
"node",
".",
"send",
"(",
"msg",
")",
";",
"// stop the scan",
"noble",
".",
"stopScanning",
"(",
"function",
"(",
")",
"{",
"node",
".",
"log",
"(",
"'BLE scanning stopped.'",
")",
";",
"node",
".",
"status",
"(",
"{",
"fill",
":",
"\"red\"",
",",
"shape",
":",
"\"ring\"",
",",
"text",
":",
"\"stopped\"",
"}",
")",
";",
"node",
".",
"scanning",
"=",
"false",
";",
"}",
")",
";",
"if",
"(",
"error",
")",
"{",
"node",
".",
"warn",
"(",
"'BLE scanning stopped due to change in adapter state.'",
")",
";",
"}",
"}",
"}"
] | Take care of stopping the scan and sending the status message | [
"Take",
"care",
"of",
"stopping",
"the",
"scan",
"and",
"sending",
"the",
"status",
"message"
] | 9f30d0928df8e4b432891820c6ff97d4c18f49f4 | https://github.com/kmi/node-red-contrib-noble/blob/9f30d0928df8e4b432891820c6ff97d4c18f49f4/noble/node-red-contrib-noble.js#L110-L130 |
22,515 | maxogden/bytewiser | exercises/modifying_buffers/exercise.js | query | function query (mode) {
var exercise = this
function send (stream) {
var input = through2()
input
.pipe(stream)
.on('error', function(err) {
exercise.emit(
'fail',
exercise.__('fail.never_read_stdin')
)
})
input.write('wow. such wow.');
input.end();
}
send(exercise.submissionChild.stdin)
if (mode == 'verify')
send(exercise.solutionChild.stdin)
} | javascript | function query (mode) {
var exercise = this
function send (stream) {
var input = through2()
input
.pipe(stream)
.on('error', function(err) {
exercise.emit(
'fail',
exercise.__('fail.never_read_stdin')
)
})
input.write('wow. such wow.');
input.end();
}
send(exercise.submissionChild.stdin)
if (mode == 'verify')
send(exercise.solutionChild.stdin)
} | [
"function",
"query",
"(",
"mode",
")",
"{",
"var",
"exercise",
"=",
"this",
"function",
"send",
"(",
"stream",
")",
"{",
"var",
"input",
"=",
"through2",
"(",
")",
"input",
".",
"pipe",
"(",
"stream",
")",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"exercise",
".",
"emit",
"(",
"'fail'",
",",
"exercise",
".",
"__",
"(",
"'fail.never_read_stdin'",
")",
")",
"}",
")",
"input",
".",
"write",
"(",
"'wow. such wow.'",
")",
";",
"input",
".",
"end",
"(",
")",
";",
"}",
"send",
"(",
"exercise",
".",
"submissionChild",
".",
"stdin",
")",
"if",
"(",
"mode",
"==",
"'verify'",
")",
"send",
"(",
"exercise",
".",
"solutionChild",
".",
"stdin",
")",
"}"
] | delayed for 500ms to wait for servers to start so we can start playing with them | [
"delayed",
"for",
"500ms",
"to",
"wait",
"for",
"servers",
"to",
"start",
"so",
"we",
"can",
"start",
"playing",
"with",
"them"
] | b111cda74ba0021b0ed69a51fb2c5f40e74284a1 | https://github.com/maxogden/bytewiser/blob/b111cda74ba0021b0ed69a51fb2c5f40e74284a1/exercises/modifying_buffers/exercise.js#L29-L50 |
22,516 | DamienP33/express-mongoose-generator | lib/formatTools.js | getFieldsForModelTemplate | function getFieldsForModelTemplate(fields) {
var lg = fields.length - 1;
var modelFields = '{' + os.EOL;
fields.forEach(function(field, index, array) {
modelFields += '\t\'' + field.name + '\' : '+ (field.isArray ? '[' : '') + (allowedFieldsTypes[field.type]).name + (field.isArray ? ']' : '');
modelFields += (lg > index) ? ',' + os.EOL : os.EOL;
if (field.reference) {
modelFields = modelFields.replace(/{ref}/, field.reference);
}
});
modelFields += '}';
return modelFields;
} | javascript | function getFieldsForModelTemplate(fields) {
var lg = fields.length - 1;
var modelFields = '{' + os.EOL;
fields.forEach(function(field, index, array) {
modelFields += '\t\'' + field.name + '\' : '+ (field.isArray ? '[' : '') + (allowedFieldsTypes[field.type]).name + (field.isArray ? ']' : '');
modelFields += (lg > index) ? ',' + os.EOL : os.EOL;
if (field.reference) {
modelFields = modelFields.replace(/{ref}/, field.reference);
}
});
modelFields += '}';
return modelFields;
} | [
"function",
"getFieldsForModelTemplate",
"(",
"fields",
")",
"{",
"var",
"lg",
"=",
"fields",
".",
"length",
"-",
"1",
";",
"var",
"modelFields",
"=",
"'{'",
"+",
"os",
".",
"EOL",
";",
"fields",
".",
"forEach",
"(",
"function",
"(",
"field",
",",
"index",
",",
"array",
")",
"{",
"modelFields",
"+=",
"'\\t\\''",
"+",
"field",
".",
"name",
"+",
"'\\' : '",
"+",
"(",
"field",
".",
"isArray",
"?",
"'['",
":",
"''",
")",
"+",
"(",
"allowedFieldsTypes",
"[",
"field",
".",
"type",
"]",
")",
".",
"name",
"+",
"(",
"field",
".",
"isArray",
"?",
"']'",
":",
"''",
")",
";",
"modelFields",
"+=",
"(",
"lg",
">",
"index",
")",
"?",
"','",
"+",
"os",
".",
"EOL",
":",
"os",
".",
"EOL",
";",
"if",
"(",
"field",
".",
"reference",
")",
"{",
"modelFields",
"=",
"modelFields",
".",
"replace",
"(",
"/",
"{ref}",
"/",
",",
"field",
".",
"reference",
")",
";",
"}",
"}",
")",
";",
"modelFields",
"+=",
"'}'",
";",
"return",
"modelFields",
";",
"}"
] | Format the fields for the model template
@param {array} fields fields input
@returns {string} formatted fields | [
"Format",
"the",
"fields",
"for",
"the",
"model",
"template"
] | ce1439c4c9c291e539fc6190907364d70e75d4d6 | https://github.com/DamienP33/express-mongoose-generator/blob/ce1439c4c9c291e539fc6190907364d70e75d4d6/lib/formatTools.js#L18-L33 |
22,517 | DamienP33/express-mongoose-generator | lib/generators.js | generateModel | function generateModel(path, modelName, modelFields, generateMethod, ts, cb) {
var fields = formatTools.getFieldsForModelTemplate(modelFields);
var schemaName = modelName + 'Schema';
var extension = (ts) ? 'ts' : 'js';
var model = ft.loadTemplateSync('model.' + extension);
model = model.replace(/{modelName}/, modelName);
model = model.replace(/{schemaName}/g, schemaName);
model = model.replace(/{fields}/, fields);
if (generateMethod === 't') {
ft.createDirIfIsNotDefined(path, 'models', function () {
ft.writeFile(path + '/models/' + modelName + 'Model.' + extension, model, null, cb);
});
} else {
ft.createDirIfIsNotDefined(path, modelName, function () {
ft.writeFile(path + '/' + modelName + '/' + modelName + 'Model.' + extension, model, null, cb);
});
}
} | javascript | function generateModel(path, modelName, modelFields, generateMethod, ts, cb) {
var fields = formatTools.getFieldsForModelTemplate(modelFields);
var schemaName = modelName + 'Schema';
var extension = (ts) ? 'ts' : 'js';
var model = ft.loadTemplateSync('model.' + extension);
model = model.replace(/{modelName}/, modelName);
model = model.replace(/{schemaName}/g, schemaName);
model = model.replace(/{fields}/, fields);
if (generateMethod === 't') {
ft.createDirIfIsNotDefined(path, 'models', function () {
ft.writeFile(path + '/models/' + modelName + 'Model.' + extension, model, null, cb);
});
} else {
ft.createDirIfIsNotDefined(path, modelName, function () {
ft.writeFile(path + '/' + modelName + '/' + modelName + 'Model.' + extension, model, null, cb);
});
}
} | [
"function",
"generateModel",
"(",
"path",
",",
"modelName",
",",
"modelFields",
",",
"generateMethod",
",",
"ts",
",",
"cb",
")",
"{",
"var",
"fields",
"=",
"formatTools",
".",
"getFieldsForModelTemplate",
"(",
"modelFields",
")",
";",
"var",
"schemaName",
"=",
"modelName",
"+",
"'Schema'",
";",
"var",
"extension",
"=",
"(",
"ts",
")",
"?",
"'ts'",
":",
"'js'",
";",
"var",
"model",
"=",
"ft",
".",
"loadTemplateSync",
"(",
"'model.'",
"+",
"extension",
")",
";",
"model",
"=",
"model",
".",
"replace",
"(",
"/",
"{modelName}",
"/",
",",
"modelName",
")",
";",
"model",
"=",
"model",
".",
"replace",
"(",
"/",
"{schemaName}",
"/",
"g",
",",
"schemaName",
")",
";",
"model",
"=",
"model",
".",
"replace",
"(",
"/",
"{fields}",
"/",
",",
"fields",
")",
";",
"if",
"(",
"generateMethod",
"===",
"'t'",
")",
"{",
"ft",
".",
"createDirIfIsNotDefined",
"(",
"path",
",",
"'models'",
",",
"function",
"(",
")",
"{",
"ft",
".",
"writeFile",
"(",
"path",
"+",
"'/models/'",
"+",
"modelName",
"+",
"'Model.'",
"+",
"extension",
",",
"model",
",",
"null",
",",
"cb",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"ft",
".",
"createDirIfIsNotDefined",
"(",
"path",
",",
"modelName",
",",
"function",
"(",
")",
"{",
"ft",
".",
"writeFile",
"(",
"path",
"+",
"'/'",
"+",
"modelName",
"+",
"'/'",
"+",
"modelName",
"+",
"'Model.'",
"+",
"extension",
",",
"model",
",",
"null",
",",
"cb",
")",
";",
"}",
")",
";",
"}",
"}"
] | Generate a Mongoose model
@param {string} path
@param {string} modelName
@param {array} modelFields
@param {string} generateMethod
@param {boolean} ts generating code in TS
@param {function} cb | [
"Generate",
"a",
"Mongoose",
"model"
] | ce1439c4c9c291e539fc6190907364d70e75d4d6 | https://github.com/DamienP33/express-mongoose-generator/blob/ce1439c4c9c291e539fc6190907364d70e75d4d6/lib/generators.js#L17-L36 |
22,518 | DamienP33/express-mongoose-generator | lib/generators.js | generateRouter | function generateRouter(path, modelName, generateMethod, ts, cb) {
var extension = (ts) ? 'ts' : 'js';
var router = ft.loadTemplateSync('router.' + extension);
router = router.replace(/{controllerName}/g, modelName + 'Controller');
if (generateMethod === 't') {
ft.createDirIfIsNotDefined(path, 'routes', function () {
router = router.replace(/{controllerPath}/g, '\'../controllers/' + modelName + 'Controller.' + extension + '\'');
ft.writeFile(path + '/routes/' + modelName + 'Routes.' + extension, router, null, cb);
});
} else {
ft.createDirIfIsNotDefined(path, modelName, function () {
router = router.replace(/{controllerPath}/g, '\'./' + modelName + 'Controller.' + extension + '\'');
ft.writeFile(path + '/' + modelName + '/' + modelName + 'Routes.' + extension, router, null, cb);
});
}
} | javascript | function generateRouter(path, modelName, generateMethod, ts, cb) {
var extension = (ts) ? 'ts' : 'js';
var router = ft.loadTemplateSync('router.' + extension);
router = router.replace(/{controllerName}/g, modelName + 'Controller');
if (generateMethod === 't') {
ft.createDirIfIsNotDefined(path, 'routes', function () {
router = router.replace(/{controllerPath}/g, '\'../controllers/' + modelName + 'Controller.' + extension + '\'');
ft.writeFile(path + '/routes/' + modelName + 'Routes.' + extension, router, null, cb);
});
} else {
ft.createDirIfIsNotDefined(path, modelName, function () {
router = router.replace(/{controllerPath}/g, '\'./' + modelName + 'Controller.' + extension + '\'');
ft.writeFile(path + '/' + modelName + '/' + modelName + 'Routes.' + extension, router, null, cb);
});
}
} | [
"function",
"generateRouter",
"(",
"path",
",",
"modelName",
",",
"generateMethod",
",",
"ts",
",",
"cb",
")",
"{",
"var",
"extension",
"=",
"(",
"ts",
")",
"?",
"'ts'",
":",
"'js'",
";",
"var",
"router",
"=",
"ft",
".",
"loadTemplateSync",
"(",
"'router.'",
"+",
"extension",
")",
";",
"router",
"=",
"router",
".",
"replace",
"(",
"/",
"{controllerName}",
"/",
"g",
",",
"modelName",
"+",
"'Controller'",
")",
";",
"if",
"(",
"generateMethod",
"===",
"'t'",
")",
"{",
"ft",
".",
"createDirIfIsNotDefined",
"(",
"path",
",",
"'routes'",
",",
"function",
"(",
")",
"{",
"router",
"=",
"router",
".",
"replace",
"(",
"/",
"{controllerPath}",
"/",
"g",
",",
"'\\'../controllers/'",
"+",
"modelName",
"+",
"'Controller.'",
"+",
"extension",
"+",
"'\\''",
")",
";",
"ft",
".",
"writeFile",
"(",
"path",
"+",
"'/routes/'",
"+",
"modelName",
"+",
"'Routes.'",
"+",
"extension",
",",
"router",
",",
"null",
",",
"cb",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"ft",
".",
"createDirIfIsNotDefined",
"(",
"path",
",",
"modelName",
",",
"function",
"(",
")",
"{",
"router",
"=",
"router",
".",
"replace",
"(",
"/",
"{controllerPath}",
"/",
"g",
",",
"'\\'./'",
"+",
"modelName",
"+",
"'Controller.'",
"+",
"extension",
"+",
"'\\''",
")",
";",
"ft",
".",
"writeFile",
"(",
"path",
"+",
"'/'",
"+",
"modelName",
"+",
"'/'",
"+",
"modelName",
"+",
"'Routes.'",
"+",
"extension",
",",
"router",
",",
"null",
",",
"cb",
")",
";",
"}",
")",
";",
"}",
"}"
] | Generate a Express router
@param {string} path
@param {string} modelName
@param {string} generateMethod
@param {boolean} ts generating code in TS
@param {function} cb | [
"Generate",
"a",
"Express",
"router"
] | ce1439c4c9c291e539fc6190907364d70e75d4d6 | https://github.com/DamienP33/express-mongoose-generator/blob/ce1439c4c9c291e539fc6190907364d70e75d4d6/lib/generators.js#L46-L62 |
22,519 | DamienP33/express-mongoose-generator | lib/fileTools.js | createDirIfIsNotDefined | function createDirIfIsNotDefined(dirPath, dirName, cb) {
if (!fs.existsSync(dirPath + '/' + dirName)){
fs.mkdirSync(dirPath + '/' + dirName);
console.info(cliStyles.cyan + '\tcreate' + cliStyles.reset + ': ' + dirPath + '/' + dirName);
}
cb();
} | javascript | function createDirIfIsNotDefined(dirPath, dirName, cb) {
if (!fs.existsSync(dirPath + '/' + dirName)){
fs.mkdirSync(dirPath + '/' + dirName);
console.info(cliStyles.cyan + '\tcreate' + cliStyles.reset + ': ' + dirPath + '/' + dirName);
}
cb();
} | [
"function",
"createDirIfIsNotDefined",
"(",
"dirPath",
",",
"dirName",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"dirPath",
"+",
"'/'",
"+",
"dirName",
")",
")",
"{",
"fs",
".",
"mkdirSync",
"(",
"dirPath",
"+",
"'/'",
"+",
"dirName",
")",
";",
"console",
".",
"info",
"(",
"cliStyles",
".",
"cyan",
"+",
"'\\tcreate'",
"+",
"cliStyles",
".",
"reset",
"+",
"': '",
"+",
"dirPath",
"+",
"'/'",
"+",
"dirName",
")",
";",
"}",
"cb",
"(",
")",
";",
"}"
] | Create a directory if not defined
@param {string} dirPath directory path parent
@param {string} dirName directory name to find
@param {function} cb callback | [
"Create",
"a",
"directory",
"if",
"not",
"defined"
] | ce1439c4c9c291e539fc6190907364d70e75d4d6 | https://github.com/DamienP33/express-mongoose-generator/blob/ce1439c4c9c291e539fc6190907364d70e75d4d6/lib/fileTools.js#L14-L21 |
22,520 | enricostara/telegram-mt-node | lib/auth/index.js | createAuthKey | function createAuthKey(callback, channel) {
flow.retryUntilIsDone(callback, null,
function (callback) {
flow.runSeries([
require('./request-pq'),
require('./request-dh-params'),
require('./set-client-dh-params')
], callback, channel);
});
} | javascript | function createAuthKey(callback, channel) {
flow.retryUntilIsDone(callback, null,
function (callback) {
flow.runSeries([
require('./request-pq'),
require('./request-dh-params'),
require('./set-client-dh-params')
], callback, channel);
});
} | [
"function",
"createAuthKey",
"(",
"callback",
",",
"channel",
")",
"{",
"flow",
".",
"retryUntilIsDone",
"(",
"callback",
",",
"null",
",",
"function",
"(",
"callback",
")",
"{",
"flow",
".",
"runSeries",
"(",
"[",
"require",
"(",
"'./request-pq'",
")",
",",
"require",
"(",
"'./request-dh-params'",
")",
",",
"require",
"(",
"'./set-client-dh-params'",
")",
"]",
",",
"callback",
",",
"channel",
")",
";",
"}",
")",
";",
"}"
] | Create the authorization key | [
"Create",
"the",
"authorization",
"key"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/index.js#L18-L28 |
22,521 | enricostara/telegram-mt-node | lib/auth/request-pq.js | requestPQ | function requestPQ(callback, channel) {
// Create a nonce for the client
var clientNonce = utility.createNonce(16);
mtproto.service.req_pq({
props: {
nonce: clientNonce
},
channel: channel,
callback: function (ex, resPQ) {
if (clientNonce === resPQ.nonce) {
var context = {
resPQ: resPQ,
channel: channel
};
callback(null, context);
} else {
callback(createError('Nonce mismatch.', 'ENONCE'));
}
}
});
} | javascript | function requestPQ(callback, channel) {
// Create a nonce for the client
var clientNonce = utility.createNonce(16);
mtproto.service.req_pq({
props: {
nonce: clientNonce
},
channel: channel,
callback: function (ex, resPQ) {
if (clientNonce === resPQ.nonce) {
var context = {
resPQ: resPQ,
channel: channel
};
callback(null, context);
} else {
callback(createError('Nonce mismatch.', 'ENONCE'));
}
}
});
} | [
"function",
"requestPQ",
"(",
"callback",
",",
"channel",
")",
"{",
"// Create a nonce for the client",
"var",
"clientNonce",
"=",
"utility",
".",
"createNonce",
"(",
"16",
")",
";",
"mtproto",
".",
"service",
".",
"req_pq",
"(",
"{",
"props",
":",
"{",
"nonce",
":",
"clientNonce",
"}",
",",
"channel",
":",
"channel",
",",
"callback",
":",
"function",
"(",
"ex",
",",
"resPQ",
")",
"{",
"if",
"(",
"clientNonce",
"===",
"resPQ",
".",
"nonce",
")",
"{",
"var",
"context",
"=",
"{",
"resPQ",
":",
"resPQ",
",",
"channel",
":",
"channel",
"}",
";",
"callback",
"(",
"null",
",",
"context",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"createError",
"(",
"'Nonce mismatch.'",
",",
"'ENONCE'",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | Request a PQ pair number | [
"Request",
"a",
"PQ",
"pair",
"number"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/request-pq.js#L27-L47 |
22,522 | enricostara/telegram-mt-node | lib/auth/request-pq.js | findPAndQ | function findPAndQ(context) {
var pqFinder = new security.PQFinder(context.resPQ.pq);
if (logger.isDebugEnabled()) {
logger.debug('Start finding P and Q, with PQ = %s', pqFinder.getPQPairNumber());
}
var pq = pqFinder.findPQ();
if (logger.isDebugEnabled()) {
logger.debug('Found P = %s and Q = %s', pq[0], pq[1]);
}
context.pBuffer = pqFinder.getPQAsBuffer()[0];
context.qBuffer = pqFinder.getPQAsBuffer()[1];
return context;
} | javascript | function findPAndQ(context) {
var pqFinder = new security.PQFinder(context.resPQ.pq);
if (logger.isDebugEnabled()) {
logger.debug('Start finding P and Q, with PQ = %s', pqFinder.getPQPairNumber());
}
var pq = pqFinder.findPQ();
if (logger.isDebugEnabled()) {
logger.debug('Found P = %s and Q = %s', pq[0], pq[1]);
}
context.pBuffer = pqFinder.getPQAsBuffer()[0];
context.qBuffer = pqFinder.getPQAsBuffer()[1];
return context;
} | [
"function",
"findPAndQ",
"(",
"context",
")",
"{",
"var",
"pqFinder",
"=",
"new",
"security",
".",
"PQFinder",
"(",
"context",
".",
"resPQ",
".",
"pq",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'Start finding P and Q, with PQ = %s'",
",",
"pqFinder",
".",
"getPQPairNumber",
"(",
")",
")",
";",
"}",
"var",
"pq",
"=",
"pqFinder",
".",
"findPQ",
"(",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'Found P = %s and Q = %s'",
",",
"pq",
"[",
"0",
"]",
",",
"pq",
"[",
"1",
"]",
")",
";",
"}",
"context",
".",
"pBuffer",
"=",
"pqFinder",
".",
"getPQAsBuffer",
"(",
")",
"[",
"0",
"]",
";",
"context",
".",
"qBuffer",
"=",
"pqFinder",
".",
"getPQAsBuffer",
"(",
")",
"[",
"1",
"]",
";",
"return",
"context",
";",
"}"
] | Find the P and Q prime numbers | [
"Find",
"the",
"P",
"and",
"Q",
"prime",
"numbers"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/request-pq.js#L50-L62 |
22,523 | enricostara/telegram-mt-node | lib/auth/request-pq.js | findPublicKey | function findPublicKey(context) {
var fingerprints = context.resPQ.server_public_key_fingerprints.getList();
if (logger.isDebugEnabled()) {
logger.debug('Public keys fingerprints from server: %s', fingerprints);
}
for (var i = 0; i < fingerprints.length; i++) {
var fingerprint = fingerprints[i];
if (logger.isDebugEnabled()) {
logger.debug('Searching fingerprint %s in store', fingerprint);
}
var publicKey = security.PublicKey.retrieveKey(fingerprint);
if (publicKey) {
if (logger.isDebugEnabled()) {
logger.debug('Fingerprint %s found in keyStore.', fingerprint);
}
context.fingerprint = fingerprint;
context.publicKey = publicKey;
return context;
}
}
throw createError('Fingerprints from server not found in keyStore.', 'EFINGERNOTFOUND');
} | javascript | function findPublicKey(context) {
var fingerprints = context.resPQ.server_public_key_fingerprints.getList();
if (logger.isDebugEnabled()) {
logger.debug('Public keys fingerprints from server: %s', fingerprints);
}
for (var i = 0; i < fingerprints.length; i++) {
var fingerprint = fingerprints[i];
if (logger.isDebugEnabled()) {
logger.debug('Searching fingerprint %s in store', fingerprint);
}
var publicKey = security.PublicKey.retrieveKey(fingerprint);
if (publicKey) {
if (logger.isDebugEnabled()) {
logger.debug('Fingerprint %s found in keyStore.', fingerprint);
}
context.fingerprint = fingerprint;
context.publicKey = publicKey;
return context;
}
}
throw createError('Fingerprints from server not found in keyStore.', 'EFINGERNOTFOUND');
} | [
"function",
"findPublicKey",
"(",
"context",
")",
"{",
"var",
"fingerprints",
"=",
"context",
".",
"resPQ",
".",
"server_public_key_fingerprints",
".",
"getList",
"(",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'Public keys fingerprints from server: %s'",
",",
"fingerprints",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"fingerprints",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"fingerprint",
"=",
"fingerprints",
"[",
"i",
"]",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'Searching fingerprint %s in store'",
",",
"fingerprint",
")",
";",
"}",
"var",
"publicKey",
"=",
"security",
".",
"PublicKey",
".",
"retrieveKey",
"(",
"fingerprint",
")",
";",
"if",
"(",
"publicKey",
")",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'Fingerprint %s found in keyStore.'",
",",
"fingerprint",
")",
";",
"}",
"context",
".",
"fingerprint",
"=",
"fingerprint",
";",
"context",
".",
"publicKey",
"=",
"publicKey",
";",
"return",
"context",
";",
"}",
"}",
"throw",
"createError",
"(",
"'Fingerprints from server not found in keyStore.'",
",",
"'EFINGERNOTFOUND'",
")",
";",
"}"
] | Find the correct Public Key using fingerprint from server response | [
"Find",
"the",
"correct",
"Public",
"Key",
"using",
"fingerprint",
"from",
"server",
"response"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/request-pq.js#L65-L86 |
22,524 | enricostara/telegram-mt-node | lib/utility.js | createMessageId | function createMessageId() {
var logger = getLogger('utility.createMessageId');
// Constants
// Take the time and sum the time-offset with the server clock
var time = new BigInteger((require('./time').getLocalTime()).toString());
// Divide the time by 1000 `result[0]` and take the fractional part `result[1]`
var result = time.divideAndRemainder(thousand);
// Prepare lower 32 bit using the fractional part of the time
var lower = result[1].multiply(lowerMultiplier);
// Create the message id
var messageId = result[0].shiftLeft(32).add(lower);
if (logger.isDebugEnabled()) {
logger.debug('MessageId(%s) was created with time = %s, lower = %s, messageID binary = %s',
messageId.toString(16), time, lower, messageId.toString(2));
}
return '0x' + messageId.toString(16);
} | javascript | function createMessageId() {
var logger = getLogger('utility.createMessageId');
// Constants
// Take the time and sum the time-offset with the server clock
var time = new BigInteger((require('./time').getLocalTime()).toString());
// Divide the time by 1000 `result[0]` and take the fractional part `result[1]`
var result = time.divideAndRemainder(thousand);
// Prepare lower 32 bit using the fractional part of the time
var lower = result[1].multiply(lowerMultiplier);
// Create the message id
var messageId = result[0].shiftLeft(32).add(lower);
if (logger.isDebugEnabled()) {
logger.debug('MessageId(%s) was created with time = %s, lower = %s, messageID binary = %s',
messageId.toString(16), time, lower, messageId.toString(2));
}
return '0x' + messageId.toString(16);
} | [
"function",
"createMessageId",
"(",
")",
"{",
"var",
"logger",
"=",
"getLogger",
"(",
"'utility.createMessageId'",
")",
";",
"// Constants",
"// Take the time and sum the time-offset with the server clock",
"var",
"time",
"=",
"new",
"BigInteger",
"(",
"(",
"require",
"(",
"'./time'",
")",
".",
"getLocalTime",
"(",
")",
")",
".",
"toString",
"(",
")",
")",
";",
"// Divide the time by 1000 `result[0]` and take the fractional part `result[1]`",
"var",
"result",
"=",
"time",
".",
"divideAndRemainder",
"(",
"thousand",
")",
";",
"// Prepare lower 32 bit using the fractional part of the time",
"var",
"lower",
"=",
"result",
"[",
"1",
"]",
".",
"multiply",
"(",
"lowerMultiplier",
")",
";",
"// Create the message id",
"var",
"messageId",
"=",
"result",
"[",
"0",
"]",
".",
"shiftLeft",
"(",
"32",
")",
".",
"add",
"(",
"lower",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'MessageId(%s) was created with time = %s, lower = %s, messageID binary = %s'",
",",
"messageId",
".",
"toString",
"(",
"16",
")",
",",
"time",
",",
"lower",
",",
"messageId",
".",
"toString",
"(",
"2",
")",
")",
";",
"}",
"return",
"'0x'",
"+",
"messageId",
".",
"toString",
"(",
"16",
")",
";",
"}"
] | Create a message ID starting from the local time | [
"Create",
"a",
"message",
"ID",
"starting",
"from",
"the",
"local",
"time"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/utility.js#L27-L43 |
22,525 | enricostara/telegram-mt-node | lib/utility.js | createSHAHash | function createSHAHash(buffer, algorithm) {
var logger = getLogger('utility.createSHA1Hash');
var sha1sum = crypto.createHash(algorithm || 'sha1');
if (require('util').isArray(buffer)) {
if (logger.isDebugEnabled()) {
logger.debug('It\'s an Array of buffers');
}
for (var i = 0; i < buffer.length; i++) {
sha1sum.update(buffer[i]);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug('It\'s only one buffer');
}
sha1sum.update(buffer);
}
return sha1sum.digest();
} | javascript | function createSHAHash(buffer, algorithm) {
var logger = getLogger('utility.createSHA1Hash');
var sha1sum = crypto.createHash(algorithm || 'sha1');
if (require('util').isArray(buffer)) {
if (logger.isDebugEnabled()) {
logger.debug('It\'s an Array of buffers');
}
for (var i = 0; i < buffer.length; i++) {
sha1sum.update(buffer[i]);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug('It\'s only one buffer');
}
sha1sum.update(buffer);
}
return sha1sum.digest();
} | [
"function",
"createSHAHash",
"(",
"buffer",
",",
"algorithm",
")",
"{",
"var",
"logger",
"=",
"getLogger",
"(",
"'utility.createSHA1Hash'",
")",
";",
"var",
"sha1sum",
"=",
"crypto",
".",
"createHash",
"(",
"algorithm",
"||",
"'sha1'",
")",
";",
"if",
"(",
"require",
"(",
"'util'",
")",
".",
"isArray",
"(",
"buffer",
")",
")",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'It\\'s an Array of buffers'",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"buffer",
".",
"length",
";",
"i",
"++",
")",
"{",
"sha1sum",
".",
"update",
"(",
"buffer",
"[",
"i",
"]",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'It\\'s only one buffer'",
")",
";",
"}",
"sha1sum",
".",
"update",
"(",
"buffer",
")",
";",
"}",
"return",
"sha1sum",
".",
"digest",
"(",
")",
";",
"}"
] | Create SHA1 hash starting from a buffer or an array of buffers | [
"Create",
"SHA1",
"hash",
"starting",
"from",
"a",
"buffer",
"or",
"an",
"array",
"of",
"buffers"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/utility.js#L46-L63 |
22,526 | enricostara/telegram-mt-node | lib/utility.js | xor | function xor(buffer1, buffer2) {
var length = Math.min(buffer1.length, buffer2.length);
var retBuffer = new Buffer(length);
for (var i = 0; i < length; i++) {
retBuffer[i] = buffer1[i] ^ buffer2[i];
}
return retBuffer;
} | javascript | function xor(buffer1, buffer2) {
var length = Math.min(buffer1.length, buffer2.length);
var retBuffer = new Buffer(length);
for (var i = 0; i < length; i++) {
retBuffer[i] = buffer1[i] ^ buffer2[i];
}
return retBuffer;
} | [
"function",
"xor",
"(",
"buffer1",
",",
"buffer2",
")",
"{",
"var",
"length",
"=",
"Math",
".",
"min",
"(",
"buffer1",
".",
"length",
",",
"buffer2",
".",
"length",
")",
";",
"var",
"retBuffer",
"=",
"new",
"Buffer",
"(",
"length",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"retBuffer",
"[",
"i",
"]",
"=",
"buffer1",
"[",
"i",
"]",
"^",
"buffer2",
"[",
"i",
"]",
";",
"}",
"return",
"retBuffer",
";",
"}"
] | Xor op on buffers | [
"Xor",
"op",
"on",
"buffers"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/utility.js#L93-L100 |
22,527 | enricostara/telegram-mt-node | lib/auth/request-dh-params.js | createPQInnerData | function createPQInnerData(context) {
var resPQ = context.resPQ;
var newNonce = utility.createNonce(32);
var pqInnerData = new mtproto.type.P_q_inner_data({
props: {
pq: resPQ.pq,
p: context.pBuffer,
q: context.qBuffer,
nonce: resPQ.nonce,
server_nonce: resPQ.server_nonce,
new_nonce: newNonce
}
}).serialize();
context.pqInnerData = pqInnerData;
context.newNonce = newNonce;
return context;
} | javascript | function createPQInnerData(context) {
var resPQ = context.resPQ;
var newNonce = utility.createNonce(32);
var pqInnerData = new mtproto.type.P_q_inner_data({
props: {
pq: resPQ.pq,
p: context.pBuffer,
q: context.qBuffer,
nonce: resPQ.nonce,
server_nonce: resPQ.server_nonce,
new_nonce: newNonce
}
}).serialize();
context.pqInnerData = pqInnerData;
context.newNonce = newNonce;
return context;
} | [
"function",
"createPQInnerData",
"(",
"context",
")",
"{",
"var",
"resPQ",
"=",
"context",
".",
"resPQ",
";",
"var",
"newNonce",
"=",
"utility",
".",
"createNonce",
"(",
"32",
")",
";",
"var",
"pqInnerData",
"=",
"new",
"mtproto",
".",
"type",
".",
"P_q_inner_data",
"(",
"{",
"props",
":",
"{",
"pq",
":",
"resPQ",
".",
"pq",
",",
"p",
":",
"context",
".",
"pBuffer",
",",
"q",
":",
"context",
".",
"qBuffer",
",",
"nonce",
":",
"resPQ",
".",
"nonce",
",",
"server_nonce",
":",
"resPQ",
".",
"server_nonce",
",",
"new_nonce",
":",
"newNonce",
"}",
"}",
")",
".",
"serialize",
"(",
")",
";",
"context",
".",
"pqInnerData",
"=",
"pqInnerData",
";",
"context",
".",
"newNonce",
"=",
"newNonce",
";",
"return",
"context",
";",
"}"
] | Create the pq_inner_data buffer | [
"Create",
"the",
"pq_inner_data",
"buffer"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/request-dh-params.js#L32-L48 |
22,528 | enricostara/telegram-mt-node | lib/auth/request-dh-params.js | encryptPQInnerDataWithRSA | function encryptPQInnerDataWithRSA(context) {
// Create the data with hash to be encrypt
var hash = utility.createSHAHash(context.pqInnerData);
var dataWithHash = Buffer.concat([hash, context.pqInnerData]);
if (logger.isDebugEnabled()) {
logger.debug('Data to be encrypted contains: hash(%s), pqInnerData(%s), total length %s',
hash.length, context.pqInnerData.length, dataWithHash.length);
}
// Encrypt data with RSA
context.encryptedData = security.cipher.rsaEncrypt(dataWithHash, context.publicKey);
return context;
} | javascript | function encryptPQInnerDataWithRSA(context) {
// Create the data with hash to be encrypt
var hash = utility.createSHAHash(context.pqInnerData);
var dataWithHash = Buffer.concat([hash, context.pqInnerData]);
if (logger.isDebugEnabled()) {
logger.debug('Data to be encrypted contains: hash(%s), pqInnerData(%s), total length %s',
hash.length, context.pqInnerData.length, dataWithHash.length);
}
// Encrypt data with RSA
context.encryptedData = security.cipher.rsaEncrypt(dataWithHash, context.publicKey);
return context;
} | [
"function",
"encryptPQInnerDataWithRSA",
"(",
"context",
")",
"{",
"// Create the data with hash to be encrypt",
"var",
"hash",
"=",
"utility",
".",
"createSHAHash",
"(",
"context",
".",
"pqInnerData",
")",
";",
"var",
"dataWithHash",
"=",
"Buffer",
".",
"concat",
"(",
"[",
"hash",
",",
"context",
".",
"pqInnerData",
"]",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'Data to be encrypted contains: hash(%s), pqInnerData(%s), total length %s'",
",",
"hash",
".",
"length",
",",
"context",
".",
"pqInnerData",
".",
"length",
",",
"dataWithHash",
".",
"length",
")",
";",
"}",
"// Encrypt data with RSA",
"context",
".",
"encryptedData",
"=",
"security",
".",
"cipher",
".",
"rsaEncrypt",
"(",
"dataWithHash",
",",
"context",
".",
"publicKey",
")",
";",
"return",
"context",
";",
"}"
] | Encrypt the pq_inner_data with RSA | [
"Encrypt",
"the",
"pq_inner_data",
"with",
"RSA"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/request-dh-params.js#L51-L62 |
22,529 | enricostara/telegram-mt-node | lib/auth/request-dh-params.js | requestDHParams | function requestDHParams(callback, context) {
var resPQ = context.resPQ;
mtproto.service.req_DH_params({
props: {
nonce: resPQ.nonce,
server_nonce: resPQ.server_nonce,
p: context.pBuffer,
q: context.qBuffer,
public_key_fingerprint: context.fingerprint,
encrypted_data: context.encryptedData
},
channel: context.channel,
callback: function (ex, serverDHParams, duration) {
if (ex) {
logger.error(ex);
if (callback) {
callback(ex);
}
} else {
if (serverDHParams.instanceOf('mtproto.type.Server_DH_params_ok')) {
if (logger.isDebugEnabled()) {
logger.debug('\'Server_DH_params_ok\' received from Telegram.');
}
context.serverDHParams = serverDHParams;
context.reqDHDuration = duration;
callback(null, context);
} else if (serverDHParams.instanceOf('mtproto.type.Server_DH_params_ko')) {
logger.warn('\'Server_DH_params_ko\' received from Telegram!');
callback(createError(JSON.stringify(serverDHParams), 'EDHPARAMKO'));
} else {
var msg = 'Unknown error received from Telegram!';
logger.error(msg);
callback(createError(msg, 'EUNKNOWN'));
}
}
}
});
} | javascript | function requestDHParams(callback, context) {
var resPQ = context.resPQ;
mtproto.service.req_DH_params({
props: {
nonce: resPQ.nonce,
server_nonce: resPQ.server_nonce,
p: context.pBuffer,
q: context.qBuffer,
public_key_fingerprint: context.fingerprint,
encrypted_data: context.encryptedData
},
channel: context.channel,
callback: function (ex, serverDHParams, duration) {
if (ex) {
logger.error(ex);
if (callback) {
callback(ex);
}
} else {
if (serverDHParams.instanceOf('mtproto.type.Server_DH_params_ok')) {
if (logger.isDebugEnabled()) {
logger.debug('\'Server_DH_params_ok\' received from Telegram.');
}
context.serverDHParams = serverDHParams;
context.reqDHDuration = duration;
callback(null, context);
} else if (serverDHParams.instanceOf('mtproto.type.Server_DH_params_ko')) {
logger.warn('\'Server_DH_params_ko\' received from Telegram!');
callback(createError(JSON.stringify(serverDHParams), 'EDHPARAMKO'));
} else {
var msg = 'Unknown error received from Telegram!';
logger.error(msg);
callback(createError(msg, 'EUNKNOWN'));
}
}
}
});
} | [
"function",
"requestDHParams",
"(",
"callback",
",",
"context",
")",
"{",
"var",
"resPQ",
"=",
"context",
".",
"resPQ",
";",
"mtproto",
".",
"service",
".",
"req_DH_params",
"(",
"{",
"props",
":",
"{",
"nonce",
":",
"resPQ",
".",
"nonce",
",",
"server_nonce",
":",
"resPQ",
".",
"server_nonce",
",",
"p",
":",
"context",
".",
"pBuffer",
",",
"q",
":",
"context",
".",
"qBuffer",
",",
"public_key_fingerprint",
":",
"context",
".",
"fingerprint",
",",
"encrypted_data",
":",
"context",
".",
"encryptedData",
"}",
",",
"channel",
":",
"context",
".",
"channel",
",",
"callback",
":",
"function",
"(",
"ex",
",",
"serverDHParams",
",",
"duration",
")",
"{",
"if",
"(",
"ex",
")",
"{",
"logger",
".",
"error",
"(",
"ex",
")",
";",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"ex",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"serverDHParams",
".",
"instanceOf",
"(",
"'mtproto.type.Server_DH_params_ok'",
")",
")",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'\\'Server_DH_params_ok\\' received from Telegram.'",
")",
";",
"}",
"context",
".",
"serverDHParams",
"=",
"serverDHParams",
";",
"context",
".",
"reqDHDuration",
"=",
"duration",
";",
"callback",
"(",
"null",
",",
"context",
")",
";",
"}",
"else",
"if",
"(",
"serverDHParams",
".",
"instanceOf",
"(",
"'mtproto.type.Server_DH_params_ko'",
")",
")",
"{",
"logger",
".",
"warn",
"(",
"'\\'Server_DH_params_ko\\' received from Telegram!'",
")",
";",
"callback",
"(",
"createError",
"(",
"JSON",
".",
"stringify",
"(",
"serverDHParams",
")",
",",
"'EDHPARAMKO'",
")",
")",
";",
"}",
"else",
"{",
"var",
"msg",
"=",
"'Unknown error received from Telegram!'",
";",
"logger",
".",
"error",
"(",
"msg",
")",
";",
"callback",
"(",
"createError",
"(",
"msg",
",",
"'EUNKNOWN'",
")",
")",
";",
"}",
"}",
"}",
"}",
")",
";",
"}"
] | Request server DH parameters | [
"Request",
"server",
"DH",
"parameters"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/request-dh-params.js#L65-L102 |
22,530 | enricostara/telegram-mt-node | lib/auth/request-dh-params.js | decryptDHParams | function decryptDHParams(context) {
var newNonce = utility.string2Buffer(context.newNonce, 32);
var serverNonce = utility.string2Buffer(context.resPQ.server_nonce, 16);
if (logger.isDebugEnabled()) {
logger.debug('newNonce = %s, serverNonce = %s', newNonce.toString('hex'), serverNonce.toString('hex'));
}
var hashNS = utility.createSHAHash([newNonce, serverNonce]);
var hashSN = utility.createSHAHash([serverNonce, newNonce]);
var hashNN = utility.createSHAHash([newNonce, newNonce]);
if (logger.isDebugEnabled()) {
logger.debug('hashNS = %s, hashSN = %s, hashNN = %s',
hashNS.toString('hex'), hashSN.toString('hex'), hashNN.toString('hex'));
}
// Create the AES key
context.aes = {
key: Buffer.concat([hashNS, hashSN.slice(0, 12)]),
iv: Buffer.concat([Buffer.concat([hashSN.slice(12), hashNN]), newNonce.slice(0, 4)]),
toPrintable: tl.utility.toPrintable
};
if (logger.isDebugEnabled()) {
logger.debug('aesKey = %s', context.aes.toPrintable());
}
// Decrypt the message
var answerWithHash = security.cipher.aesDecrypt(
context.serverDHParams.encrypted_answer,
context.aes.key,
context.aes.iv
);
context.decryptedDHParams = answerWithHash;
return context;
} | javascript | function decryptDHParams(context) {
var newNonce = utility.string2Buffer(context.newNonce, 32);
var serverNonce = utility.string2Buffer(context.resPQ.server_nonce, 16);
if (logger.isDebugEnabled()) {
logger.debug('newNonce = %s, serverNonce = %s', newNonce.toString('hex'), serverNonce.toString('hex'));
}
var hashNS = utility.createSHAHash([newNonce, serverNonce]);
var hashSN = utility.createSHAHash([serverNonce, newNonce]);
var hashNN = utility.createSHAHash([newNonce, newNonce]);
if (logger.isDebugEnabled()) {
logger.debug('hashNS = %s, hashSN = %s, hashNN = %s',
hashNS.toString('hex'), hashSN.toString('hex'), hashNN.toString('hex'));
}
// Create the AES key
context.aes = {
key: Buffer.concat([hashNS, hashSN.slice(0, 12)]),
iv: Buffer.concat([Buffer.concat([hashSN.slice(12), hashNN]), newNonce.slice(0, 4)]),
toPrintable: tl.utility.toPrintable
};
if (logger.isDebugEnabled()) {
logger.debug('aesKey = %s', context.aes.toPrintable());
}
// Decrypt the message
var answerWithHash = security.cipher.aesDecrypt(
context.serverDHParams.encrypted_answer,
context.aes.key,
context.aes.iv
);
context.decryptedDHParams = answerWithHash;
return context;
} | [
"function",
"decryptDHParams",
"(",
"context",
")",
"{",
"var",
"newNonce",
"=",
"utility",
".",
"string2Buffer",
"(",
"context",
".",
"newNonce",
",",
"32",
")",
";",
"var",
"serverNonce",
"=",
"utility",
".",
"string2Buffer",
"(",
"context",
".",
"resPQ",
".",
"server_nonce",
",",
"16",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'newNonce = %s, serverNonce = %s'",
",",
"newNonce",
".",
"toString",
"(",
"'hex'",
")",
",",
"serverNonce",
".",
"toString",
"(",
"'hex'",
")",
")",
";",
"}",
"var",
"hashNS",
"=",
"utility",
".",
"createSHAHash",
"(",
"[",
"newNonce",
",",
"serverNonce",
"]",
")",
";",
"var",
"hashSN",
"=",
"utility",
".",
"createSHAHash",
"(",
"[",
"serverNonce",
",",
"newNonce",
"]",
")",
";",
"var",
"hashNN",
"=",
"utility",
".",
"createSHAHash",
"(",
"[",
"newNonce",
",",
"newNonce",
"]",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'hashNS = %s, hashSN = %s, hashNN = %s'",
",",
"hashNS",
".",
"toString",
"(",
"'hex'",
")",
",",
"hashSN",
".",
"toString",
"(",
"'hex'",
")",
",",
"hashNN",
".",
"toString",
"(",
"'hex'",
")",
")",
";",
"}",
"// Create the AES key",
"context",
".",
"aes",
"=",
"{",
"key",
":",
"Buffer",
".",
"concat",
"(",
"[",
"hashNS",
",",
"hashSN",
".",
"slice",
"(",
"0",
",",
"12",
")",
"]",
")",
",",
"iv",
":",
"Buffer",
".",
"concat",
"(",
"[",
"Buffer",
".",
"concat",
"(",
"[",
"hashSN",
".",
"slice",
"(",
"12",
")",
",",
"hashNN",
"]",
")",
",",
"newNonce",
".",
"slice",
"(",
"0",
",",
"4",
")",
"]",
")",
",",
"toPrintable",
":",
"tl",
".",
"utility",
".",
"toPrintable",
"}",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'aesKey = %s'",
",",
"context",
".",
"aes",
".",
"toPrintable",
"(",
")",
")",
";",
"}",
"// Decrypt the message",
"var",
"answerWithHash",
"=",
"security",
".",
"cipher",
".",
"aesDecrypt",
"(",
"context",
".",
"serverDHParams",
".",
"encrypted_answer",
",",
"context",
".",
"aes",
".",
"key",
",",
"context",
".",
"aes",
".",
"iv",
")",
";",
"context",
".",
"decryptedDHParams",
"=",
"answerWithHash",
";",
"return",
"context",
";",
"}"
] | Decrypt DH parameters and synch the local time with the server time | [
"Decrypt",
"DH",
"parameters",
"and",
"synch",
"the",
"local",
"time",
"with",
"the",
"server",
"time"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/request-dh-params.js#L105-L136 |
22,531 | enricostara/telegram-mt-node | lib/auth/request-dh-params.js | deserializeDHInnerData | function deserializeDHInnerData(context) {
var decryptedDHParamsWithHash = context.decryptedDHParams;
if (logger.isDebugEnabled()) {
logger.debug('decryptedDHParamsWithHash(%s) = %s', decryptedDHParamsWithHash.length, decryptedDHParamsWithHash.toString('hex'));
}
var decryptedDHParams = decryptedDHParamsWithHash.slice(20, 564 + 20);
if (logger.isDebugEnabled()) {
logger.debug('decryptedDHParams(%s) = %s', decryptedDHParams.length, decryptedDHParams.toString('hex'));
}
var serverDHInnerData = new mtproto.type.Server_DH_inner_data({
buffer: decryptedDHParams
}).deserialize();
if (logger.isDebugEnabled()) {
logger.debug('serverDHInnerData = %s obtained in %sms', serverDHInnerData.toPrintable(), context.reqDHDuration);
}
// Check if the nonces are consistent
if (serverDHInnerData.nonce !== context.serverDHParams.nonce) {
throw createError('Nonce mismatch %s != %s', context.serverDHParams.nonce, serverDHInnerData.nonce);
}
if (serverDHInnerData.server_nonce !== context.serverDHParams.server_nonce) {
throw createError('ServerNonce mismatch %s != %s', context.serverDHParams.server_nonce, serverDHInnerData.server_nonce);
}
// Synch the local time with the server time
mtproto.time.timeSynchronization(serverDHInnerData.server_time, context.reqDHDuration);
context.serverDHInnerData = serverDHInnerData;
return context;
} | javascript | function deserializeDHInnerData(context) {
var decryptedDHParamsWithHash = context.decryptedDHParams;
if (logger.isDebugEnabled()) {
logger.debug('decryptedDHParamsWithHash(%s) = %s', decryptedDHParamsWithHash.length, decryptedDHParamsWithHash.toString('hex'));
}
var decryptedDHParams = decryptedDHParamsWithHash.slice(20, 564 + 20);
if (logger.isDebugEnabled()) {
logger.debug('decryptedDHParams(%s) = %s', decryptedDHParams.length, decryptedDHParams.toString('hex'));
}
var serverDHInnerData = new mtproto.type.Server_DH_inner_data({
buffer: decryptedDHParams
}).deserialize();
if (logger.isDebugEnabled()) {
logger.debug('serverDHInnerData = %s obtained in %sms', serverDHInnerData.toPrintable(), context.reqDHDuration);
}
// Check if the nonces are consistent
if (serverDHInnerData.nonce !== context.serverDHParams.nonce) {
throw createError('Nonce mismatch %s != %s', context.serverDHParams.nonce, serverDHInnerData.nonce);
}
if (serverDHInnerData.server_nonce !== context.serverDHParams.server_nonce) {
throw createError('ServerNonce mismatch %s != %s', context.serverDHParams.server_nonce, serverDHInnerData.server_nonce);
}
// Synch the local time with the server time
mtproto.time.timeSynchronization(serverDHInnerData.server_time, context.reqDHDuration);
context.serverDHInnerData = serverDHInnerData;
return context;
} | [
"function",
"deserializeDHInnerData",
"(",
"context",
")",
"{",
"var",
"decryptedDHParamsWithHash",
"=",
"context",
".",
"decryptedDHParams",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'decryptedDHParamsWithHash(%s) = %s'",
",",
"decryptedDHParamsWithHash",
".",
"length",
",",
"decryptedDHParamsWithHash",
".",
"toString",
"(",
"'hex'",
")",
")",
";",
"}",
"var",
"decryptedDHParams",
"=",
"decryptedDHParamsWithHash",
".",
"slice",
"(",
"20",
",",
"564",
"+",
"20",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'decryptedDHParams(%s) = %s'",
",",
"decryptedDHParams",
".",
"length",
",",
"decryptedDHParams",
".",
"toString",
"(",
"'hex'",
")",
")",
";",
"}",
"var",
"serverDHInnerData",
"=",
"new",
"mtproto",
".",
"type",
".",
"Server_DH_inner_data",
"(",
"{",
"buffer",
":",
"decryptedDHParams",
"}",
")",
".",
"deserialize",
"(",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'serverDHInnerData = %s obtained in %sms'",
",",
"serverDHInnerData",
".",
"toPrintable",
"(",
")",
",",
"context",
".",
"reqDHDuration",
")",
";",
"}",
"// Check if the nonces are consistent",
"if",
"(",
"serverDHInnerData",
".",
"nonce",
"!==",
"context",
".",
"serverDHParams",
".",
"nonce",
")",
"{",
"throw",
"createError",
"(",
"'Nonce mismatch %s != %s'",
",",
"context",
".",
"serverDHParams",
".",
"nonce",
",",
"serverDHInnerData",
".",
"nonce",
")",
";",
"}",
"if",
"(",
"serverDHInnerData",
".",
"server_nonce",
"!==",
"context",
".",
"serverDHParams",
".",
"server_nonce",
")",
"{",
"throw",
"createError",
"(",
"'ServerNonce mismatch %s != %s'",
",",
"context",
".",
"serverDHParams",
".",
"server_nonce",
",",
"serverDHInnerData",
".",
"server_nonce",
")",
";",
"}",
"// Synch the local time with the server time",
"mtproto",
".",
"time",
".",
"timeSynchronization",
"(",
"serverDHInnerData",
".",
"server_time",
",",
"context",
".",
"reqDHDuration",
")",
";",
"context",
".",
"serverDHInnerData",
"=",
"serverDHInnerData",
";",
"return",
"context",
";",
"}"
] | De-serialize the server DH inner data | [
"De",
"-",
"serialize",
"the",
"server",
"DH",
"inner",
"data"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/request-dh-params.js#L139-L165 |
22,532 | enricostara/telegram-mt-node | lib/security/cipher.js | aesDecrypt | function aesDecrypt(msg, key, iv) {
var logger = getLogger('security.cipher.aesDecrypt');
var encryptedMsg = buffer2WordArray(msg);
var keyWordArray = buffer2WordArray(key);
var ivWordArray = buffer2WordArray(iv);
if (logger.isDebugEnabled()) {
logger.debug('encryptedMsg = %s\nkeyWordArray = %s\nivWordArray = %s',
JSON.stringify(encryptedMsg), JSON.stringify(keyWordArray), JSON.stringify(ivWordArray));
}
var decryptedWordArray = CryptoJS.AES.decrypt({ciphertext: encryptedMsg}, keyWordArray, {
iv: ivWordArray,
padding: CryptoJS.pad.NoPadding,
mode: CryptoJS.mode.IGE
});
if (logger.isDebugEnabled()) {
logger.debug('decryptedWordArray = %s', JSON.stringify(decryptedWordArray));
}
return wordArray2Buffer(decryptedWordArray);
} | javascript | function aesDecrypt(msg, key, iv) {
var logger = getLogger('security.cipher.aesDecrypt');
var encryptedMsg = buffer2WordArray(msg);
var keyWordArray = buffer2WordArray(key);
var ivWordArray = buffer2WordArray(iv);
if (logger.isDebugEnabled()) {
logger.debug('encryptedMsg = %s\nkeyWordArray = %s\nivWordArray = %s',
JSON.stringify(encryptedMsg), JSON.stringify(keyWordArray), JSON.stringify(ivWordArray));
}
var decryptedWordArray = CryptoJS.AES.decrypt({ciphertext: encryptedMsg}, keyWordArray, {
iv: ivWordArray,
padding: CryptoJS.pad.NoPadding,
mode: CryptoJS.mode.IGE
});
if (logger.isDebugEnabled()) {
logger.debug('decryptedWordArray = %s', JSON.stringify(decryptedWordArray));
}
return wordArray2Buffer(decryptedWordArray);
} | [
"function",
"aesDecrypt",
"(",
"msg",
",",
"key",
",",
"iv",
")",
"{",
"var",
"logger",
"=",
"getLogger",
"(",
"'security.cipher.aesDecrypt'",
")",
";",
"var",
"encryptedMsg",
"=",
"buffer2WordArray",
"(",
"msg",
")",
";",
"var",
"keyWordArray",
"=",
"buffer2WordArray",
"(",
"key",
")",
";",
"var",
"ivWordArray",
"=",
"buffer2WordArray",
"(",
"iv",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'encryptedMsg = %s\\nkeyWordArray = %s\\nivWordArray = %s'",
",",
"JSON",
".",
"stringify",
"(",
"encryptedMsg",
")",
",",
"JSON",
".",
"stringify",
"(",
"keyWordArray",
")",
",",
"JSON",
".",
"stringify",
"(",
"ivWordArray",
")",
")",
";",
"}",
"var",
"decryptedWordArray",
"=",
"CryptoJS",
".",
"AES",
".",
"decrypt",
"(",
"{",
"ciphertext",
":",
"encryptedMsg",
"}",
",",
"keyWordArray",
",",
"{",
"iv",
":",
"ivWordArray",
",",
"padding",
":",
"CryptoJS",
".",
"pad",
".",
"NoPadding",
",",
"mode",
":",
"CryptoJS",
".",
"mode",
".",
"IGE",
"}",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'decryptedWordArray = %s'",
",",
"JSON",
".",
"stringify",
"(",
"decryptedWordArray",
")",
")",
";",
"}",
"return",
"wordArray2Buffer",
"(",
"decryptedWordArray",
")",
";",
"}"
] | AES decrypt function | [
"AES",
"decrypt",
"function"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/security/cipher.js#L50-L68 |
22,533 | enricostara/telegram-mt-node | lib/security/cipher.js | aesEncrypt | function aesEncrypt(msg, key, iv) {
var logger = getLogger('security.cipher.aesEncrypt');
// Check if padding is needed
var padding = msg.length % 16;
if (padding > 0) {
var paddingBuffer = utility.createRandomBuffer(16 - padding);
msg = Buffer.concat([msg, paddingBuffer]);
}
// Convert buffers to wordArrays
var plainMsg = buffer2WordArray(msg);
var keyWordArray = buffer2WordArray(key);
var ivWordArray = buffer2WordArray(iv);
if (logger.isDebugEnabled()) {
logger.debug('plainMsg = %s\nkeyWordArray = %s\nivWordArray = %s',
JSON.stringify(plainMsg), JSON.stringify(keyWordArray), JSON.stringify(ivWordArray));
}
// Encrypt plain message
var encryptedWordArray = CryptoJS.AES.encrypt(plainMsg, keyWordArray, {
iv: ivWordArray,
padding: CryptoJS.pad.NoPadding,
mode: CryptoJS.mode.IGE
}).ciphertext;
if (logger.isDebugEnabled()) {
logger.debug('encryptedWordArray = %s', JSON.stringify(encryptedWordArray));
}
// Return the encrypted buffer
return wordArray2Buffer(encryptedWordArray);
} | javascript | function aesEncrypt(msg, key, iv) {
var logger = getLogger('security.cipher.aesEncrypt');
// Check if padding is needed
var padding = msg.length % 16;
if (padding > 0) {
var paddingBuffer = utility.createRandomBuffer(16 - padding);
msg = Buffer.concat([msg, paddingBuffer]);
}
// Convert buffers to wordArrays
var plainMsg = buffer2WordArray(msg);
var keyWordArray = buffer2WordArray(key);
var ivWordArray = buffer2WordArray(iv);
if (logger.isDebugEnabled()) {
logger.debug('plainMsg = %s\nkeyWordArray = %s\nivWordArray = %s',
JSON.stringify(plainMsg), JSON.stringify(keyWordArray), JSON.stringify(ivWordArray));
}
// Encrypt plain message
var encryptedWordArray = CryptoJS.AES.encrypt(plainMsg, keyWordArray, {
iv: ivWordArray,
padding: CryptoJS.pad.NoPadding,
mode: CryptoJS.mode.IGE
}).ciphertext;
if (logger.isDebugEnabled()) {
logger.debug('encryptedWordArray = %s', JSON.stringify(encryptedWordArray));
}
// Return the encrypted buffer
return wordArray2Buffer(encryptedWordArray);
} | [
"function",
"aesEncrypt",
"(",
"msg",
",",
"key",
",",
"iv",
")",
"{",
"var",
"logger",
"=",
"getLogger",
"(",
"'security.cipher.aesEncrypt'",
")",
";",
"// Check if padding is needed",
"var",
"padding",
"=",
"msg",
".",
"length",
"%",
"16",
";",
"if",
"(",
"padding",
">",
"0",
")",
"{",
"var",
"paddingBuffer",
"=",
"utility",
".",
"createRandomBuffer",
"(",
"16",
"-",
"padding",
")",
";",
"msg",
"=",
"Buffer",
".",
"concat",
"(",
"[",
"msg",
",",
"paddingBuffer",
"]",
")",
";",
"}",
"// Convert buffers to wordArrays",
"var",
"plainMsg",
"=",
"buffer2WordArray",
"(",
"msg",
")",
";",
"var",
"keyWordArray",
"=",
"buffer2WordArray",
"(",
"key",
")",
";",
"var",
"ivWordArray",
"=",
"buffer2WordArray",
"(",
"iv",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'plainMsg = %s\\nkeyWordArray = %s\\nivWordArray = %s'",
",",
"JSON",
".",
"stringify",
"(",
"plainMsg",
")",
",",
"JSON",
".",
"stringify",
"(",
"keyWordArray",
")",
",",
"JSON",
".",
"stringify",
"(",
"ivWordArray",
")",
")",
";",
"}",
"// Encrypt plain message",
"var",
"encryptedWordArray",
"=",
"CryptoJS",
".",
"AES",
".",
"encrypt",
"(",
"plainMsg",
",",
"keyWordArray",
",",
"{",
"iv",
":",
"ivWordArray",
",",
"padding",
":",
"CryptoJS",
".",
"pad",
".",
"NoPadding",
",",
"mode",
":",
"CryptoJS",
".",
"mode",
".",
"IGE",
"}",
")",
".",
"ciphertext",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'encryptedWordArray = %s'",
",",
"JSON",
".",
"stringify",
"(",
"encryptedWordArray",
")",
")",
";",
"}",
"// Return the encrypted buffer",
"return",
"wordArray2Buffer",
"(",
"encryptedWordArray",
")",
";",
"}"
] | AES encrypt function | [
"AES",
"encrypt",
"function"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/security/cipher.js#L71-L98 |
22,534 | enricostara/telegram-mt-node | lib/time.js | timeSynchronization | function timeSynchronization(serverTime, requestDuration) {
var logger = getLogger('time.timeSynchronization');
var localTime = Math.floor(new Date().getTime() / 1000);
var response = requestDuration / 2;
if (logger.isDebugEnabled()) {
logger.debug('ServerTime %ss - LocalTime %ss - Response in %sms',
serverTime, localTime, response);
}
if (lastResponse > response) {
lastResponse = response;
response = Math.floor(response / 1000);
timeOffset = ((serverTime + response) - localTime);
if (logger.isDebugEnabled()) {
logger.debug('time-synchronization: (ServerTime %ss + server-response %ss) - LocalTime %ss = timeOffset %ss',
serverTime, response, localTime, timeOffset);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug('NO time-synchronization: the server-response (%s) took more time than the previous one (%s)',
response, lastResponse);
}
}
} | javascript | function timeSynchronization(serverTime, requestDuration) {
var logger = getLogger('time.timeSynchronization');
var localTime = Math.floor(new Date().getTime() / 1000);
var response = requestDuration / 2;
if (logger.isDebugEnabled()) {
logger.debug('ServerTime %ss - LocalTime %ss - Response in %sms',
serverTime, localTime, response);
}
if (lastResponse > response) {
lastResponse = response;
response = Math.floor(response / 1000);
timeOffset = ((serverTime + response) - localTime);
if (logger.isDebugEnabled()) {
logger.debug('time-synchronization: (ServerTime %ss + server-response %ss) - LocalTime %ss = timeOffset %ss',
serverTime, response, localTime, timeOffset);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug('NO time-synchronization: the server-response (%s) took more time than the previous one (%s)',
response, lastResponse);
}
}
} | [
"function",
"timeSynchronization",
"(",
"serverTime",
",",
"requestDuration",
")",
"{",
"var",
"logger",
"=",
"getLogger",
"(",
"'time.timeSynchronization'",
")",
";",
"var",
"localTime",
"=",
"Math",
".",
"floor",
"(",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"/",
"1000",
")",
";",
"var",
"response",
"=",
"requestDuration",
"/",
"2",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'ServerTime %ss - LocalTime %ss - Response in %sms'",
",",
"serverTime",
",",
"localTime",
",",
"response",
")",
";",
"}",
"if",
"(",
"lastResponse",
">",
"response",
")",
"{",
"lastResponse",
"=",
"response",
";",
"response",
"=",
"Math",
".",
"floor",
"(",
"response",
"/",
"1000",
")",
";",
"timeOffset",
"=",
"(",
"(",
"serverTime",
"+",
"response",
")",
"-",
"localTime",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'time-synchronization: (ServerTime %ss + server-response %ss) - LocalTime %ss = timeOffset %ss'",
",",
"serverTime",
",",
"response",
",",
"localTime",
",",
"timeOffset",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'NO time-synchronization: the server-response (%s) took more time than the previous one (%s)'",
",",
"response",
",",
"lastResponse",
")",
";",
"}",
"}",
"}"
] | Synchronize the local time with the server time | [
"Synchronize",
"the",
"local",
"time",
"with",
"the",
"server",
"time"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/time.js#L28-L50 |
22,535 | enricostara/telegram-mt-node | lib/auth/set-client-dh-params.js | encryptClientDHInnerDataWithAES | function encryptClientDHInnerDataWithAES(context) {
var hash = utility.createSHAHash(context.clientDHInnerData);
var dataWithHash = Buffer.concat([hash, context.clientDHInnerData]);
if (logger.isDebugEnabled()) {
logger.debug('Data to be encrypted contains: hash(%s), clientDHInnerData(%s), total length %s',
hash.length, context.clientDHInnerData.length, dataWithHash.length);
}
context.encryptClientDHInnerData = security.cipher.aesEncrypt(
dataWithHash,
context.aes.key,
context.aes.iv
);
if (logger.isDebugEnabled()) {
logger.debug('encryptClientDHInnerData(%s) = %s',
context.encryptClientDHInnerData.length, context.encryptClientDHInnerData.toString('hex'));
}
return context;
} | javascript | function encryptClientDHInnerDataWithAES(context) {
var hash = utility.createSHAHash(context.clientDHInnerData);
var dataWithHash = Buffer.concat([hash, context.clientDHInnerData]);
if (logger.isDebugEnabled()) {
logger.debug('Data to be encrypted contains: hash(%s), clientDHInnerData(%s), total length %s',
hash.length, context.clientDHInnerData.length, dataWithHash.length);
}
context.encryptClientDHInnerData = security.cipher.aesEncrypt(
dataWithHash,
context.aes.key,
context.aes.iv
);
if (logger.isDebugEnabled()) {
logger.debug('encryptClientDHInnerData(%s) = %s',
context.encryptClientDHInnerData.length, context.encryptClientDHInnerData.toString('hex'));
}
return context;
} | [
"function",
"encryptClientDHInnerDataWithAES",
"(",
"context",
")",
"{",
"var",
"hash",
"=",
"utility",
".",
"createSHAHash",
"(",
"context",
".",
"clientDHInnerData",
")",
";",
"var",
"dataWithHash",
"=",
"Buffer",
".",
"concat",
"(",
"[",
"hash",
",",
"context",
".",
"clientDHInnerData",
"]",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'Data to be encrypted contains: hash(%s), clientDHInnerData(%s), total length %s'",
",",
"hash",
".",
"length",
",",
"context",
".",
"clientDHInnerData",
".",
"length",
",",
"dataWithHash",
".",
"length",
")",
";",
"}",
"context",
".",
"encryptClientDHInnerData",
"=",
"security",
".",
"cipher",
".",
"aesEncrypt",
"(",
"dataWithHash",
",",
"context",
".",
"aes",
".",
"key",
",",
"context",
".",
"aes",
".",
"iv",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'encryptClientDHInnerData(%s) = %s'",
",",
"context",
".",
"encryptClientDHInnerData",
".",
"length",
",",
"context",
".",
"encryptClientDHInnerData",
".",
"toString",
"(",
"'hex'",
")",
")",
";",
"}",
"return",
"context",
";",
"}"
] | Encrypt Client DH inner data | [
"Encrypt",
"Client",
"DH",
"inner",
"data"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/set-client-dh-params.js#L57-L74 |
22,536 | enricostara/telegram-mt-node | lib/auth/set-client-dh-params.js | setClientDHParams | function setClientDHParams(callback, context) {
mtproto.service.set_client_DH_params({
props: {
nonce: context.resPQ.nonce,
server_nonce: context.resPQ.server_nonce,
encrypted_data: context.encryptClientDHInnerData
},
channel: context.channel,
callback: function (ex, setClientDHParamsAnswer) {
if (ex) {
logger.error(ex);
if (callback) {
callback(ex);
}
} else {
if (setClientDHParamsAnswer.instanceOf('mtproto.type.Dh_gen_ok')) {
if (logger.isDebugEnabled()) {
logger.debug('\'Dh_gen_ok\' received from Telegram.');
}
context.setClientDHParamsAnswer = setClientDHParamsAnswer;
flow.runSeries([
calculateAuthKeyValue,
createAuthKeyID,
checkNonceMatch,
createAuthKey
], callback, context);
} else if (setClientDHParamsAnswer.instanceOf('mtproto.type.Dh_gen_retry')) {
logger.warn('\'Dh_gen_retry\' received from Telegram!');
callback(createError(JSON.stringify(setClientDHParamsAnswer), 'EDHPARAMRETRY'));
} else if (setClientDHParamsAnswer.instanceOf('mtproto.type.Dh_gen_fail')) {
logger.warn('\'Dh_gen_fail\' received from Telegram!');
callback(createError(JSON.stringify(setClientDHParamsAnswer), 'EDHPARAMFAIL'));
} else {
var msg = 'Unknown error received from Telegram!';
logger.error(msg);
callback(createError(msg, 'EUNKNOWN'));
}
}
}
});
} | javascript | function setClientDHParams(callback, context) {
mtproto.service.set_client_DH_params({
props: {
nonce: context.resPQ.nonce,
server_nonce: context.resPQ.server_nonce,
encrypted_data: context.encryptClientDHInnerData
},
channel: context.channel,
callback: function (ex, setClientDHParamsAnswer) {
if (ex) {
logger.error(ex);
if (callback) {
callback(ex);
}
} else {
if (setClientDHParamsAnswer.instanceOf('mtproto.type.Dh_gen_ok')) {
if (logger.isDebugEnabled()) {
logger.debug('\'Dh_gen_ok\' received from Telegram.');
}
context.setClientDHParamsAnswer = setClientDHParamsAnswer;
flow.runSeries([
calculateAuthKeyValue,
createAuthKeyID,
checkNonceMatch,
createAuthKey
], callback, context);
} else if (setClientDHParamsAnswer.instanceOf('mtproto.type.Dh_gen_retry')) {
logger.warn('\'Dh_gen_retry\' received from Telegram!');
callback(createError(JSON.stringify(setClientDHParamsAnswer), 'EDHPARAMRETRY'));
} else if (setClientDHParamsAnswer.instanceOf('mtproto.type.Dh_gen_fail')) {
logger.warn('\'Dh_gen_fail\' received from Telegram!');
callback(createError(JSON.stringify(setClientDHParamsAnswer), 'EDHPARAMFAIL'));
} else {
var msg = 'Unknown error received from Telegram!';
logger.error(msg);
callback(createError(msg, 'EUNKNOWN'));
}
}
}
});
} | [
"function",
"setClientDHParams",
"(",
"callback",
",",
"context",
")",
"{",
"mtproto",
".",
"service",
".",
"set_client_DH_params",
"(",
"{",
"props",
":",
"{",
"nonce",
":",
"context",
".",
"resPQ",
".",
"nonce",
",",
"server_nonce",
":",
"context",
".",
"resPQ",
".",
"server_nonce",
",",
"encrypted_data",
":",
"context",
".",
"encryptClientDHInnerData",
"}",
",",
"channel",
":",
"context",
".",
"channel",
",",
"callback",
":",
"function",
"(",
"ex",
",",
"setClientDHParamsAnswer",
")",
"{",
"if",
"(",
"ex",
")",
"{",
"logger",
".",
"error",
"(",
"ex",
")",
";",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"ex",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"setClientDHParamsAnswer",
".",
"instanceOf",
"(",
"'mtproto.type.Dh_gen_ok'",
")",
")",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'\\'Dh_gen_ok\\' received from Telegram.'",
")",
";",
"}",
"context",
".",
"setClientDHParamsAnswer",
"=",
"setClientDHParamsAnswer",
";",
"flow",
".",
"runSeries",
"(",
"[",
"calculateAuthKeyValue",
",",
"createAuthKeyID",
",",
"checkNonceMatch",
",",
"createAuthKey",
"]",
",",
"callback",
",",
"context",
")",
";",
"}",
"else",
"if",
"(",
"setClientDHParamsAnswer",
".",
"instanceOf",
"(",
"'mtproto.type.Dh_gen_retry'",
")",
")",
"{",
"logger",
".",
"warn",
"(",
"'\\'Dh_gen_retry\\' received from Telegram!'",
")",
";",
"callback",
"(",
"createError",
"(",
"JSON",
".",
"stringify",
"(",
"setClientDHParamsAnswer",
")",
",",
"'EDHPARAMRETRY'",
")",
")",
";",
"}",
"else",
"if",
"(",
"setClientDHParamsAnswer",
".",
"instanceOf",
"(",
"'mtproto.type.Dh_gen_fail'",
")",
")",
"{",
"logger",
".",
"warn",
"(",
"'\\'Dh_gen_fail\\' received from Telegram!'",
")",
";",
"callback",
"(",
"createError",
"(",
"JSON",
".",
"stringify",
"(",
"setClientDHParamsAnswer",
")",
",",
"'EDHPARAMFAIL'",
")",
")",
";",
"}",
"else",
"{",
"var",
"msg",
"=",
"'Unknown error received from Telegram!'",
";",
"logger",
".",
"error",
"(",
"msg",
")",
";",
"callback",
"(",
"createError",
"(",
"msg",
",",
"'EUNKNOWN'",
")",
")",
";",
"}",
"}",
"}",
"}",
")",
";",
"}"
] | Set client DH parameters | [
"Set",
"client",
"DH",
"parameters"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/set-client-dh-params.js#L77-L117 |
22,537 | enricostara/telegram-mt-node | lib/auth/set-client-dh-params.js | calculateAuthKeyValue | function calculateAuthKeyValue(context) {
var ga = context.serverDHInnerData.g_a;
var b = context.b;
var dhPrime = context.serverDHInnerData.dh_prime;
var authKeyValue = utility.modPow(ga, b, dhPrime);
if (logger.isDebugEnabled()) {
logger.debug('authKeyValue(%s) = %s', authKeyValue.length, authKeyValue.toString('hex'));
}
context.authKeyValue = authKeyValue;
return context;
} | javascript | function calculateAuthKeyValue(context) {
var ga = context.serverDHInnerData.g_a;
var b = context.b;
var dhPrime = context.serverDHInnerData.dh_prime;
var authKeyValue = utility.modPow(ga, b, dhPrime);
if (logger.isDebugEnabled()) {
logger.debug('authKeyValue(%s) = %s', authKeyValue.length, authKeyValue.toString('hex'));
}
context.authKeyValue = authKeyValue;
return context;
} | [
"function",
"calculateAuthKeyValue",
"(",
"context",
")",
"{",
"var",
"ga",
"=",
"context",
".",
"serverDHInnerData",
".",
"g_a",
";",
"var",
"b",
"=",
"context",
".",
"b",
";",
"var",
"dhPrime",
"=",
"context",
".",
"serverDHInnerData",
".",
"dh_prime",
";",
"var",
"authKeyValue",
"=",
"utility",
".",
"modPow",
"(",
"ga",
",",
"b",
",",
"dhPrime",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'authKeyValue(%s) = %s'",
",",
"authKeyValue",
".",
"length",
",",
"authKeyValue",
".",
"toString",
"(",
"'hex'",
")",
")",
";",
"}",
"context",
".",
"authKeyValue",
"=",
"authKeyValue",
";",
"return",
"context",
";",
"}"
] | Calculate the authentication key value | [
"Calculate",
"the",
"authentication",
"key",
"value"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/set-client-dh-params.js#L120-L130 |
22,538 | enricostara/telegram-mt-node | lib/auth/set-client-dh-params.js | createAuthKeyID | function createAuthKeyID(context) {
var authKeyHash = utility.createSHAHash(context.authKeyValue);
var authKeyAuxHash = authKeyHash.slice(0, 8);
var authKeyID = authKeyHash.slice(-8);
if (logger.isDebugEnabled()) {
logger.debug('authKeyID(%s) = %s', authKeyID.length, authKeyID.toString('hex'));
}
context.authKeyID = authKeyID;
context.authKeyAuxHash = authKeyAuxHash;
return context;
} | javascript | function createAuthKeyID(context) {
var authKeyHash = utility.createSHAHash(context.authKeyValue);
var authKeyAuxHash = authKeyHash.slice(0, 8);
var authKeyID = authKeyHash.slice(-8);
if (logger.isDebugEnabled()) {
logger.debug('authKeyID(%s) = %s', authKeyID.length, authKeyID.toString('hex'));
}
context.authKeyID = authKeyID;
context.authKeyAuxHash = authKeyAuxHash;
return context;
} | [
"function",
"createAuthKeyID",
"(",
"context",
")",
"{",
"var",
"authKeyHash",
"=",
"utility",
".",
"createSHAHash",
"(",
"context",
".",
"authKeyValue",
")",
";",
"var",
"authKeyAuxHash",
"=",
"authKeyHash",
".",
"slice",
"(",
"0",
",",
"8",
")",
";",
"var",
"authKeyID",
"=",
"authKeyHash",
".",
"slice",
"(",
"-",
"8",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'authKeyID(%s) = %s'",
",",
"authKeyID",
".",
"length",
",",
"authKeyID",
".",
"toString",
"(",
"'hex'",
")",
")",
";",
"}",
"context",
".",
"authKeyID",
"=",
"authKeyID",
";",
"context",
".",
"authKeyAuxHash",
"=",
"authKeyAuxHash",
";",
"return",
"context",
";",
"}"
] | Calculate AuthKey hash and ID | [
"Calculate",
"AuthKey",
"hash",
"and",
"ID"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/set-client-dh-params.js#L133-L143 |
22,539 | enricostara/telegram-mt-node | lib/auth/set-client-dh-params.js | checkNonceMatch | function checkNonceMatch(context) {
var newNonce1 = Buffer.concat([utility.string2Buffer(context.newNonce, 32), new Buffer([1]), context.authKeyAuxHash]);
var newNonceHash = utility.buffer2String(utility.createSHAHash(newNonce1).slice(-16));
var serverNewNonceHash = context.setClientDHParamsAnswer.new_nonce_hash1;
if (logger.isDebugEnabled()) {
logger.debug('newNonceHash = %s, new_nonce_hash1 = %s', newNonceHash.toString(), serverNewNonceHash.toString());
}
if (newNonceHash !== serverNewNonceHash) {
logger.warn('\'dh_gen_ok.new_nonce_hash1\' check fails!');
throw createError(newNonceHash + ' != ' + serverNewNonceHash, 'EREPLAYATTACK');
}
return context;
} | javascript | function checkNonceMatch(context) {
var newNonce1 = Buffer.concat([utility.string2Buffer(context.newNonce, 32), new Buffer([1]), context.authKeyAuxHash]);
var newNonceHash = utility.buffer2String(utility.createSHAHash(newNonce1).slice(-16));
var serverNewNonceHash = context.setClientDHParamsAnswer.new_nonce_hash1;
if (logger.isDebugEnabled()) {
logger.debug('newNonceHash = %s, new_nonce_hash1 = %s', newNonceHash.toString(), serverNewNonceHash.toString());
}
if (newNonceHash !== serverNewNonceHash) {
logger.warn('\'dh_gen_ok.new_nonce_hash1\' check fails!');
throw createError(newNonceHash + ' != ' + serverNewNonceHash, 'EREPLAYATTACK');
}
return context;
} | [
"function",
"checkNonceMatch",
"(",
"context",
")",
"{",
"var",
"newNonce1",
"=",
"Buffer",
".",
"concat",
"(",
"[",
"utility",
".",
"string2Buffer",
"(",
"context",
".",
"newNonce",
",",
"32",
")",
",",
"new",
"Buffer",
"(",
"[",
"1",
"]",
")",
",",
"context",
".",
"authKeyAuxHash",
"]",
")",
";",
"var",
"newNonceHash",
"=",
"utility",
".",
"buffer2String",
"(",
"utility",
".",
"createSHAHash",
"(",
"newNonce1",
")",
".",
"slice",
"(",
"-",
"16",
")",
")",
";",
"var",
"serverNewNonceHash",
"=",
"context",
".",
"setClientDHParamsAnswer",
".",
"new_nonce_hash1",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'newNonceHash = %s, new_nonce_hash1 = %s'",
",",
"newNonceHash",
".",
"toString",
"(",
")",
",",
"serverNewNonceHash",
".",
"toString",
"(",
")",
")",
";",
"}",
"if",
"(",
"newNonceHash",
"!==",
"serverNewNonceHash",
")",
"{",
"logger",
".",
"warn",
"(",
"'\\'dh_gen_ok.new_nonce_hash1\\' check fails!'",
")",
";",
"throw",
"createError",
"(",
"newNonceHash",
"+",
"' != '",
"+",
"serverNewNonceHash",
",",
"'EREPLAYATTACK'",
")",
";",
"}",
"return",
"context",
";",
"}"
] | Withstand replay-attacks | [
"Withstand",
"replay",
"-",
"attacks"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/set-client-dh-params.js#L146-L158 |
22,540 | enricostara/telegram-mt-node | lib/auth/set-client-dh-params.js | createAuthKey | function createAuthKey(context) {
// Extract the nonces
var newNonce = utility.string2Buffer(context.newNonce, 32);
var serverNonce = utility.string2Buffer(context.resPQ.server_nonce, 16);
// Create the serverSalt
var serverSalt = utility.xor(newNonce.slice(0, 8), serverNonce.slice(0, 8));
if (logger.isDebugEnabled()) {
logger.debug('serverSalt(%s) = %s', serverSalt.length, serverSalt.toString('hex'));
}
// Create the AuthKey
var authKey = new AuthKey(context.authKeyID, context.authKeyValue);
if (logger.isDebugEnabled()) {
logger.debug('authKey = %s', authKey.toString());
}
return {
key: authKey,
serverSalt: serverSalt,
toPrintable: tl.utility.toPrintable
};
} | javascript | function createAuthKey(context) {
// Extract the nonces
var newNonce = utility.string2Buffer(context.newNonce, 32);
var serverNonce = utility.string2Buffer(context.resPQ.server_nonce, 16);
// Create the serverSalt
var serverSalt = utility.xor(newNonce.slice(0, 8), serverNonce.slice(0, 8));
if (logger.isDebugEnabled()) {
logger.debug('serverSalt(%s) = %s', serverSalt.length, serverSalt.toString('hex'));
}
// Create the AuthKey
var authKey = new AuthKey(context.authKeyID, context.authKeyValue);
if (logger.isDebugEnabled()) {
logger.debug('authKey = %s', authKey.toString());
}
return {
key: authKey,
serverSalt: serverSalt,
toPrintable: tl.utility.toPrintable
};
} | [
"function",
"createAuthKey",
"(",
"context",
")",
"{",
"// Extract the nonces",
"var",
"newNonce",
"=",
"utility",
".",
"string2Buffer",
"(",
"context",
".",
"newNonce",
",",
"32",
")",
";",
"var",
"serverNonce",
"=",
"utility",
".",
"string2Buffer",
"(",
"context",
".",
"resPQ",
".",
"server_nonce",
",",
"16",
")",
";",
"// Create the serverSalt",
"var",
"serverSalt",
"=",
"utility",
".",
"xor",
"(",
"newNonce",
".",
"slice",
"(",
"0",
",",
"8",
")",
",",
"serverNonce",
".",
"slice",
"(",
"0",
",",
"8",
")",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'serverSalt(%s) = %s'",
",",
"serverSalt",
".",
"length",
",",
"serverSalt",
".",
"toString",
"(",
"'hex'",
")",
")",
";",
"}",
"// Create the AuthKey",
"var",
"authKey",
"=",
"new",
"AuthKey",
"(",
"context",
".",
"authKeyID",
",",
"context",
".",
"authKeyValue",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"'authKey = %s'",
",",
"authKey",
".",
"toString",
"(",
")",
")",
";",
"}",
"return",
"{",
"key",
":",
"authKey",
",",
"serverSalt",
":",
"serverSalt",
",",
"toPrintable",
":",
"tl",
".",
"utility",
".",
"toPrintable",
"}",
";",
"}"
] | Create the AuthKey | [
"Create",
"the",
"AuthKey"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/auth/set-client-dh-params.js#L161-L180 |
22,541 | enricostara/telegram-mt-node | lib/security/public-key.js | PublicKey | function PublicKey(params) {
this._fingerprint = params.fingerprint;
this._modulus = params.modulus;
this._exponent = params.exponent;
} | javascript | function PublicKey(params) {
this._fingerprint = params.fingerprint;
this._modulus = params.modulus;
this._exponent = params.exponent;
} | [
"function",
"PublicKey",
"(",
"params",
")",
"{",
"this",
".",
"_fingerprint",
"=",
"params",
".",
"fingerprint",
";",
"this",
".",
"_modulus",
"=",
"params",
".",
"modulus",
";",
"this",
".",
"_exponent",
"=",
"params",
".",
"exponent",
";",
"}"
] | PublicKey class This class represents a Public Key The constructor requires the fingerprint, the modulus and the exponent | [
"PublicKey",
"class",
"This",
"class",
"represents",
"a",
"Public",
"Key",
"The",
"constructor",
"requires",
"the",
"fingerprint",
"the",
"modulus",
"and",
"the",
"exponent"
] | f069dfcea2d023fc1ca837c5673d3abe26d44d28 | https://github.com/enricostara/telegram-mt-node/blob/f069dfcea2d023fc1ca837c5673d3abe26d44d28/lib/security/public-key.js#L11-L15 |
22,542 | jschyma/open_fints_js_client | lib/Classes.js | function (error, order, recvMsg) {
if (error) {
me_order.client.MsgEndDialog(function (error2, recvMsg2) {
if (error2) {
me_order.client.log.con.error({
error: error2
}, 'Connection close failed after error.')
} else {
me_order.client.log.con.debug('Connection closed okay, after error.')
}
})
}
cb(error, order, recvMsg)
} | javascript | function (error, order, recvMsg) {
if (error) {
me_order.client.MsgEndDialog(function (error2, recvMsg2) {
if (error2) {
me_order.client.log.con.error({
error: error2
}, 'Connection close failed after error.')
} else {
me_order.client.log.con.debug('Connection closed okay, after error.')
}
})
}
cb(error, order, recvMsg)
} | [
"function",
"(",
"error",
",",
"order",
",",
"recvMsg",
")",
"{",
"if",
"(",
"error",
")",
"{",
"me_order",
".",
"client",
".",
"MsgEndDialog",
"(",
"function",
"(",
"error2",
",",
"recvMsg2",
")",
"{",
"if",
"(",
"error2",
")",
"{",
"me_order",
".",
"client",
".",
"log",
".",
"con",
".",
"error",
"(",
"{",
"error",
":",
"error2",
"}",
",",
"'Connection close failed after error.'",
")",
"}",
"else",
"{",
"me_order",
".",
"client",
".",
"log",
".",
"con",
".",
"debug",
"(",
"'Connection closed okay, after error.'",
")",
"}",
"}",
")",
"}",
"cb",
"(",
"error",
",",
"order",
",",
"recvMsg",
")",
"}"
] | Exit CB is called when the function returns here it is checked if an error occures and then disconnects | [
"Exit",
"CB",
"is",
"called",
"when",
"the",
"function",
"returns",
"here",
"it",
"is",
"checked",
"if",
"an",
"error",
"occures",
"and",
"then",
"disconnects"
] | 1d3a36bebeb40511e99def61b2e3f25c4248d288 | https://github.com/jschyma/open_fints_js_client/blob/1d3a36bebeb40511e99def61b2e3f25c4248d288/lib/Classes.js#L896-L909 | |
22,543 | modofunjs/modofun | index.js | createServiceHandler | function createServiceHandler(handlers = {}, options = {}, shortcutType) {
const errorHandler = options.errorHandler || defaultErrorHandler;
const middleware = options.middleware || Array.isArray(options) && options || [];
const mode = options.mode || FUNCTION_MODE;
const checkArity = options.checkArity === undefined || Boolean(options.checkArity);
const type = shortcutType || options.type || (process.env.LAMBDA_TASK_ROOT && AWS_TYPE)
|| (process.env.AzureWebJobsStorage && AZURE_TYPE) || GCLOUD_TYPE;
if (type === AWS_TYPE) {
// return handler function with fn(event, context, callback) signature
return (event, context, callback) => {
// if AWS Lambda request, convert event and context to request and response
const req = new AWSRequest(event, context);
const res = new AWSResponse(req, callback);
// handle request
handleRequest(middleware, handlers, mode, checkArity, req, res, errorHandler);
};
} else if (type === AZURE_TYPE) {
// return handler function with fn(context) signature
return (context) => {
// if Azure request, convert context to request and response
const req = new AzureRequest(context.req);
const res = new AzureResponse(req, context);
// handle request
handleRequest(middleware, handlers, mode, checkArity, req, res, errorHandler);
};
} else if (type === GCLOUD_TYPE) {
// return handler function with fn(req, res) signature
return (req, res) => {
// handle request
handleRequest(middleware, handlers, mode, checkArity, req, res, errorHandler);
};
} else {
throw new Error('Invalid type: ' + type)
}
} | javascript | function createServiceHandler(handlers = {}, options = {}, shortcutType) {
const errorHandler = options.errorHandler || defaultErrorHandler;
const middleware = options.middleware || Array.isArray(options) && options || [];
const mode = options.mode || FUNCTION_MODE;
const checkArity = options.checkArity === undefined || Boolean(options.checkArity);
const type = shortcutType || options.type || (process.env.LAMBDA_TASK_ROOT && AWS_TYPE)
|| (process.env.AzureWebJobsStorage && AZURE_TYPE) || GCLOUD_TYPE;
if (type === AWS_TYPE) {
// return handler function with fn(event, context, callback) signature
return (event, context, callback) => {
// if AWS Lambda request, convert event and context to request and response
const req = new AWSRequest(event, context);
const res = new AWSResponse(req, callback);
// handle request
handleRequest(middleware, handlers, mode, checkArity, req, res, errorHandler);
};
} else if (type === AZURE_TYPE) {
// return handler function with fn(context) signature
return (context) => {
// if Azure request, convert context to request and response
const req = new AzureRequest(context.req);
const res = new AzureResponse(req, context);
// handle request
handleRequest(middleware, handlers, mode, checkArity, req, res, errorHandler);
};
} else if (type === GCLOUD_TYPE) {
// return handler function with fn(req, res) signature
return (req, res) => {
// handle request
handleRequest(middleware, handlers, mode, checkArity, req, res, errorHandler);
};
} else {
throw new Error('Invalid type: ' + type)
}
} | [
"function",
"createServiceHandler",
"(",
"handlers",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
",",
"shortcutType",
")",
"{",
"const",
"errorHandler",
"=",
"options",
".",
"errorHandler",
"||",
"defaultErrorHandler",
";",
"const",
"middleware",
"=",
"options",
".",
"middleware",
"||",
"Array",
".",
"isArray",
"(",
"options",
")",
"&&",
"options",
"||",
"[",
"]",
";",
"const",
"mode",
"=",
"options",
".",
"mode",
"||",
"FUNCTION_MODE",
";",
"const",
"checkArity",
"=",
"options",
".",
"checkArity",
"===",
"undefined",
"||",
"Boolean",
"(",
"options",
".",
"checkArity",
")",
";",
"const",
"type",
"=",
"shortcutType",
"||",
"options",
".",
"type",
"||",
"(",
"process",
".",
"env",
".",
"LAMBDA_TASK_ROOT",
"&&",
"AWS_TYPE",
")",
"||",
"(",
"process",
".",
"env",
".",
"AzureWebJobsStorage",
"&&",
"AZURE_TYPE",
")",
"||",
"GCLOUD_TYPE",
";",
"if",
"(",
"type",
"===",
"AWS_TYPE",
")",
"{",
"// return handler function with fn(event, context, callback) signature",
"return",
"(",
"event",
",",
"context",
",",
"callback",
")",
"=>",
"{",
"// if AWS Lambda request, convert event and context to request and response",
"const",
"req",
"=",
"new",
"AWSRequest",
"(",
"event",
",",
"context",
")",
";",
"const",
"res",
"=",
"new",
"AWSResponse",
"(",
"req",
",",
"callback",
")",
";",
"// handle request",
"handleRequest",
"(",
"middleware",
",",
"handlers",
",",
"mode",
",",
"checkArity",
",",
"req",
",",
"res",
",",
"errorHandler",
")",
";",
"}",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"AZURE_TYPE",
")",
"{",
"// return handler function with fn(context) signature",
"return",
"(",
"context",
")",
"=>",
"{",
"// if Azure request, convert context to request and response",
"const",
"req",
"=",
"new",
"AzureRequest",
"(",
"context",
".",
"req",
")",
";",
"const",
"res",
"=",
"new",
"AzureResponse",
"(",
"req",
",",
"context",
")",
";",
"// handle request",
"handleRequest",
"(",
"middleware",
",",
"handlers",
",",
"mode",
",",
"checkArity",
",",
"req",
",",
"res",
",",
"errorHandler",
")",
";",
"}",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"GCLOUD_TYPE",
")",
"{",
"// return handler function with fn(req, res) signature",
"return",
"(",
"req",
",",
"res",
")",
"=>",
"{",
"// handle request",
"handleRequest",
"(",
"middleware",
",",
"handlers",
",",
"mode",
",",
"checkArity",
",",
"req",
",",
"res",
",",
"errorHandler",
")",
";",
"}",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid type: '",
"+",
"type",
")",
"}",
"}"
] | The exported function that creates the request handler
using the supplied handlers and configuration.
Returns a handler with either function(req, res) signature
or function(event, context, callback) signature.
Example:
var app = modofun(
{
authenticate: authenticate,
user: [authorize, getUser]
},
{
middleware: [logger],
errorHandler: (err, req, res) => res.status(500).send(err.message)
}
)
@public | [
"The",
"exported",
"function",
"that",
"creates",
"the",
"request",
"handler",
"using",
"the",
"supplied",
"handlers",
"and",
"configuration",
"."
] | df5ea1b4d930a0bf1884e6926493b4eb246f5ae2 | https://github.com/modofunjs/modofun/blob/df5ea1b4d930a0bf1884e6926493b4eb246f5ae2/index.js#L171-L206 |
22,544 | modofunjs/modofun | index.js | handleRequest | function handleRequest(middleware, handlers, mode, checkArity, req, res, errorHandler) {
const done = err => err && setImmediate(errorHandler, err, req, res);
// run global middleware first, then start handling request
// this is important to allow loggers for example to kick-in regardless
runMiddlewareStack(middleware, req, res, (err) => {
if (err) {
done(err);
return;
}
// try to apply supplied handlers to the requested operation
handleOperation(handlers, mode, checkArity, req, res, done);
});
} | javascript | function handleRequest(middleware, handlers, mode, checkArity, req, res, errorHandler) {
const done = err => err && setImmediate(errorHandler, err, req, res);
// run global middleware first, then start handling request
// this is important to allow loggers for example to kick-in regardless
runMiddlewareStack(middleware, req, res, (err) => {
if (err) {
done(err);
return;
}
// try to apply supplied handlers to the requested operation
handleOperation(handlers, mode, checkArity, req, res, done);
});
} | [
"function",
"handleRequest",
"(",
"middleware",
",",
"handlers",
",",
"mode",
",",
"checkArity",
",",
"req",
",",
"res",
",",
"errorHandler",
")",
"{",
"const",
"done",
"=",
"err",
"=>",
"err",
"&&",
"setImmediate",
"(",
"errorHandler",
",",
"err",
",",
"req",
",",
"res",
")",
";",
"// run global middleware first, then start handling request",
"// this is important to allow loggers for example to kick-in regardless",
"runMiddlewareStack",
"(",
"middleware",
",",
"req",
",",
"res",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"done",
"(",
"err",
")",
";",
"return",
";",
"}",
"// try to apply supplied handlers to the requested operation",
"handleOperation",
"(",
"handlers",
",",
"mode",
",",
"checkArity",
",",
"req",
",",
"res",
",",
"done",
")",
";",
"}",
")",
";",
"}"
] | Execute middleware stack and handle request.
@private | [
"Execute",
"middleware",
"stack",
"and",
"handle",
"request",
"."
] | df5ea1b4d930a0bf1884e6926493b4eb246f5ae2 | https://github.com/modofunjs/modofun/blob/df5ea1b4d930a0bf1884e6926493b4eb246f5ae2/index.js#L212-L224 |
22,545 | modofunjs/modofun | index.js | handleOperation | function handleOperation(handlers, mode, checkArity, req, res, done) {
// parse path:
// - first part is the operation name
// - the following components of the path are used as arguments
const parsedParts = parsePath(req);
if (parsedParts[0].length === 0) {
done(new ModofunError(403, 'NoOperation', 'Operation must be specified!'));
return;
}
const [operation, ...args] = parsedParts;
if (operation && handlers.hasOwnProperty(operation)) {
// the stack of operation specific middleware
let operationMiddleware = [];
// operation handler
let operationHandler = handlers[operation];
if (Array.isArray(operationHandler)) {
// if an array is passed, add operation specific middleware
// last item in the array should be the operation handler
operationMiddleware = operationHandler.slice(0, -1);
operationHandler = operationHandler[operationHandler.length-1];
} else if (typeof operationHandler !== 'function') {
// otherwise return internal error
done(new ModofunError(500, 'InvalidConfig', 'Handler must be a function or array'));
return;
}
// call middleware stack with same req/res context
runMiddlewareStack(operationMiddleware, req, res, (err) => {
if (err) {
done(err);
return;
}
try {
// call handler function
if (mode === FUNCTION_MODE) {
invokeFunctionHandler(operationHandler, args, checkArity, req, res, done);
} else {
invokeHTTPHandler(operationHandler, args, req, res, done);
}
} catch(err) {
done(err);
}
});
} else {
// fail if requested operation cannot be resolved
done(new ModofunError(404, 'NotFound', `No handler for: ${operation}`));
return;
}
} | javascript | function handleOperation(handlers, mode, checkArity, req, res, done) {
// parse path:
// - first part is the operation name
// - the following components of the path are used as arguments
const parsedParts = parsePath(req);
if (parsedParts[0].length === 0) {
done(new ModofunError(403, 'NoOperation', 'Operation must be specified!'));
return;
}
const [operation, ...args] = parsedParts;
if (operation && handlers.hasOwnProperty(operation)) {
// the stack of operation specific middleware
let operationMiddleware = [];
// operation handler
let operationHandler = handlers[operation];
if (Array.isArray(operationHandler)) {
// if an array is passed, add operation specific middleware
// last item in the array should be the operation handler
operationMiddleware = operationHandler.slice(0, -1);
operationHandler = operationHandler[operationHandler.length-1];
} else if (typeof operationHandler !== 'function') {
// otherwise return internal error
done(new ModofunError(500, 'InvalidConfig', 'Handler must be a function or array'));
return;
}
// call middleware stack with same req/res context
runMiddlewareStack(operationMiddleware, req, res, (err) => {
if (err) {
done(err);
return;
}
try {
// call handler function
if (mode === FUNCTION_MODE) {
invokeFunctionHandler(operationHandler, args, checkArity, req, res, done);
} else {
invokeHTTPHandler(operationHandler, args, req, res, done);
}
} catch(err) {
done(err);
}
});
} else {
// fail if requested operation cannot be resolved
done(new ModofunError(404, 'NotFound', `No handler for: ${operation}`));
return;
}
} | [
"function",
"handleOperation",
"(",
"handlers",
",",
"mode",
",",
"checkArity",
",",
"req",
",",
"res",
",",
"done",
")",
"{",
"// parse path:",
"// - first part is the operation name",
"// - the following components of the path are used as arguments",
"const",
"parsedParts",
"=",
"parsePath",
"(",
"req",
")",
";",
"if",
"(",
"parsedParts",
"[",
"0",
"]",
".",
"length",
"===",
"0",
")",
"{",
"done",
"(",
"new",
"ModofunError",
"(",
"403",
",",
"'NoOperation'",
",",
"'Operation must be specified!'",
")",
")",
";",
"return",
";",
"}",
"const",
"[",
"operation",
",",
"...",
"args",
"]",
"=",
"parsedParts",
";",
"if",
"(",
"operation",
"&&",
"handlers",
".",
"hasOwnProperty",
"(",
"operation",
")",
")",
"{",
"// the stack of operation specific middleware",
"let",
"operationMiddleware",
"=",
"[",
"]",
";",
"// operation handler",
"let",
"operationHandler",
"=",
"handlers",
"[",
"operation",
"]",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"operationHandler",
")",
")",
"{",
"// if an array is passed, add operation specific middleware",
"// last item in the array should be the operation handler",
"operationMiddleware",
"=",
"operationHandler",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
";",
"operationHandler",
"=",
"operationHandler",
"[",
"operationHandler",
".",
"length",
"-",
"1",
"]",
";",
"}",
"else",
"if",
"(",
"typeof",
"operationHandler",
"!==",
"'function'",
")",
"{",
"// otherwise return internal error",
"done",
"(",
"new",
"ModofunError",
"(",
"500",
",",
"'InvalidConfig'",
",",
"'Handler must be a function or array'",
")",
")",
";",
"return",
";",
"}",
"// call middleware stack with same req/res context",
"runMiddlewareStack",
"(",
"operationMiddleware",
",",
"req",
",",
"res",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"done",
"(",
"err",
")",
";",
"return",
";",
"}",
"try",
"{",
"// call handler function",
"if",
"(",
"mode",
"===",
"FUNCTION_MODE",
")",
"{",
"invokeFunctionHandler",
"(",
"operationHandler",
",",
"args",
",",
"checkArity",
",",
"req",
",",
"res",
",",
"done",
")",
";",
"}",
"else",
"{",
"invokeHTTPHandler",
"(",
"operationHandler",
",",
"args",
",",
"req",
",",
"res",
",",
"done",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"done",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"// fail if requested operation cannot be resolved",
"done",
"(",
"new",
"ModofunError",
"(",
"404",
",",
"'NotFound'",
",",
"`",
"${",
"operation",
"}",
"`",
")",
")",
";",
"return",
";",
"}",
"}"
] | Try to apply supplied handlers to the requested operation.
@private | [
"Try",
"to",
"apply",
"supplied",
"handlers",
"to",
"the",
"requested",
"operation",
"."
] | df5ea1b4d930a0bf1884e6926493b4eb246f5ae2 | https://github.com/modofunjs/modofun/blob/df5ea1b4d930a0bf1884e6926493b4eb246f5ae2/index.js#L230-L282 |
22,546 | modofunjs/modofun | index.js | invokeHTTPHandler | function invokeHTTPHandler(handler, args, req, res, done) {
// inject parsed parameters into request
req.params = args;
// call handler with typical HTTP request/response parameters
let result = handler(req, res);
// handle results that are not a trusted Promise with Promise.resolve()
// which also supports other then-ables
if (result instanceof Promise === false) {
result = Promise.resolve(result);
}
return result.then(() => done()).catch(done);
} | javascript | function invokeHTTPHandler(handler, args, req, res, done) {
// inject parsed parameters into request
req.params = args;
// call handler with typical HTTP request/response parameters
let result = handler(req, res);
// handle results that are not a trusted Promise with Promise.resolve()
// which also supports other then-ables
if (result instanceof Promise === false) {
result = Promise.resolve(result);
}
return result.then(() => done()).catch(done);
} | [
"function",
"invokeHTTPHandler",
"(",
"handler",
",",
"args",
",",
"req",
",",
"res",
",",
"done",
")",
"{",
"// inject parsed parameters into request",
"req",
".",
"params",
"=",
"args",
";",
"// call handler with typical HTTP request/response parameters",
"let",
"result",
"=",
"handler",
"(",
"req",
",",
"res",
")",
";",
"// handle results that are not a trusted Promise with Promise.resolve()",
"// which also supports other then-ables",
"if",
"(",
"result",
"instanceof",
"Promise",
"===",
"false",
")",
"{",
"result",
"=",
"Promise",
".",
"resolve",
"(",
"result",
")",
";",
"}",
"return",
"result",
".",
"then",
"(",
"(",
")",
"=>",
"done",
"(",
")",
")",
".",
"catch",
"(",
"done",
")",
";",
"}"
] | Invoke the provided request handler function.
This handler function must send a response.
If the handler returns a Promise,
it will handle the error if the Promise is rejected.
@private | [
"Invoke",
"the",
"provided",
"request",
"handler",
"function",
".",
"This",
"handler",
"function",
"must",
"send",
"a",
"response",
".",
"If",
"the",
"handler",
"returns",
"a",
"Promise",
"it",
"will",
"handle",
"the",
"error",
"if",
"the",
"Promise",
"is",
"rejected",
"."
] | df5ea1b4d930a0bf1884e6926493b4eb246f5ae2 | https://github.com/modofunjs/modofun/blob/df5ea1b4d930a0bf1884e6926493b4eb246f5ae2/index.js#L330-L341 |
22,547 | modofunjs/modofun | index.js | invokeFunctionHandler | function invokeFunctionHandler(handler, args, checkArity, req, res, done) {
// check if number of arguments provided matches the handler function arity
if (checkArity && args.length < handler.length) { // < due to possible optionals
done(new ModofunError(400, 'InvalidInput',
`This operation requires ${handler.length} parameters. Received ${args.length}.`));
return;
}
// set this in function call to the remaining relevant request data
// could consider pushing the whole request object instead?
// for now prefer to keep it to minimum to allow maximum flexibility
const thisArg = {
method: req.method,
headers: req.headers,
body: req.body,
query: req.query,
user: req.user
};
// call handler function with
let result = handler.apply(thisArg, args);
// handle results that are not a trusted Promise with Promise.resolve()
// which also supports other then-ables
if (result instanceof Promise === false) {
result = Promise.resolve(result);
}
return result
.then(value => {
if (value === null) {
done(new ModofunError(404, 'NullResponse', `${req.path} resource was not found`));
return;
}
if (value === undefined || value === '') {
res.status(204).end();
} else {
res.status(200).json(value);
}
done();
})
.catch(done);
} | javascript | function invokeFunctionHandler(handler, args, checkArity, req, res, done) {
// check if number of arguments provided matches the handler function arity
if (checkArity && args.length < handler.length) { // < due to possible optionals
done(new ModofunError(400, 'InvalidInput',
`This operation requires ${handler.length} parameters. Received ${args.length}.`));
return;
}
// set this in function call to the remaining relevant request data
// could consider pushing the whole request object instead?
// for now prefer to keep it to minimum to allow maximum flexibility
const thisArg = {
method: req.method,
headers: req.headers,
body: req.body,
query: req.query,
user: req.user
};
// call handler function with
let result = handler.apply(thisArg, args);
// handle results that are not a trusted Promise with Promise.resolve()
// which also supports other then-ables
if (result instanceof Promise === false) {
result = Promise.resolve(result);
}
return result
.then(value => {
if (value === null) {
done(new ModofunError(404, 'NullResponse', `${req.path} resource was not found`));
return;
}
if (value === undefined || value === '') {
res.status(204).end();
} else {
res.status(200).json(value);
}
done();
})
.catch(done);
} | [
"function",
"invokeFunctionHandler",
"(",
"handler",
",",
"args",
",",
"checkArity",
",",
"req",
",",
"res",
",",
"done",
")",
"{",
"// check if number of arguments provided matches the handler function arity",
"if",
"(",
"checkArity",
"&&",
"args",
".",
"length",
"<",
"handler",
".",
"length",
")",
"{",
"// < due to possible optionals",
"done",
"(",
"new",
"ModofunError",
"(",
"400",
",",
"'InvalidInput'",
",",
"`",
"${",
"handler",
".",
"length",
"}",
"${",
"args",
".",
"length",
"}",
"`",
")",
")",
";",
"return",
";",
"}",
"// set this in function call to the remaining relevant request data",
"// could consider pushing the whole request object instead?",
"// for now prefer to keep it to minimum to allow maximum flexibility",
"const",
"thisArg",
"=",
"{",
"method",
":",
"req",
".",
"method",
",",
"headers",
":",
"req",
".",
"headers",
",",
"body",
":",
"req",
".",
"body",
",",
"query",
":",
"req",
".",
"query",
",",
"user",
":",
"req",
".",
"user",
"}",
";",
"// call handler function with",
"let",
"result",
"=",
"handler",
".",
"apply",
"(",
"thisArg",
",",
"args",
")",
";",
"// handle results that are not a trusted Promise with Promise.resolve()",
"// which also supports other then-ables",
"if",
"(",
"result",
"instanceof",
"Promise",
"===",
"false",
")",
"{",
"result",
"=",
"Promise",
".",
"resolve",
"(",
"result",
")",
";",
"}",
"return",
"result",
".",
"then",
"(",
"value",
"=>",
"{",
"if",
"(",
"value",
"===",
"null",
")",
"{",
"done",
"(",
"new",
"ModofunError",
"(",
"404",
",",
"'NullResponse'",
",",
"`",
"${",
"req",
".",
"path",
"}",
"`",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"value",
"===",
"undefined",
"||",
"value",
"===",
"''",
")",
"{",
"res",
".",
"status",
"(",
"204",
")",
".",
"end",
"(",
")",
";",
"}",
"else",
"{",
"res",
".",
"status",
"(",
"200",
")",
".",
"json",
"(",
"value",
")",
";",
"}",
"done",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"done",
")",
";",
"}"
] | Invoke the provided request handler function.
The handler should return a value or a Promised value
which will be added to the reponse automatically.
@private | [
"Invoke",
"the",
"provided",
"request",
"handler",
"function",
".",
"The",
"handler",
"should",
"return",
"a",
"value",
"or",
"a",
"Promised",
"value",
"which",
"will",
"be",
"added",
"to",
"the",
"reponse",
"automatically",
"."
] | df5ea1b4d930a0bf1884e6926493b4eb246f5ae2 | https://github.com/modofunjs/modofun/blob/df5ea1b4d930a0bf1884e6926493b4eb246f5ae2/index.js#L349-L387 |
22,548 | modofunjs/modofun | index.js | defaultErrorHandler | function defaultErrorHandler(err, req, res) {
if (err.name === 'UnauthorizedError') { // authentication is expected to be a common use-case
res.status(401).end();
} else {
if (!err.status || err.status >= 500) {
console.error(err.stack || err.toString());
}
res.status(err.status || 500).json({message: err.message})
}
} | javascript | function defaultErrorHandler(err, req, res) {
if (err.name === 'UnauthorizedError') { // authentication is expected to be a common use-case
res.status(401).end();
} else {
if (!err.status || err.status >= 500) {
console.error(err.stack || err.toString());
}
res.status(err.status || 500).json({message: err.message})
}
} | [
"function",
"defaultErrorHandler",
"(",
"err",
",",
"req",
",",
"res",
")",
"{",
"if",
"(",
"err",
".",
"name",
"===",
"'UnauthorizedError'",
")",
"{",
"// authentication is expected to be a common use-case",
"res",
".",
"status",
"(",
"401",
")",
".",
"end",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"err",
".",
"status",
"||",
"err",
".",
"status",
">=",
"500",
")",
"{",
"console",
".",
"error",
"(",
"err",
".",
"stack",
"||",
"err",
".",
"toString",
"(",
")",
")",
";",
"}",
"res",
".",
"status",
"(",
"err",
".",
"status",
"||",
"500",
")",
".",
"json",
"(",
"{",
"message",
":",
"err",
".",
"message",
"}",
")",
"}",
"}"
] | The default error handler, in case none is provided by the application.
@private | [
"The",
"default",
"error",
"handler",
"in",
"case",
"none",
"is",
"provided",
"by",
"the",
"application",
"."
] | df5ea1b4d930a0bf1884e6926493b4eb246f5ae2 | https://github.com/modofunjs/modofun/blob/df5ea1b4d930a0bf1884e6926493b4eb246f5ae2/index.js#L393-L402 |
22,549 | modofunjs/modofun | index.js | parsePath | function parsePath(req) {
// get path if preprocessed or otherwise separate path from query string
const path = req.path || (req.url && req.url.split('?')[0]) || '';
// ignore start and end slashes, and split the path
return path.replace(/^\/|\/$/g, '').split('/');
} | javascript | function parsePath(req) {
// get path if preprocessed or otherwise separate path from query string
const path = req.path || (req.url && req.url.split('?')[0]) || '';
// ignore start and end slashes, and split the path
return path.replace(/^\/|\/$/g, '').split('/');
} | [
"function",
"parsePath",
"(",
"req",
")",
"{",
"// get path if preprocessed or otherwise separate path from query string",
"const",
"path",
"=",
"req",
".",
"path",
"||",
"(",
"req",
".",
"url",
"&&",
"req",
".",
"url",
".",
"split",
"(",
"'?'",
")",
"[",
"0",
"]",
")",
"||",
"''",
";",
"// ignore start and end slashes, and split the path",
"return",
"path",
".",
"replace",
"(",
"/",
"^\\/|\\/$",
"/",
"g",
",",
"''",
")",
".",
"split",
"(",
"'/'",
")",
";",
"}"
] | Parse URL path to an array of its components.
@private | [
"Parse",
"URL",
"path",
"to",
"an",
"array",
"of",
"its",
"components",
"."
] | df5ea1b4d930a0bf1884e6926493b4eb246f5ae2 | https://github.com/modofunjs/modofun/blob/df5ea1b4d930a0bf1884e6926493b4eb246f5ae2/index.js#L408-L413 |
22,550 | modofunjs/modofun | index.js | arity | function arity(min, max = Number.MAX_SAFE_INTEGER) {
return (req, res, next) => {
const foundArity = parsePath(req).length-1;
if (foundArity < min ) {
next(new ModofunError(400, 'InvalidInput',
`This operation requires ${min} parameters. Received ${foundArity}.`));
} else if (foundArity > max ) {
next(new ModofunError(400, 'InvalidInput',
`This operation doesn't accept more than ${max} parameters. Received ${foundArity}.`));
} else {
next();
}
}
} | javascript | function arity(min, max = Number.MAX_SAFE_INTEGER) {
return (req, res, next) => {
const foundArity = parsePath(req).length-1;
if (foundArity < min ) {
next(new ModofunError(400, 'InvalidInput',
`This operation requires ${min} parameters. Received ${foundArity}.`));
} else if (foundArity > max ) {
next(new ModofunError(400, 'InvalidInput',
`This operation doesn't accept more than ${max} parameters. Received ${foundArity}.`));
} else {
next();
}
}
} | [
"function",
"arity",
"(",
"min",
",",
"max",
"=",
"Number",
".",
"MAX_SAFE_INTEGER",
")",
"{",
"return",
"(",
"req",
",",
"res",
",",
"next",
")",
"=>",
"{",
"const",
"foundArity",
"=",
"parsePath",
"(",
"req",
")",
".",
"length",
"-",
"1",
";",
"if",
"(",
"foundArity",
"<",
"min",
")",
"{",
"next",
"(",
"new",
"ModofunError",
"(",
"400",
",",
"'InvalidInput'",
",",
"`",
"${",
"min",
"}",
"${",
"foundArity",
"}",
"`",
")",
")",
";",
"}",
"else",
"if",
"(",
"foundArity",
">",
"max",
")",
"{",
"next",
"(",
"new",
"ModofunError",
"(",
"400",
",",
"'InvalidInput'",
",",
"`",
"${",
"max",
"}",
"${",
"foundArity",
"}",
"`",
")",
")",
";",
"}",
"else",
"{",
"next",
"(",
")",
";",
"}",
"}",
"}"
] | Utility middleware to enforce a minimum number of parameters.
Accepts an extra argument for an optional maximum number.
@public | [
"Utility",
"middleware",
"to",
"enforce",
"a",
"minimum",
"number",
"of",
"parameters",
".",
"Accepts",
"an",
"extra",
"argument",
"for",
"an",
"optional",
"maximum",
"number",
"."
] | df5ea1b4d930a0bf1884e6926493b4eb246f5ae2 | https://github.com/modofunjs/modofun/blob/df5ea1b4d930a0bf1884e6926493b4eb246f5ae2/index.js#L420-L433 |
22,551 | dominictarr/hashlru | bench.js | run | function run (N, op, init) {
var stats = null, value
for(var j = 0; j < 100; j++) {
if(init) value = init(j)
var start = Date.now()
for(var i = 0; i < N; i++) op(value, i)
stats = Stats(stats, N/((Date.now() - start)))
}
return stats
} | javascript | function run (N, op, init) {
var stats = null, value
for(var j = 0; j < 100; j++) {
if(init) value = init(j)
var start = Date.now()
for(var i = 0; i < N; i++) op(value, i)
stats = Stats(stats, N/((Date.now() - start)))
}
return stats
} | [
"function",
"run",
"(",
"N",
",",
"op",
",",
"init",
")",
"{",
"var",
"stats",
"=",
"null",
",",
"value",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"100",
";",
"j",
"++",
")",
"{",
"if",
"(",
"init",
")",
"value",
"=",
"init",
"(",
"j",
")",
"var",
"start",
"=",
"Date",
".",
"now",
"(",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"N",
";",
"i",
"++",
")",
"op",
"(",
"value",
",",
"i",
")",
"stats",
"=",
"Stats",
"(",
"stats",
",",
"N",
"/",
"(",
"(",
"Date",
".",
"now",
"(",
")",
"-",
"start",
")",
")",
")",
"}",
"return",
"stats",
"}"
] | simple benchmarks, and measure standard deviation | [
"simple",
"benchmarks",
"and",
"measure",
"standard",
"deviation"
] | 522050a6ce00af236e17c709d38621261b87d590 | https://github.com/dominictarr/hashlru/blob/522050a6ce00af236e17c709d38621261b87d590/bench.js#L6-L15 |
22,552 | keystonejs/keystone-nightwatch-e2e | lib/src/pageObjects/adminUIApp.js | function (config) {
if (config) {
if (config.element) {
this.expect.element(config.element).to.not.be.visible;
} else {
throw new Error('adminUIApp:must specify an element!');
}
} else {
throw new Error('adminUIApp:invalid config specification!');
}
return this;
} | javascript | function (config) {
if (config) {
if (config.element) {
this.expect.element(config.element).to.not.be.visible;
} else {
throw new Error('adminUIApp:must specify an element!');
}
} else {
throw new Error('adminUIApp:invalid config specification!');
}
return this;
} | [
"function",
"(",
"config",
")",
"{",
"if",
"(",
"config",
")",
"{",
"if",
"(",
"config",
".",
"element",
")",
"{",
"this",
".",
"expect",
".",
"element",
"(",
"config",
".",
"element",
")",
".",
"to",
".",
"not",
".",
"be",
".",
"visible",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'adminUIApp:must specify an element!'",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'adminUIApp:invalid config specification!'",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Asserts that the specified home screen element UI is not visible.
@param {Object} config The config spec.
@param {string} config.element The element whose UI should not be visible. | [
"Asserts",
"that",
"the",
"specified",
"home",
"screen",
"element",
"UI",
"is",
"not",
"visible",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/lib/src/pageObjects/adminUIApp.js#L48-L59 | |
22,553 | keystonejs/keystone-nightwatch-e2e | lib/src/pageObjects/adminUIApp.js | function (config) {
if (config) {
if (config.element) {
this.expect.element(config.element).to.be.present;
} else {
throw new Error('adminUIApp:must specify an element!');
}
} else {
throw new Error('adminUIApp:invalid config specification!');
}
return this;
} | javascript | function (config) {
if (config) {
if (config.element) {
this.expect.element(config.element).to.be.present;
} else {
throw new Error('adminUIApp:must specify an element!');
}
} else {
throw new Error('adminUIApp:invalid config specification!');
}
return this;
} | [
"function",
"(",
"config",
")",
"{",
"if",
"(",
"config",
")",
"{",
"if",
"(",
"config",
".",
"element",
")",
"{",
"this",
".",
"expect",
".",
"element",
"(",
"config",
".",
"element",
")",
".",
"to",
".",
"be",
".",
"present",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'adminUIApp:must specify an element!'",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'adminUIApp:invalid config specification!'",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Asserts that the specified home screen element DOM is present.
@param {Object} config The config spec.
@param {string} config.element The element whose DOM should be present. | [
"Asserts",
"that",
"the",
"specified",
"home",
"screen",
"element",
"DOM",
"is",
"present",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/lib/src/pageObjects/adminUIApp.js#L67-L78 | |
22,554 | keystonejs/keystone-nightwatch-e2e | lib/src/pageObjects/adminUIApp.js | function (config) {
if (config) {
if (config.element && config.text) {
this.expect.element(config.element).text.to.equal(config.text);
} else {
throw new Error('adminUIApp:must specify an element and text!');
}
} else {
throw new Error('adminUIApp:invalid config specification!');
}
return this;
} | javascript | function (config) {
if (config) {
if (config.element && config.text) {
this.expect.element(config.element).text.to.equal(config.text);
} else {
throw new Error('adminUIApp:must specify an element and text!');
}
} else {
throw new Error('adminUIApp:invalid config specification!');
}
return this;
} | [
"function",
"(",
"config",
")",
"{",
"if",
"(",
"config",
")",
"{",
"if",
"(",
"config",
".",
"element",
"&&",
"config",
".",
"text",
")",
"{",
"this",
".",
"expect",
".",
"element",
"(",
"config",
".",
"element",
")",
".",
"text",
".",
"to",
".",
"equal",
"(",
"config",
".",
"text",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'adminUIApp:must specify an element and text!'",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'adminUIApp:invalid config specification!'",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Asserts that the specified home screen element text equals the specified value.
@param {Object} config The config spec.
@param {string} config.element The element whose text should be compared to the input text.
@param {String} config.text The text to compare against. | [
"Asserts",
"that",
"the",
"specified",
"home",
"screen",
"element",
"text",
"equals",
"the",
"specified",
"value",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/lib/src/pageObjects/adminUIApp.js#L106-L117 | |
22,555 | keystonejs/keystone-nightwatch-e2e | lib/src/pageObjects/adminUIApp.js | function (config) {
if (config) {
if (config.element && config.text) {
this.expect.element(config.element).text.to.contain(config.text);
} else {
throw new Error('adminUIApp:must specify an element and text!');
}
} else {
throw new Error('adminUIApp:invalid config specification!');
}
return this;
} | javascript | function (config) {
if (config) {
if (config.element && config.text) {
this.expect.element(config.element).text.to.contain(config.text);
} else {
throw new Error('adminUIApp:must specify an element and text!');
}
} else {
throw new Error('adminUIApp:invalid config specification!');
}
return this;
} | [
"function",
"(",
"config",
")",
"{",
"if",
"(",
"config",
")",
"{",
"if",
"(",
"config",
".",
"element",
"&&",
"config",
".",
"text",
")",
"{",
"this",
".",
"expect",
".",
"element",
"(",
"config",
".",
"element",
")",
".",
"text",
".",
"to",
".",
"contain",
"(",
"config",
".",
"text",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'adminUIApp:must specify an element and text!'",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'adminUIApp:invalid config specification!'",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Asserts that the specified home screen element text contains the specified value.
@param {Object} config The config spec.
@param {string} config.element The element whose text should contain the input text.
@param {String} config.text The text to compare against. | [
"Asserts",
"that",
"the",
"specified",
"home",
"screen",
"element",
"text",
"contains",
"the",
"specified",
"value",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/lib/src/pageObjects/adminUIApp.js#L146-L157 | |
22,556 | keystonejs/keystone-nightwatch-e2e | lib/src/pageObjects/adminUIApp.js | function (config) {
if (config) {
if (config.element && config.attribute && config.value) {
this.expect.element(config.element).to.have.attribute(config.attribute).which.contains(config.value);
} else {
throw new Error('adminUIApp:must specify a config element, attribute, and value!');
}
} else {
throw new Error('adminUIApp:invalid config specification!');
}
return this;
} | javascript | function (config) {
if (config) {
if (config.element && config.attribute && config.value) {
this.expect.element(config.element).to.have.attribute(config.attribute).which.contains(config.value);
} else {
throw new Error('adminUIApp:must specify a config element, attribute, and value!');
}
} else {
throw new Error('adminUIApp:invalid config specification!');
}
return this;
} | [
"function",
"(",
"config",
")",
"{",
"if",
"(",
"config",
")",
"{",
"if",
"(",
"config",
".",
"element",
"&&",
"config",
".",
"attribute",
"&&",
"config",
".",
"value",
")",
"{",
"this",
".",
"expect",
".",
"element",
"(",
"config",
".",
"element",
")",
".",
"to",
".",
"have",
".",
"attribute",
"(",
"config",
".",
"attribute",
")",
".",
"which",
".",
"contains",
"(",
"config",
".",
"value",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'adminUIApp:must specify a config element, attribute, and value!'",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'adminUIApp:invalid config specification!'",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Asserts that the specified home screen element has the specified attribute.
@param {Object} config The config spec.
@param {string} config.element The element whose UI should be visible.
@param {string} config.attribute The attribute that should be present in the element.
@param {string} config.value The value that the attribute should have. | [
"Asserts",
"that",
"the",
"specified",
"home",
"screen",
"element",
"has",
"the",
"specified",
"attribute",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/lib/src/pageObjects/adminUIApp.js#L167-L178 | |
22,557 | keystonejs/keystone-nightwatch-e2e | lib/src/pageObjects/adminUIApp.js | function (config) {
var _config = objectAssign({}, { wait: true }, config);
this.navigate();
if (_config.wait) this.waitForSigninScreen();
return this;
} | javascript | function (config) {
var _config = objectAssign({}, { wait: true }, config);
this.navigate();
if (_config.wait) this.waitForSigninScreen();
return this;
} | [
"function",
"(",
"config",
")",
"{",
"var",
"_config",
"=",
"objectAssign",
"(",
"{",
"}",
",",
"{",
"wait",
":",
"true",
"}",
",",
"config",
")",
";",
"this",
".",
"navigate",
"(",
")",
";",
"if",
"(",
"_config",
".",
"wait",
")",
"this",
".",
"waitForSigninScreen",
"(",
")",
";",
"return",
"this",
";",
"}"
] | Navigates to the signin screen.
@param {Object} config The config spec.
@param {boolean} config.wait Whether to wait for the target UI. Optional, defaults to true. | [
"Navigates",
"to",
"the",
"signin",
"screen",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/lib/src/pageObjects/adminUIApp.js#L186-L191 | |
22,558 | keystonejs/keystone-nightwatch-e2e | lib/src/pageObjects/adminUIApp.js | function (config) {
var _config = objectAssign({}, { wait: true }, config);
this.navigate();
if (_config.wait) this.waitForHomeScreen();
return this;
} | javascript | function (config) {
var _config = objectAssign({}, { wait: true }, config);
this.navigate();
if (_config.wait) this.waitForHomeScreen();
return this;
} | [
"function",
"(",
"config",
")",
"{",
"var",
"_config",
"=",
"objectAssign",
"(",
"{",
"}",
",",
"{",
"wait",
":",
"true",
"}",
",",
"config",
")",
";",
"this",
".",
"navigate",
"(",
")",
";",
"if",
"(",
"_config",
".",
"wait",
")",
"this",
".",
"waitForHomeScreen",
"(",
")",
";",
"return",
"this",
";",
"}"
] | Navigates to the home screen.
@param {Object} config The config spec.
@param {boolean} config.wait Whether to wait for the target UI. Optional, defaults to true. | [
"Navigates",
"to",
"the",
"home",
"screen",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/lib/src/pageObjects/adminUIApp.js#L199-L204 | |
22,559 | keystonejs/keystone-nightwatch-e2e | lib/src/pageObjects/adminUIApp.js | function (config) {
var _config = objectAssign({}, { wait: true }, config);
if (_config.section && _config.list) {
this.clickPrimaryNavbar({ section: _config.section })
.waitForForSecondaryNavbar()
.clickSecondaryNavbar({ list: _config.list });
} else {
throw new Error('adminUIApp:must specify a navbar section and a list!');
}
if (_config.wait) this.waitForListScreen();
return this;
} | javascript | function (config) {
var _config = objectAssign({}, { wait: true }, config);
if (_config.section && _config.list) {
this.clickPrimaryNavbar({ section: _config.section })
.waitForForSecondaryNavbar()
.clickSecondaryNavbar({ list: _config.list });
} else {
throw new Error('adminUIApp:must specify a navbar section and a list!');
}
if (_config.wait) this.waitForListScreen();
return this;
} | [
"function",
"(",
"config",
")",
"{",
"var",
"_config",
"=",
"objectAssign",
"(",
"{",
"}",
",",
"{",
"wait",
":",
"true",
"}",
",",
"config",
")",
";",
"if",
"(",
"_config",
".",
"section",
"&&",
"_config",
".",
"list",
")",
"{",
"this",
".",
"clickPrimaryNavbar",
"(",
"{",
"section",
":",
"_config",
".",
"section",
"}",
")",
".",
"waitForForSecondaryNavbar",
"(",
")",
".",
"clickSecondaryNavbar",
"(",
"{",
"list",
":",
"_config",
".",
"list",
"}",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'adminUIApp:must specify a navbar section and a list!'",
")",
";",
"}",
"if",
"(",
"_config",
".",
"wait",
")",
"this",
".",
"waitForListScreen",
"(",
")",
";",
"return",
"this",
";",
"}"
] | Opens the list of items given the specified list config spec.
@param {Object} config The config spec.
@param {string} config.section The section in the primary navbar to click on.
@param {string} config.list The list in the secondary navbar to click on.
@param {boolean} config.wait Whether to wait for the target UI. Optional, defaults to true. | [
"Opens",
"the",
"list",
"of",
"items",
"given",
"the",
"specified",
"list",
"config",
"spec",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/lib/src/pageObjects/adminUIApp.js#L214-L225 | |
22,560 | keystonejs/keystone-nightwatch-e2e | lib/src/pageObjects/adminUIApp.js | function (config) {
var _config = objectAssign({}, { wait: true }, config);
if (_config.section) {
this.click(this.getPrimaryNavbarSectionElement({ section: _config.section }));
} else {
throw new Error('adminUIApp:must specify a navbar section!');
}
if (_config.wait) this.waitForForSecondaryNavbar();
return this;
} | javascript | function (config) {
var _config = objectAssign({}, { wait: true }, config);
if (_config.section) {
this.click(this.getPrimaryNavbarSectionElement({ section: _config.section }));
} else {
throw new Error('adminUIApp:must specify a navbar section!');
}
if (_config.wait) this.waitForForSecondaryNavbar();
return this;
} | [
"function",
"(",
"config",
")",
"{",
"var",
"_config",
"=",
"objectAssign",
"(",
"{",
"}",
",",
"{",
"wait",
":",
"true",
"}",
",",
"config",
")",
";",
"if",
"(",
"_config",
".",
"section",
")",
"{",
"this",
".",
"click",
"(",
"this",
".",
"getPrimaryNavbarSectionElement",
"(",
"{",
"section",
":",
"_config",
".",
"section",
"}",
")",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'adminUIApp:must specify a navbar section!'",
")",
";",
"}",
"if",
"(",
"_config",
".",
"wait",
")",
"this",
".",
"waitForForSecondaryNavbar",
"(",
")",
";",
"return",
"this",
";",
"}"
] | Clicks the specified section in the primary navbar.
@param {Object} config The config spec.
@param {string} config.section The section in the primary navbar to click on.
@param {boolean} config.wait Whether to wait for the target UI. Optional, defaults to true. | [
"Clicks",
"the",
"specified",
"section",
"in",
"the",
"primary",
"navbar",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/lib/src/pageObjects/adminUIApp.js#L234-L243 | |
22,561 | keystonejs/keystone-nightwatch-e2e | lib/src/pageObjects/adminUIApp.js | function (config) {
var _config = objectAssign({}, { wait: true }, config);
if (_config.list) {
this.click(this.getSecondaryNavbarListElement({ list: _config.list }));
} else {
throw new Error('adminUIApp:must specify a navbar list!');
}
if (_config.wait) this.waitForListScreen();
return this;
} | javascript | function (config) {
var _config = objectAssign({}, { wait: true }, config);
if (_config.list) {
this.click(this.getSecondaryNavbarListElement({ list: _config.list }));
} else {
throw new Error('adminUIApp:must specify a navbar list!');
}
if (_config.wait) this.waitForListScreen();
return this;
} | [
"function",
"(",
"config",
")",
"{",
"var",
"_config",
"=",
"objectAssign",
"(",
"{",
"}",
",",
"{",
"wait",
":",
"true",
"}",
",",
"config",
")",
";",
"if",
"(",
"_config",
".",
"list",
")",
"{",
"this",
".",
"click",
"(",
"this",
".",
"getSecondaryNavbarListElement",
"(",
"{",
"list",
":",
"_config",
".",
"list",
"}",
")",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'adminUIApp:must specify a navbar list!'",
")",
";",
"}",
"if",
"(",
"_config",
".",
"wait",
")",
"this",
".",
"waitForListScreen",
"(",
")",
";",
"return",
"this",
";",
"}"
] | Clicks the specified list in the secondary navbar.
@param {Object} config The config spec.
@param {string} list The list in the secondary navbar to click on.
@param {boolean} config.wait Whether to wait for the target UI. Optional, defaults to true. | [
"Clicks",
"the",
"specified",
"list",
"in",
"the",
"secondary",
"navbar",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/lib/src/pageObjects/adminUIApp.js#L252-L261 | |
22,562 | keystonejs/keystone-nightwatch-e2e | lib/src/pageObjects/adminUIApp.js | function (config) {
var _config = objectAssign({}, { timeout: this.api.globals.waitForConditionTimeout }, config);
this.waitForElementVisible('@signinScreen', _config.timeout);
this.api.pause(self.screenTransitionTimeout);
return this;
} | javascript | function (config) {
var _config = objectAssign({}, { timeout: this.api.globals.waitForConditionTimeout }, config);
this.waitForElementVisible('@signinScreen', _config.timeout);
this.api.pause(self.screenTransitionTimeout);
return this;
} | [
"function",
"(",
"config",
")",
"{",
"var",
"_config",
"=",
"objectAssign",
"(",
"{",
"}",
",",
"{",
"timeout",
":",
"this",
".",
"api",
".",
"globals",
".",
"waitForConditionTimeout",
"}",
",",
"config",
")",
";",
"this",
".",
"waitForElementVisible",
"(",
"'@signinScreen'",
",",
"_config",
".",
"timeout",
")",
";",
"this",
".",
"api",
".",
"pause",
"(",
"self",
".",
"screenTransitionTimeout",
")",
";",
"return",
"this",
";",
"}"
] | Waits for the signin screen UI to be visible.
@param {Object} config The config spec.
@param {number} config.timeout Optional timeout to wait for. | [
"Waits",
"for",
"the",
"signin",
"screen",
"UI",
"to",
"be",
"visible",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/lib/src/pageObjects/adminUIApp.js#L284-L289 | |
22,563 | keystonejs/keystone-nightwatch-e2e | lib/src/pageObjects/adminUIApp.js | function (config) {
return this.expect.element(this.getPrimaryNavbarSectionElement({ section: config.section })).to.be.visible;
} | javascript | function (config) {
return this.expect.element(this.getPrimaryNavbarSectionElement({ section: config.section })).to.be.visible;
} | [
"function",
"(",
"config",
")",
"{",
"return",
"this",
".",
"expect",
".",
"element",
"(",
"this",
".",
"getPrimaryNavbarSectionElement",
"(",
"{",
"section",
":",
"config",
".",
"section",
"}",
")",
")",
".",
"to",
".",
"be",
".",
"visible",
";",
"}"
] | Asserts that the specified primary navbar section is visible.
@param {Object} config The config spec.
@param {string} config.section The section that should be visible in the primary navbar. | [
"Asserts",
"that",
"the",
"specified",
"primary",
"navbar",
"section",
"is",
"visible",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/lib/src/pageObjects/adminUIApp.js#L389-L391 | |
22,564 | keystonejs/keystone-nightwatch-e2e | lib/src/pageObjects/adminUIApp.js | function (config) {
return this.expect.element(this.getSecondaryNavbarListElement({ list: config.list })).to.be.visible;
} | javascript | function (config) {
return this.expect.element(this.getSecondaryNavbarListElement({ list: config.list })).to.be.visible;
} | [
"function",
"(",
"config",
")",
"{",
"return",
"this",
".",
"expect",
".",
"element",
"(",
"this",
".",
"getSecondaryNavbarListElement",
"(",
"{",
"list",
":",
"config",
".",
"list",
"}",
")",
")",
".",
"to",
".",
"be",
".",
"visible",
";",
"}"
] | Asserts that the specified secondary navbar list is visible. Make sure that the parent
primary navbar section is clicked on first.
@param {Object} config The config spec.
@param {string} config.list The list that should be visible in the secondary navbar. | [
"Asserts",
"that",
"the",
"specified",
"secondary",
"navbar",
"list",
"is",
"visible",
".",
"Make",
"sure",
"that",
"the",
"parent",
"primary",
"navbar",
"section",
"is",
"clicked",
"on",
"first",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/lib/src/pageObjects/adminUIApp.js#L400-L402 | |
22,565 | keystonejs/keystone-nightwatch-e2e | index.js | function (cb) {
if (argv.env === 'default' && argv['selenium-in-background']) {
process.env.KNE_SELENIUM_START_PROCESS = false;
runSeleniumInBackground(cb);
} else if (argv.env === 'default') {
process.env.KNE_SELENIUM_START_PROCESS = true;
cb();
} else {
process.env.KNE_SELENIUM_START_PROCESS = false;
cb();
}
} | javascript | function (cb) {
if (argv.env === 'default' && argv['selenium-in-background']) {
process.env.KNE_SELENIUM_START_PROCESS = false;
runSeleniumInBackground(cb);
} else if (argv.env === 'default') {
process.env.KNE_SELENIUM_START_PROCESS = true;
cb();
} else {
process.env.KNE_SELENIUM_START_PROCESS = false;
cb();
}
} | [
"function",
"(",
"cb",
")",
"{",
"if",
"(",
"argv",
".",
"env",
"===",
"'default'",
"&&",
"argv",
"[",
"'selenium-in-background'",
"]",
")",
"{",
"process",
".",
"env",
".",
"KNE_SELENIUM_START_PROCESS",
"=",
"false",
";",
"runSeleniumInBackground",
"(",
"cb",
")",
";",
"}",
"else",
"if",
"(",
"argv",
".",
"env",
"===",
"'default'",
")",
"{",
"process",
".",
"env",
".",
"KNE_SELENIUM_START_PROCESS",
"=",
"true",
";",
"cb",
"(",
")",
";",
"}",
"else",
"{",
"process",
".",
"env",
".",
"KNE_SELENIUM_START_PROCESS",
"=",
"false",
";",
"cb",
"(",
")",
";",
"}",
"}"
] | If the user wants us to start selenium manually then do so | [
"If",
"the",
"user",
"wants",
"us",
"to",
"start",
"selenium",
"manually",
"then",
"do",
"so"
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/index.js#L102-L113 | |
22,566 | keystonejs/keystone-nightwatch-e2e | index.js | function (cb) {
if (argv.env === 'saucelabs-travis' || (argv.env === 'saucelabs-local' && argv['sauce-username'] && argv['sauce-access-key'])) {
startSauceConnect(cb);
} else {
if (argv.env === 'saucelabs-local') {
console.error([moment().format('HH:mm:ss:SSS')] + ' kne: You must specify --sauce-username and --sauce-access-key when using: --' + argv.env);
cb(new Error('kne: You must specify --sauce-username and --sauce-access-key when using: --' + argv.env));
} else {
cb();
}
}
} | javascript | function (cb) {
if (argv.env === 'saucelabs-travis' || (argv.env === 'saucelabs-local' && argv['sauce-username'] && argv['sauce-access-key'])) {
startSauceConnect(cb);
} else {
if (argv.env === 'saucelabs-local') {
console.error([moment().format('HH:mm:ss:SSS')] + ' kne: You must specify --sauce-username and --sauce-access-key when using: --' + argv.env);
cb(new Error('kne: You must specify --sauce-username and --sauce-access-key when using: --' + argv.env));
} else {
cb();
}
}
} | [
"function",
"(",
"cb",
")",
"{",
"if",
"(",
"argv",
".",
"env",
"===",
"'saucelabs-travis'",
"||",
"(",
"argv",
".",
"env",
"===",
"'saucelabs-local'",
"&&",
"argv",
"[",
"'sauce-username'",
"]",
"&&",
"argv",
"[",
"'sauce-access-key'",
"]",
")",
")",
"{",
"startSauceConnect",
"(",
"cb",
")",
";",
"}",
"else",
"{",
"if",
"(",
"argv",
".",
"env",
"===",
"'saucelabs-local'",
")",
"{",
"console",
".",
"error",
"(",
"[",
"moment",
"(",
")",
".",
"format",
"(",
"'HH:mm:ss:SSS'",
")",
"]",
"+",
"' kne: You must specify --sauce-username and --sauce-access-key when using: --'",
"+",
"argv",
".",
"env",
")",
";",
"cb",
"(",
"new",
"Error",
"(",
"'kne: You must specify --sauce-username and --sauce-access-key when using: --'",
"+",
"argv",
".",
"env",
")",
")",
";",
"}",
"else",
"{",
"cb",
"(",
")",
";",
"}",
"}",
"}"
] | The only environment that currently requires starting sauce connect is travis. | [
"The",
"only",
"environment",
"that",
"currently",
"requires",
"starting",
"sauce",
"connect",
"is",
"travis",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/index.js#L118-L129 | |
22,567 | keystonejs/keystone-nightwatch-e2e | index.js | function (cb) {
Nightwatch.runner(argv, function (status) {
var err = null;
if (status) {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: tests passed');
} else {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: tests failed');
err = new Error('kne: nightwatch runner returned an error status code');
}
cb(err);
});
} | javascript | function (cb) {
Nightwatch.runner(argv, function (status) {
var err = null;
if (status) {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: tests passed');
} else {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: tests failed');
err = new Error('kne: nightwatch runner returned an error status code');
}
cb(err);
});
} | [
"function",
"(",
"cb",
")",
"{",
"Nightwatch",
".",
"runner",
"(",
"argv",
",",
"function",
"(",
"status",
")",
"{",
"var",
"err",
"=",
"null",
";",
"if",
"(",
"status",
")",
"{",
"console",
".",
"log",
"(",
"[",
"moment",
"(",
")",
".",
"format",
"(",
"'HH:mm:ss:SSS'",
")",
"]",
"+",
"' kne: tests passed'",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"[",
"moment",
"(",
")",
".",
"format",
"(",
"'HH:mm:ss:SSS'",
")",
"]",
"+",
"' kne: tests failed'",
")",
";",
"err",
"=",
"new",
"Error",
"(",
"'kne: nightwatch runner returned an error status code'",
")",
";",
"}",
"cb",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] | Run nightwatch to start executing the tests | [
"Run",
"nightwatch",
"to",
"start",
"executing",
"the",
"tests"
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/index.js#L134-L145 | |
22,568 | keystonejs/keystone-nightwatch-e2e | index.js | startSauceConnect | function startSauceConnect (done) {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: Starting Sauce Connect');
var default_options = {
username: process.env.SAUCE_USERNAME,
accessKey: process.env.SAUCE_ACCESS_KEY,
connectRetries: 5,
connectRetryTimeout: 60000,
logger: sauceConnectLog,
readyFileId: process.env.TRAVIS_JOB_NUMBER,
};
var custom_options = process.env.TRAVIS_JOB_NUMBER
? {
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
} : {
};
var options = _.extend({}, default_options, custom_options);
sauceConnectLauncher(options, function (err, sauceConnectProcess) {
if (err) {
console.error([moment().format('HH:mm:ss:SSS')] + ' kne: There was an error starting Sauce Connect');
done(err);
} else {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: Sauce Connect Ready');
sauceConnection = sauceConnectProcess;
sauceConnectionRunning = true;
setTimeout(done, 5000);
}
});
} | javascript | function startSauceConnect (done) {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: Starting Sauce Connect');
var default_options = {
username: process.env.SAUCE_USERNAME,
accessKey: process.env.SAUCE_ACCESS_KEY,
connectRetries: 5,
connectRetryTimeout: 60000,
logger: sauceConnectLog,
readyFileId: process.env.TRAVIS_JOB_NUMBER,
};
var custom_options = process.env.TRAVIS_JOB_NUMBER
? {
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
} : {
};
var options = _.extend({}, default_options, custom_options);
sauceConnectLauncher(options, function (err, sauceConnectProcess) {
if (err) {
console.error([moment().format('HH:mm:ss:SSS')] + ' kne: There was an error starting Sauce Connect');
done(err);
} else {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: Sauce Connect Ready');
sauceConnection = sauceConnectProcess;
sauceConnectionRunning = true;
setTimeout(done, 5000);
}
});
} | [
"function",
"startSauceConnect",
"(",
"done",
")",
"{",
"console",
".",
"log",
"(",
"[",
"moment",
"(",
")",
".",
"format",
"(",
"'HH:mm:ss:SSS'",
")",
"]",
"+",
"' kne: Starting Sauce Connect'",
")",
";",
"var",
"default_options",
"=",
"{",
"username",
":",
"process",
".",
"env",
".",
"SAUCE_USERNAME",
",",
"accessKey",
":",
"process",
".",
"env",
".",
"SAUCE_ACCESS_KEY",
",",
"connectRetries",
":",
"5",
",",
"connectRetryTimeout",
":",
"60000",
",",
"logger",
":",
"sauceConnectLog",
",",
"readyFileId",
":",
"process",
".",
"env",
".",
"TRAVIS_JOB_NUMBER",
",",
"}",
";",
"var",
"custom_options",
"=",
"process",
".",
"env",
".",
"TRAVIS_JOB_NUMBER",
"?",
"{",
"tunnelIdentifier",
":",
"process",
".",
"env",
".",
"TRAVIS_JOB_NUMBER",
",",
"}",
":",
"{",
"}",
";",
"var",
"options",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"default_options",
",",
"custom_options",
")",
";",
"sauceConnectLauncher",
"(",
"options",
",",
"function",
"(",
"err",
",",
"sauceConnectProcess",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"[",
"moment",
"(",
")",
".",
"format",
"(",
"'HH:mm:ss:SSS'",
")",
"]",
"+",
"' kne: There was an error starting Sauce Connect'",
")",
";",
"done",
"(",
"err",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"[",
"moment",
"(",
")",
".",
"format",
"(",
"'HH:mm:ss:SSS'",
")",
"]",
"+",
"' kne: Sauce Connect Ready'",
")",
";",
"sauceConnection",
"=",
"sauceConnectProcess",
";",
"sauceConnectionRunning",
"=",
"true",
";",
"setTimeout",
"(",
"done",
",",
"5000",
")",
";",
"}",
"}",
")",
";",
"}"
] | Function that starts the sauce connect servers if SAUCE_ACCESS_KEY is set. | [
"Function",
"that",
"starts",
"the",
"sauce",
"connect",
"servers",
"if",
"SAUCE_ACCESS_KEY",
"is",
"set",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/index.js#L168-L197 |
22,569 | keystonejs/keystone-nightwatch-e2e | index.js | checkKeystoneReady | function checkKeystoneReady (keystone, done) {
async.retry({
times: 10,
interval: 3000,
}, function (done, result) {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: checking if KeystoneJS ready for request');
request
.get('http://' + keystone.get('host') + ':' + keystone.get('port') + '/keystone')
.end(done);
}, function (err, result) {
if (!err) {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: KeystoneJS Ready!');
done();
} else {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: KeystoneJS does not appear ready!');
done(err);
}
});
} | javascript | function checkKeystoneReady (keystone, done) {
async.retry({
times: 10,
interval: 3000,
}, function (done, result) {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: checking if KeystoneJS ready for request');
request
.get('http://' + keystone.get('host') + ':' + keystone.get('port') + '/keystone')
.end(done);
}, function (err, result) {
if (!err) {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: KeystoneJS Ready!');
done();
} else {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: KeystoneJS does not appear ready!');
done(err);
}
});
} | [
"function",
"checkKeystoneReady",
"(",
"keystone",
",",
"done",
")",
"{",
"async",
".",
"retry",
"(",
"{",
"times",
":",
"10",
",",
"interval",
":",
"3000",
",",
"}",
",",
"function",
"(",
"done",
",",
"result",
")",
"{",
"console",
".",
"log",
"(",
"[",
"moment",
"(",
")",
".",
"format",
"(",
"'HH:mm:ss:SSS'",
")",
"]",
"+",
"' kne: checking if KeystoneJS ready for request'",
")",
";",
"request",
".",
"get",
"(",
"'http://'",
"+",
"keystone",
".",
"get",
"(",
"'host'",
")",
"+",
"':'",
"+",
"keystone",
".",
"get",
"(",
"'port'",
")",
"+",
"'/keystone'",
")",
".",
"end",
"(",
"done",
")",
";",
"}",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"console",
".",
"log",
"(",
"[",
"moment",
"(",
")",
".",
"format",
"(",
"'HH:mm:ss:SSS'",
")",
"]",
"+",
"' kne: KeystoneJS Ready!'",
")",
";",
"done",
"(",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"[",
"moment",
"(",
")",
".",
"format",
"(",
"'HH:mm:ss:SSS'",
")",
"]",
"+",
"' kne: KeystoneJS does not appear ready!'",
")",
";",
"done",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}"
] | Function that checks if keystone is ready before starting testing | [
"Function",
"that",
"checks",
"if",
"keystone",
"is",
"ready",
"before",
"starting",
"testing"
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/index.js#L213-L231 |
22,570 | keystonejs/keystone-nightwatch-e2e | lib/src/pageObjects/adminUISignin.js | function (config) {
var _config = objectAssign({}, { user: 'user@test.e2e', password: 'test', wait: true }, config);
this
.setValue('@email', _config.user)
.setValue('@password', _config.password)
.click('@submitButton');
if (_config.wait) this.api.page.adminUIApp().waitForHomeScreen();
return this;
} | javascript | function (config) {
var _config = objectAssign({}, { user: 'user@test.e2e', password: 'test', wait: true }, config);
this
.setValue('@email', _config.user)
.setValue('@password', _config.password)
.click('@submitButton');
if (_config.wait) this.api.page.adminUIApp().waitForHomeScreen();
return this;
} | [
"function",
"(",
"config",
")",
"{",
"var",
"_config",
"=",
"objectAssign",
"(",
"{",
"}",
",",
"{",
"user",
":",
"'user@test.e2e'",
",",
"password",
":",
"'test'",
",",
"wait",
":",
"true",
"}",
",",
"config",
")",
";",
"this",
".",
"setValue",
"(",
"'@email'",
",",
"_config",
".",
"user",
")",
".",
"setValue",
"(",
"'@password'",
",",
"_config",
".",
"password",
")",
".",
"click",
"(",
"'@submitButton'",
")",
";",
"if",
"(",
"_config",
".",
"wait",
")",
"this",
".",
"api",
".",
"page",
".",
"adminUIApp",
"(",
")",
".",
"waitForHomeScreen",
"(",
")",
";",
"return",
"this",
";",
"}"
] | Signs in to the Admin UI.
@param {Object} config The login info.
@param {string} config.user The login username/email.
@param {string} config.password The login password.
@param {boolean} config.wait Whether to wait for the home screen by default. Optional, defaults to true. | [
"Signs",
"in",
"to",
"the",
"Admin",
"UI",
"."
] | 4329b4b296ade1339363837f9f11ba4ea42e1858 | https://github.com/keystonejs/keystone-nightwatch-e2e/blob/4329b4b296ade1339363837f9f11ba4ea42e1858/lib/src/pageObjects/adminUISignin.js#L29-L37 | |
22,571 | googlearchive/backbonefire | examples/todos/js/backbonefire.js | function(model, options) {
Backbone.Model.apply(this, arguments);
var defaults = _.result(this, 'defaults');
// Apply defaults only after first sync.
this.once('sync', function() {
this.set(_.defaults(this.toJSON(), defaults));
});
this.autoSync = Backbone.Firebase._determineAutoSync(this, options);
switch (typeof this.url) {
case 'string':
this.firebase = Backbone.Firebase._determineRef(this.url);
break;
case 'function':
this.firebase = Backbone.Firebase._determineRef(this.url());
break;
case 'object':
this.firebase = Backbone.Firebase._determineRef(this.url);
break;
default:
Backbone.Firebase._throwError('url parameter required');
}
if(!this.autoSync) {
OnceModel.apply(this, arguments);
_.extend(this, OnceModel.protoype);
} else {
_.extend(this, SyncModel.protoype);
SyncModel.apply(this, arguments);
}
} | javascript | function(model, options) {
Backbone.Model.apply(this, arguments);
var defaults = _.result(this, 'defaults');
// Apply defaults only after first sync.
this.once('sync', function() {
this.set(_.defaults(this.toJSON(), defaults));
});
this.autoSync = Backbone.Firebase._determineAutoSync(this, options);
switch (typeof this.url) {
case 'string':
this.firebase = Backbone.Firebase._determineRef(this.url);
break;
case 'function':
this.firebase = Backbone.Firebase._determineRef(this.url());
break;
case 'object':
this.firebase = Backbone.Firebase._determineRef(this.url);
break;
default:
Backbone.Firebase._throwError('url parameter required');
}
if(!this.autoSync) {
OnceModel.apply(this, arguments);
_.extend(this, OnceModel.protoype);
} else {
_.extend(this, SyncModel.protoype);
SyncModel.apply(this, arguments);
}
} | [
"function",
"(",
"model",
",",
"options",
")",
"{",
"Backbone",
".",
"Model",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"var",
"defaults",
"=",
"_",
".",
"result",
"(",
"this",
",",
"'defaults'",
")",
";",
"// Apply defaults only after first sync.",
"this",
".",
"once",
"(",
"'sync'",
",",
"function",
"(",
")",
"{",
"this",
".",
"set",
"(",
"_",
".",
"defaults",
"(",
"this",
".",
"toJSON",
"(",
")",
",",
"defaults",
")",
")",
";",
"}",
")",
";",
"this",
".",
"autoSync",
"=",
"Backbone",
".",
"Firebase",
".",
"_determineAutoSync",
"(",
"this",
",",
"options",
")",
";",
"switch",
"(",
"typeof",
"this",
".",
"url",
")",
"{",
"case",
"'string'",
":",
"this",
".",
"firebase",
"=",
"Backbone",
".",
"Firebase",
".",
"_determineRef",
"(",
"this",
".",
"url",
")",
";",
"break",
";",
"case",
"'function'",
":",
"this",
".",
"firebase",
"=",
"Backbone",
".",
"Firebase",
".",
"_determineRef",
"(",
"this",
".",
"url",
"(",
")",
")",
";",
"break",
";",
"case",
"'object'",
":",
"this",
".",
"firebase",
"=",
"Backbone",
".",
"Firebase",
".",
"_determineRef",
"(",
"this",
".",
"url",
")",
";",
"break",
";",
"default",
":",
"Backbone",
".",
"Firebase",
".",
"_throwError",
"(",
"'url parameter required'",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"autoSync",
")",
"{",
"OnceModel",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"_",
".",
"extend",
"(",
"this",
",",
"OnceModel",
".",
"protoype",
")",
";",
"}",
"else",
"{",
"_",
".",
"extend",
"(",
"this",
",",
"SyncModel",
".",
"protoype",
")",
";",
"SyncModel",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"}"
] | Determine whether the realtime or once methods apply | [
"Determine",
"whether",
"the",
"realtime",
"or",
"once",
"methods",
"apply"
] | d6278d4aeb0743bdd7e9de96cc56d4e64476778b | https://github.com/googlearchive/backbonefire/blob/d6278d4aeb0743bdd7e9de96cc56d4e64476778b/examples/todos/js/backbonefire.js#L276-L309 | |
22,572 | googlearchive/backbonefire | examples/todos/js/backbonefire.js | function(snap) {
var newModel = Backbone.Firebase._checkId(snap);
if (typeof newModel === 'object' && newModel !== null) {
var diff = _.difference(_.keys(this.attributes), _.keys(newModel));
_.each(diff, _.bind(function(key) {
this.unset(key);
}, this));
}
// check to see if it needs an id
this._setId(snap);
return newModel;
} | javascript | function(snap) {
var newModel = Backbone.Firebase._checkId(snap);
if (typeof newModel === 'object' && newModel !== null) {
var diff = _.difference(_.keys(this.attributes), _.keys(newModel));
_.each(diff, _.bind(function(key) {
this.unset(key);
}, this));
}
// check to see if it needs an id
this._setId(snap);
return newModel;
} | [
"function",
"(",
"snap",
")",
"{",
"var",
"newModel",
"=",
"Backbone",
".",
"Firebase",
".",
"_checkId",
"(",
"snap",
")",
";",
"if",
"(",
"typeof",
"newModel",
"===",
"'object'",
"&&",
"newModel",
"!==",
"null",
")",
"{",
"var",
"diff",
"=",
"_",
".",
"difference",
"(",
"_",
".",
"keys",
"(",
"this",
".",
"attributes",
")",
",",
"_",
".",
"keys",
"(",
"newModel",
")",
")",
";",
"_",
".",
"each",
"(",
"diff",
",",
"_",
".",
"bind",
"(",
"function",
"(",
"key",
")",
"{",
"this",
".",
"unset",
"(",
"key",
")",
";",
"}",
",",
"this",
")",
")",
";",
"}",
"// check to see if it needs an id",
"this",
".",
"_setId",
"(",
"snap",
")",
";",
"return",
"newModel",
";",
"}"
] | Unset attributes that have been deleted from the server
by comparing the keys that have been removed. | [
"Unset",
"attributes",
"that",
"have",
"been",
"deleted",
"from",
"the",
"server",
"by",
"comparing",
"the",
"keys",
"that",
"have",
"been",
"removed",
"."
] | d6278d4aeb0743bdd7e9de96cc56d4e64476778b | https://github.com/googlearchive/backbonefire/blob/d6278d4aeb0743bdd7e9de96cc56d4e64476778b/examples/todos/js/backbonefire.js#L334-L348 | |
22,573 | googlearchive/backbonefire | examples/todos/js/backbonefire.js | function(model) {
var modelObj = model.changedAttributes();
_.each(model.changed, function(value, key) {
if (typeof value === 'undefined' || value === null) {
if (key == 'id') {
delete modelObj[key];
} else {
modelObj[key] = null;
}
}
});
return modelObj;
} | javascript | function(model) {
var modelObj = model.changedAttributes();
_.each(model.changed, function(value, key) {
if (typeof value === 'undefined' || value === null) {
if (key == 'id') {
delete modelObj[key];
} else {
modelObj[key] = null;
}
}
});
return modelObj;
} | [
"function",
"(",
"model",
")",
"{",
"var",
"modelObj",
"=",
"model",
".",
"changedAttributes",
"(",
")",
";",
"_",
".",
"each",
"(",
"model",
".",
"changed",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"if",
"(",
"typeof",
"value",
"===",
"'undefined'",
"||",
"value",
"===",
"null",
")",
"{",
"if",
"(",
"key",
"==",
"'id'",
")",
"{",
"delete",
"modelObj",
"[",
"key",
"]",
";",
"}",
"else",
"{",
"modelObj",
"[",
"key",
"]",
"=",
"null",
";",
"}",
"}",
"}",
")",
";",
"return",
"modelObj",
";",
"}"
] | Find the deleted keys and set their values to null
so Firebase properly deletes them. | [
"Find",
"the",
"deleted",
"keys",
"and",
"set",
"their",
"values",
"to",
"null",
"so",
"Firebase",
"properly",
"deletes",
"them",
"."
] | d6278d4aeb0743bdd7e9de96cc56d4e64476778b | https://github.com/googlearchive/backbonefire/blob/d6278d4aeb0743bdd7e9de96cc56d4e64476778b/examples/todos/js/backbonefire.js#L354-L367 | |
22,574 | googlearchive/backbonefire | examples/todos/js/backbonefire.js | function(cb) {
var method = cb ? 'on' : 'off';
this[method]('change', function(model) {
var newModel = this._updateModel(model);
if(_.isFunction(cb)){
cb.call(this, newModel);
}
}, this);
} | javascript | function(cb) {
var method = cb ? 'on' : 'off';
this[method]('change', function(model) {
var newModel = this._updateModel(model);
if(_.isFunction(cb)){
cb.call(this, newModel);
}
}, this);
} | [
"function",
"(",
"cb",
")",
"{",
"var",
"method",
"=",
"cb",
"?",
"'on'",
":",
"'off'",
";",
"this",
"[",
"method",
"]",
"(",
"'change'",
",",
"function",
"(",
"model",
")",
"{",
"var",
"newModel",
"=",
"this",
".",
"_updateModel",
"(",
"model",
")",
";",
"if",
"(",
"_",
".",
"isFunction",
"(",
"cb",
")",
")",
"{",
"cb",
".",
"call",
"(",
"this",
",",
"newModel",
")",
";",
"}",
"}",
",",
"this",
")",
";",
"}"
] | Determine if the model will update for every local change.
Provide a callback function to call events after the update. | [
"Determine",
"if",
"the",
"model",
"will",
"update",
"for",
"every",
"local",
"change",
".",
"Provide",
"a",
"callback",
"function",
"to",
"call",
"events",
"after",
"the",
"update",
"."
] | d6278d4aeb0743bdd7e9de96cc56d4e64476778b | https://github.com/googlearchive/backbonefire/blob/d6278d4aeb0743bdd7e9de96cc56d4e64476778b/examples/todos/js/backbonefire.js#L374-L382 | |
22,575 | googlearchive/backbonefire | examples/todos/js/backbonefire.js | function(model, options) {
model.id = Backbone.Firebase._getKey(this.firebase.push());
options = _.extend({ autoSync: false }, options);
return Backbone.Collection.prototype.create.apply(this, [model, options]);
} | javascript | function(model, options) {
model.id = Backbone.Firebase._getKey(this.firebase.push());
options = _.extend({ autoSync: false }, options);
return Backbone.Collection.prototype.create.apply(this, [model, options]);
} | [
"function",
"(",
"model",
",",
"options",
")",
"{",
"model",
".",
"id",
"=",
"Backbone",
".",
"Firebase",
".",
"_getKey",
"(",
"this",
".",
"firebase",
".",
"push",
"(",
")",
")",
";",
"options",
"=",
"_",
".",
"extend",
"(",
"{",
"autoSync",
":",
"false",
"}",
",",
"options",
")",
";",
"return",
"Backbone",
".",
"Collection",
".",
"prototype",
".",
"create",
".",
"apply",
"(",
"this",
",",
"[",
"model",
",",
"options",
"]",
")",
";",
"}"
] | Create an id from a Firebase push-id and call Backbone.create, which
will do prepare the models and trigger the proper events and then call
Backbone.Firebase.sync with the correct method. | [
"Create",
"an",
"id",
"from",
"a",
"Firebase",
"push",
"-",
"id",
"and",
"call",
"Backbone",
".",
"create",
"which",
"will",
"do",
"prepare",
"the",
"models",
"and",
"trigger",
"the",
"proper",
"events",
"and",
"then",
"call",
"Backbone",
".",
"Firebase",
".",
"sync",
"with",
"the",
"correct",
"method",
"."
] | d6278d4aeb0743bdd7e9de96cc56d4e64476778b | https://github.com/googlearchive/backbonefire/blob/d6278d4aeb0743bdd7e9de96cc56d4e64476778b/examples/todos/js/backbonefire.js#L396-L400 | |
22,576 | googlearchive/backbonefire | examples/todos/js/backbonefire.js | function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) { options.parse = true; }
var success = options.success;
var collection = this;
options.success = function(resp) {
var arr = [];
var keys = _.keys(resp);
_.each(keys, function(key) {
arr.push(resp[key]);
});
var method = options.reset ? 'reset' : 'set';
collection[method](arr, options);
if (success) { success(collection, arr, options); }
options.autoSync = false;
options.url = this.url;
collection.trigger('sync', collection, arr, options);
};
return this.sync('read', this, options);
} | javascript | function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) { options.parse = true; }
var success = options.success;
var collection = this;
options.success = function(resp) {
var arr = [];
var keys = _.keys(resp);
_.each(keys, function(key) {
arr.push(resp[key]);
});
var method = options.reset ? 'reset' : 'set';
collection[method](arr, options);
if (success) { success(collection, arr, options); }
options.autoSync = false;
options.url = this.url;
collection.trigger('sync', collection, arr, options);
};
return this.sync('read', this, options);
} | [
"function",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"?",
"_",
".",
"clone",
"(",
"options",
")",
":",
"{",
"}",
";",
"if",
"(",
"options",
".",
"parse",
"===",
"void",
"0",
")",
"{",
"options",
".",
"parse",
"=",
"true",
";",
"}",
"var",
"success",
"=",
"options",
".",
"success",
";",
"var",
"collection",
"=",
"this",
";",
"options",
".",
"success",
"=",
"function",
"(",
"resp",
")",
"{",
"var",
"arr",
"=",
"[",
"]",
";",
"var",
"keys",
"=",
"_",
".",
"keys",
"(",
"resp",
")",
";",
"_",
".",
"each",
"(",
"keys",
",",
"function",
"(",
"key",
")",
"{",
"arr",
".",
"push",
"(",
"resp",
"[",
"key",
"]",
")",
";",
"}",
")",
";",
"var",
"method",
"=",
"options",
".",
"reset",
"?",
"'reset'",
":",
"'set'",
";",
"collection",
"[",
"method",
"]",
"(",
"arr",
",",
"options",
")",
";",
"if",
"(",
"success",
")",
"{",
"success",
"(",
"collection",
",",
"arr",
",",
"options",
")",
";",
"}",
"options",
".",
"autoSync",
"=",
"false",
";",
"options",
".",
"url",
"=",
"this",
".",
"url",
";",
"collection",
".",
"trigger",
"(",
"'sync'",
",",
"collection",
",",
"arr",
",",
"options",
")",
";",
"}",
";",
"return",
"this",
".",
"sync",
"(",
"'read'",
",",
"this",
",",
"options",
")",
";",
"}"
] | Firebase returns lists as an object with keys, where Backbone
collections require an array. This function modifies the existing
Backbone.Collection.fetch method by mapping the returned object from
Firebase to an array that Backbone can use. | [
"Firebase",
"returns",
"lists",
"as",
"an",
"object",
"with",
"keys",
"where",
"Backbone",
"collections",
"require",
"an",
"array",
".",
"This",
"function",
"modifies",
"the",
"existing",
"Backbone",
".",
"Collection",
".",
"fetch",
"method",
"by",
"mapping",
"the",
"returned",
"object",
"from",
"Firebase",
"to",
"an",
"array",
"that",
"Backbone",
"can",
"use",
"."
] | d6278d4aeb0743bdd7e9de96cc56d4e64476778b | https://github.com/googlearchive/backbonefire/blob/d6278d4aeb0743bdd7e9de96cc56d4e64476778b/examples/todos/js/backbonefire.js#L423-L442 | |
22,577 | googlearchive/backbonefire | examples/todos/js/backbonefire.js | function(snap) {
var model = Backbone.Firebase._checkId(snap);
var item = _.find(this.models, function(child) {
return child.id == model.id;
});
if (!item) {
// TODO: Investigate: what is the right way to handle this case?
//throw new Error('Could not find model with ID ' + model.id);
this._childAdded(snap);
return;
}
this._preventSync(item, true);
item._remoteAttributes = model;
// find the attributes that have been deleted remotely and
// unset them locally
var diff = _.difference(_.keys(item.attributes), _.keys(model));
_.each(diff, function(key) {
item.unset(key);
});
item.set(model);
// fire sync since this is a response from the server
this.trigger('sync', this);
this._preventSync(item, false);
} | javascript | function(snap) {
var model = Backbone.Firebase._checkId(snap);
var item = _.find(this.models, function(child) {
return child.id == model.id;
});
if (!item) {
// TODO: Investigate: what is the right way to handle this case?
//throw new Error('Could not find model with ID ' + model.id);
this._childAdded(snap);
return;
}
this._preventSync(item, true);
item._remoteAttributes = model;
// find the attributes that have been deleted remotely and
// unset them locally
var diff = _.difference(_.keys(item.attributes), _.keys(model));
_.each(diff, function(key) {
item.unset(key);
});
item.set(model);
// fire sync since this is a response from the server
this.trigger('sync', this);
this._preventSync(item, false);
} | [
"function",
"(",
"snap",
")",
"{",
"var",
"model",
"=",
"Backbone",
".",
"Firebase",
".",
"_checkId",
"(",
"snap",
")",
";",
"var",
"item",
"=",
"_",
".",
"find",
"(",
"this",
".",
"models",
",",
"function",
"(",
"child",
")",
"{",
"return",
"child",
".",
"id",
"==",
"model",
".",
"id",
";",
"}",
")",
";",
"if",
"(",
"!",
"item",
")",
"{",
"// TODO: Investigate: what is the right way to handle this case?",
"//throw new Error('Could not find model with ID ' + model.id);",
"this",
".",
"_childAdded",
"(",
"snap",
")",
";",
"return",
";",
"}",
"this",
".",
"_preventSync",
"(",
"item",
",",
"true",
")",
";",
"item",
".",
"_remoteAttributes",
"=",
"model",
";",
"// find the attributes that have been deleted remotely and",
"// unset them locally",
"var",
"diff",
"=",
"_",
".",
"difference",
"(",
"_",
".",
"keys",
"(",
"item",
".",
"attributes",
")",
",",
"_",
".",
"keys",
"(",
"model",
")",
")",
";",
"_",
".",
"each",
"(",
"diff",
",",
"function",
"(",
"key",
")",
"{",
"item",
".",
"unset",
"(",
"key",
")",
";",
"}",
")",
";",
"item",
".",
"set",
"(",
"model",
")",
";",
"// fire sync since this is a response from the server",
"this",
".",
"trigger",
"(",
"'sync'",
",",
"this",
")",
";",
"this",
".",
"_preventSync",
"(",
"item",
",",
"false",
")",
";",
"}"
] | when a model has changed remotely find differences between the local and remote data and apply them to the local model | [
"when",
"a",
"model",
"has",
"changed",
"remotely",
"find",
"differences",
"between",
"the",
"local",
"and",
"remote",
"data",
"and",
"apply",
"them",
"to",
"the",
"local",
"model"
] | d6278d4aeb0743bdd7e9de96cc56d4e64476778b | https://github.com/googlearchive/backbonefire/blob/d6278d4aeb0743bdd7e9de96cc56d4e64476778b/examples/todos/js/backbonefire.js#L592-L620 | |
22,578 | googlearchive/backbonefire | examples/todos/js/backbonefire.js | function(snap) {
var model = Backbone.Firebase._checkId(snap);
if (this._suppressEvent === true) {
this._suppressEvent = false;
Backbone.Collection.prototype.remove.apply(
this, [model], {silent: true}
);
} else {
// trigger sync because data has been received from the server
this.trigger('sync', this);
Backbone.Collection.prototype.remove.apply(this, [model]);
}
} | javascript | function(snap) {
var model = Backbone.Firebase._checkId(snap);
if (this._suppressEvent === true) {
this._suppressEvent = false;
Backbone.Collection.prototype.remove.apply(
this, [model], {silent: true}
);
} else {
// trigger sync because data has been received from the server
this.trigger('sync', this);
Backbone.Collection.prototype.remove.apply(this, [model]);
}
} | [
"function",
"(",
"snap",
")",
"{",
"var",
"model",
"=",
"Backbone",
".",
"Firebase",
".",
"_checkId",
"(",
"snap",
")",
";",
"if",
"(",
"this",
".",
"_suppressEvent",
"===",
"true",
")",
"{",
"this",
".",
"_suppressEvent",
"=",
"false",
";",
"Backbone",
".",
"Collection",
".",
"prototype",
".",
"remove",
".",
"apply",
"(",
"this",
",",
"[",
"model",
"]",
",",
"{",
"silent",
":",
"true",
"}",
")",
";",
"}",
"else",
"{",
"// trigger sync because data has been received from the server",
"this",
".",
"trigger",
"(",
"'sync'",
",",
"this",
")",
";",
"Backbone",
".",
"Collection",
".",
"prototype",
".",
"remove",
".",
"apply",
"(",
"this",
",",
"[",
"model",
"]",
")",
";",
"}",
"}"
] | remove an item from the collection when removed remotely provides the ability to remove siliently | [
"remove",
"an",
"item",
"from",
"the",
"collection",
"when",
"removed",
"remotely",
"provides",
"the",
"ability",
"to",
"remove",
"siliently"
] | d6278d4aeb0743bdd7e9de96cc56d4e64476778b | https://github.com/googlearchive/backbonefire/blob/d6278d4aeb0743bdd7e9de96cc56d4e64476778b/examples/todos/js/backbonefire.js#L624-L637 | |
22,579 | googlearchive/backbonefire | examples/todos/js/backbonefire.js | function(model) {
var remoteAttributes;
var localAttributes;
var updateAttributes;
var ref;
// if the model is already being handled by listeners then return
if (model._remoteChanging) {
return;
}
remoteAttributes = model._remoteAttributes || {};
localAttributes = model.toJSON();
// consolidate the updates to Firebase
updateAttributes = this._compareAttributes(remoteAttributes, localAttributes);
ref = this.firebase.ref().child(model.id);
// if '.priority' is present setWithPriority
// else do a regular update
if (_.has(updateAttributes, '.priority')) {
this._setWithPriority(ref, localAttributes);
} else {
this._updateToFirebase(ref, localAttributes);
}
} | javascript | function(model) {
var remoteAttributes;
var localAttributes;
var updateAttributes;
var ref;
// if the model is already being handled by listeners then return
if (model._remoteChanging) {
return;
}
remoteAttributes = model._remoteAttributes || {};
localAttributes = model.toJSON();
// consolidate the updates to Firebase
updateAttributes = this._compareAttributes(remoteAttributes, localAttributes);
ref = this.firebase.ref().child(model.id);
// if '.priority' is present setWithPriority
// else do a regular update
if (_.has(updateAttributes, '.priority')) {
this._setWithPriority(ref, localAttributes);
} else {
this._updateToFirebase(ref, localAttributes);
}
} | [
"function",
"(",
"model",
")",
"{",
"var",
"remoteAttributes",
";",
"var",
"localAttributes",
";",
"var",
"updateAttributes",
";",
"var",
"ref",
";",
"// if the model is already being handled by listeners then return",
"if",
"(",
"model",
".",
"_remoteChanging",
")",
"{",
"return",
";",
"}",
"remoteAttributes",
"=",
"model",
".",
"_remoteAttributes",
"||",
"{",
"}",
";",
"localAttributes",
"=",
"model",
".",
"toJSON",
"(",
")",
";",
"// consolidate the updates to Firebase",
"updateAttributes",
"=",
"this",
".",
"_compareAttributes",
"(",
"remoteAttributes",
",",
"localAttributes",
")",
";",
"ref",
"=",
"this",
".",
"firebase",
".",
"ref",
"(",
")",
".",
"child",
"(",
"model",
".",
"id",
")",
";",
"// if '.priority' is present setWithPriority",
"// else do a regular update",
"if",
"(",
"_",
".",
"has",
"(",
"updateAttributes",
",",
"'.priority'",
")",
")",
"{",
"this",
".",
"_setWithPriority",
"(",
"ref",
",",
"localAttributes",
")",
";",
"}",
"else",
"{",
"this",
".",
"_updateToFirebase",
"(",
"ref",
",",
"localAttributes",
")",
";",
"}",
"}"
] | Add handlers for all models in this collection, and any future ones that may be added. | [
"Add",
"handlers",
"for",
"all",
"models",
"in",
"this",
"collection",
"and",
"any",
"future",
"ones",
"that",
"may",
"be",
"added",
"."
] | d6278d4aeb0743bdd7e9de96cc56d4e64476778b | https://github.com/googlearchive/backbonefire/blob/d6278d4aeb0743bdd7e9de96cc56d4e64476778b/examples/todos/js/backbonefire.js#L641-L668 | |
22,580 | googlearchive/backbonefire | examples/todos/js/backbonefire.js | function(remoteAttributes, localAttributes) {
var updateAttributes = {};
var union = _.union(_.keys(remoteAttributes), _.keys(localAttributes));
_.each(union, function(key) {
if (!_.has(localAttributes, key)) {
updateAttributes[key] = null;
} else if (localAttributes[key] != remoteAttributes[key]) {
updateAttributes[key] = localAttributes[key];
}
});
return updateAttributes;
} | javascript | function(remoteAttributes, localAttributes) {
var updateAttributes = {};
var union = _.union(_.keys(remoteAttributes), _.keys(localAttributes));
_.each(union, function(key) {
if (!_.has(localAttributes, key)) {
updateAttributes[key] = null;
} else if (localAttributes[key] != remoteAttributes[key]) {
updateAttributes[key] = localAttributes[key];
}
});
return updateAttributes;
} | [
"function",
"(",
"remoteAttributes",
",",
"localAttributes",
")",
"{",
"var",
"updateAttributes",
"=",
"{",
"}",
";",
"var",
"union",
"=",
"_",
".",
"union",
"(",
"_",
".",
"keys",
"(",
"remoteAttributes",
")",
",",
"_",
".",
"keys",
"(",
"localAttributes",
")",
")",
";",
"_",
".",
"each",
"(",
"union",
",",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"!",
"_",
".",
"has",
"(",
"localAttributes",
",",
"key",
")",
")",
"{",
"updateAttributes",
"[",
"key",
"]",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"localAttributes",
"[",
"key",
"]",
"!=",
"remoteAttributes",
"[",
"key",
"]",
")",
"{",
"updateAttributes",
"[",
"key",
"]",
"=",
"localAttributes",
"[",
"key",
"]",
";",
"}",
"}",
")",
";",
"return",
"updateAttributes",
";",
"}"
] | set the attributes to be updated to Firebase set any removed attributes to null so that Firebase removes them | [
"set",
"the",
"attributes",
"to",
"be",
"updated",
"to",
"Firebase",
"set",
"any",
"removed",
"attributes",
"to",
"null",
"so",
"that",
"Firebase",
"removes",
"them"
] | d6278d4aeb0743bdd7e9de96cc56d4e64476778b | https://github.com/googlearchive/backbonefire/blob/d6278d4aeb0743bdd7e9de96cc56d4e64476778b/examples/todos/js/backbonefire.js#L672-L686 | |
22,581 | googlearchive/backbonefire | examples/todos/js/backbonefire.js | function(ref, item) {
var priority = item['.priority'];
delete item['.priority'];
ref.setWithPriority(item, priority);
return item;
} | javascript | function(ref, item) {
var priority = item['.priority'];
delete item['.priority'];
ref.setWithPriority(item, priority);
return item;
} | [
"function",
"(",
"ref",
",",
"item",
")",
"{",
"var",
"priority",
"=",
"item",
"[",
"'.priority'",
"]",
";",
"delete",
"item",
"[",
"'.priority'",
"]",
";",
"ref",
".",
"setWithPriority",
"(",
"item",
",",
"priority",
")",
";",
"return",
"item",
";",
"}"
] | Special case if '.priority' was updated - a merge is not allowed so we'll have to do a full setWithPriority. | [
"Special",
"case",
"if",
".",
"priority",
"was",
"updated",
"-",
"a",
"merge",
"is",
"not",
"allowed",
"so",
"we",
"ll",
"have",
"to",
"do",
"a",
"full",
"setWithPriority",
"."
] | d6278d4aeb0743bdd7e9de96cc56d4e64476778b | https://github.com/googlearchive/backbonefire/blob/d6278d4aeb0743bdd7e9de96cc56d4e64476778b/examples/todos/js/backbonefire.js#L690-L695 | |
22,582 | repetere/modelscript | build/modelscript.umd.js | function(data, param) {
var eol = getEol(data,param);
var lines = data.split(eol);
var partial = lines.pop();
return {lines: lines, partial: partial};
} | javascript | function(data, param) {
var eol = getEol(data,param);
var lines = data.split(eol);
var partial = lines.pop();
return {lines: lines, partial: partial};
} | [
"function",
"(",
"data",
",",
"param",
")",
"{",
"var",
"eol",
"=",
"getEol",
"(",
"data",
",",
"param",
")",
";",
"var",
"lines",
"=",
"data",
".",
"split",
"(",
"eol",
")",
";",
"var",
"partial",
"=",
"lines",
".",
"pop",
"(",
")",
";",
"return",
"{",
"lines",
":",
"lines",
",",
"partial",
":",
"partial",
"}",
";",
"}"
] | convert data chunk to file lines array
@param {string} data data chunk as utf8 string
@param {object} param Converter param object
@return {Object} {lines:[line1,line2...],partial:String} | [
"convert",
"data",
"chunk",
"to",
"file",
"lines",
"array"
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L7560-L7565 | |
22,583 | repetere/modelscript | build/modelscript.umd.js | rowSplit | function rowSplit(rowStr, param) {
if (rowStr === "") {
return { cols: [], closed: true };
}
var quote = param.quote;
var trim = param.trim;
var escape = param.escape;
if (param.delimiter instanceof Array || param.delimiter.toLowerCase() === "auto") {
param.delimiter = getDelimiter_1(rowStr, param);
}
var delimiter = param.delimiter;
var rowArr = rowStr.split(delimiter);
if (quote === "off") {
return { cols: rowArr, closed: true };
}
var row = [];
var inquote = false;
var quoteBuff = '';
for (var i = 0, rowLen = rowArr.length; i < rowLen; i++) {
var e = rowArr[i];
if (!inquote && trim) {
e = e.trim();
}
var len = e.length;
if (!inquote) {
if (isQuoteOpen(e, param)) { //quote open
e = e.substr(1);
if (isQuoteClose(e, param)) { //quote close
e = e.substring(0, e.length - 1);
e = _escapeQuote(e, quote, escape);
row.push(e);
continue;
} else {
inquote = true;
quoteBuff += e;
continue;
}
} else {
row.push(e);
continue;
}
} else { //previous quote not closed
if (isQuoteClose(e, param)) { //close double quote
inquote = false;
e = e.substr(0, len - 1);
quoteBuff += delimiter + e;
quoteBuff = _escapeQuote(quoteBuff, quote, escape);
if (trim) {
quoteBuff = quoteBuff.trimRight();
}
row.push(quoteBuff);
quoteBuff = "";
} else {
quoteBuff += delimiter + e;
}
}
}
if (!inquote && param._needFilterRow) {
row = filterRow(row, param);
}
return { cols: row, closed: !inquote };
// if (param.workerNum<=1){
// }else{
// if (inquote && quoteBuff.length>0){//for multi core, quote will be closed at the end of line
// quoteBuff=_escapeQuote(quoteBuff,quote,escape);;
// if (trim){
// quoteBuff=quoteBuff.trimRight();
// }
// row.push(quoteBuff);
// }
// return {cols:row,closed:true};
// }
} | javascript | function rowSplit(rowStr, param) {
if (rowStr === "") {
return { cols: [], closed: true };
}
var quote = param.quote;
var trim = param.trim;
var escape = param.escape;
if (param.delimiter instanceof Array || param.delimiter.toLowerCase() === "auto") {
param.delimiter = getDelimiter_1(rowStr, param);
}
var delimiter = param.delimiter;
var rowArr = rowStr.split(delimiter);
if (quote === "off") {
return { cols: rowArr, closed: true };
}
var row = [];
var inquote = false;
var quoteBuff = '';
for (var i = 0, rowLen = rowArr.length; i < rowLen; i++) {
var e = rowArr[i];
if (!inquote && trim) {
e = e.trim();
}
var len = e.length;
if (!inquote) {
if (isQuoteOpen(e, param)) { //quote open
e = e.substr(1);
if (isQuoteClose(e, param)) { //quote close
e = e.substring(0, e.length - 1);
e = _escapeQuote(e, quote, escape);
row.push(e);
continue;
} else {
inquote = true;
quoteBuff += e;
continue;
}
} else {
row.push(e);
continue;
}
} else { //previous quote not closed
if (isQuoteClose(e, param)) { //close double quote
inquote = false;
e = e.substr(0, len - 1);
quoteBuff += delimiter + e;
quoteBuff = _escapeQuote(quoteBuff, quote, escape);
if (trim) {
quoteBuff = quoteBuff.trimRight();
}
row.push(quoteBuff);
quoteBuff = "";
} else {
quoteBuff += delimiter + e;
}
}
}
if (!inquote && param._needFilterRow) {
row = filterRow(row, param);
}
return { cols: row, closed: !inquote };
// if (param.workerNum<=1){
// }else{
// if (inquote && quoteBuff.length>0){//for multi core, quote will be closed at the end of line
// quoteBuff=_escapeQuote(quoteBuff,quote,escape);;
// if (trim){
// quoteBuff=quoteBuff.trimRight();
// }
// row.push(quoteBuff);
// }
// return {cols:row,closed:true};
// }
} | [
"function",
"rowSplit",
"(",
"rowStr",
",",
"param",
")",
"{",
"if",
"(",
"rowStr",
"===",
"\"\"",
")",
"{",
"return",
"{",
"cols",
":",
"[",
"]",
",",
"closed",
":",
"true",
"}",
";",
"}",
"var",
"quote",
"=",
"param",
".",
"quote",
";",
"var",
"trim",
"=",
"param",
".",
"trim",
";",
"var",
"escape",
"=",
"param",
".",
"escape",
";",
"if",
"(",
"param",
".",
"delimiter",
"instanceof",
"Array",
"||",
"param",
".",
"delimiter",
".",
"toLowerCase",
"(",
")",
"===",
"\"auto\"",
")",
"{",
"param",
".",
"delimiter",
"=",
"getDelimiter_1",
"(",
"rowStr",
",",
"param",
")",
";",
"}",
"var",
"delimiter",
"=",
"param",
".",
"delimiter",
";",
"var",
"rowArr",
"=",
"rowStr",
".",
"split",
"(",
"delimiter",
")",
";",
"if",
"(",
"quote",
"===",
"\"off\"",
")",
"{",
"return",
"{",
"cols",
":",
"rowArr",
",",
"closed",
":",
"true",
"}",
";",
"}",
"var",
"row",
"=",
"[",
"]",
";",
"var",
"inquote",
"=",
"false",
";",
"var",
"quoteBuff",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"rowLen",
"=",
"rowArr",
".",
"length",
";",
"i",
"<",
"rowLen",
";",
"i",
"++",
")",
"{",
"var",
"e",
"=",
"rowArr",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"inquote",
"&&",
"trim",
")",
"{",
"e",
"=",
"e",
".",
"trim",
"(",
")",
";",
"}",
"var",
"len",
"=",
"e",
".",
"length",
";",
"if",
"(",
"!",
"inquote",
")",
"{",
"if",
"(",
"isQuoteOpen",
"(",
"e",
",",
"param",
")",
")",
"{",
"//quote open",
"e",
"=",
"e",
".",
"substr",
"(",
"1",
")",
";",
"if",
"(",
"isQuoteClose",
"(",
"e",
",",
"param",
")",
")",
"{",
"//quote close",
"e",
"=",
"e",
".",
"substring",
"(",
"0",
",",
"e",
".",
"length",
"-",
"1",
")",
";",
"e",
"=",
"_escapeQuote",
"(",
"e",
",",
"quote",
",",
"escape",
")",
";",
"row",
".",
"push",
"(",
"e",
")",
";",
"continue",
";",
"}",
"else",
"{",
"inquote",
"=",
"true",
";",
"quoteBuff",
"+=",
"e",
";",
"continue",
";",
"}",
"}",
"else",
"{",
"row",
".",
"push",
"(",
"e",
")",
";",
"continue",
";",
"}",
"}",
"else",
"{",
"//previous quote not closed",
"if",
"(",
"isQuoteClose",
"(",
"e",
",",
"param",
")",
")",
"{",
"//close double quote",
"inquote",
"=",
"false",
";",
"e",
"=",
"e",
".",
"substr",
"(",
"0",
",",
"len",
"-",
"1",
")",
";",
"quoteBuff",
"+=",
"delimiter",
"+",
"e",
";",
"quoteBuff",
"=",
"_escapeQuote",
"(",
"quoteBuff",
",",
"quote",
",",
"escape",
")",
";",
"if",
"(",
"trim",
")",
"{",
"quoteBuff",
"=",
"quoteBuff",
".",
"trimRight",
"(",
")",
";",
"}",
"row",
".",
"push",
"(",
"quoteBuff",
")",
";",
"quoteBuff",
"=",
"\"\"",
";",
"}",
"else",
"{",
"quoteBuff",
"+=",
"delimiter",
"+",
"e",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"inquote",
"&&",
"param",
".",
"_needFilterRow",
")",
"{",
"row",
"=",
"filterRow",
"(",
"row",
",",
"param",
")",
";",
"}",
"return",
"{",
"cols",
":",
"row",
",",
"closed",
":",
"!",
"inquote",
"}",
";",
"// if (param.workerNum<=1){",
"// }else{",
"// if (inquote && quoteBuff.length>0){//for multi core, quote will be closed at the end of line",
"// quoteBuff=_escapeQuote(quoteBuff,quote,escape);;",
"// if (trim){",
"// quoteBuff=quoteBuff.trimRight();",
"// }",
"// row.push(quoteBuff);",
"// }",
"// return {cols:row,closed:true};",
"// }",
"}"
] | Convert a line of string to csv columns according to its delimiter
the param._header may not be ready when this is called.
@param {[type]} rowStr [description]
@param {[type]} param [Converter param]
@return {[type]} {cols:["a","b","c"],closed:boolean} the closed field indicate if the row is a complete row | [
"Convert",
"a",
"line",
"of",
"string",
"to",
"csv",
"columns",
"according",
"to",
"its",
"delimiter",
"the",
"param",
".",
"_header",
"may",
"not",
"be",
"ready",
"when",
"this",
"is",
"called",
"."
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L7617-L7692 |
22,584 | repetere/modelscript | build/modelscript.umd.js | function(lines, param) {
var csvLines = [];
var left = "";
while (lines.length) {
var line = left + lines.shift();
var row = rowSplit(line, param);
if (row.closed) {
csvLines.push(row.cols);
left = "";
} else {
left = line + (getEol(line, param) || "\n"); // if unable to getEol from data, assume "\n"
}
}
return {lines: csvLines, partial: left};
} | javascript | function(lines, param) {
var csvLines = [];
var left = "";
while (lines.length) {
var line = left + lines.shift();
var row = rowSplit(line, param);
if (row.closed) {
csvLines.push(row.cols);
left = "";
} else {
left = line + (getEol(line, param) || "\n"); // if unable to getEol from data, assume "\n"
}
}
return {lines: csvLines, partial: left};
} | [
"function",
"(",
"lines",
",",
"param",
")",
"{",
"var",
"csvLines",
"=",
"[",
"]",
";",
"var",
"left",
"=",
"\"\"",
";",
"while",
"(",
"lines",
".",
"length",
")",
"{",
"var",
"line",
"=",
"left",
"+",
"lines",
".",
"shift",
"(",
")",
";",
"var",
"row",
"=",
"rowSplit",
"(",
"line",
",",
"param",
")",
";",
"if",
"(",
"row",
".",
"closed",
")",
"{",
"csvLines",
".",
"push",
"(",
"row",
".",
"cols",
")",
";",
"left",
"=",
"\"\"",
";",
"}",
"else",
"{",
"left",
"=",
"line",
"+",
"(",
"getEol",
"(",
"line",
",",
"param",
")",
"||",
"\"\\n\"",
")",
";",
"// if unable to getEol from data, assume \"\\n\"",
"}",
"}",
"return",
"{",
"lines",
":",
"csvLines",
",",
"partial",
":",
"left",
"}",
";",
"}"
] | Convert lines to csv columns
@param {[type]} lines [file lines]
@param {[type]} param [Converter param]
@return {[type]} {lines:[[col1,col2,col3...]],partial:String} | [
"Convert",
"lines",
"to",
"csv",
"columns"
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L7737-L7751 | |
22,585 | repetere/modelscript | build/modelscript.umd.js | function(fileLine, params) {
var lines = fileLine.lines;
var csvLines = csvline(lines,params);
return {
lines: csvLines.lines,
partial: csvLines.partial + fileLine.partial
};
} | javascript | function(fileLine, params) {
var lines = fileLine.lines;
var csvLines = csvline(lines,params);
return {
lines: csvLines.lines,
partial: csvLines.partial + fileLine.partial
};
} | [
"function",
"(",
"fileLine",
",",
"params",
")",
"{",
"var",
"lines",
"=",
"fileLine",
".",
"lines",
";",
"var",
"csvLines",
"=",
"csvline",
"(",
"lines",
",",
"params",
")",
";",
"return",
"{",
"lines",
":",
"csvLines",
".",
"lines",
",",
"partial",
":",
"csvLines",
".",
"partial",
"+",
"fileLine",
".",
"partial",
"}",
";",
"}"
] | Convert data chunk to csv lines with cols
@param {[type]} data [description]
@param {[type]} params [description]
@return {[type]} {lines:[[col1,col2,col3]],partial:String} | [
"Convert",
"data",
"chunk",
"to",
"csv",
"lines",
"with",
"cols"
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L7759-L7766 | |
22,586 | repetere/modelscript | build/modelscript.umd.js | function (lines, params, idx) {
if (params._needParseJson) {
if (!params._headers) {
params._headers = [];
}
if (!params.parseRules) {
var row = params._headers;
params.parseRules = parserMgr.initParsers(row, params);
}
return processRows(lines, params, idx);
} else {
return justReturnRows(lines, params, idx);
}
} | javascript | function (lines, params, idx) {
if (params._needParseJson) {
if (!params._headers) {
params._headers = [];
}
if (!params.parseRules) {
var row = params._headers;
params.parseRules = parserMgr.initParsers(row, params);
}
return processRows(lines, params, idx);
} else {
return justReturnRows(lines, params, idx);
}
} | [
"function",
"(",
"lines",
",",
"params",
",",
"idx",
")",
"{",
"if",
"(",
"params",
".",
"_needParseJson",
")",
"{",
"if",
"(",
"!",
"params",
".",
"_headers",
")",
"{",
"params",
".",
"_headers",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"!",
"params",
".",
"parseRules",
")",
"{",
"var",
"row",
"=",
"params",
".",
"_headers",
";",
"params",
".",
"parseRules",
"=",
"parserMgr",
".",
"initParsers",
"(",
"row",
",",
"params",
")",
";",
"}",
"return",
"processRows",
"(",
"lines",
",",
"params",
",",
"idx",
")",
";",
"}",
"else",
"{",
"return",
"justReturnRows",
"(",
"lines",
",",
"params",
",",
"idx",
")",
";",
"}",
"}"
] | Convert lines of csv array into json
@param {[type]} lines [[col1,col2,col3]]
@param {[type]} params Converter params with _headers field populated
@param {[type]} idx start pos of the lines
@return {[type]} [{err:null,json:obj,index:line,row:[csv row]}] | [
"Convert",
"lines",
"of",
"csv",
"array",
"into",
"json"
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L9419-L9432 | |
22,587 | repetere/modelscript | build/modelscript.umd.js | _initConverter | function _initConverter(){
var csvConverter = new Converter_1();
var started = false;
var writeStream = process.stdout;
csvConverter.on("record_parsed",function(rowJSON){
if (started){
writeStream.write(",\n");
}
writeStream.write(JSON.stringify(rowJSON)); //write parsed JSON object one by one.
if (started === false){
started = true;
}
});
writeStream.write("[\n"); //write array symbol
csvConverter.on("end_parsed",function(){
writeStream.write("\n]"); //end array symbol
});
csvConverter.on("error",function(err){
console.error(err);
process.exit(-1);
});
return csvConverter;
} | javascript | function _initConverter(){
var csvConverter = new Converter_1();
var started = false;
var writeStream = process.stdout;
csvConverter.on("record_parsed",function(rowJSON){
if (started){
writeStream.write(",\n");
}
writeStream.write(JSON.stringify(rowJSON)); //write parsed JSON object one by one.
if (started === false){
started = true;
}
});
writeStream.write("[\n"); //write array symbol
csvConverter.on("end_parsed",function(){
writeStream.write("\n]"); //end array symbol
});
csvConverter.on("error",function(err){
console.error(err);
process.exit(-1);
});
return csvConverter;
} | [
"function",
"_initConverter",
"(",
")",
"{",
"var",
"csvConverter",
"=",
"new",
"Converter_1",
"(",
")",
";",
"var",
"started",
"=",
"false",
";",
"var",
"writeStream",
"=",
"process",
".",
"stdout",
";",
"csvConverter",
".",
"on",
"(",
"\"record_parsed\"",
",",
"function",
"(",
"rowJSON",
")",
"{",
"if",
"(",
"started",
")",
"{",
"writeStream",
".",
"write",
"(",
"\",\\n\"",
")",
";",
"}",
"writeStream",
".",
"write",
"(",
"JSON",
".",
"stringify",
"(",
"rowJSON",
")",
")",
";",
"//write parsed JSON object one by one.",
"if",
"(",
"started",
"===",
"false",
")",
"{",
"started",
"=",
"true",
";",
"}",
"}",
")",
";",
"writeStream",
".",
"write",
"(",
"\"[\\n\"",
")",
";",
"//write array symbol",
"csvConverter",
".",
"on",
"(",
"\"end_parsed\"",
",",
"function",
"(",
")",
"{",
"writeStream",
".",
"write",
"(",
"\"\\n]\"",
")",
";",
"//end array symbol",
"}",
")",
";",
"csvConverter",
".",
"on",
"(",
"\"error\"",
",",
"function",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"err",
")",
";",
"process",
".",
"exit",
"(",
"-",
"1",
")",
";",
"}",
")",
";",
"return",
"csvConverter",
";",
"}"
] | Convert input to process stdout
implementation | [
"Convert",
"input",
"to",
"process",
"stdout",
"implementation"
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L27505-L27528 |
22,588 | repetere/modelscript | build/modelscript.umd.js | loadCSVURI | async function loadCSVURI(filepath, options) {
const reqMethod = (filepath.search('https', 'gi') > -1) ? get : get;
return new Promise((resolve, reject) => {
const csvData = [];
const config = Object.assign({ checkType: true, }, options);
const req = reqMethod(filepath, res => {
csvtojson(config).fromStream(res)
.on('json', jsonObj => {
csvData.push(jsonObj);
})
.on('error', err => {
return reject(err);
})
.on('done', error => {
if (error) {
return reject(error);
} else {
return resolve(csvData);
}
});
});
req.on('error', reject);
});
} | javascript | async function loadCSVURI(filepath, options) {
const reqMethod = (filepath.search('https', 'gi') > -1) ? get : get;
return new Promise((resolve, reject) => {
const csvData = [];
const config = Object.assign({ checkType: true, }, options);
const req = reqMethod(filepath, res => {
csvtojson(config).fromStream(res)
.on('json', jsonObj => {
csvData.push(jsonObj);
})
.on('error', err => {
return reject(err);
})
.on('done', error => {
if (error) {
return reject(error);
} else {
return resolve(csvData);
}
});
});
req.on('error', reject);
});
} | [
"async",
"function",
"loadCSVURI",
"(",
"filepath",
",",
"options",
")",
"{",
"const",
"reqMethod",
"=",
"(",
"filepath",
".",
"search",
"(",
"'https'",
",",
"'gi'",
")",
">",
"-",
"1",
")",
"?",
"get",
":",
"get",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"csvData",
"=",
"[",
"]",
";",
"const",
"config",
"=",
"Object",
".",
"assign",
"(",
"{",
"checkType",
":",
"true",
",",
"}",
",",
"options",
")",
";",
"const",
"req",
"=",
"reqMethod",
"(",
"filepath",
",",
"res",
"=>",
"{",
"csvtojson",
"(",
"config",
")",
".",
"fromStream",
"(",
"res",
")",
".",
"on",
"(",
"'json'",
",",
"jsonObj",
"=>",
"{",
"csvData",
".",
"push",
"(",
"jsonObj",
")",
";",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"err",
"=>",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
")",
".",
"on",
"(",
"'done'",
",",
"error",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"reject",
"(",
"error",
")",
";",
"}",
"else",
"{",
"return",
"resolve",
"(",
"csvData",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"req",
".",
"on",
"(",
"'error'",
",",
"reject",
")",
";",
"}",
")",
";",
"}"
] | Asynchronously loads a CSV from a remote URL and returns an array of objects
@example
// returns [{header:value,header2:value2}]
loadCSVURI('https://raw.githubusercontent.com/repetere/modelscript/master/test/mock/data.csv').then(csvData).catch(console.error)
@memberOf csv
@param {string} filepath - URL to CSV path
@param {Object} [options] - options passed to csvtojson
@returns {Object[]} returns an array of objects from a csv where each column header is the property name | [
"Asynchronously",
"loads",
"a",
"CSV",
"from",
"a",
"remote",
"URL",
"and",
"returns",
"an",
"array",
"of",
"objects"
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L27578-L27601 |
22,589 | repetere/modelscript | build/modelscript.umd.js | loadCSV | async function loadCSV(filepath, options) {
if (validUrl.isUri(filepath)) {
return loadCSVURI(filepath, options);
} else {
return new Promise((resolve, reject) => {
const csvData = [];
const config = Object.assign({ checkType: true, }, options);
csvtojson(config).fromFile(filepath)
.on('json', jsonObj => {
csvData.push(jsonObj);
})
.on('error', err => {
return reject(err);
})
.on('done', error => {
if (error) {
return reject(error);
} else {
return resolve(csvData);
}
});
});
}
} | javascript | async function loadCSV(filepath, options) {
if (validUrl.isUri(filepath)) {
return loadCSVURI(filepath, options);
} else {
return new Promise((resolve, reject) => {
const csvData = [];
const config = Object.assign({ checkType: true, }, options);
csvtojson(config).fromFile(filepath)
.on('json', jsonObj => {
csvData.push(jsonObj);
})
.on('error', err => {
return reject(err);
})
.on('done', error => {
if (error) {
return reject(error);
} else {
return resolve(csvData);
}
});
});
}
} | [
"async",
"function",
"loadCSV",
"(",
"filepath",
",",
"options",
")",
"{",
"if",
"(",
"validUrl",
".",
"isUri",
"(",
"filepath",
")",
")",
"{",
"return",
"loadCSVURI",
"(",
"filepath",
",",
"options",
")",
";",
"}",
"else",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"csvData",
"=",
"[",
"]",
";",
"const",
"config",
"=",
"Object",
".",
"assign",
"(",
"{",
"checkType",
":",
"true",
",",
"}",
",",
"options",
")",
";",
"csvtojson",
"(",
"config",
")",
".",
"fromFile",
"(",
"filepath",
")",
".",
"on",
"(",
"'json'",
",",
"jsonObj",
"=>",
"{",
"csvData",
".",
"push",
"(",
"jsonObj",
")",
";",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"err",
"=>",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
")",
".",
"on",
"(",
"'done'",
",",
"error",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"reject",
"(",
"error",
")",
";",
"}",
"else",
"{",
"return",
"resolve",
"(",
"csvData",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
"}"
] | Asynchronously loads a CSV from either a filepath or remote URL and returns an array of objects
@example
// returns [{header:value,header2:value2}]
loadCSV('../mock/invalid-file.csv').then(csvData).catch(console.error)
@memberOf csv
@param {string} filepath - URL to CSV path
@param {Object} [options] - options passed to csvtojson
@returns {Object[]} returns an array of objects from a csv where each column header is the property name | [
"Asynchronously",
"loads",
"a",
"CSV",
"from",
"either",
"a",
"filepath",
"or",
"remote",
"URL",
"and",
"returns",
"an",
"array",
"of",
"objects"
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L27614-L27637 |
22,590 | repetere/modelscript | build/modelscript.umd.js | loadTSV | async function loadTSV(filepath, options) {
const tsvOptions = Object.assign({
checkType: true,
}, options, {
delimiter: '\t',
});
return loadCSV(filepath, tsvOptions);
} | javascript | async function loadTSV(filepath, options) {
const tsvOptions = Object.assign({
checkType: true,
}, options, {
delimiter: '\t',
});
return loadCSV(filepath, tsvOptions);
} | [
"async",
"function",
"loadTSV",
"(",
"filepath",
",",
"options",
")",
"{",
"const",
"tsvOptions",
"=",
"Object",
".",
"assign",
"(",
"{",
"checkType",
":",
"true",
",",
"}",
",",
"options",
",",
"{",
"delimiter",
":",
"'\\t'",
",",
"}",
")",
";",
"return",
"loadCSV",
"(",
"filepath",
",",
"tsvOptions",
")",
";",
"}"
] | Asynchronously loads a TSV from either a filepath or remote URL and returns an array of objects
@example
// returns [{header:value,header2:value2}]
loadCSV('../mock/invalid-file.tsv').then(csvData).catch(console.error)
@memberOf csv
@param {string} filepath - URL to CSV path
@param {Object} [options] - options passed to csvtojson
@returns {Object[]} returns an array of objects from a csv where each column header is the property name | [
"Asynchronously",
"loads",
"a",
"TSV",
"from",
"either",
"a",
"filepath",
"or",
"remote",
"URL",
"and",
"returns",
"an",
"array",
"of",
"objects"
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L27649-L27656 |
22,591 | repetere/modelscript | build/modelscript.umd.js | max | function max(input) {
if (!Array.isArray(input)) {
throw new Error('input must be an array');
}
if (input.length === 0) {
throw new Error('input must not be empty');
}
var max = input[0];
for (var i = 1; i < input.length; i++) {
if (input[i] > max) max = input[i];
}
return max;
} | javascript | function max(input) {
if (!Array.isArray(input)) {
throw new Error('input must be an array');
}
if (input.length === 0) {
throw new Error('input must not be empty');
}
var max = input[0];
for (var i = 1; i < input.length; i++) {
if (input[i] > max) max = input[i];
}
return max;
} | [
"function",
"max",
"(",
"input",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"input",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'input must be an array'",
")",
";",
"}",
"if",
"(",
"input",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'input must not be empty'",
")",
";",
"}",
"var",
"max",
"=",
"input",
"[",
"0",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"input",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"input",
"[",
"i",
"]",
">",
"max",
")",
"max",
"=",
"input",
"[",
"i",
"]",
";",
"}",
"return",
"max",
";",
"}"
] | Computes the maximum of the given values
@param {Array<number>} input
@return {number} | [
"Computes",
"the",
"maximum",
"of",
"the",
"given",
"values"
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L28466-L28480 |
22,592 | repetere/modelscript | build/modelscript.umd.js | min | function min(input) {
if (!Array.isArray(input)) {
throw new Error('input must be an array');
}
if (input.length === 0) {
throw new Error('input must not be empty');
}
var min = input[0];
for (var i = 1; i < input.length; i++) {
if (input[i] < min) min = input[i];
}
return min;
} | javascript | function min(input) {
if (!Array.isArray(input)) {
throw new Error('input must be an array');
}
if (input.length === 0) {
throw new Error('input must not be empty');
}
var min = input[0];
for (var i = 1; i < input.length; i++) {
if (input[i] < min) min = input[i];
}
return min;
} | [
"function",
"min",
"(",
"input",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"input",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'input must be an array'",
")",
";",
"}",
"if",
"(",
"input",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'input must not be empty'",
")",
";",
"}",
"var",
"min",
"=",
"input",
"[",
"0",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"input",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"input",
"[",
"i",
"]",
"<",
"min",
")",
"min",
"=",
"input",
"[",
"i",
"]",
";",
"}",
"return",
"min",
";",
"}"
] | Computes the minimum of the given values
@param {Array<number>} input
@return {number} | [
"Computes",
"the",
"minimum",
"of",
"the",
"given",
"values"
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L28487-L28501 |
22,593 | repetere/modelscript | build/modelscript.umd.js | embed | function embed(mat, rows, cols) {
var r = mat.rows;
var c = mat.columns;
if ((r === rows) && (c === cols)) {
return mat;
} else {
var resultat = Matrix.zeros(rows, cols);
resultat = resultat.setSubMatrix(mat, 0, 0);
return resultat;
}
} | javascript | function embed(mat, rows, cols) {
var r = mat.rows;
var c = mat.columns;
if ((r === rows) && (c === cols)) {
return mat;
} else {
var resultat = Matrix.zeros(rows, cols);
resultat = resultat.setSubMatrix(mat, 0, 0);
return resultat;
}
} | [
"function",
"embed",
"(",
"mat",
",",
"rows",
",",
"cols",
")",
"{",
"var",
"r",
"=",
"mat",
".",
"rows",
";",
"var",
"c",
"=",
"mat",
".",
"columns",
";",
"if",
"(",
"(",
"r",
"===",
"rows",
")",
"&&",
"(",
"c",
"===",
"cols",
")",
")",
"{",
"return",
"mat",
";",
"}",
"else",
"{",
"var",
"resultat",
"=",
"Matrix",
".",
"zeros",
"(",
"rows",
",",
"cols",
")",
";",
"resultat",
"=",
"resultat",
".",
"setSubMatrix",
"(",
"mat",
",",
"0",
",",
"0",
")",
";",
"return",
"resultat",
";",
"}",
"}"
] | Put a matrix into the top left of a matrix of zeros. `rows` and `cols` are the dimensions of the output matrix. | [
"Put",
"a",
"matrix",
"into",
"the",
"top",
"left",
"of",
"a",
"matrix",
"of",
"zeros",
".",
"rows",
"and",
"cols",
"are",
"the",
"dimensions",
"of",
"the",
"output",
"matrix",
"."
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L29971-L29981 |
22,594 | repetere/modelscript | build/modelscript.umd.js | mean | function mean(input) {
if (!Array.isArray(input)) {
throw new Error('input must be an array');
}
if (input.length === 0) {
throw new Error('input must not be empty');
}
var sum = 0;
for (var i = 0; i < input.length; i++) {
sum += input[i];
}
return sum / input.length;
} | javascript | function mean(input) {
if (!Array.isArray(input)) {
throw new Error('input must be an array');
}
if (input.length === 0) {
throw new Error('input must not be empty');
}
var sum = 0;
for (var i = 0; i < input.length; i++) {
sum += input[i];
}
return sum / input.length;
} | [
"function",
"mean",
"(",
"input",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"input",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'input must be an array'",
")",
";",
"}",
"if",
"(",
"input",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'input must not be empty'",
")",
";",
"}",
"var",
"sum",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"input",
".",
"length",
";",
"i",
"++",
")",
"{",
"sum",
"+=",
"input",
"[",
"i",
"]",
";",
"}",
"return",
"sum",
"/",
"input",
".",
"length",
";",
"}"
] | Computes the mean of the given values
@param {Array<number>} input
@return {number} | [
"Computes",
"the",
"mean",
"of",
"the",
"given",
"values"
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L30898-L30912 |
22,595 | repetere/modelscript | build/modelscript.umd.js | examplesBaggingWithReplacement | function examplesBaggingWithReplacement(trainingSet, trainingValue, seed) {
var engine = random.engines.mt19937();
var distribution = random.integer(0, trainingSet.rows - 1);
if (seed === undefined) {
engine = engine.autoSeed();
} else if (Number.isInteger(seed)) {
engine = engine.seed(seed);
} else {
throw new RangeError(`Expected seed must be undefined or integer not ${seed}`);
}
var Xr = new Array(trainingSet.rows);
var yr = new Array(trainingSet.rows);
for (var i = 0; i < trainingSet.rows; ++i) {
var index = distribution(engine);
Xr[i] = trainingSet[index];
yr[i] = trainingValue[index];
}
return {
X: new Matrix$1(Xr),
y: yr
};
} | javascript | function examplesBaggingWithReplacement(trainingSet, trainingValue, seed) {
var engine = random.engines.mt19937();
var distribution = random.integer(0, trainingSet.rows - 1);
if (seed === undefined) {
engine = engine.autoSeed();
} else if (Number.isInteger(seed)) {
engine = engine.seed(seed);
} else {
throw new RangeError(`Expected seed must be undefined or integer not ${seed}`);
}
var Xr = new Array(trainingSet.rows);
var yr = new Array(trainingSet.rows);
for (var i = 0; i < trainingSet.rows; ++i) {
var index = distribution(engine);
Xr[i] = trainingSet[index];
yr[i] = trainingValue[index];
}
return {
X: new Matrix$1(Xr),
y: yr
};
} | [
"function",
"examplesBaggingWithReplacement",
"(",
"trainingSet",
",",
"trainingValue",
",",
"seed",
")",
"{",
"var",
"engine",
"=",
"random",
".",
"engines",
".",
"mt19937",
"(",
")",
";",
"var",
"distribution",
"=",
"random",
".",
"integer",
"(",
"0",
",",
"trainingSet",
".",
"rows",
"-",
"1",
")",
";",
"if",
"(",
"seed",
"===",
"undefined",
")",
"{",
"engine",
"=",
"engine",
".",
"autoSeed",
"(",
")",
";",
"}",
"else",
"if",
"(",
"Number",
".",
"isInteger",
"(",
"seed",
")",
")",
"{",
"engine",
"=",
"engine",
".",
"seed",
"(",
"seed",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"RangeError",
"(",
"`",
"${",
"seed",
"}",
"`",
")",
";",
"}",
"var",
"Xr",
"=",
"new",
"Array",
"(",
"trainingSet",
".",
"rows",
")",
";",
"var",
"yr",
"=",
"new",
"Array",
"(",
"trainingSet",
".",
"rows",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"trainingSet",
".",
"rows",
";",
"++",
"i",
")",
"{",
"var",
"index",
"=",
"distribution",
"(",
"engine",
")",
";",
"Xr",
"[",
"i",
"]",
"=",
"trainingSet",
"[",
"index",
"]",
";",
"yr",
"[",
"i",
"]",
"=",
"trainingValue",
"[",
"index",
"]",
";",
"}",
"return",
"{",
"X",
":",
"new",
"Matrix$1",
"(",
"Xr",
")",
",",
"y",
":",
"yr",
"}",
";",
"}"
] | Select n with replacement elements on the training set and values, where n is the size of the training set.
@ignore
@param {Matrix} trainingSet
@param {Array} trainingValue
@param {number} seed - seed for the random selection, must be a 32-bit integer.
@return {object} with new X and y. | [
"Select",
"n",
"with",
"replacement",
"elements",
"on",
"the",
"training",
"set",
"and",
"values",
"where",
"n",
"is",
"the",
"size",
"of",
"the",
"training",
"set",
"."
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L36609-L36633 |
22,596 | repetere/modelscript | build/modelscript.umd.js | featureBagging | function featureBagging(trainingSet, n, replacement, seed) {
if (trainingSet.columns < n) {
throw new RangeError('N should be less or equal to the number of columns of X');
}
var distribution = random.integer(0, trainingSet.columns - 1);
var engine = random.engines.mt19937();
if (seed === undefined) {
engine = engine.autoSeed();
} else if (Number.isInteger(seed)) {
engine = engine.seed(seed);
} else {
throw new RangeError(`Expected seed must be undefined or integer not ${seed}`);
}
var toRet = new Matrix$1(trainingSet.rows, n);
if (replacement) {
var usedIndex = new Array(n);
for (var i = 0; i < n; ++i) {
var index = distribution(engine);
usedIndex[i] = index;
toRet.setColumn(i, trainingSet.getColumn(index));
}
} else {
usedIndex = new Set();
index = distribution(engine);
for (i = 0; i < n; ++i) {
while (usedIndex.has(index)) {
index = distribution(engine);
}
toRet.setColumn(i, trainingSet.getColumn(index));
usedIndex.add(index);
}
usedIndex = Array.from(usedIndex);
}
return {
X: toRet,
usedIndex: usedIndex
};
} | javascript | function featureBagging(trainingSet, n, replacement, seed) {
if (trainingSet.columns < n) {
throw new RangeError('N should be less or equal to the number of columns of X');
}
var distribution = random.integer(0, trainingSet.columns - 1);
var engine = random.engines.mt19937();
if (seed === undefined) {
engine = engine.autoSeed();
} else if (Number.isInteger(seed)) {
engine = engine.seed(seed);
} else {
throw new RangeError(`Expected seed must be undefined or integer not ${seed}`);
}
var toRet = new Matrix$1(trainingSet.rows, n);
if (replacement) {
var usedIndex = new Array(n);
for (var i = 0; i < n; ++i) {
var index = distribution(engine);
usedIndex[i] = index;
toRet.setColumn(i, trainingSet.getColumn(index));
}
} else {
usedIndex = new Set();
index = distribution(engine);
for (i = 0; i < n; ++i) {
while (usedIndex.has(index)) {
index = distribution(engine);
}
toRet.setColumn(i, trainingSet.getColumn(index));
usedIndex.add(index);
}
usedIndex = Array.from(usedIndex);
}
return {
X: toRet,
usedIndex: usedIndex
};
} | [
"function",
"featureBagging",
"(",
"trainingSet",
",",
"n",
",",
"replacement",
",",
"seed",
")",
"{",
"if",
"(",
"trainingSet",
".",
"columns",
"<",
"n",
")",
"{",
"throw",
"new",
"RangeError",
"(",
"'N should be less or equal to the number of columns of X'",
")",
";",
"}",
"var",
"distribution",
"=",
"random",
".",
"integer",
"(",
"0",
",",
"trainingSet",
".",
"columns",
"-",
"1",
")",
";",
"var",
"engine",
"=",
"random",
".",
"engines",
".",
"mt19937",
"(",
")",
";",
"if",
"(",
"seed",
"===",
"undefined",
")",
"{",
"engine",
"=",
"engine",
".",
"autoSeed",
"(",
")",
";",
"}",
"else",
"if",
"(",
"Number",
".",
"isInteger",
"(",
"seed",
")",
")",
"{",
"engine",
"=",
"engine",
".",
"seed",
"(",
"seed",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"RangeError",
"(",
"`",
"${",
"seed",
"}",
"`",
")",
";",
"}",
"var",
"toRet",
"=",
"new",
"Matrix$1",
"(",
"trainingSet",
".",
"rows",
",",
"n",
")",
";",
"if",
"(",
"replacement",
")",
"{",
"var",
"usedIndex",
"=",
"new",
"Array",
"(",
"n",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"var",
"index",
"=",
"distribution",
"(",
"engine",
")",
";",
"usedIndex",
"[",
"i",
"]",
"=",
"index",
";",
"toRet",
".",
"setColumn",
"(",
"i",
",",
"trainingSet",
".",
"getColumn",
"(",
"index",
")",
")",
";",
"}",
"}",
"else",
"{",
"usedIndex",
"=",
"new",
"Set",
"(",
")",
";",
"index",
"=",
"distribution",
"(",
"engine",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"while",
"(",
"usedIndex",
".",
"has",
"(",
"index",
")",
")",
"{",
"index",
"=",
"distribution",
"(",
"engine",
")",
";",
"}",
"toRet",
".",
"setColumn",
"(",
"i",
",",
"trainingSet",
".",
"getColumn",
"(",
"index",
")",
")",
";",
"usedIndex",
".",
"add",
"(",
"index",
")",
";",
"}",
"usedIndex",
"=",
"Array",
".",
"from",
"(",
"usedIndex",
")",
";",
"}",
"return",
"{",
"X",
":",
"toRet",
",",
"usedIndex",
":",
"usedIndex",
"}",
";",
"}"
] | selects n features from the training set with or without replacement, returns the new training set and the indexes used.
@ignore
@param {Matrix} trainingSet
@param {number} n - features.
@param {boolean} replacement
@param {number} seed - seed for the random selection, must be a 32-bit integer.
@return {object} | [
"selects",
"n",
"features",
"from",
"the",
"training",
"set",
"with",
"or",
"without",
"replacement",
"returns",
"the",
"new",
"training",
"set",
"and",
"the",
"indexes",
"used",
"."
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L36644-L36685 |
22,597 | repetere/modelscript | build/modelscript.umd.js | mode | function mode(arr) {
return arr.sort((a, b) =>
arr.filter((v) => v === a).length
- arr.filter((v) => v === b).length
).pop();
} | javascript | function mode(arr) {
return arr.sort((a, b) =>
arr.filter((v) => v === a).length
- arr.filter((v) => v === b).length
).pop();
} | [
"function",
"mode",
"(",
"arr",
")",
"{",
"return",
"arr",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"arr",
".",
"filter",
"(",
"(",
"v",
")",
"=>",
"v",
"===",
"a",
")",
".",
"length",
"-",
"arr",
".",
"filter",
"(",
"(",
"v",
")",
"=>",
"v",
"===",
"b",
")",
".",
"length",
")",
".",
"pop",
"(",
")",
";",
"}"
] | Return the most repeated element on the array.
@param {Array} arr
@return {number} mode | [
"Return",
"the",
"most",
"repeated",
"element",
"on",
"the",
"array",
"."
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L36909-L36914 |
22,598 | repetere/modelscript | build/modelscript.umd.js | median | function median(input) {
if (!Array.isArray(input)) {
throw new Error('input must be an array');
}
if (input.length === 0) {
throw new Error('input must not be empty');
}
return medianQuickselect_min(input.slice());
} | javascript | function median(input) {
if (!Array.isArray(input)) {
throw new Error('input must be an array');
}
if (input.length === 0) {
throw new Error('input must not be empty');
}
return medianQuickselect_min(input.slice());
} | [
"function",
"median",
"(",
"input",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"input",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'input must be an array'",
")",
";",
"}",
"if",
"(",
"input",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'input must not be empty'",
")",
";",
"}",
"return",
"medianQuickselect_min",
"(",
"input",
".",
"slice",
"(",
")",
")",
";",
"}"
] | Computes the median of the given values
@param {Array<number>} input
@return {number} | [
"Computes",
"the",
"median",
"of",
"the",
"given",
"values"
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L36925-L36935 |
22,599 | repetere/modelscript | build/modelscript.umd.js | nearestVector | function nearestVector(listVectors, vector, options) {
options = options || defaultOptions$7;
const distanceFunction = options.distanceFunction || defaultOptions$7.distanceFunction;
const similarityFunction = options.similarityFunction || defaultOptions$7.similarityFunction;
const returnVector = options.returnVector || defaultOptions$7.returnVector;
var vectorIndex = -1;
if (typeof similarityFunction === 'function') {
// maximum similarity
var maxSim = Number.MIN_VALUE;
for (var j = 0; j < listVectors.length; j++) {
var sim = similarityFunction(vector, listVectors[j]);
if (sim > maxSim) {
maxSim = sim;
vectorIndex = j;
}
}
} else if (typeof distanceFunction === 'function') {
// minimum distance
var minDist = Number.MAX_VALUE;
for (var i = 0; i < listVectors.length; i++) {
var dist = distanceFunction(vector, listVectors[i]);
if (dist < minDist) {
minDist = dist;
vectorIndex = i;
}
}
} else {
throw new Error('A similarity or distance function it\'s required');
}
if (returnVector) {
return listVectors[vectorIndex];
} else {
return vectorIndex;
}
} | javascript | function nearestVector(listVectors, vector, options) {
options = options || defaultOptions$7;
const distanceFunction = options.distanceFunction || defaultOptions$7.distanceFunction;
const similarityFunction = options.similarityFunction || defaultOptions$7.similarityFunction;
const returnVector = options.returnVector || defaultOptions$7.returnVector;
var vectorIndex = -1;
if (typeof similarityFunction === 'function') {
// maximum similarity
var maxSim = Number.MIN_VALUE;
for (var j = 0; j < listVectors.length; j++) {
var sim = similarityFunction(vector, listVectors[j]);
if (sim > maxSim) {
maxSim = sim;
vectorIndex = j;
}
}
} else if (typeof distanceFunction === 'function') {
// minimum distance
var minDist = Number.MAX_VALUE;
for (var i = 0; i < listVectors.length; i++) {
var dist = distanceFunction(vector, listVectors[i]);
if (dist < minDist) {
minDist = dist;
vectorIndex = i;
}
}
} else {
throw new Error('A similarity or distance function it\'s required');
}
if (returnVector) {
return listVectors[vectorIndex];
} else {
return vectorIndex;
}
} | [
"function",
"nearestVector",
"(",
"listVectors",
",",
"vector",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"defaultOptions$7",
";",
"const",
"distanceFunction",
"=",
"options",
".",
"distanceFunction",
"||",
"defaultOptions$7",
".",
"distanceFunction",
";",
"const",
"similarityFunction",
"=",
"options",
".",
"similarityFunction",
"||",
"defaultOptions$7",
".",
"similarityFunction",
";",
"const",
"returnVector",
"=",
"options",
".",
"returnVector",
"||",
"defaultOptions$7",
".",
"returnVector",
";",
"var",
"vectorIndex",
"=",
"-",
"1",
";",
"if",
"(",
"typeof",
"similarityFunction",
"===",
"'function'",
")",
"{",
"// maximum similarity",
"var",
"maxSim",
"=",
"Number",
".",
"MIN_VALUE",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"listVectors",
".",
"length",
";",
"j",
"++",
")",
"{",
"var",
"sim",
"=",
"similarityFunction",
"(",
"vector",
",",
"listVectors",
"[",
"j",
"]",
")",
";",
"if",
"(",
"sim",
">",
"maxSim",
")",
"{",
"maxSim",
"=",
"sim",
";",
"vectorIndex",
"=",
"j",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"typeof",
"distanceFunction",
"===",
"'function'",
")",
"{",
"// minimum distance",
"var",
"minDist",
"=",
"Number",
".",
"MAX_VALUE",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"listVectors",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"dist",
"=",
"distanceFunction",
"(",
"vector",
",",
"listVectors",
"[",
"i",
"]",
")",
";",
"if",
"(",
"dist",
"<",
"minDist",
")",
"{",
"minDist",
"=",
"dist",
";",
"vectorIndex",
"=",
"i",
";",
"}",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'A similarity or distance function it\\'s required'",
")",
";",
"}",
"if",
"(",
"returnVector",
")",
"{",
"return",
"listVectors",
"[",
"vectorIndex",
"]",
";",
"}",
"else",
"{",
"return",
"vectorIndex",
";",
"}",
"}"
] | Find the nearest vector in a list to a sample vector
@param {Array<Array<number>>} listVectors - List of vectors with same dimensions
@param {Array<number>} vector - Reference vector to "classify"
@param {object} [options] - Options object
@param {function} [options.distanceFunction = squaredDistance] - Function that receives two vectors and return their distance value as number
@param {function} [options.similarityFunction = undefined] - Function that receives two vectors and return their similarity value as number
@param {boolean} [options.returnVector = false] - Return the nearest vector instead of its index
@return {number|Array<number>} - The index or the content of the nearest vector | [
"Find",
"the",
"nearest",
"vector",
"in",
"a",
"list",
"to",
"a",
"sample",
"vector"
] | b507fad9b3ecfb4a9ec4d44d41052a8082dac763 | https://github.com/repetere/modelscript/blob/b507fad9b3ecfb4a9ec4d44d41052a8082dac763/build/modelscript.umd.js#L43753-L43791 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.