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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
19,200
|
bitovi/documentjs
|
lib/generators/html/build/make_default_helpers.js
|
function(name, title, attrs){
if (!name) return (title || "");
name = name.replace('::', '.prototype.');
if (docMap[name]) {
var attrsArr = [];
for(var prop in attrs){
attrsArr.push(prop+"=\""+attrs[prop]+"\"")
}
return '<a href="' + docsFilename(name, config) + '" '+attrsArr.join(" ")+'>' + (title || name ) + '</a>';
} else {
return title || name || "";
}
}
|
javascript
|
function(name, title, attrs){
if (!name) return (title || "");
name = name.replace('::', '.prototype.');
if (docMap[name]) {
var attrsArr = [];
for(var prop in attrs){
attrsArr.push(prop+"=\""+attrs[prop]+"\"")
}
return '<a href="' + docsFilename(name, config) + '" '+attrsArr.join(" ")+'>' + (title || name ) + '</a>';
} else {
return title || name || "";
}
}
|
[
"function",
"(",
"name",
",",
"title",
",",
"attrs",
")",
"{",
"if",
"(",
"!",
"name",
")",
"return",
"(",
"title",
"||",
"\"\"",
")",
";",
"name",
"=",
"name",
".",
"replace",
"(",
"'::'",
",",
"'.prototype.'",
")",
";",
"if",
"(",
"docMap",
"[",
"name",
"]",
")",
"{",
"var",
"attrsArr",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"prop",
"in",
"attrs",
")",
"{",
"attrsArr",
".",
"push",
"(",
"prop",
"+",
"\"=\\\"\"",
"+",
"attrs",
"[",
"prop",
"]",
"+",
"\"\\\"\"",
")",
"}",
"return",
"'<a href=\"'",
"+",
"docsFilename",
"(",
"name",
",",
"config",
")",
"+",
"'\" '",
"+",
"attrsArr",
".",
"join",
"(",
"\" \"",
")",
"+",
"'>'",
"+",
"(",
"title",
"||",
"name",
")",
"+",
"'</a>'",
";",
"}",
"else",
"{",
"return",
"title",
"||",
"name",
"||",
"\"\"",
";",
"}",
"}"
] |
helper that creates a link to a docObject
|
[
"helper",
"that",
"creates",
"a",
"link",
"to",
"a",
"docObject"
] |
5f6af5b213b840a0bfca1e146f1678db853f3b60
|
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/generators/html/build/make_default_helpers.js#L392-L404
|
|
19,201
|
bitovi/documentjs
|
lib/generators/html/build/make_default_helpers.js
|
function(types, options){
if(!Array.isArray(types)) {
return options.inverse(this);
}
var typesWithDescriptions = [];
types.forEach(function( type ){
if(type.description){
typesWithDescriptions.push(type)
}
});
if( !typesWithDescriptions.length ) {
// check the 1st one's options
if(types.length == 1 && types[0].options ) {
types[0].options.forEach(function(option){
typesWithDescriptions.push(option);
});
}
}
if(typesWithDescriptions.length){
return options.fn({types: typesWithDescriptions});
} else {
return options.inverse(this);
}
}
|
javascript
|
function(types, options){
if(!Array.isArray(types)) {
return options.inverse(this);
}
var typesWithDescriptions = [];
types.forEach(function( type ){
if(type.description){
typesWithDescriptions.push(type)
}
});
if( !typesWithDescriptions.length ) {
// check the 1st one's options
if(types.length == 1 && types[0].options ) {
types[0].options.forEach(function(option){
typesWithDescriptions.push(option);
});
}
}
if(typesWithDescriptions.length){
return options.fn({types: typesWithDescriptions});
} else {
return options.inverse(this);
}
}
|
[
"function",
"(",
"types",
",",
"options",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"types",
")",
")",
"{",
"return",
"options",
".",
"inverse",
"(",
"this",
")",
";",
"}",
"var",
"typesWithDescriptions",
"=",
"[",
"]",
";",
"types",
".",
"forEach",
"(",
"function",
"(",
"type",
")",
"{",
"if",
"(",
"type",
".",
"description",
")",
"{",
"typesWithDescriptions",
".",
"push",
"(",
"type",
")",
"}",
"}",
")",
";",
"if",
"(",
"!",
"typesWithDescriptions",
".",
"length",
")",
"{",
"// check the 1st one's options",
"if",
"(",
"types",
".",
"length",
"==",
"1",
"&&",
"types",
"[",
"0",
"]",
".",
"options",
")",
"{",
"types",
"[",
"0",
"]",
".",
"options",
".",
"forEach",
"(",
"function",
"(",
"option",
")",
"{",
"typesWithDescriptions",
".",
"push",
"(",
"option",
")",
";",
"}",
")",
";",
"}",
"}",
"if",
"(",
"typesWithDescriptions",
".",
"length",
")",
"{",
"return",
"options",
".",
"fn",
"(",
"{",
"types",
":",
"typesWithDescriptions",
"}",
")",
";",
"}",
"else",
"{",
"return",
"options",
".",
"inverse",
"(",
"this",
")",
";",
"}",
"}"
] |
Getting and transforming data and making it available to the template
@function documentjs.generators.html.defaultHelpers.getTypesWithDescriptions
|
[
"Getting",
"and",
"transforming",
"data",
"and",
"making",
"it",
"available",
"to",
"the",
"template"
] |
5f6af5b213b840a0bfca1e146f1678db853f3b60
|
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/generators/html/build/make_default_helpers.js#L502-L528
|
|
19,202
|
AndersDJohnson/magnificent.js
|
src/js/mag-control.js
|
function (element, options) {
this.element = $(element)
this.options = $.extend(true, {}, this.options, options)
this._init()
}
|
javascript
|
function (element, options) {
this.element = $(element)
this.options = $.extend(true, {}, this.options, options)
this._init()
}
|
[
"function",
"(",
"element",
",",
"options",
")",
"{",
"this",
".",
"element",
"=",
"$",
"(",
"element",
")",
"this",
".",
"options",
"=",
"$",
".",
"extend",
"(",
"true",
",",
"{",
"}",
",",
"this",
".",
"options",
",",
"options",
")",
"this",
".",
"_init",
"(",
")",
"}"
] |
eslint-disable-line semi
|
[
"eslint",
"-",
"disable",
"-",
"line",
"semi"
] |
c2277fe0e154588b35ef2fdadb4e0af01fe68d15
|
https://github.com/AndersDJohnson/magnificent.js/blob/c2277fe0e154588b35ef2fdadb4e0af01fe68d15/src/js/mag-control.js#L17-L21
|
|
19,203
|
mapbox/mock-aws-sdk-js
|
index.js
|
stubMethod
|
function stubMethod(service, method, replacement) {
if (!isStubbed(service)) stubService(service);
if (!replacement) return sinon.stub(getService(service).prototype, method);
return sinon.stub(getService(service).prototype, method).callsFake(function(params, callback) {
var _this = { request: stubRequest(), response: stubResponse() };
replacement.call(_this, params, callback);
return _this.request;
});
}
|
javascript
|
function stubMethod(service, method, replacement) {
if (!isStubbed(service)) stubService(service);
if (!replacement) return sinon.stub(getService(service).prototype, method);
return sinon.stub(getService(service).prototype, method).callsFake(function(params, callback) {
var _this = { request: stubRequest(), response: stubResponse() };
replacement.call(_this, params, callback);
return _this.request;
});
}
|
[
"function",
"stubMethod",
"(",
"service",
",",
"method",
",",
"replacement",
")",
"{",
"if",
"(",
"!",
"isStubbed",
"(",
"service",
")",
")",
"stubService",
"(",
"service",
")",
";",
"if",
"(",
"!",
"replacement",
")",
"return",
"sinon",
".",
"stub",
"(",
"getService",
"(",
"service",
")",
".",
"prototype",
",",
"method",
")",
";",
"return",
"sinon",
".",
"stub",
"(",
"getService",
"(",
"service",
")",
".",
"prototype",
",",
"method",
")",
".",
"callsFake",
"(",
"function",
"(",
"params",
",",
"callback",
")",
"{",
"var",
"_this",
"=",
"{",
"request",
":",
"stubRequest",
"(",
")",
",",
"response",
":",
"stubResponse",
"(",
")",
"}",
";",
"replacement",
".",
"call",
"(",
"_this",
",",
"params",
",",
"callback",
")",
";",
"return",
"_this",
".",
"request",
";",
"}",
")",
";",
"}"
] |
Replaces a single AWS service method with a stub.
@param {string} service - the name of the AWS service. Can include `.` for
nested services, e.g. `'DynamoDB.DocumentClient'`.
@param {string} method - the name of the service method to stub.
@param {function} [replacement] - if specified, this function will be called
when the service method stub is invoked. `this` in the context of the function
will provide a reference to stubbed AWS.Request and AWS.Response objects to
simulate more advanced aws-sdk-js usage patterns.
@returns {object} stub - [a sinon stub](http://sinonjs.org/docs/#stubs).
|
[
"Replaces",
"a",
"single",
"AWS",
"service",
"method",
"with",
"a",
"stub",
"."
] |
a0e80985cd842b3ade1e68e7136ebaf6aa1f3475
|
https://github.com/mapbox/mock-aws-sdk-js/blob/a0e80985cd842b3ade1e68e7136ebaf6aa1f3475/index.js#L21-L30
|
19,204
|
gulpjs/gulp-util
|
lib/PluginError.js
|
function(plugin, message, opt) {
opt = opt || {};
if (typeof plugin === 'object') {
opt = plugin;
} else {
if (message instanceof Error) {
opt.error = message;
} else if (typeof message === 'object') {
opt = message;
} else {
opt.message = message;
}
opt.plugin = plugin;
}
return objectAssign({
showStack: false,
showProperties: true
}, opt);
}
|
javascript
|
function(plugin, message, opt) {
opt = opt || {};
if (typeof plugin === 'object') {
opt = plugin;
} else {
if (message instanceof Error) {
opt.error = message;
} else if (typeof message === 'object') {
opt = message;
} else {
opt.message = message;
}
opt.plugin = plugin;
}
return objectAssign({
showStack: false,
showProperties: true
}, opt);
}
|
[
"function",
"(",
"plugin",
",",
"message",
",",
"opt",
")",
"{",
"opt",
"=",
"opt",
"||",
"{",
"}",
";",
"if",
"(",
"typeof",
"plugin",
"===",
"'object'",
")",
"{",
"opt",
"=",
"plugin",
";",
"}",
"else",
"{",
"if",
"(",
"message",
"instanceof",
"Error",
")",
"{",
"opt",
".",
"error",
"=",
"message",
";",
"}",
"else",
"if",
"(",
"typeof",
"message",
"===",
"'object'",
")",
"{",
"opt",
"=",
"message",
";",
"}",
"else",
"{",
"opt",
".",
"message",
"=",
"message",
";",
"}",
"opt",
".",
"plugin",
"=",
"plugin",
";",
"}",
"return",
"objectAssign",
"(",
"{",
"showStack",
":",
"false",
",",
"showProperties",
":",
"true",
"}",
",",
"opt",
")",
";",
"}"
] |
wow what a clusterfuck
|
[
"wow",
"what",
"a",
"clusterfuck"
] |
2035ebdbc29f700189356a1da717703411d87b7a
|
https://github.com/gulpjs/gulp-util/blob/2035ebdbc29f700189356a1da717703411d87b7a/lib/PluginError.js#L11-L30
|
|
19,205
|
benjamn/private
|
private.js
|
makeSafeToCall
|
function makeSafeToCall(fun) {
if (fun) {
defProp(fun, "call", fun.call);
defProp(fun, "apply", fun.apply);
}
return fun;
}
|
javascript
|
function makeSafeToCall(fun) {
if (fun) {
defProp(fun, "call", fun.call);
defProp(fun, "apply", fun.apply);
}
return fun;
}
|
[
"function",
"makeSafeToCall",
"(",
"fun",
")",
"{",
"if",
"(",
"fun",
")",
"{",
"defProp",
"(",
"fun",
",",
"\"call\"",
",",
"fun",
".",
"call",
")",
";",
"defProp",
"(",
"fun",
",",
"\"apply\"",
",",
"fun",
".",
"apply",
")",
";",
"}",
"return",
"fun",
";",
"}"
] |
For functions that will be invoked using .call or .apply, we need to define those methods on the function objects themselves, rather than inheriting them from Function.prototype, so that a malicious or clumsy third party cannot interfere with the functionality of this module by redefining Function.prototype.call or .apply.
|
[
"For",
"functions",
"that",
"will",
"be",
"invoked",
"using",
".",
"call",
"or",
".",
"apply",
"we",
"need",
"to",
"define",
"those",
"methods",
"on",
"the",
"function",
"objects",
"themselves",
"rather",
"than",
"inheriting",
"them",
"from",
"Function",
".",
"prototype",
"so",
"that",
"a",
"malicious",
"or",
"clumsy",
"third",
"party",
"cannot",
"interfere",
"with",
"the",
"functionality",
"of",
"this",
"module",
"by",
"redefining",
"Function",
".",
"prototype",
".",
"call",
"or",
".",
"apply",
"."
] |
288cadd93e61b330d4afa10b61e4cb7868709de9
|
https://github.com/benjamn/private/blob/288cadd93e61b330d4afa10b61e4cb7868709de9/private.js#L22-L28
|
19,206
|
benjamn/private
|
private.js
|
vault
|
function vault(key, forget) {
// Only code that has access to the passkey can retrieve (or forget)
// the secret object.
if (key === passkey) {
return forget
? secret = null
: secret || (secret = secretCreatorFn(object));
}
}
|
javascript
|
function vault(key, forget) {
// Only code that has access to the passkey can retrieve (or forget)
// the secret object.
if (key === passkey) {
return forget
? secret = null
: secret || (secret = secretCreatorFn(object));
}
}
|
[
"function",
"vault",
"(",
"key",
",",
"forget",
")",
"{",
"// Only code that has access to the passkey can retrieve (or forget)",
"// the secret object.",
"if",
"(",
"key",
"===",
"passkey",
")",
"{",
"return",
"forget",
"?",
"secret",
"=",
"null",
":",
"secret",
"||",
"(",
"secret",
"=",
"secretCreatorFn",
"(",
"object",
")",
")",
";",
"}",
"}"
] |
Created lazily.
|
[
"Created",
"lazily",
"."
] |
288cadd93e61b330d4afa10b61e4cb7868709de9
|
https://github.com/benjamn/private/blob/288cadd93e61b330d4afa10b61e4cb7868709de9/private.js#L102-L110
|
19,207
|
s-yadav/jsonQ
|
jsonQ.js
|
newFormat
|
function newFormat(option) {
//parameter change
var keyAdded = option.keyAdded || [],
json = option.json,
path = option.path,
newJson = option.newJson;
//add to new json
jsonQ.each(json, function(k, val) {
var lvlpath = path ? JSON.parse(JSON.stringify(path)) : [];
lvlpath.push(k);
//to add a new direct access for each key in json so we get the path of that key easily
if (objType(json) == 'object') {
if (keyAdded.indexOf(k) == -1) {
keyAdded.push(k);
newJson.jsonQ_path[k] = [];
}
newJson.jsonQ_path[k].push({
path: lvlpath
});
}
//if value is json or array go to further level
var type = objType(val);
if (type == 'object' || type == 'array') {
newFormat({
'json': val,
'newJson': newJson,
'path': lvlpath,
'keyAdded': keyAdded
});
}
});
return newJson;
}
|
javascript
|
function newFormat(option) {
//parameter change
var keyAdded = option.keyAdded || [],
json = option.json,
path = option.path,
newJson = option.newJson;
//add to new json
jsonQ.each(json, function(k, val) {
var lvlpath = path ? JSON.parse(JSON.stringify(path)) : [];
lvlpath.push(k);
//to add a new direct access for each key in json so we get the path of that key easily
if (objType(json) == 'object') {
if (keyAdded.indexOf(k) == -1) {
keyAdded.push(k);
newJson.jsonQ_path[k] = [];
}
newJson.jsonQ_path[k].push({
path: lvlpath
});
}
//if value is json or array go to further level
var type = objType(val);
if (type == 'object' || type == 'array') {
newFormat({
'json': val,
'newJson': newJson,
'path': lvlpath,
'keyAdded': keyAdded
});
}
});
return newJson;
}
|
[
"function",
"newFormat",
"(",
"option",
")",
"{",
"//parameter change",
"var",
"keyAdded",
"=",
"option",
".",
"keyAdded",
"||",
"[",
"]",
",",
"json",
"=",
"option",
".",
"json",
",",
"path",
"=",
"option",
".",
"path",
",",
"newJson",
"=",
"option",
".",
"newJson",
";",
"//add to new json",
"jsonQ",
".",
"each",
"(",
"json",
",",
"function",
"(",
"k",
",",
"val",
")",
"{",
"var",
"lvlpath",
"=",
"path",
"?",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"path",
")",
")",
":",
"[",
"]",
";",
"lvlpath",
".",
"push",
"(",
"k",
")",
";",
"//to add a new direct access for each key in json so we get the path of that key easily",
"if",
"(",
"objType",
"(",
"json",
")",
"==",
"'object'",
")",
"{",
"if",
"(",
"keyAdded",
".",
"indexOf",
"(",
"k",
")",
"==",
"-",
"1",
")",
"{",
"keyAdded",
".",
"push",
"(",
"k",
")",
";",
"newJson",
".",
"jsonQ_path",
"[",
"k",
"]",
"=",
"[",
"]",
";",
"}",
"newJson",
".",
"jsonQ_path",
"[",
"k",
"]",
".",
"push",
"(",
"{",
"path",
":",
"lvlpath",
"}",
")",
";",
"}",
"//if value is json or array go to further level",
"var",
"type",
"=",
"objType",
"(",
"val",
")",
";",
"if",
"(",
"type",
"==",
"'object'",
"||",
"type",
"==",
"'array'",
")",
"{",
"newFormat",
"(",
"{",
"'json'",
":",
"val",
",",
"'newJson'",
":",
"newJson",
",",
"'path'",
":",
"lvlpath",
",",
"'keyAdded'",
":",
"keyAdded",
"}",
")",
";",
"}",
"}",
")",
";",
"return",
"newJson",
";",
"}"
] |
function to create new format
|
[
"function",
"to",
"create",
"new",
"format"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L56-L94
|
19,208
|
s-yadav/jsonQ
|
jsonQ.js
|
function(option) {
var current = this.jsonQ_current,
newObj = this.cloneObj(jsonQ()),
newCurrent = newObj.jsonQ_current = [],
prevPathStr = '',
key = option.key,
method = option.method;
for (var i = 0, ln = current.length; i < ln; i++) {
var pathC = current[i].path,
pathStr,
outofBound = false,
parPath = pathC.concat([]);
//to run callback to apply top traverse logic
if (method == 'parent') {
if (parPath.length === 0) {
outofBound = true;
} else {
parPath.pop();
}
} else {
var keyIndex = parPath.lastIndexOf(key);
if (keyIndex == -1) {
outofBound = true;
} else {
parPath = parPath.slice(0, keyIndex + 1);
}
}
pathStr = JSON.stringify(parPath);
if (prevPathStr != pathStr && !outofBound) {
newCurrent.push({
path: parPath
});
}
prevPathStr = pathStr;
}
//set other definition variables
newObj.length = newCurrent.length;
//to add selector
newObj.selector.push({
method: method,
key: key
});
return newObj;
}
|
javascript
|
function(option) {
var current = this.jsonQ_current,
newObj = this.cloneObj(jsonQ()),
newCurrent = newObj.jsonQ_current = [],
prevPathStr = '',
key = option.key,
method = option.method;
for (var i = 0, ln = current.length; i < ln; i++) {
var pathC = current[i].path,
pathStr,
outofBound = false,
parPath = pathC.concat([]);
//to run callback to apply top traverse logic
if (method == 'parent') {
if (parPath.length === 0) {
outofBound = true;
} else {
parPath.pop();
}
} else {
var keyIndex = parPath.lastIndexOf(key);
if (keyIndex == -1) {
outofBound = true;
} else {
parPath = parPath.slice(0, keyIndex + 1);
}
}
pathStr = JSON.stringify(parPath);
if (prevPathStr != pathStr && !outofBound) {
newCurrent.push({
path: parPath
});
}
prevPathStr = pathStr;
}
//set other definition variables
newObj.length = newCurrent.length;
//to add selector
newObj.selector.push({
method: method,
key: key
});
return newObj;
}
|
[
"function",
"(",
"option",
")",
"{",
"var",
"current",
"=",
"this",
".",
"jsonQ_current",
",",
"newObj",
"=",
"this",
".",
"cloneObj",
"(",
"jsonQ",
"(",
")",
")",
",",
"newCurrent",
"=",
"newObj",
".",
"jsonQ_current",
"=",
"[",
"]",
",",
"prevPathStr",
"=",
"''",
",",
"key",
"=",
"option",
".",
"key",
",",
"method",
"=",
"option",
".",
"method",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"ln",
"=",
"current",
".",
"length",
";",
"i",
"<",
"ln",
";",
"i",
"++",
")",
"{",
"var",
"pathC",
"=",
"current",
"[",
"i",
"]",
".",
"path",
",",
"pathStr",
",",
"outofBound",
"=",
"false",
",",
"parPath",
"=",
"pathC",
".",
"concat",
"(",
"[",
"]",
")",
";",
"//to run callback to apply top traverse logic",
"if",
"(",
"method",
"==",
"'parent'",
")",
"{",
"if",
"(",
"parPath",
".",
"length",
"===",
"0",
")",
"{",
"outofBound",
"=",
"true",
";",
"}",
"else",
"{",
"parPath",
".",
"pop",
"(",
")",
";",
"}",
"}",
"else",
"{",
"var",
"keyIndex",
"=",
"parPath",
".",
"lastIndexOf",
"(",
"key",
")",
";",
"if",
"(",
"keyIndex",
"==",
"-",
"1",
")",
"{",
"outofBound",
"=",
"true",
";",
"}",
"else",
"{",
"parPath",
"=",
"parPath",
".",
"slice",
"(",
"0",
",",
"keyIndex",
"+",
"1",
")",
";",
"}",
"}",
"pathStr",
"=",
"JSON",
".",
"stringify",
"(",
"parPath",
")",
";",
"if",
"(",
"prevPathStr",
"!=",
"pathStr",
"&&",
"!",
"outofBound",
")",
"{",
"newCurrent",
".",
"push",
"(",
"{",
"path",
":",
"parPath",
"}",
")",
";",
"}",
"prevPathStr",
"=",
"pathStr",
";",
"}",
"//set other definition variables",
"newObj",
".",
"length",
"=",
"newCurrent",
".",
"length",
";",
"//to add selector",
"newObj",
".",
"selector",
".",
"push",
"(",
"{",
"method",
":",
"method",
",",
"key",
":",
"key",
"}",
")",
";",
"return",
"newObj",
";",
"}"
] |
search on top level
|
[
"search",
"on",
"top",
"level"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L99-L149
|
|
19,209
|
s-yadav/jsonQ
|
jsonQ.js
|
function(option) {
var current = this.jsonQ_current,
newObj = this.cloneObj(jsonQ()),
newCurrent = newObj.jsonQ_current = [],
pathObj = this.jsonQ_path,
//key element (an array of paths with following key)
key = option.key,
//dont work with original object clone it and if undefined than make as empty array
elm = jsonQ.clone(pathObj[key]) || [],
//qualifier
qualifier = option.qualifier,
qType = objType(qualifier),
//travese method
method = option.method,
find = method == "find" ? true : false;
for (var i = 0, ln = current.length; i < ln; i++) {
var pathC = current[i].path,
pathCTemp = [],
found = false;
if (!find) {
//if it is top level continue the loop. This case comes when we do sibling method called on initial object
if (pathC.length === 0) {
continue;
}
pathCTemp = pathC.concat([]);
pathCTemp.pop();
}
//make a loop on element to match the current path and element path
for (var j = 0; j < elm.length; j++) {
var pathE = elm[j].path,
condition;
if (find) {
condition = matchPath(pathC, pathE);
} else {
var pathETemp = pathE.concat([]);
//to pop last element
pathETemp.pop();
condition = pathCTemp.join() == pathETemp.join();
}
if (condition) {
//code to check qualifier need to be written this on is only when quantifier when it is function in other case it will be applied on last
var qTest = tFunc.qTest.call(this, qType, qualifier, pathE, newCurrent);
if (qTest) {
//to remove element which is already added
elm.splice(j, 1);
j--;
}
//make found flag true
found = true;
}
//break if path doesent match in next sequence and for one element is already there.
else if (found) {
break;
}
}
}
//to apply qualifier if it is string . its mainly for array kind of qualifier
if (qType == "string") {
newObj = this.filter.call(newObj, qualifier);
}
//set other defination variables
newObj.length = newObj.jsonQ_current.length;
//to add selector
newObj.selector.push({
method: method,
key: key,
qualifier: qualifier
});
return newObj;
}
|
javascript
|
function(option) {
var current = this.jsonQ_current,
newObj = this.cloneObj(jsonQ()),
newCurrent = newObj.jsonQ_current = [],
pathObj = this.jsonQ_path,
//key element (an array of paths with following key)
key = option.key,
//dont work with original object clone it and if undefined than make as empty array
elm = jsonQ.clone(pathObj[key]) || [],
//qualifier
qualifier = option.qualifier,
qType = objType(qualifier),
//travese method
method = option.method,
find = method == "find" ? true : false;
for (var i = 0, ln = current.length; i < ln; i++) {
var pathC = current[i].path,
pathCTemp = [],
found = false;
if (!find) {
//if it is top level continue the loop. This case comes when we do sibling method called on initial object
if (pathC.length === 0) {
continue;
}
pathCTemp = pathC.concat([]);
pathCTemp.pop();
}
//make a loop on element to match the current path and element path
for (var j = 0; j < elm.length; j++) {
var pathE = elm[j].path,
condition;
if (find) {
condition = matchPath(pathC, pathE);
} else {
var pathETemp = pathE.concat([]);
//to pop last element
pathETemp.pop();
condition = pathCTemp.join() == pathETemp.join();
}
if (condition) {
//code to check qualifier need to be written this on is only when quantifier when it is function in other case it will be applied on last
var qTest = tFunc.qTest.call(this, qType, qualifier, pathE, newCurrent);
if (qTest) {
//to remove element which is already added
elm.splice(j, 1);
j--;
}
//make found flag true
found = true;
}
//break if path doesent match in next sequence and for one element is already there.
else if (found) {
break;
}
}
}
//to apply qualifier if it is string . its mainly for array kind of qualifier
if (qType == "string") {
newObj = this.filter.call(newObj, qualifier);
}
//set other defination variables
newObj.length = newObj.jsonQ_current.length;
//to add selector
newObj.selector.push({
method: method,
key: key,
qualifier: qualifier
});
return newObj;
}
|
[
"function",
"(",
"option",
")",
"{",
"var",
"current",
"=",
"this",
".",
"jsonQ_current",
",",
"newObj",
"=",
"this",
".",
"cloneObj",
"(",
"jsonQ",
"(",
")",
")",
",",
"newCurrent",
"=",
"newObj",
".",
"jsonQ_current",
"=",
"[",
"]",
",",
"pathObj",
"=",
"this",
".",
"jsonQ_path",
",",
"//key element (an array of paths with following key)",
"key",
"=",
"option",
".",
"key",
",",
"//dont work with original object clone it and if undefined than make as empty array",
"elm",
"=",
"jsonQ",
".",
"clone",
"(",
"pathObj",
"[",
"key",
"]",
")",
"||",
"[",
"]",
",",
"//qualifier",
"qualifier",
"=",
"option",
".",
"qualifier",
",",
"qType",
"=",
"objType",
"(",
"qualifier",
")",
",",
"//travese method",
"method",
"=",
"option",
".",
"method",
",",
"find",
"=",
"method",
"==",
"\"find\"",
"?",
"true",
":",
"false",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"ln",
"=",
"current",
".",
"length",
";",
"i",
"<",
"ln",
";",
"i",
"++",
")",
"{",
"var",
"pathC",
"=",
"current",
"[",
"i",
"]",
".",
"path",
",",
"pathCTemp",
"=",
"[",
"]",
",",
"found",
"=",
"false",
";",
"if",
"(",
"!",
"find",
")",
"{",
"//if it is top level continue the loop. This case comes when we do sibling method called on initial object",
"if",
"(",
"pathC",
".",
"length",
"===",
"0",
")",
"{",
"continue",
";",
"}",
"pathCTemp",
"=",
"pathC",
".",
"concat",
"(",
"[",
"]",
")",
";",
"pathCTemp",
".",
"pop",
"(",
")",
";",
"}",
"//make a loop on element to match the current path and element path",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"elm",
".",
"length",
";",
"j",
"++",
")",
"{",
"var",
"pathE",
"=",
"elm",
"[",
"j",
"]",
".",
"path",
",",
"condition",
";",
"if",
"(",
"find",
")",
"{",
"condition",
"=",
"matchPath",
"(",
"pathC",
",",
"pathE",
")",
";",
"}",
"else",
"{",
"var",
"pathETemp",
"=",
"pathE",
".",
"concat",
"(",
"[",
"]",
")",
";",
"//to pop last element",
"pathETemp",
".",
"pop",
"(",
")",
";",
"condition",
"=",
"pathCTemp",
".",
"join",
"(",
")",
"==",
"pathETemp",
".",
"join",
"(",
")",
";",
"}",
"if",
"(",
"condition",
")",
"{",
"//code to check qualifier need to be written this on is only when quantifier when it is function in other case it will be applied on last",
"var",
"qTest",
"=",
"tFunc",
".",
"qTest",
".",
"call",
"(",
"this",
",",
"qType",
",",
"qualifier",
",",
"pathE",
",",
"newCurrent",
")",
";",
"if",
"(",
"qTest",
")",
"{",
"//to remove element which is already added",
"elm",
".",
"splice",
"(",
"j",
",",
"1",
")",
";",
"j",
"--",
";",
"}",
"//make found flag true",
"found",
"=",
"true",
";",
"}",
"//break if path doesent match in next sequence and for one element is already there.",
"else",
"if",
"(",
"found",
")",
"{",
"break",
";",
"}",
"}",
"}",
"//to apply qualifier if it is string . its mainly for array kind of qualifier",
"if",
"(",
"qType",
"==",
"\"string\"",
")",
"{",
"newObj",
"=",
"this",
".",
"filter",
".",
"call",
"(",
"newObj",
",",
"qualifier",
")",
";",
"}",
"//set other defination variables",
"newObj",
".",
"length",
"=",
"newObj",
".",
"jsonQ_current",
".",
"length",
";",
"//to add selector",
"newObj",
".",
"selector",
".",
"push",
"(",
"{",
"method",
":",
"method",
",",
"key",
":",
"key",
",",
"qualifier",
":",
"qualifier",
"}",
")",
";",
"return",
"newObj",
";",
"}"
] |
traverse which have qualifiers mainly on bottom and sibling method
|
[
"traverse",
"which",
"have",
"qualifiers",
"mainly",
"on",
"bottom",
"and",
"sibling",
"method"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L151-L235
|
|
19,210
|
s-yadav/jsonQ
|
jsonQ.js
|
function(index, valObj, clone) {
var current = this.jsonQ_current;
//return if incorrect index is given
if (isNaN(index) && index != "first" && index != "last") {
error(index + 'is not a valid index.');
return this;
}
for (var i = 0, ln = current.length; i < ln; i++) {
var pathC = current[i].path.concat([]),
lastKey = pathC.pop(),
parRef = this.pathValue(pathC),
type = objType(parRef[lastKey]),
objLn = parRef[lastKey].length;
//to limit index
var idx = index < 0 || index == "first" ? 0 : index > objLn || index == "last" ? objLn : index;
//if array push
if (type == 'array') {
valObj = clone ? jsonQ.clone(valObj) : valObj;
parRef[lastKey].splice(idx, 0, valObj);
}
//if string concatenate , if number add
else if (type == 'string') {
var str = parRef[lastKey];
parRef[lastKey] = str.substring(0, idx) + valObj + str.substring(idx, objLn);
}
}
return this;
}
|
javascript
|
function(index, valObj, clone) {
var current = this.jsonQ_current;
//return if incorrect index is given
if (isNaN(index) && index != "first" && index != "last") {
error(index + 'is not a valid index.');
return this;
}
for (var i = 0, ln = current.length; i < ln; i++) {
var pathC = current[i].path.concat([]),
lastKey = pathC.pop(),
parRef = this.pathValue(pathC),
type = objType(parRef[lastKey]),
objLn = parRef[lastKey].length;
//to limit index
var idx = index < 0 || index == "first" ? 0 : index > objLn || index == "last" ? objLn : index;
//if array push
if (type == 'array') {
valObj = clone ? jsonQ.clone(valObj) : valObj;
parRef[lastKey].splice(idx, 0, valObj);
}
//if string concatenate , if number add
else if (type == 'string') {
var str = parRef[lastKey];
parRef[lastKey] = str.substring(0, idx) + valObj + str.substring(idx, objLn);
}
}
return this;
}
|
[
"function",
"(",
"index",
",",
"valObj",
",",
"clone",
")",
"{",
"var",
"current",
"=",
"this",
".",
"jsonQ_current",
";",
"//return if incorrect index is given",
"if",
"(",
"isNaN",
"(",
"index",
")",
"&&",
"index",
"!=",
"\"first\"",
"&&",
"index",
"!=",
"\"last\"",
")",
"{",
"error",
"(",
"index",
"+",
"'is not a valid index.'",
")",
";",
"return",
"this",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"ln",
"=",
"current",
".",
"length",
";",
"i",
"<",
"ln",
";",
"i",
"++",
")",
"{",
"var",
"pathC",
"=",
"current",
"[",
"i",
"]",
".",
"path",
".",
"concat",
"(",
"[",
"]",
")",
",",
"lastKey",
"=",
"pathC",
".",
"pop",
"(",
")",
",",
"parRef",
"=",
"this",
".",
"pathValue",
"(",
"pathC",
")",
",",
"type",
"=",
"objType",
"(",
"parRef",
"[",
"lastKey",
"]",
")",
",",
"objLn",
"=",
"parRef",
"[",
"lastKey",
"]",
".",
"length",
";",
"//to limit index",
"var",
"idx",
"=",
"index",
"<",
"0",
"||",
"index",
"==",
"\"first\"",
"?",
"0",
":",
"index",
">",
"objLn",
"||",
"index",
"==",
"\"last\"",
"?",
"objLn",
":",
"index",
";",
"//if array push",
"if",
"(",
"type",
"==",
"'array'",
")",
"{",
"valObj",
"=",
"clone",
"?",
"jsonQ",
".",
"clone",
"(",
"valObj",
")",
":",
"valObj",
";",
"parRef",
"[",
"lastKey",
"]",
".",
"splice",
"(",
"idx",
",",
"0",
",",
"valObj",
")",
";",
"}",
"//if string concatenate , if number add",
"else",
"if",
"(",
"type",
"==",
"'string'",
")",
"{",
"var",
"str",
"=",
"parRef",
"[",
"lastKey",
"]",
";",
"parRef",
"[",
"lastKey",
"]",
"=",
"str",
".",
"substring",
"(",
"0",
",",
"idx",
")",
"+",
"valObj",
"+",
"str",
".",
"substring",
"(",
"idx",
",",
"objLn",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
] |
to append at specific index of values of current
|
[
"to",
"append",
"at",
"specific",
"index",
"of",
"values",
"of",
"current"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L393-L430
|
|
19,211
|
s-yadav/jsonQ
|
jsonQ.js
|
function(key, qualifier) {
return tFunc.qualTrv.call(this, {
method: "find",
key: key,
qualifier: qualifier
});
}
|
javascript
|
function(key, qualifier) {
return tFunc.qualTrv.call(this, {
method: "find",
key: key,
qualifier: qualifier
});
}
|
[
"function",
"(",
"key",
",",
"qualifier",
")",
"{",
"return",
"tFunc",
".",
"qualTrv",
".",
"call",
"(",
"this",
",",
"{",
"method",
":",
"\"find\"",
",",
"key",
":",
"key",
",",
"qualifier",
":",
"qualifier",
"}",
")",
";",
"}"
] |
first argument is key in which you want to search, second key is qualifier of it.
|
[
"first",
"argument",
"is",
"key",
"in",
"which",
"you",
"want",
"to",
"search",
"second",
"key",
"is",
"qualifier",
"of",
"it",
"."
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L473-L479
|
|
19,212
|
s-yadav/jsonQ
|
jsonQ.js
|
function(key, settings) {
//merge global setting with local setting
settings = jsonQ.merge({}, jsonQ.settings.sort, settings);
var jobj = this.find(key),
current = jobj.clone(),
sortStack = [],
i, ln,
sortedPath = [],
type = objType(jobj.pathValue(current[0].path)),
//function to get value which is an array from pathKey traversing from right.
getClosestArray = function(key) {
while (key.length !== 0) {
var lastKey = key.pop();
if (!isNaN(lastKey)) {
var val = jobj.pathValue(key);
if (objType(val) == 'array') {
return val;
}
}
}
return null;
};
//initialize sort stack
for (i = 0, ln = current.length; i < ln; i++) {
sortStack.push({
pathHolder: current[i].path.concat([]),
current: current[i].path.concat([])
});
}
//to run the loop until all are sorted
var alpha = 0,
// function to remove element if sorting is done for that path
spliceElm = function(i) {
sortStack.splice(i, 1);
return --i;
};
while (sortStack.length !== 0) {
alpha++;
for (i = 0; i < sortStack.length; i++) {
var cur = sortStack[i].current,
pH = sortStack[i].pathHolder,
//to get the closest array in the current path. This will also change value of current path variable.
ary = getClosestArray(cur),
pathStr = cur.join();
//to remove from sort stack if no array is left on key or if that is already sorted
if (cur.length === 0 || sortedPath.indexOf(pathStr) != -1) {
i = spliceElm(i);
}
//to sort if array found
else {
//logic path is path which we add in on condition to find the element value according to which we are sorting
var logicPath = pH.slice(cur.length + 1, pH.length),
logic = function(a) {
var val = jsonQ.pathValue(a, logicPath);
//to convert val to be compared
val = sortFunc.baseConv(type, val, settings);
return settings.logic(val);
};
//to sort the root json
sortFunc.sortAry(ary, logic, settings);
//if multilevel sort is true
if (settings.allLevel) {
//to maintain the path which is already sorted and change pathHolder to point first element of sorted array
pH[cur.length] = 0;
sortedPath.push(pathStr);
} else {
//remove sorted path
i = spliceElm(i);
}
}
}
}
return jsonQ(jobj.jsonQ_root).find(key);
}
|
javascript
|
function(key, settings) {
//merge global setting with local setting
settings = jsonQ.merge({}, jsonQ.settings.sort, settings);
var jobj = this.find(key),
current = jobj.clone(),
sortStack = [],
i, ln,
sortedPath = [],
type = objType(jobj.pathValue(current[0].path)),
//function to get value which is an array from pathKey traversing from right.
getClosestArray = function(key) {
while (key.length !== 0) {
var lastKey = key.pop();
if (!isNaN(lastKey)) {
var val = jobj.pathValue(key);
if (objType(val) == 'array') {
return val;
}
}
}
return null;
};
//initialize sort stack
for (i = 0, ln = current.length; i < ln; i++) {
sortStack.push({
pathHolder: current[i].path.concat([]),
current: current[i].path.concat([])
});
}
//to run the loop until all are sorted
var alpha = 0,
// function to remove element if sorting is done for that path
spliceElm = function(i) {
sortStack.splice(i, 1);
return --i;
};
while (sortStack.length !== 0) {
alpha++;
for (i = 0; i < sortStack.length; i++) {
var cur = sortStack[i].current,
pH = sortStack[i].pathHolder,
//to get the closest array in the current path. This will also change value of current path variable.
ary = getClosestArray(cur),
pathStr = cur.join();
//to remove from sort stack if no array is left on key or if that is already sorted
if (cur.length === 0 || sortedPath.indexOf(pathStr) != -1) {
i = spliceElm(i);
}
//to sort if array found
else {
//logic path is path which we add in on condition to find the element value according to which we are sorting
var logicPath = pH.slice(cur.length + 1, pH.length),
logic = function(a) {
var val = jsonQ.pathValue(a, logicPath);
//to convert val to be compared
val = sortFunc.baseConv(type, val, settings);
return settings.logic(val);
};
//to sort the root json
sortFunc.sortAry(ary, logic, settings);
//if multilevel sort is true
if (settings.allLevel) {
//to maintain the path which is already sorted and change pathHolder to point first element of sorted array
pH[cur.length] = 0;
sortedPath.push(pathStr);
} else {
//remove sorted path
i = spliceElm(i);
}
}
}
}
return jsonQ(jobj.jsonQ_root).find(key);
}
|
[
"function",
"(",
"key",
",",
"settings",
")",
"{",
"//merge global setting with local setting",
"settings",
"=",
"jsonQ",
".",
"merge",
"(",
"{",
"}",
",",
"jsonQ",
".",
"settings",
".",
"sort",
",",
"settings",
")",
";",
"var",
"jobj",
"=",
"this",
".",
"find",
"(",
"key",
")",
",",
"current",
"=",
"jobj",
".",
"clone",
"(",
")",
",",
"sortStack",
"=",
"[",
"]",
",",
"i",
",",
"ln",
",",
"sortedPath",
"=",
"[",
"]",
",",
"type",
"=",
"objType",
"(",
"jobj",
".",
"pathValue",
"(",
"current",
"[",
"0",
"]",
".",
"path",
")",
")",
",",
"//function to get value which is an array from pathKey traversing from right.",
"getClosestArray",
"=",
"function",
"(",
"key",
")",
"{",
"while",
"(",
"key",
".",
"length",
"!==",
"0",
")",
"{",
"var",
"lastKey",
"=",
"key",
".",
"pop",
"(",
")",
";",
"if",
"(",
"!",
"isNaN",
"(",
"lastKey",
")",
")",
"{",
"var",
"val",
"=",
"jobj",
".",
"pathValue",
"(",
"key",
")",
";",
"if",
"(",
"objType",
"(",
"val",
")",
"==",
"'array'",
")",
"{",
"return",
"val",
";",
"}",
"}",
"}",
"return",
"null",
";",
"}",
";",
"//initialize sort stack",
"for",
"(",
"i",
"=",
"0",
",",
"ln",
"=",
"current",
".",
"length",
";",
"i",
"<",
"ln",
";",
"i",
"++",
")",
"{",
"sortStack",
".",
"push",
"(",
"{",
"pathHolder",
":",
"current",
"[",
"i",
"]",
".",
"path",
".",
"concat",
"(",
"[",
"]",
")",
",",
"current",
":",
"current",
"[",
"i",
"]",
".",
"path",
".",
"concat",
"(",
"[",
"]",
")",
"}",
")",
";",
"}",
"//to run the loop until all are sorted",
"var",
"alpha",
"=",
"0",
",",
"// function to remove element if sorting is done for that path",
"spliceElm",
"=",
"function",
"(",
"i",
")",
"{",
"sortStack",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"return",
"--",
"i",
";",
"}",
";",
"while",
"(",
"sortStack",
".",
"length",
"!==",
"0",
")",
"{",
"alpha",
"++",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"sortStack",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"cur",
"=",
"sortStack",
"[",
"i",
"]",
".",
"current",
",",
"pH",
"=",
"sortStack",
"[",
"i",
"]",
".",
"pathHolder",
",",
"//to get the closest array in the current path. This will also change value of current path variable.",
"ary",
"=",
"getClosestArray",
"(",
"cur",
")",
",",
"pathStr",
"=",
"cur",
".",
"join",
"(",
")",
";",
"//to remove from sort stack if no array is left on key or if that is already sorted",
"if",
"(",
"cur",
".",
"length",
"===",
"0",
"||",
"sortedPath",
".",
"indexOf",
"(",
"pathStr",
")",
"!=",
"-",
"1",
")",
"{",
"i",
"=",
"spliceElm",
"(",
"i",
")",
";",
"}",
"//to sort if array found",
"else",
"{",
"//logic path is path which we add in on condition to find the element value according to which we are sorting",
"var",
"logicPath",
"=",
"pH",
".",
"slice",
"(",
"cur",
".",
"length",
"+",
"1",
",",
"pH",
".",
"length",
")",
",",
"logic",
"=",
"function",
"(",
"a",
")",
"{",
"var",
"val",
"=",
"jsonQ",
".",
"pathValue",
"(",
"a",
",",
"logicPath",
")",
";",
"//to convert val to be compared",
"val",
"=",
"sortFunc",
".",
"baseConv",
"(",
"type",
",",
"val",
",",
"settings",
")",
";",
"return",
"settings",
".",
"logic",
"(",
"val",
")",
";",
"}",
";",
"//to sort the root json",
"sortFunc",
".",
"sortAry",
"(",
"ary",
",",
"logic",
",",
"settings",
")",
";",
"//if multilevel sort is true",
"if",
"(",
"settings",
".",
"allLevel",
")",
"{",
"//to maintain the path which is already sorted and change pathHolder to point first element of sorted array",
"pH",
"[",
"cur",
".",
"length",
"]",
"=",
"0",
";",
"sortedPath",
".",
"push",
"(",
"pathStr",
")",
";",
"}",
"else",
"{",
"//remove sorted path",
"i",
"=",
"spliceElm",
"(",
"i",
")",
";",
"}",
"}",
"}",
"}",
"return",
"jsonQ",
"(",
"jobj",
".",
"jsonQ_root",
")",
".",
"find",
"(",
"key",
")",
";",
"}"
] |
function to sort array objects
|
[
"function",
"to",
"sort",
"array",
"objects"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L521-L610
|
|
19,213
|
s-yadav/jsonQ
|
jsonQ.js
|
function(a) {
var val = jsonQ.pathValue(a, logicPath);
//to convert val to be compared
val = sortFunc.baseConv(type, val, settings);
return settings.logic(val);
}
|
javascript
|
function(a) {
var val = jsonQ.pathValue(a, logicPath);
//to convert val to be compared
val = sortFunc.baseConv(type, val, settings);
return settings.logic(val);
}
|
[
"function",
"(",
"a",
")",
"{",
"var",
"val",
"=",
"jsonQ",
".",
"pathValue",
"(",
"a",
",",
"logicPath",
")",
";",
"//to convert val to be compared",
"val",
"=",
"sortFunc",
".",
"baseConv",
"(",
"type",
",",
"val",
",",
"settings",
")",
";",
"return",
"settings",
".",
"logic",
"(",
"val",
")",
";",
"}"
] |
logic path is path which we add in on condition to find the element value according to which we are sorting
|
[
"logic",
"path",
"is",
"path",
"which",
"we",
"add",
"in",
"on",
"condition",
"to",
"find",
"the",
"element",
"value",
"according",
"to",
"which",
"we",
"are",
"sorting"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L581-L587
|
|
19,214
|
s-yadav/jsonQ
|
jsonQ.js
|
function(callback) {
var current = this.jsonQ_current;
for (var i = 0, ln = current.length; i < ln; i++) {
callback(i, current[i].path, this.pathValue(current[i].path));
}
return this;
}
|
javascript
|
function(callback) {
var current = this.jsonQ_current;
for (var i = 0, ln = current.length; i < ln; i++) {
callback(i, current[i].path, this.pathValue(current[i].path));
}
return this;
}
|
[
"function",
"(",
"callback",
")",
"{",
"var",
"current",
"=",
"this",
".",
"jsonQ_current",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"ln",
"=",
"current",
".",
"length",
";",
"i",
"<",
"ln",
";",
"i",
"++",
")",
"{",
"callback",
"(",
"i",
",",
"current",
"[",
"i",
"]",
".",
"path",
",",
"this",
".",
"pathValue",
"(",
"current",
"[",
"i",
"]",
".",
"path",
")",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
to make loop on current
|
[
"to",
"make",
"loop",
"on",
"current"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L612-L618
|
|
19,215
|
s-yadav/jsonQ
|
jsonQ.js
|
function(k, v) {
var type = objType(v),
tarType = objType(target[k]);
if (deep && (type == "array" || type == "object")) {
target[k] = type == tarType && (tarType == "array" || tarType == "object") ? target[k] : type == "array" ? [] : {};
//to merge recursively
jsonQ.merge(deep, target[k], v);
} else {
target[k] = v;
}
}
|
javascript
|
function(k, v) {
var type = objType(v),
tarType = objType(target[k]);
if (deep && (type == "array" || type == "object")) {
target[k] = type == tarType && (tarType == "array" || tarType == "object") ? target[k] : type == "array" ? [] : {};
//to merge recursively
jsonQ.merge(deep, target[k], v);
} else {
target[k] = v;
}
}
|
[
"function",
"(",
"k",
",",
"v",
")",
"{",
"var",
"type",
"=",
"objType",
"(",
"v",
")",
",",
"tarType",
"=",
"objType",
"(",
"target",
"[",
"k",
"]",
")",
";",
"if",
"(",
"deep",
"&&",
"(",
"type",
"==",
"\"array\"",
"||",
"type",
"==",
"\"object\"",
")",
")",
"{",
"target",
"[",
"k",
"]",
"=",
"type",
"==",
"tarType",
"&&",
"(",
"tarType",
"==",
"\"array\"",
"||",
"tarType",
"==",
"\"object\"",
")",
"?",
"target",
"[",
"k",
"]",
":",
"type",
"==",
"\"array\"",
"?",
"[",
"]",
":",
"{",
"}",
";",
"//to merge recursively",
"jsonQ",
".",
"merge",
"(",
"deep",
",",
"target",
"[",
"k",
"]",
",",
"v",
")",
";",
"}",
"else",
"{",
"target",
"[",
"k",
"]",
"=",
"v",
";",
"}",
"}"
] |
callback function to recursiveliy merge
|
[
"callback",
"function",
"to",
"recursiveliy",
"merge"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L697-L709
|
|
19,216
|
s-yadav/jsonQ
|
jsonQ.js
|
function(list, elm, isQualifier) {
var type = objType(elm),
ln = list.length,
//check that elm is a object or not that is taken by reference
refObj = type == "object" || type == "array" || type == "function" ? true : false;
//if elm is a function consider it as a qualifier
if (type == "function") {
isQualifier = true;
}
if (refObj && !isQualifier) {
//convert object to string so that they can be compared.
var jsonStr = stringify(jsonQ.order(elm));
}
for (var i = 0; i < ln; i++) {
var cur = list[i];
if (refObj) {
var lType = objType(cur);
if (lType != type && !isQualifier) continue;
//to compare
if (!isQualifier) {
if (stringify(jsonQ.order(cur)) == jsonStr) {
return i;
}
//if element is a qualifier
} else {
var test;
if (type == 'function') {
test = elm.call(cur);
} else if (type == "object" && lType == "object") {
test = jsonQ.checkKeyValue(cur, elm);
} else if (lType == "array") {
if (type == "array") {
for (var j = 0, elmLn = elm.length; j < elmLn; j++) {
test = jsonQ.index(cur, elm[j]) != -1;
if (!test) break;
}
} else {
test = jsonQ.index(cur, elm) != -1;
}
}
//return index if it passes the test
if (test) return i;
}
} else if (elm == cur) {
return i;
}
}
return -1;
}
|
javascript
|
function(list, elm, isQualifier) {
var type = objType(elm),
ln = list.length,
//check that elm is a object or not that is taken by reference
refObj = type == "object" || type == "array" || type == "function" ? true : false;
//if elm is a function consider it as a qualifier
if (type == "function") {
isQualifier = true;
}
if (refObj && !isQualifier) {
//convert object to string so that they can be compared.
var jsonStr = stringify(jsonQ.order(elm));
}
for (var i = 0; i < ln; i++) {
var cur = list[i];
if (refObj) {
var lType = objType(cur);
if (lType != type && !isQualifier) continue;
//to compare
if (!isQualifier) {
if (stringify(jsonQ.order(cur)) == jsonStr) {
return i;
}
//if element is a qualifier
} else {
var test;
if (type == 'function') {
test = elm.call(cur);
} else if (type == "object" && lType == "object") {
test = jsonQ.checkKeyValue(cur, elm);
} else if (lType == "array") {
if (type == "array") {
for (var j = 0, elmLn = elm.length; j < elmLn; j++) {
test = jsonQ.index(cur, elm[j]) != -1;
if (!test) break;
}
} else {
test = jsonQ.index(cur, elm) != -1;
}
}
//return index if it passes the test
if (test) return i;
}
} else if (elm == cur) {
return i;
}
}
return -1;
}
|
[
"function",
"(",
"list",
",",
"elm",
",",
"isQualifier",
")",
"{",
"var",
"type",
"=",
"objType",
"(",
"elm",
")",
",",
"ln",
"=",
"list",
".",
"length",
",",
"//check that elm is a object or not that is taken by reference",
"refObj",
"=",
"type",
"==",
"\"object\"",
"||",
"type",
"==",
"\"array\"",
"||",
"type",
"==",
"\"function\"",
"?",
"true",
":",
"false",
";",
"//if elm is a function consider it as a qualifier",
"if",
"(",
"type",
"==",
"\"function\"",
")",
"{",
"isQualifier",
"=",
"true",
";",
"}",
"if",
"(",
"refObj",
"&&",
"!",
"isQualifier",
")",
"{",
"//convert object to string so that they can be compared.",
"var",
"jsonStr",
"=",
"stringify",
"(",
"jsonQ",
".",
"order",
"(",
"elm",
")",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"ln",
";",
"i",
"++",
")",
"{",
"var",
"cur",
"=",
"list",
"[",
"i",
"]",
";",
"if",
"(",
"refObj",
")",
"{",
"var",
"lType",
"=",
"objType",
"(",
"cur",
")",
";",
"if",
"(",
"lType",
"!=",
"type",
"&&",
"!",
"isQualifier",
")",
"continue",
";",
"//to compare",
"if",
"(",
"!",
"isQualifier",
")",
"{",
"if",
"(",
"stringify",
"(",
"jsonQ",
".",
"order",
"(",
"cur",
")",
")",
"==",
"jsonStr",
")",
"{",
"return",
"i",
";",
"}",
"//if element is a qualifier",
"}",
"else",
"{",
"var",
"test",
";",
"if",
"(",
"type",
"==",
"'function'",
")",
"{",
"test",
"=",
"elm",
".",
"call",
"(",
"cur",
")",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"\"object\"",
"&&",
"lType",
"==",
"\"object\"",
")",
"{",
"test",
"=",
"jsonQ",
".",
"checkKeyValue",
"(",
"cur",
",",
"elm",
")",
";",
"}",
"else",
"if",
"(",
"lType",
"==",
"\"array\"",
")",
"{",
"if",
"(",
"type",
"==",
"\"array\"",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"elmLn",
"=",
"elm",
".",
"length",
";",
"j",
"<",
"elmLn",
";",
"j",
"++",
")",
"{",
"test",
"=",
"jsonQ",
".",
"index",
"(",
"cur",
",",
"elm",
"[",
"j",
"]",
")",
"!=",
"-",
"1",
";",
"if",
"(",
"!",
"test",
")",
"break",
";",
"}",
"}",
"else",
"{",
"test",
"=",
"jsonQ",
".",
"index",
"(",
"cur",
",",
"elm",
")",
"!=",
"-",
"1",
";",
"}",
"}",
"//return index if it passes the test",
"if",
"(",
"test",
")",
"return",
"i",
";",
"}",
"}",
"else",
"if",
"(",
"elm",
"==",
"cur",
")",
"{",
"return",
"i",
";",
"}",
"}",
"return",
"-",
"1",
";",
"}"
] |
to find index of an element in set of element
|
[
"to",
"find",
"index",
"of",
"an",
"element",
"in",
"set",
"of",
"element"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L791-L848
|
|
19,217
|
s-yadav/jsonQ
|
jsonQ.js
|
function(json, keyVal) {
for (var k in keyVal) {
if (keyVal.hasOwnProperty(k))
if (!jsonQ.identical(keyVal[k], json[k])) return false;
}
return true;
}
|
javascript
|
function(json, keyVal) {
for (var k in keyVal) {
if (keyVal.hasOwnProperty(k))
if (!jsonQ.identical(keyVal[k], json[k])) return false;
}
return true;
}
|
[
"function",
"(",
"json",
",",
"keyVal",
")",
"{",
"for",
"(",
"var",
"k",
"in",
"keyVal",
")",
"{",
"if",
"(",
"keyVal",
".",
"hasOwnProperty",
"(",
"k",
")",
")",
"if",
"(",
"!",
"jsonQ",
".",
"identical",
"(",
"keyVal",
"[",
"k",
"]",
",",
"json",
"[",
"k",
"]",
")",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
function to check an json object contains a set of key value pair or not
|
[
"function",
"to",
"check",
"an",
"json",
"object",
"contains",
"a",
"set",
"of",
"key",
"value",
"pair",
"or",
"not"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L854-L860
|
|
19,218
|
s-yadav/jsonQ
|
jsonQ.js
|
function(a, b) {
function sort(object) {
if (typeof object !== "object" || object === null) {
return object;
}
return Object.keys(object).sort().map(function(key) {
return {
key: key,
value: sort(object[key])
};
});
}
return JSON.stringify(sort(a)) === JSON.stringify(sort(b));
}
|
javascript
|
function(a, b) {
function sort(object) {
if (typeof object !== "object" || object === null) {
return object;
}
return Object.keys(object).sort().map(function(key) {
return {
key: key,
value: sort(object[key])
};
});
}
return JSON.stringify(sort(a)) === JSON.stringify(sort(b));
}
|
[
"function",
"(",
"a",
",",
"b",
")",
"{",
"function",
"sort",
"(",
"object",
")",
"{",
"if",
"(",
"typeof",
"object",
"!==",
"\"object\"",
"||",
"object",
"===",
"null",
")",
"{",
"return",
"object",
";",
"}",
"return",
"Object",
".",
"keys",
"(",
"object",
")",
".",
"sort",
"(",
")",
".",
"map",
"(",
"function",
"(",
"key",
")",
"{",
"return",
"{",
"key",
":",
"key",
",",
"value",
":",
"sort",
"(",
"object",
"[",
"key",
"]",
")",
"}",
";",
"}",
")",
";",
"}",
"return",
"JSON",
".",
"stringify",
"(",
"sort",
"(",
"a",
")",
")",
"===",
"JSON",
".",
"stringify",
"(",
"sort",
"(",
"b",
")",
")",
";",
"}"
] |
need to modify it little bit By Chris O'Brien, prettycode.org
|
[
"need",
"to",
"modify",
"it",
"little",
"bit",
"By",
"Chris",
"O",
"Brien",
"prettycode",
".",
"org"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L924-L940
|
|
19,219
|
s-yadav/jsonQ
|
jsonQ.js
|
function() {
var arg = arguments,
target = [],
ln = arg.length;
for (var i = 0; i < ln; i++) {
var aryLn = arg[i].length;
for (var j = 0; j < aryLn; j++) {
var itm = arg[i][j];
if (jsonQ.index(target, itm) == -1) {
target.push(itm);
}
}
}
return target;
}
|
javascript
|
function() {
var arg = arguments,
target = [],
ln = arg.length;
for (var i = 0; i < ln; i++) {
var aryLn = arg[i].length;
for (var j = 0; j < aryLn; j++) {
var itm = arg[i][j];
if (jsonQ.index(target, itm) == -1) {
target.push(itm);
}
}
}
return target;
}
|
[
"function",
"(",
")",
"{",
"var",
"arg",
"=",
"arguments",
",",
"target",
"=",
"[",
"]",
",",
"ln",
"=",
"arg",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"ln",
";",
"i",
"++",
")",
"{",
"var",
"aryLn",
"=",
"arg",
"[",
"i",
"]",
".",
"length",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"aryLn",
";",
"j",
"++",
")",
"{",
"var",
"itm",
"=",
"arg",
"[",
"i",
"]",
"[",
"j",
"]",
";",
"if",
"(",
"jsonQ",
".",
"index",
"(",
"target",
",",
"itm",
")",
"==",
"-",
"1",
")",
"{",
"target",
".",
"push",
"(",
"itm",
")",
";",
"}",
"}",
"}",
"return",
"target",
";",
"}"
] |
Return the union of arrays in new array
|
[
"Return",
"the",
"union",
"of",
"arrays",
"in",
"new",
"array"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L942-L958
|
|
19,220
|
s-yadav/jsonQ
|
jsonQ.js
|
function() {
var arg = arguments,
target = [],
flag,
ln = arg.length;
if (ln == 1) {
target = arg[0];
} else {
for (var j = 0, aryLn = arg[0].length; j < aryLn; j++) {
var elm = arg[0][j];
flag = 1;
for (var i = 1; i < ln; i++) {
if (jsonQ.index(arg[i], elm) == -1) {
flag = 0;
break;
}
}
if (flag == 1) {
target.push(elm);
}
}
}
return target;
}
|
javascript
|
function() {
var arg = arguments,
target = [],
flag,
ln = arg.length;
if (ln == 1) {
target = arg[0];
} else {
for (var j = 0, aryLn = arg[0].length; j < aryLn; j++) {
var elm = arg[0][j];
flag = 1;
for (var i = 1; i < ln; i++) {
if (jsonQ.index(arg[i], elm) == -1) {
flag = 0;
break;
}
}
if (flag == 1) {
target.push(elm);
}
}
}
return target;
}
|
[
"function",
"(",
")",
"{",
"var",
"arg",
"=",
"arguments",
",",
"target",
"=",
"[",
"]",
",",
"flag",
",",
"ln",
"=",
"arg",
".",
"length",
";",
"if",
"(",
"ln",
"==",
"1",
")",
"{",
"target",
"=",
"arg",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"aryLn",
"=",
"arg",
"[",
"0",
"]",
".",
"length",
";",
"j",
"<",
"aryLn",
";",
"j",
"++",
")",
"{",
"var",
"elm",
"=",
"arg",
"[",
"0",
"]",
"[",
"j",
"]",
";",
"flag",
"=",
"1",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"ln",
";",
"i",
"++",
")",
"{",
"if",
"(",
"jsonQ",
".",
"index",
"(",
"arg",
"[",
"i",
"]",
",",
"elm",
")",
"==",
"-",
"1",
")",
"{",
"flag",
"=",
"0",
";",
"break",
";",
"}",
"}",
"if",
"(",
"flag",
"==",
"1",
")",
"{",
"target",
".",
"push",
"(",
"elm",
")",
";",
"}",
"}",
"}",
"return",
"target",
";",
"}"
] |
return intersection of array in new array
|
[
"return",
"intersection",
"of",
"array",
"in",
"new",
"array"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L960-L985
|
|
19,221
|
s-yadav/jsonQ
|
jsonQ.js
|
function(array) {
for (var i = 1, ln = array.length; i < ln; i++) {
var j = Math.floor(Math.random() * (i + 1)),
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
return array;
}
|
javascript
|
function(array) {
for (var i = 1, ln = array.length; i < ln; i++) {
var j = Math.floor(Math.random() * (i + 1)),
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
return array;
}
|
[
"function",
"(",
"array",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"1",
",",
"ln",
"=",
"array",
".",
"length",
";",
"i",
"<",
"ln",
";",
"i",
"++",
")",
"{",
"var",
"j",
"=",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"(",
"i",
"+",
"1",
")",
")",
",",
"tmp",
"=",
"array",
"[",
"i",
"]",
";",
"array",
"[",
"i",
"]",
"=",
"array",
"[",
"j",
"]",
";",
"array",
"[",
"j",
"]",
"=",
"tmp",
";",
"}",
"return",
"array",
";",
"}"
] |
shuffle the order of elements in a array. returns the same array.
|
[
"shuffle",
"the",
"order",
"of",
"elements",
"in",
"a",
"array",
".",
"returns",
"the",
"same",
"array",
"."
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L987-L996
|
|
19,222
|
s-yadav/jsonQ
|
jsonQ.js
|
function(json, path) {
var i = 0,
ln = path.length;
if (json === null) {
return null;
}
while (i < ln) {
if (json[path[i]] === null) {
json = null;
return;
} else {
json = json[path[i]];
}
i = i + 1;
}
return json;
}
|
javascript
|
function(json, path) {
var i = 0,
ln = path.length;
if (json === null) {
return null;
}
while (i < ln) {
if (json[path[i]] === null) {
json = null;
return;
} else {
json = json[path[i]];
}
i = i + 1;
}
return json;
}
|
[
"function",
"(",
"json",
",",
"path",
")",
"{",
"var",
"i",
"=",
"0",
",",
"ln",
"=",
"path",
".",
"length",
";",
"if",
"(",
"json",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"while",
"(",
"i",
"<",
"ln",
")",
"{",
"if",
"(",
"json",
"[",
"path",
"[",
"i",
"]",
"]",
"===",
"null",
")",
"{",
"json",
"=",
"null",
";",
"return",
";",
"}",
"else",
"{",
"json",
"=",
"json",
"[",
"path",
"[",
"i",
"]",
"]",
";",
"}",
"i",
"=",
"i",
"+",
"1",
";",
"}",
"return",
"json",
";",
"}"
] |
to get value at specific path in a json
|
[
"to",
"get",
"value",
"at",
"specific",
"path",
"in",
"a",
"json"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L1013-L1031
|
|
19,223
|
s-yadav/jsonQ
|
jsonQ.js
|
function(target, index, val, clone) {
if (isNaN(index) && index != "first" && index != "last") {
error(index + 'is not a valid index.');
return;
}
var type = objType(target),
length = target.length;
//to limit index
var idx = index < 0 || index == "first" ? 0 : index > length || index == "last" ? length : index;
//if array push
if (type == 'array') {
val = clone ? jsonQ.clone(val) : val;
target.splice(idx, 0, val);
}
//if string concatenate , if number add
else if (type == 'string') {
target = target.substring(0, idx) + val + target.substring(idx, length);
}
return target;
}
|
javascript
|
function(target, index, val, clone) {
if (isNaN(index) && index != "first" && index != "last") {
error(index + 'is not a valid index.');
return;
}
var type = objType(target),
length = target.length;
//to limit index
var idx = index < 0 || index == "first" ? 0 : index > length || index == "last" ? length : index;
//if array push
if (type == 'array') {
val = clone ? jsonQ.clone(val) : val;
target.splice(idx, 0, val);
}
//if string concatenate , if number add
else if (type == 'string') {
target = target.substring(0, idx) + val + target.substring(idx, length);
}
return target;
}
|
[
"function",
"(",
"target",
",",
"index",
",",
"val",
",",
"clone",
")",
"{",
"if",
"(",
"isNaN",
"(",
"index",
")",
"&&",
"index",
"!=",
"\"first\"",
"&&",
"index",
"!=",
"\"last\"",
")",
"{",
"error",
"(",
"index",
"+",
"'is not a valid index.'",
")",
";",
"return",
";",
"}",
"var",
"type",
"=",
"objType",
"(",
"target",
")",
",",
"length",
"=",
"target",
".",
"length",
";",
"//to limit index",
"var",
"idx",
"=",
"index",
"<",
"0",
"||",
"index",
"==",
"\"first\"",
"?",
"0",
":",
"index",
">",
"length",
"||",
"index",
"==",
"\"last\"",
"?",
"length",
":",
"index",
";",
"//if array push",
"if",
"(",
"type",
"==",
"'array'",
")",
"{",
"val",
"=",
"clone",
"?",
"jsonQ",
".",
"clone",
"(",
"val",
")",
":",
"val",
";",
"target",
".",
"splice",
"(",
"idx",
",",
"0",
",",
"val",
")",
";",
"}",
"//if string concatenate , if number add",
"else",
"if",
"(",
"type",
"==",
"'string'",
")",
"{",
"target",
"=",
"target",
".",
"substring",
"(",
"0",
",",
"idx",
")",
"+",
"val",
"+",
"target",
".",
"substring",
"(",
"idx",
",",
"length",
")",
";",
"}",
"return",
"target",
";",
"}"
] |
to append at specific index of values of array or string
|
[
"to",
"append",
"at",
"specific",
"index",
"of",
"values",
"of",
"array",
"or",
"string"
] |
845399736d2627c7a60cd4519f56e56553ae6f4f
|
https://github.com/s-yadav/jsonQ/blob/845399736d2627c7a60cd4519f56e56553ae6f4f/jsonQ.js#L1096-L1124
|
|
19,224
|
daurnimator/lua.vm.js
|
src/lua.js
|
getmain
|
function getmain(L) {
L.rawgeti(Lua.defines.REGISTRYINDEX, Lua.defines.RIDX_MAINTHREAD);
var _L = L.tothread(-1);
L.pop(1);
return _L;
}
|
javascript
|
function getmain(L) {
L.rawgeti(Lua.defines.REGISTRYINDEX, Lua.defines.RIDX_MAINTHREAD);
var _L = L.tothread(-1);
L.pop(1);
return _L;
}
|
[
"function",
"getmain",
"(",
"L",
")",
"{",
"L",
".",
"rawgeti",
"(",
"Lua",
".",
"defines",
".",
"REGISTRYINDEX",
",",
"Lua",
".",
"defines",
".",
"RIDX_MAINTHREAD",
")",
";",
"var",
"_L",
"=",
"L",
".",
"tothread",
"(",
"-",
"1",
")",
";",
"L",
".",
"pop",
"(",
"1",
")",
";",
"return",
"_L",
";",
"}"
] |
Get main lua_State of given thread
|
[
"Get",
"main",
"lua_State",
"of",
"given",
"thread"
] |
4e3fd0341205b6bdecf74de80ea94e5d5e53013a
|
https://github.com/daurnimator/lua.vm.js/blob/4e3fd0341205b6bdecf74de80ea94e5d5e53013a/src/lua.js#L517-L522
|
19,225
|
vbauer/manet
|
example/client.js
|
screenshotServiceUrl
|
function screenshotServiceUrl(siteUrl) {
return url.format({
protocol: 'http',
hostname: DEF_MANET_HOST,
port: DEF_MANET_PORT,
query: {
callback: DEF_CALLBACK,
url: siteUrl,
force: true
}
});
}
|
javascript
|
function screenshotServiceUrl(siteUrl) {
return url.format({
protocol: 'http',
hostname: DEF_MANET_HOST,
port: DEF_MANET_PORT,
query: {
callback: DEF_CALLBACK,
url: siteUrl,
force: true
}
});
}
|
[
"function",
"screenshotServiceUrl",
"(",
"siteUrl",
")",
"{",
"return",
"url",
".",
"format",
"(",
"{",
"protocol",
":",
"'http'",
",",
"hostname",
":",
"DEF_MANET_HOST",
",",
"port",
":",
"DEF_MANET_PORT",
",",
"query",
":",
"{",
"callback",
":",
"DEF_CALLBACK",
",",
"url",
":",
"siteUrl",
",",
"force",
":",
"true",
"}",
"}",
")",
";",
"}"
] |
Generate full URL to the screenshot service.
|
[
"Generate",
"full",
"URL",
"to",
"the",
"screenshot",
"service",
"."
] |
83cb65f1f0bce75988cda74d38d588e1101893d3
|
https://github.com/vbauer/manet/blob/83cb65f1f0bce75988cda74d38d588e1101893d3/example/client.js#L29-L40
|
19,226
|
vbauer/manet
|
example/client.js
|
captureScreenshot
|
function captureScreenshot(url) {
const serviceUrl = screenshotServiceUrl(url);
console.log('Sending request to capture screenshot from %s', url);
http.get(serviceUrl, (res) =>
console.log('Screenshot from %s was captured with status %s', url, res.statusCode));
console.log('Request to capture screenshot from %s was sent', url);
}
|
javascript
|
function captureScreenshot(url) {
const serviceUrl = screenshotServiceUrl(url);
console.log('Sending request to capture screenshot from %s', url);
http.get(serviceUrl, (res) =>
console.log('Screenshot from %s was captured with status %s', url, res.statusCode));
console.log('Request to capture screenshot from %s was sent', url);
}
|
[
"function",
"captureScreenshot",
"(",
"url",
")",
"{",
"const",
"serviceUrl",
"=",
"screenshotServiceUrl",
"(",
"url",
")",
";",
"console",
".",
"log",
"(",
"'Sending request to capture screenshot from %s'",
",",
"url",
")",
";",
"http",
".",
"get",
"(",
"serviceUrl",
",",
"(",
"res",
")",
"=>",
"console",
".",
"log",
"(",
"'Screenshot from %s was captured with status %s'",
",",
"url",
",",
"res",
".",
"statusCode",
")",
")",
";",
"console",
".",
"log",
"(",
"'Request to capture screenshot from %s was sent'",
",",
"url",
")",
";",
"}"
] |
Call the Manet using the current server as a callback.
|
[
"Call",
"the",
"Manet",
"using",
"the",
"current",
"server",
"as",
"a",
"callback",
"."
] |
83cb65f1f0bce75988cda74d38d588e1101893d3
|
https://github.com/vbauer/manet/blob/83cb65f1f0bce75988cda74d38d588e1101893d3/example/client.js#L45-L52
|
19,227
|
vbauer/manet
|
example/client.js
|
startPoller
|
function startPoller() {
setInterval(() => {
for (let i = 0; i < DEF_SITES_URL.length; i++) {
captureScreenshot(DEF_SITES_URL[i]);
}
}, DEF_DELAY);
}
|
javascript
|
function startPoller() {
setInterval(() => {
for (let i = 0; i < DEF_SITES_URL.length; i++) {
captureScreenshot(DEF_SITES_URL[i]);
}
}, DEF_DELAY);
}
|
[
"function",
"startPoller",
"(",
")",
"{",
"setInterval",
"(",
"(",
")",
"=>",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"DEF_SITES_URL",
".",
"length",
";",
"i",
"++",
")",
"{",
"captureScreenshot",
"(",
"DEF_SITES_URL",
"[",
"i",
"]",
")",
";",
"}",
"}",
",",
"DEF_DELAY",
")",
";",
"}"
] |
Start HTTP requests poller.
|
[
"Start",
"HTTP",
"requests",
"poller",
"."
] |
83cb65f1f0bce75988cda74d38d588e1101893d3
|
https://github.com/vbauer/manet/blob/83cb65f1f0bce75988cda74d38d588e1101893d3/example/client.js#L57-L63
|
19,228
|
vbauer/manet
|
example/client.js
|
startServer
|
function startServer() {
http.createServer((req, res) => {
const fileName = __dirname + path.sep + new Date().getTime() + '.png';
req.on('end', () => {
res.writeHead(200);
res.end();
fs.stat(fileName, function(error, stat) {
console.log(
'Stored file ' + fileName +
' with size ' + stat.size +
', headers: ' + JSON.stringify(req.headers)
);
fs.unlinkSync(fileName);
});
});
req.pipe(fs.createWriteStream(fileName));
}).listen(DEF_CLIENT_PORT);
console.log("Client server running on port 8124");
}
|
javascript
|
function startServer() {
http.createServer((req, res) => {
const fileName = __dirname + path.sep + new Date().getTime() + '.png';
req.on('end', () => {
res.writeHead(200);
res.end();
fs.stat(fileName, function(error, stat) {
console.log(
'Stored file ' + fileName +
' with size ' + stat.size +
', headers: ' + JSON.stringify(req.headers)
);
fs.unlinkSync(fileName);
});
});
req.pipe(fs.createWriteStream(fileName));
}).listen(DEF_CLIENT_PORT);
console.log("Client server running on port 8124");
}
|
[
"function",
"startServer",
"(",
")",
"{",
"http",
".",
"createServer",
"(",
"(",
"req",
",",
"res",
")",
"=>",
"{",
"const",
"fileName",
"=",
"__dirname",
"+",
"path",
".",
"sep",
"+",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"+",
"'.png'",
";",
"req",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"{",
"res",
".",
"writeHead",
"(",
"200",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"fs",
".",
"stat",
"(",
"fileName",
",",
"function",
"(",
"error",
",",
"stat",
")",
"{",
"console",
".",
"log",
"(",
"'Stored file '",
"+",
"fileName",
"+",
"' with size '",
"+",
"stat",
".",
"size",
"+",
"', headers: '",
"+",
"JSON",
".",
"stringify",
"(",
"req",
".",
"headers",
")",
")",
";",
"fs",
".",
"unlinkSync",
"(",
"fileName",
")",
";",
"}",
")",
";",
"}",
")",
";",
"req",
".",
"pipe",
"(",
"fs",
".",
"createWriteStream",
"(",
"fileName",
")",
")",
";",
"}",
")",
".",
"listen",
"(",
"DEF_CLIENT_PORT",
")",
";",
"console",
".",
"log",
"(",
"\"Client server running on port 8124\"",
")",
";",
"}"
] |
Start client HTTP server.
|
[
"Start",
"client",
"HTTP",
"server",
"."
] |
83cb65f1f0bce75988cda74d38d588e1101893d3
|
https://github.com/vbauer/manet/blob/83cb65f1f0bce75988cda74d38d588e1101893d3/example/client.js#L68-L89
|
19,229
|
caolan/jam
|
lib/utils.js
|
getURL
|
function getURL( repository ) {
var repourl;
if (typeof repository === 'object') {
repourl = repository.url;
} else {
repourl = repository
};
return repourl;
}
|
javascript
|
function getURL( repository ) {
var repourl;
if (typeof repository === 'object') {
repourl = repository.url;
} else {
repourl = repository
};
return repourl;
}
|
[
"function",
"getURL",
"(",
"repository",
")",
"{",
"var",
"repourl",
";",
"if",
"(",
"typeof",
"repository",
"===",
"'object'",
")",
"{",
"repourl",
"=",
"repository",
".",
"url",
";",
"}",
"else",
"{",
"repourl",
"=",
"repository",
"}",
";",
"return",
"repourl",
";",
"}"
] |
Returns a URL according to the type of a repository
@private
@commit 4fd38b97f4763d288f9f948acbf1122f33bf6951
|
[
"Returns",
"a",
"URL",
"according",
"to",
"the",
"type",
"of",
"a",
"repository"
] |
befa3f276dcb9ce593bc0d913e0313c50835f16c
|
https://github.com/caolan/jam/blob/befa3f276dcb9ce593bc0d913e0313c50835f16c/lib/utils.js#L394-L404
|
19,230
|
caolan/jam
|
lib/logger.js
|
function (levels, fn) {
return function (label, val) {
for (var i = 0; i < levels.length; i++) {
if (levels[i] === exports.level) {
return fn(label, val);
}
}
};
}
|
javascript
|
function (levels, fn) {
return function (label, val) {
for (var i = 0; i < levels.length; i++) {
if (levels[i] === exports.level) {
return fn(label, val);
}
}
};
}
|
[
"function",
"(",
"levels",
",",
"fn",
")",
"{",
"return",
"function",
"(",
"label",
",",
"val",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"levels",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"levels",
"[",
"i",
"]",
"===",
"exports",
".",
"level",
")",
"{",
"return",
"fn",
"(",
"label",
",",
"val",
")",
";",
"}",
"}",
"}",
";",
"}"
] |
Executes a function only if the current log level is in the levels list
@param {Array} levels
@param {Function} fn
|
[
"Executes",
"a",
"function",
"only",
"if",
"the",
"current",
"log",
"level",
"is",
"in",
"the",
"levels",
"list"
] |
befa3f276dcb9ce593bc0d913e0313c50835f16c
|
https://github.com/caolan/jam/blob/befa3f276dcb9ce593bc0d913e0313c50835f16c/lib/logger.js#L40-L48
|
|
19,231
|
kminami/apib2swagger
|
index.js
|
swaggerSecurity
|
function swaggerSecurity(context, headers) {
var security = null;
headers.filter(function(header) {
return header.name.toLowerCase() === 'authorization';
}).forEach(function(header) {
if (header.value.match(/^Basic /)) {
if (!security) security = {};
security['basic'] = [];
context.swagger.securityDefinitions['basic'] = { type: 'basic' };
} else if (header.value.match(/^Bearer /)) {
if (!security) security = {};
if (context.options.bearerAsApikey) {
security['bearer'] = [];
context.swagger.securityDefinitions['bearer'] = {
type: 'apiKey', in: 'header', name: 'Authorization'
};
} else {
security['oauth2'] = [];
context.swagger.securityDefinitions['oauth2'] = {
type: 'oauth2', flow: 'accessCode',
authorizationUrl: '', tokenUrl: '', scopes: {} };
}
}
});
return security;
}
|
javascript
|
function swaggerSecurity(context, headers) {
var security = null;
headers.filter(function(header) {
return header.name.toLowerCase() === 'authorization';
}).forEach(function(header) {
if (header.value.match(/^Basic /)) {
if (!security) security = {};
security['basic'] = [];
context.swagger.securityDefinitions['basic'] = { type: 'basic' };
} else if (header.value.match(/^Bearer /)) {
if (!security) security = {};
if (context.options.bearerAsApikey) {
security['bearer'] = [];
context.swagger.securityDefinitions['bearer'] = {
type: 'apiKey', in: 'header', name: 'Authorization'
};
} else {
security['oauth2'] = [];
context.swagger.securityDefinitions['oauth2'] = {
type: 'oauth2', flow: 'accessCode',
authorizationUrl: '', tokenUrl: '', scopes: {} };
}
}
});
return security;
}
|
[
"function",
"swaggerSecurity",
"(",
"context",
",",
"headers",
")",
"{",
"var",
"security",
"=",
"null",
";",
"headers",
".",
"filter",
"(",
"function",
"(",
"header",
")",
"{",
"return",
"header",
".",
"name",
".",
"toLowerCase",
"(",
")",
"===",
"'authorization'",
";",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"header",
")",
"{",
"if",
"(",
"header",
".",
"value",
".",
"match",
"(",
"/",
"^Basic ",
"/",
")",
")",
"{",
"if",
"(",
"!",
"security",
")",
"security",
"=",
"{",
"}",
";",
"security",
"[",
"'basic'",
"]",
"=",
"[",
"]",
";",
"context",
".",
"swagger",
".",
"securityDefinitions",
"[",
"'basic'",
"]",
"=",
"{",
"type",
":",
"'basic'",
"}",
";",
"}",
"else",
"if",
"(",
"header",
".",
"value",
".",
"match",
"(",
"/",
"^Bearer ",
"/",
")",
")",
"{",
"if",
"(",
"!",
"security",
")",
"security",
"=",
"{",
"}",
";",
"if",
"(",
"context",
".",
"options",
".",
"bearerAsApikey",
")",
"{",
"security",
"[",
"'bearer'",
"]",
"=",
"[",
"]",
";",
"context",
".",
"swagger",
".",
"securityDefinitions",
"[",
"'bearer'",
"]",
"=",
"{",
"type",
":",
"'apiKey'",
",",
"in",
":",
"'header'",
",",
"name",
":",
"'Authorization'",
"}",
";",
"}",
"else",
"{",
"security",
"[",
"'oauth2'",
"]",
"=",
"[",
"]",
";",
"context",
".",
"swagger",
".",
"securityDefinitions",
"[",
"'oauth2'",
"]",
"=",
"{",
"type",
":",
"'oauth2'",
",",
"flow",
":",
"'accessCode'",
",",
"authorizationUrl",
":",
"''",
",",
"tokenUrl",
":",
"''",
",",
"scopes",
":",
"{",
"}",
"}",
";",
"}",
"}",
"}",
")",
";",
"return",
"security",
";",
"}"
] |
generate security and securityDefinitions from authorization headers
|
[
"generate",
"security",
"and",
"securityDefinitions",
"from",
"authorization",
"headers"
] |
24eeec1662b4c6c933f81572fce012aefcc96cf0
|
https://github.com/kminami/apib2swagger/blob/24eeec1662b4c6c933f81572fce012aefcc96cf0/index.js#L221-L246
|
19,232
|
wix/eslint-plugin-lodash
|
src/util/methodDataUtil.js
|
expandAliases
|
function expandAliases(version, methods) {
return _.flatMap(methods, method => expandAlias(version, method))
}
|
javascript
|
function expandAliases(version, methods) {
return _.flatMap(methods, method => expandAlias(version, method))
}
|
[
"function",
"expandAliases",
"(",
"version",
",",
"methods",
")",
"{",
"return",
"_",
".",
"flatMap",
"(",
"methods",
",",
"method",
"=>",
"expandAlias",
"(",
"version",
",",
"method",
")",
")",
"}"
] |
Gets a major version number and a list of methods and returns a list of methods and all their aliases
@param version
@param methods
@returns {string[]}
|
[
"Gets",
"a",
"major",
"version",
"number",
"and",
"a",
"list",
"of",
"methods",
"and",
"returns",
"a",
"list",
"of",
"methods",
"and",
"all",
"their",
"aliases"
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/methodDataUtil.js#L24-L26
|
19,233
|
wix/eslint-plugin-lodash
|
src/util/methodDataUtil.js
|
isChainable
|
function isChainable(version, method) {
const data = getMethodData(version)
return _.get(data, [getMainAlias(version, method), 'chainable'], false)
}
|
javascript
|
function isChainable(version, method) {
const data = getMethodData(version)
return _.get(data, [getMainAlias(version, method), 'chainable'], false)
}
|
[
"function",
"isChainable",
"(",
"version",
",",
"method",
")",
"{",
"const",
"data",
"=",
"getMethodData",
"(",
"version",
")",
"return",
"_",
".",
"get",
"(",
"data",
",",
"[",
"getMainAlias",
"(",
"version",
",",
"method",
")",
",",
"'chainable'",
"]",
",",
"false",
")",
"}"
] |
Gets a list of all chainable methods and their aliases for a given version
@param {Number} version
@param {string} method
@returns {boolean}
|
[
"Gets",
"a",
"list",
"of",
"all",
"chainable",
"methods",
"and",
"their",
"aliases",
"for",
"a",
"given",
"version"
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/methodDataUtil.js#L44-L47
|
19,234
|
wix/eslint-plugin-lodash
|
src/util/methodDataUtil.js
|
isCollectionMethod
|
function isCollectionMethod(version, method) {
return methodSupportsShorthand(version, method) || _.includes(expandAliases(version, ['reduce', 'reduceRight']), method)
}
|
javascript
|
function isCollectionMethod(version, method) {
return methodSupportsShorthand(version, method) || _.includes(expandAliases(version, ['reduce', 'reduceRight']), method)
}
|
[
"function",
"isCollectionMethod",
"(",
"version",
",",
"method",
")",
"{",
"return",
"methodSupportsShorthand",
"(",
"version",
",",
"method",
")",
"||",
"_",
".",
"includes",
"(",
"expandAliases",
"(",
"version",
",",
"[",
"'reduce'",
",",
"'reduceRight'",
"]",
")",
",",
"method",
")",
"}"
] |
Gets whether the method is a collection method
@param {Number} version
@param {string} method
@returns {Boolean}
|
[
"Gets",
"whether",
"the",
"method",
"is",
"a",
"collection",
"method"
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/methodDataUtil.js#L55-L57
|
19,235
|
wix/eslint-plugin-lodash
|
src/util/methodDataUtil.js
|
methodSupportsShorthand
|
function methodSupportsShorthand(version, method, shorthandType) {
const mainAlias = getMainAlias(version, method)
const methodShorthandData = _.get(getMethodData(version), [mainAlias, 'shorthand'])
return _.isObject(methodShorthandData) ? Boolean(shorthandType && methodShorthandData[shorthandType]) : Boolean(methodShorthandData)
}
|
javascript
|
function methodSupportsShorthand(version, method, shorthandType) {
const mainAlias = getMainAlias(version, method)
const methodShorthandData = _.get(getMethodData(version), [mainAlias, 'shorthand'])
return _.isObject(methodShorthandData) ? Boolean(shorthandType && methodShorthandData[shorthandType]) : Boolean(methodShorthandData)
}
|
[
"function",
"methodSupportsShorthand",
"(",
"version",
",",
"method",
",",
"shorthandType",
")",
"{",
"const",
"mainAlias",
"=",
"getMainAlias",
"(",
"version",
",",
"method",
")",
"const",
"methodShorthandData",
"=",
"_",
".",
"get",
"(",
"getMethodData",
"(",
"version",
")",
",",
"[",
"mainAlias",
",",
"'shorthand'",
"]",
")",
"return",
"_",
".",
"isObject",
"(",
"methodShorthandData",
")",
"?",
"Boolean",
"(",
"shorthandType",
"&&",
"methodShorthandData",
"[",
"shorthandType",
"]",
")",
":",
"Boolean",
"(",
"methodShorthandData",
")",
"}"
] |
Returns whether the node's method call supports using shorthands in the specified version
@param {Number} version
@param {string} method
@returns {boolean}
|
[
"Returns",
"whether",
"the",
"node",
"s",
"method",
"call",
"supports",
"using",
"shorthands",
"in",
"the",
"specified",
"version"
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/methodDataUtil.js#L66-L70
|
19,236
|
wix/eslint-plugin-lodash
|
src/util/methodDataUtil.js
|
isAliasOfMethod
|
function isAliasOfMethod(version, method, suspect) {
return method === suspect || _.includes(_.get(getMethodData(version), [method, 'aliases']), suspect)
}
|
javascript
|
function isAliasOfMethod(version, method, suspect) {
return method === suspect || _.includes(_.get(getMethodData(version), [method, 'aliases']), suspect)
}
|
[
"function",
"isAliasOfMethod",
"(",
"version",
",",
"method",
",",
"suspect",
")",
"{",
"return",
"method",
"===",
"suspect",
"||",
"_",
".",
"includes",
"(",
"_",
".",
"get",
"(",
"getMethodData",
"(",
"version",
")",
",",
"[",
"method",
",",
"'aliases'",
"]",
")",
",",
"suspect",
")",
"}"
] |
Gets whether the suspect is an alias of the method in a given version
@param {Number} version
@param {string} method
@param {string} suspect
@returns {boolean}
|
[
"Gets",
"whether",
"the",
"suspect",
"is",
"an",
"alias",
"of",
"the",
"method",
"in",
"a",
"given",
"version"
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/methodDataUtil.js#L88-L90
|
19,237
|
wix/eslint-plugin-lodash
|
src/util/methodDataUtil.js
|
getMainAlias
|
function getMainAlias(version, method) {
const data = getMethodData(version)
return data[method] ? method : _.findKey(data, methodData => _.includes(methodData.aliases, method))
}
|
javascript
|
function getMainAlias(version, method) {
const data = getMethodData(version)
return data[method] ? method : _.findKey(data, methodData => _.includes(methodData.aliases, method))
}
|
[
"function",
"getMainAlias",
"(",
"version",
",",
"method",
")",
"{",
"const",
"data",
"=",
"getMethodData",
"(",
"version",
")",
"return",
"data",
"[",
"method",
"]",
"?",
"method",
":",
"_",
".",
"findKey",
"(",
"data",
",",
"methodData",
"=>",
"_",
".",
"includes",
"(",
"methodData",
".",
"aliases",
",",
"method",
")",
")",
"}"
] |
Returns the main alias for the method in the specified version.
@param {number} version
@param {string} method
@returns {string}
|
[
"Returns",
"the",
"main",
"alias",
"for",
"the",
"method",
"in",
"the",
"specified",
"version",
"."
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/methodDataUtil.js#L98-L101
|
19,238
|
wix/eslint-plugin-lodash
|
src/util/methodDataUtil.js
|
getIterateeIndex
|
function getIterateeIndex(version, method) {
const mainAlias = getMainAlias(version, method)
const methodData = getMethodData(version)[mainAlias]
if (_.has(methodData, 'iterateeIndex')) {
return methodData.iterateeIndex
}
if (methodData && methodData.iteratee) {
return 1
}
return -1
}
|
javascript
|
function getIterateeIndex(version, method) {
const mainAlias = getMainAlias(version, method)
const methodData = getMethodData(version)[mainAlias]
if (_.has(methodData, 'iterateeIndex')) {
return methodData.iterateeIndex
}
if (methodData && methodData.iteratee) {
return 1
}
return -1
}
|
[
"function",
"getIterateeIndex",
"(",
"version",
",",
"method",
")",
"{",
"const",
"mainAlias",
"=",
"getMainAlias",
"(",
"version",
",",
"method",
")",
"const",
"methodData",
"=",
"getMethodData",
"(",
"version",
")",
"[",
"mainAlias",
"]",
"if",
"(",
"_",
".",
"has",
"(",
"methodData",
",",
"'iterateeIndex'",
")",
")",
"{",
"return",
"methodData",
".",
"iterateeIndex",
"}",
"if",
"(",
"methodData",
"&&",
"methodData",
".",
"iteratee",
")",
"{",
"return",
"1",
"}",
"return",
"-",
"1",
"}"
] |
Gets the index of the iteratee of a method when it isn't chained, or -1 if it doesn't have one.
@param {number} version
@param {string} method
@returns {number}
|
[
"Gets",
"the",
"index",
"of",
"the",
"iteratee",
"of",
"a",
"method",
"when",
"it",
"isn",
"t",
"chained",
"or",
"-",
"1",
"if",
"it",
"doesn",
"t",
"have",
"one",
"."
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/methodDataUtil.js#L109-L119
|
19,239
|
wix/eslint-plugin-lodash
|
src/util/astUtil.js
|
isMemberExpOf
|
function isMemberExpOf(node, objectName, {maxLength = Number.MAX_VALUE, allowComputed} = {}) {
if (objectName) {
let curr = node
let depth = maxLength
while (curr && depth) {
if (allowComputed || isPropAccess(curr)) {
if (curr.type === 'MemberExpression' && curr.object.name === objectName) {
return true
}
curr = curr.object
depth--
} else {
return false
}
}
}
}
|
javascript
|
function isMemberExpOf(node, objectName, {maxLength = Number.MAX_VALUE, allowComputed} = {}) {
if (objectName) {
let curr = node
let depth = maxLength
while (curr && depth) {
if (allowComputed || isPropAccess(curr)) {
if (curr.type === 'MemberExpression' && curr.object.name === objectName) {
return true
}
curr = curr.object
depth--
} else {
return false
}
}
}
}
|
[
"function",
"isMemberExpOf",
"(",
"node",
",",
"objectName",
",",
"{",
"maxLength",
"=",
"Number",
".",
"MAX_VALUE",
",",
"allowComputed",
"}",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"objectName",
")",
"{",
"let",
"curr",
"=",
"node",
"let",
"depth",
"=",
"maxLength",
"while",
"(",
"curr",
"&&",
"depth",
")",
"{",
"if",
"(",
"allowComputed",
"||",
"isPropAccess",
"(",
"curr",
")",
")",
"{",
"if",
"(",
"curr",
".",
"type",
"===",
"'MemberExpression'",
"&&",
"curr",
".",
"object",
".",
"name",
"===",
"objectName",
")",
"{",
"return",
"true",
"}",
"curr",
"=",
"curr",
".",
"object",
"depth",
"--",
"}",
"else",
"{",
"return",
"false",
"}",
"}",
"}",
"}"
] |
Returns whether the node is a member expression starting with the same object, up to the specified length
@param {Object} node
@param {string} objectName
@param {Object} [options]
@param {number} [options.maxLength]
@param {boolean} [options.allowComputed]
@returns {boolean|undefined}
|
[
"Returns",
"whether",
"the",
"node",
"is",
"a",
"member",
"expression",
"starting",
"with",
"the",
"same",
"object",
"up",
"to",
"the",
"specified",
"length"
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/astUtil.js#L65-L81
|
19,240
|
wix/eslint-plugin-lodash
|
src/util/astUtil.js
|
hasOnlyOneStatement
|
function hasOnlyOneStatement(func) {
if (isFunctionDefinitionWithBlock(func)) {
return _.get(func, 'body.body.length') === 1
}
if (func.type === 'ArrowFunctionExpression') {
return !_.get(func, 'body.body')
}
}
|
javascript
|
function hasOnlyOneStatement(func) {
if (isFunctionDefinitionWithBlock(func)) {
return _.get(func, 'body.body.length') === 1
}
if (func.type === 'ArrowFunctionExpression') {
return !_.get(func, 'body.body')
}
}
|
[
"function",
"hasOnlyOneStatement",
"(",
"func",
")",
"{",
"if",
"(",
"isFunctionDefinitionWithBlock",
"(",
"func",
")",
")",
"{",
"return",
"_",
".",
"get",
"(",
"func",
",",
"'body.body.length'",
")",
"===",
"1",
"}",
"if",
"(",
"func",
".",
"type",
"===",
"'ArrowFunctionExpression'",
")",
"{",
"return",
"!",
"_",
".",
"get",
"(",
"func",
",",
"'body.body'",
")",
"}",
"}"
] |
Returns whether the node specified has only one statement
@param {Object} func
@returns {boolean}
|
[
"Returns",
"whether",
"the",
"node",
"specified",
"has",
"only",
"one",
"statement"
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/astUtil.js#L102-L109
|
19,241
|
wix/eslint-plugin-lodash
|
src/util/astUtil.js
|
isBinaryExpWithMemberOf
|
function isBinaryExpWithMemberOf(operator, exp, objectName, {maxLength, allowComputed, onlyLiterals} = {}) {
if (!_.isMatch(exp, {type: 'BinaryExpression', operator})) {
return false
}
const [left, right] = [exp.left, exp.right].map(side => isMemberExpOf(side, objectName, {maxLength, allowComputed}))
return (left === !right) && (!onlyLiterals || isLiteral(exp.left) || isLiteral(exp.right))
}
|
javascript
|
function isBinaryExpWithMemberOf(operator, exp, objectName, {maxLength, allowComputed, onlyLiterals} = {}) {
if (!_.isMatch(exp, {type: 'BinaryExpression', operator})) {
return false
}
const [left, right] = [exp.left, exp.right].map(side => isMemberExpOf(side, objectName, {maxLength, allowComputed}))
return (left === !right) && (!onlyLiterals || isLiteral(exp.left) || isLiteral(exp.right))
}
|
[
"function",
"isBinaryExpWithMemberOf",
"(",
"operator",
",",
"exp",
",",
"objectName",
",",
"{",
"maxLength",
",",
"allowComputed",
",",
"onlyLiterals",
"}",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isMatch",
"(",
"exp",
",",
"{",
"type",
":",
"'BinaryExpression'",
",",
"operator",
"}",
")",
")",
"{",
"return",
"false",
"}",
"const",
"[",
"left",
",",
"right",
"]",
"=",
"[",
"exp",
".",
"left",
",",
"exp",
".",
"right",
"]",
".",
"map",
"(",
"side",
"=>",
"isMemberExpOf",
"(",
"side",
",",
"objectName",
",",
"{",
"maxLength",
",",
"allowComputed",
"}",
")",
")",
"return",
"(",
"left",
"===",
"!",
"right",
")",
"&&",
"(",
"!",
"onlyLiterals",
"||",
"isLiteral",
"(",
"exp",
".",
"left",
")",
"||",
"isLiteral",
"(",
"exp",
".",
"right",
")",
")",
"}"
] |
Returns whether the expression specified is a binary expression with the specified operator and one of its sides is a member expression of the specified object name
@param {string} operator
@param {Object} exp
@param {string} objectName
@param {number} maxLength
@param {boolean} allowComputed
@param {boolean} onlyLiterals
@returns {boolean|undefined}
|
[
"Returns",
"whether",
"the",
"expression",
"specified",
"is",
"a",
"binary",
"expression",
"with",
"the",
"specified",
"operator",
"and",
"one",
"of",
"its",
"sides",
"is",
"a",
"member",
"expression",
"of",
"the",
"specified",
"object",
"name"
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/astUtil.js#L139-L145
|
19,242
|
wix/eslint-plugin-lodash
|
src/util/astUtil.js
|
isNegationOfMemberOf
|
function isNegationOfMemberOf(exp, objectName, {maxLength} = {}) {
return isNegationExpression(exp) && isMemberExpOf(exp.argument, objectName, {maxLength, allowComputed: false})
}
|
javascript
|
function isNegationOfMemberOf(exp, objectName, {maxLength} = {}) {
return isNegationExpression(exp) && isMemberExpOf(exp.argument, objectName, {maxLength, allowComputed: false})
}
|
[
"function",
"isNegationOfMemberOf",
"(",
"exp",
",",
"objectName",
",",
"{",
"maxLength",
"}",
"=",
"{",
"}",
")",
"{",
"return",
"isNegationExpression",
"(",
"exp",
")",
"&&",
"isMemberExpOf",
"(",
"exp",
".",
"argument",
",",
"objectName",
",",
"{",
"maxLength",
",",
"allowComputed",
":",
"false",
"}",
")",
"}"
] |
Returns whether the expression is a negation of a member of objectName, in the specified depth.
@param {Object} exp
@param {string} objectName
@param {number} maxLength
@returns {boolean|undefined}
|
[
"Returns",
"whether",
"the",
"expression",
"is",
"a",
"negation",
"of",
"a",
"member",
"of",
"objectName",
"in",
"the",
"specified",
"depth",
"."
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/astUtil.js#L162-L164
|
19,243
|
wix/eslint-plugin-lodash
|
src/util/astUtil.js
|
getValueReturnedInFirstStatement
|
function getValueReturnedInFirstStatement(func) {
const firstLine = getFirstFunctionLine(func)
if (func) {
if (isFunctionDefinitionWithBlock(func)) {
return isReturnStatement(firstLine) ? firstLine.argument : undefined
}
if (func.type === 'ArrowFunctionExpression') {
return firstLine
}
}
}
|
javascript
|
function getValueReturnedInFirstStatement(func) {
const firstLine = getFirstFunctionLine(func)
if (func) {
if (isFunctionDefinitionWithBlock(func)) {
return isReturnStatement(firstLine) ? firstLine.argument : undefined
}
if (func.type === 'ArrowFunctionExpression') {
return firstLine
}
}
}
|
[
"function",
"getValueReturnedInFirstStatement",
"(",
"func",
")",
"{",
"const",
"firstLine",
"=",
"getFirstFunctionLine",
"(",
"func",
")",
"if",
"(",
"func",
")",
"{",
"if",
"(",
"isFunctionDefinitionWithBlock",
"(",
"func",
")",
")",
"{",
"return",
"isReturnStatement",
"(",
"firstLine",
")",
"?",
"firstLine",
".",
"argument",
":",
"undefined",
"}",
"if",
"(",
"func",
".",
"type",
"===",
"'ArrowFunctionExpression'",
")",
"{",
"return",
"firstLine",
"}",
"}",
"}"
] |
Returns the node of the value returned in the first line, if any
@param {Object} func
@returns {Object|undefined}
|
[
"Returns",
"the",
"node",
"of",
"the",
"value",
"returned",
"in",
"the",
"first",
"line",
"if",
"any"
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/astUtil.js#L181-L191
|
19,244
|
wix/eslint-plugin-lodash
|
src/util/astUtil.js
|
isCallFromObject
|
function isCallFromObject(node, objName) {
return node && objName && node.type === 'CallExpression' && _.get(node, 'callee.object.name') === objName
}
|
javascript
|
function isCallFromObject(node, objName) {
return node && objName && node.type === 'CallExpression' && _.get(node, 'callee.object.name') === objName
}
|
[
"function",
"isCallFromObject",
"(",
"node",
",",
"objName",
")",
"{",
"return",
"node",
"&&",
"objName",
"&&",
"node",
".",
"type",
"===",
"'CallExpression'",
"&&",
"_",
".",
"get",
"(",
"node",
",",
"'callee.object.name'",
")",
"===",
"objName",
"}"
] |
Returns whether the node is a call from the specified object name
@param {Object} node
@param {string} objName
@returns {boolean|undefined}
|
[
"Returns",
"whether",
"the",
"node",
"is",
"a",
"call",
"from",
"the",
"specified",
"object",
"name"
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/astUtil.js#L199-L201
|
19,245
|
wix/eslint-plugin-lodash
|
src/util/astUtil.js
|
getExpressionComparedToInt
|
function getExpressionComparedToInt(node, value, checkOver) {
const isValue = getIsValue(value)
if (_.includes(comparisonOperators, node.operator)) {
if (isValue(node.right)) {
return node.left
}
if (isValue(node.left)) {
return node.right
}
}
if (checkOver) {
if (node.operator === '>' && isValue(node.right)) {
return node.left
}
if (node.operator === '<' && isValue(node.left)) {
return node.right
}
const isNext = getIsValue(value + 1)
if ((node.operator === '>=' || node.operator === '<') && isNext(node.right)) {
return node.left
}
if ((node.operator === '<=' || node.operator === '>') && isNext(node.left)) {
return node.right
}
}
}
|
javascript
|
function getExpressionComparedToInt(node, value, checkOver) {
const isValue = getIsValue(value)
if (_.includes(comparisonOperators, node.operator)) {
if (isValue(node.right)) {
return node.left
}
if (isValue(node.left)) {
return node.right
}
}
if (checkOver) {
if (node.operator === '>' && isValue(node.right)) {
return node.left
}
if (node.operator === '<' && isValue(node.left)) {
return node.right
}
const isNext = getIsValue(value + 1)
if ((node.operator === '>=' || node.operator === '<') && isNext(node.right)) {
return node.left
}
if ((node.operator === '<=' || node.operator === '>') && isNext(node.left)) {
return node.right
}
}
}
|
[
"function",
"getExpressionComparedToInt",
"(",
"node",
",",
"value",
",",
"checkOver",
")",
"{",
"const",
"isValue",
"=",
"getIsValue",
"(",
"value",
")",
"if",
"(",
"_",
".",
"includes",
"(",
"comparisonOperators",
",",
"node",
".",
"operator",
")",
")",
"{",
"if",
"(",
"isValue",
"(",
"node",
".",
"right",
")",
")",
"{",
"return",
"node",
".",
"left",
"}",
"if",
"(",
"isValue",
"(",
"node",
".",
"left",
")",
")",
"{",
"return",
"node",
".",
"right",
"}",
"}",
"if",
"(",
"checkOver",
")",
"{",
"if",
"(",
"node",
".",
"operator",
"===",
"'>'",
"&&",
"isValue",
"(",
"node",
".",
"right",
")",
")",
"{",
"return",
"node",
".",
"left",
"}",
"if",
"(",
"node",
".",
"operator",
"===",
"'<'",
"&&",
"isValue",
"(",
"node",
".",
"left",
")",
")",
"{",
"return",
"node",
".",
"right",
"}",
"const",
"isNext",
"=",
"getIsValue",
"(",
"value",
"+",
"1",
")",
"if",
"(",
"(",
"node",
".",
"operator",
"===",
"'>='",
"||",
"node",
".",
"operator",
"===",
"'<'",
")",
"&&",
"isNext",
"(",
"node",
".",
"right",
")",
")",
"{",
"return",
"node",
".",
"left",
"}",
"if",
"(",
"(",
"node",
".",
"operator",
"===",
"'<='",
"||",
"node",
".",
"operator",
"===",
"'>'",
")",
"&&",
"isNext",
"(",
"node",
".",
"left",
")",
")",
"{",
"return",
"node",
".",
"right",
"}",
"}",
"}"
] |
Returns the expression compared to the value in a binary expression, or undefined if there isn't one
@param {Object} node
@param {number} value
@param {boolean} [checkOver=false]
@returns {Object|undefined}
|
[
"Returns",
"the",
"expression",
"compared",
"to",
"the",
"value",
"in",
"a",
"binary",
"expression",
"or",
"undefined",
"if",
"there",
"isn",
"t",
"one"
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/astUtil.js#L268-L293
|
19,246
|
wix/eslint-plugin-lodash
|
src/util/astUtil.js
|
collectParameterValues
|
function collectParameterValues(node) {
switch (node && node.type) {
case 'Identifier':
return [node.name]
case 'ObjectPattern':
return _.flatMap(node.properties, prop => collectParameterValues(prop.value))
case 'ArrayPattern':
return _.flatMap(node.elements, collectParameterValues)
default:
return []
}
}
|
javascript
|
function collectParameterValues(node) {
switch (node && node.type) {
case 'Identifier':
return [node.name]
case 'ObjectPattern':
return _.flatMap(node.properties, prop => collectParameterValues(prop.value))
case 'ArrayPattern':
return _.flatMap(node.elements, collectParameterValues)
default:
return []
}
}
|
[
"function",
"collectParameterValues",
"(",
"node",
")",
"{",
"switch",
"(",
"node",
"&&",
"node",
".",
"type",
")",
"{",
"case",
"'Identifier'",
":",
"return",
"[",
"node",
".",
"name",
"]",
"case",
"'ObjectPattern'",
":",
"return",
"_",
".",
"flatMap",
"(",
"node",
".",
"properties",
",",
"prop",
"=>",
"collectParameterValues",
"(",
"prop",
".",
"value",
")",
")",
"case",
"'ArrayPattern'",
":",
"return",
"_",
".",
"flatMap",
"(",
"node",
".",
"elements",
",",
"collectParameterValues",
")",
"default",
":",
"return",
"[",
"]",
"}",
"}"
] |
Returns an array of identifier names returned in a parameter or variable definition
@param node an AST node which is a parameter or variable declaration
@returns {string[]} List of names defined in the parameter
|
[
"Returns",
"an",
"array",
"of",
"identifier",
"names",
"returned",
"in",
"a",
"parameter",
"or",
"variable",
"definition"
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/astUtil.js#L314-L325
|
19,247
|
wix/eslint-plugin-lodash
|
src/util/lodashUtil.js
|
isCallToMethod
|
function isCallToMethod(node, version, method) {
return methodDataUtil.isAliasOfMethod(version, method, astUtil.getMethodName(node))
}
|
javascript
|
function isCallToMethod(node, version, method) {
return methodDataUtil.isAliasOfMethod(version, method, astUtil.getMethodName(node))
}
|
[
"function",
"isCallToMethod",
"(",
"node",
",",
"version",
",",
"method",
")",
"{",
"return",
"methodDataUtil",
".",
"isAliasOfMethod",
"(",
"version",
",",
"method",
",",
"astUtil",
".",
"getMethodName",
"(",
"node",
")",
")",
"}"
] |
Returns whether the node is a call to the specified method or one of its aliases in the version
@param {Object} node
@param {number} version
@param {string} method
@returns {boolean}
|
[
"Returns",
"whether",
"the",
"node",
"is",
"a",
"call",
"to",
"the",
"specified",
"method",
"or",
"one",
"of",
"its",
"aliases",
"in",
"the",
"version"
] |
2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5
|
https://github.com/wix/eslint-plugin-lodash/blob/2a778227d4beeefa86c5af4e0cd193b4f7d5f5e5/src/util/lodashUtil.js#L34-L36
|
19,248
|
apache/cordova-create
|
index.js
|
cordovaCreateLegacyAdapter
|
function cordovaCreateLegacyAdapter (dir, id, name, cfg, extEvents) {
// Unwrap and shallow-clone that nasty nested config object
const opts = Object.assign({}, ((cfg || {}).lib || {}).www);
if (id) opts.id = id;
if (name) opts.name = name;
if (extEvents) opts.extEvents = extEvents;
return cordovaCreate(dir, opts);
}
|
javascript
|
function cordovaCreateLegacyAdapter (dir, id, name, cfg, extEvents) {
// Unwrap and shallow-clone that nasty nested config object
const opts = Object.assign({}, ((cfg || {}).lib || {}).www);
if (id) opts.id = id;
if (name) opts.name = name;
if (extEvents) opts.extEvents = extEvents;
return cordovaCreate(dir, opts);
}
|
[
"function",
"cordovaCreateLegacyAdapter",
"(",
"dir",
",",
"id",
",",
"name",
",",
"cfg",
",",
"extEvents",
")",
"{",
"// Unwrap and shallow-clone that nasty nested config object",
"const",
"opts",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"(",
"(",
"cfg",
"||",
"{",
"}",
")",
".",
"lib",
"||",
"{",
"}",
")",
".",
"www",
")",
";",
"if",
"(",
"id",
")",
"opts",
".",
"id",
"=",
"id",
";",
"if",
"(",
"name",
")",
"opts",
".",
"name",
"=",
"name",
";",
"if",
"(",
"extEvents",
")",
"opts",
".",
"extEvents",
"=",
"extEvents",
";",
"return",
"cordovaCreate",
"(",
"dir",
",",
"opts",
")",
";",
"}"
] |
Legacy interface. See README for documentation
|
[
"Legacy",
"interface",
".",
"See",
"README",
"for",
"documentation"
] |
d2cf1045c497f2e0954f5ee7d813ec1bcc5607d8
|
https://github.com/apache/cordova-create/blob/d2cf1045c497f2e0954f5ee7d813ec1bcc5607d8/index.js#L63-L72
|
19,249
|
apache/cordova-create
|
spec/helpers.js
|
createWithMockFetch
|
function createWithMockFetch (dir, id, name, cfg, events) {
const mockFetchDest = path.join(tmpDir, 'mockFetchDest');
const templateDir = path.dirname(require.resolve('cordova-app-hello-world'));
const fetchSpy = jasmine.createSpy('fetchSpy')
.and.callFake(() => Promise.resolve(mockFetchDest));
fs.copySync(templateDir, mockFetchDest);
return createWith({fetch: fetchSpy})(dir, id, name, cfg, events)
.then(() => fetchSpy);
}
|
javascript
|
function createWithMockFetch (dir, id, name, cfg, events) {
const mockFetchDest = path.join(tmpDir, 'mockFetchDest');
const templateDir = path.dirname(require.resolve('cordova-app-hello-world'));
const fetchSpy = jasmine.createSpy('fetchSpy')
.and.callFake(() => Promise.resolve(mockFetchDest));
fs.copySync(templateDir, mockFetchDest);
return createWith({fetch: fetchSpy})(dir, id, name, cfg, events)
.then(() => fetchSpy);
}
|
[
"function",
"createWithMockFetch",
"(",
"dir",
",",
"id",
",",
"name",
",",
"cfg",
",",
"events",
")",
"{",
"const",
"mockFetchDest",
"=",
"path",
".",
"join",
"(",
"tmpDir",
",",
"'mockFetchDest'",
")",
";",
"const",
"templateDir",
"=",
"path",
".",
"dirname",
"(",
"require",
".",
"resolve",
"(",
"'cordova-app-hello-world'",
")",
")",
";",
"const",
"fetchSpy",
"=",
"jasmine",
".",
"createSpy",
"(",
"'fetchSpy'",
")",
".",
"and",
".",
"callFake",
"(",
"(",
")",
"=>",
"Promise",
".",
"resolve",
"(",
"mockFetchDest",
")",
")",
";",
"fs",
".",
"copySync",
"(",
"templateDir",
",",
"mockFetchDest",
")",
";",
"return",
"createWith",
"(",
"{",
"fetch",
":",
"fetchSpy",
"}",
")",
"(",
"dir",
",",
"id",
",",
"name",
",",
"cfg",
",",
"events",
")",
".",
"then",
"(",
"(",
")",
"=>",
"fetchSpy",
")",
";",
"}"
] |
Calls create with mocked fetch to not depend on the outside world
|
[
"Calls",
"create",
"with",
"mocked",
"fetch",
"to",
"not",
"depend",
"on",
"the",
"outside",
"world"
] |
d2cf1045c497f2e0954f5ee7d813ec1bcc5607d8
|
https://github.com/apache/cordova-create/blob/d2cf1045c497f2e0954f5ee7d813ec1bcc5607d8/spec/helpers.js#L40-L49
|
19,250
|
apache/cordova-create
|
spec/helpers.js
|
expectRejection
|
function expectRejection (promise, expectedReason) {
return promise.then(
() => fail('Expected promise to be rejected'),
reason => {
if (expectedReason instanceof Error) {
expect(reason instanceof expectedReason.constructor).toBeTruthy();
expect(reason.message).toContain(expectedReason.message);
} else if (typeof expectedReason === 'function') {
expect(expectedReason(reason)).toBeTruthy();
} else if (expectedReason !== undefined) {
expect(reason).toBe(expectedReason);
} else {
expect().nothing();
}
});
}
|
javascript
|
function expectRejection (promise, expectedReason) {
return promise.then(
() => fail('Expected promise to be rejected'),
reason => {
if (expectedReason instanceof Error) {
expect(reason instanceof expectedReason.constructor).toBeTruthy();
expect(reason.message).toContain(expectedReason.message);
} else if (typeof expectedReason === 'function') {
expect(expectedReason(reason)).toBeTruthy();
} else if (expectedReason !== undefined) {
expect(reason).toBe(expectedReason);
} else {
expect().nothing();
}
});
}
|
[
"function",
"expectRejection",
"(",
"promise",
",",
"expectedReason",
")",
"{",
"return",
"promise",
".",
"then",
"(",
"(",
")",
"=>",
"fail",
"(",
"'Expected promise to be rejected'",
")",
",",
"reason",
"=>",
"{",
"if",
"(",
"expectedReason",
"instanceof",
"Error",
")",
"{",
"expect",
"(",
"reason",
"instanceof",
"expectedReason",
".",
"constructor",
")",
".",
"toBeTruthy",
"(",
")",
";",
"expect",
"(",
"reason",
".",
"message",
")",
".",
"toContain",
"(",
"expectedReason",
".",
"message",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"expectedReason",
"===",
"'function'",
")",
"{",
"expect",
"(",
"expectedReason",
"(",
"reason",
")",
")",
".",
"toBeTruthy",
"(",
")",
";",
"}",
"else",
"if",
"(",
"expectedReason",
"!==",
"undefined",
")",
"{",
"expect",
"(",
"reason",
")",
".",
"toBe",
"(",
"expectedReason",
")",
";",
"}",
"else",
"{",
"expect",
"(",
")",
".",
"nothing",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Expect promise to get rejected with a reason matching expectedReason
|
[
"Expect",
"promise",
"to",
"get",
"rejected",
"with",
"a",
"reason",
"matching",
"expectedReason"
] |
d2cf1045c497f2e0954f5ee7d813ec1bcc5607d8
|
https://github.com/apache/cordova-create/blob/d2cf1045c497f2e0954f5ee7d813ec1bcc5607d8/spec/helpers.js#L52-L67
|
19,251
|
apache/cordova-create
|
spec/create.spec.js
|
checkPackageJson
|
function checkPackageJson () {
const pkg = requireFresh(path.join(project, 'package.json'));
expect(pkg.name).toEqual(appId);
expect(pkg.displayName).toEqual(appName);
expect(pkg.version).toEqual(appVersion);
}
|
javascript
|
function checkPackageJson () {
const pkg = requireFresh(path.join(project, 'package.json'));
expect(pkg.name).toEqual(appId);
expect(pkg.displayName).toEqual(appName);
expect(pkg.version).toEqual(appVersion);
}
|
[
"function",
"checkPackageJson",
"(",
")",
"{",
"const",
"pkg",
"=",
"requireFresh",
"(",
"path",
".",
"join",
"(",
"project",
",",
"'package.json'",
")",
")",
";",
"expect",
"(",
"pkg",
".",
"name",
")",
".",
"toEqual",
"(",
"appId",
")",
";",
"expect",
"(",
"pkg",
".",
"displayName",
")",
".",
"toEqual",
"(",
"appName",
")",
";",
"expect",
"(",
"pkg",
".",
"version",
")",
".",
"toEqual",
"(",
"appVersion",
")",
";",
"}"
] |
Check that we got package.json and it was updated correctly
|
[
"Check",
"that",
"we",
"got",
"package",
".",
"json",
"and",
"it",
"was",
"updated",
"correctly"
] |
d2cf1045c497f2e0954f5ee7d813ec1bcc5607d8
|
https://github.com/apache/cordova-create/blob/d2cf1045c497f2e0954f5ee7d813ec1bcc5607d8/spec/create.spec.js#L92-L97
|
19,252
|
apache/cordova-create
|
spec/create.spec.js
|
checkDefaultTemplate
|
function checkDefaultTemplate () {
const pkg = requireFresh(path.join(project, 'package.json'));
expect(pkg.author).toEqual('Apache Cordova Team');
const configXml = new ConfigParser(path.join(project, 'config.xml'));
expect(configXml.author()).toEqual('Apache Cordova Team');
}
|
javascript
|
function checkDefaultTemplate () {
const pkg = requireFresh(path.join(project, 'package.json'));
expect(pkg.author).toEqual('Apache Cordova Team');
const configXml = new ConfigParser(path.join(project, 'config.xml'));
expect(configXml.author()).toEqual('Apache Cordova Team');
}
|
[
"function",
"checkDefaultTemplate",
"(",
")",
"{",
"const",
"pkg",
"=",
"requireFresh",
"(",
"path",
".",
"join",
"(",
"project",
",",
"'package.json'",
")",
")",
";",
"expect",
"(",
"pkg",
".",
"author",
")",
".",
"toEqual",
"(",
"'Apache Cordova Team'",
")",
";",
"const",
"configXml",
"=",
"new",
"ConfigParser",
"(",
"path",
".",
"join",
"(",
"project",
",",
"'config.xml'",
")",
")",
";",
"expect",
"(",
"configXml",
".",
"author",
"(",
")",
")",
".",
"toEqual",
"(",
"'Apache Cordova Team'",
")",
";",
"}"
] |
Check that we did use the default template
|
[
"Check",
"that",
"we",
"did",
"use",
"the",
"default",
"template"
] |
d2cf1045c497f2e0954f5ee7d813ec1bcc5607d8
|
https://github.com/apache/cordova-create/blob/d2cf1045c497f2e0954f5ee7d813ec1bcc5607d8/spec/create.spec.js#L105-L111
|
19,253
|
apache/cordova-create
|
spec/create.spec.js
|
checkNotDefaultTemplate
|
function checkNotDefaultTemplate () {
const configXml = new ConfigParser(path.join(project, 'config.xml'));
expect(configXml.author()).not.toEqual('Apache Cordova Team');
}
|
javascript
|
function checkNotDefaultTemplate () {
const configXml = new ConfigParser(path.join(project, 'config.xml'));
expect(configXml.author()).not.toEqual('Apache Cordova Team');
}
|
[
"function",
"checkNotDefaultTemplate",
"(",
")",
"{",
"const",
"configXml",
"=",
"new",
"ConfigParser",
"(",
"path",
".",
"join",
"(",
"project",
",",
"'config.xml'",
")",
")",
";",
"expect",
"(",
"configXml",
".",
"author",
"(",
")",
")",
".",
"not",
".",
"toEqual",
"(",
"'Apache Cordova Team'",
")",
";",
"}"
] |
Check that we did not use the default template
|
[
"Check",
"that",
"we",
"did",
"not",
"use",
"the",
"default",
"template"
] |
d2cf1045c497f2e0954f5ee7d813ec1bcc5607d8
|
https://github.com/apache/cordova-create/blob/d2cf1045c497f2e0954f5ee7d813ec1bcc5607d8/spec/create.spec.js#L114-L117
|
19,254
|
jls/nightwatch-html-reporter
|
lib/normalize.js
|
function(results, run, options, done) {
_.each(results, function(result) {
var pkg = {
name: result.testsuites.$.name,
tests: parse(result.testsuites.$.tests),
failures: parse(result.testsuites.$.failures),
suites: []
};
pkg.isFailure = pkg.failures > 0;
var filename = result.filename;
_.each(result.testsuites.testsuite, function(suiteData) {
var $ = suiteData.$;
var suite = {
name: $.name,
pkgName: $.package,
failures: parse($.failures),
errors: parse($.errors),
skipped: parse($.skipped),
tests: parse($.tests),
cases: []
};
// Sometimes the package name isn't in the
// xml reports...
if (!pkg.name) {
if (result.testsuites.filename) {
pkg.name = result.testsuites.filename;
} else {
pkg.name = suite.pkgName;
}
} else {
if (result.testsuites.filename) {
pkg.name = result.testsuites.filename + '-' + pkg.name;
}
}
suite.passed = suite.tests - suite.errors - suite.failures;
suite.isFailure = suite.errors > 0 || suite.failures > 0;
suite.errmessages = $['system-err'];
pkg.suites.push(suite);
_.each(suiteData.testcase, function(caseData) {
var assert = {
message: caseData.$.name,
time: caseData.$.time,
stacktrace: '',
failure: false,
skipped: false,
screenshots: []
// failure: false or failure message,
// screenshots: ['path/to/screen1', '/path/to/screen2']
};
if (caseData.skipped)
assert.skipped = true;
if (caseData.failure && caseData.failure.length > 0)
assert.failure = caseData.failure[0].$.message;
if (caseData['system-out']) {
var sspaths = getScreenshotPaths(caseData['system-out']);
sspaths.map(function(sspath) {
if (options.relativeScreenshots) {
sspath = getRelativePath(options.fullOutputFilename, sspath);
}
assert.screenshots.push(sspath);
});
}
assert.isFailure = assert.failure;
suite.cases.push(assert);
if (assert.isFailure)
suite.isFailure = true;
});
if (suite.isFailure)
pkg.isFailure = true;
});
run.addPackage(pkg);
});
done(null, run);
}
|
javascript
|
function(results, run, options, done) {
_.each(results, function(result) {
var pkg = {
name: result.testsuites.$.name,
tests: parse(result.testsuites.$.tests),
failures: parse(result.testsuites.$.failures),
suites: []
};
pkg.isFailure = pkg.failures > 0;
var filename = result.filename;
_.each(result.testsuites.testsuite, function(suiteData) {
var $ = suiteData.$;
var suite = {
name: $.name,
pkgName: $.package,
failures: parse($.failures),
errors: parse($.errors),
skipped: parse($.skipped),
tests: parse($.tests),
cases: []
};
// Sometimes the package name isn't in the
// xml reports...
if (!pkg.name) {
if (result.testsuites.filename) {
pkg.name = result.testsuites.filename;
} else {
pkg.name = suite.pkgName;
}
} else {
if (result.testsuites.filename) {
pkg.name = result.testsuites.filename + '-' + pkg.name;
}
}
suite.passed = suite.tests - suite.errors - suite.failures;
suite.isFailure = suite.errors > 0 || suite.failures > 0;
suite.errmessages = $['system-err'];
pkg.suites.push(suite);
_.each(suiteData.testcase, function(caseData) {
var assert = {
message: caseData.$.name,
time: caseData.$.time,
stacktrace: '',
failure: false,
skipped: false,
screenshots: []
// failure: false or failure message,
// screenshots: ['path/to/screen1', '/path/to/screen2']
};
if (caseData.skipped)
assert.skipped = true;
if (caseData.failure && caseData.failure.length > 0)
assert.failure = caseData.failure[0].$.message;
if (caseData['system-out']) {
var sspaths = getScreenshotPaths(caseData['system-out']);
sspaths.map(function(sspath) {
if (options.relativeScreenshots) {
sspath = getRelativePath(options.fullOutputFilename, sspath);
}
assert.screenshots.push(sspath);
});
}
assert.isFailure = assert.failure;
suite.cases.push(assert);
if (assert.isFailure)
suite.isFailure = true;
});
if (suite.isFailure)
pkg.isFailure = true;
});
run.addPackage(pkg);
});
done(null, run);
}
|
[
"function",
"(",
"results",
",",
"run",
",",
"options",
",",
"done",
")",
"{",
"_",
".",
"each",
"(",
"results",
",",
"function",
"(",
"result",
")",
"{",
"var",
"pkg",
"=",
"{",
"name",
":",
"result",
".",
"testsuites",
".",
"$",
".",
"name",
",",
"tests",
":",
"parse",
"(",
"result",
".",
"testsuites",
".",
"$",
".",
"tests",
")",
",",
"failures",
":",
"parse",
"(",
"result",
".",
"testsuites",
".",
"$",
".",
"failures",
")",
",",
"suites",
":",
"[",
"]",
"}",
";",
"pkg",
".",
"isFailure",
"=",
"pkg",
".",
"failures",
">",
"0",
";",
"var",
"filename",
"=",
"result",
".",
"filename",
";",
"_",
".",
"each",
"(",
"result",
".",
"testsuites",
".",
"testsuite",
",",
"function",
"(",
"suiteData",
")",
"{",
"var",
"$",
"=",
"suiteData",
".",
"$",
";",
"var",
"suite",
"=",
"{",
"name",
":",
"$",
".",
"name",
",",
"pkgName",
":",
"$",
".",
"package",
",",
"failures",
":",
"parse",
"(",
"$",
".",
"failures",
")",
",",
"errors",
":",
"parse",
"(",
"$",
".",
"errors",
")",
",",
"skipped",
":",
"parse",
"(",
"$",
".",
"skipped",
")",
",",
"tests",
":",
"parse",
"(",
"$",
".",
"tests",
")",
",",
"cases",
":",
"[",
"]",
"}",
";",
"// Sometimes the package name isn't in the",
"// xml reports...",
"if",
"(",
"!",
"pkg",
".",
"name",
")",
"{",
"if",
"(",
"result",
".",
"testsuites",
".",
"filename",
")",
"{",
"pkg",
".",
"name",
"=",
"result",
".",
"testsuites",
".",
"filename",
";",
"}",
"else",
"{",
"pkg",
".",
"name",
"=",
"suite",
".",
"pkgName",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"result",
".",
"testsuites",
".",
"filename",
")",
"{",
"pkg",
".",
"name",
"=",
"result",
".",
"testsuites",
".",
"filename",
"+",
"'-'",
"+",
"pkg",
".",
"name",
";",
"}",
"}",
"suite",
".",
"passed",
"=",
"suite",
".",
"tests",
"-",
"suite",
".",
"errors",
"-",
"suite",
".",
"failures",
";",
"suite",
".",
"isFailure",
"=",
"suite",
".",
"errors",
">",
"0",
"||",
"suite",
".",
"failures",
">",
"0",
";",
"suite",
".",
"errmessages",
"=",
"$",
"[",
"'system-err'",
"]",
";",
"pkg",
".",
"suites",
".",
"push",
"(",
"suite",
")",
";",
"_",
".",
"each",
"(",
"suiteData",
".",
"testcase",
",",
"function",
"(",
"caseData",
")",
"{",
"var",
"assert",
"=",
"{",
"message",
":",
"caseData",
".",
"$",
".",
"name",
",",
"time",
":",
"caseData",
".",
"$",
".",
"time",
",",
"stacktrace",
":",
"''",
",",
"failure",
":",
"false",
",",
"skipped",
":",
"false",
",",
"screenshots",
":",
"[",
"]",
"// failure: false or failure message,",
"// screenshots: ['path/to/screen1', '/path/to/screen2']",
"}",
";",
"if",
"(",
"caseData",
".",
"skipped",
")",
"assert",
".",
"skipped",
"=",
"true",
";",
"if",
"(",
"caseData",
".",
"failure",
"&&",
"caseData",
".",
"failure",
".",
"length",
">",
"0",
")",
"assert",
".",
"failure",
"=",
"caseData",
".",
"failure",
"[",
"0",
"]",
".",
"$",
".",
"message",
";",
"if",
"(",
"caseData",
"[",
"'system-out'",
"]",
")",
"{",
"var",
"sspaths",
"=",
"getScreenshotPaths",
"(",
"caseData",
"[",
"'system-out'",
"]",
")",
";",
"sspaths",
".",
"map",
"(",
"function",
"(",
"sspath",
")",
"{",
"if",
"(",
"options",
".",
"relativeScreenshots",
")",
"{",
"sspath",
"=",
"getRelativePath",
"(",
"options",
".",
"fullOutputFilename",
",",
"sspath",
")",
";",
"}",
"assert",
".",
"screenshots",
".",
"push",
"(",
"sspath",
")",
";",
"}",
")",
";",
"}",
"assert",
".",
"isFailure",
"=",
"assert",
".",
"failure",
";",
"suite",
".",
"cases",
".",
"push",
"(",
"assert",
")",
";",
"if",
"(",
"assert",
".",
"isFailure",
")",
"suite",
".",
"isFailure",
"=",
"true",
";",
"}",
")",
";",
"if",
"(",
"suite",
".",
"isFailure",
")",
"pkg",
".",
"isFailure",
"=",
"true",
";",
"}",
")",
";",
"run",
".",
"addPackage",
"(",
"pkg",
")",
";",
"}",
")",
";",
"done",
"(",
"null",
",",
"run",
")",
";",
"}"
] |
Converts a object parsed from XML report files into models.
|
[
"Converts",
"a",
"object",
"parsed",
"from",
"XML",
"report",
"files",
"into",
"models",
"."
] |
6214bcf627dead978f7aea368a6f0fe31d9a5415
|
https://github.com/jls/nightwatch-html-reporter/blob/6214bcf627dead978f7aea368a6f0fe31d9a5415/lib/normalize.js#L58-L152
|
|
19,255
|
jls/nightwatch-html-reporter
|
lib/normalize.js
|
function(results, run, options, done) {
run.errmessages = concatErrMessages(run.errmessages, results.errmessages);
_.forOwn(results.modules, function(pkg, pkgName) {
var npkg = {
name: pkgName,
suites: [],
tests: pkg.tests,
failures: pkg.failures,
errors: pkg.errors,
isFailure: (pkg.failures !== 0 && pkg.errors !== 0)
};
_.forOwn(pkg.completed, function(suite, suiteName) {
var nsuite = {
name: suiteName,
pkgName: npkg.name,
passed: suite.passed,
failures: suite.failed,
errors: suite.errors,
skipped: suite.skipped,
time: suite.time,
cases: []
};
// Little weird here but the report object
// will not report an error, it will instead
// have X failed and empty assertions array.
if (nsuite.failures > 0 && suite.assertions.length === 0)
nsuite.errors = nsuite.failures;
nsuite.isFailure = nsuite.failures !== 0 || nsuite.errors !== 0;
npkg.suites.push(nsuite);
_.each(suite.assertions, function(assertion) {
var assert = _.clone(assertion, true);
assert.screenshots = assert.screenshots || [];
assert.isFailure = assertion.failure;
nsuite.cases.push(assert);
if (options.relativeScreenshots) {
assert.screenshots = assert.screenshots.map(function(sspath) {
return getRelativePath(options.fullOutputFilename, sspath);
});
}
if (assert.isFailure)
nsuite.isFailure = true;
});
if (nsuite.isFailure)
npkg.isFailure = true;
});
run.addPackage(npkg);
if (npkg.isFailure)
run.isFailure = npkg.isFailure;
});
done(null, run);
}
|
javascript
|
function(results, run, options, done) {
run.errmessages = concatErrMessages(run.errmessages, results.errmessages);
_.forOwn(results.modules, function(pkg, pkgName) {
var npkg = {
name: pkgName,
suites: [],
tests: pkg.tests,
failures: pkg.failures,
errors: pkg.errors,
isFailure: (pkg.failures !== 0 && pkg.errors !== 0)
};
_.forOwn(pkg.completed, function(suite, suiteName) {
var nsuite = {
name: suiteName,
pkgName: npkg.name,
passed: suite.passed,
failures: suite.failed,
errors: suite.errors,
skipped: suite.skipped,
time: suite.time,
cases: []
};
// Little weird here but the report object
// will not report an error, it will instead
// have X failed and empty assertions array.
if (nsuite.failures > 0 && suite.assertions.length === 0)
nsuite.errors = nsuite.failures;
nsuite.isFailure = nsuite.failures !== 0 || nsuite.errors !== 0;
npkg.suites.push(nsuite);
_.each(suite.assertions, function(assertion) {
var assert = _.clone(assertion, true);
assert.screenshots = assert.screenshots || [];
assert.isFailure = assertion.failure;
nsuite.cases.push(assert);
if (options.relativeScreenshots) {
assert.screenshots = assert.screenshots.map(function(sspath) {
return getRelativePath(options.fullOutputFilename, sspath);
});
}
if (assert.isFailure)
nsuite.isFailure = true;
});
if (nsuite.isFailure)
npkg.isFailure = true;
});
run.addPackage(npkg);
if (npkg.isFailure)
run.isFailure = npkg.isFailure;
});
done(null, run);
}
|
[
"function",
"(",
"results",
",",
"run",
",",
"options",
",",
"done",
")",
"{",
"run",
".",
"errmessages",
"=",
"concatErrMessages",
"(",
"run",
".",
"errmessages",
",",
"results",
".",
"errmessages",
")",
";",
"_",
".",
"forOwn",
"(",
"results",
".",
"modules",
",",
"function",
"(",
"pkg",
",",
"pkgName",
")",
"{",
"var",
"npkg",
"=",
"{",
"name",
":",
"pkgName",
",",
"suites",
":",
"[",
"]",
",",
"tests",
":",
"pkg",
".",
"tests",
",",
"failures",
":",
"pkg",
".",
"failures",
",",
"errors",
":",
"pkg",
".",
"errors",
",",
"isFailure",
":",
"(",
"pkg",
".",
"failures",
"!==",
"0",
"&&",
"pkg",
".",
"errors",
"!==",
"0",
")",
"}",
";",
"_",
".",
"forOwn",
"(",
"pkg",
".",
"completed",
",",
"function",
"(",
"suite",
",",
"suiteName",
")",
"{",
"var",
"nsuite",
"=",
"{",
"name",
":",
"suiteName",
",",
"pkgName",
":",
"npkg",
".",
"name",
",",
"passed",
":",
"suite",
".",
"passed",
",",
"failures",
":",
"suite",
".",
"failed",
",",
"errors",
":",
"suite",
".",
"errors",
",",
"skipped",
":",
"suite",
".",
"skipped",
",",
"time",
":",
"suite",
".",
"time",
",",
"cases",
":",
"[",
"]",
"}",
";",
"// Little weird here but the report object",
"// will not report an error, it will instead",
"// have X failed and empty assertions array.",
"if",
"(",
"nsuite",
".",
"failures",
">",
"0",
"&&",
"suite",
".",
"assertions",
".",
"length",
"===",
"0",
")",
"nsuite",
".",
"errors",
"=",
"nsuite",
".",
"failures",
";",
"nsuite",
".",
"isFailure",
"=",
"nsuite",
".",
"failures",
"!==",
"0",
"||",
"nsuite",
".",
"errors",
"!==",
"0",
";",
"npkg",
".",
"suites",
".",
"push",
"(",
"nsuite",
")",
";",
"_",
".",
"each",
"(",
"suite",
".",
"assertions",
",",
"function",
"(",
"assertion",
")",
"{",
"var",
"assert",
"=",
"_",
".",
"clone",
"(",
"assertion",
",",
"true",
")",
";",
"assert",
".",
"screenshots",
"=",
"assert",
".",
"screenshots",
"||",
"[",
"]",
";",
"assert",
".",
"isFailure",
"=",
"assertion",
".",
"failure",
";",
"nsuite",
".",
"cases",
".",
"push",
"(",
"assert",
")",
";",
"if",
"(",
"options",
".",
"relativeScreenshots",
")",
"{",
"assert",
".",
"screenshots",
"=",
"assert",
".",
"screenshots",
".",
"map",
"(",
"function",
"(",
"sspath",
")",
"{",
"return",
"getRelativePath",
"(",
"options",
".",
"fullOutputFilename",
",",
"sspath",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"assert",
".",
"isFailure",
")",
"nsuite",
".",
"isFailure",
"=",
"true",
";",
"}",
")",
";",
"if",
"(",
"nsuite",
".",
"isFailure",
")",
"npkg",
".",
"isFailure",
"=",
"true",
";",
"}",
")",
";",
"run",
".",
"addPackage",
"(",
"npkg",
")",
";",
"if",
"(",
"npkg",
".",
"isFailure",
")",
"run",
".",
"isFailure",
"=",
"npkg",
".",
"isFailure",
";",
"}",
")",
";",
"done",
"(",
"null",
",",
"run",
")",
";",
"}"
] |
Converts an object given to us by nightwatch into models.
|
[
"Converts",
"an",
"object",
"given",
"to",
"us",
"by",
"nightwatch",
"into",
"models",
"."
] |
6214bcf627dead978f7aea368a6f0fe31d9a5415
|
https://github.com/jls/nightwatch-html-reporter/blob/6214bcf627dead978f7aea368a6f0fe31d9a5415/lib/normalize.js#L156-L224
|
|
19,256
|
auth0/auth0-guardian.js
|
lib/entities/enrollment.js
|
enrollment
|
function enrollment(data) {
var self = object.create(enrollment.prototype);
self.data = data;
return self;
}
|
javascript
|
function enrollment(data) {
var self = object.create(enrollment.prototype);
self.data = data;
return self;
}
|
[
"function",
"enrollment",
"(",
"data",
")",
"{",
"var",
"self",
"=",
"object",
".",
"create",
"(",
"enrollment",
".",
"prototype",
")",
";",
"self",
".",
"data",
"=",
"data",
";",
"return",
"self",
";",
"}"
] |
Represents a complete enrollment with its associated data
@param {string} [data.name] Enrollment name
@param {string} [data.phoneNumber] Enrollment phone number (masked)
@param {array.<sms|push|otp>} data.availableAuthenticatorTypes
@public
@returns {Enrollment}
|
[
"Represents",
"a",
"complete",
"enrollment",
"with",
"its",
"associated",
"data"
] |
c0823e588456e3578f5a18a3a2bff56b334c740d
|
https://github.com/auth0/auth0-guardian.js/blob/c0823e588456e3578f5a18a3a2bff56b334c740d/lib/entities/enrollment.js#L15-L21
|
19,257
|
auth0/auth0-guardian.js
|
lib/utils/socket_client.js
|
socketClient
|
function socketClient(serviceUrl) {
var self = object.create(socketClient.prototype);
var urlObject = url.parse(serviceUrl);
// create the url without the path
var socketIoUrl = url.format({
protocol: urlObject.protocol,
hostname: urlObject.hostname
});
var options = {
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 50000,
reconnectionAttempts: 5,
autoConnect: false,
path: url.clearTraliningSlash(urlObject.path) + '/socket.io/'
};
self.socket = io(socketIoUrl, options);
self.opened = false;
return self;
}
|
javascript
|
function socketClient(serviceUrl) {
var self = object.create(socketClient.prototype);
var urlObject = url.parse(serviceUrl);
// create the url without the path
var socketIoUrl = url.format({
protocol: urlObject.protocol,
hostname: urlObject.hostname
});
var options = {
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 50000,
reconnectionAttempts: 5,
autoConnect: false,
path: url.clearTraliningSlash(urlObject.path) + '/socket.io/'
};
self.socket = io(socketIoUrl, options);
self.opened = false;
return self;
}
|
[
"function",
"socketClient",
"(",
"serviceUrl",
")",
"{",
"var",
"self",
"=",
"object",
".",
"create",
"(",
"socketClient",
".",
"prototype",
")",
";",
"var",
"urlObject",
"=",
"url",
".",
"parse",
"(",
"serviceUrl",
")",
";",
"// create the url without the path",
"var",
"socketIoUrl",
"=",
"url",
".",
"format",
"(",
"{",
"protocol",
":",
"urlObject",
".",
"protocol",
",",
"hostname",
":",
"urlObject",
".",
"hostname",
"}",
")",
";",
"var",
"options",
"=",
"{",
"reconnection",
":",
"true",
",",
"reconnectionDelay",
":",
"1000",
",",
"reconnectionDelayMax",
":",
"50000",
",",
"reconnectionAttempts",
":",
"5",
",",
"autoConnect",
":",
"false",
",",
"path",
":",
"url",
".",
"clearTraliningSlash",
"(",
"urlObject",
".",
"path",
")",
"+",
"'/socket.io/'",
"}",
";",
"self",
".",
"socket",
"=",
"io",
"(",
"socketIoUrl",
",",
"options",
")",
";",
"self",
".",
"opened",
"=",
"false",
";",
"return",
"self",
";",
"}"
] |
Construct a socket io client based on a serviceUrl
@param {string} serviceUrl
@return {socketClient}
|
[
"Construct",
"a",
"socket",
"io",
"client",
"based",
"on",
"a",
"serviceUrl"
] |
c0823e588456e3578f5a18a3a2bff56b334c740d
|
https://github.com/auth0/auth0-guardian.js/blob/c0823e588456e3578f5a18a3a2bff56b334c740d/lib/utils/socket_client.js#L17-L40
|
19,258
|
auth0/auth0-guardian.js
|
lib/entities/enrollment_attempt.js
|
enrollmentAttempt
|
function enrollmentAttempt(data, active) {
var self = object.create(enrollmentAttempt.prototype);
self.data = data;
self.active = active || false;
return self;
}
|
javascript
|
function enrollmentAttempt(data, active) {
var self = object.create(enrollmentAttempt.prototype);
self.data = data;
self.active = active || false;
return self;
}
|
[
"function",
"enrollmentAttempt",
"(",
"data",
",",
"active",
")",
"{",
"var",
"self",
"=",
"object",
".",
"create",
"(",
"enrollmentAttempt",
".",
"prototype",
")",
";",
"self",
".",
"data",
"=",
"data",
";",
"self",
".",
"active",
"=",
"active",
"||",
"false",
";",
"return",
"self",
";",
"}"
] |
Represents a not-yet-complete enrollment; once it is complete an enrollment
will be created instead
@param {string} data.enrollmentTxId
@param {string} data.otpSecret
@param {string} data.issuer.name
@param {string} data.issuer.label
@param {string} data.recoveryCode
@param {string} data.baseUrl
@param {string} data.enrollmentId
@param {boolean} active
@private
|
[
"Represents",
"a",
"not",
"-",
"yet",
"-",
"complete",
"enrollment",
";",
"once",
"it",
"is",
"complete",
"an",
"enrollment",
"will",
"be",
"created",
"instead"
] |
c0823e588456e3578f5a18a3a2bff56b334c740d
|
https://github.com/auth0/auth0-guardian.js/blob/c0823e588456e3578f5a18a3a2bff56b334c740d/lib/entities/enrollment_attempt.js#L21-L28
|
19,259
|
auth0/auth0-guardian.js
|
lib/utils/event_sequencer.js
|
eventSequencer
|
function eventSequencer() {
var self = object.create(eventSequencer.prototype);
EventEmitter.call(self);
self.sequences = {};
self.received = {};
self.pipedEmitter = null;
return self;
}
|
javascript
|
function eventSequencer() {
var self = object.create(eventSequencer.prototype);
EventEmitter.call(self);
self.sequences = {};
self.received = {};
self.pipedEmitter = null;
return self;
}
|
[
"function",
"eventSequencer",
"(",
")",
"{",
"var",
"self",
"=",
"object",
".",
"create",
"(",
"eventSequencer",
".",
"prototype",
")",
";",
"EventEmitter",
".",
"call",
"(",
"self",
")",
";",
"self",
".",
"sequences",
"=",
"{",
"}",
";",
"self",
".",
"received",
"=",
"{",
"}",
";",
"self",
".",
"pipedEmitter",
"=",
"null",
";",
"return",
"self",
";",
"}"
] |
Controls the sequence of events, accepts events in any sequence and re-emits
them in the right sequence once it gets all the events in the sequence.
If no sequence is defined the event is re-emitted immediatelly.
Useful to abstract transport layer timming issues and garantee a given
event sequence
Assumed that there is a single event of each time on each the sequence
The sequences are assumed to be compatible, that is to say the sequence of
shared events must be the same in every sequence
|
[
"Controls",
"the",
"sequence",
"of",
"events",
"accepts",
"events",
"in",
"any",
"sequence",
"and",
"re",
"-",
"emits",
"them",
"in",
"the",
"right",
"sequence",
"once",
"it",
"gets",
"all",
"the",
"events",
"in",
"the",
"sequence",
".",
"If",
"no",
"sequence",
"is",
"defined",
"the",
"event",
"is",
"re",
"-",
"emitted",
"immediatelly",
"."
] |
c0823e588456e3578f5a18a3a2bff56b334c740d
|
https://github.com/auth0/auth0-guardian.js/blob/c0823e588456e3578f5a18a3a2bff56b334c740d/lib/utils/event_sequencer.js#L18-L28
|
19,260
|
auth0/auth0-guardian.js
|
lib/utils/http_client.js
|
httpClient
|
function httpClient(baseUrl, globalTrackingId) {
var self = object.create(httpClient.prototype);
self.baseUrl = baseUrl;
self.globalTrackingId = globalTrackingId;
return self;
}
|
javascript
|
function httpClient(baseUrl, globalTrackingId) {
var self = object.create(httpClient.prototype);
self.baseUrl = baseUrl;
self.globalTrackingId = globalTrackingId;
return self;
}
|
[
"function",
"httpClient",
"(",
"baseUrl",
",",
"globalTrackingId",
")",
"{",
"var",
"self",
"=",
"object",
".",
"create",
"(",
"httpClient",
".",
"prototype",
")",
";",
"self",
".",
"baseUrl",
"=",
"baseUrl",
";",
"self",
".",
"globalTrackingId",
"=",
"globalTrackingId",
";",
"return",
"self",
";",
"}"
] |
HTTP Client library
@param {string} baseUrl to be format with url.format
@param {string} [globalTrackingId] id uses to associate the request with the
secuence of request in multiple services (just for debugging purposes)
|
[
"HTTP",
"Client",
"library"
] |
c0823e588456e3578f5a18a3a2bff56b334c740d
|
https://github.com/auth0/auth0-guardian.js/blob/c0823e588456e3578f5a18a3a2bff56b334c740d/lib/utils/http_client.js#L15-L22
|
19,261
|
auth0/auth0-guardian.js
|
lib/utils/event_listener_hub.js
|
eventListenerHub
|
function eventListenerHub(emitter, eventName) {
var self = object.create(eventListenerHub.prototype);
self.emitter = emitter;
self.eventName = eventName;
self.handlers = [];
self.defaultHandlerFn = null;
return self;
}
|
javascript
|
function eventListenerHub(emitter, eventName) {
var self = object.create(eventListenerHub.prototype);
self.emitter = emitter;
self.eventName = eventName;
self.handlers = [];
self.defaultHandlerFn = null;
return self;
}
|
[
"function",
"eventListenerHub",
"(",
"emitter",
",",
"eventName",
")",
"{",
"var",
"self",
"=",
"object",
".",
"create",
"(",
"eventListenerHub",
".",
"prototype",
")",
";",
"self",
".",
"emitter",
"=",
"emitter",
";",
"self",
".",
"eventName",
"=",
"eventName",
";",
"self",
".",
"handlers",
"=",
"[",
"]",
";",
"self",
".",
"defaultHandlerFn",
"=",
"null",
";",
"return",
"self",
";",
"}"
] |
A hub keeps track of an event and its listeners on a particular context and
is able to manage them on that context
@param {EventEmitter} emitter
@param {string} eventName
|
[
"A",
"hub",
"keeps",
"track",
"of",
"an",
"event",
"and",
"its",
"listeners",
"on",
"a",
"particular",
"context",
"and",
"is",
"able",
"to",
"manage",
"them",
"on",
"that",
"context"
] |
c0823e588456e3578f5a18a3a2bff56b334c740d
|
https://github.com/auth0/auth0-guardian.js/blob/c0823e588456e3578f5a18a3a2bff56b334c740d/lib/utils/event_listener_hub.js#L12-L21
|
19,262
|
digitalbazaar/jsonld-signatures
|
lib/ProofSet.js
|
_addToJSON
|
function _addToJSON(error) {
Object.defineProperty(error, 'toJSON', {
value: function() {
return serializeError(this);
},
configurable: true,
writable: true
});
}
|
javascript
|
function _addToJSON(error) {
Object.defineProperty(error, 'toJSON', {
value: function() {
return serializeError(this);
},
configurable: true,
writable: true
});
}
|
[
"function",
"_addToJSON",
"(",
"error",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"error",
",",
"'toJSON'",
",",
"{",
"value",
":",
"function",
"(",
")",
"{",
"return",
"serializeError",
"(",
"this",
")",
";",
"}",
",",
"configurable",
":",
"true",
",",
"writable",
":",
"true",
"}",
")",
";",
"}"
] |
add a `toJSON` method to an error which allows for errors in validation reports to be serialized properly by `JSON.stringify`.
|
[
"add",
"a",
"toJSON",
"method",
"to",
"an",
"error",
"which",
"allows",
"for",
"errors",
"in",
"validation",
"reports",
"to",
"be",
"serialized",
"properly",
"by",
"JSON",
".",
"stringify",
"."
] |
c2e995a4ff27279a37fcacf55ca131cef2b8c5e4
|
https://github.com/digitalbazaar/jsonld-signatures/blob/c2e995a4ff27279a37fcacf55ca131cef2b8c5e4/lib/ProofSet.js#L341-L349
|
19,263
|
nativescript-vue/nativescript-vue-devtools
|
index.js
|
getServerIpAddress
|
function getServerIpAddress(host, port) {
if (host) {
return `${host}:${port}`
}
if (isAndroid) {
const FINGERPRINT = android.os.Build.FINGERPRINT
if (FINGERPRINT.includes("vbox")) {
// running on genymotion
return `10.0.3.2:${port}`
} else if (FINGERPRINT.includes("generic")) {
// running on android emulator
return `10.0.2.2:${port}`
}
}
// ios simulator uses localhost
return `127.0.0.1:${port}`
}
|
javascript
|
function getServerIpAddress(host, port) {
if (host) {
return `${host}:${port}`
}
if (isAndroid) {
const FINGERPRINT = android.os.Build.FINGERPRINT
if (FINGERPRINT.includes("vbox")) {
// running on genymotion
return `10.0.3.2:${port}`
} else if (FINGERPRINT.includes("generic")) {
// running on android emulator
return `10.0.2.2:${port}`
}
}
// ios simulator uses localhost
return `127.0.0.1:${port}`
}
|
[
"function",
"getServerIpAddress",
"(",
"host",
",",
"port",
")",
"{",
"if",
"(",
"host",
")",
"{",
"return",
"`",
"${",
"host",
"}",
"${",
"port",
"}",
"`",
"}",
"if",
"(",
"isAndroid",
")",
"{",
"const",
"FINGERPRINT",
"=",
"android",
".",
"os",
".",
"Build",
".",
"FINGERPRINT",
"if",
"(",
"FINGERPRINT",
".",
"includes",
"(",
"\"vbox\"",
")",
")",
"{",
"// running on genymotion",
"return",
"`",
"${",
"port",
"}",
"`",
"}",
"else",
"if",
"(",
"FINGERPRINT",
".",
"includes",
"(",
"\"generic\"",
")",
")",
"{",
"// running on android emulator",
"return",
"`",
"${",
"port",
"}",
"`",
"}",
"}",
"// ios simulator uses localhost",
"return",
"`",
"${",
"port",
"}",
"`",
"}"
] |
Returns the correct address for the host machine when running on emulator
@param host
@param port
@returns {string}
|
[
"Returns",
"the",
"correct",
"address",
"for",
"the",
"host",
"machine",
"when",
"running",
"on",
"emulator"
] |
dc876038d56bb7ae9a1a0f4d77b546d2c41b03e1
|
https://github.com/nativescript-vue/nativescript-vue-devtools/blob/dc876038d56bb7ae9a1a0f4d77b546d2c41b03e1/index.js#L28-L46
|
19,264
|
opentripplanner/otp-react-redux
|
lib/actions/api.js
|
createQueryAction
|
function createQueryAction (endpoint, responseAction, errorAction, rewritePayload, postprocess) {
return async function (dispatch, getState) {
const otpState = getState().otp
const api = otpState.config.api
const url = `${api.host}${api.port ? ':' + api.port : ''}${api.path}/${endpoint}`
let payload
try {
const response = await fetch(url)
if (response.status >= 400) {
const error = new Error('Received error from server')
error.response = response
throw error
}
payload = await response.json()
} catch (err) {
return dispatch(errorAction(err))
}
if (typeof rewritePayload === 'function') {
dispatch(responseAction(rewritePayload(payload)))
} else {
dispatch(responseAction(payload))
}
if (typeof postprocess === 'function') {
postprocess(payload, dispatch, getState)
}
}
}
|
javascript
|
function createQueryAction (endpoint, responseAction, errorAction, rewritePayload, postprocess) {
return async function (dispatch, getState) {
const otpState = getState().otp
const api = otpState.config.api
const url = `${api.host}${api.port ? ':' + api.port : ''}${api.path}/${endpoint}`
let payload
try {
const response = await fetch(url)
if (response.status >= 400) {
const error = new Error('Received error from server')
error.response = response
throw error
}
payload = await response.json()
} catch (err) {
return dispatch(errorAction(err))
}
if (typeof rewritePayload === 'function') {
dispatch(responseAction(rewritePayload(payload)))
} else {
dispatch(responseAction(payload))
}
if (typeof postprocess === 'function') {
postprocess(payload, dispatch, getState)
}
}
}
|
[
"function",
"createQueryAction",
"(",
"endpoint",
",",
"responseAction",
",",
"errorAction",
",",
"rewritePayload",
",",
"postprocess",
")",
"{",
"return",
"async",
"function",
"(",
"dispatch",
",",
"getState",
")",
"{",
"const",
"otpState",
"=",
"getState",
"(",
")",
".",
"otp",
"const",
"api",
"=",
"otpState",
".",
"config",
".",
"api",
"const",
"url",
"=",
"`",
"${",
"api",
".",
"host",
"}",
"${",
"api",
".",
"port",
"?",
"':'",
"+",
"api",
".",
"port",
":",
"''",
"}",
"${",
"api",
".",
"path",
"}",
"${",
"endpoint",
"}",
"`",
"let",
"payload",
"try",
"{",
"const",
"response",
"=",
"await",
"fetch",
"(",
"url",
")",
"if",
"(",
"response",
".",
"status",
">=",
"400",
")",
"{",
"const",
"error",
"=",
"new",
"Error",
"(",
"'Received error from server'",
")",
"error",
".",
"response",
"=",
"response",
"throw",
"error",
"}",
"payload",
"=",
"await",
"response",
".",
"json",
"(",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"dispatch",
"(",
"errorAction",
"(",
"err",
")",
")",
"}",
"if",
"(",
"typeof",
"rewritePayload",
"===",
"'function'",
")",
"{",
"dispatch",
"(",
"responseAction",
"(",
"rewritePayload",
"(",
"payload",
")",
")",
")",
"}",
"else",
"{",
"dispatch",
"(",
"responseAction",
"(",
"payload",
")",
")",
"}",
"if",
"(",
"typeof",
"postprocess",
"===",
"'function'",
")",
"{",
"postprocess",
"(",
"payload",
",",
"dispatch",
",",
"getState",
")",
"}",
"}",
"}"
] |
generic helper for constructing API queries
|
[
"generic",
"helper",
"for",
"constructing",
"API",
"queries"
] |
bf31d167b42e99262380321ae4f07deb18fce29a
|
https://github.com/opentripplanner/otp-react-redux/blob/bf31d167b42e99262380321ae4f07deb18fce29a/lib/actions/api.js#L346-L374
|
19,265
|
opentripplanner/otp-react-redux
|
lib/components/viewers/stop-viewer.js
|
getStatusLabel
|
function getStatusLabel (delay) {
// late departure
if (delay > 60) {
return (
<div className='status-label' style={{ backgroundColor: '#d9534f' }}>
{formatDuration(delay)} Late
</div>
)
}
// early departure
if (delay < -60) {
return (
<div className='status-label' style={{ backgroundColor: '#337ab7' }}>
{formatDuration(Math.abs(delay))} Early
</div>
)
}
// on-time departure
return (
<div className='status-label' style={{ backgroundColor: '#5cb85c' }}>
On Time
</div>
)
}
|
javascript
|
function getStatusLabel (delay) {
// late departure
if (delay > 60) {
return (
<div className='status-label' style={{ backgroundColor: '#d9534f' }}>
{formatDuration(delay)} Late
</div>
)
}
// early departure
if (delay < -60) {
return (
<div className='status-label' style={{ backgroundColor: '#337ab7' }}>
{formatDuration(Math.abs(delay))} Early
</div>
)
}
// on-time departure
return (
<div className='status-label' style={{ backgroundColor: '#5cb85c' }}>
On Time
</div>
)
}
|
[
"function",
"getStatusLabel",
"(",
"delay",
")",
"{",
"// late departure",
"if",
"(",
"delay",
">",
"60",
")",
"{",
"return",
"(",
"<",
"div",
"className",
"=",
"'status-label'",
"style",
"=",
"{",
"{",
"backgroundColor",
":",
"'#d9534f'",
"}",
"}",
">",
"\n ",
"{",
"formatDuration",
"(",
"delay",
")",
"}",
" Late\n ",
"<",
"/",
"div",
">",
")",
"}",
"// early departure",
"if",
"(",
"delay",
"<",
"-",
"60",
")",
"{",
"return",
"(",
"<",
"div",
"className",
"=",
"'status-label'",
"style",
"=",
"{",
"{",
"backgroundColor",
":",
"'#337ab7'",
"}",
"}",
">",
"\n ",
"{",
"formatDuration",
"(",
"Math",
".",
"abs",
"(",
"delay",
")",
")",
"}",
" Early\n ",
"<",
"/",
"div",
">",
")",
"}",
"// on-time departure",
"return",
"(",
"<",
"div",
"className",
"=",
"'status-label'",
"style",
"=",
"{",
"{",
"backgroundColor",
":",
"'#5cb85c'",
"}",
"}",
">",
"\n On Time\n ",
"<",
"/",
"div",
">",
")",
"}"
] |
helper method to generate status label
|
[
"helper",
"method",
"to",
"generate",
"status",
"label"
] |
bf31d167b42e99262380321ae4f07deb18fce29a
|
https://github.com/opentripplanner/otp-react-redux/blob/bf31d167b42e99262380321ae4f07deb18fce29a/lib/components/viewers/stop-viewer.js#L247-L272
|
19,266
|
opentripplanner/otp-react-redux
|
lib/components/map/stylized-map.js
|
mergeTransitiveStyles
|
function mergeTransitiveStyles (base, extended) {
const styles = Object.assign({}, base)
for (const key in extended) {
if (key in base) styles[key] = Object.assign({}, styles[key], extended[key])
else styles[key] = extended[key]
}
return styles
}
|
javascript
|
function mergeTransitiveStyles (base, extended) {
const styles = Object.assign({}, base)
for (const key in extended) {
if (key in base) styles[key] = Object.assign({}, styles[key], extended[key])
else styles[key] = extended[key]
}
return styles
}
|
[
"function",
"mergeTransitiveStyles",
"(",
"base",
",",
"extended",
")",
"{",
"const",
"styles",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"base",
")",
"for",
"(",
"const",
"key",
"in",
"extended",
")",
"{",
"if",
"(",
"key",
"in",
"base",
")",
"styles",
"[",
"key",
"]",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"styles",
"[",
"key",
"]",
",",
"extended",
"[",
"key",
"]",
")",
"else",
"styles",
"[",
"key",
"]",
"=",
"extended",
"[",
"key",
"]",
"}",
"return",
"styles",
"}"
] |
extend common transitive styles for stylized map view
|
[
"extend",
"common",
"transitive",
"styles",
"for",
"stylized",
"map",
"view"
] |
bf31d167b42e99262380321ae4f07deb18fce29a
|
https://github.com/opentripplanner/otp-react-redux/blob/bf31d167b42e99262380321ae4f07deb18fce29a/lib/components/map/stylized-map.js#L46-L53
|
19,267
|
bitovi/testee
|
lib/reporter/index.js
|
Reporter
|
function Reporter(MochaReporter, coverage, root, reporterOptions) {
if(typeof MochaReporter === 'string') {
if(mocha.reporters[MochaReporter]) {
MochaReporter = mocha.reporters[MochaReporter];
} else {
try {
MochaReporter = require(MochaReporter);
} catch (e) {
throw new Error('reporter "' + MochaReporter + '" does not exist');
}
}
}
// The event emitter used to emit the final events
var runner = this.runner = new EventEmitter();
// A store (by data GUID) for the Mocha objects we created.
// The handler for buffering simultaneous test runs
this.buffers = new BufferManager(runner);
// The actual (suite and test) objects we can feed to the Mocha runner
this._mochaObjects = {};
// The instantiated Mocha reporter
this.reporter = new MochaReporter(runner, {reporterOptions: reporterOptions});
// This is where we store errors so that we can report them all
// at once at the end
this.errors = [];
// Options for reporting code coverage
this.coverage = coverage;
// Option for root path
this.root = root;
}
|
javascript
|
function Reporter(MochaReporter, coverage, root, reporterOptions) {
if(typeof MochaReporter === 'string') {
if(mocha.reporters[MochaReporter]) {
MochaReporter = mocha.reporters[MochaReporter];
} else {
try {
MochaReporter = require(MochaReporter);
} catch (e) {
throw new Error('reporter "' + MochaReporter + '" does not exist');
}
}
}
// The event emitter used to emit the final events
var runner = this.runner = new EventEmitter();
// A store (by data GUID) for the Mocha objects we created.
// The handler for buffering simultaneous test runs
this.buffers = new BufferManager(runner);
// The actual (suite and test) objects we can feed to the Mocha runner
this._mochaObjects = {};
// The instantiated Mocha reporter
this.reporter = new MochaReporter(runner, {reporterOptions: reporterOptions});
// This is where we store errors so that we can report them all
// at once at the end
this.errors = [];
// Options for reporting code coverage
this.coverage = coverage;
// Option for root path
this.root = root;
}
|
[
"function",
"Reporter",
"(",
"MochaReporter",
",",
"coverage",
",",
"root",
",",
"reporterOptions",
")",
"{",
"if",
"(",
"typeof",
"MochaReporter",
"===",
"'string'",
")",
"{",
"if",
"(",
"mocha",
".",
"reporters",
"[",
"MochaReporter",
"]",
")",
"{",
"MochaReporter",
"=",
"mocha",
".",
"reporters",
"[",
"MochaReporter",
"]",
";",
"}",
"else",
"{",
"try",
"{",
"MochaReporter",
"=",
"require",
"(",
"MochaReporter",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"throw",
"new",
"Error",
"(",
"'reporter \"'",
"+",
"MochaReporter",
"+",
"'\" does not exist'",
")",
";",
"}",
"}",
"}",
"// The event emitter used to emit the final events",
"var",
"runner",
"=",
"this",
".",
"runner",
"=",
"new",
"EventEmitter",
"(",
")",
";",
"// A store (by data GUID) for the Mocha objects we created.",
"// The handler for buffering simultaneous test runs",
"this",
".",
"buffers",
"=",
"new",
"BufferManager",
"(",
"runner",
")",
";",
"// The actual (suite and test) objects we can feed to the Mocha runner",
"this",
".",
"_mochaObjects",
"=",
"{",
"}",
";",
"// The instantiated Mocha reporter",
"this",
".",
"reporter",
"=",
"new",
"MochaReporter",
"(",
"runner",
",",
"{",
"reporterOptions",
":",
"reporterOptions",
"}",
")",
";",
"// This is where we store errors so that we can report them all",
"// at once at the end",
"this",
".",
"errors",
"=",
"[",
"]",
";",
"// Options for reporting code coverage",
"this",
".",
"coverage",
"=",
"coverage",
";",
"// Option for root path",
"this",
".",
"root",
"=",
"root",
";",
"}"
] |
The reporter listens to service events and reports it to the command line using any of the Mocha reporters.
|
[
"The",
"reporter",
"listens",
"to",
"service",
"events",
"and",
"reports",
"it",
"to",
"the",
"command",
"line",
"using",
"any",
"of",
"the",
"Mocha",
"reporters",
"."
] |
c48fbd35f5c10d17400e6f55b3b3ce3875d1e175
|
https://github.com/bitovi/testee/blob/c48fbd35f5c10d17400e6f55b3b3ce3875d1e175/lib/reporter/index.js#L17-L46
|
19,268
|
bitovi/testee
|
lib/runner.js
|
function (data) {
var isSigned = isTokenSigned(data.file);
var isFinished = data.status === 'finished';
var isComplete = isSigned && isFinished;
debug('checking if run', url, 'is finished', isComplete);
if (isComplete) {
testRuns.removeListener('patched', checkIfRunIsFinished);
resolve(data);
}
}
|
javascript
|
function (data) {
var isSigned = isTokenSigned(data.file);
var isFinished = data.status === 'finished';
var isComplete = isSigned && isFinished;
debug('checking if run', url, 'is finished', isComplete);
if (isComplete) {
testRuns.removeListener('patched', checkIfRunIsFinished);
resolve(data);
}
}
|
[
"function",
"(",
"data",
")",
"{",
"var",
"isSigned",
"=",
"isTokenSigned",
"(",
"data",
".",
"file",
")",
";",
"var",
"isFinished",
"=",
"data",
".",
"status",
"===",
"'finished'",
";",
"var",
"isComplete",
"=",
"isSigned",
"&&",
"isFinished",
";",
"debug",
"(",
"'checking if run'",
",",
"url",
",",
"'is finished'",
",",
"isComplete",
")",
";",
"if",
"(",
"isComplete",
")",
"{",
"testRuns",
".",
"removeListener",
"(",
"'patched'",
",",
"checkIfRunIsFinished",
")",
";",
"resolve",
"(",
"data",
")",
";",
"}",
"}"
] |
The emitted data.file property contains the token we added to the browser URL
|
[
"The",
"emitted",
"data",
".",
"file",
"property",
"contains",
"the",
"token",
"we",
"added",
"to",
"the",
"browser",
"URL"
] |
c48fbd35f5c10d17400e6f55b3b3ce3875d1e175
|
https://github.com/bitovi/testee/blob/c48fbd35f5c10d17400e6f55b3b3ce3875d1e175/lib/runner.js#L32-L41
|
|
19,269
|
ph0bos/express-microservice-starter
|
lib/utils/file-util.js
|
checkFileExistsSync
|
function checkFileExistsSync(filepath){
var flag = true;
try {
fs.accessSync(filepath, fs.F_OK);
} catch(e){
flag = false;
}
return flag;
}
|
javascript
|
function checkFileExistsSync(filepath){
var flag = true;
try {
fs.accessSync(filepath, fs.F_OK);
} catch(e){
flag = false;
}
return flag;
}
|
[
"function",
"checkFileExistsSync",
"(",
"filepath",
")",
"{",
"var",
"flag",
"=",
"true",
";",
"try",
"{",
"fs",
".",
"accessSync",
"(",
"filepath",
",",
"fs",
".",
"F_OK",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"flag",
"=",
"false",
";",
"}",
"return",
"flag",
";",
"}"
] |
Check the existence of the file
|
[
"Check",
"the",
"existence",
"of",
"the",
"file"
] |
44953044e518d7c04319423ed1d8b87225e61343
|
https://github.com/ph0bos/express-microservice-starter/blob/44953044e518d7c04319423ed1d8b87225e61343/lib/utils/file-util.js#L8-L18
|
19,270
|
ph0bos/express-microservice-starter
|
lib/monitors/microservice-monitor.js
|
checkMicroserviceHealth
|
function checkMicroserviceHealth() {
var resolver = Promise.pending();
if (!zoologist.getServiceDiscovery() || !zoologist.getServiceDiscovery().getData()) {
resolver.resolve({
status: (zoologist.getClient().getClient().getState().name === 'SYNC_CONNECTED') ? 'UP' : 'DOWN'
});
return resolver.promise;
}
var health = {
id: zoologist.getServiceDiscovery().getData().id,
status: (zoologist.getClient().getClient().getState().name === 'SYNC_CONNECTED') ? 'UP' : 'DOWN',
name: zoologist.getServiceInstance().getData().name,
basePath: zoologist.getServiceInstance().getData().basePath || DEFAULT_BASE_PATH,
address: zoologist.getServiceInstance().getData().address,
port: zoologist.getServiceInstance().getData().port,
registrationTime: new Date(zoologist.getServiceInstance().getData().registrationTimeUTC)
};
if (health.status === 'UP' && zoologist.getServiceDependencies() && zoologist.getServiceDependencies().length > 0) {
checkDependencies(zoologist.getServiceDependencies(), function(err, dependencies) {
health.dependencies = dependencies;
// If any dependencies have zero count, set service 'DOWN'
Object.keys(dependencies).forEach(function(dependency) {
if (dependencies[dependency] == 0) health.status = 'DOWN';
});
resolver.resolve(health);
});
} else {
resolver.resolve(health);
}
return resolver.promise;
}
|
javascript
|
function checkMicroserviceHealth() {
var resolver = Promise.pending();
if (!zoologist.getServiceDiscovery() || !zoologist.getServiceDiscovery().getData()) {
resolver.resolve({
status: (zoologist.getClient().getClient().getState().name === 'SYNC_CONNECTED') ? 'UP' : 'DOWN'
});
return resolver.promise;
}
var health = {
id: zoologist.getServiceDiscovery().getData().id,
status: (zoologist.getClient().getClient().getState().name === 'SYNC_CONNECTED') ? 'UP' : 'DOWN',
name: zoologist.getServiceInstance().getData().name,
basePath: zoologist.getServiceInstance().getData().basePath || DEFAULT_BASE_PATH,
address: zoologist.getServiceInstance().getData().address,
port: zoologist.getServiceInstance().getData().port,
registrationTime: new Date(zoologist.getServiceInstance().getData().registrationTimeUTC)
};
if (health.status === 'UP' && zoologist.getServiceDependencies() && zoologist.getServiceDependencies().length > 0) {
checkDependencies(zoologist.getServiceDependencies(), function(err, dependencies) {
health.dependencies = dependencies;
// If any dependencies have zero count, set service 'DOWN'
Object.keys(dependencies).forEach(function(dependency) {
if (dependencies[dependency] == 0) health.status = 'DOWN';
});
resolver.resolve(health);
});
} else {
resolver.resolve(health);
}
return resolver.promise;
}
|
[
"function",
"checkMicroserviceHealth",
"(",
")",
"{",
"var",
"resolver",
"=",
"Promise",
".",
"pending",
"(",
")",
";",
"if",
"(",
"!",
"zoologist",
".",
"getServiceDiscovery",
"(",
")",
"||",
"!",
"zoologist",
".",
"getServiceDiscovery",
"(",
")",
".",
"getData",
"(",
")",
")",
"{",
"resolver",
".",
"resolve",
"(",
"{",
"status",
":",
"(",
"zoologist",
".",
"getClient",
"(",
")",
".",
"getClient",
"(",
")",
".",
"getState",
"(",
")",
".",
"name",
"===",
"'SYNC_CONNECTED'",
")",
"?",
"'UP'",
":",
"'DOWN'",
"}",
")",
";",
"return",
"resolver",
".",
"promise",
";",
"}",
"var",
"health",
"=",
"{",
"id",
":",
"zoologist",
".",
"getServiceDiscovery",
"(",
")",
".",
"getData",
"(",
")",
".",
"id",
",",
"status",
":",
"(",
"zoologist",
".",
"getClient",
"(",
")",
".",
"getClient",
"(",
")",
".",
"getState",
"(",
")",
".",
"name",
"===",
"'SYNC_CONNECTED'",
")",
"?",
"'UP'",
":",
"'DOWN'",
",",
"name",
":",
"zoologist",
".",
"getServiceInstance",
"(",
")",
".",
"getData",
"(",
")",
".",
"name",
",",
"basePath",
":",
"zoologist",
".",
"getServiceInstance",
"(",
")",
".",
"getData",
"(",
")",
".",
"basePath",
"||",
"DEFAULT_BASE_PATH",
",",
"address",
":",
"zoologist",
".",
"getServiceInstance",
"(",
")",
".",
"getData",
"(",
")",
".",
"address",
",",
"port",
":",
"zoologist",
".",
"getServiceInstance",
"(",
")",
".",
"getData",
"(",
")",
".",
"port",
",",
"registrationTime",
":",
"new",
"Date",
"(",
"zoologist",
".",
"getServiceInstance",
"(",
")",
".",
"getData",
"(",
")",
".",
"registrationTimeUTC",
")",
"}",
";",
"if",
"(",
"health",
".",
"status",
"===",
"'UP'",
"&&",
"zoologist",
".",
"getServiceDependencies",
"(",
")",
"&&",
"zoologist",
".",
"getServiceDependencies",
"(",
")",
".",
"length",
">",
"0",
")",
"{",
"checkDependencies",
"(",
"zoologist",
".",
"getServiceDependencies",
"(",
")",
",",
"function",
"(",
"err",
",",
"dependencies",
")",
"{",
"health",
".",
"dependencies",
"=",
"dependencies",
";",
"// If any dependencies have zero count, set service 'DOWN'",
"Object",
".",
"keys",
"(",
"dependencies",
")",
".",
"forEach",
"(",
"function",
"(",
"dependency",
")",
"{",
"if",
"(",
"dependencies",
"[",
"dependency",
"]",
"==",
"0",
")",
"health",
".",
"status",
"=",
"'DOWN'",
";",
"}",
")",
";",
"resolver",
".",
"resolve",
"(",
"health",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"resolver",
".",
"resolve",
"(",
"health",
")",
";",
"}",
"return",
"resolver",
".",
"promise",
";",
"}"
] |
Invoke health check.
|
[
"Invoke",
"health",
"check",
"."
] |
44953044e518d7c04319423ed1d8b87225e61343
|
https://github.com/ph0bos/express-microservice-starter/blob/44953044e518d7c04319423ed1d8b87225e61343/lib/monitors/microservice-monitor.js#L46-L83
|
19,271
|
ph0bos/express-microservice-starter
|
lib/monitors/microservice-monitor.js
|
checkDependencies
|
function checkDependencies(dependencies, callback) {
var checkedDependencies = {};
async.each(dependencies, function (dependency, callback) {
zoologist.getServiceDiscovery().queryForInstances(dependency, function(err, instances) {
checkedDependencies[dependency] = ((instances) ? instances.length : 0);
callback(err);
});
}, function(err) {
// Ignore error and just return zero'd counts
callback(null, checkedDependencies);
});
}
|
javascript
|
function checkDependencies(dependencies, callback) {
var checkedDependencies = {};
async.each(dependencies, function (dependency, callback) {
zoologist.getServiceDiscovery().queryForInstances(dependency, function(err, instances) {
checkedDependencies[dependency] = ((instances) ? instances.length : 0);
callback(err);
});
}, function(err) {
// Ignore error and just return zero'd counts
callback(null, checkedDependencies);
});
}
|
[
"function",
"checkDependencies",
"(",
"dependencies",
",",
"callback",
")",
"{",
"var",
"checkedDependencies",
"=",
"{",
"}",
";",
"async",
".",
"each",
"(",
"dependencies",
",",
"function",
"(",
"dependency",
",",
"callback",
")",
"{",
"zoologist",
".",
"getServiceDiscovery",
"(",
")",
".",
"queryForInstances",
"(",
"dependency",
",",
"function",
"(",
"err",
",",
"instances",
")",
"{",
"checkedDependencies",
"[",
"dependency",
"]",
"=",
"(",
"(",
"instances",
")",
"?",
"instances",
".",
"length",
":",
"0",
")",
";",
"callback",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"// Ignore error and just return zero'd counts",
"callback",
"(",
"null",
",",
"checkedDependencies",
")",
";",
"}",
")",
";",
"}"
] |
Check the status of any dependencies of this service.
|
[
"Check",
"the",
"status",
"of",
"any",
"dependencies",
"of",
"this",
"service",
"."
] |
44953044e518d7c04319423ed1d8b87225e61343
|
https://github.com/ph0bos/express-microservice-starter/blob/44953044e518d7c04319423ed1d8b87225e61343/lib/monitors/microservice-monitor.js#L88-L100
|
19,272
|
ph0bos/express-microservice-starter
|
index.js
|
function(options) {
options = options || {};
var config = konfig({ path: options.configPath || process.cwd() + '/config' });
// Default options
options.server = options.server || { port: process.env.PORT };
options.debug = options.debug || false;
options.discoverable = options.discoverable || false;
options.monitorsPath = options.monitorsPath || 'monitors';
options.controllersPath = options.controllersPath || 'controllers';
options.callerPath = options.callerPath || path.dirname(caller(2));
options.serviceName = pkgInfo.name;
options.serviceBasePath = 'services';
options.zookeeper = { connectionString: 'localhost:2181', retry: { count: 5 } };
options.partialResponseQuery = options.partialResponseQuery || 'fields';
options.correlationHeaderName = options.correlationHeaderName || 'X-CorrelationID';
options.validatorOptions = options.validatorOptions || null;
// Feature Flags
options.enableBodyParsing = options.enableBodyParsing || true;
options.enableEtag = options.enableEtag || false;
options.enableRequestTracing = options.enableRequestTracing || false;
// Return now if we have no config
if (!config.app) {
return options;
}
// Overlay config file options
options.server = config.app.server || { port: process.env.PORT };
options.serviceName = config.app.microservice.server.name || pkgInfo.name;
options.serviceBasePath = config.app.microservice.basePath || 'services';
options.networkInterfaces = (config.app.microservice.server.registrationNetworkInterfacePriority) ? config.app.microservice.server.registrationNetworkInterfacePriority : null;
options.serviceDependencies = (config.app.microservice.server.dependencies) ? config.app.microservice.server.dependencies.split(',') : null;
options.zookeeper = config.app.zookeeper || { connectionString: 'localhost:2181', retry: { count: 5 } };
return options;
}
|
javascript
|
function(options) {
options = options || {};
var config = konfig({ path: options.configPath || process.cwd() + '/config' });
// Default options
options.server = options.server || { port: process.env.PORT };
options.debug = options.debug || false;
options.discoverable = options.discoverable || false;
options.monitorsPath = options.monitorsPath || 'monitors';
options.controllersPath = options.controllersPath || 'controllers';
options.callerPath = options.callerPath || path.dirname(caller(2));
options.serviceName = pkgInfo.name;
options.serviceBasePath = 'services';
options.zookeeper = { connectionString: 'localhost:2181', retry: { count: 5 } };
options.partialResponseQuery = options.partialResponseQuery || 'fields';
options.correlationHeaderName = options.correlationHeaderName || 'X-CorrelationID';
options.validatorOptions = options.validatorOptions || null;
// Feature Flags
options.enableBodyParsing = options.enableBodyParsing || true;
options.enableEtag = options.enableEtag || false;
options.enableRequestTracing = options.enableRequestTracing || false;
// Return now if we have no config
if (!config.app) {
return options;
}
// Overlay config file options
options.server = config.app.server || { port: process.env.PORT };
options.serviceName = config.app.microservice.server.name || pkgInfo.name;
options.serviceBasePath = config.app.microservice.basePath || 'services';
options.networkInterfaces = (config.app.microservice.server.registrationNetworkInterfacePriority) ? config.app.microservice.server.registrationNetworkInterfacePriority : null;
options.serviceDependencies = (config.app.microservice.server.dependencies) ? config.app.microservice.server.dependencies.split(',') : null;
options.zookeeper = config.app.zookeeper || { connectionString: 'localhost:2181', retry: { count: 5 } };
return options;
}
|
[
"function",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"config",
"=",
"konfig",
"(",
"{",
"path",
":",
"options",
".",
"configPath",
"||",
"process",
".",
"cwd",
"(",
")",
"+",
"'/config'",
"}",
")",
";",
"// Default options",
"options",
".",
"server",
"=",
"options",
".",
"server",
"||",
"{",
"port",
":",
"process",
".",
"env",
".",
"PORT",
"}",
";",
"options",
".",
"debug",
"=",
"options",
".",
"debug",
"||",
"false",
";",
"options",
".",
"discoverable",
"=",
"options",
".",
"discoverable",
"||",
"false",
";",
"options",
".",
"monitorsPath",
"=",
"options",
".",
"monitorsPath",
"||",
"'monitors'",
";",
"options",
".",
"controllersPath",
"=",
"options",
".",
"controllersPath",
"||",
"'controllers'",
";",
"options",
".",
"callerPath",
"=",
"options",
".",
"callerPath",
"||",
"path",
".",
"dirname",
"(",
"caller",
"(",
"2",
")",
")",
";",
"options",
".",
"serviceName",
"=",
"pkgInfo",
".",
"name",
";",
"options",
".",
"serviceBasePath",
"=",
"'services'",
";",
"options",
".",
"zookeeper",
"=",
"{",
"connectionString",
":",
"'localhost:2181'",
",",
"retry",
":",
"{",
"count",
":",
"5",
"}",
"}",
";",
"options",
".",
"partialResponseQuery",
"=",
"options",
".",
"partialResponseQuery",
"||",
"'fields'",
";",
"options",
".",
"correlationHeaderName",
"=",
"options",
".",
"correlationHeaderName",
"||",
"'X-CorrelationID'",
";",
"options",
".",
"validatorOptions",
"=",
"options",
".",
"validatorOptions",
"||",
"null",
";",
"// Feature Flags",
"options",
".",
"enableBodyParsing",
"=",
"options",
".",
"enableBodyParsing",
"||",
"true",
";",
"options",
".",
"enableEtag",
"=",
"options",
".",
"enableEtag",
"||",
"false",
";",
"options",
".",
"enableRequestTracing",
"=",
"options",
".",
"enableRequestTracing",
"||",
"false",
";",
"// Return now if we have no config",
"if",
"(",
"!",
"config",
".",
"app",
")",
"{",
"return",
"options",
";",
"}",
"// Overlay config file options",
"options",
".",
"server",
"=",
"config",
".",
"app",
".",
"server",
"||",
"{",
"port",
":",
"process",
".",
"env",
".",
"PORT",
"}",
";",
"options",
".",
"serviceName",
"=",
"config",
".",
"app",
".",
"microservice",
".",
"server",
".",
"name",
"||",
"pkgInfo",
".",
"name",
";",
"options",
".",
"serviceBasePath",
"=",
"config",
".",
"app",
".",
"microservice",
".",
"basePath",
"||",
"'services'",
";",
"options",
".",
"networkInterfaces",
"=",
"(",
"config",
".",
"app",
".",
"microservice",
".",
"server",
".",
"registrationNetworkInterfacePriority",
")",
"?",
"config",
".",
"app",
".",
"microservice",
".",
"server",
".",
"registrationNetworkInterfacePriority",
":",
"null",
";",
"options",
".",
"serviceDependencies",
"=",
"(",
"config",
".",
"app",
".",
"microservice",
".",
"server",
".",
"dependencies",
")",
"?",
"config",
".",
"app",
".",
"microservice",
".",
"server",
".",
"dependencies",
".",
"split",
"(",
"','",
")",
":",
"null",
";",
"options",
".",
"zookeeper",
"=",
"config",
".",
"app",
".",
"zookeeper",
"||",
"{",
"connectionString",
":",
"'localhost:2181'",
",",
"retry",
":",
"{",
"count",
":",
"5",
"}",
"}",
";",
"return",
"options",
";",
"}"
] |
Construct an options instance.
|
[
"Construct",
"an",
"options",
"instance",
"."
] |
44953044e518d7c04319423ed1d8b87225e61343
|
https://github.com/ph0bos/express-microservice-starter/blob/44953044e518d7c04319423ed1d8b87225e61343/index.js#L42-L80
|
|
19,273
|
ph0bos/express-microservice-starter
|
lib/zoologist.js
|
ZoologistConfig
|
function ZoologistConfig() {
this.initialised = false;
this.client = null;
this.serviceInstance = null;
this.serviceDiscovery = null;
this.serviceDependencies = null;
}
|
javascript
|
function ZoologistConfig() {
this.initialised = false;
this.client = null;
this.serviceInstance = null;
this.serviceDiscovery = null;
this.serviceDependencies = null;
}
|
[
"function",
"ZoologistConfig",
"(",
")",
"{",
"this",
".",
"initialised",
"=",
"false",
";",
"this",
".",
"client",
"=",
"null",
";",
"this",
".",
"serviceInstance",
"=",
"null",
";",
"this",
".",
"serviceDiscovery",
"=",
"null",
";",
"this",
".",
"serviceDependencies",
"=",
"null",
";",
"}"
] |
Create an instance of ZoologistConfig.
@public
@constructor
|
[
"Create",
"an",
"instance",
"of",
"ZoologistConfig",
"."
] |
44953044e518d7c04319423ed1d8b87225e61343
|
https://github.com/ph0bos/express-microservice-starter/blob/44953044e518d7c04319423ed1d8b87225e61343/lib/zoologist.js#L22-L28
|
19,274
|
mapbox/cfn-config
|
lib/actions.js
|
describeChangeset
|
function describeChangeset(cfn, name, changesetId, callback) {
var changesetDescriptions;
var changes = [];
(function callAPI(nextToken, callback) {
cfn.describeChangeSet({ ChangeSetName: changesetId, StackName: name, NextToken: nextToken }, function(err, data) {
if (err) return callback(err);
changesetDescriptions = data;
if (data.Status === 'CREATE_COMPLETE' || data.Status === 'FAILED' || data.status === 'DELETE_COMPLETE') {
changes = changes.concat(data.Changes || []);
if (!data.NextToken) {
if (changes.length) changesetDescriptions.Changes = changes;
return callback(null, changesetDescriptions);
}
}
setTimeout(callAPI, 1000, data.NextToken, callback);
});
})(undefined, callback);
}
|
javascript
|
function describeChangeset(cfn, name, changesetId, callback) {
var changesetDescriptions;
var changes = [];
(function callAPI(nextToken, callback) {
cfn.describeChangeSet({ ChangeSetName: changesetId, StackName: name, NextToken: nextToken }, function(err, data) {
if (err) return callback(err);
changesetDescriptions = data;
if (data.Status === 'CREATE_COMPLETE' || data.Status === 'FAILED' || data.status === 'DELETE_COMPLETE') {
changes = changes.concat(data.Changes || []);
if (!data.NextToken) {
if (changes.length) changesetDescriptions.Changes = changes;
return callback(null, changesetDescriptions);
}
}
setTimeout(callAPI, 1000, data.NextToken, callback);
});
})(undefined, callback);
}
|
[
"function",
"describeChangeset",
"(",
"cfn",
",",
"name",
",",
"changesetId",
",",
"callback",
")",
"{",
"var",
"changesetDescriptions",
";",
"var",
"changes",
"=",
"[",
"]",
";",
"(",
"function",
"callAPI",
"(",
"nextToken",
",",
"callback",
")",
"{",
"cfn",
".",
"describeChangeSet",
"(",
"{",
"ChangeSetName",
":",
"changesetId",
",",
"StackName",
":",
"name",
",",
"NextToken",
":",
"nextToken",
"}",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"changesetDescriptions",
"=",
"data",
";",
"if",
"(",
"data",
".",
"Status",
"===",
"'CREATE_COMPLETE'",
"||",
"data",
".",
"Status",
"===",
"'FAILED'",
"||",
"data",
".",
"status",
"===",
"'DELETE_COMPLETE'",
")",
"{",
"changes",
"=",
"changes",
".",
"concat",
"(",
"data",
".",
"Changes",
"||",
"[",
"]",
")",
";",
"if",
"(",
"!",
"data",
".",
"NextToken",
")",
"{",
"if",
"(",
"changes",
".",
"length",
")",
"changesetDescriptions",
".",
"Changes",
"=",
"changes",
";",
"return",
"callback",
"(",
"null",
",",
"changesetDescriptions",
")",
";",
"}",
"}",
"setTimeout",
"(",
"callAPI",
",",
"1000",
",",
"data",
".",
"NextToken",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
")",
"(",
"undefined",
",",
"callback",
")",
";",
"}"
] |
Poll changeset until it has reached a completed state.
@private
@param {object} cfn - a cloudformation client object
@param {string} name - the name of the existing stack to update
@param {string} changesetId - the name or ARN of an existing changeset
@param {function} callback - a function that will be provided with the changeset
details once the changeset is in CREATE_COMPLETE, DELETE_COMPLETE, or FAILED state
|
[
"Poll",
"changeset",
"until",
"it",
"has",
"reached",
"a",
"completed",
"state",
"."
] |
920af56b0dce8918aed30c27869c127be1ba1e99
|
https://github.com/mapbox/cfn-config/blob/920af56b0dce8918aed30c27869c127be1ba1e99/lib/actions.js#L292-L315
|
19,275
|
mapbox/cfn-config
|
lib/actions.js
|
stackParameters
|
function stackParameters(name, changeSetType, templateUrl, parameters) {
return {
StackName: name,
Capabilities: [
'CAPABILITY_IAM',
'CAPABILITY_NAMED_IAM'
],
ChangeSetType: changeSetType,
TemplateURL: templateUrl,
Parameters: Object.keys(parameters).map(function(key) {
return { ParameterKey: key, ParameterValue: parameters[key] };
})
};
}
|
javascript
|
function stackParameters(name, changeSetType, templateUrl, parameters) {
return {
StackName: name,
Capabilities: [
'CAPABILITY_IAM',
'CAPABILITY_NAMED_IAM'
],
ChangeSetType: changeSetType,
TemplateURL: templateUrl,
Parameters: Object.keys(parameters).map(function(key) {
return { ParameterKey: key, ParameterValue: parameters[key] };
})
};
}
|
[
"function",
"stackParameters",
"(",
"name",
",",
"changeSetType",
",",
"templateUrl",
",",
"parameters",
")",
"{",
"return",
"{",
"StackName",
":",
"name",
",",
"Capabilities",
":",
"[",
"'CAPABILITY_IAM'",
",",
"'CAPABILITY_NAMED_IAM'",
"]",
",",
"ChangeSetType",
":",
"changeSetType",
",",
"TemplateURL",
":",
"templateUrl",
",",
"Parameters",
":",
"Object",
".",
"keys",
"(",
"parameters",
")",
".",
"map",
"(",
"function",
"(",
"key",
")",
"{",
"return",
"{",
"ParameterKey",
":",
"key",
",",
"ParameterValue",
":",
"parameters",
"[",
"key",
"]",
"}",
";",
"}",
")",
"}",
";",
"}"
] |
Build parameters object for CloudFormation requests
@private
@param {string} name - the name of the stack
@param {string} changeSetType - the type of changeset, either UPDATE or CREATE
@param {string} templateUrl - the URL for the template on S3
@param {object} parameters - name/value pairs defining the desired stack configuration
@returns {object} params - an object for use in create/update/delete stack requests
|
[
"Build",
"parameters",
"object",
"for",
"CloudFormation",
"requests"
] |
920af56b0dce8918aed30c27869c127be1ba1e99
|
https://github.com/mapbox/cfn-config/blob/920af56b0dce8918aed30c27869c127be1ba1e99/lib/actions.js#L327-L340
|
19,276
|
javivelasco/react-css-themr
|
src/components/themr.js
|
validateComposeOption
|
function validateComposeOption(composeTheme) {
if ([ COMPOSE_DEEPLY, COMPOSE_SOFTLY, DONT_COMPOSE ].indexOf(composeTheme) === -1) {
throw new Error(
`Invalid composeTheme option for react-css-themr. Valid composition options\
are ${COMPOSE_DEEPLY}, ${COMPOSE_SOFTLY} and ${DONT_COMPOSE}. The given\
option was ${composeTheme}`
)
}
}
|
javascript
|
function validateComposeOption(composeTheme) {
if ([ COMPOSE_DEEPLY, COMPOSE_SOFTLY, DONT_COMPOSE ].indexOf(composeTheme) === -1) {
throw new Error(
`Invalid composeTheme option for react-css-themr. Valid composition options\
are ${COMPOSE_DEEPLY}, ${COMPOSE_SOFTLY} and ${DONT_COMPOSE}. The given\
option was ${composeTheme}`
)
}
}
|
[
"function",
"validateComposeOption",
"(",
"composeTheme",
")",
"{",
"if",
"(",
"[",
"COMPOSE_DEEPLY",
",",
"COMPOSE_SOFTLY",
",",
"DONT_COMPOSE",
"]",
".",
"indexOf",
"(",
"composeTheme",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"\\\n",
"${",
"COMPOSE_DEEPLY",
"}",
"${",
"COMPOSE_SOFTLY",
"}",
"${",
"DONT_COMPOSE",
"}",
"\\\n",
"${",
"composeTheme",
"}",
"`",
")",
"}",
"}"
] |
Validates compose option
@param {String|Boolean} composeTheme - Compose them option
@throws
@returns {undefined}
|
[
"Validates",
"compose",
"option"
] |
8d12cfdca26c141c549a85e8e3065c45b83be654
|
https://github.com/javivelasco/react-css-themr/blob/8d12cfdca26c141c549a85e8e3065c45b83be654/src/components/themr.js#L262-L270
|
19,277
|
javivelasco/react-css-themr
|
src/components/themr.js
|
removeNamespace
|
function removeNamespace(key, themeNamespace) {
const capitalized = key.substr(themeNamespace.length)
return capitalized.slice(0, 1).toLowerCase() + capitalized.slice(1)
}
|
javascript
|
function removeNamespace(key, themeNamespace) {
const capitalized = key.substr(themeNamespace.length)
return capitalized.slice(0, 1).toLowerCase() + capitalized.slice(1)
}
|
[
"function",
"removeNamespace",
"(",
"key",
",",
"themeNamespace",
")",
"{",
"const",
"capitalized",
"=",
"key",
".",
"substr",
"(",
"themeNamespace",
".",
"length",
")",
"return",
"capitalized",
".",
"slice",
"(",
"0",
",",
"1",
")",
".",
"toLowerCase",
"(",
")",
"+",
"capitalized",
".",
"slice",
"(",
"1",
")",
"}"
] |
Removes namespace from key
@param {String} key - Key
@param {String} themeNamespace - Theme namespace
@returns {String} - Key
|
[
"Removes",
"namespace",
"from",
"key"
] |
8d12cfdca26c141c549a85e8e3065c45b83be654
|
https://github.com/javivelasco/react-css-themr/blob/8d12cfdca26c141c549a85e8e3065c45b83be654/src/components/themr.js#L279-L282
|
19,278
|
javivelasco/react-css-themr
|
src/components/themr.js
|
defaultMapThemrProps
|
function defaultMapThemrProps(ownProps, theme) {
const {
composeTheme, //eslint-disable-line no-unused-vars
innerRef,
themeNamespace, //eslint-disable-line no-unused-vars
mapThemrProps, //eslint-disable-line no-unused-vars
...rest
} = ownProps
return {
...rest,
ref: innerRef,
theme
}
}
|
javascript
|
function defaultMapThemrProps(ownProps, theme) {
const {
composeTheme, //eslint-disable-line no-unused-vars
innerRef,
themeNamespace, //eslint-disable-line no-unused-vars
mapThemrProps, //eslint-disable-line no-unused-vars
...rest
} = ownProps
return {
...rest,
ref: innerRef,
theme
}
}
|
[
"function",
"defaultMapThemrProps",
"(",
"ownProps",
",",
"theme",
")",
"{",
"const",
"{",
"composeTheme",
",",
"//eslint-disable-line no-unused-vars",
"innerRef",
",",
"themeNamespace",
",",
"//eslint-disable-line no-unused-vars",
"mapThemrProps",
",",
"//eslint-disable-line no-unused-vars",
"...",
"rest",
"}",
"=",
"ownProps",
"return",
"{",
"...",
"rest",
",",
"ref",
":",
"innerRef",
",",
"theme",
"}",
"}"
] |
Maps props and theme to an object that will be used to pass down props to the
decorated component.
@param {Object} ownProps - All props given to the decorated component
@param {Object} theme - Calculated then that should be passed down
@returns {Object} - Props that will be passed down to the decorated component
|
[
"Maps",
"props",
"and",
"theme",
"to",
"an",
"object",
"that",
"will",
"be",
"used",
"to",
"pass",
"down",
"props",
"to",
"the",
"decorated",
"component",
"."
] |
8d12cfdca26c141c549a85e8e3065c45b83be654
|
https://github.com/javivelasco/react-css-themr/blob/8d12cfdca26c141c549a85e8e3065c45b83be654/src/components/themr.js#L292-L306
|
19,279
|
nisaacson/pdf-extract
|
lib/raw.js
|
function (pdf_file, cb) {
var quality = 300;
if (options.hasOwnProperty('quality') && options.quality) {
quality = options.quality;
}
convert(pdf_file.file_path, quality, function (err, tif_path) {
var zeroBasedNumPages = num_pages-1;
self.emit('log', 'converted page to intermediate tiff file, page '+ index+ ' (0-based indexing) of '+ zeroBasedNumPages);
if (err) { return cb(err); }
var ocr_flags = [
'-psm 6'
];
if (options.ocr_flags) {
ocr_flags = options.ocr_flags;
}
ocr(tif_path, ocr_flags, function (err, extract) {
fs.unlink(tif_path, function (tif_cleanup_err, reply) {
if (tif_cleanup_err) {
err += ', error removing temporary tif file: "'+tif_cleanup_err+'"';
}
if (err) { return cb(err); }
var page_number = index+1
self.emit('log', 'raw ocr: page ' + index + ' (0-based indexing) of ' +zeroBasedNumPages + ' complete');
single_page_pdf_file_paths.push(pdf_file.file_path);
self.emit('page', { hash: hash, text: extract, index: index, num_pages: num_pages, pdf_path: pdf_path, single_page_pdf_path: pdf_file.file_path});
text_pages.push(extract);
index++;
cb();
});
});
});
}
|
javascript
|
function (pdf_file, cb) {
var quality = 300;
if (options.hasOwnProperty('quality') && options.quality) {
quality = options.quality;
}
convert(pdf_file.file_path, quality, function (err, tif_path) {
var zeroBasedNumPages = num_pages-1;
self.emit('log', 'converted page to intermediate tiff file, page '+ index+ ' (0-based indexing) of '+ zeroBasedNumPages);
if (err) { return cb(err); }
var ocr_flags = [
'-psm 6'
];
if (options.ocr_flags) {
ocr_flags = options.ocr_flags;
}
ocr(tif_path, ocr_flags, function (err, extract) {
fs.unlink(tif_path, function (tif_cleanup_err, reply) {
if (tif_cleanup_err) {
err += ', error removing temporary tif file: "'+tif_cleanup_err+'"';
}
if (err) { return cb(err); }
var page_number = index+1
self.emit('log', 'raw ocr: page ' + index + ' (0-based indexing) of ' +zeroBasedNumPages + ' complete');
single_page_pdf_file_paths.push(pdf_file.file_path);
self.emit('page', { hash: hash, text: extract, index: index, num_pages: num_pages, pdf_path: pdf_path, single_page_pdf_path: pdf_file.file_path});
text_pages.push(extract);
index++;
cb();
});
});
});
}
|
[
"function",
"(",
"pdf_file",
",",
"cb",
")",
"{",
"var",
"quality",
"=",
"300",
";",
"if",
"(",
"options",
".",
"hasOwnProperty",
"(",
"'quality'",
")",
"&&",
"options",
".",
"quality",
")",
"{",
"quality",
"=",
"options",
".",
"quality",
";",
"}",
"convert",
"(",
"pdf_file",
".",
"file_path",
",",
"quality",
",",
"function",
"(",
"err",
",",
"tif_path",
")",
"{",
"var",
"zeroBasedNumPages",
"=",
"num_pages",
"-",
"1",
";",
"self",
".",
"emit",
"(",
"'log'",
",",
"'converted page to intermediate tiff file, page '",
"+",
"index",
"+",
"' (0-based indexing) of '",
"+",
"zeroBasedNumPages",
")",
";",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"var",
"ocr_flags",
"=",
"[",
"'-psm 6'",
"]",
";",
"if",
"(",
"options",
".",
"ocr_flags",
")",
"{",
"ocr_flags",
"=",
"options",
".",
"ocr_flags",
";",
"}",
"ocr",
"(",
"tif_path",
",",
"ocr_flags",
",",
"function",
"(",
"err",
",",
"extract",
")",
"{",
"fs",
".",
"unlink",
"(",
"tif_path",
",",
"function",
"(",
"tif_cleanup_err",
",",
"reply",
")",
"{",
"if",
"(",
"tif_cleanup_err",
")",
"{",
"err",
"+=",
"', error removing temporary tif file: \"'",
"+",
"tif_cleanup_err",
"+",
"'\"'",
";",
"}",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"var",
"page_number",
"=",
"index",
"+",
"1",
"self",
".",
"emit",
"(",
"'log'",
",",
"'raw ocr: page '",
"+",
"index",
"+",
"' (0-based indexing) of '",
"+",
"zeroBasedNumPages",
"+",
"' complete'",
")",
";",
"single_page_pdf_file_paths",
".",
"push",
"(",
"pdf_file",
".",
"file_path",
")",
";",
"self",
".",
"emit",
"(",
"'page'",
",",
"{",
"hash",
":",
"hash",
",",
"text",
":",
"extract",
",",
"index",
":",
"index",
",",
"num_pages",
":",
"num_pages",
",",
"pdf_path",
":",
"pdf_path",
",",
"single_page_pdf_path",
":",
"pdf_file",
".",
"file_path",
"}",
")",
";",
"text_pages",
".",
"push",
"(",
"extract",
")",
";",
"index",
"++",
";",
"cb",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
extract the text for each page via ocr
|
[
"extract",
"the",
"text",
"for",
"each",
"page",
"via",
"ocr"
] |
3325af68da09ced577ce00202ef544f6c10b4833
|
https://github.com/nisaacson/pdf-extract/blob/3325af68da09ced577ce00202ef544f6c10b4833/lib/raw.js#L83-L114
|
|
19,280
|
nisaacson/pdf-extract
|
lib/split.js
|
remove_doc_data
|
function remove_doc_data(callback) {
var folder = path.join(__dirname, '..');
var doc_data_path = path.join(folder, 'doc_data.txt');
fs.exists(doc_data_path, function (exists) {
if (!exists) {
return callback();
}
fs.unlink(doc_data_path, callback);
});
}
|
javascript
|
function remove_doc_data(callback) {
var folder = path.join(__dirname, '..');
var doc_data_path = path.join(folder, 'doc_data.txt');
fs.exists(doc_data_path, function (exists) {
if (!exists) {
return callback();
}
fs.unlink(doc_data_path, callback);
});
}
|
[
"function",
"remove_doc_data",
"(",
"callback",
")",
"{",
"var",
"folder",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'..'",
")",
";",
"var",
"doc_data_path",
"=",
"path",
".",
"join",
"(",
"folder",
",",
"'doc_data.txt'",
")",
";",
"fs",
".",
"exists",
"(",
"doc_data_path",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"!",
"exists",
")",
"{",
"return",
"callback",
"(",
")",
";",
"}",
"fs",
".",
"unlink",
"(",
"doc_data_path",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] |
pdftk creates a file called doc_data.txt during the burst split process.
This file is not needed so remove it now
|
[
"pdftk",
"creates",
"a",
"file",
"called",
"doc_data",
".",
"txt",
"during",
"the",
"burst",
"split",
"process",
".",
"This",
"file",
"is",
"not",
"needed",
"so",
"remove",
"it",
"now"
] |
3325af68da09ced577ce00202ef544f6c10b4833
|
https://github.com/nisaacson/pdf-extract/blob/3325af68da09ced577ce00202ef544f6c10b4833/lib/split.js#L127-L136
|
19,281
|
nisaacson/pdf-extract
|
lib/searchable.js
|
cleanup_directory
|
function cleanup_directory(directory_path, callback) {
// only remove the folder at directory_path if it exists
fs.exists(directory_path, function (exists) {
if (!exists) {
return callback();
}
rimraf(directory_path, callback);
});
}
|
javascript
|
function cleanup_directory(directory_path, callback) {
// only remove the folder at directory_path if it exists
fs.exists(directory_path, function (exists) {
if (!exists) {
return callback();
}
rimraf(directory_path, callback);
});
}
|
[
"function",
"cleanup_directory",
"(",
"directory_path",
",",
"callback",
")",
"{",
"// only remove the folder at directory_path if it exists",
"fs",
".",
"exists",
"(",
"directory_path",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"!",
"exists",
")",
"{",
"return",
"callback",
"(",
")",
";",
"}",
"rimraf",
"(",
"directory_path",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] |
Cleanup any single page pdfs on error
|
[
"Cleanup",
"any",
"single",
"page",
"pdfs",
"on",
"error"
] |
3325af68da09ced577ce00202ef544f6c10b4833
|
https://github.com/nisaacson/pdf-extract/blob/3325af68da09ced577ce00202ef544f6c10b4833/lib/searchable.js#L75-L83
|
19,282
|
koajs/userauth
|
index.js
|
async function () {
let redirectURL = ctx.url;
try {
redirectURL = encodeURIComponent(redirectURL);
} catch (e) {
// URIError: URI malformed
// use source url
}
const loginURL = options.loginPath + '?redirect=' + redirectURL;
debug('redirect to %s', loginURL);
redirect(ctx, loginURL);
}
|
javascript
|
async function () {
let redirectURL = ctx.url;
try {
redirectURL = encodeURIComponent(redirectURL);
} catch (e) {
// URIError: URI malformed
// use source url
}
const loginURL = options.loginPath + '?redirect=' + redirectURL;
debug('redirect to %s', loginURL);
redirect(ctx, loginURL);
}
|
[
"async",
"function",
"(",
")",
"{",
"let",
"redirectURL",
"=",
"ctx",
".",
"url",
";",
"try",
"{",
"redirectURL",
"=",
"encodeURIComponent",
"(",
"redirectURL",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// URIError: URI malformed",
"// use source url",
"}",
"const",
"loginURL",
"=",
"options",
".",
"loginPath",
"+",
"'?redirect='",
"+",
"redirectURL",
";",
"debug",
"(",
"'redirect to %s'",
",",
"loginURL",
")",
";",
"redirect",
"(",
"ctx",
",",
"loginURL",
")",
";",
"}"
] |
make next handle an Async Function so it can use await next in redirectHandle
|
[
"make",
"next",
"handle",
"an",
"Async",
"Function",
"so",
"it",
"can",
"use",
"await",
"next",
"in",
"redirectHandle"
] |
6d848cbdea4e8fb7dfe50418e009c120bdd1cab9
|
https://github.com/koajs/userauth/blob/6d848cbdea4e8fb7dfe50418e009c120bdd1cab9/index.js#L181-L192
|
|
19,283
|
koajs/userauth
|
index.js
|
redirect
|
function redirect(ctx, url, status) {
if (ctx.accepts('html', 'json') === 'json') {
ctx.set('Location', url);
ctx.status = 401;
ctx.body = {
error: '401 Unauthorized'
};
return;
}
return ctx.redirect(url, status);
}
|
javascript
|
function redirect(ctx, url, status) {
if (ctx.accepts('html', 'json') === 'json') {
ctx.set('Location', url);
ctx.status = 401;
ctx.body = {
error: '401 Unauthorized'
};
return;
}
return ctx.redirect(url, status);
}
|
[
"function",
"redirect",
"(",
"ctx",
",",
"url",
",",
"status",
")",
"{",
"if",
"(",
"ctx",
".",
"accepts",
"(",
"'html'",
",",
"'json'",
")",
"===",
"'json'",
")",
"{",
"ctx",
".",
"set",
"(",
"'Location'",
",",
"url",
")",
";",
"ctx",
".",
"status",
"=",
"401",
";",
"ctx",
".",
"body",
"=",
"{",
"error",
":",
"'401 Unauthorized'",
"}",
";",
"return",
";",
"}",
"return",
"ctx",
".",
"redirect",
"(",
"url",
",",
"status",
")",
";",
"}"
] |
Send redirect response.
@param {Context} ctx
@param {String} url, redirect URL
@param {Number|String} status, response status code, default is `302`
@api public
|
[
"Send",
"redirect",
"response",
"."
] |
6d848cbdea4e8fb7dfe50418e009c120bdd1cab9
|
https://github.com/koajs/userauth/blob/6d848cbdea4e8fb7dfe50418e009c120bdd1cab9/index.js#L238-L248
|
19,284
|
koajs/userauth
|
index.js
|
login
|
function login(options) {
const defaultHost = options.host;
return async function loginHandler(ctx) {
const loginCallbackPath = options.loginCallbackPath;
const loginPath = options.loginPath;
// ctx.session should be exists
if (ctx.session) {
ctx.session.userauthLoginReferer = formatReferer(ctx, loginPath, options.rootPath);
debug('set loginReferer into session: %s', ctx.session.userauthLoginReferer);
}
const host = defaultHost || ctx.host;
const protocol = options.protocol || ctx.protocol;
const currentURL = protocol + '://' + host + loginCallbackPath;
const loginURL = options.loginURLFormatter(currentURL, options.rootPath, ctx);
debug('login redrect to loginURL: %s', loginURL);
redirect(ctx, loginURL);
};
}
|
javascript
|
function login(options) {
const defaultHost = options.host;
return async function loginHandler(ctx) {
const loginCallbackPath = options.loginCallbackPath;
const loginPath = options.loginPath;
// ctx.session should be exists
if (ctx.session) {
ctx.session.userauthLoginReferer = formatReferer(ctx, loginPath, options.rootPath);
debug('set loginReferer into session: %s', ctx.session.userauthLoginReferer);
}
const host = defaultHost || ctx.host;
const protocol = options.protocol || ctx.protocol;
const currentURL = protocol + '://' + host + loginCallbackPath;
const loginURL = options.loginURLFormatter(currentURL, options.rootPath, ctx);
debug('login redrect to loginURL: %s', loginURL);
redirect(ctx, loginURL);
};
}
|
[
"function",
"login",
"(",
"options",
")",
"{",
"const",
"defaultHost",
"=",
"options",
".",
"host",
";",
"return",
"async",
"function",
"loginHandler",
"(",
"ctx",
")",
"{",
"const",
"loginCallbackPath",
"=",
"options",
".",
"loginCallbackPath",
";",
"const",
"loginPath",
"=",
"options",
".",
"loginPath",
";",
"// ctx.session should be exists",
"if",
"(",
"ctx",
".",
"session",
")",
"{",
"ctx",
".",
"session",
".",
"userauthLoginReferer",
"=",
"formatReferer",
"(",
"ctx",
",",
"loginPath",
",",
"options",
".",
"rootPath",
")",
";",
"debug",
"(",
"'set loginReferer into session: %s'",
",",
"ctx",
".",
"session",
".",
"userauthLoginReferer",
")",
";",
"}",
"const",
"host",
"=",
"defaultHost",
"||",
"ctx",
".",
"host",
";",
"const",
"protocol",
"=",
"options",
".",
"protocol",
"||",
"ctx",
".",
"protocol",
";",
"const",
"currentURL",
"=",
"protocol",
"+",
"'://'",
"+",
"host",
"+",
"loginCallbackPath",
";",
"const",
"loginURL",
"=",
"options",
".",
"loginURLFormatter",
"(",
"currentURL",
",",
"options",
".",
"rootPath",
",",
"ctx",
")",
";",
"debug",
"(",
"'login redrect to loginURL: %s'",
",",
"loginURL",
")",
";",
"redirect",
"(",
"ctx",
",",
"loginURL",
")",
";",
"}",
";",
"}"
] |
return a loginHandler
@param {Object} options
@return {Function}
|
[
"return",
"a",
"loginHandler"
] |
6d848cbdea4e8fb7dfe50418e009c120bdd1cab9
|
https://github.com/koajs/userauth/blob/6d848cbdea4e8fb7dfe50418e009c120bdd1cab9/index.js#L279-L297
|
19,285
|
koajs/userauth
|
index.js
|
loginCallback
|
function loginCallback(options) {
return async function loginCallbackHandler(ctx) {
let referer;
// customize how to get redirect target
if (options.getRedirectTarget) {
referer = options.getRedirectTarget(ctx);
}
if (!referer) referer = ctx.session.userauthLoginReferer || options.rootPath;
debug('loginReferer in session: %j', ctx.session.userauthLoginReferer);
// cleanup the userauthLoginReferer on session
ctx.session.userauthLoginReferer = undefined;
let user = ctx.session[options.userField];
if (user) {
// already login
return redirect(ctx, referer);
}
user = await options.getUser(ctx);
if (!user) {
return redirect(ctx, referer);
}
const res = await options.loginCallback(ctx, user);
const loginUser = res[0];
const redirectURL = res[1];
ctx.session[options.userField] = loginUser;
if (redirectURL) {
referer = redirectURL;
}
redirect(ctx, referer);
};
}
|
javascript
|
function loginCallback(options) {
return async function loginCallbackHandler(ctx) {
let referer;
// customize how to get redirect target
if (options.getRedirectTarget) {
referer = options.getRedirectTarget(ctx);
}
if (!referer) referer = ctx.session.userauthLoginReferer || options.rootPath;
debug('loginReferer in session: %j', ctx.session.userauthLoginReferer);
// cleanup the userauthLoginReferer on session
ctx.session.userauthLoginReferer = undefined;
let user = ctx.session[options.userField];
if (user) {
// already login
return redirect(ctx, referer);
}
user = await options.getUser(ctx);
if (!user) {
return redirect(ctx, referer);
}
const res = await options.loginCallback(ctx, user);
const loginUser = res[0];
const redirectURL = res[1];
ctx.session[options.userField] = loginUser;
if (redirectURL) {
referer = redirectURL;
}
redirect(ctx, referer);
};
}
|
[
"function",
"loginCallback",
"(",
"options",
")",
"{",
"return",
"async",
"function",
"loginCallbackHandler",
"(",
"ctx",
")",
"{",
"let",
"referer",
";",
"// customize how to get redirect target",
"if",
"(",
"options",
".",
"getRedirectTarget",
")",
"{",
"referer",
"=",
"options",
".",
"getRedirectTarget",
"(",
"ctx",
")",
";",
"}",
"if",
"(",
"!",
"referer",
")",
"referer",
"=",
"ctx",
".",
"session",
".",
"userauthLoginReferer",
"||",
"options",
".",
"rootPath",
";",
"debug",
"(",
"'loginReferer in session: %j'",
",",
"ctx",
".",
"session",
".",
"userauthLoginReferer",
")",
";",
"// cleanup the userauthLoginReferer on session",
"ctx",
".",
"session",
".",
"userauthLoginReferer",
"=",
"undefined",
";",
"let",
"user",
"=",
"ctx",
".",
"session",
"[",
"options",
".",
"userField",
"]",
";",
"if",
"(",
"user",
")",
"{",
"// already login",
"return",
"redirect",
"(",
"ctx",
",",
"referer",
")",
";",
"}",
"user",
"=",
"await",
"options",
".",
"getUser",
"(",
"ctx",
")",
";",
"if",
"(",
"!",
"user",
")",
"{",
"return",
"redirect",
"(",
"ctx",
",",
"referer",
")",
";",
"}",
"const",
"res",
"=",
"await",
"options",
".",
"loginCallback",
"(",
"ctx",
",",
"user",
")",
";",
"const",
"loginUser",
"=",
"res",
"[",
"0",
"]",
";",
"const",
"redirectURL",
"=",
"res",
"[",
"1",
"]",
";",
"ctx",
".",
"session",
"[",
"options",
".",
"userField",
"]",
"=",
"loginUser",
";",
"if",
"(",
"redirectURL",
")",
"{",
"referer",
"=",
"redirectURL",
";",
"}",
"redirect",
"(",
"ctx",
",",
"referer",
")",
";",
"}",
";",
"}"
] |
return a loginCallbackHandler
@param {Object} options
@return {Function}
|
[
"return",
"a",
"loginCallbackHandler"
] |
6d848cbdea4e8fb7dfe50418e009c120bdd1cab9
|
https://github.com/koajs/userauth/blob/6d848cbdea4e8fb7dfe50418e009c120bdd1cab9/index.js#L305-L336
|
19,286
|
koajs/userauth
|
index.js
|
logout
|
function logout(options) {
return async function logoutHandler(ctx) {
let referer = formatReferer(ctx, options.logoutPath, options.rootPath);
const user = ctx.session[options.userField];
if (!user) {
return redirect(ctx, referer);
}
const redirectURL = await options.logoutCallback(ctx, user);
ctx.session[options.userField] = null;
if (redirectURL) {
referer = redirectURL;
}
redirect(ctx, referer);
};
}
|
javascript
|
function logout(options) {
return async function logoutHandler(ctx) {
let referer = formatReferer(ctx, options.logoutPath, options.rootPath);
const user = ctx.session[options.userField];
if (!user) {
return redirect(ctx, referer);
}
const redirectURL = await options.logoutCallback(ctx, user);
ctx.session[options.userField] = null;
if (redirectURL) {
referer = redirectURL;
}
redirect(ctx, referer);
};
}
|
[
"function",
"logout",
"(",
"options",
")",
"{",
"return",
"async",
"function",
"logoutHandler",
"(",
"ctx",
")",
"{",
"let",
"referer",
"=",
"formatReferer",
"(",
"ctx",
",",
"options",
".",
"logoutPath",
",",
"options",
".",
"rootPath",
")",
";",
"const",
"user",
"=",
"ctx",
".",
"session",
"[",
"options",
".",
"userField",
"]",
";",
"if",
"(",
"!",
"user",
")",
"{",
"return",
"redirect",
"(",
"ctx",
",",
"referer",
")",
";",
"}",
"const",
"redirectURL",
"=",
"await",
"options",
".",
"logoutCallback",
"(",
"ctx",
",",
"user",
")",
";",
"ctx",
".",
"session",
"[",
"options",
".",
"userField",
"]",
"=",
"null",
";",
"if",
"(",
"redirectURL",
")",
"{",
"referer",
"=",
"redirectURL",
";",
"}",
"redirect",
"(",
"ctx",
",",
"referer",
")",
";",
"}",
";",
"}"
] |
return a logoutHandler
@param {Object} options
@return {Function}
|
[
"return",
"a",
"logoutHandler"
] |
6d848cbdea4e8fb7dfe50418e009c120bdd1cab9
|
https://github.com/koajs/userauth/blob/6d848cbdea4e8fb7dfe50418e009c120bdd1cab9/index.js#L344-L360
|
19,287
|
mjeanroy/rollup-plugin-prettier
|
scripts/release/index.js
|
bumpLevel
|
function bumpLevel(level) {
return gulp.src(config.pkg)
.pipe(bump({type: level}))
.on('error', (e) => log.error(e))
.pipe(gulp.dest(config.root));
}
|
javascript
|
function bumpLevel(level) {
return gulp.src(config.pkg)
.pipe(bump({type: level}))
.on('error', (e) => log.error(e))
.pipe(gulp.dest(config.root));
}
|
[
"function",
"bumpLevel",
"(",
"level",
")",
"{",
"return",
"gulp",
".",
"src",
"(",
"config",
".",
"pkg",
")",
".",
"pipe",
"(",
"bump",
"(",
"{",
"type",
":",
"level",
"}",
")",
")",
".",
"on",
"(",
"'error'",
",",
"(",
"e",
")",
"=>",
"log",
".",
"error",
"(",
"e",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"config",
".",
"root",
")",
")",
";",
"}"
] |
Update version in number in `package.json` file.
@param {string} level The semver level identifier (`major`, `minor` or `patch`).
@return {WritableStream} The stream pipeline.
|
[
"Update",
"version",
"in",
"number",
"in",
"package",
".",
"json",
"file",
"."
] |
ecac447199b485d7c1a769a4732d3848779a4a61
|
https://github.com/mjeanroy/rollup-plugin-prettier/blob/ecac447199b485d7c1a769a4732d3848779a4a61/scripts/release/index.js#L38-L43
|
19,288
|
mjeanroy/rollup-plugin-prettier
|
scripts/release/index.js
|
createReleaseTask
|
function createReleaseTask(level) {
/**
* Prepare the release: upgrade version number according to
* the specified level.
*
* @return {WritableStream} The stream pipeline.
*/
function prepareRelease() {
return bumpLevel(level);
}
return gulp.series(
prepareRelease,
performRelease,
tagRelease,
prepareNextRelease
);
}
|
javascript
|
function createReleaseTask(level) {
/**
* Prepare the release: upgrade version number according to
* the specified level.
*
* @return {WritableStream} The stream pipeline.
*/
function prepareRelease() {
return bumpLevel(level);
}
return gulp.series(
prepareRelease,
performRelease,
tagRelease,
prepareNextRelease
);
}
|
[
"function",
"createReleaseTask",
"(",
"level",
")",
"{",
"/**\n * Prepare the release: upgrade version number according to\n * the specified level.\n *\n * @return {WritableStream} The stream pipeline.\n */",
"function",
"prepareRelease",
"(",
")",
"{",
"return",
"bumpLevel",
"(",
"level",
")",
";",
"}",
"return",
"gulp",
".",
"series",
"(",
"prepareRelease",
",",
"performRelease",
",",
"tagRelease",
",",
"prepareNextRelease",
")",
";",
"}"
] |
Create the release task.
@param {string} level The version level upgrade.
@return {function} The release task function.
|
[
"Create",
"the",
"release",
"task",
"."
] |
ecac447199b485d7c1a769a4732d3848779a4a61
|
https://github.com/mjeanroy/rollup-plugin-prettier/blob/ecac447199b485d7c1a769a4732d3848779a4a61/scripts/release/index.js#L97-L114
|
19,289
|
cozy/cozy-home
|
src/lib/realtime.js
|
subscribeWhenReady
|
function subscribeWhenReady(doctype, socket) {
if (socket.readyState === WEBSOCKET_STATE.OPEN) {
try {
socket.send(
JSON.stringify({
method: 'SUBSCRIBE',
payload: {
type: doctype
}
})
)
} catch (error) {
// eslint-disable-next-line no-console
console.warn(`Cannot subscribe to doctype ${doctype}: ${error.message}`)
throw error
}
} else {
setTimeout(() => {
subscribeWhenReady(doctype, socket)
}, 10)
}
}
|
javascript
|
function subscribeWhenReady(doctype, socket) {
if (socket.readyState === WEBSOCKET_STATE.OPEN) {
try {
socket.send(
JSON.stringify({
method: 'SUBSCRIBE',
payload: {
type: doctype
}
})
)
} catch (error) {
// eslint-disable-next-line no-console
console.warn(`Cannot subscribe to doctype ${doctype}: ${error.message}`)
throw error
}
} else {
setTimeout(() => {
subscribeWhenReady(doctype, socket)
}, 10)
}
}
|
[
"function",
"subscribeWhenReady",
"(",
"doctype",
",",
"socket",
")",
"{",
"if",
"(",
"socket",
".",
"readyState",
"===",
"WEBSOCKET_STATE",
".",
"OPEN",
")",
"{",
"try",
"{",
"socket",
".",
"send",
"(",
"JSON",
".",
"stringify",
"(",
"{",
"method",
":",
"'SUBSCRIBE'",
",",
"payload",
":",
"{",
"type",
":",
"doctype",
"}",
"}",
")",
")",
"}",
"catch",
"(",
"error",
")",
"{",
"// eslint-disable-next-line no-console",
"console",
".",
"warn",
"(",
"`",
"${",
"doctype",
"}",
"${",
"error",
".",
"message",
"}",
"`",
")",
"throw",
"error",
"}",
"}",
"else",
"{",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"subscribeWhenReady",
"(",
"doctype",
",",
"socket",
")",
"}",
",",
"10",
")",
"}",
"}"
] |
Send a subscribe message for the given doctype trough the given websocket, but only if it is in a ready state. If not, retry a few milliseconds later.
|
[
"Send",
"a",
"subscribe",
"message",
"for",
"the",
"given",
"doctype",
"trough",
"the",
"given",
"websocket",
"but",
"only",
"if",
"it",
"is",
"in",
"a",
"ready",
"state",
".",
"If",
"not",
"retry",
"a",
"few",
"milliseconds",
"later",
"."
] |
c9df834bd2ddba1f1830c950efc6f5bd49531e32
|
https://github.com/cozy/cozy-home/blob/c9df834bd2ddba1f1830c950efc6f5bd49531e32/src/lib/realtime.js#L23-L44
|
19,290
|
webtorrent/create-torrent
|
index.js
|
createTorrent
|
function createTorrent (input, opts, cb) {
if (typeof opts === 'function') [ opts, cb ] = [ cb, opts ]
opts = opts ? Object.assign({}, opts) : {}
_parseInput(input, opts, (err, files, singleFileTorrent) => {
if (err) return cb(err)
opts.singleFileTorrent = singleFileTorrent
onFiles(files, opts, cb)
})
}
|
javascript
|
function createTorrent (input, opts, cb) {
if (typeof opts === 'function') [ opts, cb ] = [ cb, opts ]
opts = opts ? Object.assign({}, opts) : {}
_parseInput(input, opts, (err, files, singleFileTorrent) => {
if (err) return cb(err)
opts.singleFileTorrent = singleFileTorrent
onFiles(files, opts, cb)
})
}
|
[
"function",
"createTorrent",
"(",
"input",
",",
"opts",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"opts",
"===",
"'function'",
")",
"[",
"opts",
",",
"cb",
"]",
"=",
"[",
"cb",
",",
"opts",
"]",
"opts",
"=",
"opts",
"?",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"opts",
")",
":",
"{",
"}",
"_parseInput",
"(",
"input",
",",
"opts",
",",
"(",
"err",
",",
"files",
",",
"singleFileTorrent",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"opts",
".",
"singleFileTorrent",
"=",
"singleFileTorrent",
"onFiles",
"(",
"files",
",",
"opts",
",",
"cb",
")",
"}",
")",
"}"
] |
Create a torrent.
@param {string|File|FileList|Buffer|Stream|Array.<string|File|Buffer|Stream>} input
@param {Object} opts
@param {string=} opts.name
@param {Date=} opts.creationDate
@param {string=} opts.comment
@param {string=} opts.createdBy
@param {boolean|number=} opts.private
@param {number=} opts.pieceLength
@param {Array.<Array.<string>>=} opts.announceList
@param {Array.<string>=} opts.urlList
@param {function} cb
@return {Buffer} buffer of .torrent file data
|
[
"Create",
"a",
"torrent",
"."
] |
6e6fc18aac7d212a5a8d9c766b12a525618e9ceb
|
https://github.com/webtorrent/create-torrent/blob/6e6fc18aac7d212a5a8d9c766b12a525618e9ceb/index.js#L42-L51
|
19,291
|
webtorrent/create-torrent
|
index.js
|
getStreamStream
|
function getStreamStream (readable, file) {
return () => {
const counter = new stream.Transform()
counter._transform = function (buf, enc, done) {
file.length += buf.length
this.push(buf)
done()
}
readable.pipe(counter)
return counter
}
}
|
javascript
|
function getStreamStream (readable, file) {
return () => {
const counter = new stream.Transform()
counter._transform = function (buf, enc, done) {
file.length += buf.length
this.push(buf)
done()
}
readable.pipe(counter)
return counter
}
}
|
[
"function",
"getStreamStream",
"(",
"readable",
",",
"file",
")",
"{",
"return",
"(",
")",
"=>",
"{",
"const",
"counter",
"=",
"new",
"stream",
".",
"Transform",
"(",
")",
"counter",
".",
"_transform",
"=",
"function",
"(",
"buf",
",",
"enc",
",",
"done",
")",
"{",
"file",
".",
"length",
"+=",
"buf",
".",
"length",
"this",
".",
"push",
"(",
"buf",
")",
"done",
"(",
")",
"}",
"readable",
".",
"pipe",
"(",
"counter",
")",
"return",
"counter",
"}",
"}"
] |
Convert a readable stream to a lazy readable stream. Adds instrumentation to track
the number of bytes in the stream and set `file.length`.
@param {Stream} stream
@param {Object} file
@return {function}
|
[
"Convert",
"a",
"readable",
"stream",
"to",
"a",
"lazy",
"readable",
"stream",
".",
"Adds",
"instrumentation",
"to",
"track",
"the",
"number",
"of",
"bytes",
"in",
"the",
"stream",
"and",
"set",
"file",
".",
"length",
"."
] |
6e6fc18aac7d212a5a8d9c766b12a525618e9ceb
|
https://github.com/webtorrent/create-torrent/blob/6e6fc18aac7d212a5a8d9c766b12a525618e9ceb/index.js#L466-L477
|
19,292
|
foreverjs/nssocket
|
lib/nssocket.js
|
doReconnect
|
function doReconnect() {
//
// Cleanup and recreate the socket associated
// with this instance.
//
self.retry.waiting = true;
self.socket.removeAllListeners();
self.socket = common.createSocket(self._options);
//
// Cleanup reconnect logic once the socket connects
//
self.socket.once('connect', function () {
self.retry.waiting = false;
self.retry.retries = 0;
});
//
// Attempt to reconnect the socket
//
self._setup();
self.connect();
}
|
javascript
|
function doReconnect() {
//
// Cleanup and recreate the socket associated
// with this instance.
//
self.retry.waiting = true;
self.socket.removeAllListeners();
self.socket = common.createSocket(self._options);
//
// Cleanup reconnect logic once the socket connects
//
self.socket.once('connect', function () {
self.retry.waiting = false;
self.retry.retries = 0;
});
//
// Attempt to reconnect the socket
//
self._setup();
self.connect();
}
|
[
"function",
"doReconnect",
"(",
")",
"{",
"//",
"// Cleanup and recreate the socket associated",
"// with this instance.",
"//",
"self",
".",
"retry",
".",
"waiting",
"=",
"true",
";",
"self",
".",
"socket",
".",
"removeAllListeners",
"(",
")",
";",
"self",
".",
"socket",
"=",
"common",
".",
"createSocket",
"(",
"self",
".",
"_options",
")",
";",
"//",
"// Cleanup reconnect logic once the socket connects",
"//",
"self",
".",
"socket",
".",
"once",
"(",
"'connect'",
",",
"function",
"(",
")",
"{",
"self",
".",
"retry",
".",
"waiting",
"=",
"false",
";",
"self",
".",
"retry",
".",
"retries",
"=",
"0",
";",
"}",
")",
";",
"//",
"// Attempt to reconnect the socket",
"//",
"self",
".",
"_setup",
"(",
")",
";",
"self",
".",
"connect",
"(",
")",
";",
"}"
] |
Helper function containing the core reconnect logic
|
[
"Helper",
"function",
"containing",
"the",
"core",
"reconnect",
"logic"
] |
ef5be453c895cdfca297a4e15cf5c783d1296515
|
https://github.com/foreverjs/nssocket/blob/ef5be453c895cdfca297a4e15cf5c783d1296515/lib/nssocket.js#L315-L337
|
19,293
|
foreverjs/nssocket
|
lib/nssocket.js
|
tryReconnect
|
function tryReconnect() {
self.retry.retries++;
if (self.retry.retries >= self.retry.max) {
return self.emit('error', new Error('Did not reconnect after maximum retries: ' + self.retry.max));
}
doReconnect();
}
|
javascript
|
function tryReconnect() {
self.retry.retries++;
if (self.retry.retries >= self.retry.max) {
return self.emit('error', new Error('Did not reconnect after maximum retries: ' + self.retry.max));
}
doReconnect();
}
|
[
"function",
"tryReconnect",
"(",
")",
"{",
"self",
".",
"retry",
".",
"retries",
"++",
";",
"if",
"(",
"self",
".",
"retry",
".",
"retries",
">=",
"self",
".",
"retry",
".",
"max",
")",
"{",
"return",
"self",
".",
"emit",
"(",
"'error'",
",",
"new",
"Error",
"(",
"'Did not reconnect after maximum retries: '",
"+",
"self",
".",
"retry",
".",
"max",
")",
")",
";",
"}",
"doReconnect",
"(",
")",
";",
"}"
] |
Helper function which attempts to retry if it is less than the maximum
|
[
"Helper",
"function",
"which",
"attempts",
"to",
"retry",
"if",
"it",
"is",
"less",
"than",
"the",
"maximum"
] |
ef5be453c895cdfca297a4e15cf5c783d1296515
|
https://github.com/foreverjs/nssocket/blob/ef5be453c895cdfca297a4e15cf5c783d1296515/lib/nssocket.js#L343-L350
|
19,294
|
tj/better-assert
|
index.js
|
assert
|
function assert(expr) {
if (expr) return;
var stack = callsite();
var call = stack[1];
var file = call.getFileName();
var lineno = call.getLineNumber();
var src = fs.readFileSync(file, 'utf8');
var line = src.split('\n')[lineno-1];
var src = line.match(/assert\((.*)\)/)[1];
var err = new AssertionError({
message: src,
stackStartFunction: stack[0].getFunction()
});
throw err;
}
|
javascript
|
function assert(expr) {
if (expr) return;
var stack = callsite();
var call = stack[1];
var file = call.getFileName();
var lineno = call.getLineNumber();
var src = fs.readFileSync(file, 'utf8');
var line = src.split('\n')[lineno-1];
var src = line.match(/assert\((.*)\)/)[1];
var err = new AssertionError({
message: src,
stackStartFunction: stack[0].getFunction()
});
throw err;
}
|
[
"function",
"assert",
"(",
"expr",
")",
"{",
"if",
"(",
"expr",
")",
"return",
";",
"var",
"stack",
"=",
"callsite",
"(",
")",
";",
"var",
"call",
"=",
"stack",
"[",
"1",
"]",
";",
"var",
"file",
"=",
"call",
".",
"getFileName",
"(",
")",
";",
"var",
"lineno",
"=",
"call",
".",
"getLineNumber",
"(",
")",
";",
"var",
"src",
"=",
"fs",
".",
"readFileSync",
"(",
"file",
",",
"'utf8'",
")",
";",
"var",
"line",
"=",
"src",
".",
"split",
"(",
"'\\n'",
")",
"[",
"lineno",
"-",
"1",
"]",
";",
"var",
"src",
"=",
"line",
".",
"match",
"(",
"/",
"assert\\((.*)\\)",
"/",
")",
"[",
"1",
"]",
";",
"var",
"err",
"=",
"new",
"AssertionError",
"(",
"{",
"message",
":",
"src",
",",
"stackStartFunction",
":",
"stack",
"[",
"0",
"]",
".",
"getFunction",
"(",
")",
"}",
")",
";",
"throw",
"err",
";",
"}"
] |
Assert the given `expr`.
|
[
"Assert",
"the",
"given",
"expr",
"."
] |
dadbe26bc0fb86eeddd14f4651ee56a4a0f4126e
|
https://github.com/tj/better-assert/blob/dadbe26bc0fb86eeddd14f4651ee56a4a0f4126e/index.js#L21-L38
|
19,295
|
jDataView/jDataView
|
src/jdataview.js
|
add
|
function add(x, y) {
var z = [];
var n = Math.max(x.length, y.length);
var carry = 0;
var i = 0;
while (i < n || carry) {
var xi = i < x.length ? x[i] : 0;
var yi = i < y.length ? y[i] : 0;
var zi = carry + xi + yi;
z.push(zi % 10);
carry = Math.floor(zi / 10);
i++;
}
return z;
}
|
javascript
|
function add(x, y) {
var z = [];
var n = Math.max(x.length, y.length);
var carry = 0;
var i = 0;
while (i < n || carry) {
var xi = i < x.length ? x[i] : 0;
var yi = i < y.length ? y[i] : 0;
var zi = carry + xi + yi;
z.push(zi % 10);
carry = Math.floor(zi / 10);
i++;
}
return z;
}
|
[
"function",
"add",
"(",
"x",
",",
"y",
")",
"{",
"var",
"z",
"=",
"[",
"]",
";",
"var",
"n",
"=",
"Math",
".",
"max",
"(",
"x",
".",
"length",
",",
"y",
".",
"length",
")",
";",
"var",
"carry",
"=",
"0",
";",
"var",
"i",
"=",
"0",
";",
"while",
"(",
"i",
"<",
"n",
"||",
"carry",
")",
"{",
"var",
"xi",
"=",
"i",
"<",
"x",
".",
"length",
"?",
"x",
"[",
"i",
"]",
":",
"0",
";",
"var",
"yi",
"=",
"i",
"<",
"y",
".",
"length",
"?",
"y",
"[",
"i",
"]",
":",
"0",
";",
"var",
"zi",
"=",
"carry",
"+",
"xi",
"+",
"yi",
";",
"z",
".",
"push",
"(",
"zi",
"%",
"10",
")",
";",
"carry",
"=",
"Math",
".",
"floor",
"(",
"zi",
"/",
"10",
")",
";",
"i",
"++",
";",
"}",
"return",
"z",
";",
"}"
] |
Adds two digit arrays, returning the result.
|
[
"Adds",
"two",
"digit",
"arrays",
"returning",
"the",
"result",
"."
] |
c9c29eac67c54de78ac48d16e5dffc5194a0c7bf
|
https://github.com/jDataView/jDataView/blob/c9c29eac67c54de78ac48d16e5dffc5194a0c7bf/src/jdataview.js#L254-L268
|
19,296
|
MarkBind/markbind
|
src/Site.js
|
getPluginPath
|
function getPluginPath(rootPath, plugin) {
// Check in project folder
const pluginPath = path.join(rootPath, PROJECT_PLUGIN_FOLDER_NAME, `${plugin}.js`);
if (fs.existsSync(pluginPath)) {
return pluginPath;
}
// Check in src folder
const srcPath = path.join(__dirname, BUILT_IN_PLUGIN_FOLDER_NAME, `${plugin}.js`);
if (fs.existsSync(srcPath)) {
return srcPath;
}
// Check in default folder
const defaultPath = path.join(__dirname, BUILT_IN_DEFAULT_PLUGIN_FOLDER_NAME, `${plugin}.js`);
if (fs.existsSync(defaultPath)) {
return defaultPath;
}
return '';
}
|
javascript
|
function getPluginPath(rootPath, plugin) {
// Check in project folder
const pluginPath = path.join(rootPath, PROJECT_PLUGIN_FOLDER_NAME, `${plugin}.js`);
if (fs.existsSync(pluginPath)) {
return pluginPath;
}
// Check in src folder
const srcPath = path.join(__dirname, BUILT_IN_PLUGIN_FOLDER_NAME, `${plugin}.js`);
if (fs.existsSync(srcPath)) {
return srcPath;
}
// Check in default folder
const defaultPath = path.join(__dirname, BUILT_IN_DEFAULT_PLUGIN_FOLDER_NAME, `${plugin}.js`);
if (fs.existsSync(defaultPath)) {
return defaultPath;
}
return '';
}
|
[
"function",
"getPluginPath",
"(",
"rootPath",
",",
"plugin",
")",
"{",
"// Check in project folder",
"const",
"pluginPath",
"=",
"path",
".",
"join",
"(",
"rootPath",
",",
"PROJECT_PLUGIN_FOLDER_NAME",
",",
"`",
"${",
"plugin",
"}",
"`",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"pluginPath",
")",
")",
"{",
"return",
"pluginPath",
";",
"}",
"// Check in src folder",
"const",
"srcPath",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"BUILT_IN_PLUGIN_FOLDER_NAME",
",",
"`",
"${",
"plugin",
"}",
"`",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"srcPath",
")",
")",
"{",
"return",
"srcPath",
";",
"}",
"// Check in default folder",
"const",
"defaultPath",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"BUILT_IN_DEFAULT_PLUGIN_FOLDER_NAME",
",",
"`",
"${",
"plugin",
"}",
"`",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"defaultPath",
")",
")",
"{",
"return",
"defaultPath",
";",
"}",
"return",
"''",
";",
"}"
] |
Retrieves the correct plugin path for a plugin name, if not in node_modules
@param rootPath root of the project
@param plugin name of the plugin
|
[
"Retrieves",
"the",
"correct",
"plugin",
"path",
"for",
"a",
"plugin",
"name",
"if",
"not",
"in",
"node_modules"
] |
4d1101243781742448475993b43b6da2921836ab
|
https://github.com/MarkBind/markbind/blob/4d1101243781742448475993b43b6da2921836ab/src/Site.js#L871-L891
|
19,297
|
MarkBind/markbind
|
src/Site.js
|
findDefaultPlugins
|
function findDefaultPlugins() {
const globPath = path.join(__dirname, BUILT_IN_DEFAULT_PLUGIN_FOLDER_NAME);
if (!fs.existsSync(globPath)) {
return [];
}
return walkSync(globPath, {
directories: false,
globs: [`${MARKBIND_PLUGIN_PREFIX}*.js`],
}).map(file => path.parse(file).name);
}
|
javascript
|
function findDefaultPlugins() {
const globPath = path.join(__dirname, BUILT_IN_DEFAULT_PLUGIN_FOLDER_NAME);
if (!fs.existsSync(globPath)) {
return [];
}
return walkSync(globPath, {
directories: false,
globs: [`${MARKBIND_PLUGIN_PREFIX}*.js`],
}).map(file => path.parse(file).name);
}
|
[
"function",
"findDefaultPlugins",
"(",
")",
"{",
"const",
"globPath",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"BUILT_IN_DEFAULT_PLUGIN_FOLDER_NAME",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"globPath",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"return",
"walkSync",
"(",
"globPath",
",",
"{",
"directories",
":",
"false",
",",
"globs",
":",
"[",
"`",
"${",
"MARKBIND_PLUGIN_PREFIX",
"}",
"`",
"]",
",",
"}",
")",
".",
"map",
"(",
"file",
"=>",
"path",
".",
"parse",
"(",
"file",
")",
".",
"name",
")",
";",
"}"
] |
Finds plugins in the site's default plugin folder
|
[
"Finds",
"plugins",
"in",
"the",
"site",
"s",
"default",
"plugin",
"folder"
] |
4d1101243781742448475993b43b6da2921836ab
|
https://github.com/MarkBind/markbind/blob/4d1101243781742448475993b43b6da2921836ab/src/Site.js#L896-L905
|
19,298
|
MarkBind/markbind
|
src/plugins/filterTags.js
|
filterTags
|
function filterTags(tags, content) {
if (!tags) {
return content;
}
const $ = cheerio.load(content, { xmlMode: false });
const tagOperations = tags.map(tag => ({
// Trim leading + or -, replace * with .*, add ^ and $
tagExp: `^${escapeRegExp(tag.replace(/^(\+|-)/g, '')).replace(/\\\*/, '.*')}$`,
// Whether it is makes tags visible or hides them
isHidden: tag.startsWith('-'),
}));
$('[tags]').each((i, element) => {
$(element).attr('hidden', true);
$(element).attr('tags').split(' ').forEach((tag) => {
tagOperations.forEach((tagOperation) => {
if (!tag.match(tagOperation.tagExp)) {
return;
}
if (tagOperation.isHidden) {
$(element).attr('hidden', true);
} else {
$(element).removeAttr('hidden');
}
});
});
});
$('[hidden]').remove();
return $.html();
}
|
javascript
|
function filterTags(tags, content) {
if (!tags) {
return content;
}
const $ = cheerio.load(content, { xmlMode: false });
const tagOperations = tags.map(tag => ({
// Trim leading + or -, replace * with .*, add ^ and $
tagExp: `^${escapeRegExp(tag.replace(/^(\+|-)/g, '')).replace(/\\\*/, '.*')}$`,
// Whether it is makes tags visible or hides them
isHidden: tag.startsWith('-'),
}));
$('[tags]').each((i, element) => {
$(element).attr('hidden', true);
$(element).attr('tags').split(' ').forEach((tag) => {
tagOperations.forEach((tagOperation) => {
if (!tag.match(tagOperation.tagExp)) {
return;
}
if (tagOperation.isHidden) {
$(element).attr('hidden', true);
} else {
$(element).removeAttr('hidden');
}
});
});
});
$('[hidden]').remove();
return $.html();
}
|
[
"function",
"filterTags",
"(",
"tags",
",",
"content",
")",
"{",
"if",
"(",
"!",
"tags",
")",
"{",
"return",
"content",
";",
"}",
"const",
"$",
"=",
"cheerio",
".",
"load",
"(",
"content",
",",
"{",
"xmlMode",
":",
"false",
"}",
")",
";",
"const",
"tagOperations",
"=",
"tags",
".",
"map",
"(",
"tag",
"=>",
"(",
"{",
"// Trim leading + or -, replace * with .*, add ^ and $",
"tagExp",
":",
"`",
"${",
"escapeRegExp",
"(",
"tag",
".",
"replace",
"(",
"/",
"^(\\+|-)",
"/",
"g",
",",
"''",
")",
")",
".",
"replace",
"(",
"/",
"\\\\\\*",
"/",
",",
"'.*'",
")",
"}",
"`",
",",
"// Whether it is makes tags visible or hides them",
"isHidden",
":",
"tag",
".",
"startsWith",
"(",
"'-'",
")",
",",
"}",
")",
")",
";",
"$",
"(",
"'[tags]'",
")",
".",
"each",
"(",
"(",
"i",
",",
"element",
")",
"=>",
"{",
"$",
"(",
"element",
")",
".",
"attr",
"(",
"'hidden'",
",",
"true",
")",
";",
"$",
"(",
"element",
")",
".",
"attr",
"(",
"'tags'",
")",
".",
"split",
"(",
"' '",
")",
".",
"forEach",
"(",
"(",
"tag",
")",
"=>",
"{",
"tagOperations",
".",
"forEach",
"(",
"(",
"tagOperation",
")",
"=>",
"{",
"if",
"(",
"!",
"tag",
".",
"match",
"(",
"tagOperation",
".",
"tagExp",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"tagOperation",
".",
"isHidden",
")",
"{",
"$",
"(",
"element",
")",
".",
"attr",
"(",
"'hidden'",
",",
"true",
")",
";",
"}",
"else",
"{",
"$",
"(",
"element",
")",
".",
"removeAttr",
"(",
"'hidden'",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"$",
"(",
"'[hidden]'",
")",
".",
"remove",
"(",
")",
";",
"return",
"$",
".",
"html",
"(",
")",
";",
"}"
] |
Filters out elements on the page based on config tags
@param tags to filter
@param content of the page
|
[
"Filters",
"out",
"elements",
"on",
"the",
"page",
"based",
"on",
"config",
"tags"
] |
4d1101243781742448475993b43b6da2921836ab
|
https://github.com/MarkBind/markbind/blob/4d1101243781742448475993b43b6da2921836ab/src/plugins/filterTags.js#L9-L37
|
19,299
|
MarkBind/markbind
|
__mocks__/fs-extra-promise.js
|
rimraf
|
function rimraf(dirPath) {
if (fs.existsSync(dirPath)) {
fs.readdirSync(dirPath).forEach((entry) => {
const entryPath = path.join(dirPath, entry);
if (fs.lstatSync(entryPath).isDirectory()) {
rimraf(entryPath);
} else {
fs.unlinkSync(entryPath);
}
});
fs.rmdirSync(dirPath);
}
}
|
javascript
|
function rimraf(dirPath) {
if (fs.existsSync(dirPath)) {
fs.readdirSync(dirPath).forEach((entry) => {
const entryPath = path.join(dirPath, entry);
if (fs.lstatSync(entryPath).isDirectory()) {
rimraf(entryPath);
} else {
fs.unlinkSync(entryPath);
}
});
fs.rmdirSync(dirPath);
}
}
|
[
"function",
"rimraf",
"(",
"dirPath",
")",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"dirPath",
")",
")",
"{",
"fs",
".",
"readdirSync",
"(",
"dirPath",
")",
".",
"forEach",
"(",
"(",
"entry",
")",
"=>",
"{",
"const",
"entryPath",
"=",
"path",
".",
"join",
"(",
"dirPath",
",",
"entry",
")",
";",
"if",
"(",
"fs",
".",
"lstatSync",
"(",
"entryPath",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"rimraf",
"(",
"entryPath",
")",
";",
"}",
"else",
"{",
"fs",
".",
"unlinkSync",
"(",
"entryPath",
")",
";",
"}",
"}",
")",
";",
"fs",
".",
"rmdirSync",
"(",
"dirPath",
")",
";",
"}",
"}"
] |
Utils
Remove directory recursively
@param {string} dirPath
@see https://stackoverflow.com/a/42505874/3027390
|
[
"Utils",
"Remove",
"directory",
"recursively"
] |
4d1101243781742448475993b43b6da2921836ab
|
https://github.com/MarkBind/markbind/blob/4d1101243781742448475993b43b6da2921836ab/__mocks__/fs-extra-promise.js#L14-L26
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.