repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
canjs/can-set | src/set-core.js | concatUnique | function concatUnique(aItems, bItems, algebra) {
var idTree = {};
var aSet;
// IE 9 and 10 don't have Set.
if(typeof Set !== "undefined") {
aSet = new Set(); // jshint ignore:line
}
aItems.forEach(function(item) {
var keyNode = idTree;
if(aSet) {
aSet.add(item);
}
each(algebra.clauses.id, function(prop) {
var propVal = getProp(item, prop);
if(keyNode && typeof propVal !== "undefined") {
keyNode = keyNode[propVal] = keyNode[propVal] || {};
} else {
keyNode = undefined;
}
});
});
return aItems.concat(bItems.filter(function(item) {
var keyNode = idTree;
if(aSet && aSet.has(item)) {
return false;
}
// IE9/10 case
if(!aSet && aItems.indexOf(item) > -1) {
return false;
}
each(algebra.clauses.id, function(prop) {
keyNode = keyNode && keyNode[getProp(item, prop)];
});
return keyNode === idTree || !keyNode;
}));
} | javascript | function concatUnique(aItems, bItems, algebra) {
var idTree = {};
var aSet;
// IE 9 and 10 don't have Set.
if(typeof Set !== "undefined") {
aSet = new Set(); // jshint ignore:line
}
aItems.forEach(function(item) {
var keyNode = idTree;
if(aSet) {
aSet.add(item);
}
each(algebra.clauses.id, function(prop) {
var propVal = getProp(item, prop);
if(keyNode && typeof propVal !== "undefined") {
keyNode = keyNode[propVal] = keyNode[propVal] || {};
} else {
keyNode = undefined;
}
});
});
return aItems.concat(bItems.filter(function(item) {
var keyNode = idTree;
if(aSet && aSet.has(item)) {
return false;
}
// IE9/10 case
if(!aSet && aItems.indexOf(item) > -1) {
return false;
}
each(algebra.clauses.id, function(prop) {
keyNode = keyNode && keyNode[getProp(item, prop)];
});
return keyNode === idTree || !keyNode;
}));
} | [
"function",
"concatUnique",
"(",
"aItems",
",",
"bItems",
",",
"algebra",
")",
"{",
"var",
"idTree",
"=",
"{",
"}",
";",
"var",
"aSet",
";",
"if",
"(",
"typeof",
"Set",
"!==",
"\"undefined\"",
")",
"{",
"aSet",
"=",
"new",
"Set",
"(",
")",
";",
"}",
"aItems",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"var",
"keyNode",
"=",
"idTree",
";",
"if",
"(",
"aSet",
")",
"{",
"aSet",
".",
"add",
"(",
"item",
")",
";",
"}",
"each",
"(",
"algebra",
".",
"clauses",
".",
"id",
",",
"function",
"(",
"prop",
")",
"{",
"var",
"propVal",
"=",
"getProp",
"(",
"item",
",",
"prop",
")",
";",
"if",
"(",
"keyNode",
"&&",
"typeof",
"propVal",
"!==",
"\"undefined\"",
")",
"{",
"keyNode",
"=",
"keyNode",
"[",
"propVal",
"]",
"=",
"keyNode",
"[",
"propVal",
"]",
"||",
"{",
"}",
";",
"}",
"else",
"{",
"keyNode",
"=",
"undefined",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"return",
"aItems",
".",
"concat",
"(",
"bItems",
".",
"filter",
"(",
"function",
"(",
"item",
")",
"{",
"var",
"keyNode",
"=",
"idTree",
";",
"if",
"(",
"aSet",
"&&",
"aSet",
".",
"has",
"(",
"item",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"aSet",
"&&",
"aItems",
".",
"indexOf",
"(",
"item",
")",
">",
"-",
"1",
")",
"{",
"return",
"false",
";",
"}",
"each",
"(",
"algebra",
".",
"clauses",
".",
"id",
",",
"function",
"(",
"prop",
")",
"{",
"keyNode",
"=",
"keyNode",
"&&",
"keyNode",
"[",
"getProp",
"(",
"item",
",",
"prop",
")",
"]",
";",
"}",
")",
";",
"return",
"keyNode",
"===",
"idTree",
"||",
"!",
"keyNode",
";",
"}",
")",
")",
";",
"}"
] | concatUnique concat all items in bItems onto aItems that do not already exist in aItems. same-object and ID collisions are both looked at when deciding whether an item matches another. | [
"concatUnique",
"concat",
"all",
"items",
"in",
"bItems",
"onto",
"aItems",
"that",
"do",
"not",
"already",
"exist",
"in",
"aItems",
".",
"same",
"-",
"object",
"and",
"ID",
"collisions",
"are",
"both",
"looked",
"at",
"when",
"deciding",
"whether",
"an",
"item",
"matches",
"another",
"."
] | d7123f41fdadc103a2b2bac99bb05a6537af307a | https://github.com/canjs/can-set/blob/d7123f41fdadc103a2b2bac99bb05a6537af307a/src/set-core.js#L16-L53 | train |
canjs/can-set | src/set-core.js | function(){
var clauses = this.clauses = {
where: {},
order: {},
paginate: {},
id: {}
};
this.translators = {
where: new Translate("where", {
fromSet: function(set, setRemainder){
return setRemainder;
},
toSet: function(set, wheres){
return assign(set, wheres);
}
})
};
var self = this;
each(arguments, function(arg) {
if(arg) {
if(arg instanceof Translate) {
self.translators[arg.clause] = arg;
} else {
assign(clauses[arg.constructor.type || 'where'], arg);
}
}
});
} | javascript | function(){
var clauses = this.clauses = {
where: {},
order: {},
paginate: {},
id: {}
};
this.translators = {
where: new Translate("where", {
fromSet: function(set, setRemainder){
return setRemainder;
},
toSet: function(set, wheres){
return assign(set, wheres);
}
})
};
var self = this;
each(arguments, function(arg) {
if(arg) {
if(arg instanceof Translate) {
self.translators[arg.clause] = arg;
} else {
assign(clauses[arg.constructor.type || 'where'], arg);
}
}
});
} | [
"function",
"(",
")",
"{",
"var",
"clauses",
"=",
"this",
".",
"clauses",
"=",
"{",
"where",
":",
"{",
"}",
",",
"order",
":",
"{",
"}",
",",
"paginate",
":",
"{",
"}",
",",
"id",
":",
"{",
"}",
"}",
";",
"this",
".",
"translators",
"=",
"{",
"where",
":",
"new",
"Translate",
"(",
"\"where\"",
",",
"{",
"fromSet",
":",
"function",
"(",
"set",
",",
"setRemainder",
")",
"{",
"return",
"setRemainder",
";",
"}",
",",
"toSet",
":",
"function",
"(",
"set",
",",
"wheres",
")",
"{",
"return",
"assign",
"(",
"set",
",",
"wheres",
")",
";",
"}",
"}",
")",
"}",
";",
"var",
"self",
"=",
"this",
";",
"each",
"(",
"arguments",
",",
"function",
"(",
"arg",
")",
"{",
"if",
"(",
"arg",
")",
"{",
"if",
"(",
"arg",
"instanceof",
"Translate",
")",
"{",
"self",
".",
"translators",
"[",
"arg",
".",
"clause",
"]",
"=",
"arg",
";",
"}",
"else",
"{",
"assign",
"(",
"clauses",
"[",
"arg",
".",
"constructor",
".",
"type",
"||",
"'where'",
"]",
",",
"arg",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | An `Algebra` internally keeps different properties organized by clause type.
If an object comes in that isn't a clause type, it's assuemd to be a where.
new set.Algebra(Where(),Paginate(),Sort())
@hide | [
"An",
"Algebra",
"internally",
"keeps",
"different",
"properties",
"organized",
"by",
"clause",
"type",
".",
"If",
"an",
"object",
"comes",
"in",
"that",
"isn",
"t",
"a",
"clause",
"type",
"it",
"s",
"assuemd",
"to",
"be",
"a",
"where",
"."
] | d7123f41fdadc103a2b2bac99bb05a6537af307a | https://github.com/canjs/can-set/blob/d7123f41fdadc103a2b2bac99bb05a6537af307a/src/set-core.js#L103-L131 | train |
|
canjs/can-set | src/set-core.js | function(aClauses, bClauses) {
var self = this;
var differentTypes = [];
each(clause.TYPES, function(type) {
if( !self.evaluateOperator(compare.equal, aClauses[type], bClauses[type], {isProperties: true},{isProperties:true}) ) {
differentTypes.push(type);
}
});
return differentTypes;
} | javascript | function(aClauses, bClauses) {
var self = this;
var differentTypes = [];
each(clause.TYPES, function(type) {
if( !self.evaluateOperator(compare.equal, aClauses[type], bClauses[type], {isProperties: true},{isProperties:true}) ) {
differentTypes.push(type);
}
});
return differentTypes;
} | [
"function",
"(",
"aClauses",
",",
"bClauses",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"differentTypes",
"=",
"[",
"]",
";",
"each",
"(",
"clause",
".",
"TYPES",
",",
"function",
"(",
"type",
")",
"{",
"if",
"(",
"!",
"self",
".",
"evaluateOperator",
"(",
"compare",
".",
"equal",
",",
"aClauses",
"[",
"type",
"]",
",",
"bClauses",
"[",
"type",
"]",
",",
"{",
"isProperties",
":",
"true",
"}",
",",
"{",
"isProperties",
":",
"true",
"}",
")",
")",
"{",
"differentTypes",
".",
"push",
"(",
"type",
")",
";",
"}",
"}",
")",
";",
"return",
"differentTypes",
";",
"}"
] | Given the broken out clause properties of `getClauseProperties` returns the names of the clauses that aren't exactly equal. | [
"Given",
"the",
"broken",
"out",
"clause",
"properties",
"of",
"getClauseProperties",
"returns",
"the",
"names",
"of",
"the",
"clauses",
"that",
"aren",
"t",
"exactly",
"equal",
"."
] | d7123f41fdadc103a2b2bac99bb05a6537af307a | https://github.com/canjs/can-set/blob/d7123f41fdadc103a2b2bac99bb05a6537af307a/src/set-core.js#L207-L218 | train |
|
canjs/can-set | src/set-core.js | function(set, clause, result, useSet) {
if(result && typeof result === "object" && useSet !== false) {
if( this.translators[clause] ) {
set = this.translators.where.toSet(set, result);
} else {
set = assign(set, result);
}
return true;
}
else if(result) {
return useSet === undefined ? undefined : false;
}
else {
return false;
}
} | javascript | function(set, clause, result, useSet) {
if(result && typeof result === "object" && useSet !== false) {
if( this.translators[clause] ) {
set = this.translators.where.toSet(set, result);
} else {
set = assign(set, result);
}
return true;
}
else if(result) {
return useSet === undefined ? undefined : false;
}
else {
return false;
}
} | [
"function",
"(",
"set",
",",
"clause",
",",
"result",
",",
"useSet",
")",
"{",
"if",
"(",
"result",
"&&",
"typeof",
"result",
"===",
"\"object\"",
"&&",
"useSet",
"!==",
"false",
")",
"{",
"if",
"(",
"this",
".",
"translators",
"[",
"clause",
"]",
")",
"{",
"set",
"=",
"this",
".",
"translators",
".",
"where",
".",
"toSet",
"(",
"set",
",",
"result",
")",
";",
"}",
"else",
"{",
"set",
"=",
"assign",
"(",
"set",
",",
"result",
")",
";",
"}",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"result",
")",
"{",
"return",
"useSet",
"===",
"undefined",
"?",
"undefined",
":",
"false",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | updates the set data with a result. - `set` - the current set - `clause` - which clause this is on - `result` - a boolean or set data - `useSet` - indicates to use the set or a boolean response | [
"updates",
"the",
"set",
"data",
"with",
"a",
"result",
".",
"-",
"set",
"-",
"the",
"current",
"set",
"-",
"clause",
"-",
"which",
"clause",
"this",
"is",
"on",
"-",
"result",
"-",
"a",
"boolean",
"or",
"set",
"data",
"-",
"useSet",
"-",
"indicates",
"to",
"use",
"the",
"set",
"or",
"a",
"boolean",
"response"
] | d7123f41fdadc103a2b2bac99bb05a6537af307a | https://github.com/canjs/can-set/blob/d7123f41fdadc103a2b2bac99bb05a6537af307a/src/set-core.js#L224-L239 | train |
|
canjs/can-set | src/set-core.js | function(operator, a, b, aOptions, bOptions, evaluateOptions) {
aOptions = aOptions || {};
bOptions = bOptions || {};
evaluateOptions = assign({
evaluateWhere: operator,
evaluatePaginate: operator,
evaluateOrder: operator,
shouldEvaluatePaginate: function(aClauseProps, bClauseProps) {
return aClauseProps.enabled.paginate || bClauseProps.enabled.paginate;
},
shouldEvaluateOrder: function(aClauseProps, bClauseProps) {
return aClauseProps.enabled.order && compare.equal(aClauseProps.order, bClauseProps.order, undefined, undefined, undefined,{},{});
}
/* aClauseProps.enabled.order || bClauseProps.enabled.order */
}, evaluateOptions||{});
var aClauseProps = this.getClauseProperties(a, aOptions),
bClauseProps = this.getClauseProperties(b, bOptions),
set = {},
useSet;
var result = evaluateOptions.evaluateWhere(aClauseProps.where, bClauseProps.where,
undefined, undefined, undefined, this.clauses.where, {});
useSet = this.updateSet(set, "where", result, useSet);
// if success, and either has paginate props
if(result && evaluateOptions.shouldEvaluatePaginate(aClauseProps,bClauseProps) ) {
// if they have an order, it has to be true for paginate to be valid
// this isn't true if a < b, a is paginated, and b is not.
if( evaluateOptions.shouldEvaluateOrder(aClauseProps,bClauseProps)) {
result = evaluateOptions.evaluateOrder(aClauseProps.order, bClauseProps.order, undefined,
undefined, undefined, {}, {});
useSet = this.updateSet(set, "order", result, useSet);
}
if(result) {
result = evaluateOptions.evaluatePaginate(aClauseProps.paginate, bClauseProps.paginate,
undefined, undefined, undefined, this.clauses.paginate, {});
useSet = this.updateSet(set, "paginate", result, useSet);
}
}
// if orders are the same keep order!
else if( result && evaluateOptions.shouldEvaluateOrder(aClauseProps,bClauseProps) ) {
result = operator(aClauseProps.order, bClauseProps.order, undefined,
undefined, undefined, {}, {});
useSet = this.updateSet(set, "order", result, useSet);
}
// not checking order here makes it mean that different orders represent the same set?
return result && useSet ? set : result;
} | javascript | function(operator, a, b, aOptions, bOptions, evaluateOptions) {
aOptions = aOptions || {};
bOptions = bOptions || {};
evaluateOptions = assign({
evaluateWhere: operator,
evaluatePaginate: operator,
evaluateOrder: operator,
shouldEvaluatePaginate: function(aClauseProps, bClauseProps) {
return aClauseProps.enabled.paginate || bClauseProps.enabled.paginate;
},
shouldEvaluateOrder: function(aClauseProps, bClauseProps) {
return aClauseProps.enabled.order && compare.equal(aClauseProps.order, bClauseProps.order, undefined, undefined, undefined,{},{});
}
/* aClauseProps.enabled.order || bClauseProps.enabled.order */
}, evaluateOptions||{});
var aClauseProps = this.getClauseProperties(a, aOptions),
bClauseProps = this.getClauseProperties(b, bOptions),
set = {},
useSet;
var result = evaluateOptions.evaluateWhere(aClauseProps.where, bClauseProps.where,
undefined, undefined, undefined, this.clauses.where, {});
useSet = this.updateSet(set, "where", result, useSet);
// if success, and either has paginate props
if(result && evaluateOptions.shouldEvaluatePaginate(aClauseProps,bClauseProps) ) {
// if they have an order, it has to be true for paginate to be valid
// this isn't true if a < b, a is paginated, and b is not.
if( evaluateOptions.shouldEvaluateOrder(aClauseProps,bClauseProps)) {
result = evaluateOptions.evaluateOrder(aClauseProps.order, bClauseProps.order, undefined,
undefined, undefined, {}, {});
useSet = this.updateSet(set, "order", result, useSet);
}
if(result) {
result = evaluateOptions.evaluatePaginate(aClauseProps.paginate, bClauseProps.paginate,
undefined, undefined, undefined, this.clauses.paginate, {});
useSet = this.updateSet(set, "paginate", result, useSet);
}
}
// if orders are the same keep order!
else if( result && evaluateOptions.shouldEvaluateOrder(aClauseProps,bClauseProps) ) {
result = operator(aClauseProps.order, bClauseProps.order, undefined,
undefined, undefined, {}, {});
useSet = this.updateSet(set, "order", result, useSet);
}
// not checking order here makes it mean that different orders represent the same set?
return result && useSet ? set : result;
} | [
"function",
"(",
"operator",
",",
"a",
",",
"b",
",",
"aOptions",
",",
"bOptions",
",",
"evaluateOptions",
")",
"{",
"aOptions",
"=",
"aOptions",
"||",
"{",
"}",
";",
"bOptions",
"=",
"bOptions",
"||",
"{",
"}",
";",
"evaluateOptions",
"=",
"assign",
"(",
"{",
"evaluateWhere",
":",
"operator",
",",
"evaluatePaginate",
":",
"operator",
",",
"evaluateOrder",
":",
"operator",
",",
"shouldEvaluatePaginate",
":",
"function",
"(",
"aClauseProps",
",",
"bClauseProps",
")",
"{",
"return",
"aClauseProps",
".",
"enabled",
".",
"paginate",
"||",
"bClauseProps",
".",
"enabled",
".",
"paginate",
";",
"}",
",",
"shouldEvaluateOrder",
":",
"function",
"(",
"aClauseProps",
",",
"bClauseProps",
")",
"{",
"return",
"aClauseProps",
".",
"enabled",
".",
"order",
"&&",
"compare",
".",
"equal",
"(",
"aClauseProps",
".",
"order",
",",
"bClauseProps",
".",
"order",
",",
"undefined",
",",
"undefined",
",",
"undefined",
",",
"{",
"}",
",",
"{",
"}",
")",
";",
"}",
"}",
",",
"evaluateOptions",
"||",
"{",
"}",
")",
";",
"var",
"aClauseProps",
"=",
"this",
".",
"getClauseProperties",
"(",
"a",
",",
"aOptions",
")",
",",
"bClauseProps",
"=",
"this",
".",
"getClauseProperties",
"(",
"b",
",",
"bOptions",
")",
",",
"set",
"=",
"{",
"}",
",",
"useSet",
";",
"var",
"result",
"=",
"evaluateOptions",
".",
"evaluateWhere",
"(",
"aClauseProps",
".",
"where",
",",
"bClauseProps",
".",
"where",
",",
"undefined",
",",
"undefined",
",",
"undefined",
",",
"this",
".",
"clauses",
".",
"where",
",",
"{",
"}",
")",
";",
"useSet",
"=",
"this",
".",
"updateSet",
"(",
"set",
",",
"\"where\"",
",",
"result",
",",
"useSet",
")",
";",
"if",
"(",
"result",
"&&",
"evaluateOptions",
".",
"shouldEvaluatePaginate",
"(",
"aClauseProps",
",",
"bClauseProps",
")",
")",
"{",
"if",
"(",
"evaluateOptions",
".",
"shouldEvaluateOrder",
"(",
"aClauseProps",
",",
"bClauseProps",
")",
")",
"{",
"result",
"=",
"evaluateOptions",
".",
"evaluateOrder",
"(",
"aClauseProps",
".",
"order",
",",
"bClauseProps",
".",
"order",
",",
"undefined",
",",
"undefined",
",",
"undefined",
",",
"{",
"}",
",",
"{",
"}",
")",
";",
"useSet",
"=",
"this",
".",
"updateSet",
"(",
"set",
",",
"\"order\"",
",",
"result",
",",
"useSet",
")",
";",
"}",
"if",
"(",
"result",
")",
"{",
"result",
"=",
"evaluateOptions",
".",
"evaluatePaginate",
"(",
"aClauseProps",
".",
"paginate",
",",
"bClauseProps",
".",
"paginate",
",",
"undefined",
",",
"undefined",
",",
"undefined",
",",
"this",
".",
"clauses",
".",
"paginate",
",",
"{",
"}",
")",
";",
"useSet",
"=",
"this",
".",
"updateSet",
"(",
"set",
",",
"\"paginate\"",
",",
"result",
",",
"useSet",
")",
";",
"}",
"}",
"else",
"if",
"(",
"result",
"&&",
"evaluateOptions",
".",
"shouldEvaluateOrder",
"(",
"aClauseProps",
",",
"bClauseProps",
")",
")",
"{",
"result",
"=",
"operator",
"(",
"aClauseProps",
".",
"order",
",",
"bClauseProps",
".",
"order",
",",
"undefined",
",",
"undefined",
",",
"undefined",
",",
"{",
"}",
",",
"{",
"}",
")",
";",
"useSet",
"=",
"this",
".",
"updateSet",
"(",
"set",
",",
"\"order\"",
",",
"result",
",",
"useSet",
")",
";",
"}",
"return",
"result",
"&&",
"useSet",
"?",
"set",
":",
"result",
";",
"}"
] | calls the operator method on different parts of the set. | [
"calls",
"the",
"operator",
"method",
"on",
"different",
"parts",
"of",
"the",
"set",
"."
] | d7123f41fdadc103a2b2bac99bb05a6537af307a | https://github.com/canjs/can-set/blob/d7123f41fdadc103a2b2bac99bb05a6537af307a/src/set-core.js#L241-L299 | train |
|
canjs/can-set | src/props.js | function(setA, setB, property1, property2){
// p for param
// v for value
var numProps = numericProperties(setA, setB, property1, property2);
var sAv1 = numProps.sAv1,
sAv2 = numProps.sAv2,
sBv1 = numProps.sBv1,
sBv2 = numProps.sBv2,
count = sAv2 - sAv1 + 1;
var after = {
difference: [sBv2+1, sAv2],
intersection: [sAv1,sBv2],
union: [sBv1, sAv2],
count: count,
meta: "after"
};
var before = {
difference: [sAv1, sBv1-1],
intersection: [sBv1,sAv2],
union: [sAv1, sBv2],
count: count,
meta: "before"
};
// if the sets are equal
if(sAv1 === sBv1 && sAv2 === sBv2) {
return {
intersection: [sAv1,sAv2],
union: [sAv1,sAv2],
count: count,
meta: "equal"
};
}
// A starts at B but A ends later
else if( sAv1 === sBv1 && sBv2 < sAv2 ) {
return after;
}
// A end at B but A starts earlier
else if( sAv2 === sBv2 && sBv1 > sAv1 ) {
return before;
}
// B contains A
else if( within(sAv1, [sBv1, sBv2]) && within(sAv2, [sBv1, sBv2]) ) {
return {
intersection: [sAv1,sAv2],
union: [sBv1, sBv2],
count: count,
meta: "subset"
};
}
// A contains B
else if( within(sBv1, [sAv1, sAv2]) && within(sBv2, [sAv1, sAv2]) ) {
return {
intersection: [sBv1,sBv2],
// there is a difference in what A has
difference: [null, null],
union: [sAv1, sAv2],
count: count,
meta: "superset"
};
}
// setA starts earlier and overlaps setB
else if(sAv1 < sBv1 && within(sAv2, [sBv1, sBv2]) ) {
return before;
}
// setB starts earlier and overlaps setA
else if(sBv1 < sAv1 && within(sBv2, [sAv1, sAv2]) ) {
return after;
}
// side by side ... nothing intersection
else if(sAv2 === sBv1-1) {
return {
difference: [sAv1,sAv2],
union: [sAv1, sBv2],
count: count,
meta: "disjoint-before"
};
}
else if(sBv2 === sAv1 - 1) {
return {
difference: [sAv1,sAv2],
union: [sBv1, sAv2],
count: count,
meta: "disjoint-after"
};
}
if(!isNaN(count)) {
return {
count: count,
meta: "disjoint"
};
}
} | javascript | function(setA, setB, property1, property2){
// p for param
// v for value
var numProps = numericProperties(setA, setB, property1, property2);
var sAv1 = numProps.sAv1,
sAv2 = numProps.sAv2,
sBv1 = numProps.sBv1,
sBv2 = numProps.sBv2,
count = sAv2 - sAv1 + 1;
var after = {
difference: [sBv2+1, sAv2],
intersection: [sAv1,sBv2],
union: [sBv1, sAv2],
count: count,
meta: "after"
};
var before = {
difference: [sAv1, sBv1-1],
intersection: [sBv1,sAv2],
union: [sAv1, sBv2],
count: count,
meta: "before"
};
// if the sets are equal
if(sAv1 === sBv1 && sAv2 === sBv2) {
return {
intersection: [sAv1,sAv2],
union: [sAv1,sAv2],
count: count,
meta: "equal"
};
}
// A starts at B but A ends later
else if( sAv1 === sBv1 && sBv2 < sAv2 ) {
return after;
}
// A end at B but A starts earlier
else if( sAv2 === sBv2 && sBv1 > sAv1 ) {
return before;
}
// B contains A
else if( within(sAv1, [sBv1, sBv2]) && within(sAv2, [sBv1, sBv2]) ) {
return {
intersection: [sAv1,sAv2],
union: [sBv1, sBv2],
count: count,
meta: "subset"
};
}
// A contains B
else if( within(sBv1, [sAv1, sAv2]) && within(sBv2, [sAv1, sAv2]) ) {
return {
intersection: [sBv1,sBv2],
// there is a difference in what A has
difference: [null, null],
union: [sAv1, sAv2],
count: count,
meta: "superset"
};
}
// setA starts earlier and overlaps setB
else if(sAv1 < sBv1 && within(sAv2, [sBv1, sBv2]) ) {
return before;
}
// setB starts earlier and overlaps setA
else if(sBv1 < sAv1 && within(sBv2, [sAv1, sAv2]) ) {
return after;
}
// side by side ... nothing intersection
else if(sAv2 === sBv1-1) {
return {
difference: [sAv1,sAv2],
union: [sAv1, sBv2],
count: count,
meta: "disjoint-before"
};
}
else if(sBv2 === sAv1 - 1) {
return {
difference: [sAv1,sAv2],
union: [sBv1, sAv2],
count: count,
meta: "disjoint-after"
};
}
if(!isNaN(count)) {
return {
count: count,
meta: "disjoint"
};
}
} | [
"function",
"(",
"setA",
",",
"setB",
",",
"property1",
",",
"property2",
")",
"{",
"var",
"numProps",
"=",
"numericProperties",
"(",
"setA",
",",
"setB",
",",
"property1",
",",
"property2",
")",
";",
"var",
"sAv1",
"=",
"numProps",
".",
"sAv1",
",",
"sAv2",
"=",
"numProps",
".",
"sAv2",
",",
"sBv1",
"=",
"numProps",
".",
"sBv1",
",",
"sBv2",
"=",
"numProps",
".",
"sBv2",
",",
"count",
"=",
"sAv2",
"-",
"sAv1",
"+",
"1",
";",
"var",
"after",
"=",
"{",
"difference",
":",
"[",
"sBv2",
"+",
"1",
",",
"sAv2",
"]",
",",
"intersection",
":",
"[",
"sAv1",
",",
"sBv2",
"]",
",",
"union",
":",
"[",
"sBv1",
",",
"sAv2",
"]",
",",
"count",
":",
"count",
",",
"meta",
":",
"\"after\"",
"}",
";",
"var",
"before",
"=",
"{",
"difference",
":",
"[",
"sAv1",
",",
"sBv1",
"-",
"1",
"]",
",",
"intersection",
":",
"[",
"sBv1",
",",
"sAv2",
"]",
",",
"union",
":",
"[",
"sAv1",
",",
"sBv2",
"]",
",",
"count",
":",
"count",
",",
"meta",
":",
"\"before\"",
"}",
";",
"if",
"(",
"sAv1",
"===",
"sBv1",
"&&",
"sAv2",
"===",
"sBv2",
")",
"{",
"return",
"{",
"intersection",
":",
"[",
"sAv1",
",",
"sAv2",
"]",
",",
"union",
":",
"[",
"sAv1",
",",
"sAv2",
"]",
",",
"count",
":",
"count",
",",
"meta",
":",
"\"equal\"",
"}",
";",
"}",
"else",
"if",
"(",
"sAv1",
"===",
"sBv1",
"&&",
"sBv2",
"<",
"sAv2",
")",
"{",
"return",
"after",
";",
"}",
"else",
"if",
"(",
"sAv2",
"===",
"sBv2",
"&&",
"sBv1",
">",
"sAv1",
")",
"{",
"return",
"before",
";",
"}",
"else",
"if",
"(",
"within",
"(",
"sAv1",
",",
"[",
"sBv1",
",",
"sBv2",
"]",
")",
"&&",
"within",
"(",
"sAv2",
",",
"[",
"sBv1",
",",
"sBv2",
"]",
")",
")",
"{",
"return",
"{",
"intersection",
":",
"[",
"sAv1",
",",
"sAv2",
"]",
",",
"union",
":",
"[",
"sBv1",
",",
"sBv2",
"]",
",",
"count",
":",
"count",
",",
"meta",
":",
"\"subset\"",
"}",
";",
"}",
"else",
"if",
"(",
"within",
"(",
"sBv1",
",",
"[",
"sAv1",
",",
"sAv2",
"]",
")",
"&&",
"within",
"(",
"sBv2",
",",
"[",
"sAv1",
",",
"sAv2",
"]",
")",
")",
"{",
"return",
"{",
"intersection",
":",
"[",
"sBv1",
",",
"sBv2",
"]",
",",
"difference",
":",
"[",
"null",
",",
"null",
"]",
",",
"union",
":",
"[",
"sAv1",
",",
"sAv2",
"]",
",",
"count",
":",
"count",
",",
"meta",
":",
"\"superset\"",
"}",
";",
"}",
"else",
"if",
"(",
"sAv1",
"<",
"sBv1",
"&&",
"within",
"(",
"sAv2",
",",
"[",
"sBv1",
",",
"sBv2",
"]",
")",
")",
"{",
"return",
"before",
";",
"}",
"else",
"if",
"(",
"sBv1",
"<",
"sAv1",
"&&",
"within",
"(",
"sBv2",
",",
"[",
"sAv1",
",",
"sAv2",
"]",
")",
")",
"{",
"return",
"after",
";",
"}",
"else",
"if",
"(",
"sAv2",
"===",
"sBv1",
"-",
"1",
")",
"{",
"return",
"{",
"difference",
":",
"[",
"sAv1",
",",
"sAv2",
"]",
",",
"union",
":",
"[",
"sAv1",
",",
"sBv2",
"]",
",",
"count",
":",
"count",
",",
"meta",
":",
"\"disjoint-before\"",
"}",
";",
"}",
"else",
"if",
"(",
"sBv2",
"===",
"sAv1",
"-",
"1",
")",
"{",
"return",
"{",
"difference",
":",
"[",
"sAv1",
",",
"sAv2",
"]",
",",
"union",
":",
"[",
"sBv1",
",",
"sAv2",
"]",
",",
"count",
":",
"count",
",",
"meta",
":",
"\"disjoint-after\"",
"}",
";",
"}",
"if",
"(",
"!",
"isNaN",
"(",
"count",
")",
")",
"{",
"return",
"{",
"count",
":",
"count",
",",
"meta",
":",
"\"disjoint\"",
"}",
";",
"}",
"}"
] | diff from setA's perspective | [
"diff",
"from",
"setA",
"s",
"perspective"
] | d7123f41fdadc103a2b2bac99bb05a6537af307a | https://github.com/canjs/can-set/blob/d7123f41fdadc103a2b2bac99bb05a6537af307a/src/props.js#L19-L114 | train |
|
catamphetamine/javascript-time-ago | source/grade.js | getThreshold | function getThreshold(fromStep, toStep, now)
{
let threshold
// Allows custom thresholds when moving
// from a specific step to a specific step.
if (fromStep && (fromStep.id || fromStep.unit)) {
threshold = toStep[`threshold_for_${fromStep.id || fromStep.unit}`]
}
// If no custom threshold is set for this transition
// then use the usual threshold for the next step.
if (threshold === undefined) {
threshold = toStep.threshold
}
// Convert threshold to a number.
if (typeof threshold === 'function') {
threshold = threshold(now)
}
// Throw if no threshold is found.
if (fromStep && typeof threshold !== 'number') {
// Babel transforms `typeof` into some "branches"
// so istanbul will show this as "branch not covered".
/* istanbul ignore next */
const type = typeof threshold
throw new Error(`Each step of a gradation must have a threshold defined except for the first one. Got "${threshold}", ${type}. Step: ${JSON.stringify(toStep)}`)
}
return threshold
} | javascript | function getThreshold(fromStep, toStep, now)
{
let threshold
// Allows custom thresholds when moving
// from a specific step to a specific step.
if (fromStep && (fromStep.id || fromStep.unit)) {
threshold = toStep[`threshold_for_${fromStep.id || fromStep.unit}`]
}
// If no custom threshold is set for this transition
// then use the usual threshold for the next step.
if (threshold === undefined) {
threshold = toStep.threshold
}
// Convert threshold to a number.
if (typeof threshold === 'function') {
threshold = threshold(now)
}
// Throw if no threshold is found.
if (fromStep && typeof threshold !== 'number') {
// Babel transforms `typeof` into some "branches"
// so istanbul will show this as "branch not covered".
/* istanbul ignore next */
const type = typeof threshold
throw new Error(`Each step of a gradation must have a threshold defined except for the first one. Got "${threshold}", ${type}. Step: ${JSON.stringify(toStep)}`)
}
return threshold
} | [
"function",
"getThreshold",
"(",
"fromStep",
",",
"toStep",
",",
"now",
")",
"{",
"let",
"threshold",
"if",
"(",
"fromStep",
"&&",
"(",
"fromStep",
".",
"id",
"||",
"fromStep",
".",
"unit",
")",
")",
"{",
"threshold",
"=",
"toStep",
"[",
"`",
"${",
"fromStep",
".",
"id",
"||",
"fromStep",
".",
"unit",
"}",
"`",
"]",
"}",
"if",
"(",
"threshold",
"===",
"undefined",
")",
"{",
"threshold",
"=",
"toStep",
".",
"threshold",
"}",
"if",
"(",
"typeof",
"threshold",
"===",
"'function'",
")",
"{",
"threshold",
"=",
"threshold",
"(",
"now",
")",
"}",
"if",
"(",
"fromStep",
"&&",
"typeof",
"threshold",
"!==",
"'number'",
")",
"{",
"const",
"type",
"=",
"typeof",
"threshold",
"throw",
"new",
"Error",
"(",
"`",
"${",
"threshold",
"}",
"${",
"type",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"toStep",
")",
"}",
"`",
")",
"}",
"return",
"threshold",
"}"
] | Gets threshold for moving from `fromStep` to `next_step`.
@param {Object} fromStep - From step.
@param {Object} next_step - To step.
@param {number} now - The current timestamp.
@return {number}
@throws Will throw if no threshold is found. | [
"Gets",
"threshold",
"for",
"moving",
"from",
"fromStep",
"to",
"next_step",
"."
] | c6eba9b30c5c40a19883fffee0f45adff088f223 | https://github.com/catamphetamine/javascript-time-ago/blob/c6eba9b30c5c40a19883fffee0f45adff088f223/source/grade.js#L74-L105 | train |
catamphetamine/javascript-time-ago | source/grade.js | getAllowedSteps | function getAllowedSteps(gradation, units)
{
return gradation.filter(({ unit }) => {
// If this step has a `unit` defined
// then this `unit` must be in the list of `units` allowed.
if (unit) {
return units.indexOf(unit) >= 0
}
// A gradation step is not required to specify a `unit`.
// E.g. for Twitter gradation it specifies `format()` instead.
return true
})
} | javascript | function getAllowedSteps(gradation, units)
{
return gradation.filter(({ unit }) => {
// If this step has a `unit` defined
// then this `unit` must be in the list of `units` allowed.
if (unit) {
return units.indexOf(unit) >= 0
}
// A gradation step is not required to specify a `unit`.
// E.g. for Twitter gradation it specifies `format()` instead.
return true
})
} | [
"function",
"getAllowedSteps",
"(",
"gradation",
",",
"units",
")",
"{",
"return",
"gradation",
".",
"filter",
"(",
"(",
"{",
"unit",
"}",
")",
"=>",
"{",
"if",
"(",
"unit",
")",
"{",
"return",
"units",
".",
"indexOf",
"(",
"unit",
")",
">=",
"0",
"}",
"return",
"true",
"}",
")",
"}"
] | Leaves only allowed gradation steps.
@param {Object[]} gradation
@param {string[]} units - Allowed time units.
@return {Object[]} | [
"Leaves",
"only",
"allowed",
"gradation",
"steps",
"."
] | c6eba9b30c5c40a19883fffee0f45adff088f223 | https://github.com/catamphetamine/javascript-time-ago/blob/c6eba9b30c5c40a19883fffee0f45adff088f223/source/grade.js#L135-L147 | train |
catamphetamine/javascript-time-ago | source/JavascriptTimeAgo.js | getTimeIntervalMeasurementUnits | function getTimeIntervalMeasurementUnits(localeData, restrictedSetOfUnits)
{
// All available time interval measurement units.
let units = Object.keys(localeData)
// If only a specific set of available
// time measurement units can be used.
if (restrictedSetOfUnits) {
// Reduce available time interval measurement units
// based on user's preferences.
units = restrictedSetOfUnits.filter(_ => units.indexOf(_) >= 0)
}
// Stock `Intl.RelativeTimeFormat` locale data doesn't have "now" units.
// So either "now" is present in extended locale data
// or it's taken from ".second.current".
if ((!restrictedSetOfUnits || restrictedSetOfUnits.indexOf('now') >= 0) &&
units.indexOf('now') < 0) {
if (localeData.second.current) {
units.unshift('now')
}
}
return units
} | javascript | function getTimeIntervalMeasurementUnits(localeData, restrictedSetOfUnits)
{
// All available time interval measurement units.
let units = Object.keys(localeData)
// If only a specific set of available
// time measurement units can be used.
if (restrictedSetOfUnits) {
// Reduce available time interval measurement units
// based on user's preferences.
units = restrictedSetOfUnits.filter(_ => units.indexOf(_) >= 0)
}
// Stock `Intl.RelativeTimeFormat` locale data doesn't have "now" units.
// So either "now" is present in extended locale data
// or it's taken from ".second.current".
if ((!restrictedSetOfUnits || restrictedSetOfUnits.indexOf('now') >= 0) &&
units.indexOf('now') < 0) {
if (localeData.second.current) {
units.unshift('now')
}
}
return units
} | [
"function",
"getTimeIntervalMeasurementUnits",
"(",
"localeData",
",",
"restrictedSetOfUnits",
")",
"{",
"let",
"units",
"=",
"Object",
".",
"keys",
"(",
"localeData",
")",
"if",
"(",
"restrictedSetOfUnits",
")",
"{",
"units",
"=",
"restrictedSetOfUnits",
".",
"filter",
"(",
"_",
"=>",
"units",
".",
"indexOf",
"(",
"_",
")",
">=",
"0",
")",
"}",
"if",
"(",
"(",
"!",
"restrictedSetOfUnits",
"||",
"restrictedSetOfUnits",
".",
"indexOf",
"(",
"'now'",
")",
">=",
"0",
")",
"&&",
"units",
".",
"indexOf",
"(",
"'now'",
")",
"<",
"0",
")",
"{",
"if",
"(",
"localeData",
".",
"second",
".",
"current",
")",
"{",
"units",
".",
"unshift",
"(",
"'now'",
")",
"}",
"}",
"return",
"units",
"}"
] | Get available time interval measurement units. | [
"Get",
"available",
"time",
"interval",
"measurement",
"units",
"."
] | c6eba9b30c5c40a19883fffee0f45adff088f223 | https://github.com/catamphetamine/javascript-time-ago/blob/c6eba9b30c5c40a19883fffee0f45adff088f223/source/JavascriptTimeAgo.js#L376-L400 | train |
ibericode/boxzilla.js | src/animator.js | toggle | function toggle(element, animation, callbackFn) {
var nowVisible = element.style.display != 'none' || element.offsetLeft > 0;
// create clone for reference
var clone = element.cloneNode(true);
var cleanup = function() {
element.removeAttribute('data-animated');
element.setAttribute('style', clone.getAttribute('style'));
element.style.display = nowVisible ? 'none' : '';
if( callbackFn ) { callbackFn(); }
};
// store attribute so everyone knows we're animating this element
element.setAttribute('data-animated', "true");
// toggle element visiblity right away if we're making something visible
if( ! nowVisible ) {
element.style.display = '';
}
var hiddenStyles, visibleStyles;
// animate properties
if( animation === 'slide' ) {
hiddenStyles = initObjectProperties(["height", "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"], 0);
visibleStyles = {};
if( ! nowVisible ) {
var computedStyles = window.getComputedStyle(element);
visibleStyles = copyObjectProperties(["height", "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"], computedStyles);
// in some browsers, getComputedStyle returns "auto" value. this falls back to getBoundingClientRect() in those browsers since we need an actual height.
if(!isFinite(visibleStyles.height)) {
var clientRect = element.getBoundingClientRect();
visibleStyles.height = clientRect.height;
}
css(element, hiddenStyles);
}
// don't show a scrollbar during animation
element.style.overflowY = 'hidden';
animate(element, nowVisible ? hiddenStyles : visibleStyles, cleanup);
} else {
hiddenStyles = { opacity: 0 };
visibleStyles = { opacity: 1 };
if( ! nowVisible ) {
css(element, hiddenStyles);
}
animate(element, nowVisible ? hiddenStyles : visibleStyles, cleanup);
}
} | javascript | function toggle(element, animation, callbackFn) {
var nowVisible = element.style.display != 'none' || element.offsetLeft > 0;
// create clone for reference
var clone = element.cloneNode(true);
var cleanup = function() {
element.removeAttribute('data-animated');
element.setAttribute('style', clone.getAttribute('style'));
element.style.display = nowVisible ? 'none' : '';
if( callbackFn ) { callbackFn(); }
};
// store attribute so everyone knows we're animating this element
element.setAttribute('data-animated', "true");
// toggle element visiblity right away if we're making something visible
if( ! nowVisible ) {
element.style.display = '';
}
var hiddenStyles, visibleStyles;
// animate properties
if( animation === 'slide' ) {
hiddenStyles = initObjectProperties(["height", "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"], 0);
visibleStyles = {};
if( ! nowVisible ) {
var computedStyles = window.getComputedStyle(element);
visibleStyles = copyObjectProperties(["height", "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"], computedStyles);
// in some browsers, getComputedStyle returns "auto" value. this falls back to getBoundingClientRect() in those browsers since we need an actual height.
if(!isFinite(visibleStyles.height)) {
var clientRect = element.getBoundingClientRect();
visibleStyles.height = clientRect.height;
}
css(element, hiddenStyles);
}
// don't show a scrollbar during animation
element.style.overflowY = 'hidden';
animate(element, nowVisible ? hiddenStyles : visibleStyles, cleanup);
} else {
hiddenStyles = { opacity: 0 };
visibleStyles = { opacity: 1 };
if( ! nowVisible ) {
css(element, hiddenStyles);
}
animate(element, nowVisible ? hiddenStyles : visibleStyles, cleanup);
}
} | [
"function",
"toggle",
"(",
"element",
",",
"animation",
",",
"callbackFn",
")",
"{",
"var",
"nowVisible",
"=",
"element",
".",
"style",
".",
"display",
"!=",
"'none'",
"||",
"element",
".",
"offsetLeft",
">",
"0",
";",
"var",
"clone",
"=",
"element",
".",
"cloneNode",
"(",
"true",
")",
";",
"var",
"cleanup",
"=",
"function",
"(",
")",
"{",
"element",
".",
"removeAttribute",
"(",
"'data-animated'",
")",
";",
"element",
".",
"setAttribute",
"(",
"'style'",
",",
"clone",
".",
"getAttribute",
"(",
"'style'",
")",
")",
";",
"element",
".",
"style",
".",
"display",
"=",
"nowVisible",
"?",
"'none'",
":",
"''",
";",
"if",
"(",
"callbackFn",
")",
"{",
"callbackFn",
"(",
")",
";",
"}",
"}",
";",
"element",
".",
"setAttribute",
"(",
"'data-animated'",
",",
"\"true\"",
")",
";",
"if",
"(",
"!",
"nowVisible",
")",
"{",
"element",
".",
"style",
".",
"display",
"=",
"''",
";",
"}",
"var",
"hiddenStyles",
",",
"visibleStyles",
";",
"if",
"(",
"animation",
"===",
"'slide'",
")",
"{",
"hiddenStyles",
"=",
"initObjectProperties",
"(",
"[",
"\"height\"",
",",
"\"borderTopWidth\"",
",",
"\"borderBottomWidth\"",
",",
"\"paddingTop\"",
",",
"\"paddingBottom\"",
"]",
",",
"0",
")",
";",
"visibleStyles",
"=",
"{",
"}",
";",
"if",
"(",
"!",
"nowVisible",
")",
"{",
"var",
"computedStyles",
"=",
"window",
".",
"getComputedStyle",
"(",
"element",
")",
";",
"visibleStyles",
"=",
"copyObjectProperties",
"(",
"[",
"\"height\"",
",",
"\"borderTopWidth\"",
",",
"\"borderBottomWidth\"",
",",
"\"paddingTop\"",
",",
"\"paddingBottom\"",
"]",
",",
"computedStyles",
")",
";",
"if",
"(",
"!",
"isFinite",
"(",
"visibleStyles",
".",
"height",
")",
")",
"{",
"var",
"clientRect",
"=",
"element",
".",
"getBoundingClientRect",
"(",
")",
";",
"visibleStyles",
".",
"height",
"=",
"clientRect",
".",
"height",
";",
"}",
"css",
"(",
"element",
",",
"hiddenStyles",
")",
";",
"}",
"element",
".",
"style",
".",
"overflowY",
"=",
"'hidden'",
";",
"animate",
"(",
"element",
",",
"nowVisible",
"?",
"hiddenStyles",
":",
"visibleStyles",
",",
"cleanup",
")",
";",
"}",
"else",
"{",
"hiddenStyles",
"=",
"{",
"opacity",
":",
"0",
"}",
";",
"visibleStyles",
"=",
"{",
"opacity",
":",
"1",
"}",
";",
"if",
"(",
"!",
"nowVisible",
")",
"{",
"css",
"(",
"element",
",",
"hiddenStyles",
")",
";",
"}",
"animate",
"(",
"element",
",",
"nowVisible",
"?",
"hiddenStyles",
":",
"visibleStyles",
",",
"cleanup",
")",
";",
"}",
"}"
] | Toggles the element using the given animation.
@param element
@param animation Either "fade" or "slide" | [
"Toggles",
"the",
"element",
"using",
"the",
"given",
"animation",
"."
] | 6f2575e112a019da6a78510a2f830aae40ea3e37 | https://github.com/ibericode/boxzilla.js/blob/6f2575e112a019da6a78510a2f830aae40ea3e37/src/animator.js#L41-L92 | train |
dy/parenthesis | index.js | nest | function nest (str, refs, escape) {
var res = [], match
var a = 0
while (match = re.exec(str)) {
if (a++ > 10e3) throw Error('Circular references in parenthesis')
res.push(str.slice(0, match.index))
res.push(nest(refs[match[1]], refs))
str = str.slice(match.index + match[0].length)
}
res.push(str)
return res
} | javascript | function nest (str, refs, escape) {
var res = [], match
var a = 0
while (match = re.exec(str)) {
if (a++ > 10e3) throw Error('Circular references in parenthesis')
res.push(str.slice(0, match.index))
res.push(nest(refs[match[1]], refs))
str = str.slice(match.index + match[0].length)
}
res.push(str)
return res
} | [
"function",
"nest",
"(",
"str",
",",
"refs",
",",
"escape",
")",
"{",
"var",
"res",
"=",
"[",
"]",
",",
"match",
"var",
"a",
"=",
"0",
"while",
"(",
"match",
"=",
"re",
".",
"exec",
"(",
"str",
")",
")",
"{",
"if",
"(",
"a",
"++",
">",
"10e3",
")",
"throw",
"Error",
"(",
"'Circular references in parenthesis'",
")",
"res",
".",
"push",
"(",
"str",
".",
"slice",
"(",
"0",
",",
"match",
".",
"index",
")",
")",
"res",
".",
"push",
"(",
"nest",
"(",
"refs",
"[",
"match",
"[",
"1",
"]",
"]",
",",
"refs",
")",
")",
"str",
"=",
"str",
".",
"slice",
"(",
"match",
".",
"index",
"+",
"match",
"[",
"0",
"]",
".",
"length",
")",
"}",
"res",
".",
"push",
"(",
"str",
")",
"return",
"res",
"}"
] | transform references to tree | [
"transform",
"references",
"to",
"tree"
] | 067464b0d0160c23e8369c1b2a45e835a7b3c063 | https://github.com/dy/parenthesis/blob/067464b0d0160c23e8369c1b2a45e835a7b3c063/index.js#L66-L83 | train |
devongovett/zipcode | index.js | loadData | function loadData() {
var data = fs.readFileSync(__dirname + '/zip_codes.csv', 'utf8');
var lines = data.split('\r\n');
var trie = {};
lines.forEach(function(line) {
var parts = line.split(',');
var zip = parts[0], city = parts[1], state = parts[2];
var node = trie;
for (var i = 0; i < zip.length; i++) {
var num = zip[i];
var pos = node[num];
if (pos == null)
node = node[num] = (i === zip.length - 1) ? [city, state] : {};
else
node = node[num];
}
});
return trie;
} | javascript | function loadData() {
var data = fs.readFileSync(__dirname + '/zip_codes.csv', 'utf8');
var lines = data.split('\r\n');
var trie = {};
lines.forEach(function(line) {
var parts = line.split(',');
var zip = parts[0], city = parts[1], state = parts[2];
var node = trie;
for (var i = 0; i < zip.length; i++) {
var num = zip[i];
var pos = node[num];
if (pos == null)
node = node[num] = (i === zip.length - 1) ? [city, state] : {};
else
node = node[num];
}
});
return trie;
} | [
"function",
"loadData",
"(",
")",
"{",
"var",
"data",
"=",
"fs",
".",
"readFileSync",
"(",
"__dirname",
"+",
"'/zip_codes.csv'",
",",
"'utf8'",
")",
";",
"var",
"lines",
"=",
"data",
".",
"split",
"(",
"'\\r\\n'",
")",
";",
"\\r",
"\\n",
"var",
"trie",
"=",
"{",
"}",
";",
"}"
] | Parses zip_codes.csv and creates a trie for fast lookups | [
"Parses",
"zip_codes",
".",
"csv",
"and",
"creates",
"a",
"trie",
"for",
"fast",
"lookups"
] | 4af9e26c620a081cb33ec85cecc2dc2ef18406ba | https://github.com/devongovett/zipcode/blob/4af9e26c620a081cb33ec85cecc2dc2ef18406ba/index.js#L7-L28 | train |
Galeria-Kaufhof/stylegen | src/Cli.js | setupStyleguide | function setupStyleguide(options) {
let cwd = !!options && !!options.cwd ? options.cwd : process.cwd()
success('Styleguide.new:', 'initialize styleguide ...')
return new Styleguide()
.initialize(cwd)
.then(function (styleguide) {
success('Styleguide.new:', 'initialize finished')
if (!options || !options.prepare) {
success('Styleguide.prepare:', 'preparing the styleguide target ...')
return styleguide.prepare()
} else {
return Promise.resolve(styleguide)
}
})
} | javascript | function setupStyleguide(options) {
let cwd = !!options && !!options.cwd ? options.cwd : process.cwd()
success('Styleguide.new:', 'initialize styleguide ...')
return new Styleguide()
.initialize(cwd)
.then(function (styleguide) {
success('Styleguide.new:', 'initialize finished')
if (!options || !options.prepare) {
success('Styleguide.prepare:', 'preparing the styleguide target ...')
return styleguide.prepare()
} else {
return Promise.resolve(styleguide)
}
})
} | [
"function",
"setupStyleguide",
"(",
"options",
")",
"{",
"let",
"cwd",
"=",
"!",
"!",
"options",
"&&",
"!",
"!",
"options",
".",
"cwd",
"?",
"options",
".",
"cwd",
":",
"process",
".",
"cwd",
"(",
")",
"success",
"(",
"'Styleguide.new:'",
",",
"'initialize styleguide ...'",
")",
"return",
"new",
"Styleguide",
"(",
")",
".",
"initialize",
"(",
"cwd",
")",
".",
"then",
"(",
"function",
"(",
"styleguide",
")",
"{",
"success",
"(",
"'Styleguide.new:'",
",",
"'initialize finished'",
")",
"if",
"(",
"!",
"options",
"||",
"!",
"options",
".",
"prepare",
")",
"{",
"success",
"(",
"'Styleguide.prepare:'",
",",
"'preparing the styleguide target ...'",
")",
"return",
"styleguide",
".",
"prepare",
"(",
")",
"}",
"else",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"styleguide",
")",
"}",
"}",
")",
"}"
] | initialize the styleguide, by reading its configuration and preprare any necessary target structure | [
"initialize",
"the",
"styleguide",
"by",
"reading",
"its",
"configuration",
"and",
"preprare",
"any",
"necessary",
"target",
"structure"
] | 4729199b184fc1aa58b6abeef55e131fd58a1e00 | https://github.com/Galeria-Kaufhof/stylegen/blob/4729199b184fc1aa58b6abeef55e131fd58a1e00/src/Cli.js#L8-L22 | train |
Galeria-Kaufhof/stylegen | src/Cli.js | resolveStyleguide | function resolveStyleguide(options) {
return setupStyleguide(options)
.then(function (styleguide) {
success('Styleguide.read:', 'start reading ...')
return styleguide.read()
})
.then(function (styleguide) {
success('Styleguide.read:', 'finished reading')
return Promise.resolve(styleguide)
})
} | javascript | function resolveStyleguide(options) {
return setupStyleguide(options)
.then(function (styleguide) {
success('Styleguide.read:', 'start reading ...')
return styleguide.read()
})
.then(function (styleguide) {
success('Styleguide.read:', 'finished reading')
return Promise.resolve(styleguide)
})
} | [
"function",
"resolveStyleguide",
"(",
"options",
")",
"{",
"return",
"setupStyleguide",
"(",
"options",
")",
".",
"then",
"(",
"function",
"(",
"styleguide",
")",
"{",
"success",
"(",
"'Styleguide.read:'",
",",
"'start reading ...'",
")",
"return",
"styleguide",
".",
"read",
"(",
")",
"}",
")",
".",
"then",
"(",
"function",
"(",
"styleguide",
")",
"{",
"success",
"(",
"'Styleguide.read:'",
",",
"'finished reading'",
")",
"return",
"Promise",
".",
"resolve",
"(",
"styleguide",
")",
"}",
")",
"}"
] | reading in the actual styleguide content, components and pages | [
"reading",
"in",
"the",
"actual",
"styleguide",
"content",
"components",
"and",
"pages"
] | 4729199b184fc1aa58b6abeef55e131fd58a1e00 | https://github.com/Galeria-Kaufhof/stylegen/blob/4729199b184fc1aa58b6abeef55e131fd58a1e00/src/Cli.js#L27-L37 | train |
Galeria-Kaufhof/stylegen | src/Cli.js | build | function build(options) {
options = Object.assign({}, options)
return resolveStyleguide(options)
.then(function (styleguide) {
success('Styleguide.write:', 'start writing ...')
return styleguide.write()
})
.then(function (styleguide) {
success('Styleguide.write:', 'finished writing')
return styleguide
})
.catch(function (e) {
error('Cli.build', 'failed to build Styleguide', e)
throw (e)
})
} | javascript | function build(options) {
options = Object.assign({}, options)
return resolveStyleguide(options)
.then(function (styleguide) {
success('Styleguide.write:', 'start writing ...')
return styleguide.write()
})
.then(function (styleguide) {
success('Styleguide.write:', 'finished writing')
return styleguide
})
.catch(function (e) {
error('Cli.build', 'failed to build Styleguide', e)
throw (e)
})
} | [
"function",
"build",
"(",
"options",
")",
"{",
"options",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
")",
"return",
"resolveStyleguide",
"(",
"options",
")",
".",
"then",
"(",
"function",
"(",
"styleguide",
")",
"{",
"success",
"(",
"'Styleguide.write:'",
",",
"'start writing ...'",
")",
"return",
"styleguide",
".",
"write",
"(",
")",
"}",
")",
".",
"then",
"(",
"function",
"(",
"styleguide",
")",
"{",
"success",
"(",
"'Styleguide.write:'",
",",
"'finished writing'",
")",
"return",
"styleguide",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"e",
")",
"{",
"error",
"(",
"'Cli.build'",
",",
"'failed to build Styleguide'",
",",
"e",
")",
"throw",
"(",
"e",
")",
"}",
")",
"}"
] | create the static styleguide | [
"create",
"the",
"static",
"styleguide"
] | 4729199b184fc1aa58b6abeef55e131fd58a1e00 | https://github.com/Galeria-Kaufhof/stylegen/blob/4729199b184fc1aa58b6abeef55e131fd58a1e00/src/Cli.js#L42-L58 | train |
Galeria-Kaufhof/stylegen | src/Cli.js | createExport | function createExport(options) {
options = Object.assign({}, options, { prepare: false })
/** we need no styleguide preparation, like asset copying etc. */
return resolveStyleguide(options)
.then(function (styleguide) {
return styleguide.exportStyleguide()
})
.catch(function (e) {
error('Cli.createExport', 'failed to build Styleguide', e)
throw (e)
})
/** create static styleguide structure */
} | javascript | function createExport(options) {
options = Object.assign({}, options, { prepare: false })
/** we need no styleguide preparation, like asset copying etc. */
return resolveStyleguide(options)
.then(function (styleguide) {
return styleguide.exportStyleguide()
})
.catch(function (e) {
error('Cli.createExport', 'failed to build Styleguide', e)
throw (e)
})
/** create static styleguide structure */
} | [
"function",
"createExport",
"(",
"options",
")",
"{",
"options",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
",",
"{",
"prepare",
":",
"false",
"}",
")",
"return",
"resolveStyleguide",
"(",
"options",
")",
".",
"then",
"(",
"function",
"(",
"styleguide",
")",
"{",
"return",
"styleguide",
".",
"exportStyleguide",
"(",
")",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"e",
")",
"{",
"error",
"(",
"'Cli.createExport'",
",",
"'failed to build Styleguide'",
",",
"e",
")",
"throw",
"(",
"e",
")",
"}",
")",
"}"
] | create styleguide partials, and maybe other exports | [
"create",
"styleguide",
"partials",
"and",
"maybe",
"other",
"exports"
] | 4729199b184fc1aa58b6abeef55e131fd58a1e00 | https://github.com/Galeria-Kaufhof/stylegen/blob/4729199b184fc1aa58b6abeef55e131fd58a1e00/src/Cli.js#L63-L76 | train |
nabil-boag/angular-multimocks | tasks/multimocksGenerator.js | function (config, mockSrc, defaultScenario, filenames,
scenarioName) {
// read mock data files for this scenario
var scenario = filenames.map(function (filename) {
var filepath = fs.realpathSync(path.join(mockSrc, filename));
return {
scenarioName: scenarioName,
filename: filename,
scenario: require(filepath)
};
});
return scenario;
} | javascript | function (config, mockSrc, defaultScenario, filenames,
scenarioName) {
// read mock data files for this scenario
var scenario = filenames.map(function (filename) {
var filepath = fs.realpathSync(path.join(mockSrc, filename));
return {
scenarioName: scenarioName,
filename: filename,
scenario: require(filepath)
};
});
return scenario;
} | [
"function",
"(",
"config",
",",
"mockSrc",
",",
"defaultScenario",
",",
"filenames",
",",
"scenarioName",
")",
"{",
"var",
"scenario",
"=",
"filenames",
".",
"map",
"(",
"function",
"(",
"filename",
")",
"{",
"var",
"filepath",
"=",
"fs",
".",
"realpathSync",
"(",
"path",
".",
"join",
"(",
"mockSrc",
",",
"filename",
")",
")",
";",
"return",
"{",
"scenarioName",
":",
"scenarioName",
",",
"filename",
":",
"filename",
",",
"scenario",
":",
"require",
"(",
"filepath",
")",
"}",
";",
"}",
")",
";",
"return",
"scenario",
";",
"}"
] | Read a scenario from a list of resource files, add URIs and merge in
resources from default scenario. | [
"Read",
"a",
"scenario",
"from",
"a",
"list",
"of",
"resource",
"files",
"add",
"URIs",
"and",
"merge",
"in",
"resources",
"from",
"default",
"scenario",
"."
] | 2b8cf993766a32703d62f11000c60da6df1777df | https://github.com/nabil-boag/angular-multimocks/blob/2b8cf993766a32703d62f11000c60da6df1777df/tasks/multimocksGenerator.js#L22-L36 | train |
|
nabil-boag/angular-multimocks | tasks/multimocksGenerator.js | function (config, mockSrc) {
var mockManifestPath = path.join(process.cwd(), mockSrc,
mockManifestFilename),
// read manifest JSON by require'ing it
mockManifest = require(mockManifestPath),
// read files for default scenario first, so we can merge it into other
// scenarios later
defaultScenario = readScenario(config, mockSrc, [],
mockManifest._default, '_default');
// read files for each scenario
return _.mapValues(mockManifest, function (filenames, scenarioName) {
return readScenario(config, mockSrc, defaultScenario, filenames,
scenarioName);
});
} | javascript | function (config, mockSrc) {
var mockManifestPath = path.join(process.cwd(), mockSrc,
mockManifestFilename),
// read manifest JSON by require'ing it
mockManifest = require(mockManifestPath),
// read files for default scenario first, so we can merge it into other
// scenarios later
defaultScenario = readScenario(config, mockSrc, [],
mockManifest._default, '_default');
// read files for each scenario
return _.mapValues(mockManifest, function (filenames, scenarioName) {
return readScenario(config, mockSrc, defaultScenario, filenames,
scenarioName);
});
} | [
"function",
"(",
"config",
",",
"mockSrc",
")",
"{",
"var",
"mockManifestPath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"mockSrc",
",",
"mockManifestFilename",
")",
",",
"mockManifest",
"=",
"require",
"(",
"mockManifestPath",
")",
",",
"defaultScenario",
"=",
"readScenario",
"(",
"config",
",",
"mockSrc",
",",
"[",
"]",
",",
"mockManifest",
".",
"_default",
",",
"'_default'",
")",
";",
"return",
"_",
".",
"mapValues",
"(",
"mockManifest",
",",
"function",
"(",
"filenames",
",",
"scenarioName",
")",
"{",
"return",
"readScenario",
"(",
"config",
",",
"mockSrc",
",",
"defaultScenario",
",",
"filenames",
",",
"scenarioName",
")",
";",
"}",
")",
";",
"}"
] | Read scenario definitions and return a structure that
multimockDataProvider.setMockData will understand. | [
"Read",
"scenario",
"definitions",
"and",
"return",
"a",
"structure",
"that",
"multimockDataProvider",
".",
"setMockData",
"will",
"understand",
"."
] | 2b8cf993766a32703d62f11000c60da6df1777df | https://github.com/nabil-boag/angular-multimocks/blob/2b8cf993766a32703d62f11000c60da6df1777df/tasks/multimocksGenerator.js#L42-L59 | train |
|
nabil-boag/angular-multimocks | tasks/multimocksGenerator.js | function (data, pluginNames) {
logger('runPlugins input', data);
var plugins = pluginNames.map(function (pn) { return pluginRegistry[pn]; }),
applyPlugin = function (oldData, plugin) { return plugin(oldData); };
// Use reduce to apply all the plugins to the data
var output = plugins.reduce(applyPlugin, data);
logger('runPlugins output', output);
return output;
} | javascript | function (data, pluginNames) {
logger('runPlugins input', data);
var plugins = pluginNames.map(function (pn) { return pluginRegistry[pn]; }),
applyPlugin = function (oldData, plugin) { return plugin(oldData); };
// Use reduce to apply all the plugins to the data
var output = plugins.reduce(applyPlugin, data);
logger('runPlugins output', output);
return output;
} | [
"function",
"(",
"data",
",",
"pluginNames",
")",
"{",
"logger",
"(",
"'runPlugins input'",
",",
"data",
")",
";",
"var",
"plugins",
"=",
"pluginNames",
".",
"map",
"(",
"function",
"(",
"pn",
")",
"{",
"return",
"pluginRegistry",
"[",
"pn",
"]",
";",
"}",
")",
",",
"applyPlugin",
"=",
"function",
"(",
"oldData",
",",
"plugin",
")",
"{",
"return",
"plugin",
"(",
"oldData",
")",
";",
"}",
";",
"var",
"output",
"=",
"plugins",
".",
"reduce",
"(",
"applyPlugin",
",",
"data",
")",
";",
"logger",
"(",
"'runPlugins output'",
",",
"output",
")",
";",
"return",
"output",
";",
"}"
] | Executes each of the plugins configured in the application to
decorate responses.
@param {object} data
@param {array} plugins
@return {object} decoratedData | [
"Executes",
"each",
"of",
"the",
"plugins",
"configured",
"in",
"the",
"application",
"to",
"decorate",
"responses",
"."
] | 2b8cf993766a32703d62f11000c60da6df1777df | https://github.com/nabil-boag/angular-multimocks/blob/2b8cf993766a32703d62f11000c60da6df1777df/tasks/multimocksGenerator.js#L69-L77 | train |
|
nabil-boag/angular-multimocks | tasks/multimocksGenerator.js | function (dataWithContext) {
return _.mapValues(dataWithContext, function (scenario) {
return scenario.map(function (response) {
return response.scenario;
});
});
} | javascript | function (dataWithContext) {
return _.mapValues(dataWithContext, function (scenario) {
return scenario.map(function (response) {
return response.scenario;
});
});
} | [
"function",
"(",
"dataWithContext",
")",
"{",
"return",
"_",
".",
"mapValues",
"(",
"dataWithContext",
",",
"function",
"(",
"scenario",
")",
"{",
"return",
"scenario",
".",
"map",
"(",
"function",
"(",
"response",
")",
"{",
"return",
"response",
".",
"scenario",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Strip context metadata from scenarios. | [
"Strip",
"context",
"metadata",
"from",
"scenarios",
"."
] | 2b8cf993766a32703d62f11000c60da6df1777df | https://github.com/nabil-boag/angular-multimocks/blob/2b8cf993766a32703d62f11000c60da6df1777df/tasks/multimocksGenerator.js#L82-L88 | train |
|
nabil-boag/angular-multimocks | tasks/multimocksGenerator.js | function (config, mockSrc) {
var dataWithContext = readMockManifest(config, mockSrc);
// log('readScenarioData config', config);
if (config.plugins) {
dataWithContext = runPlugins(dataWithContext, config.plugins);
}
return removeContext(dataWithContext);
} | javascript | function (config, mockSrc) {
var dataWithContext = readMockManifest(config, mockSrc);
// log('readScenarioData config', config);
if (config.plugins) {
dataWithContext = runPlugins(dataWithContext, config.plugins);
}
return removeContext(dataWithContext);
} | [
"function",
"(",
"config",
",",
"mockSrc",
")",
"{",
"var",
"dataWithContext",
"=",
"readMockManifest",
"(",
"config",
",",
"mockSrc",
")",
";",
"if",
"(",
"config",
".",
"plugins",
")",
"{",
"dataWithContext",
"=",
"runPlugins",
"(",
"dataWithContext",
",",
"config",
".",
"plugins",
")",
";",
"}",
"return",
"removeContext",
"(",
"dataWithContext",
")",
";",
"}"
] | Return a javascript object of all scenario data.
@param {string} config
@param {string} mockSrc
@returns {object} | [
"Return",
"a",
"javascript",
"object",
"of",
"all",
"scenario",
"data",
"."
] | 2b8cf993766a32703d62f11000c60da6df1777df | https://github.com/nabil-boag/angular-multimocks/blob/2b8cf993766a32703d62f11000c60da6df1777df/tasks/multimocksGenerator.js#L98-L107 | train |
|
nabil-boag/angular-multimocks | tasks/multimocksGenerator.js | function (templatePath, path, data, name) {
var templateString = fs.readFileSync(templatePath);
// generate scenarioData.js contents by inserting data into template
var templateData = {scenarioData: data};
templateData.scenarioDataName = name || '';
var output = _.template(templateString)(templateData);
mkdirp.sync(getDirName(path));
fs.writeFileSync(path, output);
} | javascript | function (templatePath, path, data, name) {
var templateString = fs.readFileSync(templatePath);
// generate scenarioData.js contents by inserting data into template
var templateData = {scenarioData: data};
templateData.scenarioDataName = name || '';
var output = _.template(templateString)(templateData);
mkdirp.sync(getDirName(path));
fs.writeFileSync(path, output);
} | [
"function",
"(",
"templatePath",
",",
"path",
",",
"data",
",",
"name",
")",
"{",
"var",
"templateString",
"=",
"fs",
".",
"readFileSync",
"(",
"templatePath",
")",
";",
"var",
"templateData",
"=",
"{",
"scenarioData",
":",
"data",
"}",
";",
"templateData",
".",
"scenarioDataName",
"=",
"name",
"||",
"''",
";",
"var",
"output",
"=",
"_",
".",
"template",
"(",
"templateString",
")",
"(",
"templateData",
")",
";",
"mkdirp",
".",
"sync",
"(",
"getDirName",
"(",
"path",
")",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"path",
",",
"output",
")",
";",
"}"
] | Save the file
@param {string} template
@param {string} path
@param {string} data
@param {string} name | [
"Save",
"the",
"file"
] | 2b8cf993766a32703d62f11000c60da6df1777df | https://github.com/nabil-boag/angular-multimocks/blob/2b8cf993766a32703d62f11000c60da6df1777df/tasks/multimocksGenerator.js#L117-L128 | train |
|
nabil-boag/angular-multimocks | tasks/multimocksGenerator.js | function () {
config.multipleFiles = config.multipleFiles || false;
var defaultTemplate = singleFileDefaultTemplate;
if (config.multipleFiles) {
defaultTemplate = multipleFilesDefaultTemplate;
}
config.template = config.template || defaultTemplate;
var mockSrc = _.isArray(config.src) ? _.first(config.src) : config.src;
logger('mock source', mockSrc);
logger('dest', config.dest);
logger('template', config.template);
logger('multipleFiles', config.multipleFiles);
logger('plugins', config.plugins);
// read all scenario data from manifest/JSON files
var scenarioData = readScenarioData(config, mockSrc);
logger('scenarioData', scenarioData);
var scenarioModuleFilename = config.dest,
scenarioString;
if (!config.multipleFiles) {
// stringify all scenario files into a single Angular module
scenarioString = JSON.stringify(scenarioData);
writeScenarioModule(config.template, scenarioModuleFilename,
scenarioString);
} else {
fs.mkdirSync(config.dest);
// stringify each scenario file into it's own Angular module
for (var scenarioName in scenarioData) {
if (scenarioData.hasOwnProperty(scenarioName)) {
scenarioModuleFilename = config.dest + '/' + scenarioName +
'.js';
scenarioString = JSON.stringify(scenarioData[scenarioName]);
writeScenarioModule(config.template, scenarioModuleFilename,
scenarioString, scenarioName);
}
}
}
} | javascript | function () {
config.multipleFiles = config.multipleFiles || false;
var defaultTemplate = singleFileDefaultTemplate;
if (config.multipleFiles) {
defaultTemplate = multipleFilesDefaultTemplate;
}
config.template = config.template || defaultTemplate;
var mockSrc = _.isArray(config.src) ? _.first(config.src) : config.src;
logger('mock source', mockSrc);
logger('dest', config.dest);
logger('template', config.template);
logger('multipleFiles', config.multipleFiles);
logger('plugins', config.plugins);
// read all scenario data from manifest/JSON files
var scenarioData = readScenarioData(config, mockSrc);
logger('scenarioData', scenarioData);
var scenarioModuleFilename = config.dest,
scenarioString;
if (!config.multipleFiles) {
// stringify all scenario files into a single Angular module
scenarioString = JSON.stringify(scenarioData);
writeScenarioModule(config.template, scenarioModuleFilename,
scenarioString);
} else {
fs.mkdirSync(config.dest);
// stringify each scenario file into it's own Angular module
for (var scenarioName in scenarioData) {
if (scenarioData.hasOwnProperty(scenarioName)) {
scenarioModuleFilename = config.dest + '/' + scenarioName +
'.js';
scenarioString = JSON.stringify(scenarioData[scenarioName]);
writeScenarioModule(config.template, scenarioModuleFilename,
scenarioString, scenarioName);
}
}
}
} | [
"function",
"(",
")",
"{",
"config",
".",
"multipleFiles",
"=",
"config",
".",
"multipleFiles",
"||",
"false",
";",
"var",
"defaultTemplate",
"=",
"singleFileDefaultTemplate",
";",
"if",
"(",
"config",
".",
"multipleFiles",
")",
"{",
"defaultTemplate",
"=",
"multipleFilesDefaultTemplate",
";",
"}",
"config",
".",
"template",
"=",
"config",
".",
"template",
"||",
"defaultTemplate",
";",
"var",
"mockSrc",
"=",
"_",
".",
"isArray",
"(",
"config",
".",
"src",
")",
"?",
"_",
".",
"first",
"(",
"config",
".",
"src",
")",
":",
"config",
".",
"src",
";",
"logger",
"(",
"'mock source'",
",",
"mockSrc",
")",
";",
"logger",
"(",
"'dest'",
",",
"config",
".",
"dest",
")",
";",
"logger",
"(",
"'template'",
",",
"config",
".",
"template",
")",
";",
"logger",
"(",
"'multipleFiles'",
",",
"config",
".",
"multipleFiles",
")",
";",
"logger",
"(",
"'plugins'",
",",
"config",
".",
"plugins",
")",
";",
"var",
"scenarioData",
"=",
"readScenarioData",
"(",
"config",
",",
"mockSrc",
")",
";",
"logger",
"(",
"'scenarioData'",
",",
"scenarioData",
")",
";",
"var",
"scenarioModuleFilename",
"=",
"config",
".",
"dest",
",",
"scenarioString",
";",
"if",
"(",
"!",
"config",
".",
"multipleFiles",
")",
"{",
"scenarioString",
"=",
"JSON",
".",
"stringify",
"(",
"scenarioData",
")",
";",
"writeScenarioModule",
"(",
"config",
".",
"template",
",",
"scenarioModuleFilename",
",",
"scenarioString",
")",
";",
"}",
"else",
"{",
"fs",
".",
"mkdirSync",
"(",
"config",
".",
"dest",
")",
";",
"for",
"(",
"var",
"scenarioName",
"in",
"scenarioData",
")",
"{",
"if",
"(",
"scenarioData",
".",
"hasOwnProperty",
"(",
"scenarioName",
")",
")",
"{",
"scenarioModuleFilename",
"=",
"config",
".",
"dest",
"+",
"'/'",
"+",
"scenarioName",
"+",
"'.js'",
";",
"scenarioString",
"=",
"JSON",
".",
"stringify",
"(",
"scenarioData",
"[",
"scenarioName",
"]",
")",
";",
"writeScenarioModule",
"(",
"config",
".",
"template",
",",
"scenarioModuleFilename",
",",
"scenarioString",
",",
"scenarioName",
")",
";",
"}",
"}",
"}",
"}"
] | Read mock manifest and JSON files and compile into JS files ready for
inclusion into an Angular app. | [
"Read",
"mock",
"manifest",
"and",
"JSON",
"files",
"and",
"compile",
"into",
"JS",
"files",
"ready",
"for",
"inclusion",
"into",
"an",
"Angular",
"app",
"."
] | 2b8cf993766a32703d62f11000c60da6df1777df | https://github.com/nabil-boag/angular-multimocks/blob/2b8cf993766a32703d62f11000c60da6df1777df/tasks/multimocksGenerator.js#L134-L178 | train |
|
kiln/flourish-popup | src/index.js | accessor | function accessor(k) {
Popup.prototype[k] = function(v) {
if (typeof v == "undefined") return this["_" + k];
this["_" + k] = v;
return this;
};
} | javascript | function accessor(k) {
Popup.prototype[k] = function(v) {
if (typeof v == "undefined") return this["_" + k];
this["_" + k] = v;
return this;
};
} | [
"function",
"accessor",
"(",
"k",
")",
"{",
"Popup",
".",
"prototype",
"[",
"k",
"]",
"=",
"function",
"(",
"v",
")",
"{",
"if",
"(",
"typeof",
"v",
"==",
"\"undefined\"",
")",
"return",
"this",
"[",
"\"_\"",
"+",
"k",
"]",
";",
"this",
"[",
"\"_\"",
"+",
"k",
"]",
"=",
"v",
";",
"return",
"this",
";",
"}",
";",
"}"
] | Create accessor methods for all the options | [
"Create",
"accessor",
"methods",
"for",
"all",
"the",
"options"
] | b0fb3a63d864a417f5dade9bb07132ce96584fc4 | https://github.com/kiln/flourish-popup/blob/b0fb3a63d864a417f5dade9bb07132ce96584fc4/src/index.js#L33-L39 | train |
syntax-tree/unist-util-inspect | index.js | compile | function compile(pos) {
var values = []
if (!pos) {
return null
}
values = [[pos.line || 1, pos.column || 1].join(':')]
if ('offset' in pos) {
values.push(String(pos.offset || 0))
}
return values
} | javascript | function compile(pos) {
var values = []
if (!pos) {
return null
}
values = [[pos.line || 1, pos.column || 1].join(':')]
if ('offset' in pos) {
values.push(String(pos.offset || 0))
}
return values
} | [
"function",
"compile",
"(",
"pos",
")",
"{",
"var",
"values",
"=",
"[",
"]",
"if",
"(",
"!",
"pos",
")",
"{",
"return",
"null",
"}",
"values",
"=",
"[",
"[",
"pos",
".",
"line",
"||",
"1",
",",
"pos",
".",
"column",
"||",
"1",
"]",
".",
"join",
"(",
"':'",
")",
"]",
"if",
"(",
"'offset'",
"in",
"pos",
")",
"{",
"values",
".",
"push",
"(",
"String",
"(",
"pos",
".",
"offset",
"||",
"0",
")",
")",
"}",
"return",
"values",
"}"
] | Compile a single position. | [
"Compile",
"a",
"single",
"position",
"."
] | 3756c4a88ae74f102633f69d57bda26b341f1fe2 | https://github.com/syntax-tree/unist-util-inspect/blob/3756c4a88ae74f102633f69d57bda26b341f1fe2/index.js#L103-L117 | train |
syntax-tree/unist-util-inspect | index.js | stringify | function stringify(start, end) {
var values = []
var positions = []
var offsets = []
add(start)
add(end)
if (positions.length !== 0) {
values.push(positions.join('-'))
}
if (offsets.length !== 0) {
values.push(offsets.join('-'))
}
return values.join(', ')
// Add a position.
function add(position) {
var tuple = compile(position)
if (tuple) {
positions.push(tuple[0])
if (tuple[1]) {
offsets.push(tuple[1])
}
}
}
} | javascript | function stringify(start, end) {
var values = []
var positions = []
var offsets = []
add(start)
add(end)
if (positions.length !== 0) {
values.push(positions.join('-'))
}
if (offsets.length !== 0) {
values.push(offsets.join('-'))
}
return values.join(', ')
// Add a position.
function add(position) {
var tuple = compile(position)
if (tuple) {
positions.push(tuple[0])
if (tuple[1]) {
offsets.push(tuple[1])
}
}
}
} | [
"function",
"stringify",
"(",
"start",
",",
"end",
")",
"{",
"var",
"values",
"=",
"[",
"]",
"var",
"positions",
"=",
"[",
"]",
"var",
"offsets",
"=",
"[",
"]",
"add",
"(",
"start",
")",
"add",
"(",
"end",
")",
"if",
"(",
"positions",
".",
"length",
"!==",
"0",
")",
"{",
"values",
".",
"push",
"(",
"positions",
".",
"join",
"(",
"'-'",
")",
")",
"}",
"if",
"(",
"offsets",
".",
"length",
"!==",
"0",
")",
"{",
"values",
".",
"push",
"(",
"offsets",
".",
"join",
"(",
"'-'",
")",
")",
"}",
"return",
"values",
".",
"join",
"(",
"', '",
")",
"function",
"add",
"(",
"position",
")",
"{",
"var",
"tuple",
"=",
"compile",
"(",
"position",
")",
"if",
"(",
"tuple",
")",
"{",
"positions",
".",
"push",
"(",
"tuple",
"[",
"0",
"]",
")",
"if",
"(",
"tuple",
"[",
"1",
"]",
")",
"{",
"offsets",
".",
"push",
"(",
"tuple",
"[",
"1",
"]",
")",
"}",
"}",
"}",
"}"
] | Compile a location. | [
"Compile",
"a",
"location",
"."
] | 3756c4a88ae74f102633f69d57bda26b341f1fe2 | https://github.com/syntax-tree/unist-util-inspect/blob/3756c4a88ae74f102633f69d57bda26b341f1fe2/index.js#L120-L150 | train |
syntax-tree/unist-util-inspect | index.js | add | function add(position) {
var tuple = compile(position)
if (tuple) {
positions.push(tuple[0])
if (tuple[1]) {
offsets.push(tuple[1])
}
}
} | javascript | function add(position) {
var tuple = compile(position)
if (tuple) {
positions.push(tuple[0])
if (tuple[1]) {
offsets.push(tuple[1])
}
}
} | [
"function",
"add",
"(",
"position",
")",
"{",
"var",
"tuple",
"=",
"compile",
"(",
"position",
")",
"if",
"(",
"tuple",
")",
"{",
"positions",
".",
"push",
"(",
"tuple",
"[",
"0",
"]",
")",
"if",
"(",
"tuple",
"[",
"1",
"]",
")",
"{",
"offsets",
".",
"push",
"(",
"tuple",
"[",
"1",
"]",
")",
"}",
"}",
"}"
] | Add a position. | [
"Add",
"a",
"position",
"."
] | 3756c4a88ae74f102633f69d57bda26b341f1fe2 | https://github.com/syntax-tree/unist-util-inspect/blob/3756c4a88ae74f102633f69d57bda26b341f1fe2/index.js#L139-L149 | train |
syntax-tree/unist-util-inspect | index.js | formatNode | function formatNode(node) {
var log = node.type
var location = node.position || {}
var position = stringify(location.start, location.end)
var key
var values = []
var value
if (node.children) {
log += dim('[') + yellow(node.children.length) + dim(']')
} else if (typeof node.value === 'string') {
log += dim(': ') + green(JSON.stringify(node.value))
}
if (position) {
log += ' (' + position + ')'
}
for (key in node) {
value = node[key]
if (
ignore.indexOf(key) !== -1 ||
value === null ||
value === undefined ||
(typeof value === 'object' && isEmpty(value))
) {
continue
}
values.push('[' + key + '=' + JSON.stringify(value) + ']')
}
if (values.length !== 0) {
log += ' ' + values.join('')
}
return log
} | javascript | function formatNode(node) {
var log = node.type
var location = node.position || {}
var position = stringify(location.start, location.end)
var key
var values = []
var value
if (node.children) {
log += dim('[') + yellow(node.children.length) + dim(']')
} else if (typeof node.value === 'string') {
log += dim(': ') + green(JSON.stringify(node.value))
}
if (position) {
log += ' (' + position + ')'
}
for (key in node) {
value = node[key]
if (
ignore.indexOf(key) !== -1 ||
value === null ||
value === undefined ||
(typeof value === 'object' && isEmpty(value))
) {
continue
}
values.push('[' + key + '=' + JSON.stringify(value) + ']')
}
if (values.length !== 0) {
log += ' ' + values.join('')
}
return log
} | [
"function",
"formatNode",
"(",
"node",
")",
"{",
"var",
"log",
"=",
"node",
".",
"type",
"var",
"location",
"=",
"node",
".",
"position",
"||",
"{",
"}",
"var",
"position",
"=",
"stringify",
"(",
"location",
".",
"start",
",",
"location",
".",
"end",
")",
"var",
"key",
"var",
"values",
"=",
"[",
"]",
"var",
"value",
"if",
"(",
"node",
".",
"children",
")",
"{",
"log",
"+=",
"dim",
"(",
"'['",
")",
"+",
"yellow",
"(",
"node",
".",
"children",
".",
"length",
")",
"+",
"dim",
"(",
"']'",
")",
"}",
"else",
"if",
"(",
"typeof",
"node",
".",
"value",
"===",
"'string'",
")",
"{",
"log",
"+=",
"dim",
"(",
"': '",
")",
"+",
"green",
"(",
"JSON",
".",
"stringify",
"(",
"node",
".",
"value",
")",
")",
"}",
"if",
"(",
"position",
")",
"{",
"log",
"+=",
"' ('",
"+",
"position",
"+",
"')'",
"}",
"for",
"(",
"key",
"in",
"node",
")",
"{",
"value",
"=",
"node",
"[",
"key",
"]",
"if",
"(",
"ignore",
".",
"indexOf",
"(",
"key",
")",
"!==",
"-",
"1",
"||",
"value",
"===",
"null",
"||",
"value",
"===",
"undefined",
"||",
"(",
"typeof",
"value",
"===",
"'object'",
"&&",
"isEmpty",
"(",
"value",
")",
")",
")",
"{",
"continue",
"}",
"values",
".",
"push",
"(",
"'['",
"+",
"key",
"+",
"'='",
"+",
"JSON",
".",
"stringify",
"(",
"value",
")",
"+",
"']'",
")",
"}",
"if",
"(",
"values",
".",
"length",
"!==",
"0",
")",
"{",
"log",
"+=",
"' '",
"+",
"values",
".",
"join",
"(",
"''",
")",
"}",
"return",
"log",
"}"
] | Colored node formatter. | [
"Colored",
"node",
"formatter",
"."
] | 3756c4a88ae74f102633f69d57bda26b341f1fe2 | https://github.com/syntax-tree/unist-util-inspect/blob/3756c4a88ae74f102633f69d57bda26b341f1fe2/index.js#L153-L191 | train |
mjeanroy/rollup-plugin-bower-resolve | src/bower.js | execList | function execList(options) {
const deferred = Q.defer();
const json = options.json !== false;
const offline = options.offline !== false;
const cwd = options.cwd || process.cwd();
const config = {json, offline, cwd};
bower.commands.list(undefined, config)
.on('end', (conf) => {
deferred.resolve(flatten(conf));
})
.on('error', (error) => {
deferred.reject(error);
});
return deferred.promise;
} | javascript | function execList(options) {
const deferred = Q.defer();
const json = options.json !== false;
const offline = options.offline !== false;
const cwd = options.cwd || process.cwd();
const config = {json, offline, cwd};
bower.commands.list(undefined, config)
.on('end', (conf) => {
deferred.resolve(flatten(conf));
})
.on('error', (error) => {
deferred.reject(error);
});
return deferred.promise;
} | [
"function",
"execList",
"(",
"options",
")",
"{",
"const",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"const",
"json",
"=",
"options",
".",
"json",
"!==",
"false",
";",
"const",
"offline",
"=",
"options",
".",
"offline",
"!==",
"false",
";",
"const",
"cwd",
"=",
"options",
".",
"cwd",
"||",
"process",
".",
"cwd",
"(",
")",
";",
"const",
"config",
"=",
"{",
"json",
",",
"offline",
",",
"cwd",
"}",
";",
"bower",
".",
"commands",
".",
"list",
"(",
"undefined",
",",
"config",
")",
".",
"on",
"(",
"'end'",
",",
"(",
"conf",
")",
"=>",
"{",
"deferred",
".",
"resolve",
"(",
"flatten",
"(",
"conf",
")",
")",
";",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"(",
"error",
")",
"=>",
"{",
"deferred",
".",
"reject",
"(",
"error",
")",
";",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] | List all dependencies of a bower package.
@param {Object} options Bower options.
@return {Promise<Object>} The promise of dependency object. | [
"List",
"all",
"dependencies",
"of",
"a",
"bower",
"package",
"."
] | 17ce6b3b6346351c1dd8ca7479afc21e73711af1 | https://github.com/mjeanroy/rollup-plugin-bower-resolve/blob/17ce6b3b6346351c1dd8ca7479afc21e73711af1/src/bower.js#L41-L58 | train |
thunks/tman | lib/reporters/diff.js | errMessageFormat | function errMessageFormat (showDiff, pos, title, msg, stack) {
if (showDiff) {
return format.red(' ' + pos + ') ' + title + ':\n' + msg) + format.gray('\n' + stack + '\n')
}
return format.red(' ' + pos + ') ' + title + ':\n') +
format.white(' ' + msg) +
format.white('\n' + stack + '\n')
} | javascript | function errMessageFormat (showDiff, pos, title, msg, stack) {
if (showDiff) {
return format.red(' ' + pos + ') ' + title + ':\n' + msg) + format.gray('\n' + stack + '\n')
}
return format.red(' ' + pos + ') ' + title + ':\n') +
format.white(' ' + msg) +
format.white('\n' + stack + '\n')
} | [
"function",
"errMessageFormat",
"(",
"showDiff",
",",
"pos",
",",
"title",
",",
"msg",
",",
"stack",
")",
"{",
"if",
"(",
"showDiff",
")",
"{",
"return",
"format",
".",
"red",
"(",
"' '",
"+",
"pos",
"+",
"') '",
"+",
"title",
"+",
"':\\n'",
"+",
"\\n",
")",
"+",
"msg",
"}",
"format",
".",
"gray",
"(",
"'\\n'",
"+",
"\\n",
"+",
"stack",
")",
"}"
] | Return formated error message
@private
@param{boolean} is diff message
@param{number} index of message in Error queue
@param{string} test suite title
@param{string} error message
@param{string} error stack | [
"Return",
"formated",
"error",
"message"
] | 095f3adb50c71eea65c28a04ef505ab34baf8435 | https://github.com/thunks/tman/blob/095f3adb50c71eea65c28a04ef505ab34baf8435/lib/reporters/diff.js#L94-L101 | train |
thunks/tman | lib/reporters/diff.js | unifiedDiff | function unifiedDiff (err) {
let indent = ' '
function cleanUp (line) {
if (line[0] === '+') {
return indent + format.colorLines('green', line)
}
if (line[0] === '-') {
return indent + format.colorLines('red', line)
}
if (line.match(/@@/)) {
return null
}
if (line.match(/\\ No newline/)) {
return null
}
if (line.trim().length) {
line = format.colorLines('white', line)
}
return indent + line
}
function notBlank (line) {
return typeof line !== 'undefined' && line !== null
}
let msg = diff.createPatch('string', err.actual, err.expected)
let lines = msg.split('\n').splice(4)
let diffResult = lines.map(cleanUp).filter(notBlank).join('\n')
if (!diffResult.trim().length) {
msg = diff.createPatch(
'string',
stringify(Object.keys(err._actual || err.actual).sort()),
stringify(Object.keys(err._expected || err.expected).sort())
)
lines = msg.split('\n').splice(4)
diffResult = format.red(' object keys not match: \n') + lines.map(cleanUp).filter(notBlank).join('\n')
}
return '\n ' +
format.colorLines('green', '+ expected') + ' ' +
format.colorLines('red', '- actual') +
'\n\n' +
diffResult
} | javascript | function unifiedDiff (err) {
let indent = ' '
function cleanUp (line) {
if (line[0] === '+') {
return indent + format.colorLines('green', line)
}
if (line[0] === '-') {
return indent + format.colorLines('red', line)
}
if (line.match(/@@/)) {
return null
}
if (line.match(/\\ No newline/)) {
return null
}
if (line.trim().length) {
line = format.colorLines('white', line)
}
return indent + line
}
function notBlank (line) {
return typeof line !== 'undefined' && line !== null
}
let msg = diff.createPatch('string', err.actual, err.expected)
let lines = msg.split('\n').splice(4)
let diffResult = lines.map(cleanUp).filter(notBlank).join('\n')
if (!diffResult.trim().length) {
msg = diff.createPatch(
'string',
stringify(Object.keys(err._actual || err.actual).sort()),
stringify(Object.keys(err._expected || err.expected).sort())
)
lines = msg.split('\n').splice(4)
diffResult = format.red(' object keys not match: \n') + lines.map(cleanUp).filter(notBlank).join('\n')
}
return '\n ' +
format.colorLines('green', '+ expected') + ' ' +
format.colorLines('red', '- actual') +
'\n\n' +
diffResult
} | [
"function",
"unifiedDiff",
"(",
"err",
")",
"{",
"let",
"indent",
"=",
"' '",
"function",
"cleanUp",
"(",
"line",
")",
"{",
"if",
"(",
"line",
"[",
"0",
"]",
"===",
"'+'",
")",
"{",
"return",
"indent",
"+",
"format",
".",
"colorLines",
"(",
"'green'",
",",
"line",
")",
"}",
"if",
"(",
"line",
"[",
"0",
"]",
"===",
"'-'",
")",
"{",
"return",
"indent",
"+",
"format",
".",
"colorLines",
"(",
"'red'",
",",
"line",
")",
"}",
"if",
"(",
"line",
".",
"match",
"(",
"/",
"@@",
"/",
")",
")",
"{",
"return",
"null",
"}",
"if",
"(",
"line",
".",
"match",
"(",
"/",
"\\\\ No newline",
"/",
")",
")",
"{",
"return",
"null",
"}",
"if",
"(",
"line",
".",
"trim",
"(",
")",
".",
"length",
")",
"{",
"line",
"=",
"format",
".",
"colorLines",
"(",
"'white'",
",",
"line",
")",
"}",
"return",
"indent",
"+",
"line",
"}",
"function",
"notBlank",
"(",
"line",
")",
"{",
"return",
"typeof",
"line",
"!==",
"'undefined'",
"&&",
"line",
"!==",
"null",
"}",
"let",
"msg",
"=",
"diff",
".",
"createPatch",
"(",
"'string'",
",",
"err",
".",
"actual",
",",
"err",
".",
"expected",
")",
"let",
"lines",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
".",
"\\n",
"splice",
"(",
"4",
")",
"let",
"diffResult",
"=",
"lines",
".",
"map",
"(",
"cleanUp",
")",
".",
"filter",
"(",
"notBlank",
")",
".",
"join",
"(",
"'\\n'",
")",
"\\n",
"}"
] | Returns a unified diff between two strings.
@private
@param {Error} err with actual/expected
@return {string} The diff. | [
"Returns",
"a",
"unified",
"diff",
"between",
"two",
"strings",
"."
] | 095f3adb50c71eea65c28a04ef505ab34baf8435 | https://github.com/thunks/tman/blob/095f3adb50c71eea65c28a04ef505ab34baf8435/lib/reporters/diff.js#L109-L149 | train |
pugjs/with | src/index.js | unwrapReturns | function unwrapReturns(ast, src, result) {
const charArray = src.split('');
const state = {
hasReturn: false,
source(node) {
return src.slice(node.start, node.end);
},
replace(node, str) {
charArray.fill('', node.start, node.end);
charArray[node.start] = str;
}
};
walk(ast, unwrapReturnsVisitors, state);
return {
before: state.hasReturn ? `var ${result} = ` : '',
body: charArray.join(''),
after: state.hasReturn ? `;if (${result}) return ${result}.value` : ''
};
} | javascript | function unwrapReturns(ast, src, result) {
const charArray = src.split('');
const state = {
hasReturn: false,
source(node) {
return src.slice(node.start, node.end);
},
replace(node, str) {
charArray.fill('', node.start, node.end);
charArray[node.start] = str;
}
};
walk(ast, unwrapReturnsVisitors, state);
return {
before: state.hasReturn ? `var ${result} = ` : '',
body: charArray.join(''),
after: state.hasReturn ? `;if (${result}) return ${result}.value` : ''
};
} | [
"function",
"unwrapReturns",
"(",
"ast",
",",
"src",
",",
"result",
")",
"{",
"const",
"charArray",
"=",
"src",
".",
"split",
"(",
"''",
")",
";",
"const",
"state",
"=",
"{",
"hasReturn",
":",
"false",
",",
"source",
"(",
"node",
")",
"{",
"return",
"src",
".",
"slice",
"(",
"node",
".",
"start",
",",
"node",
".",
"end",
")",
";",
"}",
",",
"replace",
"(",
"node",
",",
"str",
")",
"{",
"charArray",
".",
"fill",
"(",
"''",
",",
"node",
".",
"start",
",",
"node",
".",
"end",
")",
";",
"charArray",
"[",
"node",
".",
"start",
"]",
"=",
"str",
";",
"}",
"}",
";",
"walk",
"(",
"ast",
",",
"unwrapReturnsVisitors",
",",
"state",
")",
";",
"return",
"{",
"before",
":",
"state",
".",
"hasReturn",
"?",
"`",
"${",
"result",
"}",
"`",
":",
"''",
",",
"body",
":",
"charArray",
".",
"join",
"(",
"''",
")",
",",
"after",
":",
"state",
".",
"hasReturn",
"?",
"`",
"${",
"result",
"}",
"${",
"result",
"}",
"`",
":",
"''",
"}",
";",
"}"
] | Take a self calling function, and unwrap it such that return inside the function
results in return outside the function
@param {String} src Some JavaScript code representing a self-calling function
@param {String} result A temporary variable to store the result in | [
"Take",
"a",
"self",
"calling",
"function",
"and",
"unwrap",
"it",
"such",
"that",
"return",
"inside",
"the",
"function",
"results",
"in",
"return",
"outside",
"the",
"function"
] | bba6079960cfb657079573117b1c651f291ce3a6 | https://github.com/pugjs/with/blob/bba6079960cfb657079573117b1c651f291ce3a6/src/index.js#L114-L135 | train |
ibericode/boxzilla.js | src/boxzilla.js | checkPageViewsCriteria | function checkPageViewsCriteria() {
// don't bother if another box is currently open
if( isAnyBoxVisible() ) {
return;
}
boxes.forEach(function(box) {
if( ! box.mayAutoShow() ) {
return;
}
if( box.config.trigger.method === 'pageviews' && pageViews >= box.config.trigger.value ) {
box.trigger();
}
});
} | javascript | function checkPageViewsCriteria() {
// don't bother if another box is currently open
if( isAnyBoxVisible() ) {
return;
}
boxes.forEach(function(box) {
if( ! box.mayAutoShow() ) {
return;
}
if( box.config.trigger.method === 'pageviews' && pageViews >= box.config.trigger.value ) {
box.trigger();
}
});
} | [
"function",
"checkPageViewsCriteria",
"(",
")",
"{",
"if",
"(",
"isAnyBoxVisible",
"(",
")",
")",
"{",
"return",
";",
"}",
"boxes",
".",
"forEach",
"(",
"function",
"(",
"box",
")",
"{",
"if",
"(",
"!",
"box",
".",
"mayAutoShow",
"(",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"box",
".",
"config",
".",
"trigger",
".",
"method",
"===",
"'pageviews'",
"&&",
"pageViews",
">=",
"box",
".",
"config",
".",
"trigger",
".",
"value",
")",
"{",
"box",
".",
"trigger",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | check "pageviews" criteria for each box | [
"check",
"pageviews",
"criteria",
"for",
"each",
"box"
] | 6f2575e112a019da6a78510a2f830aae40ea3e37 | https://github.com/ibericode/boxzilla.js/blob/6f2575e112a019da6a78510a2f830aae40ea3e37/src/boxzilla.js#L49-L65 | train |
ibericode/boxzilla.js | src/boxzilla.js | checkTimeCriteria | function checkTimeCriteria() {
// don't bother if another box is currently open
if( isAnyBoxVisible() ) {
return;
}
boxes.forEach(function(box) {
if( ! box.mayAutoShow() ) {
return;
}
// check "time on site" trigger
if (box.config.trigger.method === 'time_on_site' && siteTimer.time >= box.config.trigger.value) {
box.trigger();
}
// check "time on page" trigger
if (box.config.trigger.method === 'time_on_page' && pageTimer.time >= box.config.trigger.value) {
box.trigger();
}
});
} | javascript | function checkTimeCriteria() {
// don't bother if another box is currently open
if( isAnyBoxVisible() ) {
return;
}
boxes.forEach(function(box) {
if( ! box.mayAutoShow() ) {
return;
}
// check "time on site" trigger
if (box.config.trigger.method === 'time_on_site' && siteTimer.time >= box.config.trigger.value) {
box.trigger();
}
// check "time on page" trigger
if (box.config.trigger.method === 'time_on_page' && pageTimer.time >= box.config.trigger.value) {
box.trigger();
}
});
} | [
"function",
"checkTimeCriteria",
"(",
")",
"{",
"if",
"(",
"isAnyBoxVisible",
"(",
")",
")",
"{",
"return",
";",
"}",
"boxes",
".",
"forEach",
"(",
"function",
"(",
"box",
")",
"{",
"if",
"(",
"!",
"box",
".",
"mayAutoShow",
"(",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"box",
".",
"config",
".",
"trigger",
".",
"method",
"===",
"'time_on_site'",
"&&",
"siteTimer",
".",
"time",
">=",
"box",
".",
"config",
".",
"trigger",
".",
"value",
")",
"{",
"box",
".",
"trigger",
"(",
")",
";",
"}",
"if",
"(",
"box",
".",
"config",
".",
"trigger",
".",
"method",
"===",
"'time_on_page'",
"&&",
"pageTimer",
".",
"time",
">=",
"box",
".",
"config",
".",
"trigger",
".",
"value",
")",
"{",
"box",
".",
"trigger",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | check time trigger criteria for each box | [
"check",
"time",
"trigger",
"criteria",
"for",
"each",
"box"
] | 6f2575e112a019da6a78510a2f830aae40ea3e37 | https://github.com/ibericode/boxzilla.js/blob/6f2575e112a019da6a78510a2f830aae40ea3e37/src/boxzilla.js#L68-L89 | train |
ibericode/boxzilla.js | src/boxzilla.js | checkHeightCriteria | function checkHeightCriteria() {
var scrollY = scrollElement.hasOwnProperty('pageYOffset') ? scrollElement.pageYOffset : scrollElement.scrollTop;
scrollY = scrollY + window.innerHeight * 0.9;
boxes.forEach(function(box) {
if( ! box.mayAutoShow() || box.triggerHeight <= 0 ) {
return;
}
if( scrollY > box.triggerHeight ) {
// don't bother if another box is currently open
if( isAnyBoxVisible() ) {
return;
}
// trigger box
box.trigger();
}
// if box may auto-hide and scrollY is less than triggerHeight (with small margin of error), hide box
if( box.mayRehide() && scrollY < ( box.triggerHeight - 5 ) ) {
box.hide();
}
});
} | javascript | function checkHeightCriteria() {
var scrollY = scrollElement.hasOwnProperty('pageYOffset') ? scrollElement.pageYOffset : scrollElement.scrollTop;
scrollY = scrollY + window.innerHeight * 0.9;
boxes.forEach(function(box) {
if( ! box.mayAutoShow() || box.triggerHeight <= 0 ) {
return;
}
if( scrollY > box.triggerHeight ) {
// don't bother if another box is currently open
if( isAnyBoxVisible() ) {
return;
}
// trigger box
box.trigger();
}
// if box may auto-hide and scrollY is less than triggerHeight (with small margin of error), hide box
if( box.mayRehide() && scrollY < ( box.triggerHeight - 5 ) ) {
box.hide();
}
});
} | [
"function",
"checkHeightCriteria",
"(",
")",
"{",
"var",
"scrollY",
"=",
"scrollElement",
".",
"hasOwnProperty",
"(",
"'pageYOffset'",
")",
"?",
"scrollElement",
".",
"pageYOffset",
":",
"scrollElement",
".",
"scrollTop",
";",
"scrollY",
"=",
"scrollY",
"+",
"window",
".",
"innerHeight",
"*",
"0.9",
";",
"boxes",
".",
"forEach",
"(",
"function",
"(",
"box",
")",
"{",
"if",
"(",
"!",
"box",
".",
"mayAutoShow",
"(",
")",
"||",
"box",
".",
"triggerHeight",
"<=",
"0",
")",
"{",
"return",
";",
"}",
"if",
"(",
"scrollY",
">",
"box",
".",
"triggerHeight",
")",
"{",
"if",
"(",
"isAnyBoxVisible",
"(",
")",
")",
"{",
"return",
";",
"}",
"box",
".",
"trigger",
"(",
")",
";",
"}",
"if",
"(",
"box",
".",
"mayRehide",
"(",
")",
"&&",
"scrollY",
"<",
"(",
"box",
".",
"triggerHeight",
"-",
"5",
")",
")",
"{",
"box",
".",
"hide",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | check triggerHeight criteria for all boxes | [
"check",
"triggerHeight",
"criteria",
"for",
"all",
"boxes"
] | 6f2575e112a019da6a78510a2f830aae40ea3e37 | https://github.com/ibericode/boxzilla.js/blob/6f2575e112a019da6a78510a2f830aae40ea3e37/src/boxzilla.js#L92-L117 | train |
bpmn-io/object-refs | lib/refs.js | Refs | function Refs(a, b) {
if (!(this instanceof Refs)) {
return new Refs(a, b);
}
// link
a.inverse = b;
b.inverse = a;
this.props = {};
this.props[a.name] = a;
this.props[b.name] = b;
} | javascript | function Refs(a, b) {
if (!(this instanceof Refs)) {
return new Refs(a, b);
}
// link
a.inverse = b;
b.inverse = a;
this.props = {};
this.props[a.name] = a;
this.props[b.name] = b;
} | [
"function",
"Refs",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Refs",
")",
")",
"{",
"return",
"new",
"Refs",
"(",
"a",
",",
"b",
")",
";",
"}",
"a",
".",
"inverse",
"=",
"b",
";",
"b",
".",
"inverse",
"=",
"a",
";",
"this",
".",
"props",
"=",
"{",
"}",
";",
"this",
".",
"props",
"[",
"a",
".",
"name",
"]",
"=",
"a",
";",
"this",
".",
"props",
"[",
"b",
".",
"name",
"]",
"=",
"b",
";",
"}"
] | Creates a new references object defining two inversly related
attribute descriptors a and b.
<p>
When bound to an object using {@link Refs#bind} the references
get activated and ensure that add and remove operations are applied
reversely, too.
</p>
<p>
For attributes represented as collections {@link Refs} provides the
{@link RefsCollection#add}, {@link RefsCollection#remove} and {@link RefsCollection#contains} extensions
that must be used to properly hook into the inverse change mechanism.
</p>
@class Refs
@classdesc A bi-directional reference between two attributes.
@param {Refs.AttributeDescriptor} a property descriptor
@param {Refs.AttributeDescriptor} b property descriptor
@example
var refs = Refs({ name: 'wheels', collection: true, enumerable: true }, { name: 'car' });
var car = { name: 'toyota' };
var wheels = [{ pos: 'front-left' }, { pos: 'front-right' }];
refs.bind(car, 'wheels');
car.wheels // []
car.wheels.add(wheels[0]);
car.wheels.add(wheels[1]);
car.wheels // [{ pos: 'front-left' }, { pos: 'front-right' }]
wheels[0].car // { name: 'toyota' };
car.wheels.remove(wheels[0]);
wheels[0].car // undefined | [
"Creates",
"a",
"new",
"references",
"object",
"defining",
"two",
"inversly",
"related",
"attribute",
"descriptors",
"a",
"and",
"b",
"."
] | e742b8c506260b1bf241d25b9883cd08453284d5 | https://github.com/bpmn-io/object-refs/blob/e742b8c506260b1bf241d25b9883cd08453284d5/lib/refs.js#L110-L123 | train |
chocolatechip-ui/chocolatechipui | src/core/events.js | function(element, event, callback, capturePhase) {
if (!element.id) element.id = $.uuid()
if (!ChuiEventCache.elements[element.id]) {
ChuiEventCache.elements[element.id] = []
}
ChuiEventCache.elements[element.id].push({
event: event,
callback: callback
})
element.addEventListener(event, callback, capturePhase)
} | javascript | function(element, event, callback, capturePhase) {
if (!element.id) element.id = $.uuid()
if (!ChuiEventCache.elements[element.id]) {
ChuiEventCache.elements[element.id] = []
}
ChuiEventCache.elements[element.id].push({
event: event,
callback: callback
})
element.addEventListener(event, callback, capturePhase)
} | [
"function",
"(",
"element",
",",
"event",
",",
"callback",
",",
"capturePhase",
")",
"{",
"if",
"(",
"!",
"element",
".",
"id",
")",
"element",
".",
"id",
"=",
"$",
".",
"uuid",
"(",
")",
"if",
"(",
"!",
"ChuiEventCache",
".",
"elements",
"[",
"element",
".",
"id",
"]",
")",
"{",
"ChuiEventCache",
".",
"elements",
"[",
"element",
".",
"id",
"]",
"=",
"[",
"]",
"}",
"ChuiEventCache",
".",
"elements",
"[",
"element",
".",
"id",
"]",
".",
"push",
"(",
"{",
"event",
":",
"event",
",",
"callback",
":",
"callback",
"}",
")",
"element",
".",
"addEventListener",
"(",
"event",
",",
"callback",
",",
"capturePhase",
")",
"}"
] | Private method to set events on ChuiEventCache | [
"Private",
"method",
"to",
"set",
"events",
"on",
"ChuiEventCache"
] | 5971e275168caf51eb60dd71d041e9d6fda53829 | https://github.com/chocolatechip-ui/chocolatechipui/blob/5971e275168caf51eb60dd71d041e9d6fda53829/src/core/events.js#L48-L58 | train |
|
chocolatechip-ui/chocolatechipui | src/core/events.js | function(element, event, callback) {
const eventStack = ChuiEventCache.elements[element.id]
if (!eventStack) return
let deleteOrder = []
if (!event) {
deleteOrder = []
eventStack.forEach(function(evt, idx) {
element.removeEventListener(evt.event, evt.callback, evt.capturePhase)
deleteOrder.push(idx)
})
deleteFromEventStack(deleteOrder, eventStack)
} else if (!!event && !callback) {
deleteOrder = []
eventStack.forEach(function(evt, idx) {
if (evt.event === event) {
element.removeEventListener(evt.event, evt.callback, evt.capturePhase)
deleteOrder.push(idx)
}
})
deleteFromEventStack(deleteOrder, eventStack)
} else if (callback) {
deleteOrder = []
eventStack.forEach(function(evt, idx) {
if (callback === evt.callback) {
element.removeEventListener(evt.event, evt.callback, evt.capturePhase)
deleteOrder.push(idx)
}
})
deleteFromEventStack(deleteOrder, eventStack)
}
} | javascript | function(element, event, callback) {
const eventStack = ChuiEventCache.elements[element.id]
if (!eventStack) return
let deleteOrder = []
if (!event) {
deleteOrder = []
eventStack.forEach(function(evt, idx) {
element.removeEventListener(evt.event, evt.callback, evt.capturePhase)
deleteOrder.push(idx)
})
deleteFromEventStack(deleteOrder, eventStack)
} else if (!!event && !callback) {
deleteOrder = []
eventStack.forEach(function(evt, idx) {
if (evt.event === event) {
element.removeEventListener(evt.event, evt.callback, evt.capturePhase)
deleteOrder.push(idx)
}
})
deleteFromEventStack(deleteOrder, eventStack)
} else if (callback) {
deleteOrder = []
eventStack.forEach(function(evt, idx) {
if (callback === evt.callback) {
element.removeEventListener(evt.event, evt.callback, evt.capturePhase)
deleteOrder.push(idx)
}
})
deleteFromEventStack(deleteOrder, eventStack)
}
} | [
"function",
"(",
"element",
",",
"event",
",",
"callback",
")",
"{",
"const",
"eventStack",
"=",
"ChuiEventCache",
".",
"elements",
"[",
"element",
".",
"id",
"]",
"if",
"(",
"!",
"eventStack",
")",
"return",
"let",
"deleteOrder",
"=",
"[",
"]",
"if",
"(",
"!",
"event",
")",
"{",
"deleteOrder",
"=",
"[",
"]",
"eventStack",
".",
"forEach",
"(",
"function",
"(",
"evt",
",",
"idx",
")",
"{",
"element",
".",
"removeEventListener",
"(",
"evt",
".",
"event",
",",
"evt",
".",
"callback",
",",
"evt",
".",
"capturePhase",
")",
"deleteOrder",
".",
"push",
"(",
"idx",
")",
"}",
")",
"deleteFromEventStack",
"(",
"deleteOrder",
",",
"eventStack",
")",
"}",
"else",
"if",
"(",
"!",
"!",
"event",
"&&",
"!",
"callback",
")",
"{",
"deleteOrder",
"=",
"[",
"]",
"eventStack",
".",
"forEach",
"(",
"function",
"(",
"evt",
",",
"idx",
")",
"{",
"if",
"(",
"evt",
".",
"event",
"===",
"event",
")",
"{",
"element",
".",
"removeEventListener",
"(",
"evt",
".",
"event",
",",
"evt",
".",
"callback",
",",
"evt",
".",
"capturePhase",
")",
"deleteOrder",
".",
"push",
"(",
"idx",
")",
"}",
"}",
")",
"deleteFromEventStack",
"(",
"deleteOrder",
",",
"eventStack",
")",
"}",
"else",
"if",
"(",
"callback",
")",
"{",
"deleteOrder",
"=",
"[",
"]",
"eventStack",
".",
"forEach",
"(",
"function",
"(",
"evt",
",",
"idx",
")",
"{",
"if",
"(",
"callback",
"===",
"evt",
".",
"callback",
")",
"{",
"element",
".",
"removeEventListener",
"(",
"evt",
".",
"event",
",",
"evt",
".",
"callback",
",",
"evt",
".",
"capturePhase",
")",
"deleteOrder",
".",
"push",
"(",
"idx",
")",
"}",
"}",
")",
"deleteFromEventStack",
"(",
"deleteOrder",
",",
"eventStack",
")",
"}",
"}"
] | Private method to unbind events on ChuiEventCache | [
"Private",
"method",
"to",
"unbind",
"events",
"on",
"ChuiEventCache"
] | 5971e275168caf51eb60dd71d041e9d6fda53829 | https://github.com/chocolatechip-ui/chocolatechipui/blob/5971e275168caf51eb60dd71d041e9d6fda53829/src/core/events.js#L73-L109 | train |
|
chocolatechip-ui/chocolatechipui | src/core/events.js | function(element, selector, event, callback, capturePhase) {
const delegateElement = $(element).array[0]
$(element).forEach(function(ctx) {
$(ctx).on(event, function(e) {
let target = e.target
if (e.target.nodeType === 3) {
target = e.target.parentNode
}
$(ctx).find(selector).forEach(function(delegateElement) {
if (delegateElement === target) {
callback.call(delegateElement, e)
} else {
try {
const ancestor = $(target).closest(selector)
if (delegateElement === ancestor.array[0]) {
callback.call(delegateElement, e)
}
} catch (err) {}
}
})
}, capturePhase)
})
} | javascript | function(element, selector, event, callback, capturePhase) {
const delegateElement = $(element).array[0]
$(element).forEach(function(ctx) {
$(ctx).on(event, function(e) {
let target = e.target
if (e.target.nodeType === 3) {
target = e.target.parentNode
}
$(ctx).find(selector).forEach(function(delegateElement) {
if (delegateElement === target) {
callback.call(delegateElement, e)
} else {
try {
const ancestor = $(target).closest(selector)
if (delegateElement === ancestor.array[0]) {
callback.call(delegateElement, e)
}
} catch (err) {}
}
})
}, capturePhase)
})
} | [
"function",
"(",
"element",
",",
"selector",
",",
"event",
",",
"callback",
",",
"capturePhase",
")",
"{",
"const",
"delegateElement",
"=",
"$",
"(",
"element",
")",
".",
"array",
"[",
"0",
"]",
"$",
"(",
"element",
")",
".",
"forEach",
"(",
"function",
"(",
"ctx",
")",
"{",
"$",
"(",
"ctx",
")",
".",
"on",
"(",
"event",
",",
"function",
"(",
"e",
")",
"{",
"let",
"target",
"=",
"e",
".",
"target",
"if",
"(",
"e",
".",
"target",
".",
"nodeType",
"===",
"3",
")",
"{",
"target",
"=",
"e",
".",
"target",
".",
"parentNode",
"}",
"$",
"(",
"ctx",
")",
".",
"find",
"(",
"selector",
")",
".",
"forEach",
"(",
"function",
"(",
"delegateElement",
")",
"{",
"if",
"(",
"delegateElement",
"===",
"target",
")",
"{",
"callback",
".",
"call",
"(",
"delegateElement",
",",
"e",
")",
"}",
"else",
"{",
"try",
"{",
"const",
"ancestor",
"=",
"$",
"(",
"target",
")",
".",
"closest",
"(",
"selector",
")",
"if",
"(",
"delegateElement",
"===",
"ancestor",
".",
"array",
"[",
"0",
"]",
")",
"{",
"callback",
".",
"call",
"(",
"delegateElement",
",",
"e",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"}",
"}",
")",
"}",
",",
"capturePhase",
")",
"}",
")",
"}"
] | Set delegated events on ChuiEventCache | [
"Set",
"delegated",
"events",
"on",
"ChuiEventCache"
] | 5971e275168caf51eb60dd71d041e9d6fda53829 | https://github.com/chocolatechip-ui/chocolatechipui/blob/5971e275168caf51eb60dd71d041e9d6fda53829/src/core/events.js#L114-L136 | train |
|
feedhenry/fh-db | lib/utils.js | getName | function getName () {
const pathname = url.parse(parts[parts.length - 1]).pathname;
return pathname ? pathname.replace('/', '') : pathname;
} | javascript | function getName () {
const pathname = url.parse(parts[parts.length - 1]).pathname;
return pathname ? pathname.replace('/', '') : pathname;
} | [
"function",
"getName",
"(",
")",
"{",
"const",
"pathname",
"=",
"url",
".",
"parse",
"(",
"parts",
"[",
"parts",
".",
"length",
"-",
"1",
"]",
")",
".",
"pathname",
";",
"return",
"pathname",
"?",
"pathname",
".",
"replace",
"(",
"'/'",
",",
"''",
")",
":",
"pathname",
";",
"}"
] | The name comes from the path in the URL. We must always use the last host | [
"The",
"name",
"comes",
"from",
"the",
"path",
"in",
"the",
"URL",
".",
"We",
"must",
"always",
"use",
"the",
"last",
"host"
] | 9fd8f6b3ada5e39533f05903beddab984bcd0149 | https://github.com/feedhenry/fh-db/blob/9fd8f6b3ada5e39533f05903beddab984bcd0149/lib/utils.js#L19-L23 | train |
feedhenry/fh-db | lib/utils.js | getOptionsObject | function getOptionsObject () {
if (parts.length > 1) {
// Options should be appended to the last hosts querystring
return qs.parse(url.parse(parts[parts.length - 1]).query);
}
return {};
} | javascript | function getOptionsObject () {
if (parts.length > 1) {
// Options should be appended to the last hosts querystring
return qs.parse(url.parse(parts[parts.length - 1]).query);
}
return {};
} | [
"function",
"getOptionsObject",
"(",
")",
"{",
"if",
"(",
"parts",
".",
"length",
">",
"1",
")",
"{",
"return",
"qs",
".",
"parse",
"(",
"url",
".",
"parse",
"(",
"parts",
"[",
"parts",
".",
"length",
"-",
"1",
"]",
")",
".",
"query",
")",
";",
"}",
"return",
"{",
"}",
";",
"}"
] | Parse the query string from the last host portion | [
"Parse",
"the",
"query",
"string",
"from",
"the",
"last",
"host",
"portion"
] | 9fd8f6b3ada5e39533f05903beddab984bcd0149 | https://github.com/feedhenry/fh-db/blob/9fd8f6b3ada5e39533f05903beddab984bcd0149/lib/utils.js#L26-L33 | train |
feedhenry/fh-db | lib/utils.js | getAuthenticationObject | function getAuthenticationObject () {
const authString = url.parse(parts[0]).auth;
if (authString) {
return {
source: getName(),
user: authString.split(':')[0],
pass: authString.split(':')[1]
};
} else {
return {};
}
} | javascript | function getAuthenticationObject () {
const authString = url.parse(parts[0]).auth;
if (authString) {
return {
source: getName(),
user: authString.split(':')[0],
pass: authString.split(':')[1]
};
} else {
return {};
}
} | [
"function",
"getAuthenticationObject",
"(",
")",
"{",
"const",
"authString",
"=",
"url",
".",
"parse",
"(",
"parts",
"[",
"0",
"]",
")",
".",
"auth",
";",
"if",
"(",
"authString",
")",
"{",
"return",
"{",
"source",
":",
"getName",
"(",
")",
",",
"user",
":",
"authString",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
",",
"pass",
":",
"authString",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
"}",
";",
"}",
"else",
"{",
"return",
"{",
"}",
";",
"}",
"}"
] | Authentication is defined in the primary host URL | [
"Authentication",
"is",
"defined",
"in",
"the",
"primary",
"host",
"URL"
] | 9fd8f6b3ada5e39533f05903beddab984bcd0149 | https://github.com/feedhenry/fh-db/blob/9fd8f6b3ada5e39533f05903beddab984bcd0149/lib/utils.js#L36-L48 | train |
webgme/executor-worker | node_worker.classes.build.js | function (metadata) {
var key;
if (metadata) {
this.name = metadata.name;
this.size = metadata.size || 0;
this.mime = metadata.mime || '';
this.isPublic = metadata.isPublic || false;
this.tags = metadata.tags || [];
this.content = metadata.content;
this.contentType = metadata.contentType || BlobMetadata.CONTENT_TYPES.OBJECT;
if (this.contentType === BlobMetadata.CONTENT_TYPES.COMPLEX) {
for (key in this.content) {
if (this.content.hasOwnProperty(key)) {
if (BlobConfig.hashRegex.test(this.content[key].content) === false) {
throw new Error('BlobMetadata is malformed: hash \'' + this.content[key].content +
'\'is invalid');
}
}
}
}
} else {
throw new Error('metadata parameter is not defined');
}
} | javascript | function (metadata) {
var key;
if (metadata) {
this.name = metadata.name;
this.size = metadata.size || 0;
this.mime = metadata.mime || '';
this.isPublic = metadata.isPublic || false;
this.tags = metadata.tags || [];
this.content = metadata.content;
this.contentType = metadata.contentType || BlobMetadata.CONTENT_TYPES.OBJECT;
if (this.contentType === BlobMetadata.CONTENT_TYPES.COMPLEX) {
for (key in this.content) {
if (this.content.hasOwnProperty(key)) {
if (BlobConfig.hashRegex.test(this.content[key].content) === false) {
throw new Error('BlobMetadata is malformed: hash \'' + this.content[key].content +
'\'is invalid');
}
}
}
}
} else {
throw new Error('metadata parameter is not defined');
}
} | [
"function",
"(",
"metadata",
")",
"{",
"var",
"key",
";",
"if",
"(",
"metadata",
")",
"{",
"this",
".",
"name",
"=",
"metadata",
".",
"name",
";",
"this",
".",
"size",
"=",
"metadata",
".",
"size",
"||",
"0",
";",
"this",
".",
"mime",
"=",
"metadata",
".",
"mime",
"||",
"''",
";",
"this",
".",
"isPublic",
"=",
"metadata",
".",
"isPublic",
"||",
"false",
";",
"this",
".",
"tags",
"=",
"metadata",
".",
"tags",
"||",
"[",
"]",
";",
"this",
".",
"content",
"=",
"metadata",
".",
"content",
";",
"this",
".",
"contentType",
"=",
"metadata",
".",
"contentType",
"||",
"BlobMetadata",
".",
"CONTENT_TYPES",
".",
"OBJECT",
";",
"if",
"(",
"this",
".",
"contentType",
"===",
"BlobMetadata",
".",
"CONTENT_TYPES",
".",
"COMPLEX",
")",
"{",
"for",
"(",
"key",
"in",
"this",
".",
"content",
")",
"{",
"if",
"(",
"this",
".",
"content",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"if",
"(",
"BlobConfig",
".",
"hashRegex",
".",
"test",
"(",
"this",
".",
"content",
"[",
"key",
"]",
".",
"content",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"Error",
"(",
"'BlobMetadata is malformed: hash \\''",
"+",
"\\'",
"+",
"this",
".",
"content",
"[",
"key",
"]",
".",
"content",
")",
";",
"}",
"}",
"}",
"}",
"}",
"else",
"'\\'is invalid'",
"}"
] | Initializes a new instance of BlobMetadata
@param {object} metadata - A serialized metadata object.
@param {string} metadata.name
@param {string|Object} metadata.content
@param {number} [metadata.size=0]
@param {BlobMetadata.CONTENT_TYPES} [metadata.contentType=BlobMetadata.CONTENT_TYPES.OBJECT]
@param {string} [metadata.mime='']
@param {boolean} [metadata.isPublic=false]
@param {string[]} [metadata.tags=[]]
@constructor
@alias BlobMetadata | [
"Initializes",
"a",
"new",
"instance",
"of",
"BlobMetadata"
] | 13c85023e59d6a3e4e594f797e240daa4884488d | https://github.com/webgme/executor-worker/blob/13c85023e59d6a3e4e594f797e240daa4884488d/node_worker.classes.build.js#L2150-L2173 | train |
|
webgme/executor-worker | node_worker.classes.build.js | function (parameters) {
parameters = parameters || {};
if (parameters.logger) {
this.logger = parameters.logger;
} else {
/*eslint-disable no-console*/
var doLog = function () {
console.log.apply(console, arguments);
};
this.logger = {
debug: doLog,
log: doLog,
info: doLog,
warn: doLog,
error: doLog
};
console.warn('Since v1.3.0 ExecutorClient requires a logger, falling back on console.log.');
/*eslint-enable no-console*/
}
this.logger.debug('ctor', {metadata: parameters});
this.isNodeJS = (typeof window === 'undefined') && (typeof process === 'object');
this.isNodeWebkit = (typeof window === 'object') && (typeof process === 'object');
//console.log(isNode);
if (this.isNodeJS) {
this.logger.debug('Running under node');
this.server = '127.0.0.1';
this.httpsecure = false;
}
this.server = parameters.server || this.server;
this.serverPort = parameters.serverPort || this.serverPort;
this.httpsecure = (parameters.httpsecure !== undefined) ? parameters.httpsecure : this.httpsecure;
if (this.isNodeJS) {
this.http = this.httpsecure ? require('https') : require('http');
}
this.origin = '';
if (this.httpsecure !== undefined && this.server && this.serverPort) {
this.origin = (this.httpsecure ? 'https://' : 'http://') + this.server + ':' + this.serverPort;
}
if (parameters && typeof parameters.relativeUrl === 'string') {
this.relativeUrl = parameters.relativeUrl;
} else if (typeof WebGMEGlobal !== 'undefined' && WebGMEGlobal.gmeConfig &&
typeof WebGMEGlobal.gmeConfig.client.mountedPath === 'string') {
this.relativeUrl = WebGMEGlobal.gmeConfig.client.mountedPath + '/rest/executor/';
} else {
this.relativeUrl = '/rest/executor/';
}
this.executorUrl = this.origin + this.relativeUrl;
// TODO: TOKEN???
// TODO: any ways to ask for this or get it from the configuration?
if (parameters.executorNonce) {
this.executorNonce = parameters.executorNonce;
}
this.logger.debug('origin', this.origin);
this.logger.debug('executorUrl', this.executorUrl);
} | javascript | function (parameters) {
parameters = parameters || {};
if (parameters.logger) {
this.logger = parameters.logger;
} else {
/*eslint-disable no-console*/
var doLog = function () {
console.log.apply(console, arguments);
};
this.logger = {
debug: doLog,
log: doLog,
info: doLog,
warn: doLog,
error: doLog
};
console.warn('Since v1.3.0 ExecutorClient requires a logger, falling back on console.log.');
/*eslint-enable no-console*/
}
this.logger.debug('ctor', {metadata: parameters});
this.isNodeJS = (typeof window === 'undefined') && (typeof process === 'object');
this.isNodeWebkit = (typeof window === 'object') && (typeof process === 'object');
//console.log(isNode);
if (this.isNodeJS) {
this.logger.debug('Running under node');
this.server = '127.0.0.1';
this.httpsecure = false;
}
this.server = parameters.server || this.server;
this.serverPort = parameters.serverPort || this.serverPort;
this.httpsecure = (parameters.httpsecure !== undefined) ? parameters.httpsecure : this.httpsecure;
if (this.isNodeJS) {
this.http = this.httpsecure ? require('https') : require('http');
}
this.origin = '';
if (this.httpsecure !== undefined && this.server && this.serverPort) {
this.origin = (this.httpsecure ? 'https://' : 'http://') + this.server + ':' + this.serverPort;
}
if (parameters && typeof parameters.relativeUrl === 'string') {
this.relativeUrl = parameters.relativeUrl;
} else if (typeof WebGMEGlobal !== 'undefined' && WebGMEGlobal.gmeConfig &&
typeof WebGMEGlobal.gmeConfig.client.mountedPath === 'string') {
this.relativeUrl = WebGMEGlobal.gmeConfig.client.mountedPath + '/rest/executor/';
} else {
this.relativeUrl = '/rest/executor/';
}
this.executorUrl = this.origin + this.relativeUrl;
// TODO: TOKEN???
// TODO: any ways to ask for this or get it from the configuration?
if (parameters.executorNonce) {
this.executorNonce = parameters.executorNonce;
}
this.logger.debug('origin', this.origin);
this.logger.debug('executorUrl', this.executorUrl);
} | [
"function",
"(",
"parameters",
")",
"{",
"parameters",
"=",
"parameters",
"||",
"{",
"}",
";",
"if",
"(",
"parameters",
".",
"logger",
")",
"{",
"this",
".",
"logger",
"=",
"parameters",
".",
"logger",
";",
"}",
"else",
"{",
"var",
"doLog",
"=",
"function",
"(",
")",
"{",
"console",
".",
"log",
".",
"apply",
"(",
"console",
",",
"arguments",
")",
";",
"}",
";",
"this",
".",
"logger",
"=",
"{",
"debug",
":",
"doLog",
",",
"log",
":",
"doLog",
",",
"info",
":",
"doLog",
",",
"warn",
":",
"doLog",
",",
"error",
":",
"doLog",
"}",
";",
"console",
".",
"warn",
"(",
"'Since v1.3.0 ExecutorClient requires a logger, falling back on console.log.'",
")",
";",
"}",
"this",
".",
"logger",
".",
"debug",
"(",
"'ctor'",
",",
"{",
"metadata",
":",
"parameters",
"}",
")",
";",
"this",
".",
"isNodeJS",
"=",
"(",
"typeof",
"window",
"===",
"'undefined'",
")",
"&&",
"(",
"typeof",
"process",
"===",
"'object'",
")",
";",
"this",
".",
"isNodeWebkit",
"=",
"(",
"typeof",
"window",
"===",
"'object'",
")",
"&&",
"(",
"typeof",
"process",
"===",
"'object'",
")",
";",
"if",
"(",
"this",
".",
"isNodeJS",
")",
"{",
"this",
".",
"logger",
".",
"debug",
"(",
"'Running under node'",
")",
";",
"this",
".",
"server",
"=",
"'127.0.0.1'",
";",
"this",
".",
"httpsecure",
"=",
"false",
";",
"}",
"this",
".",
"server",
"=",
"parameters",
".",
"server",
"||",
"this",
".",
"server",
";",
"this",
".",
"serverPort",
"=",
"parameters",
".",
"serverPort",
"||",
"this",
".",
"serverPort",
";",
"this",
".",
"httpsecure",
"=",
"(",
"parameters",
".",
"httpsecure",
"!==",
"undefined",
")",
"?",
"parameters",
".",
"httpsecure",
":",
"this",
".",
"httpsecure",
";",
"if",
"(",
"this",
".",
"isNodeJS",
")",
"{",
"this",
".",
"http",
"=",
"this",
".",
"httpsecure",
"?",
"require",
"(",
"'https'",
")",
":",
"require",
"(",
"'http'",
")",
";",
"}",
"this",
".",
"origin",
"=",
"''",
";",
"if",
"(",
"this",
".",
"httpsecure",
"!==",
"undefined",
"&&",
"this",
".",
"server",
"&&",
"this",
".",
"serverPort",
")",
"{",
"this",
".",
"origin",
"=",
"(",
"this",
".",
"httpsecure",
"?",
"'https://'",
":",
"'http://'",
")",
"+",
"this",
".",
"server",
"+",
"':'",
"+",
"this",
".",
"serverPort",
";",
"}",
"if",
"(",
"parameters",
"&&",
"typeof",
"parameters",
".",
"relativeUrl",
"===",
"'string'",
")",
"{",
"this",
".",
"relativeUrl",
"=",
"parameters",
".",
"relativeUrl",
";",
"}",
"else",
"if",
"(",
"typeof",
"WebGMEGlobal",
"!==",
"'undefined'",
"&&",
"WebGMEGlobal",
".",
"gmeConfig",
"&&",
"typeof",
"WebGMEGlobal",
".",
"gmeConfig",
".",
"client",
".",
"mountedPath",
"===",
"'string'",
")",
"{",
"this",
".",
"relativeUrl",
"=",
"WebGMEGlobal",
".",
"gmeConfig",
".",
"client",
".",
"mountedPath",
"+",
"'/rest/executor/'",
";",
"}",
"else",
"{",
"this",
".",
"relativeUrl",
"=",
"'/rest/executor/'",
";",
"}",
"this",
".",
"executorUrl",
"=",
"this",
".",
"origin",
"+",
"this",
".",
"relativeUrl",
";",
"if",
"(",
"parameters",
".",
"executorNonce",
")",
"{",
"this",
".",
"executorNonce",
"=",
"parameters",
".",
"executorNonce",
";",
"}",
"this",
".",
"logger",
".",
"debug",
"(",
"'origin'",
",",
"this",
".",
"origin",
")",
";",
"this",
".",
"logger",
".",
"debug",
"(",
"'executorUrl'",
",",
"this",
".",
"executorUrl",
")",
";",
"}"
] | Client for creating, monitoring, and receiving output executor jobs.
This client is used by the Executor Workers and some of the API calls are not
meant to be used by "end users".
@param {object} parameters
@param {object} parameters.logger
@constructor
@alias ExecutorClient | [
"Client",
"for",
"creating",
"monitoring",
"and",
"receiving",
"output",
"executor",
"jobs",
".",
"This",
"client",
"is",
"used",
"by",
"the",
"Executor",
"Workers",
"and",
"some",
"of",
"the",
"API",
"calls",
"are",
"not",
"meant",
"to",
"be",
"used",
"by",
"end",
"users",
"."
] | 13c85023e59d6a3e4e594f797e240daa4884488d | https://github.com/webgme/executor-worker/blob/13c85023e59d6a3e4e594f797e240daa4884488d/node_worker.classes.build.js#L3984-L4044 | train |
|
mixmaxhq/publication-server | client/src/utils.js | expandKeys | function expandKeys(object) {
var hasFlattenedKeys = _.some(object, function(val, key) {
return key.split('.').length > 1;
});
if (!hasFlattenedKeys) return object;
return _.reduce(object, function(payload, value, key) {
var path = key.split('.');
if (path.length === 1) {
var obj = {};
obj[key] = value;
payload = deepExtend(payload, obj);
return payload;
}
var subKey = path.pop();
var localObj = payload;
while (path.length) {
var subPath = path.shift();
localObj = localObj[subPath] = localObj[subPath] || {};
}
localObj[subKey] = object[key];
return payload;
}, {});
} | javascript | function expandKeys(object) {
var hasFlattenedKeys = _.some(object, function(val, key) {
return key.split('.').length > 1;
});
if (!hasFlattenedKeys) return object;
return _.reduce(object, function(payload, value, key) {
var path = key.split('.');
if (path.length === 1) {
var obj = {};
obj[key] = value;
payload = deepExtend(payload, obj);
return payload;
}
var subKey = path.pop();
var localObj = payload;
while (path.length) {
var subPath = path.shift();
localObj = localObj[subPath] = localObj[subPath] || {};
}
localObj[subKey] = object[key];
return payload;
}, {});
} | [
"function",
"expandKeys",
"(",
"object",
")",
"{",
"var",
"hasFlattenedKeys",
"=",
"_",
".",
"some",
"(",
"object",
",",
"function",
"(",
"val",
",",
"key",
")",
"{",
"return",
"key",
".",
"split",
"(",
"'.'",
")",
".",
"length",
">",
"1",
";",
"}",
")",
";",
"if",
"(",
"!",
"hasFlattenedKeys",
")",
"return",
"object",
";",
"return",
"_",
".",
"reduce",
"(",
"object",
",",
"function",
"(",
"payload",
",",
"value",
",",
"key",
")",
"{",
"var",
"path",
"=",
"key",
".",
"split",
"(",
"'.'",
")",
";",
"if",
"(",
"path",
".",
"length",
"===",
"1",
")",
"{",
"var",
"obj",
"=",
"{",
"}",
";",
"obj",
"[",
"key",
"]",
"=",
"value",
";",
"payload",
"=",
"deepExtend",
"(",
"payload",
",",
"obj",
")",
";",
"return",
"payload",
";",
"}",
"var",
"subKey",
"=",
"path",
".",
"pop",
"(",
")",
";",
"var",
"localObj",
"=",
"payload",
";",
"while",
"(",
"path",
".",
"length",
")",
"{",
"var",
"subPath",
"=",
"path",
".",
"shift",
"(",
")",
";",
"localObj",
"=",
"localObj",
"[",
"subPath",
"]",
"=",
"localObj",
"[",
"subPath",
"]",
"||",
"{",
"}",
";",
"}",
"localObj",
"[",
"subKey",
"]",
"=",
"object",
"[",
"key",
"]",
";",
"return",
"payload",
";",
"}",
",",
"{",
"}",
")",
";",
"}"
] | Expands any keys with dot notation in an object.
Returns the original object if there aren't any flattened keys to begin with.
@param {Object} object
@return {Object} object with keys as nested objects | [
"Expands",
"any",
"keys",
"with",
"dot",
"notation",
"in",
"an",
"object",
".",
"Returns",
"the",
"original",
"object",
"if",
"there",
"aren",
"t",
"any",
"flattened",
"keys",
"to",
"begin",
"with",
"."
] | 8b8276c158fe038a9f90d8a268f60075ad785568 | https://github.com/mixmaxhq/publication-server/blob/8b8276c158fe038a9f90d8a268f60075ad785568/client/src/utils.js#L55-L78 | train |
mixmaxhq/publication-server | client/src/utils.js | deepExtend | function deepExtend(target, source) {
_.each(source, function(value, key) {
if (_.has(target, key) && isObject(target[key]) && isObject(source[key])) {
deepExtend(target[key], source[key]);
} else {
target[key] = source[key];
}
});
return target;
} | javascript | function deepExtend(target, source) {
_.each(source, function(value, key) {
if (_.has(target, key) && isObject(target[key]) && isObject(source[key])) {
deepExtend(target[key], source[key]);
} else {
target[key] = source[key];
}
});
return target;
} | [
"function",
"deepExtend",
"(",
"target",
",",
"source",
")",
"{",
"_",
".",
"each",
"(",
"source",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"if",
"(",
"_",
".",
"has",
"(",
"target",
",",
"key",
")",
"&&",
"isObject",
"(",
"target",
"[",
"key",
"]",
")",
"&&",
"isObject",
"(",
"source",
"[",
"key",
"]",
")",
")",
"{",
"deepExtend",
"(",
"target",
"[",
"key",
"]",
",",
"source",
"[",
"key",
"]",
")",
";",
"}",
"else",
"{",
"target",
"[",
"key",
"]",
"=",
"source",
"[",
"key",
"]",
";",
"}",
"}",
")",
";",
"return",
"target",
";",
"}"
] | Performs a deep merge of two objects, source into target.
@param {Object} target
@param {Object} source
@return {Object} | [
"Performs",
"a",
"deep",
"merge",
"of",
"two",
"objects",
"source",
"into",
"target",
"."
] | 8b8276c158fe038a9f90d8a268f60075ad785568 | https://github.com/mixmaxhq/publication-server/blob/8b8276c158fe038a9f90d8a268f60075ad785568/client/src/utils.js#L87-L96 | train |
feedhenry/fh-db | lib/convert_query_type.js | query | function query(value, field, expression) {
if (!expression) {
return value;
}
var expressionQuery = {};
expressionQuery[expression] = value;
return expressionQuery;
} | javascript | function query(value, field, expression) {
if (!expression) {
return value;
}
var expressionQuery = {};
expressionQuery[expression] = value;
return expressionQuery;
} | [
"function",
"query",
"(",
"value",
",",
"field",
",",
"expression",
")",
"{",
"if",
"(",
"!",
"expression",
")",
"{",
"return",
"value",
";",
"}",
"var",
"expressionQuery",
"=",
"{",
"}",
";",
"expressionQuery",
"[",
"expression",
"]",
"=",
"value",
";",
"return",
"expressionQuery",
";",
"}"
] | Creates an object containing the expression key and value queried.
@param {String} expression - This is the operator used in query.
@param {String} field - This is the column being quried.
@param {ObjectId|Number|Boolean} value - This is the value being quried.
@returns {Object} expressionQuery - contains the expressions key and query value. | [
"Creates",
"an",
"object",
"containing",
"the",
"expression",
"key",
"and",
"value",
"queried",
"."
] | 9fd8f6b3ada5e39533f05903beddab984bcd0149 | https://github.com/feedhenry/fh-db/blob/9fd8f6b3ada5e39533f05903beddab984bcd0149/lib/convert_query_type.js#L12-L20 | train |
elidupuis/ember-cli-deploy-archive | index.js | function() {
var distDir = this.readConfig('distDir');
var packedDirName = this.readConfig('packedDirName');
var archivePath = this.readConfig('archivePath');
if (packedDirName) {
packedDirName = path.join(archivePath, packedDirName);
this.log('moving ' + distDir + ' to ' + packedDirName);
this.distDir = packedDirName;
return move(distDir, packedDirName);
}
return RSVP.resolve();
} | javascript | function() {
var distDir = this.readConfig('distDir');
var packedDirName = this.readConfig('packedDirName');
var archivePath = this.readConfig('archivePath');
if (packedDirName) {
packedDirName = path.join(archivePath, packedDirName);
this.log('moving ' + distDir + ' to ' + packedDirName);
this.distDir = packedDirName;
return move(distDir, packedDirName);
}
return RSVP.resolve();
} | [
"function",
"(",
")",
"{",
"var",
"distDir",
"=",
"this",
".",
"readConfig",
"(",
"'distDir'",
")",
";",
"var",
"packedDirName",
"=",
"this",
".",
"readConfig",
"(",
"'packedDirName'",
")",
";",
"var",
"archivePath",
"=",
"this",
".",
"readConfig",
"(",
"'archivePath'",
")",
";",
"if",
"(",
"packedDirName",
")",
"{",
"packedDirName",
"=",
"path",
".",
"join",
"(",
"archivePath",
",",
"packedDirName",
")",
";",
"this",
".",
"log",
"(",
"'moving '",
"+",
"distDir",
"+",
"' to '",
"+",
"packedDirName",
")",
";",
"this",
".",
"distDir",
"=",
"packedDirName",
";",
"return",
"move",
"(",
"distDir",
",",
"packedDirName",
")",
";",
"}",
"return",
"RSVP",
".",
"resolve",
"(",
")",
";",
"}"
] | to allow configurable naming of the directory inside the tarball | [
"to",
"allow",
"configurable",
"naming",
"of",
"the",
"directory",
"inside",
"the",
"tarball"
] | 034e29c527a8df888dee2642b7a318693c463689 | https://github.com/elidupuis/ember-cli-deploy-archive/blob/034e29c527a8df888dee2642b7a318693c463689/index.js#L77-L91 | train |
|
racker/node-swiz | lib/valve.js | checkChain | function checkChain(value, chain, baton, callback) {
var funs = chain.validators.map(function(i) {
return i.func;
});
function _reduce(memo, validator, callback) {
validator(memo, baton, function(err, result) {
var message;
if (err) {
if (err.hasOwnProperty(message)) {
message = err.message;
} else {
message = err;
}
callback(message);
} else {
callback(null, result);
}
});
}
async.reduce(funs, value, _reduce, callback);
} | javascript | function checkChain(value, chain, baton, callback) {
var funs = chain.validators.map(function(i) {
return i.func;
});
function _reduce(memo, validator, callback) {
validator(memo, baton, function(err, result) {
var message;
if (err) {
if (err.hasOwnProperty(message)) {
message = err.message;
} else {
message = err;
}
callback(message);
} else {
callback(null, result);
}
});
}
async.reduce(funs, value, _reduce, callback);
} | [
"function",
"checkChain",
"(",
"value",
",",
"chain",
",",
"baton",
",",
"callback",
")",
"{",
"var",
"funs",
"=",
"chain",
".",
"validators",
".",
"map",
"(",
"function",
"(",
"i",
")",
"{",
"return",
"i",
".",
"func",
";",
"}",
")",
";",
"function",
"_reduce",
"(",
"memo",
",",
"validator",
",",
"callback",
")",
"{",
"validator",
"(",
"memo",
",",
"baton",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"var",
"message",
";",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"hasOwnProperty",
"(",
"message",
")",
")",
"{",
"message",
"=",
"err",
".",
"message",
";",
"}",
"else",
"{",
"message",
"=",
"err",
";",
"}",
"callback",
"(",
"message",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"result",
")",
";",
"}",
"}",
")",
";",
"}",
"async",
".",
"reduce",
"(",
"funs",
",",
"value",
",",
"_reduce",
",",
"callback",
")",
";",
"}"
] | Tests the specified value against the validator chain, converting the
value if applicable.
@private
@param {String|Number|Object} value The value to be tested.
@param {Chain} chain The validator chain against which the value will
be tested.
@param {Function(err, result)} callback The callback that will be invoked
with the "cleaned" (tested/converted) value. | [
"Tests",
"the",
"specified",
"value",
"against",
"the",
"validator",
"chain",
"converting",
"the",
"value",
"if",
"applicable",
"."
] | 602f6cf2fe493e9f1eb7533fdb815c3cc7b56bd5 | https://github.com/racker/node-swiz/blob/602f6cf2fe493e9f1eb7533fdb815c3cc7b56bd5/lib/valve.js#L393-L415 | train |
racker/node-swiz | lib/valve.js | chainHelp | function chainHelp(chain) {
return chain.validators.map(function(e) {
return e.help;
})
.filter(function(e) {
return e;
});
} | javascript | function chainHelp(chain) {
return chain.validators.map(function(e) {
return e.help;
})
.filter(function(e) {
return e;
});
} | [
"function",
"chainHelp",
"(",
"chain",
")",
"{",
"return",
"chain",
".",
"validators",
".",
"map",
"(",
"function",
"(",
"e",
")",
"{",
"return",
"e",
".",
"help",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"e",
")",
"{",
"return",
"e",
";",
"}",
")",
";",
"}"
] | Returns an array of documentation strings for each validator in a chain.
@private
@param {Chain} chain The validator chain.
@return {Array} An array of documentation strings. | [
"Returns",
"an",
"array",
"of",
"documentation",
"strings",
"for",
"each",
"validator",
"in",
"a",
"chain",
"."
] | 602f6cf2fe493e9f1eb7533fdb815c3cc7b56bd5 | https://github.com/racker/node-swiz/blob/602f6cf2fe493e9f1eb7533fdb815c3cc7b56bd5/lib/valve.js#L425-L432 | train |
racker/node-swiz | lib/valve.js | function() {
if (! (this instanceof Chain)) {
return new Chain();
}
this.validators = [];
this.target = null;
this.isOptional = false;
this.isImmutable = false;
this.isUpdateRequired = false;
this._validatorCount = 0;
this._numItemsValidator = null;
} | javascript | function() {
if (! (this instanceof Chain)) {
return new Chain();
}
this.validators = [];
this.target = null;
this.isOptional = false;
this.isImmutable = false;
this.isUpdateRequired = false;
this._validatorCount = 0;
this._numItemsValidator = null;
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Chain",
")",
")",
"{",
"return",
"new",
"Chain",
"(",
")",
";",
"}",
"this",
".",
"validators",
"=",
"[",
"]",
";",
"this",
".",
"target",
"=",
"null",
";",
"this",
".",
"isOptional",
"=",
"false",
";",
"this",
".",
"isImmutable",
"=",
"false",
";",
"this",
".",
"isUpdateRequired",
"=",
"false",
";",
"this",
".",
"_validatorCount",
"=",
"0",
";",
"this",
".",
"_numItemsValidator",
"=",
"null",
";",
"}"
] | A validator chain object. A new instance of this object must be placed at
head of the list of validator functions for each key in a Valve schema.
@constructor
@return {Chain} A validator chain object. | [
"A",
"validator",
"chain",
"object",
".",
"A",
"new",
"instance",
"of",
"this",
"object",
"must",
"be",
"placed",
"at",
"head",
"of",
"the",
"list",
"of",
"validator",
"functions",
"for",
"each",
"key",
"in",
"a",
"Valve",
"schema",
"."
] | 602f6cf2fe493e9f1eb7533fdb815c3cc7b56bd5 | https://github.com/racker/node-swiz/blob/602f6cf2fe493e9f1eb7533fdb815c3cc7b56bd5/lib/valve.js#L481-L493 | train |
|
racker/node-swiz | lib/valve.js | function(schema, /* optional */ baton) {
if (! (this instanceof Valve)) {
return new Valve(schema, baton);
}
this.schema = schema;
this.baton = baton;
} | javascript | function(schema, /* optional */ baton) {
if (! (this instanceof Valve)) {
return new Valve(schema, baton);
}
this.schema = schema;
this.baton = baton;
} | [
"function",
"(",
"schema",
",",
"baton",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Valve",
")",
")",
"{",
"return",
"new",
"Valve",
"(",
"schema",
",",
"baton",
")",
";",
"}",
"this",
".",
"schema",
"=",
"schema",
";",
"this",
".",
"baton",
"=",
"baton",
";",
"}"
] | Creates a new Valve object.
@constructor
@param {Object} schema The schema defining the test/conversion rules. | [
"Creates",
"a",
"new",
"Valve",
"object",
"."
] | 602f6cf2fe493e9f1eb7533fdb815c3cc7b56bd5 | https://github.com/racker/node-swiz/blob/602f6cf2fe493e9f1eb7533fdb815c3cc7b56bd5/lib/valve.js#L2312-L2318 | train |
|
feedhenry/fh-db | lib/mongo_compat_api.js | createDitcherInstance | function createDitcherInstance(mongoUrl, callback) {
// Default config used by ditcher if no connection string
// is provided
var config = {
database: {
host: process.env.MONGODB_HOST || '127.0.0.1',
port: process.env.FH_LOCAL_DB_PORT || 27017,
name: 'FH_LOCAL'
}
};
if (mongoUrl) {
try {
config = utils.parseMongoConnectionURL(mongoUrl);
} catch(e) {
return callback(e);
}
}
var versString = (mongoUrl) ? "db per app" : "shared db";
var ditcher = new fhditcher.Ditcher(config, logger, versString, function () {
return callback(null, ditcher);
});
} | javascript | function createDitcherInstance(mongoUrl, callback) {
// Default config used by ditcher if no connection string
// is provided
var config = {
database: {
host: process.env.MONGODB_HOST || '127.0.0.1',
port: process.env.FH_LOCAL_DB_PORT || 27017,
name: 'FH_LOCAL'
}
};
if (mongoUrl) {
try {
config = utils.parseMongoConnectionURL(mongoUrl);
} catch(e) {
return callback(e);
}
}
var versString = (mongoUrl) ? "db per app" : "shared db";
var ditcher = new fhditcher.Ditcher(config, logger, versString, function () {
return callback(null, ditcher);
});
} | [
"function",
"createDitcherInstance",
"(",
"mongoUrl",
",",
"callback",
")",
"{",
"var",
"config",
"=",
"{",
"database",
":",
"{",
"host",
":",
"process",
".",
"env",
".",
"MONGODB_HOST",
"||",
"'127.0.0.1'",
",",
"port",
":",
"process",
".",
"env",
".",
"FH_LOCAL_DB_PORT",
"||",
"27017",
",",
"name",
":",
"'FH_LOCAL'",
"}",
"}",
";",
"if",
"(",
"mongoUrl",
")",
"{",
"try",
"{",
"config",
"=",
"utils",
".",
"parseMongoConnectionURL",
"(",
"mongoUrl",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"callback",
"(",
"e",
")",
";",
"}",
"}",
"var",
"versString",
"=",
"(",
"mongoUrl",
")",
"?",
"\"db per app\"",
":",
"\"shared db\"",
";",
"var",
"ditcher",
"=",
"new",
"fhditcher",
".",
"Ditcher",
"(",
"config",
",",
"logger",
",",
"versString",
",",
"function",
"(",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"ditcher",
")",
";",
"}",
")",
";",
"}"
] | Create a ditcher instance in case we are working with a shared
database.
@param mongoUrl Mongodb connection string to be used
@param callback result callback | [
"Create",
"a",
"ditcher",
"instance",
"in",
"case",
"we",
"are",
"working",
"with",
"a",
"shared",
"database",
"."
] | 9fd8f6b3ada5e39533f05903beddab984bcd0149 | https://github.com/feedhenry/fh-db/blob/9fd8f6b3ada5e39533f05903beddab984bcd0149/lib/mongo_compat_api.js#L15-L38 | train |
vseryakov/backendjs | modules/bk_shell_aws.js | function(next) {
logger.log("DeregisterImage:", images);
if (shell.isArg("-dry-run", options)) return next();
lib.forEachSeries(images, function(img, next2) {
aws.ec2DeregisterImage(img.imageId, { snapshots: 1 }, next2);
}, next);
} | javascript | function(next) {
logger.log("DeregisterImage:", images);
if (shell.isArg("-dry-run", options)) return next();
lib.forEachSeries(images, function(img, next2) {
aws.ec2DeregisterImage(img.imageId, { snapshots: 1 }, next2);
}, next);
} | [
"function",
"(",
"next",
")",
"{",
"logger",
".",
"log",
"(",
"\"DeregisterImage:\"",
",",
"images",
")",
";",
"if",
"(",
"shell",
".",
"isArg",
"(",
"\"-dry-run\"",
",",
"options",
")",
")",
"return",
"next",
"(",
")",
";",
"lib",
".",
"forEachSeries",
"(",
"images",
",",
"function",
"(",
"img",
",",
"next2",
")",
"{",
"aws",
".",
"ec2DeregisterImage",
"(",
"img",
".",
"imageId",
",",
"{",
"snapshots",
":",
"1",
"}",
",",
"next2",
")",
";",
"}",
",",
"next",
")",
";",
"}"
] | Deregister existing image with the same name in the destination region | [
"Deregister",
"existing",
"image",
"with",
"the",
"same",
"name",
"in",
"the",
"destination",
"region"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/modules/bk_shell_aws.js#L373-L379 | train |
|
andreypopp/connect-browserify | specs/index.js | makeRequest | function makeRequest(capturedError) {
req(app)
.get('/bundle.js')
.expect(500)
.end(function(err, res) {
if (err) {
done(err);
}
assert.ok(capturedError, 'expected error in onerror');
assert.equal(res.text, capturedError.stack);
done();
});
} | javascript | function makeRequest(capturedError) {
req(app)
.get('/bundle.js')
.expect(500)
.end(function(err, res) {
if (err) {
done(err);
}
assert.ok(capturedError, 'expected error in onerror');
assert.equal(res.text, capturedError.stack);
done();
});
} | [
"function",
"makeRequest",
"(",
"capturedError",
")",
"{",
"req",
"(",
"app",
")",
".",
"get",
"(",
"'/bundle.js'",
")",
".",
"expect",
"(",
"500",
")",
".",
"end",
"(",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"{",
"done",
"(",
"err",
")",
";",
"}",
"assert",
".",
"ok",
"(",
"capturedError",
",",
"'expected error in onerror'",
")",
";",
"assert",
".",
"equal",
"(",
"res",
".",
"text",
",",
"capturedError",
".",
"stack",
")",
";",
"done",
"(",
")",
";",
"}",
")",
";",
"}"
] | Let the promise resolve as error before making a request | [
"Let",
"the",
"promise",
"resolve",
"as",
"error",
"before",
"making",
"a",
"request"
] | fd9cfa96bf5385e4746c83afd920ac60545873bd | https://github.com/andreypopp/connect-browserify/blob/fd9cfa96bf5385e4746c83afd920ac60545873bd/specs/index.js#L120-L132 | train |
inversoft/passport-node-client | lib/PassportClient.js | function(userIds) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/user/bulk')
.urlParameter('userId', userIds)
.delete()
.go(this._responseHandler(resolve, reject));
});
} | javascript | function(userIds) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/user/bulk')
.urlParameter('userId', userIds)
.delete()
.go(this._responseHandler(resolve, reject));
});
} | [
"function",
"(",
"userIds",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"this",
".",
"_start",
"(",
")",
".",
"uri",
"(",
"'/api/user/bulk'",
")",
".",
"urlParameter",
"(",
"'userId'",
",",
"userIds",
")",
".",
"delete",
"(",
")",
".",
"go",
"(",
"this",
".",
"_responseHandler",
"(",
"resolve",
",",
"reject",
")",
")",
";",
"}",
")",
";",
"}"
] | Deactivates the users with the given ids.
@param {Array} userIds The ids of the users to deactivate.
@return {Promise} A Promise for the Passport call. | [
"Deactivates",
"the",
"users",
"with",
"the",
"given",
"ids",
"."
] | 35da4a461a6a773850e78bfa307b6e59fe87cfc7 | https://github.com/inversoft/passport-node-client/blob/35da4a461a6a773850e78bfa307b6e59fe87cfc7/lib/PassportClient.js#L397-L405 | train |
|
inversoft/passport-node-client | lib/PassportClient.js | function(userId, applicationId, callerIPAddress) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/login')
.urlSegment(userId)
.urlSegment(applicationId)
.urlParameter('ipAddress', callerIPAddress)
.put()
.go(this._responseHandler(resolve, reject));
});
} | javascript | function(userId, applicationId, callerIPAddress) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/login')
.urlSegment(userId)
.urlSegment(applicationId)
.urlParameter('ipAddress', callerIPAddress)
.put()
.go(this._responseHandler(resolve, reject));
});
} | [
"function",
"(",
"userId",
",",
"applicationId",
",",
"callerIPAddress",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"this",
".",
"_start",
"(",
")",
".",
"uri",
"(",
"'/api/login'",
")",
".",
"urlSegment",
"(",
"userId",
")",
".",
"urlSegment",
"(",
"applicationId",
")",
".",
"urlParameter",
"(",
"'ipAddress'",
",",
"callerIPAddress",
")",
".",
"put",
"(",
")",
".",
"go",
"(",
"this",
".",
"_responseHandler",
"(",
"resolve",
",",
"reject",
")",
")",
";",
"}",
")",
";",
"}"
] | Sends a ping to Passport indicating that the user was automatically logged into an application. When using
Passport's SSO or your own, you should call this if the user is already logged in centrally, but accesses an
application where they no longer have a session. This helps correctly track login counts, times and helps with
reporting.
@param {string} userId The Id of the user that was logged in.
@param {string} applicationId The Id of the application that they logged into.
@param {?string} callerIPAddress (Optional) The IP address of the end-user that is logging in. If a null value is provided
the IP address will be that of the client or last proxy that sent the request.
@return {Promise} A Promise for the Passport call. | [
"Sends",
"a",
"ping",
"to",
"Passport",
"indicating",
"that",
"the",
"user",
"was",
"automatically",
"logged",
"into",
"an",
"application",
".",
"When",
"using",
"Passport",
"s",
"SSO",
"or",
"your",
"own",
"you",
"should",
"call",
"this",
"if",
"the",
"user",
"is",
"already",
"logged",
"in",
"centrally",
"but",
"accesses",
"an",
"application",
"where",
"they",
"no",
"longer",
"have",
"a",
"session",
".",
"This",
"helps",
"correctly",
"track",
"login",
"counts",
"times",
"and",
"helps",
"with",
"reporting",
"."
] | 35da4a461a6a773850e78bfa307b6e59fe87cfc7 | https://github.com/inversoft/passport-node-client/blob/35da4a461a6a773850e78bfa307b6e59fe87cfc7/lib/PassportClient.js#L875-L885 | train |
|
inversoft/passport-node-client | lib/PassportClient.js | function(global, refreshToken) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/logout')
.urlParameter('global', global)
.urlParameter('refreshToken', refreshToken)
.post()
.go(this._responseHandler(resolve, reject));
});
} | javascript | function(global, refreshToken) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/logout')
.urlParameter('global', global)
.urlParameter('refreshToken', refreshToken)
.post()
.go(this._responseHandler(resolve, reject));
});
} | [
"function",
"(",
"global",
",",
"refreshToken",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"this",
".",
"_start",
"(",
")",
".",
"uri",
"(",
"'/api/logout'",
")",
".",
"urlParameter",
"(",
"'global'",
",",
"global",
")",
".",
"urlParameter",
"(",
"'refreshToken'",
",",
"refreshToken",
")",
".",
"post",
"(",
")",
".",
"go",
"(",
"this",
".",
"_responseHandler",
"(",
"resolve",
",",
"reject",
")",
")",
";",
"}",
")",
";",
"}"
] | The Logout API is intended to be used to remove the refresh token and access token cookies if they exist on the
client and revoke the refresh token stored. This API does nothing if the request does not contain an access
token or refresh token cookies.
@param {Object} global When this value is set to true all of the refresh tokens issued to the owner of the
provided token will be revoked.
@param {?string} refreshToken (Optional) The refresh_token as a request parameter instead of coming in via a cookie.
If provided this takes precedence over the cookie.
@return {Promise} A Promise for the Passport call. | [
"The",
"Logout",
"API",
"is",
"intended",
"to",
"be",
"used",
"to",
"remove",
"the",
"refresh",
"token",
"and",
"access",
"token",
"cookies",
"if",
"they",
"exist",
"on",
"the",
"client",
"and",
"revoke",
"the",
"refresh",
"token",
"stored",
".",
"This",
"API",
"does",
"nothing",
"if",
"the",
"request",
"does",
"not",
"contain",
"an",
"access",
"token",
"or",
"refresh",
"token",
"cookies",
"."
] | 35da4a461a6a773850e78bfa307b6e59fe87cfc7 | https://github.com/inversoft/passport-node-client/blob/35da4a461a6a773850e78bfa307b6e59fe87cfc7/lib/PassportClient.js#L898-L907 | train |
|
inversoft/passport-node-client | lib/PassportClient.js | function(applicationId, start, end) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/report/daily-active-user')
.urlParameter('applicationId', applicationId)
.urlParameter('start', start)
.urlParameter('end', end)
.get()
.go(this._responseHandler(resolve, reject));
});
} | javascript | function(applicationId, start, end) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/report/daily-active-user')
.urlParameter('applicationId', applicationId)
.urlParameter('start', start)
.urlParameter('end', end)
.get()
.go(this._responseHandler(resolve, reject));
});
} | [
"function",
"(",
"applicationId",
",",
"start",
",",
"end",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"this",
".",
"_start",
"(",
")",
".",
"uri",
"(",
"'/api/report/daily-active-user'",
")",
".",
"urlParameter",
"(",
"'applicationId'",
",",
"applicationId",
")",
".",
"urlParameter",
"(",
"'start'",
",",
"start",
")",
".",
"urlParameter",
"(",
"'end'",
",",
"end",
")",
".",
"get",
"(",
")",
".",
"go",
"(",
"this",
".",
"_responseHandler",
"(",
"resolve",
",",
"reject",
")",
")",
";",
"}",
")",
";",
"}"
] | Retrieves the daily active user report between the two instants. If you specify an application id, it will only
return the daily active counts for that application.
@param {?string} applicationId (Optional) The application id.
@param {Object} start The start instant as UTC milliseconds since Epoch.
@param {Object} end The end instant as UTC milliseconds since Epoch.
@return {Promise} A Promise for the Passport call. | [
"Retrieves",
"the",
"daily",
"active",
"user",
"report",
"between",
"the",
"two",
"instants",
".",
"If",
"you",
"specify",
"an",
"application",
"id",
"it",
"will",
"only",
"return",
"the",
"daily",
"active",
"counts",
"for",
"that",
"application",
"."
] | 35da4a461a6a773850e78bfa307b6e59fe87cfc7 | https://github.com/inversoft/passport-node-client/blob/35da4a461a6a773850e78bfa307b6e59fe87cfc7/lib/PassportClient.js#L1155-L1165 | train |
|
inversoft/passport-node-client | lib/PassportClient.js | function(userId) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/user')
.urlSegment(userId)
.get()
.go(this._responseHandler(resolve, reject));
});
} | javascript | function(userId) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/user')
.urlSegment(userId)
.get()
.go(this._responseHandler(resolve, reject));
});
} | [
"function",
"(",
"userId",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"this",
".",
"_start",
"(",
")",
".",
"uri",
"(",
"'/api/user'",
")",
".",
"urlSegment",
"(",
"userId",
")",
".",
"get",
"(",
")",
".",
"go",
"(",
"this",
".",
"_responseHandler",
"(",
"resolve",
",",
"reject",
")",
")",
";",
"}",
")",
";",
"}"
] | Retrieves the user for the given Id.
@param {string} userId The Id of the user.
@return {Promise} A Promise for the Passport call. | [
"Retrieves",
"the",
"user",
"for",
"the",
"given",
"Id",
"."
] | 35da4a461a6a773850e78bfa307b6e59fe87cfc7 | https://github.com/inversoft/passport-node-client/blob/35da4a461a6a773850e78bfa307b6e59fe87cfc7/lib/PassportClient.js#L1544-L1552 | train |
|
inversoft/passport-node-client | lib/PassportClient.js | function(userId, offset, limit) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/report/user-login')
.urlParameter('userId', userId)
.urlParameter('offset', offset)
.urlParameter('limit', limit)
.get()
.go(this._responseHandler(resolve, reject));
});
} | javascript | function(userId, offset, limit) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/report/user-login')
.urlParameter('userId', userId)
.urlParameter('offset', offset)
.urlParameter('limit', limit)
.get()
.go(this._responseHandler(resolve, reject));
});
} | [
"function",
"(",
"userId",
",",
"offset",
",",
"limit",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"this",
".",
"_start",
"(",
")",
".",
"uri",
"(",
"'/api/report/user-login'",
")",
".",
"urlParameter",
"(",
"'userId'",
",",
"userId",
")",
".",
"urlParameter",
"(",
"'offset'",
",",
"offset",
")",
".",
"urlParameter",
"(",
"'limit'",
",",
"limit",
")",
".",
"get",
"(",
")",
".",
"go",
"(",
"this",
".",
"_responseHandler",
"(",
"resolve",
",",
"reject",
")",
")",
";",
"}",
")",
";",
"}"
] | Retrieves the last number of login records for a user.
@param {string} userId The Id of the user.
@param {Object} offset The initial record. e.g. 0 is the last login, 100 will be the 100th most recent login.
@param {string} limit (Optional, defaults to 10) The number of records to retrieve.
@return {Promise} A Promise for the Passport call. | [
"Retrieves",
"the",
"last",
"number",
"of",
"login",
"records",
"for",
"a",
"user",
"."
] | 35da4a461a6a773850e78bfa307b6e59fe87cfc7 | https://github.com/inversoft/passport-node-client/blob/35da4a461a6a773850e78bfa307b6e59fe87cfc7/lib/PassportClient.js#L1722-L1732 | train |
|
inversoft/passport-node-client | lib/PassportClient.js | function(token, userId, applicationId) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/jwt/refresh')
.urlParameter('token', token)
.urlParameter('userId', userId)
.urlParameter('applicationId', applicationId)
.delete()
.go(this._responseHandler(resolve, reject));
});
} | javascript | function(token, userId, applicationId) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/jwt/refresh')
.urlParameter('token', token)
.urlParameter('userId', userId)
.urlParameter('applicationId', applicationId)
.delete()
.go(this._responseHandler(resolve, reject));
});
} | [
"function",
"(",
"token",
",",
"userId",
",",
"applicationId",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"this",
".",
"_start",
"(",
")",
".",
"uri",
"(",
"'/api/jwt/refresh'",
")",
".",
"urlParameter",
"(",
"'token'",
",",
"token",
")",
".",
"urlParameter",
"(",
"'userId'",
",",
"userId",
")",
".",
"urlParameter",
"(",
"'applicationId'",
",",
"applicationId",
")",
".",
"delete",
"(",
")",
".",
"go",
"(",
"this",
".",
"_responseHandler",
"(",
"resolve",
",",
"reject",
")",
")",
";",
"}",
")",
";",
"}"
] | Revokes a single refresh token, all tokens for a user or all tokens for an application. If you provide a user id
and an application id, this will delete all the refresh tokens for that user for that application.
@param {?string} token (Optional) The refresh token to delete.
@param {?string} userId (Optional) The user id whose tokens to delete.
@param {?string} applicationId (Optional) The application id of the tokens to delete.
@return {Promise} A Promise for the Passport call. | [
"Revokes",
"a",
"single",
"refresh",
"token",
"all",
"tokens",
"for",
"a",
"user",
"or",
"all",
"tokens",
"for",
"an",
"application",
".",
"If",
"you",
"provide",
"a",
"user",
"id",
"and",
"an",
"application",
"id",
"this",
"will",
"delete",
"all",
"the",
"refresh",
"tokens",
"for",
"that",
"user",
"for",
"that",
"application",
"."
] | 35da4a461a6a773850e78bfa307b6e59fe87cfc7 | https://github.com/inversoft/passport-node-client/blob/35da4a461a6a773850e78bfa307b6e59fe87cfc7/lib/PassportClient.js#L1789-L1799 | train |
|
inversoft/passport-node-client | lib/PassportClient.js | function(request) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/system/audit-log/search')
.setJSONBody(request)
.post()
.go(this._responseHandler(resolve, reject));
});
} | javascript | function(request) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/system/audit-log/search')
.setJSONBody(request)
.post()
.go(this._responseHandler(resolve, reject));
});
} | [
"function",
"(",
"request",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"this",
".",
"_start",
"(",
")",
".",
"uri",
"(",
"'/api/system/audit-log/search'",
")",
".",
"setJSONBody",
"(",
"request",
")",
".",
"post",
"(",
")",
".",
"go",
"(",
"this",
".",
"_responseHandler",
"(",
"resolve",
",",
"reject",
")",
")",
";",
"}",
")",
";",
"}"
] | Searches the audit logs with the specified criteria and pagination.
@param {Object} request The search criteria and pagination information.
@return {Promise} A Promise for the Passport call. | [
"Searches",
"the",
"audit",
"logs",
"with",
"the",
"specified",
"criteria",
"and",
"pagination",
"."
] | 35da4a461a6a773850e78bfa307b6e59fe87cfc7 | https://github.com/inversoft/passport-node-client/blob/35da4a461a6a773850e78bfa307b6e59fe87cfc7/lib/PassportClient.js#L1807-L1815 | train |
|
inversoft/passport-node-client | lib/PassportClient.js | function(verificationId) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/user/verify-email')
.urlSegment(verificationId)
.post()
.go(this._responseHandler(resolve, reject));
});
} | javascript | function(verificationId) {
return new Promise((resolve, reject) => {
this._start()
.uri('/api/user/verify-email')
.urlSegment(verificationId)
.post()
.go(this._responseHandler(resolve, reject));
});
} | [
"function",
"(",
"verificationId",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"this",
".",
"_start",
"(",
")",
".",
"uri",
"(",
"'/api/user/verify-email'",
")",
".",
"urlSegment",
"(",
"verificationId",
")",
".",
"post",
"(",
")",
".",
"go",
"(",
"this",
".",
"_responseHandler",
"(",
"resolve",
",",
"reject",
")",
")",
";",
"}",
")",
";",
"}"
] | Confirms a email verification. The Id given is usually from an email sent to the user.
@param {string} verificationId The email verification id sent to the user.
@return {Promise} A Promise for the Passport call. | [
"Confirms",
"a",
"email",
"verification",
".",
"The",
"Id",
"given",
"is",
"usually",
"from",
"an",
"email",
"sent",
"to",
"the",
"user",
"."
] | 35da4a461a6a773850e78bfa307b6e59fe87cfc7 | https://github.com/inversoft/passport-node-client/blob/35da4a461a6a773850e78bfa307b6e59fe87cfc7/lib/PassportClient.js#L2194-L2202 | train |
|
dgeb/grunt-ember-templates | Gruntfile.js | function(version) {
var command = 'node_modules/.bin/bower uninstall ember && node_modules/.bin/bower install ember#' + version;
grunt.log.writeln('Running bower install', command);
try {
var resultBower = execSync(command);
grunt.log.writeln(resultBower);
} catch (e) {
grunt.fail.warn(e);
}
} | javascript | function(version) {
var command = 'node_modules/.bin/bower uninstall ember && node_modules/.bin/bower install ember#' + version;
grunt.log.writeln('Running bower install', command);
try {
var resultBower = execSync(command);
grunt.log.writeln(resultBower);
} catch (e) {
grunt.fail.warn(e);
}
} | [
"function",
"(",
"version",
")",
"{",
"var",
"command",
"=",
"'node_modules/.bin/bower uninstall ember && node_modules/.bin/bower install ember#'",
"+",
"version",
";",
"grunt",
".",
"log",
".",
"writeln",
"(",
"'Running bower install'",
",",
"command",
")",
";",
"try",
"{",
"var",
"resultBower",
"=",
"execSync",
"(",
"command",
")",
";",
"grunt",
".",
"log",
".",
"writeln",
"(",
"resultBower",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"grunt",
".",
"fail",
".",
"warn",
"(",
"e",
")",
";",
"}",
"}"
] | Install the determined version of Ember package with bower.
@param {String} version | [
"Install",
"the",
"determined",
"version",
"of",
"Ember",
"package",
"with",
"bower",
"."
] | 1141a631317bfa8d5d279e03348dc3364082507c | https://github.com/dgeb/grunt-ember-templates/blob/1141a631317bfa8d5d279e03348dc3364082507c/Gruntfile.js#L257-L268 | train |
|
dgeb/grunt-ember-templates | Gruntfile.js | function(nodeUnitTaskName) {
grunt.registerTask(nodeUnitTaskName, 'Nodeunit sync runner', function() {
try {
var result = execSync('node_modules/.bin/nodeunit --reporter="minimal"', { encoding: 'utf8' });
grunt.log.writeln(result);
} catch (e) {
grunt.fail.warn(e);
}
});
} | javascript | function(nodeUnitTaskName) {
grunt.registerTask(nodeUnitTaskName, 'Nodeunit sync runner', function() {
try {
var result = execSync('node_modules/.bin/nodeunit --reporter="minimal"', { encoding: 'utf8' });
grunt.log.writeln(result);
} catch (e) {
grunt.fail.warn(e);
}
});
} | [
"function",
"(",
"nodeUnitTaskName",
")",
"{",
"grunt",
".",
"registerTask",
"(",
"nodeUnitTaskName",
",",
"'Nodeunit sync runner'",
",",
"function",
"(",
")",
"{",
"try",
"{",
"var",
"result",
"=",
"execSync",
"(",
"'node_modules/.bin/nodeunit --reporter=\"minimal\"'",
",",
"{",
"encoding",
":",
"'utf8'",
"}",
")",
";",
"grunt",
".",
"log",
".",
"writeln",
"(",
"result",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"grunt",
".",
"fail",
".",
"warn",
"(",
"e",
")",
";",
"}",
"}",
")",
";",
"}"
] | Dynamically generates new nodeunit runner, otherwise nodeunit wouldn't reinitialize the changed filesystem.
Bower install new ember version, template compiler generates new files, so nodeunit has to read these new files.
Using always the same nodeunit taskname wouldn't sync the test source, so only the first test iteration would work.
@param {String} nodeUnitTaskName | [
"Dynamically",
"generates",
"new",
"nodeunit",
"runner",
"otherwise",
"nodeunit",
"wouldn",
"t",
"reinitialize",
"the",
"changed",
"filesystem",
".",
"Bower",
"install",
"new",
"ember",
"version",
"template",
"compiler",
"generates",
"new",
"files",
"so",
"nodeunit",
"has",
"to",
"read",
"these",
"new",
"files",
".",
"Using",
"always",
"the",
"same",
"nodeunit",
"taskname",
"wouldn",
"t",
"sync",
"the",
"test",
"source",
"so",
"only",
"the",
"first",
"test",
"iteration",
"would",
"work",
"."
] | 1141a631317bfa8d5d279e03348dc3364082507c | https://github.com/dgeb/grunt-ember-templates/blob/1141a631317bfa8d5d279e03348dc3364082507c/Gruntfile.js#L289-L298 | train |
|
vseryakov/backendjs | lib/core_utils.js | matchObj | function matchObj(obj, line) {
for (const p in obj) if (obj[p] && obj[p].test(line)) return p;
return "";
} | javascript | function matchObj(obj, line) {
for (const p in obj) if (obj[p] && obj[p].test(line)) return p;
return "";
} | [
"function",
"matchObj",
"(",
"obj",
",",
"line",
")",
"{",
"for",
"(",
"const",
"p",
"in",
"obj",
")",
"if",
"(",
"obj",
"[",
"p",
"]",
"&&",
"obj",
"[",
"p",
"]",
".",
"test",
"(",
"line",
")",
")",
"return",
"p",
";",
"return",
"\"\"",
";",
"}"
] | Run over all regexps in the object, return channel name if any matched | [
"Run",
"over",
"all",
"regexps",
"in",
"the",
"object",
"return",
"channel",
"name",
"if",
"any",
"matched"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/core_utils.js#L302-L305 | train |
vseryakov/backendjs | lib/db.js | processRow | function processRow(row) {
if (!row) row = {};
for (var i = 0; i < hooks.length; i++) {
if (hooks[i].call(row, req, row) === true) return false;
}
return true;
} | javascript | function processRow(row) {
if (!row) row = {};
for (var i = 0; i < hooks.length; i++) {
if (hooks[i].call(row, req, row) === true) return false;
}
return true;
} | [
"function",
"processRow",
"(",
"row",
")",
"{",
"if",
"(",
"!",
"row",
")",
"row",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"hooks",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"hooks",
"[",
"i",
"]",
".",
"call",
"(",
"row",
",",
"req",
",",
"row",
")",
"===",
"true",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Stop on the first hook returning true to remove this row from the list | [
"Stop",
"on",
"the",
"first",
"hook",
"returning",
"true",
"to",
"remove",
"this",
"row",
"from",
"the",
"list"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/db.js#L2433-L2439 | train |
vseryakov/backendjs | examples/taxi/app.js | updateTaxis | function updateTaxis()
{
var ids = [ "11", "22", "33" ];
var statuses = [ "avail", "busy", "scheduled" ];
var bbox = bkutils.geoBoundingBox(center[0], center[1], 2); // within 2 km from the center
var latitude = lib.randomNum(bbox[0], bbox[2], 5);
var longitude = lib.randomNum(bbox[1], bbox[3], 5);
var id = ids[lib.randomInt(0, ids.length - 1)];
var status = statuses[lib.randomInt(0, statuses.length - 1)];
db.put("taxi", { id: id, status: status, latitude: latitude, longitude: longitude });
} | javascript | function updateTaxis()
{
var ids = [ "11", "22", "33" ];
var statuses = [ "avail", "busy", "scheduled" ];
var bbox = bkutils.geoBoundingBox(center[0], center[1], 2); // within 2 km from the center
var latitude = lib.randomNum(bbox[0], bbox[2], 5);
var longitude = lib.randomNum(bbox[1], bbox[3], 5);
var id = ids[lib.randomInt(0, ids.length - 1)];
var status = statuses[lib.randomInt(0, statuses.length - 1)];
db.put("taxi", { id: id, status: status, latitude: latitude, longitude: longitude });
} | [
"function",
"updateTaxis",
"(",
")",
"{",
"var",
"ids",
"=",
"[",
"\"11\"",
",",
"\"22\"",
",",
"\"33\"",
"]",
";",
"var",
"statuses",
"=",
"[",
"\"avail\"",
",",
"\"busy\"",
",",
"\"scheduled\"",
"]",
";",
"var",
"bbox",
"=",
"bkutils",
".",
"geoBoundingBox",
"(",
"center",
"[",
"0",
"]",
",",
"center",
"[",
"1",
"]",
",",
"2",
")",
";",
"var",
"latitude",
"=",
"lib",
".",
"randomNum",
"(",
"bbox",
"[",
"0",
"]",
",",
"bbox",
"[",
"2",
"]",
",",
"5",
")",
";",
"var",
"longitude",
"=",
"lib",
".",
"randomNum",
"(",
"bbox",
"[",
"1",
"]",
",",
"bbox",
"[",
"3",
"]",
",",
"5",
")",
";",
"var",
"id",
"=",
"ids",
"[",
"lib",
".",
"randomInt",
"(",
"0",
",",
"ids",
".",
"length",
"-",
"1",
")",
"]",
";",
"var",
"status",
"=",
"statuses",
"[",
"lib",
".",
"randomInt",
"(",
"0",
",",
"statuses",
".",
"length",
"-",
"1",
")",
"]",
";",
"db",
".",
"put",
"(",
"\"taxi\"",
",",
"{",
"id",
":",
"id",
",",
"status",
":",
"status",
",",
"latitude",
":",
"latitude",
",",
"longitude",
":",
"longitude",
"}",
")",
";",
"}"
] | Simulate taxi location changes | [
"Simulate",
"taxi",
"location",
"changes"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/examples/taxi/app.js#L54-L65 | train |
godmodelabs/flora | lib/request-resolver.js | mergeSubResource | function mergeSubResource(attrNode, subResourceConfig, context) {
// Merge options from sub-resource to parent (order is irrelevant here):
Object.keys(subResourceConfig).forEach(optionName => {
if (optionName === 'attributes') {
if (!attrNode.attributes) attrNode.attributes = {};
} else if (optionName === 'dataSources') {
const newDataSources = Object.assign({}, subResourceConfig.dataSources);
if (attrNode.dataSources) {
Object.keys(attrNode.dataSources).forEach(dataSourceName => {
if (newDataSources[dataSourceName]) {
if (attrNode.dataSources[dataSourceName].inherit) {
if (attrNode.dataSources[dataSourceName].inherit === 'inherit') {
newDataSources[dataSourceName] = Object.assign(
{},
newDataSources[dataSourceName],
attrNode.dataSources[dataSourceName]
);
} else if (attrNode.dataSources[dataSourceName].inherit === 'replace') {
newDataSources[dataSourceName] = attrNode.dataSources[dataSourceName];
}
} else {
throw new ImplementationError(
`Cannot overwrite DataSource "${dataSourceName}"` +
` in "${context.attrPath.join('.')}" (maybe use "inherit"?)`
);
}
} else {
newDataSources[dataSourceName] = attrNode.dataSources[dataSourceName];
}
});
}
attrNode.dataSources = newDataSources;
} else if (typeof subResourceConfig[optionName] === 'object') {
attrNode[optionName] = cloneDeep(subResourceConfig[optionName]);
} else if (!(optionName in attrNode)) {
attrNode[optionName] = subResourceConfig[optionName];
}
});
attrNode._origNodes = attrNode._origNodes || [];
attrNode._origNodes.push(subResourceConfig);
} | javascript | function mergeSubResource(attrNode, subResourceConfig, context) {
// Merge options from sub-resource to parent (order is irrelevant here):
Object.keys(subResourceConfig).forEach(optionName => {
if (optionName === 'attributes') {
if (!attrNode.attributes) attrNode.attributes = {};
} else if (optionName === 'dataSources') {
const newDataSources = Object.assign({}, subResourceConfig.dataSources);
if (attrNode.dataSources) {
Object.keys(attrNode.dataSources).forEach(dataSourceName => {
if (newDataSources[dataSourceName]) {
if (attrNode.dataSources[dataSourceName].inherit) {
if (attrNode.dataSources[dataSourceName].inherit === 'inherit') {
newDataSources[dataSourceName] = Object.assign(
{},
newDataSources[dataSourceName],
attrNode.dataSources[dataSourceName]
);
} else if (attrNode.dataSources[dataSourceName].inherit === 'replace') {
newDataSources[dataSourceName] = attrNode.dataSources[dataSourceName];
}
} else {
throw new ImplementationError(
`Cannot overwrite DataSource "${dataSourceName}"` +
` in "${context.attrPath.join('.')}" (maybe use "inherit"?)`
);
}
} else {
newDataSources[dataSourceName] = attrNode.dataSources[dataSourceName];
}
});
}
attrNode.dataSources = newDataSources;
} else if (typeof subResourceConfig[optionName] === 'object') {
attrNode[optionName] = cloneDeep(subResourceConfig[optionName]);
} else if (!(optionName in attrNode)) {
attrNode[optionName] = subResourceConfig[optionName];
}
});
attrNode._origNodes = attrNode._origNodes || [];
attrNode._origNodes.push(subResourceConfig);
} | [
"function",
"mergeSubResource",
"(",
"attrNode",
",",
"subResourceConfig",
",",
"context",
")",
"{",
"Object",
".",
"keys",
"(",
"subResourceConfig",
")",
".",
"forEach",
"(",
"optionName",
"=>",
"{",
"if",
"(",
"optionName",
"===",
"'attributes'",
")",
"{",
"if",
"(",
"!",
"attrNode",
".",
"attributes",
")",
"attrNode",
".",
"attributes",
"=",
"{",
"}",
";",
"}",
"else",
"if",
"(",
"optionName",
"===",
"'dataSources'",
")",
"{",
"const",
"newDataSources",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"subResourceConfig",
".",
"dataSources",
")",
";",
"if",
"(",
"attrNode",
".",
"dataSources",
")",
"{",
"Object",
".",
"keys",
"(",
"attrNode",
".",
"dataSources",
")",
".",
"forEach",
"(",
"dataSourceName",
"=>",
"{",
"if",
"(",
"newDataSources",
"[",
"dataSourceName",
"]",
")",
"{",
"if",
"(",
"attrNode",
".",
"dataSources",
"[",
"dataSourceName",
"]",
".",
"inherit",
")",
"{",
"if",
"(",
"attrNode",
".",
"dataSources",
"[",
"dataSourceName",
"]",
".",
"inherit",
"===",
"'inherit'",
")",
"{",
"newDataSources",
"[",
"dataSourceName",
"]",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"newDataSources",
"[",
"dataSourceName",
"]",
",",
"attrNode",
".",
"dataSources",
"[",
"dataSourceName",
"]",
")",
";",
"}",
"else",
"if",
"(",
"attrNode",
".",
"dataSources",
"[",
"dataSourceName",
"]",
".",
"inherit",
"===",
"'replace'",
")",
"{",
"newDataSources",
"[",
"dataSourceName",
"]",
"=",
"attrNode",
".",
"dataSources",
"[",
"dataSourceName",
"]",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"dataSourceName",
"}",
"`",
"+",
"`",
"${",
"context",
".",
"attrPath",
".",
"join",
"(",
"'.'",
")",
"}",
"`",
")",
";",
"}",
"}",
"else",
"{",
"newDataSources",
"[",
"dataSourceName",
"]",
"=",
"attrNode",
".",
"dataSources",
"[",
"dataSourceName",
"]",
";",
"}",
"}",
")",
";",
"}",
"attrNode",
".",
"dataSources",
"=",
"newDataSources",
";",
"}",
"else",
"if",
"(",
"typeof",
"subResourceConfig",
"[",
"optionName",
"]",
"===",
"'object'",
")",
"{",
"attrNode",
"[",
"optionName",
"]",
"=",
"cloneDeep",
"(",
"subResourceConfig",
"[",
"optionName",
"]",
")",
";",
"}",
"else",
"if",
"(",
"!",
"(",
"optionName",
"in",
"attrNode",
")",
")",
"{",
"attrNode",
"[",
"optionName",
"]",
"=",
"subResourceConfig",
"[",
"optionName",
"]",
";",
"}",
"}",
")",
";",
"attrNode",
".",
"_origNodes",
"=",
"attrNode",
".",
"_origNodes",
"||",
"[",
"]",
";",
"attrNode",
".",
"_origNodes",
".",
"push",
"(",
"subResourceConfig",
")",
";",
"}"
] | Merges additional options, attributes and DataSources from parent-resource
into sub-resource.
@param attrNode - Destination node
@param subResourceConfig - Sub-resource-config (not cloned!)
@private | [
"Merges",
"additional",
"options",
"attributes",
"and",
"DataSources",
"from",
"parent",
"-",
"resource",
"into",
"sub",
"-",
"resource",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/request-resolver.js#L26-L69 | train |
godmodelabs/flora | lib/request-resolver.js | getAttribute | function getAttribute(path, attrNode, context) {
path.forEach((attributeName, i) => {
if (!(attrNode.attributes && attrNode.attributes[attributeName])) {
if (attrNode._origNodes) {
let subAttrNode = null;
attrNode._origNodes.forEach((origNode, inheritDepth) => {
if (!origNode || !origNode.attributes || !origNode.attributes[attributeName]) return;
let origSubAttrNode = origNode.attributes[attributeName];
if (subAttrNode) {
if (subAttrNode.inherit === 'inherit') {
// just add/merge options from sub-resource below
} else if (subAttrNode.inherit === 'replace') {
return; // just ignore options from sub-resource
} else {
let attrPath = context.attrPath.join('.');
throw new ImplementationError(
`Cannot overwrite attribute "${attributeName}" in "${attrPath}" (maybe use "inherit"?)`
);
}
} else {
subAttrNode = {};
}
Object.keys(origSubAttrNode).forEach(optionName => {
if (subAttrNode.hasOwnProperty(optionName)) return; // for inherit
if (optionName === 'attributes') {
subAttrNode[optionName] = {};
} else if (optionName === 'dataSources') {
// DataSources are handled/cloned later in resolveResourceTree():
subAttrNode[optionName] = origSubAttrNode[optionName];
} else if (typeof origSubAttrNode[optionName] === 'object') {
subAttrNode[optionName] = cloneDeep(origSubAttrNode[optionName]);
} else {
subAttrNode[optionName] = origSubAttrNode[optionName];
}
});
// keep the inherit-depth (array length) from parent:
subAttrNode._origNodes = subAttrNode._origNodes || Array(attrNode._origNodes.length);
subAttrNode._origNodes[inheritDepth] = origSubAttrNode;
attrNode.attributes[attributeName] = subAttrNode;
});
}
if (!(attrNode.attributes && attrNode.attributes[attributeName])) {
throw new RequestError(
'Unknown attribute ' + `"${context.attrPath.concat(path.slice(0, i + 1)).join('.')}"`
);
}
}
attrNode = attrNode.attributes[attributeName];
if (attrNode.resource) {
const subContext = Object.assign({}, context);
subContext.attrPath = subContext.attrPath.concat(path.slice(0, i + 1));
resolveIncludes(attrNode, subContext);
}
});
return attrNode;
} | javascript | function getAttribute(path, attrNode, context) {
path.forEach((attributeName, i) => {
if (!(attrNode.attributes && attrNode.attributes[attributeName])) {
if (attrNode._origNodes) {
let subAttrNode = null;
attrNode._origNodes.forEach((origNode, inheritDepth) => {
if (!origNode || !origNode.attributes || !origNode.attributes[attributeName]) return;
let origSubAttrNode = origNode.attributes[attributeName];
if (subAttrNode) {
if (subAttrNode.inherit === 'inherit') {
// just add/merge options from sub-resource below
} else if (subAttrNode.inherit === 'replace') {
return; // just ignore options from sub-resource
} else {
let attrPath = context.attrPath.join('.');
throw new ImplementationError(
`Cannot overwrite attribute "${attributeName}" in "${attrPath}" (maybe use "inherit"?)`
);
}
} else {
subAttrNode = {};
}
Object.keys(origSubAttrNode).forEach(optionName => {
if (subAttrNode.hasOwnProperty(optionName)) return; // for inherit
if (optionName === 'attributes') {
subAttrNode[optionName] = {};
} else if (optionName === 'dataSources') {
// DataSources are handled/cloned later in resolveResourceTree():
subAttrNode[optionName] = origSubAttrNode[optionName];
} else if (typeof origSubAttrNode[optionName] === 'object') {
subAttrNode[optionName] = cloneDeep(origSubAttrNode[optionName]);
} else {
subAttrNode[optionName] = origSubAttrNode[optionName];
}
});
// keep the inherit-depth (array length) from parent:
subAttrNode._origNodes = subAttrNode._origNodes || Array(attrNode._origNodes.length);
subAttrNode._origNodes[inheritDepth] = origSubAttrNode;
attrNode.attributes[attributeName] = subAttrNode;
});
}
if (!(attrNode.attributes && attrNode.attributes[attributeName])) {
throw new RequestError(
'Unknown attribute ' + `"${context.attrPath.concat(path.slice(0, i + 1)).join('.')}"`
);
}
}
attrNode = attrNode.attributes[attributeName];
if (attrNode.resource) {
const subContext = Object.assign({}, context);
subContext.attrPath = subContext.attrPath.concat(path.slice(0, i + 1));
resolveIncludes(attrNode, subContext);
}
});
return attrNode;
} | [
"function",
"getAttribute",
"(",
"path",
",",
"attrNode",
",",
"context",
")",
"{",
"path",
".",
"forEach",
"(",
"(",
"attributeName",
",",
"i",
")",
"=>",
"{",
"if",
"(",
"!",
"(",
"attrNode",
".",
"attributes",
"&&",
"attrNode",
".",
"attributes",
"[",
"attributeName",
"]",
")",
")",
"{",
"if",
"(",
"attrNode",
".",
"_origNodes",
")",
"{",
"let",
"subAttrNode",
"=",
"null",
";",
"attrNode",
".",
"_origNodes",
".",
"forEach",
"(",
"(",
"origNode",
",",
"inheritDepth",
")",
"=>",
"{",
"if",
"(",
"!",
"origNode",
"||",
"!",
"origNode",
".",
"attributes",
"||",
"!",
"origNode",
".",
"attributes",
"[",
"attributeName",
"]",
")",
"return",
";",
"let",
"origSubAttrNode",
"=",
"origNode",
".",
"attributes",
"[",
"attributeName",
"]",
";",
"if",
"(",
"subAttrNode",
")",
"{",
"if",
"(",
"subAttrNode",
".",
"inherit",
"===",
"'inherit'",
")",
"{",
"}",
"else",
"if",
"(",
"subAttrNode",
".",
"inherit",
"===",
"'replace'",
")",
"{",
"return",
";",
"}",
"else",
"{",
"let",
"attrPath",
"=",
"context",
".",
"attrPath",
".",
"join",
"(",
"'.'",
")",
";",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"attributeName",
"}",
"${",
"attrPath",
"}",
"`",
")",
";",
"}",
"}",
"else",
"{",
"subAttrNode",
"=",
"{",
"}",
";",
"}",
"Object",
".",
"keys",
"(",
"origSubAttrNode",
")",
".",
"forEach",
"(",
"optionName",
"=>",
"{",
"if",
"(",
"subAttrNode",
".",
"hasOwnProperty",
"(",
"optionName",
")",
")",
"return",
";",
"if",
"(",
"optionName",
"===",
"'attributes'",
")",
"{",
"subAttrNode",
"[",
"optionName",
"]",
"=",
"{",
"}",
";",
"}",
"else",
"if",
"(",
"optionName",
"===",
"'dataSources'",
")",
"{",
"subAttrNode",
"[",
"optionName",
"]",
"=",
"origSubAttrNode",
"[",
"optionName",
"]",
";",
"}",
"else",
"if",
"(",
"typeof",
"origSubAttrNode",
"[",
"optionName",
"]",
"===",
"'object'",
")",
"{",
"subAttrNode",
"[",
"optionName",
"]",
"=",
"cloneDeep",
"(",
"origSubAttrNode",
"[",
"optionName",
"]",
")",
";",
"}",
"else",
"{",
"subAttrNode",
"[",
"optionName",
"]",
"=",
"origSubAttrNode",
"[",
"optionName",
"]",
";",
"}",
"}",
")",
";",
"subAttrNode",
".",
"_origNodes",
"=",
"subAttrNode",
".",
"_origNodes",
"||",
"Array",
"(",
"attrNode",
".",
"_origNodes",
".",
"length",
")",
";",
"subAttrNode",
".",
"_origNodes",
"[",
"inheritDepth",
"]",
"=",
"origSubAttrNode",
";",
"attrNode",
".",
"attributes",
"[",
"attributeName",
"]",
"=",
"subAttrNode",
";",
"}",
")",
";",
"}",
"if",
"(",
"!",
"(",
"attrNode",
".",
"attributes",
"&&",
"attrNode",
".",
"attributes",
"[",
"attributeName",
"]",
")",
")",
"{",
"throw",
"new",
"RequestError",
"(",
"'Unknown attribute '",
"+",
"`",
"${",
"context",
".",
"attrPath",
".",
"concat",
"(",
"path",
".",
"slice",
"(",
"0",
",",
"i",
"+",
"1",
")",
")",
".",
"join",
"(",
"'.'",
")",
"}",
"`",
")",
";",
"}",
"}",
"attrNode",
"=",
"attrNode",
".",
"attributes",
"[",
"attributeName",
"]",
";",
"if",
"(",
"attrNode",
".",
"resource",
")",
"{",
"const",
"subContext",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"context",
")",
";",
"subContext",
".",
"attrPath",
"=",
"subContext",
".",
"attrPath",
".",
"concat",
"(",
"path",
".",
"slice",
"(",
"0",
",",
"i",
"+",
"1",
")",
")",
";",
"resolveIncludes",
"(",
"attrNode",
",",
"subContext",
")",
";",
"}",
"}",
")",
";",
"return",
"attrNode",
";",
"}"
] | Resolve attribute path relative to attrNode, handle included resources
and return child attrNode
@param path - Array of attribute-names representing the path
@param attrNode - Root node where to start resolving
@param context - "Global" things and context for better error-handling
@private | [
"Resolve",
"attribute",
"path",
"relative",
"to",
"attrNode",
"handle",
"included",
"resources",
"and",
"return",
"child",
"attrNode"
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/request-resolver.js#L124-L189 | train |
godmodelabs/flora | lib/request-resolver.js | resolveDataSourceAttributes | function resolveDataSourceAttributes(resourceTree, dataSources, primaryName) {
Object.keys(dataSources).forEach(dataSourceName => {
const dataSource = dataSources[dataSourceName];
dataSource.attributes = [];
dataSource.attributeOptions = {};
});
resourceTree.attributes.forEach(function resolveAttribute(attrInfo) {
let selectedDataSources;
if (attrInfo.fromDataSource === '#same-group') {
return attrInfo.attributes.forEach(resolveAttribute); // handle key-groups as flat
}
if (attrInfo.fromDataSource === '#all-selected') {
attrInfo.attrNode.selectedDataSource = primaryName;
selectedDataSources = [];
Object.keys(dataSources).forEach(dataSourceName => {
if (dataSources[dataSourceName].joinParentKey) return;
selectedDataSources.push(dataSourceName);
});
} else if (attrInfo.fromDataSource === '#current-primary') {
attrInfo.attrNode.selectedDataSource = primaryName;
selectedDataSources = [attrInfo.attrNode.selectedDataSource];
} else if (attrInfo.fromDataSource) {
attrInfo.attrNode.selectedDataSource = attrInfo.fromDataSource;
selectedDataSources = [attrInfo.attrNode.selectedDataSource];
} else {
attrInfo.attrNode.selectedDataSource = Object.keys(attrInfo.dataSourceMap).find(
dataSourceName => dataSources[dataSourceName]
);
if (!attrInfo.attrNode.selectedDataSource) {
throw new ImplementationError(
'No proper DataSource selected for attribute ' +
'(this should not happen - bug in request-resolver in Flora core)'
);
}
selectedDataSources = [attrInfo.attrNode.selectedDataSource];
}
selectedDataSources.forEach(selectedDataSourceName => {
const attribute = attrInfo.dataSourceMap[selectedDataSourceName];
dataSources[selectedDataSourceName].attributes.push(attribute);
dataSources[selectedDataSourceName].attributeOptions[attribute] = _.pick(attrInfo.attrNode, [
'type',
'storedType',
'multiValued',
'delimiter'
]);
});
return null;
});
Object.keys(dataSources).forEach(dataSourceName => {
dataSources[dataSourceName].attributes = _.uniq(dataSources[dataSourceName].attributes);
});
} | javascript | function resolveDataSourceAttributes(resourceTree, dataSources, primaryName) {
Object.keys(dataSources).forEach(dataSourceName => {
const dataSource = dataSources[dataSourceName];
dataSource.attributes = [];
dataSource.attributeOptions = {};
});
resourceTree.attributes.forEach(function resolveAttribute(attrInfo) {
let selectedDataSources;
if (attrInfo.fromDataSource === '#same-group') {
return attrInfo.attributes.forEach(resolveAttribute); // handle key-groups as flat
}
if (attrInfo.fromDataSource === '#all-selected') {
attrInfo.attrNode.selectedDataSource = primaryName;
selectedDataSources = [];
Object.keys(dataSources).forEach(dataSourceName => {
if (dataSources[dataSourceName].joinParentKey) return;
selectedDataSources.push(dataSourceName);
});
} else if (attrInfo.fromDataSource === '#current-primary') {
attrInfo.attrNode.selectedDataSource = primaryName;
selectedDataSources = [attrInfo.attrNode.selectedDataSource];
} else if (attrInfo.fromDataSource) {
attrInfo.attrNode.selectedDataSource = attrInfo.fromDataSource;
selectedDataSources = [attrInfo.attrNode.selectedDataSource];
} else {
attrInfo.attrNode.selectedDataSource = Object.keys(attrInfo.dataSourceMap).find(
dataSourceName => dataSources[dataSourceName]
);
if (!attrInfo.attrNode.selectedDataSource) {
throw new ImplementationError(
'No proper DataSource selected for attribute ' +
'(this should not happen - bug in request-resolver in Flora core)'
);
}
selectedDataSources = [attrInfo.attrNode.selectedDataSource];
}
selectedDataSources.forEach(selectedDataSourceName => {
const attribute = attrInfo.dataSourceMap[selectedDataSourceName];
dataSources[selectedDataSourceName].attributes.push(attribute);
dataSources[selectedDataSourceName].attributeOptions[attribute] = _.pick(attrInfo.attrNode, [
'type',
'storedType',
'multiValued',
'delimiter'
]);
});
return null;
});
Object.keys(dataSources).forEach(dataSourceName => {
dataSources[dataSourceName].attributes = _.uniq(dataSources[dataSourceName].attributes);
});
} | [
"function",
"resolveDataSourceAttributes",
"(",
"resourceTree",
",",
"dataSources",
",",
"primaryName",
")",
"{",
"Object",
".",
"keys",
"(",
"dataSources",
")",
".",
"forEach",
"(",
"dataSourceName",
"=>",
"{",
"const",
"dataSource",
"=",
"dataSources",
"[",
"dataSourceName",
"]",
";",
"dataSource",
".",
"attributes",
"=",
"[",
"]",
";",
"dataSource",
".",
"attributeOptions",
"=",
"{",
"}",
";",
"}",
")",
";",
"resourceTree",
".",
"attributes",
".",
"forEach",
"(",
"function",
"resolveAttribute",
"(",
"attrInfo",
")",
"{",
"let",
"selectedDataSources",
";",
"if",
"(",
"attrInfo",
".",
"fromDataSource",
"===",
"'#same-group'",
")",
"{",
"return",
"attrInfo",
".",
"attributes",
".",
"forEach",
"(",
"resolveAttribute",
")",
";",
"}",
"if",
"(",
"attrInfo",
".",
"fromDataSource",
"===",
"'#all-selected'",
")",
"{",
"attrInfo",
".",
"attrNode",
".",
"selectedDataSource",
"=",
"primaryName",
";",
"selectedDataSources",
"=",
"[",
"]",
";",
"Object",
".",
"keys",
"(",
"dataSources",
")",
".",
"forEach",
"(",
"dataSourceName",
"=>",
"{",
"if",
"(",
"dataSources",
"[",
"dataSourceName",
"]",
".",
"joinParentKey",
")",
"return",
";",
"selectedDataSources",
".",
"push",
"(",
"dataSourceName",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"attrInfo",
".",
"fromDataSource",
"===",
"'#current-primary'",
")",
"{",
"attrInfo",
".",
"attrNode",
".",
"selectedDataSource",
"=",
"primaryName",
";",
"selectedDataSources",
"=",
"[",
"attrInfo",
".",
"attrNode",
".",
"selectedDataSource",
"]",
";",
"}",
"else",
"if",
"(",
"attrInfo",
".",
"fromDataSource",
")",
"{",
"attrInfo",
".",
"attrNode",
".",
"selectedDataSource",
"=",
"attrInfo",
".",
"fromDataSource",
";",
"selectedDataSources",
"=",
"[",
"attrInfo",
".",
"attrNode",
".",
"selectedDataSource",
"]",
";",
"}",
"else",
"{",
"attrInfo",
".",
"attrNode",
".",
"selectedDataSource",
"=",
"Object",
".",
"keys",
"(",
"attrInfo",
".",
"dataSourceMap",
")",
".",
"find",
"(",
"dataSourceName",
"=>",
"dataSources",
"[",
"dataSourceName",
"]",
")",
";",
"if",
"(",
"!",
"attrInfo",
".",
"attrNode",
".",
"selectedDataSource",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"'No proper DataSource selected for attribute '",
"+",
"'(this should not happen - bug in request-resolver in Flora core)'",
")",
";",
"}",
"selectedDataSources",
"=",
"[",
"attrInfo",
".",
"attrNode",
".",
"selectedDataSource",
"]",
";",
"}",
"selectedDataSources",
".",
"forEach",
"(",
"selectedDataSourceName",
"=>",
"{",
"const",
"attribute",
"=",
"attrInfo",
".",
"dataSourceMap",
"[",
"selectedDataSourceName",
"]",
";",
"dataSources",
"[",
"selectedDataSourceName",
"]",
".",
"attributes",
".",
"push",
"(",
"attribute",
")",
";",
"dataSources",
"[",
"selectedDataSourceName",
"]",
".",
"attributeOptions",
"[",
"attribute",
"]",
"=",
"_",
".",
"pick",
"(",
"attrInfo",
".",
"attrNode",
",",
"[",
"'type'",
",",
"'storedType'",
",",
"'multiValued'",
",",
"'delimiter'",
"]",
")",
";",
"}",
")",
";",
"return",
"null",
";",
"}",
")",
";",
"Object",
".",
"keys",
"(",
"dataSources",
")",
".",
"forEach",
"(",
"dataSourceName",
"=>",
"{",
"dataSources",
"[",
"dataSourceName",
"]",
".",
"attributes",
"=",
"_",
".",
"uniq",
"(",
"dataSources",
"[",
"dataSourceName",
"]",
".",
"attributes",
")",
";",
"}",
")",
";",
"}"
] | Distribute attributes over DataSources.
@private | [
"Distribute",
"attributes",
"over",
"DataSources",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/request-resolver.js#L818-L876 | train |
gemini-testing/ssh-tun | index.js | function () {
var _this = this;
console.info('INFO: creating tunnel to %s', this.proxyHost);
this._tunnel = childProcess.spawn('ssh', this._buildSSHArgs());
var cleanup = function () {
_this._tunnel.stderr.removeAllListeners('data');
};
this._tunnel.stderr.on('data', function (data) {
if (/success/.test(data)) {
cleanup();
return _this._resolveTunnel();
}
if (/failed/.test(data)) {
cleanup();
return _this._rejectTunnel();
}
});
this._tunnel.on('exit', function (code, signal) {
_this.emit('exit', code, signal);
});
this._tunnel.on('close', function (code, signal) {
_this.emit('close', code, signal);
return _this._closeTunnel(code);
});
this._tunnel.on('error', function () {
return _this._rejectTunnel();
});
return _this._tunnelDeferred.promise.timeout(this._connectTimeout);
} | javascript | function () {
var _this = this;
console.info('INFO: creating tunnel to %s', this.proxyHost);
this._tunnel = childProcess.spawn('ssh', this._buildSSHArgs());
var cleanup = function () {
_this._tunnel.stderr.removeAllListeners('data');
};
this._tunnel.stderr.on('data', function (data) {
if (/success/.test(data)) {
cleanup();
return _this._resolveTunnel();
}
if (/failed/.test(data)) {
cleanup();
return _this._rejectTunnel();
}
});
this._tunnel.on('exit', function (code, signal) {
_this.emit('exit', code, signal);
});
this._tunnel.on('close', function (code, signal) {
_this.emit('close', code, signal);
return _this._closeTunnel(code);
});
this._tunnel.on('error', function () {
return _this._rejectTunnel();
});
return _this._tunnelDeferred.promise.timeout(this._connectTimeout);
} | [
"function",
"(",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"console",
".",
"info",
"(",
"'INFO: creating tunnel to %s'",
",",
"this",
".",
"proxyHost",
")",
";",
"this",
".",
"_tunnel",
"=",
"childProcess",
".",
"spawn",
"(",
"'ssh'",
",",
"this",
".",
"_buildSSHArgs",
"(",
")",
")",
";",
"var",
"cleanup",
"=",
"function",
"(",
")",
"{",
"_this",
".",
"_tunnel",
".",
"stderr",
".",
"removeAllListeners",
"(",
"'data'",
")",
";",
"}",
";",
"this",
".",
"_tunnel",
".",
"stderr",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"if",
"(",
"/",
"success",
"/",
".",
"test",
"(",
"data",
")",
")",
"{",
"cleanup",
"(",
")",
";",
"return",
"_this",
".",
"_resolveTunnel",
"(",
")",
";",
"}",
"if",
"(",
"/",
"failed",
"/",
".",
"test",
"(",
"data",
")",
")",
"{",
"cleanup",
"(",
")",
";",
"return",
"_this",
".",
"_rejectTunnel",
"(",
")",
";",
"}",
"}",
")",
";",
"this",
".",
"_tunnel",
".",
"on",
"(",
"'exit'",
",",
"function",
"(",
"code",
",",
"signal",
")",
"{",
"_this",
".",
"emit",
"(",
"'exit'",
",",
"code",
",",
"signal",
")",
";",
"}",
")",
";",
"this",
".",
"_tunnel",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
"code",
",",
"signal",
")",
"{",
"_this",
".",
"emit",
"(",
"'close'",
",",
"code",
",",
"signal",
")",
";",
"return",
"_this",
".",
"_closeTunnel",
"(",
"code",
")",
";",
"}",
")",
";",
"this",
".",
"_tunnel",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
")",
"{",
"return",
"_this",
".",
"_rejectTunnel",
"(",
")",
";",
"}",
")",
";",
"return",
"_this",
".",
"_tunnelDeferred",
".",
"promise",
".",
"timeout",
"(",
"this",
".",
"_connectTimeout",
")",
";",
"}"
] | Tries to open ssh connection to remote server
@returns {Promise} | [
"Tries",
"to",
"open",
"ssh",
"connection",
"to",
"remote",
"server"
] | 60106cad0dfdbde77a16cd4f249b18da4ec82777 | https://github.com/gemini-testing/ssh-tun/blob/60106cad0dfdbde77a16cd4f249b18da4ec82777/index.js#L47-L84 | train |
|
gemini-testing/ssh-tun | index.js | function () {
if (!this._tunnel) {
return q();
}
var _this = this;
this._tunnel.kill('SIGTERM');
return this._closeDeferred.promise.timeout(3000).fail(function () {
_this._tunnel.kill('SIGKILL');
return _this._closeTunnel(-1);
});
} | javascript | function () {
if (!this._tunnel) {
return q();
}
var _this = this;
this._tunnel.kill('SIGTERM');
return this._closeDeferred.promise.timeout(3000).fail(function () {
_this._tunnel.kill('SIGKILL');
return _this._closeTunnel(-1);
});
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_tunnel",
")",
"{",
"return",
"q",
"(",
")",
";",
"}",
"var",
"_this",
"=",
"this",
";",
"this",
".",
"_tunnel",
".",
"kill",
"(",
"'SIGTERM'",
")",
";",
"return",
"this",
".",
"_closeDeferred",
".",
"promise",
".",
"timeout",
"(",
"3000",
")",
".",
"fail",
"(",
"function",
"(",
")",
"{",
"_this",
".",
"_tunnel",
".",
"kill",
"(",
"'SIGKILL'",
")",
";",
"return",
"_this",
".",
"_closeTunnel",
"(",
"-",
"1",
")",
";",
"}",
")",
";",
"}"
] | Closes connection. If no connection established does nothing
@returns {Promise} | [
"Closes",
"connection",
".",
"If",
"no",
"connection",
"established",
"does",
"nothing"
] | 60106cad0dfdbde77a16cd4f249b18da4ec82777 | https://github.com/gemini-testing/ssh-tun/blob/60106cad0dfdbde77a16cd4f249b18da4ec82777/index.js#L90-L102 | train |
|
vseryakov/backendjs | lib/core.js | function(next) {
core.allowPackages.forEach(function(pkg) {
try {
var mod = path.dirname(require.resolve(pkg)).replace(/\/lib$/, "");
core.packages[pkg] = { path: mod };
if (lib.statSync(mod + "/etc").isDirectory()) {
core.packages[pkg].etc = 1;
var cfg = lib.readFileSync(mod + "/etc/config");
if (cfg) {
config = cfg + "\n" + config;
core.packages[pkg].config = 1;
core.parseConfig(cfg, 1);
}
}
["modules","locales","views","web"].forEach(function(x) {
if (lib.statSync(mod + "/" + x).isDirectory()) {
core.path[x].unshift(mod + "/" + x);
core.packages[pkg][x] = 1;
}
});
logger.debug("init:", "npm package:", pkg, core.packages[pkg]);
} catch(e) {
logger.error("init:", "npm package:", pkg, e);
}
});
next();
} | javascript | function(next) {
core.allowPackages.forEach(function(pkg) {
try {
var mod = path.dirname(require.resolve(pkg)).replace(/\/lib$/, "");
core.packages[pkg] = { path: mod };
if (lib.statSync(mod + "/etc").isDirectory()) {
core.packages[pkg].etc = 1;
var cfg = lib.readFileSync(mod + "/etc/config");
if (cfg) {
config = cfg + "\n" + config;
core.packages[pkg].config = 1;
core.parseConfig(cfg, 1);
}
}
["modules","locales","views","web"].forEach(function(x) {
if (lib.statSync(mod + "/" + x).isDirectory()) {
core.path[x].unshift(mod + "/" + x);
core.packages[pkg][x] = 1;
}
});
logger.debug("init:", "npm package:", pkg, core.packages[pkg]);
} catch(e) {
logger.error("init:", "npm package:", pkg, e);
}
});
next();
} | [
"function",
"(",
"next",
")",
"{",
"core",
".",
"allowPackages",
".",
"forEach",
"(",
"function",
"(",
"pkg",
")",
"{",
"try",
"{",
"var",
"mod",
"=",
"path",
".",
"dirname",
"(",
"require",
".",
"resolve",
"(",
"pkg",
")",
")",
".",
"replace",
"(",
"/",
"\\/lib$",
"/",
",",
"\"\"",
")",
";",
"core",
".",
"packages",
"[",
"pkg",
"]",
"=",
"{",
"path",
":",
"mod",
"}",
";",
"if",
"(",
"lib",
".",
"statSync",
"(",
"mod",
"+",
"\"/etc\"",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"core",
".",
"packages",
"[",
"pkg",
"]",
".",
"etc",
"=",
"1",
";",
"var",
"cfg",
"=",
"lib",
".",
"readFileSync",
"(",
"mod",
"+",
"\"/etc/config\"",
")",
";",
"if",
"(",
"cfg",
")",
"{",
"config",
"=",
"cfg",
"+",
"\"\\n\"",
"+",
"\\n",
";",
"config",
"core",
".",
"packages",
"[",
"pkg",
"]",
".",
"config",
"=",
"1",
";",
"}",
"}",
"core",
".",
"parseConfig",
"(",
"cfg",
",",
"1",
")",
";",
"[",
"\"modules\"",
",",
"\"locales\"",
",",
"\"views\"",
",",
"\"web\"",
"]",
".",
"forEach",
"(",
"function",
"(",
"x",
")",
"{",
"if",
"(",
"lib",
".",
"statSync",
"(",
"mod",
"+",
"\"/\"",
"+",
"x",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"core",
".",
"path",
"[",
"x",
"]",
".",
"unshift",
"(",
"mod",
"+",
"\"/\"",
"+",
"x",
")",
";",
"core",
".",
"packages",
"[",
"pkg",
"]",
"[",
"x",
"]",
"=",
"1",
";",
"}",
"}",
")",
";",
"}",
"logger",
".",
"debug",
"(",
"\"init:\"",
",",
"\"npm package:\"",
",",
"pkg",
",",
"core",
".",
"packages",
"[",
"pkg",
"]",
")",
";",
"}",
")",
";",
"catch",
"(",
"e",
")",
"{",
"logger",
".",
"error",
"(",
"\"init:\"",
",",
"\"npm package:\"",
",",
"pkg",
",",
"e",
")",
";",
"}",
"}"
] | Load NPM packages and auto configure paths from each package, config files inside packages will be used as well | [
"Load",
"NPM",
"packages",
"and",
"auto",
"configure",
"paths",
"from",
"each",
"package",
"config",
"files",
"inside",
"packages",
"will",
"be",
"used",
"as",
"well"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/core.js#L361-L387 | train |
|
vseryakov/backendjs | lib/core.js | function(next) {
if (options.noModules) return next();
var opts = {
denyModules: options.denyModules || core.denyModules[core.role] || core.denyModules[""],
allowModules: options.allowModules || core.allowModules[core.role] || core.allowModules[""],
stopOnError: options.stopOnError || core.stopOnError,
};
var modules = path.resolve(__dirname, "../modules");
core.loadModules(modules, opts);
core.path.modules.forEach(function(mod) {
if (modules == path.resolve(mod)) return;
core.loadModules(mod, opts);
});
next();
} | javascript | function(next) {
if (options.noModules) return next();
var opts = {
denyModules: options.denyModules || core.denyModules[core.role] || core.denyModules[""],
allowModules: options.allowModules || core.allowModules[core.role] || core.allowModules[""],
stopOnError: options.stopOnError || core.stopOnError,
};
var modules = path.resolve(__dirname, "../modules");
core.loadModules(modules, opts);
core.path.modules.forEach(function(mod) {
if (modules == path.resolve(mod)) return;
core.loadModules(mod, opts);
});
next();
} | [
"function",
"(",
"next",
")",
"{",
"if",
"(",
"options",
".",
"noModules",
")",
"return",
"next",
"(",
")",
";",
"var",
"opts",
"=",
"{",
"denyModules",
":",
"options",
".",
"denyModules",
"||",
"core",
".",
"denyModules",
"[",
"core",
".",
"role",
"]",
"||",
"core",
".",
"denyModules",
"[",
"\"\"",
"]",
",",
"allowModules",
":",
"options",
".",
"allowModules",
"||",
"core",
".",
"allowModules",
"[",
"core",
".",
"role",
"]",
"||",
"core",
".",
"allowModules",
"[",
"\"\"",
"]",
",",
"stopOnError",
":",
"options",
".",
"stopOnError",
"||",
"core",
".",
"stopOnError",
",",
"}",
";",
"var",
"modules",
"=",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"\"../modules\"",
")",
";",
"core",
".",
"loadModules",
"(",
"modules",
",",
"opts",
")",
";",
"core",
".",
"path",
".",
"modules",
".",
"forEach",
"(",
"function",
"(",
"mod",
")",
"{",
"if",
"(",
"modules",
"==",
"path",
".",
"resolve",
"(",
"mod",
")",
")",
"return",
";",
"core",
".",
"loadModules",
"(",
"mod",
",",
"opts",
")",
";",
"}",
")",
";",
"next",
"(",
")",
";",
"}"
] | Load external modules, from the core and from the app home | [
"Load",
"external",
"modules",
"from",
"the",
"core",
"and",
"from",
"the",
"app",
"home"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/core.js#L390-L404 | train |
|
vseryakov/backendjs | lib/core.js | function(next) {
var files = [];
if (core.appPackage && core.packages[core.appPackage]) files.push(core.packages[core.appPackage].path);
files.push(core.home, core.path.etc + "/..", __dirname + "/..");
for (var i in files) {
var pkg = lib.readFileSync(files[i] + "/package.json", { json: 1, logger: "error", missingok: 1 });
logger.debug("init:", files[i] + "/package.json", pkg.name, pkg.version);
if (!core.appName && pkg.name) core.appName = pkg.name;
if (!core.appVersion && pkg.version) core.appVersion = pkg.version;
if (!core.appDescr && pkg.description) core.appDescr = pkg.description;
if (!core.version && pkg.name == "backendjs") core.version = pkg.version;
}
if (!core.appName) core.appName = core.name;
if (!core.appVersion) core.appVersion = core.version;
// Use the app name as salt for consistentcy
if (!core.salt) core.salt = lib.salt = core.appName;
next();
} | javascript | function(next) {
var files = [];
if (core.appPackage && core.packages[core.appPackage]) files.push(core.packages[core.appPackage].path);
files.push(core.home, core.path.etc + "/..", __dirname + "/..");
for (var i in files) {
var pkg = lib.readFileSync(files[i] + "/package.json", { json: 1, logger: "error", missingok: 1 });
logger.debug("init:", files[i] + "/package.json", pkg.name, pkg.version);
if (!core.appName && pkg.name) core.appName = pkg.name;
if (!core.appVersion && pkg.version) core.appVersion = pkg.version;
if (!core.appDescr && pkg.description) core.appDescr = pkg.description;
if (!core.version && pkg.name == "backendjs") core.version = pkg.version;
}
if (!core.appName) core.appName = core.name;
if (!core.appVersion) core.appVersion = core.version;
// Use the app name as salt for consistentcy
if (!core.salt) core.salt = lib.salt = core.appName;
next();
} | [
"function",
"(",
"next",
")",
"{",
"var",
"files",
"=",
"[",
"]",
";",
"if",
"(",
"core",
".",
"appPackage",
"&&",
"core",
".",
"packages",
"[",
"core",
".",
"appPackage",
"]",
")",
"files",
".",
"push",
"(",
"core",
".",
"packages",
"[",
"core",
".",
"appPackage",
"]",
".",
"path",
")",
";",
"files",
".",
"push",
"(",
"core",
".",
"home",
",",
"core",
".",
"path",
".",
"etc",
"+",
"\"/..\"",
",",
"__dirname",
"+",
"\"/..\"",
")",
";",
"for",
"(",
"var",
"i",
"in",
"files",
")",
"{",
"var",
"pkg",
"=",
"lib",
".",
"readFileSync",
"(",
"files",
"[",
"i",
"]",
"+",
"\"/package.json\"",
",",
"{",
"json",
":",
"1",
",",
"logger",
":",
"\"error\"",
",",
"missingok",
":",
"1",
"}",
")",
";",
"logger",
".",
"debug",
"(",
"\"init:\"",
",",
"files",
"[",
"i",
"]",
"+",
"\"/package.json\"",
",",
"pkg",
".",
"name",
",",
"pkg",
".",
"version",
")",
";",
"if",
"(",
"!",
"core",
".",
"appName",
"&&",
"pkg",
".",
"name",
")",
"core",
".",
"appName",
"=",
"pkg",
".",
"name",
";",
"if",
"(",
"!",
"core",
".",
"appVersion",
"&&",
"pkg",
".",
"version",
")",
"core",
".",
"appVersion",
"=",
"pkg",
".",
"version",
";",
"if",
"(",
"!",
"core",
".",
"appDescr",
"&&",
"pkg",
".",
"description",
")",
"core",
".",
"appDescr",
"=",
"pkg",
".",
"description",
";",
"if",
"(",
"!",
"core",
".",
"version",
"&&",
"pkg",
".",
"name",
"==",
"\"backendjs\"",
")",
"core",
".",
"version",
"=",
"pkg",
".",
"version",
";",
"}",
"if",
"(",
"!",
"core",
".",
"appName",
")",
"core",
".",
"appName",
"=",
"core",
".",
"name",
";",
"if",
"(",
"!",
"core",
".",
"appVersion",
")",
"core",
".",
"appVersion",
"=",
"core",
".",
"version",
";",
"if",
"(",
"!",
"core",
".",
"salt",
")",
"core",
".",
"salt",
"=",
"lib",
".",
"salt",
"=",
"core",
".",
"appName",
";",
"next",
"(",
")",
";",
"}"
] | Application version from the package.json | [
"Application",
"version",
"from",
"the",
"package",
".",
"json"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/core.js#L414-L431 | train |
|
vseryakov/backendjs | lib/core.js | function(next) {
if (options.noDns || core.noDns) return next();
core.loadDnsConfig(options, next);
} | javascript | function(next) {
if (options.noDns || core.noDns) return next();
core.loadDnsConfig(options, next);
} | [
"function",
"(",
"next",
")",
"{",
"if",
"(",
"options",
".",
"noDns",
"||",
"core",
".",
"noDns",
")",
"return",
"next",
"(",
")",
";",
"core",
".",
"loadDnsConfig",
"(",
"options",
",",
"next",
")",
";",
"}"
] | Load config params from the DNS TXT records, only the ones marked as dns | [
"Load",
"config",
"params",
"from",
"the",
"DNS",
"TXT",
"records",
"only",
"the",
"ones",
"marked",
"as",
"dns"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/core.js#L434-L437 | train |
|
vseryakov/backendjs | lib/core.js | function(next) {
try { process.umask(core.umask); } catch(e) { logger.error("umask:", core.umask, e) }
// Create all subfolders with permissions, run it before initializing db which may create files in the spool folder
if (!cluster.isWorker && !core.worker) {
Object.keys(core.path).forEach(function(p) {
var paths = Array.isArray(core.path[p]) ? core.path[p] : [core.path[p]];
paths.forEach(function(x) {
if (!x || path.isAbsolute(x)) return;
lib.mkdirSync(x);
lib.chownSync(this.uid, this.gid, x);
});
});
}
next();
} | javascript | function(next) {
try { process.umask(core.umask); } catch(e) { logger.error("umask:", core.umask, e) }
// Create all subfolders with permissions, run it before initializing db which may create files in the spool folder
if (!cluster.isWorker && !core.worker) {
Object.keys(core.path).forEach(function(p) {
var paths = Array.isArray(core.path[p]) ? core.path[p] : [core.path[p]];
paths.forEach(function(x) {
if (!x || path.isAbsolute(x)) return;
lib.mkdirSync(x);
lib.chownSync(this.uid, this.gid, x);
});
});
}
next();
} | [
"function",
"(",
"next",
")",
"{",
"try",
"{",
"process",
".",
"umask",
"(",
"core",
".",
"umask",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"logger",
".",
"error",
"(",
"\"umask:\"",
",",
"core",
".",
"umask",
",",
"e",
")",
"}",
"if",
"(",
"!",
"cluster",
".",
"isWorker",
"&&",
"!",
"core",
".",
"worker",
")",
"{",
"Object",
".",
"keys",
"(",
"core",
".",
"path",
")",
".",
"forEach",
"(",
"function",
"(",
"p",
")",
"{",
"var",
"paths",
"=",
"Array",
".",
"isArray",
"(",
"core",
".",
"path",
"[",
"p",
"]",
")",
"?",
"core",
".",
"path",
"[",
"p",
"]",
":",
"[",
"core",
".",
"path",
"[",
"p",
"]",
"]",
";",
"paths",
".",
"forEach",
"(",
"function",
"(",
"x",
")",
"{",
"if",
"(",
"!",
"x",
"||",
"path",
".",
"isAbsolute",
"(",
"x",
")",
")",
"return",
";",
"lib",
".",
"mkdirSync",
"(",
"x",
")",
";",
"lib",
".",
"chownSync",
"(",
"this",
".",
"uid",
",",
"this",
".",
"gid",
",",
"x",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"next",
"(",
")",
";",
"}"
] | Create all directories, only master should do it once but we resolve absolute paths in any mode | [
"Create",
"all",
"directories",
"only",
"master",
"should",
"do",
"it",
"once",
"but",
"we",
"resolve",
"absolute",
"paths",
"in",
"any",
"mode"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/core.js#L440-L455 | train |
|
vseryakov/backendjs | lib/core.js | function(next) {
if (options.noDb || core.noDb) return next();
db.init(options, next);
} | javascript | function(next) {
if (options.noDb || core.noDb) return next();
db.init(options, next);
} | [
"function",
"(",
"next",
")",
"{",
"if",
"(",
"options",
".",
"noDb",
"||",
"core",
".",
"noDb",
")",
"return",
"next",
"(",
")",
";",
"db",
".",
"init",
"(",
"options",
",",
"next",
")",
";",
"}"
] | Initialize all database pools | [
"Initialize",
"all",
"database",
"pools"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/core.js#L464-L467 | train |
|
vseryakov/backendjs | lib/core.js | function(next) {
if (options.noDb || core.noDb) return next();
db.initConfig(options, next);
} | javascript | function(next) {
if (options.noDb || core.noDb) return next();
db.initConfig(options, next);
} | [
"function",
"(",
"next",
")",
"{",
"if",
"(",
"options",
".",
"noDb",
"||",
"core",
".",
"noDb",
")",
"return",
"next",
"(",
")",
";",
"db",
".",
"initConfig",
"(",
"options",
",",
"next",
")",
";",
"}"
] | Load all available config parameters from the config database for the specified config type | [
"Load",
"all",
"available",
"config",
"parameters",
"from",
"the",
"config",
"database",
"for",
"the",
"specified",
"config",
"type"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/core.js#L470-L473 | train |
|
vseryakov/backendjs | lib/core.js | function(next) {
if (!cluster.isWorker && !core.worker && process.getuid() == 0) {
lib.findFileSync(core.path.spool).forEach(function(p) { lib.chownSync(core.uid, core.gid, p); });
}
next();
} | javascript | function(next) {
if (!cluster.isWorker && !core.worker && process.getuid() == 0) {
lib.findFileSync(core.path.spool).forEach(function(p) { lib.chownSync(core.uid, core.gid, p); });
}
next();
} | [
"function",
"(",
"next",
")",
"{",
"if",
"(",
"!",
"cluster",
".",
"isWorker",
"&&",
"!",
"core",
".",
"worker",
"&&",
"process",
".",
"getuid",
"(",
")",
"==",
"0",
")",
"{",
"lib",
".",
"findFileSync",
"(",
"core",
".",
"path",
".",
"spool",
")",
".",
"forEach",
"(",
"function",
"(",
"p",
")",
"{",
"lib",
".",
"chownSync",
"(",
"core",
".",
"uid",
",",
"core",
".",
"gid",
",",
"p",
")",
";",
"}",
")",
";",
"}",
"next",
"(",
")",
";",
"}"
] | Make sure spool and db files are owned by regular user, not the root | [
"Make",
"sure",
"spool",
"and",
"db",
"files",
"are",
"owned",
"by",
"regular",
"user",
"not",
"the",
"root"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/core.js#L483-L488 | train |
|
vseryakov/backendjs | lib/core.js | function(next) {
if (options.noConfigure || core.noConfigure) return next();
core.runMethods("configureModule", options, next);
} | javascript | function(next) {
if (options.noConfigure || core.noConfigure) return next();
core.runMethods("configureModule", options, next);
} | [
"function",
"(",
"next",
")",
"{",
"if",
"(",
"options",
".",
"noConfigure",
"||",
"core",
".",
"noConfigure",
")",
"return",
"next",
"(",
")",
";",
"core",
".",
"runMethods",
"(",
"\"configureModule\"",
",",
"options",
",",
"next",
")",
";",
"}"
] | Initialize all modules after core is done | [
"Initialize",
"all",
"modules",
"after",
"core",
"is",
"done"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/core.js#L507-L510 | train |
|
zengfenfei/ringcentral-ts | script/update-package.json.js | updateVersion2gitTag | function updateVersion2gitTag(pkg) {
let tag = child_process.execSync('git describe --tag').toString().trim();
pkg.version = tag;
} | javascript | function updateVersion2gitTag(pkg) {
let tag = child_process.execSync('git describe --tag').toString().trim();
pkg.version = tag;
} | [
"function",
"updateVersion2gitTag",
"(",
"pkg",
")",
"{",
"let",
"tag",
"=",
"child_process",
".",
"execSync",
"(",
"'git describe --tag'",
")",
".",
"toString",
"(",
")",
".",
"trim",
"(",
")",
";",
"pkg",
".",
"version",
"=",
"tag",
";",
"}"
] | Will throw if not on a tag | [
"Will",
"throw",
"if",
"not",
"on",
"a",
"tag"
] | a434e87f400f137744bba7a30e16a792475cea80 | https://github.com/zengfenfei/ringcentral-ts/blob/a434e87f400f137744bba7a30e16a792475cea80/script/update-package.json.js#L17-L20 | train |
vseryakov/backendjs | lib/lib.js | function(t, utc, lang, tz) {
return zeropad(utc ? t.getUTCMinutes() : t.getMinutes())
} | javascript | function(t, utc, lang, tz) {
return zeropad(utc ? t.getUTCMinutes() : t.getMinutes())
} | [
"function",
"(",
"t",
",",
"utc",
",",
"lang",
",",
"tz",
")",
"{",
"return",
"zeropad",
"(",
"utc",
"?",
"t",
".",
"getUTCMinutes",
"(",
")",
":",
"t",
".",
"getMinutes",
"(",
")",
")",
"}"
] | month-1 | [
"month",
"-",
"1"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/lib.js#L2536-L2538 | train |
|
vseryakov/backendjs | lib/lib.js | _parse | function _parse(type, obj, options)
{
if (!obj) return _checkResult(type, lib.newError("empty " + type), obj, options);
try {
obj = _parseResult(type, obj, options);
} catch(err) {
obj = _checkResult(type, err, obj, options);
}
return obj;
} | javascript | function _parse(type, obj, options)
{
if (!obj) return _checkResult(type, lib.newError("empty " + type), obj, options);
try {
obj = _parseResult(type, obj, options);
} catch(err) {
obj = _checkResult(type, err, obj, options);
}
return obj;
} | [
"function",
"_parse",
"(",
"type",
",",
"obj",
",",
"options",
")",
"{",
"if",
"(",
"!",
"obj",
")",
"return",
"_checkResult",
"(",
"type",
",",
"lib",
".",
"newError",
"(",
"\"empty \"",
"+",
"type",
")",
",",
"obj",
",",
"options",
")",
";",
"try",
"{",
"obj",
"=",
"_parseResult",
"(",
"type",
",",
"obj",
",",
"options",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"obj",
"=",
"_checkResult",
"(",
"type",
",",
"err",
",",
"obj",
",",
"options",
")",
";",
"}",
"return",
"obj",
";",
"}"
] | Combined parser with type validation | [
"Combined",
"parser",
"with",
"type",
"validation"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/lib.js#L3951-L3960 | train |
vseryakov/backendjs | lib/lib.js | _checkResult | function _checkResult(type, err, obj, options)
{
if (options) {
if (options.logger) logger.logger(options.logger, 'parse:', type, options, lib.traceError(err), obj);
if (options.datatype == "object" || options.datatype == "obj") return {};
if (options.datatype == "list") return [];
if (options.datatype == "str") return "";
}
return null;
} | javascript | function _checkResult(type, err, obj, options)
{
if (options) {
if (options.logger) logger.logger(options.logger, 'parse:', type, options, lib.traceError(err), obj);
if (options.datatype == "object" || options.datatype == "obj") return {};
if (options.datatype == "list") return [];
if (options.datatype == "str") return "";
}
return null;
} | [
"function",
"_checkResult",
"(",
"type",
",",
"err",
",",
"obj",
",",
"options",
")",
"{",
"if",
"(",
"options",
")",
"{",
"if",
"(",
"options",
".",
"logger",
")",
"logger",
".",
"logger",
"(",
"options",
".",
"logger",
",",
"'parse:'",
",",
"type",
",",
"options",
",",
"lib",
".",
"traceError",
"(",
"err",
")",
",",
"obj",
")",
";",
"if",
"(",
"options",
".",
"datatype",
"==",
"\"object\"",
"||",
"options",
".",
"datatype",
"==",
"\"obj\"",
")",
"return",
"{",
"}",
";",
"if",
"(",
"options",
".",
"datatype",
"==",
"\"list\"",
")",
"return",
"[",
"]",
";",
"if",
"(",
"options",
".",
"datatype",
"==",
"\"str\"",
")",
"return",
"\"\"",
";",
"}",
"return",
"null",
";",
"}"
] | Perform validation of the result type, make sure we return what is expected, this is a helper that is used by other conversion routines | [
"Perform",
"validation",
"of",
"the",
"result",
"type",
"make",
"sure",
"we",
"return",
"what",
"is",
"expected",
"this",
"is",
"a",
"helper",
"that",
"is",
"used",
"by",
"other",
"conversion",
"routines"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/lib.js#L3996-L4005 | train |
metascript/metascript | lib/mjs.js | getConfig | function getConfig(fpath, defaults) {
var path = require('path');
var dpath = path.dirname(path.resolve(fpath));
function parentpath(fromdir, pattern) {
var pp = require('parentpath'),
cwd = process.cwd();
try {
process.chdir(fromdir);
return pp.sync(pattern);
} catch (e) {
return null;
} finally {
process.chdir(cwd);
}
}
function fromNpm() {
var config;
var dir = parentpath(dpath, 'package.json');
if (dir) {
try {
config = require(dir + '/package.json')[MJS_NPM];
config.__origin__ = dir + '/package.json';
} catch (e) {
}
}
return config;
}
function fromResourceFile() {
var candidates = [
parentpath(path, MJS_RC),
process.env.HOME, process.env.USERPROFILE, process.env.HOMEPATH, process.env.HOMEDRIVE + process.env.HOMEPATH
];
var config;
for (var i = 0; i < candidates.length; i++) {
var candidate = candidates[i] + '/' + MJS_RC;
if (fs.existsSync(candidate)) {
try {
config = JSON.parse(fs.readFileSync(candidate));
config.__origin__ = candidate;
break;
} catch (e) {
showHelpAndExit('Unable to read config from "' + candidate + '": ' + e.message, 1);
}
}
}
return config;
}
var config = fromNpm() || fromResourceFile() || {};
// Make sure we apply defaults to missing values
Object.keys(defaults).filter(function (k) {
return config[k] == null
}).forEach(function (k) {
config[k] = defaults[k];
});
return config;
} | javascript | function getConfig(fpath, defaults) {
var path = require('path');
var dpath = path.dirname(path.resolve(fpath));
function parentpath(fromdir, pattern) {
var pp = require('parentpath'),
cwd = process.cwd();
try {
process.chdir(fromdir);
return pp.sync(pattern);
} catch (e) {
return null;
} finally {
process.chdir(cwd);
}
}
function fromNpm() {
var config;
var dir = parentpath(dpath, 'package.json');
if (dir) {
try {
config = require(dir + '/package.json')[MJS_NPM];
config.__origin__ = dir + '/package.json';
} catch (e) {
}
}
return config;
}
function fromResourceFile() {
var candidates = [
parentpath(path, MJS_RC),
process.env.HOME, process.env.USERPROFILE, process.env.HOMEPATH, process.env.HOMEDRIVE + process.env.HOMEPATH
];
var config;
for (var i = 0; i < candidates.length; i++) {
var candidate = candidates[i] + '/' + MJS_RC;
if (fs.existsSync(candidate)) {
try {
config = JSON.parse(fs.readFileSync(candidate));
config.__origin__ = candidate;
break;
} catch (e) {
showHelpAndExit('Unable to read config from "' + candidate + '": ' + e.message, 1);
}
}
}
return config;
}
var config = fromNpm() || fromResourceFile() || {};
// Make sure we apply defaults to missing values
Object.keys(defaults).filter(function (k) {
return config[k] == null
}).forEach(function (k) {
config[k] = defaults[k];
});
return config;
} | [
"function",
"getConfig",
"(",
"fpath",
",",
"defaults",
")",
"{",
"var",
"path",
"=",
"require",
"(",
"'path'",
")",
";",
"var",
"dpath",
"=",
"path",
".",
"dirname",
"(",
"path",
".",
"resolve",
"(",
"fpath",
")",
")",
";",
"function",
"parentpath",
"(",
"fromdir",
",",
"pattern",
")",
"{",
"var",
"pp",
"=",
"require",
"(",
"'parentpath'",
")",
",",
"cwd",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"try",
"{",
"process",
".",
"chdir",
"(",
"fromdir",
")",
";",
"return",
"pp",
".",
"sync",
"(",
"pattern",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"null",
";",
"}",
"finally",
"{",
"process",
".",
"chdir",
"(",
"cwd",
")",
";",
"}",
"}",
"function",
"fromNpm",
"(",
")",
"{",
"var",
"config",
";",
"var",
"dir",
"=",
"parentpath",
"(",
"dpath",
",",
"'package.json'",
")",
";",
"if",
"(",
"dir",
")",
"{",
"try",
"{",
"config",
"=",
"require",
"(",
"dir",
"+",
"'/package.json'",
")",
"[",
"MJS_NPM",
"]",
";",
"config",
".",
"__origin__",
"=",
"dir",
"+",
"'/package.json'",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"}",
"return",
"config",
";",
"}",
"function",
"fromResourceFile",
"(",
")",
"{",
"var",
"candidates",
"=",
"[",
"parentpath",
"(",
"path",
",",
"MJS_RC",
")",
",",
"process",
".",
"env",
".",
"HOME",
",",
"process",
".",
"env",
".",
"USERPROFILE",
",",
"process",
".",
"env",
".",
"HOMEPATH",
",",
"process",
".",
"env",
".",
"HOMEDRIVE",
"+",
"process",
".",
"env",
".",
"HOMEPATH",
"]",
";",
"var",
"config",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"candidates",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"candidate",
"=",
"candidates",
"[",
"i",
"]",
"+",
"'/'",
"+",
"MJS_RC",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"candidate",
")",
")",
"{",
"try",
"{",
"config",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"candidate",
")",
")",
";",
"config",
".",
"__origin__",
"=",
"candidate",
";",
"break",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"showHelpAndExit",
"(",
"'Unable to read config from \"'",
"+",
"candidate",
"+",
"'\": '",
"+",
"e",
".",
"message",
",",
"1",
")",
";",
"}",
"}",
"}",
"return",
"config",
";",
"}",
"var",
"config",
"=",
"fromNpm",
"(",
")",
"||",
"fromResourceFile",
"(",
")",
"||",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"defaults",
")",
".",
"filter",
"(",
"function",
"(",
"k",
")",
"{",
"return",
"config",
"[",
"k",
"]",
"==",
"null",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"k",
")",
"{",
"config",
"[",
"k",
"]",
"=",
"defaults",
"[",
"k",
"]",
";",
"}",
")",
";",
"return",
"config",
";",
"}"
] | Get configuration from NPM package or from resource files | [
"Get",
"configuration",
"from",
"NPM",
"package",
"or",
"from",
"resource",
"files"
] | 68ab8609d101359a88c0f7aff5e7e8ea213e378d | https://github.com/metascript/metascript/blob/68ab8609d101359a88c0f7aff5e7e8ea213e378d/lib/mjs.js#L185-L245 | train |
godmodelabs/flora | lib/config-loader.js | walk | function walk(configDirectory, resourceName, resources) {
resourceName = resourceName || '';
resources = resources || {};
fs.readdirSync(path.join(configDirectory, resourceName)).forEach(fileName => {
const subResourceName = (resourceName !== '' ? resourceName + '/' : '') + fileName;
const absoluteFilePath = path.join(configDirectory, subResourceName);
const stat = fs.statSync(absoluteFilePath);
if (stat && stat.isDirectory()) {
walk(configDirectory, subResourceName, resources);
} else if (resourceName !== '') {
if (fileName.startsWith('config.')) {
if (!resources[resourceName]) resources[resourceName] = {};
resources[resourceName].configFile = absoluteFilePath;
}
if (fileName === 'index.js') {
if (!resources[resourceName]) resources[resourceName] = {};
resources[resourceName].instanceFile = absoluteFilePath;
}
}
});
return resources;
} | javascript | function walk(configDirectory, resourceName, resources) {
resourceName = resourceName || '';
resources = resources || {};
fs.readdirSync(path.join(configDirectory, resourceName)).forEach(fileName => {
const subResourceName = (resourceName !== '' ? resourceName + '/' : '') + fileName;
const absoluteFilePath = path.join(configDirectory, subResourceName);
const stat = fs.statSync(absoluteFilePath);
if (stat && stat.isDirectory()) {
walk(configDirectory, subResourceName, resources);
} else if (resourceName !== '') {
if (fileName.startsWith('config.')) {
if (!resources[resourceName]) resources[resourceName] = {};
resources[resourceName].configFile = absoluteFilePath;
}
if (fileName === 'index.js') {
if (!resources[resourceName]) resources[resourceName] = {};
resources[resourceName].instanceFile = absoluteFilePath;
}
}
});
return resources;
} | [
"function",
"walk",
"(",
"configDirectory",
",",
"resourceName",
",",
"resources",
")",
"{",
"resourceName",
"=",
"resourceName",
"||",
"''",
";",
"resources",
"=",
"resources",
"||",
"{",
"}",
";",
"fs",
".",
"readdirSync",
"(",
"path",
".",
"join",
"(",
"configDirectory",
",",
"resourceName",
")",
")",
".",
"forEach",
"(",
"fileName",
"=>",
"{",
"const",
"subResourceName",
"=",
"(",
"resourceName",
"!==",
"''",
"?",
"resourceName",
"+",
"'/'",
":",
"''",
")",
"+",
"fileName",
";",
"const",
"absoluteFilePath",
"=",
"path",
".",
"join",
"(",
"configDirectory",
",",
"subResourceName",
")",
";",
"const",
"stat",
"=",
"fs",
".",
"statSync",
"(",
"absoluteFilePath",
")",
";",
"if",
"(",
"stat",
"&&",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"walk",
"(",
"configDirectory",
",",
"subResourceName",
",",
"resources",
")",
";",
"}",
"else",
"if",
"(",
"resourceName",
"!==",
"''",
")",
"{",
"if",
"(",
"fileName",
".",
"startsWith",
"(",
"'config.'",
")",
")",
"{",
"if",
"(",
"!",
"resources",
"[",
"resourceName",
"]",
")",
"resources",
"[",
"resourceName",
"]",
"=",
"{",
"}",
";",
"resources",
"[",
"resourceName",
"]",
".",
"configFile",
"=",
"absoluteFilePath",
";",
"}",
"if",
"(",
"fileName",
"===",
"'index.js'",
")",
"{",
"if",
"(",
"!",
"resources",
"[",
"resourceName",
"]",
")",
"resources",
"[",
"resourceName",
"]",
"=",
"{",
"}",
";",
"resources",
"[",
"resourceName",
"]",
".",
"instanceFile",
"=",
"absoluteFilePath",
";",
"}",
"}",
"}",
")",
";",
"return",
"resources",
";",
"}"
] | Read config files from directory recursively.
@param {string} configDirectory
@param {string} resourceName
@param {object} resources
@return {Array}
@private | [
"Read",
"config",
"files",
"from",
"directory",
"recursively",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/config-loader.js#L16-L39 | train |
alibaba/ots | lib/client.js | Client | function Client(options) {
this.accessID = options.accessID;
this.accessKey = options.accessKey;
this.signatureMethod = options.signatureMethod || 'HmacSHA1';
this.signatureVersion = options.signatureVersion || '1';
this.APIVersion = options.APIVersion || '2013-05-10';
this.APIHost = options.APIHost || 'http://ots.aliyuncs.com';
// protocol: 'http:'
// hostname: 'service.ots.aliyun.com'
// port: undefined
this.APIHostInfo = urlparse(this.APIHost);
this.requestAgent = options.agent || null;
this.requestTimeout = options.requestTimeout || 5000;
var dnsCacheTime = options.dnsCacheTime || 10000;
this.dns = CacheDNS.create({cacheTime: dnsCacheTime});
this.vip = options.vip;
} | javascript | function Client(options) {
this.accessID = options.accessID;
this.accessKey = options.accessKey;
this.signatureMethod = options.signatureMethod || 'HmacSHA1';
this.signatureVersion = options.signatureVersion || '1';
this.APIVersion = options.APIVersion || '2013-05-10';
this.APIHost = options.APIHost || 'http://ots.aliyuncs.com';
// protocol: 'http:'
// hostname: 'service.ots.aliyun.com'
// port: undefined
this.APIHostInfo = urlparse(this.APIHost);
this.requestAgent = options.agent || null;
this.requestTimeout = options.requestTimeout || 5000;
var dnsCacheTime = options.dnsCacheTime || 10000;
this.dns = CacheDNS.create({cacheTime: dnsCacheTime});
this.vip = options.vip;
} | [
"function",
"Client",
"(",
"options",
")",
"{",
"this",
".",
"accessID",
"=",
"options",
".",
"accessID",
";",
"this",
".",
"accessKey",
"=",
"options",
".",
"accessKey",
";",
"this",
".",
"signatureMethod",
"=",
"options",
".",
"signatureMethod",
"||",
"'HmacSHA1'",
";",
"this",
".",
"signatureVersion",
"=",
"options",
".",
"signatureVersion",
"||",
"'1'",
";",
"this",
".",
"APIVersion",
"=",
"options",
".",
"APIVersion",
"||",
"'2013-05-10'",
";",
"this",
".",
"APIHost",
"=",
"options",
".",
"APIHost",
"||",
"'http://ots.aliyuncs.com'",
";",
"this",
".",
"APIHostInfo",
"=",
"urlparse",
"(",
"this",
".",
"APIHost",
")",
";",
"this",
".",
"requestAgent",
"=",
"options",
".",
"agent",
"||",
"null",
";",
"this",
".",
"requestTimeout",
"=",
"options",
".",
"requestTimeout",
"||",
"5000",
";",
"var",
"dnsCacheTime",
"=",
"options",
".",
"dnsCacheTime",
"||",
"10000",
";",
"this",
".",
"dns",
"=",
"CacheDNS",
".",
"create",
"(",
"{",
"cacheTime",
":",
"dnsCacheTime",
"}",
")",
";",
"this",
".",
"vip",
"=",
"options",
".",
"vip",
";",
"}"
] | OTS Client.
@param {Object} options
- {String} accessID
- {String} accessKey
- {Number} [requestTimeout], default 5000ms.
- {Agent} [http] request agent, default is `urllib.agent`.
- {Number} [dnsCacheTime] dns cache time, default is `10000 ms`.
- {String} [APIVersion] api version, default is '2013-05-10'.
- {String} [APIHost] api host URL, default is 'http://service.ots.aliyun.com'.
- {Object} [vip] OTS vip manager, only use for alibaba-inc. @suqian.yf
@constructor | [
"OTS",
"Client",
"."
] | 7875e6dde241fcbe53dd7bb00259075d4269fd37 | https://github.com/alibaba/ots/blob/7875e6dde241fcbe53dd7bb00259075d4269fd37/lib/client.js#L108-L124 | train |
godmodelabs/flora | lib/xml-reader.js | getDataSource | function getDataSource(node) {
const config = Object.assign({}, copyXmlAttributes(node));
if (node.childNodes.length) {
// parse datasource options
for (let i = 0; i < node.childNodes.length; ++i) {
const childNode = node.childNodes.item(i);
if (childNode.nodeType === TEXT_NODE && childNode.textContent.trim().length > 0) {
throw new ImplementationError(`dataSource contains useless text: "${childNode.textContent.trim()}"`);
}
if (
childNode.nodeType === ELEMENT_NODE &&
childNode.namespaceURI === 'urn:flora:options' &&
childNode.localName === 'option'
) {
if (childNode.attributes.length !== 1)
throw new Error('flora:option element requires a name attribute');
const attr = childNode.attributes.item(0);
if (attr.localName !== 'name') throw new Error('flora:option element requires a name attribute');
if (config[attr.value]) throw new Error(`Data source option "${attr.value}" already defined`);
config[attr.value] = childNode.textContent.trim();
}
}
}
const name = config.name ? config.name : 'primary';
if (config.name) delete config.name;
return { name, config };
} | javascript | function getDataSource(node) {
const config = Object.assign({}, copyXmlAttributes(node));
if (node.childNodes.length) {
// parse datasource options
for (let i = 0; i < node.childNodes.length; ++i) {
const childNode = node.childNodes.item(i);
if (childNode.nodeType === TEXT_NODE && childNode.textContent.trim().length > 0) {
throw new ImplementationError(`dataSource contains useless text: "${childNode.textContent.trim()}"`);
}
if (
childNode.nodeType === ELEMENT_NODE &&
childNode.namespaceURI === 'urn:flora:options' &&
childNode.localName === 'option'
) {
if (childNode.attributes.length !== 1)
throw new Error('flora:option element requires a name attribute');
const attr = childNode.attributes.item(0);
if (attr.localName !== 'name') throw new Error('flora:option element requires a name attribute');
if (config[attr.value]) throw new Error(`Data source option "${attr.value}" already defined`);
config[attr.value] = childNode.textContent.trim();
}
}
}
const name = config.name ? config.name : 'primary';
if (config.name) delete config.name;
return { name, config };
} | [
"function",
"getDataSource",
"(",
"node",
")",
"{",
"const",
"config",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"copyXmlAttributes",
"(",
"node",
")",
")",
";",
"if",
"(",
"node",
".",
"childNodes",
".",
"length",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"node",
".",
"childNodes",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"childNode",
"=",
"node",
".",
"childNodes",
".",
"item",
"(",
"i",
")",
";",
"if",
"(",
"childNode",
".",
"nodeType",
"===",
"TEXT_NODE",
"&&",
"childNode",
".",
"textContent",
".",
"trim",
"(",
")",
".",
"length",
">",
"0",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"childNode",
".",
"textContent",
".",
"trim",
"(",
")",
"}",
"`",
")",
";",
"}",
"if",
"(",
"childNode",
".",
"nodeType",
"===",
"ELEMENT_NODE",
"&&",
"childNode",
".",
"namespaceURI",
"===",
"'urn:flora:options'",
"&&",
"childNode",
".",
"localName",
"===",
"'option'",
")",
"{",
"if",
"(",
"childNode",
".",
"attributes",
".",
"length",
"!==",
"1",
")",
"throw",
"new",
"Error",
"(",
"'flora:option element requires a name attribute'",
")",
";",
"const",
"attr",
"=",
"childNode",
".",
"attributes",
".",
"item",
"(",
"0",
")",
";",
"if",
"(",
"attr",
".",
"localName",
"!==",
"'name'",
")",
"throw",
"new",
"Error",
"(",
"'flora:option element requires a name attribute'",
")",
";",
"if",
"(",
"config",
"[",
"attr",
".",
"value",
"]",
")",
"throw",
"new",
"Error",
"(",
"`",
"${",
"attr",
".",
"value",
"}",
"`",
")",
";",
"config",
"[",
"attr",
".",
"value",
"]",
"=",
"childNode",
".",
"textContent",
".",
"trim",
"(",
")",
";",
"}",
"}",
"}",
"const",
"name",
"=",
"config",
".",
"name",
"?",
"config",
".",
"name",
":",
"'primary'",
";",
"if",
"(",
"config",
".",
"name",
")",
"delete",
"config",
".",
"name",
";",
"return",
"{",
"name",
",",
"config",
"}",
";",
"}"
] | Extract config from dataSource nodes.
@param {Node} node
@return {Object}
@private | [
"Extract",
"config",
"from",
"dataSource",
"nodes",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/xml-reader.js#L60-L93 | train |
godmodelabs/flora | lib/xml-reader.js | parse | function parse(node) {
const cfg = Object.assign({}, copyXmlAttributes(node));
for (let i = 0, l = node.childNodes.length; i < l; ++i) {
const el = node.childNodes.item(i);
if (el.nodeType === ELEMENT_NODE) {
if (!el.namespaceURI) {
// attribute elements
if (!cfg.attributes) cfg.attributes = {};
cfg.attributes[el.localName] = el.childNodes.length ? parse(el) : copyXmlAttributes(el);
} else if (el.namespaceURI === 'urn:flora:options') {
// flora specific elements
if (el.localName === 'dataSource') {
const dataSource = getDataSource(el);
if (!cfg.dataSources) cfg.dataSources = {};
if (cfg.dataSources[dataSource.name]) {
throw new Error(`Data source "${dataSource.name}" already defined`);
}
cfg.dataSources[dataSource.name] = dataSource.config;
}
if (el.localName === 'subFilter') {
if (!cfg.subFilters) cfg.subFilters = [];
cfg.subFilters.push(copyXmlAttributes(el));
}
}
} else if (el.nodeType === TEXT_NODE && el.textContent.trim().length > 0) {
throw new ImplementationError(`Config contains unnecessary text: "${el.textContent.trim()}"`);
}
}
return cfg;
} | javascript | function parse(node) {
const cfg = Object.assign({}, copyXmlAttributes(node));
for (let i = 0, l = node.childNodes.length; i < l; ++i) {
const el = node.childNodes.item(i);
if (el.nodeType === ELEMENT_NODE) {
if (!el.namespaceURI) {
// attribute elements
if (!cfg.attributes) cfg.attributes = {};
cfg.attributes[el.localName] = el.childNodes.length ? parse(el) : copyXmlAttributes(el);
} else if (el.namespaceURI === 'urn:flora:options') {
// flora specific elements
if (el.localName === 'dataSource') {
const dataSource = getDataSource(el);
if (!cfg.dataSources) cfg.dataSources = {};
if (cfg.dataSources[dataSource.name]) {
throw new Error(`Data source "${dataSource.name}" already defined`);
}
cfg.dataSources[dataSource.name] = dataSource.config;
}
if (el.localName === 'subFilter') {
if (!cfg.subFilters) cfg.subFilters = [];
cfg.subFilters.push(copyXmlAttributes(el));
}
}
} else if (el.nodeType === TEXT_NODE && el.textContent.trim().length > 0) {
throw new ImplementationError(`Config contains unnecessary text: "${el.textContent.trim()}"`);
}
}
return cfg;
} | [
"function",
"parse",
"(",
"node",
")",
"{",
"const",
"cfg",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"copyXmlAttributes",
"(",
"node",
")",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"l",
"=",
"node",
".",
"childNodes",
".",
"length",
";",
"i",
"<",
"l",
";",
"++",
"i",
")",
"{",
"const",
"el",
"=",
"node",
".",
"childNodes",
".",
"item",
"(",
"i",
")",
";",
"if",
"(",
"el",
".",
"nodeType",
"===",
"ELEMENT_NODE",
")",
"{",
"if",
"(",
"!",
"el",
".",
"namespaceURI",
")",
"{",
"if",
"(",
"!",
"cfg",
".",
"attributes",
")",
"cfg",
".",
"attributes",
"=",
"{",
"}",
";",
"cfg",
".",
"attributes",
"[",
"el",
".",
"localName",
"]",
"=",
"el",
".",
"childNodes",
".",
"length",
"?",
"parse",
"(",
"el",
")",
":",
"copyXmlAttributes",
"(",
"el",
")",
";",
"}",
"else",
"if",
"(",
"el",
".",
"namespaceURI",
"===",
"'urn:flora:options'",
")",
"{",
"if",
"(",
"el",
".",
"localName",
"===",
"'dataSource'",
")",
"{",
"const",
"dataSource",
"=",
"getDataSource",
"(",
"el",
")",
";",
"if",
"(",
"!",
"cfg",
".",
"dataSources",
")",
"cfg",
".",
"dataSources",
"=",
"{",
"}",
";",
"if",
"(",
"cfg",
".",
"dataSources",
"[",
"dataSource",
".",
"name",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"dataSource",
".",
"name",
"}",
"`",
")",
";",
"}",
"cfg",
".",
"dataSources",
"[",
"dataSource",
".",
"name",
"]",
"=",
"dataSource",
".",
"config",
";",
"}",
"if",
"(",
"el",
".",
"localName",
"===",
"'subFilter'",
")",
"{",
"if",
"(",
"!",
"cfg",
".",
"subFilters",
")",
"cfg",
".",
"subFilters",
"=",
"[",
"]",
";",
"cfg",
".",
"subFilters",
".",
"push",
"(",
"copyXmlAttributes",
"(",
"el",
")",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"el",
".",
"nodeType",
"===",
"TEXT_NODE",
"&&",
"el",
".",
"textContent",
".",
"trim",
"(",
")",
".",
"length",
">",
"0",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"el",
".",
"textContent",
".",
"trim",
"(",
")",
"}",
"`",
")",
";",
"}",
"}",
"return",
"cfg",
";",
"}"
] | Return DataSources, attributes and sub-resources as plain JS object.
@param {Node} node
@return {Object}
@private | [
"Return",
"DataSources",
"attributes",
"and",
"sub",
"-",
"resources",
"as",
"plain",
"JS",
"object",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/xml-reader.js#L102-L133 | train |
godmodelabs/flora | lib/result-builder.js | getAttribute | function getAttribute(path, attrNode) {
path.forEach(attrName => {
if (!(attrNode.attributes && attrNode.attributes[attrName])) {
throw new ImplementationError(`Result-Builder: Unknown attribute "${path.join('.')}"`);
}
attrNode = attrNode.attributes[attrName];
});
return attrNode;
} | javascript | function getAttribute(path, attrNode) {
path.forEach(attrName => {
if (!(attrNode.attributes && attrNode.attributes[attrName])) {
throw new ImplementationError(`Result-Builder: Unknown attribute "${path.join('.')}"`);
}
attrNode = attrNode.attributes[attrName];
});
return attrNode;
} | [
"function",
"getAttribute",
"(",
"path",
",",
"attrNode",
")",
"{",
"path",
".",
"forEach",
"(",
"attrName",
"=>",
"{",
"if",
"(",
"!",
"(",
"attrNode",
".",
"attributes",
"&&",
"attrNode",
".",
"attributes",
"[",
"attrName",
"]",
")",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"path",
".",
"join",
"(",
"'.'",
")",
"}",
"`",
")",
";",
"}",
"attrNode",
"=",
"attrNode",
".",
"attributes",
"[",
"attrName",
"]",
";",
"}",
")",
";",
"return",
"attrNode",
";",
"}"
] | Resolve attribute path relative to attrNode and return child attrNode
@param {Array} path Array of attribute-names representing the path
@param {Object} attrNode Root node where to start resolving
@private | [
"Resolve",
"attribute",
"path",
"relative",
"to",
"attrNode",
"and",
"return",
"child",
"attrNode"
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/result-builder.js#L14-L22 | train |
godmodelabs/flora | lib/result-builder.js | preprocessRawResults | function preprocessRawResults(rawResults, resolvedConfig) {
rawResults.forEach((rawResult, resultId) => {
if (!rawResult.attributePath) return; // e.g. sub-filter results don't need indexing
// link resultIds into attribute tree (per DataSource):
const attrNode = getAttribute(rawResult.attributePath, resolvedConfig);
attrNode.dataSources[rawResult.dataSourceName].resultId = resultId;
// index rows by childKey if available
// (top-level result has no childKey and does not need to be indexed):
if (rawResult.childKey) {
const keyAttr = rawResult.childKey.length === 1 ? rawResult.childKey[0] : null;
rawResult.indexedData = {};
rawResult.data.forEach((row, i) => {
function dereferenceKeyAttr(keyAttrib) {
const keyVal = row[keyAttrib];
if (keyVal === undefined) {
const attrPath =
rawResult.attributePath.length > 0 ? rawResult.attributePath.join('.') : '{root}';
throw new DataError(
`Result-row ${i} of "${attrPath}" (DataSource "${
rawResult.dataSourceName
}") misses child key attribute "${keyAttr}"`
);
}
return keyVal;
}
const key = keyAttr
? '' + dereferenceKeyAttr(keyAttr) // speed up non-composite keys
: rawResult.childKey.map(dereferenceKeyAttr).join(keySeparator);
if (!rawResult.uniqueChildKey) {
if (!rawResult.indexedData[key]) rawResult.indexedData[key] = [];
rawResult.indexedData[key].push(row);
} else {
if (rawResult.indexedData[key]) {
const attrPath =
rawResult.attributePath.length > 0 ? rawResult.attributePath.join('.') : '{root}';
throw new DataError(
`Result-row ${i} of "${attrPath}" (DataSource "${
rawResult.dataSourceName
}") has duplicate child key "${key}"`
);
}
rawResult.indexedData[key] = row;
}
});
}
});
} | javascript | function preprocessRawResults(rawResults, resolvedConfig) {
rawResults.forEach((rawResult, resultId) => {
if (!rawResult.attributePath) return; // e.g. sub-filter results don't need indexing
// link resultIds into attribute tree (per DataSource):
const attrNode = getAttribute(rawResult.attributePath, resolvedConfig);
attrNode.dataSources[rawResult.dataSourceName].resultId = resultId;
// index rows by childKey if available
// (top-level result has no childKey and does not need to be indexed):
if (rawResult.childKey) {
const keyAttr = rawResult.childKey.length === 1 ? rawResult.childKey[0] : null;
rawResult.indexedData = {};
rawResult.data.forEach((row, i) => {
function dereferenceKeyAttr(keyAttrib) {
const keyVal = row[keyAttrib];
if (keyVal === undefined) {
const attrPath =
rawResult.attributePath.length > 0 ? rawResult.attributePath.join('.') : '{root}';
throw new DataError(
`Result-row ${i} of "${attrPath}" (DataSource "${
rawResult.dataSourceName
}") misses child key attribute "${keyAttr}"`
);
}
return keyVal;
}
const key = keyAttr
? '' + dereferenceKeyAttr(keyAttr) // speed up non-composite keys
: rawResult.childKey.map(dereferenceKeyAttr).join(keySeparator);
if (!rawResult.uniqueChildKey) {
if (!rawResult.indexedData[key]) rawResult.indexedData[key] = [];
rawResult.indexedData[key].push(row);
} else {
if (rawResult.indexedData[key]) {
const attrPath =
rawResult.attributePath.length > 0 ? rawResult.attributePath.join('.') : '{root}';
throw new DataError(
`Result-row ${i} of "${attrPath}" (DataSource "${
rawResult.dataSourceName
}") has duplicate child key "${key}"`
);
}
rawResult.indexedData[key] = row;
}
});
}
});
} | [
"function",
"preprocessRawResults",
"(",
"rawResults",
",",
"resolvedConfig",
")",
"{",
"rawResults",
".",
"forEach",
"(",
"(",
"rawResult",
",",
"resultId",
")",
"=>",
"{",
"if",
"(",
"!",
"rawResult",
".",
"attributePath",
")",
"return",
";",
"const",
"attrNode",
"=",
"getAttribute",
"(",
"rawResult",
".",
"attributePath",
",",
"resolvedConfig",
")",
";",
"attrNode",
".",
"dataSources",
"[",
"rawResult",
".",
"dataSourceName",
"]",
".",
"resultId",
"=",
"resultId",
";",
"if",
"(",
"rawResult",
".",
"childKey",
")",
"{",
"const",
"keyAttr",
"=",
"rawResult",
".",
"childKey",
".",
"length",
"===",
"1",
"?",
"rawResult",
".",
"childKey",
"[",
"0",
"]",
":",
"null",
";",
"rawResult",
".",
"indexedData",
"=",
"{",
"}",
";",
"rawResult",
".",
"data",
".",
"forEach",
"(",
"(",
"row",
",",
"i",
")",
"=>",
"{",
"function",
"dereferenceKeyAttr",
"(",
"keyAttrib",
")",
"{",
"const",
"keyVal",
"=",
"row",
"[",
"keyAttrib",
"]",
";",
"if",
"(",
"keyVal",
"===",
"undefined",
")",
"{",
"const",
"attrPath",
"=",
"rawResult",
".",
"attributePath",
".",
"length",
">",
"0",
"?",
"rawResult",
".",
"attributePath",
".",
"join",
"(",
"'.'",
")",
":",
"'{root}'",
";",
"throw",
"new",
"DataError",
"(",
"`",
"${",
"i",
"}",
"${",
"attrPath",
"}",
"${",
"rawResult",
".",
"dataSourceName",
"}",
"${",
"keyAttr",
"}",
"`",
")",
";",
"}",
"return",
"keyVal",
";",
"}",
"const",
"key",
"=",
"keyAttr",
"?",
"''",
"+",
"dereferenceKeyAttr",
"(",
"keyAttr",
")",
":",
"rawResult",
".",
"childKey",
".",
"map",
"(",
"dereferenceKeyAttr",
")",
".",
"join",
"(",
"keySeparator",
")",
";",
"if",
"(",
"!",
"rawResult",
".",
"uniqueChildKey",
")",
"{",
"if",
"(",
"!",
"rawResult",
".",
"indexedData",
"[",
"key",
"]",
")",
"rawResult",
".",
"indexedData",
"[",
"key",
"]",
"=",
"[",
"]",
";",
"rawResult",
".",
"indexedData",
"[",
"key",
"]",
".",
"push",
"(",
"row",
")",
";",
"}",
"else",
"{",
"if",
"(",
"rawResult",
".",
"indexedData",
"[",
"key",
"]",
")",
"{",
"const",
"attrPath",
"=",
"rawResult",
".",
"attributePath",
".",
"length",
">",
"0",
"?",
"rawResult",
".",
"attributePath",
".",
"join",
"(",
"'.'",
")",
":",
"'{root}'",
";",
"throw",
"new",
"DataError",
"(",
"`",
"${",
"i",
"}",
"${",
"attrPath",
"}",
"${",
"rawResult",
".",
"dataSourceName",
"}",
"${",
"key",
"}",
"`",
")",
";",
"}",
"rawResult",
".",
"indexedData",
"[",
"key",
"]",
"=",
"row",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | Link resultIds into attribute tree and index rows by key.
@private | [
"Link",
"resultIds",
"into",
"attribute",
"tree",
"and",
"index",
"rows",
"by",
"key",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/result-builder.js#L29-L79 | train |
godmodelabs/flora | lib/config-parser.js | parseNode | function parseNode(attrNode, parsers, context) {
const attrNames = Object.keys(attrNode);
const errorContext = context.errorContext;
Object.keys(parsers).forEach(attrName => {
const parser = parsers[attrName];
context.errorContext = ` (option "${attrName}"${errorContext})`;
removeValue(attrNames, attrName);
if (attrName in attrNode && parser !== null) {
attrNode[attrName] = parser(attrNode[attrName], context);
}
});
context.errorContext = errorContext;
if (attrNames.length > 0) {
throw new ImplementationError(`Invalid option "${attrNames.join(', ')}"${context.errorContext}`);
}
} | javascript | function parseNode(attrNode, parsers, context) {
const attrNames = Object.keys(attrNode);
const errorContext = context.errorContext;
Object.keys(parsers).forEach(attrName => {
const parser = parsers[attrName];
context.errorContext = ` (option "${attrName}"${errorContext})`;
removeValue(attrNames, attrName);
if (attrName in attrNode && parser !== null) {
attrNode[attrName] = parser(attrNode[attrName], context);
}
});
context.errorContext = errorContext;
if (attrNames.length > 0) {
throw new ImplementationError(`Invalid option "${attrNames.join(', ')}"${context.errorContext}`);
}
} | [
"function",
"parseNode",
"(",
"attrNode",
",",
"parsers",
",",
"context",
")",
"{",
"const",
"attrNames",
"=",
"Object",
".",
"keys",
"(",
"attrNode",
")",
";",
"const",
"errorContext",
"=",
"context",
".",
"errorContext",
";",
"Object",
".",
"keys",
"(",
"parsers",
")",
".",
"forEach",
"(",
"attrName",
"=>",
"{",
"const",
"parser",
"=",
"parsers",
"[",
"attrName",
"]",
";",
"context",
".",
"errorContext",
"=",
"`",
"${",
"attrName",
"}",
"${",
"errorContext",
"}",
"`",
";",
"removeValue",
"(",
"attrNames",
",",
"attrName",
")",
";",
"if",
"(",
"attrName",
"in",
"attrNode",
"&&",
"parser",
"!==",
"null",
")",
"{",
"attrNode",
"[",
"attrName",
"]",
"=",
"parser",
"(",
"attrNode",
"[",
"attrName",
"]",
",",
"context",
")",
";",
"}",
"}",
")",
";",
"context",
".",
"errorContext",
"=",
"errorContext",
";",
"if",
"(",
"attrNames",
".",
"length",
">",
"0",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"attrNames",
".",
"join",
"(",
"', '",
")",
"}",
"${",
"context",
".",
"errorContext",
"}",
"`",
")",
";",
"}",
"}"
] | Meta function which calls the defined parsers for current node and fails
on additionally defined options.
@private | [
"Meta",
"function",
"which",
"calls",
"the",
"defined",
"parsers",
"for",
"current",
"node",
"and",
"fails",
"on",
"additionally",
"defined",
"options",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/config-parser.js#L39-L59 | train |
godmodelabs/flora | lib/config-parser.js | checkIdentifier | function checkIdentifier(str, context) {
if (!/^[a-zA-Z_][a-zA-Z_0-9]*$/.test(str)) {
throw new ImplementationError(`Invalid identifier "${str}"${context.errorContext}`);
}
return str;
} | javascript | function checkIdentifier(str, context) {
if (!/^[a-zA-Z_][a-zA-Z_0-9]*$/.test(str)) {
throw new ImplementationError(`Invalid identifier "${str}"${context.errorContext}`);
}
return str;
} | [
"function",
"checkIdentifier",
"(",
"str",
",",
"context",
")",
"{",
"if",
"(",
"!",
"/",
"^[a-zA-Z_][a-zA-Z_0-9]*$",
"/",
".",
"test",
"(",
"str",
")",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"str",
"}",
"${",
"context",
".",
"errorContext",
"}",
"`",
")",
";",
"}",
"return",
"str",
";",
"}"
] | Generates an error for invalid identifier strings. Identifiers contain letters,
numbers and underscore - and do not start with a number.
@private | [
"Generates",
"an",
"error",
"for",
"invalid",
"identifier",
"strings",
".",
"Identifiers",
"contain",
"letters",
"numbers",
"and",
"underscore",
"-",
"and",
"do",
"not",
"start",
"with",
"a",
"number",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/config-parser.js#L67-L72 | train |
godmodelabs/flora | lib/config-parser.js | parseAttributePath | function parseAttributePath(attrPath, context) {
const parsed = attrPath.split('.');
parsed.forEach(item => checkIdentifier(item, context));
return parsed;
} | javascript | function parseAttributePath(attrPath, context) {
const parsed = attrPath.split('.');
parsed.forEach(item => checkIdentifier(item, context));
return parsed;
} | [
"function",
"parseAttributePath",
"(",
"attrPath",
",",
"context",
")",
"{",
"const",
"parsed",
"=",
"attrPath",
".",
"split",
"(",
"'.'",
")",
";",
"parsed",
".",
"forEach",
"(",
"item",
"=>",
"checkIdentifier",
"(",
"item",
",",
"context",
")",
")",
";",
"return",
"parsed",
";",
"}"
] | Parses "id", "meta.id".
@private | [
"Parses",
"id",
"meta",
".",
"id",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/config-parser.js#L79-L83 | train |
godmodelabs/flora | lib/config-parser.js | parsePrimaryKey | function parsePrimaryKey(attrPathList, context) {
return attrPathList.split(',').map(attrPath => parseAttributePath(attrPath, context));
} | javascript | function parsePrimaryKey(attrPathList, context) {
return attrPathList.split(',').map(attrPath => parseAttributePath(attrPath, context));
} | [
"function",
"parsePrimaryKey",
"(",
"attrPathList",
",",
"context",
")",
"{",
"return",
"attrPathList",
".",
"split",
"(",
"','",
")",
".",
"map",
"(",
"attrPath",
"=>",
"parseAttributePath",
"(",
"attrPath",
",",
"context",
")",
")",
";",
"}"
] | Parses "id", "meta.id,meta.context".
@private | [
"Parses",
"id",
"meta",
".",
"id",
"meta",
".",
"context",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/config-parser.js#L90-L92 | train |
godmodelabs/flora | lib/config-parser.js | checkWhitelist | function checkWhitelist(str, whitelist, context) {
if (whitelist.indexOf(str) === -1) {
throw new ImplementationError(
'Invalid "' + str + '" (allowed: ' + whitelist.join(', ') + ')' + context.errorContext
);
}
return str;
} | javascript | function checkWhitelist(str, whitelist, context) {
if (whitelist.indexOf(str) === -1) {
throw new ImplementationError(
'Invalid "' + str + '" (allowed: ' + whitelist.join(', ') + ')' + context.errorContext
);
}
return str;
} | [
"function",
"checkWhitelist",
"(",
"str",
",",
"whitelist",
",",
"context",
")",
"{",
"if",
"(",
"whitelist",
".",
"indexOf",
"(",
"str",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"'Invalid \"'",
"+",
"str",
"+",
"'\" (allowed: '",
"+",
"whitelist",
".",
"join",
"(",
"', '",
")",
"+",
"')'",
"+",
"context",
".",
"errorContext",
")",
";",
"}",
"return",
"str",
";",
"}"
] | Validates string against whitelist.
@private | [
"Validates",
"string",
"against",
"whitelist",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/config-parser.js#L132-L139 | train |
godmodelabs/flora | lib/config-parser.js | parseList | function parseList(list, whitelist, context) {
const parsed = list.split(',');
parsed.forEach(item => checkWhitelist(item, whitelist, context));
return parsed;
} | javascript | function parseList(list, whitelist, context) {
const parsed = list.split(',');
parsed.forEach(item => checkWhitelist(item, whitelist, context));
return parsed;
} | [
"function",
"parseList",
"(",
"list",
",",
"whitelist",
",",
"context",
")",
"{",
"const",
"parsed",
"=",
"list",
".",
"split",
"(",
"','",
")",
";",
"parsed",
".",
"forEach",
"(",
"item",
"=>",
"checkWhitelist",
"(",
"item",
",",
"whitelist",
",",
"context",
")",
")",
";",
"return",
"parsed",
";",
"}"
] | Parses a list of comma-separated strings and validates them against whitelist.
@private | [
"Parses",
"a",
"list",
"of",
"comma",
"-",
"separated",
"strings",
"and",
"validates",
"them",
"against",
"whitelist",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/config-parser.js#L157-L161 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.