id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
54,200 | coolony/inverter | inverter.js | function(str){
return str.replace(BORDER_RADIUS_RE,
function(){
var ret = 'border-radius' + arguments[1]
+ ':'
+ arguments[2]
+ reorderBorderRadius(arguments[3],
arguments[4],
arguments[5],
arguments[6]);
if(arguments[7])
ret += ' / ' + reorderBorderRadius(arguments[8],
arguments[9],
arguments[10],
arguments[11]);
return ret;
}
);
} | javascript | function(str){
return str.replace(BORDER_RADIUS_RE,
function(){
var ret = 'border-radius' + arguments[1]
+ ':'
+ arguments[2]
+ reorderBorderRadius(arguments[3],
arguments[4],
arguments[5],
arguments[6]);
if(arguments[7])
ret += ' / ' + reorderBorderRadius(arguments[8],
arguments[9],
arguments[10],
arguments[11]);
return ret;
}
);
} | [
"function",
"(",
"str",
")",
"{",
"return",
"str",
".",
"replace",
"(",
"BORDER_RADIUS_RE",
",",
"function",
"(",
")",
"{",
"var",
"ret",
"=",
"'border-radius'",
"+",
"arguments",
"[",
"1",
"]",
"+",
"':'",
"+",
"arguments",
"[",
"2",
"]",
"+",
"reorderBorderRadius",
"(",
"arguments",
"[",
"3",
"]",
",",
"arguments",
"[",
"4",
"]",
",",
"arguments",
"[",
"5",
"]",
",",
"arguments",
"[",
"6",
"]",
")",
";",
"if",
"(",
"arguments",
"[",
"7",
"]",
")",
"ret",
"+=",
"' / '",
"+",
"reorderBorderRadius",
"(",
"arguments",
"[",
"8",
"]",
",",
"arguments",
"[",
"9",
"]",
",",
"arguments",
"[",
"10",
"]",
",",
"arguments",
"[",
"11",
"]",
")",
";",
"return",
"ret",
";",
"}",
")",
";",
"}"
] | Fixes border radius This case is special because of the particularities of border-radius | [
"Fixes",
"border",
"radius",
"This",
"case",
"is",
"special",
"because",
"of",
"the",
"particularities",
"of",
"border",
"-",
"radius"
] | 77224da8675c36fd30fea88f4698f7e43674f83c | https://github.com/coolony/inverter/blob/77224da8675c36fd30fea88f4698f7e43674f83c/inverter.js#L113-L132 |
|
54,201 | coolony/inverter | inverter.js | invert | function invert(str, options){
if(!options) options = {};
if(!options.exclude) options.exclude = [];
for(var rule in rules) {
// Pass excluded rules
if(options.exclude.indexOf(rule) != -1) continue;
// Run rule
str = rules[rule](str, options);
}
return str;
} | javascript | function invert(str, options){
if(!options) options = {};
if(!options.exclude) options.exclude = [];
for(var rule in rules) {
// Pass excluded rules
if(options.exclude.indexOf(rule) != -1) continue;
// Run rule
str = rules[rule](str, options);
}
return str;
} | [
"function",
"invert",
"(",
"str",
",",
"options",
")",
"{",
"if",
"(",
"!",
"options",
")",
"options",
"=",
"{",
"}",
";",
"if",
"(",
"!",
"options",
".",
"exclude",
")",
"options",
".",
"exclude",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"rule",
"in",
"rules",
")",
"{",
"// Pass excluded rules",
"if",
"(",
"options",
".",
"exclude",
".",
"indexOf",
"(",
"rule",
")",
"!=",
"-",
"1",
")",
"continue",
";",
"// Run rule",
"str",
"=",
"rules",
"[",
"rule",
"]",
"(",
"str",
",",
"options",
")",
";",
"}",
"return",
"str",
";",
"}"
] | Inverts a CSS string
@param {String} str CSS string
@param {Object} options (Optional)
@return {String} Inverted CSS
@api public | [
"Inverts",
"a",
"CSS",
"string"
] | 77224da8675c36fd30fea88f4698f7e43674f83c | https://github.com/coolony/inverter/blob/77224da8675c36fd30fea88f4698f7e43674f83c/inverter.js#L182-L199 |
54,202 | coolony/inverter | inverter.js | reorderBorderRadius | function reorderBorderRadius(p1, p2, p3, p4){
if(p4)
return [p2, p1, p4, p3].join(' ');
if(p3)
return [p2, p1, p2, p3].join(' ');
if(p2)
return [p2, p1].join(' ');
else
return p1;
} | javascript | function reorderBorderRadius(p1, p2, p3, p4){
if(p4)
return [p2, p1, p4, p3].join(' ');
if(p3)
return [p2, p1, p2, p3].join(' ');
if(p2)
return [p2, p1].join(' ');
else
return p1;
} | [
"function",
"reorderBorderRadius",
"(",
"p1",
",",
"p2",
",",
"p3",
",",
"p4",
")",
"{",
"if",
"(",
"p4",
")",
"return",
"[",
"p2",
",",
"p1",
",",
"p4",
",",
"p3",
"]",
".",
"join",
"(",
"' '",
")",
";",
"if",
"(",
"p3",
")",
"return",
"[",
"p2",
",",
"p1",
",",
"p2",
",",
"p3",
"]",
".",
"join",
"(",
"' '",
")",
";",
"if",
"(",
"p2",
")",
"return",
"[",
"p2",
",",
"p1",
"]",
".",
"join",
"(",
"' '",
")",
";",
"else",
"return",
"p1",
";",
"}"
] | Reorders border radius values for opposite direction
reorderBorderRadius(A, B, C, D) -> 'B A D C'
reorderBorderRadius(A, B, C) -> 'B A B C'
reorderBorderRadius(A, B) -> 'B A'
reorderBorderRadius(A) -> 'A'
@param {String} p1 First element
@param {String} p2 (Optional) Second element
@param {String} p3 (Optional) Third element
@param {String} p4 (Optional) Fourth element
@return {String} Result
@api private | [
"Reorders",
"border",
"radius",
"values",
"for",
"opposite",
"direction"
] | 77224da8675c36fd30fea88f4698f7e43674f83c | https://github.com/coolony/inverter/blob/77224da8675c36fd30fea88f4698f7e43674f83c/inverter.js#L218-L227 |
54,203 | coolony/inverter | inverter.js | fixGradient | function fixGradient(str) {
var ret = str.replace(GRADIENT_REPLACE_RE, function($0, $1, $2){
return $1 ?
$0 :
($2 == 'right') ?
'left' :
($2 == 'left') ?
'right' :
(parseInt($2) % 180 == 0) ?
$2 :
($2.substr(0,1) == '-') ?
$2.substr(1) :
('-' + $2);
});
return ret;
} | javascript | function fixGradient(str) {
var ret = str.replace(GRADIENT_REPLACE_RE, function($0, $1, $2){
return $1 ?
$0 :
($2 == 'right') ?
'left' :
($2 == 'left') ?
'right' :
(parseInt($2) % 180 == 0) ?
$2 :
($2.substr(0,1) == '-') ?
$2.substr(1) :
('-' + $2);
});
return ret;
} | [
"function",
"fixGradient",
"(",
"str",
")",
"{",
"var",
"ret",
"=",
"str",
".",
"replace",
"(",
"GRADIENT_REPLACE_RE",
",",
"function",
"(",
"$0",
",",
"$1",
",",
"$2",
")",
"{",
"return",
"$1",
"?",
"$0",
":",
"(",
"$2",
"==",
"'right'",
")",
"?",
"'left'",
":",
"(",
"$2",
"==",
"'left'",
")",
"?",
"'right'",
":",
"(",
"parseInt",
"(",
"$2",
")",
"%",
"180",
"==",
"0",
")",
"?",
"$2",
":",
"(",
"$2",
".",
"substr",
"(",
"0",
",",
"1",
")",
"==",
"'-'",
")",
"?",
"$2",
".",
"substr",
"(",
"1",
")",
":",
"(",
"'-'",
"+",
"$2",
")",
";",
"}",
")",
";",
"return",
"ret",
";",
"}"
] | Fixes most gradient definitions
Replaces `left` with `right`, `X(X(X))deg` to `-X(X(X))deg`, and the opposites
fixGradient("-webkit-gradient(linear, left bottom, right top, color-stop(0%,#000), color-stop(100%,#fff))")
-> "fixGradient("-webkit-gradient(linear, right bottom, left top, color-stop(0%,#000), color-stop(100%,#fff))")"
fixGradient("background: linear-gradient(45deg, #000 0%, #fff 100%)")
-> "linear-gradient(-45deg, #000 0%,#fff 100%)" | [
"Fixes",
"most",
"gradient",
"definitions"
] | 77224da8675c36fd30fea88f4698f7e43674f83c | https://github.com/coolony/inverter/blob/77224da8675c36fd30fea88f4698f7e43674f83c/inverter.js#L241-L256 |
54,204 | thlorenz/kodieren | kodieren.js | bitsToLayout | function bitsToLayout(bits) {
var idx = 0
const map = {}
for (const [ name, b ] of bits) {
const mask = maskForBits(b)
map[name] = [ idx, mask ]
idx += b
}
return map
} | javascript | function bitsToLayout(bits) {
var idx = 0
const map = {}
for (const [ name, b ] of bits) {
const mask = maskForBits(b)
map[name] = [ idx, mask ]
idx += b
}
return map
} | [
"function",
"bitsToLayout",
"(",
"bits",
")",
"{",
"var",
"idx",
"=",
"0",
"const",
"map",
"=",
"{",
"}",
"for",
"(",
"const",
"[",
"name",
",",
"b",
"]",
"of",
"bits",
")",
"{",
"const",
"mask",
"=",
"maskForBits",
"(",
"b",
")",
"map",
"[",
"name",
"]",
"=",
"[",
"idx",
",",
"mask",
"]",
"idx",
"+=",
"b",
"}",
"return",
"map",
"}"
] | Takes a table of properties with bit length and derives bit layout from it.
The bit layout is a hash map indexed by property name and each entry contains
the index of the property in the bit field and it's mask needed to isolate it.
### Example:
```
bitsToLayout([ [ 'foo', 2 ], [ 'bar', 4 ] ])
// => { foo: [ 0, 0b11 ], bar: [ 2, 0b1111 ] }
```
@name bitsToLayout
@param {Array.<Array<String, Number>>} bits
@returns {Object.<Array.<Number, Number>>} | [
"Takes",
"a",
"table",
"of",
"properties",
"with",
"bit",
"length",
"and",
"derives",
"bit",
"layout",
"from",
"it",
".",
"The",
"bit",
"layout",
"is",
"a",
"hash",
"map",
"indexed",
"by",
"property",
"name",
"and",
"each",
"entry",
"contains",
"the",
"index",
"of",
"the",
"property",
"in",
"the",
"bit",
"field",
"and",
"it",
"s",
"mask",
"needed",
"to",
"isolate",
"it",
"."
] | 2310ae3a8d38962deee8d0140092066f3bd1fbb3 | https://github.com/thlorenz/kodieren/blob/2310ae3a8d38962deee8d0140092066f3bd1fbb3/kodieren.js#L53-L62 |
54,205 | insin/concur | examples/models.js | function(prototypeProps, constructorProps) {
if (typeof prototypeProps.Meta == 'undefined' ||
typeof prototypeProps.Meta.name == 'undefined') {
throw new Error('When extending Model, you must provide a name via a Meta object.')
}
var options = new ModelOptions(prototypeProps.Meta)
delete prototypeProps.Meta
for (var prop in prototypeProps) {
if (prototypeProps.hasOwnProperty(prop)) {
var field = prototypeProps[prop]
if (field instanceof Field || field instanceof Rel) {
field.name = prop
options.fields.push(field)
delete prototypeProps[prop]
}
}
}
prototypeProps._meta = constructorProps._meta = options
} | javascript | function(prototypeProps, constructorProps) {
if (typeof prototypeProps.Meta == 'undefined' ||
typeof prototypeProps.Meta.name == 'undefined') {
throw new Error('When extending Model, you must provide a name via a Meta object.')
}
var options = new ModelOptions(prototypeProps.Meta)
delete prototypeProps.Meta
for (var prop in prototypeProps) {
if (prototypeProps.hasOwnProperty(prop)) {
var field = prototypeProps[prop]
if (field instanceof Field || field instanceof Rel) {
field.name = prop
options.fields.push(field)
delete prototypeProps[prop]
}
}
}
prototypeProps._meta = constructorProps._meta = options
} | [
"function",
"(",
"prototypeProps",
",",
"constructorProps",
")",
"{",
"if",
"(",
"typeof",
"prototypeProps",
".",
"Meta",
"==",
"'undefined'",
"||",
"typeof",
"prototypeProps",
".",
"Meta",
".",
"name",
"==",
"'undefined'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'When extending Model, you must provide a name via a Meta object.'",
")",
"}",
"var",
"options",
"=",
"new",
"ModelOptions",
"(",
"prototypeProps",
".",
"Meta",
")",
"delete",
"prototypeProps",
".",
"Meta",
"for",
"(",
"var",
"prop",
"in",
"prototypeProps",
")",
"{",
"if",
"(",
"prototypeProps",
".",
"hasOwnProperty",
"(",
"prop",
")",
")",
"{",
"var",
"field",
"=",
"prototypeProps",
"[",
"prop",
"]",
"if",
"(",
"field",
"instanceof",
"Field",
"||",
"field",
"instanceof",
"Rel",
")",
"{",
"field",
".",
"name",
"=",
"prop",
"options",
".",
"fields",
".",
"push",
"(",
"field",
")",
"delete",
"prototypeProps",
"[",
"prop",
"]",
"}",
"}",
"}",
"prototypeProps",
".",
"_meta",
"=",
"constructorProps",
".",
"_meta",
"=",
"options",
"}"
] | Prepares a ModelOptions for the extended Model and places it in a
_meta property on the prototype and constructor. | [
"Prepares",
"a",
"ModelOptions",
"for",
"the",
"extended",
"Model",
"and",
"places",
"it",
"in",
"a",
"_meta",
"property",
"on",
"the",
"prototype",
"and",
"constructor",
"."
] | 86e816f1a0cb90ec227371bee065cc76e7234b7c | https://github.com/insin/concur/blob/86e816f1a0cb90ec227371bee065cc76e7234b7c/examples/models.js#L38-L59 |
|
54,206 | Tarrask/sails-generate-webpack-vue | vueAdapter.js | run | function run(cb) {
// check if template is local
if (/^[./]|(\w:)/.test(template)) {
var templatePath = template.charAt(0) === '/' || /^\w:/.test(template)
? template
: path.normalize(path.join(process.cwd(), template))
if (exists(templatePath)) {
generate(name, templatePath, to, cb)
} else {
logger.fatal('Local template "%s" not found.', template)
}
} else {
checkVersion(function () {
if (!hasSlash) {
// use official templates
var officialTemplate = 'vuejs-templates/' + template
if (template.indexOf('#') !== -1) {
downloadAndGenerate(officialTemplate, cb)
} else {
if (template.indexOf('-2.0') !== -1) {
warnings.v2SuffixTemplatesDeprecated(template, inPlace ? '' : name)
return
}
warnings.v2BranchIsNowDefault(template, inPlace ? '' : name)
downloadAndGenerate(officialTemplate, cb)
}
} else {
downloadAndGenerate(template, cb)
}
})
}
} | javascript | function run(cb) {
// check if template is local
if (/^[./]|(\w:)/.test(template)) {
var templatePath = template.charAt(0) === '/' || /^\w:/.test(template)
? template
: path.normalize(path.join(process.cwd(), template))
if (exists(templatePath)) {
generate(name, templatePath, to, cb)
} else {
logger.fatal('Local template "%s" not found.', template)
}
} else {
checkVersion(function () {
if (!hasSlash) {
// use official templates
var officialTemplate = 'vuejs-templates/' + template
if (template.indexOf('#') !== -1) {
downloadAndGenerate(officialTemplate, cb)
} else {
if (template.indexOf('-2.0') !== -1) {
warnings.v2SuffixTemplatesDeprecated(template, inPlace ? '' : name)
return
}
warnings.v2BranchIsNowDefault(template, inPlace ? '' : name)
downloadAndGenerate(officialTemplate, cb)
}
} else {
downloadAndGenerate(template, cb)
}
})
}
} | [
"function",
"run",
"(",
"cb",
")",
"{",
"// check if template is local",
"if",
"(",
"/",
"^[./]|(\\w:)",
"/",
".",
"test",
"(",
"template",
")",
")",
"{",
"var",
"templatePath",
"=",
"template",
".",
"charAt",
"(",
"0",
")",
"===",
"'/'",
"||",
"/",
"^\\w:",
"/",
".",
"test",
"(",
"template",
")",
"?",
"template",
":",
"path",
".",
"normalize",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"template",
")",
")",
"if",
"(",
"exists",
"(",
"templatePath",
")",
")",
"{",
"generate",
"(",
"name",
",",
"templatePath",
",",
"to",
",",
"cb",
")",
"}",
"else",
"{",
"logger",
".",
"fatal",
"(",
"'Local template \"%s\" not found.'",
",",
"template",
")",
"}",
"}",
"else",
"{",
"checkVersion",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"hasSlash",
")",
"{",
"// use official templates",
"var",
"officialTemplate",
"=",
"'vuejs-templates/'",
"+",
"template",
"if",
"(",
"template",
".",
"indexOf",
"(",
"'#'",
")",
"!==",
"-",
"1",
")",
"{",
"downloadAndGenerate",
"(",
"officialTemplate",
",",
"cb",
")",
"}",
"else",
"{",
"if",
"(",
"template",
".",
"indexOf",
"(",
"'-2.0'",
")",
"!==",
"-",
"1",
")",
"{",
"warnings",
".",
"v2SuffixTemplatesDeprecated",
"(",
"template",
",",
"inPlace",
"?",
"''",
":",
"name",
")",
"return",
"}",
"warnings",
".",
"v2BranchIsNowDefault",
"(",
"template",
",",
"inPlace",
"?",
"''",
":",
"name",
")",
"downloadAndGenerate",
"(",
"officialTemplate",
",",
"cb",
")",
"}",
"}",
"else",
"{",
"downloadAndGenerate",
"(",
"template",
",",
"cb",
")",
"}",
"}",
")",
"}",
"}"
] | Check, download and generate the project. | [
"Check",
"download",
"and",
"generate",
"the",
"project",
"."
] | 73f203bc8e3226edd13e21421adcddb938414eda | https://github.com/Tarrask/sails-generate-webpack-vue/blob/73f203bc8e3226edd13e21421adcddb938414eda/vueAdapter.js#L35-L67 |
54,207 | Tarrask/sails-generate-webpack-vue | vueAdapter.js | downloadAndGenerate | function downloadAndGenerate (template, cb) {
var spinner = ora('downloading template')
spinner.start()
download(template, tmp, { clone: clone }, function (err) {
spinner.stop()
if (err) logger.fatal('Failed to download repo ' + template + ': ' + err.message.trim())
generate(name, tmp, to, cb)
})
} | javascript | function downloadAndGenerate (template, cb) {
var spinner = ora('downloading template')
spinner.start()
download(template, tmp, { clone: clone }, function (err) {
spinner.stop()
if (err) logger.fatal('Failed to download repo ' + template + ': ' + err.message.trim())
generate(name, tmp, to, cb)
})
} | [
"function",
"downloadAndGenerate",
"(",
"template",
",",
"cb",
")",
"{",
"var",
"spinner",
"=",
"ora",
"(",
"'downloading template'",
")",
"spinner",
".",
"start",
"(",
")",
"download",
"(",
"template",
",",
"tmp",
",",
"{",
"clone",
":",
"clone",
"}",
",",
"function",
"(",
"err",
")",
"{",
"spinner",
".",
"stop",
"(",
")",
"if",
"(",
"err",
")",
"logger",
".",
"fatal",
"(",
"'Failed to download repo '",
"+",
"template",
"+",
"': '",
"+",
"err",
".",
"message",
".",
"trim",
"(",
")",
")",
"generate",
"(",
"name",
",",
"tmp",
",",
"to",
",",
"cb",
")",
"}",
")",
"}"
] | Download a generate from a template repo.
@param {String} template | [
"Download",
"a",
"generate",
"from",
"a",
"template",
"repo",
"."
] | 73f203bc8e3226edd13e21421adcddb938414eda | https://github.com/Tarrask/sails-generate-webpack-vue/blob/73f203bc8e3226edd13e21421adcddb938414eda/vueAdapter.js#L75-L83 |
54,208 | olivejs/olive | lib/actions/new.js | validateSeed | function validateSeed() {
return Q.Promise(function(resolve, reject) {
https.get('https://github.com/olivejs/seed-' + options.seed, function(res) {
if (res.statusCode === 200) {
resolve('>> seed exists');
} else {
reject(new Error('Invalid seed: ' + options.seed));
}
}).on('error', function(err) {
logger.error('\n %s\n', err.message);
reject(err);
});
});
} | javascript | function validateSeed() {
return Q.Promise(function(resolve, reject) {
https.get('https://github.com/olivejs/seed-' + options.seed, function(res) {
if (res.statusCode === 200) {
resolve('>> seed exists');
} else {
reject(new Error('Invalid seed: ' + options.seed));
}
}).on('error', function(err) {
logger.error('\n %s\n', err.message);
reject(err);
});
});
} | [
"function",
"validateSeed",
"(",
")",
"{",
"return",
"Q",
".",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"https",
".",
"get",
"(",
"'https://github.com/olivejs/seed-'",
"+",
"options",
".",
"seed",
",",
"function",
"(",
"res",
")",
"{",
"if",
"(",
"res",
".",
"statusCode",
"===",
"200",
")",
"{",
"resolve",
"(",
"'>> seed exists'",
")",
";",
"}",
"else",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'Invalid seed: '",
"+",
"options",
".",
"seed",
")",
")",
";",
"}",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"'\\n %s\\n'",
",",
"err",
".",
"message",
")",
";",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Checks whether a seed exists
@param {String} seed Name of the seed
@return {Promise} | [
"Checks",
"whether",
"a",
"seed",
"exists"
] | ce7bd3fb4ef94d0b862276cbcee83b481ea23cef | https://github.com/olivejs/olive/blob/ce7bd3fb4ef94d0b862276cbcee83b481ea23cef/lib/actions/new.js#L17-L30 |
54,209 | AndiDittrich/Node.mysql-magic | lib/pool-connection.js | exposeAPI | function exposeAPI(connection){
return {
query: function(stmt, params){
return _query(connection, stmt, params);
},
insert: function(table, data){
return _insert(connection, table, data);
},
fetchRow: function(stmt, params){
return _fetchRow(connection, stmt, params);
},
fetchAll: function(stmt, params){
return _fetchAll(connection, stmt, params);
},
release: function(){
return connection.release();
}
};
} | javascript | function exposeAPI(connection){
return {
query: function(stmt, params){
return _query(connection, stmt, params);
},
insert: function(table, data){
return _insert(connection, table, data);
},
fetchRow: function(stmt, params){
return _fetchRow(connection, stmt, params);
},
fetchAll: function(stmt, params){
return _fetchAll(connection, stmt, params);
},
release: function(){
return connection.release();
}
};
} | [
"function",
"exposeAPI",
"(",
"connection",
")",
"{",
"return",
"{",
"query",
":",
"function",
"(",
"stmt",
",",
"params",
")",
"{",
"return",
"_query",
"(",
"connection",
",",
"stmt",
",",
"params",
")",
";",
"}",
",",
"insert",
":",
"function",
"(",
"table",
",",
"data",
")",
"{",
"return",
"_insert",
"(",
"connection",
",",
"table",
",",
"data",
")",
";",
"}",
",",
"fetchRow",
":",
"function",
"(",
"stmt",
",",
"params",
")",
"{",
"return",
"_fetchRow",
"(",
"connection",
",",
"stmt",
",",
"params",
")",
";",
"}",
",",
"fetchAll",
":",
"function",
"(",
"stmt",
",",
"params",
")",
"{",
"return",
"_fetchAll",
"(",
"connection",
",",
"stmt",
",",
"params",
")",
";",
"}",
",",
"release",
":",
"function",
"(",
")",
"{",
"return",
"connection",
".",
"release",
"(",
")",
";",
"}",
"}",
";",
"}"
] | expose async api wrapper | [
"expose",
"async",
"api",
"wrapper"
] | f9783ac93f4a5744407781d7875ae68cad58cc48 | https://github.com/AndiDittrich/Node.mysql-magic/blob/f9783ac93f4a5744407781d7875ae68cad58cc48/lib/pool-connection.js#L7-L30 |
54,210 | robgietema/twist | public/libs/obviel/1.0b5/obviel-sync.js | function(config, defaults) {
var key, subdefaults, subconfig;
for (key in defaults) {
subdefaults = defaults[key];
subconfig = config[key];
if ($.isPlainObject(subdefaults)) {
if (!$.isPlainObject(subconfig)) {
subconfig = config[key] = {};
}
defaultsUpdater(subconfig, subdefaults);
// } else if (subconfig === undefined) {
// config[key] = null;
// }
} else {
if (subconfig === undefined) {
config[key] = subdefaults;
}
}
}
} | javascript | function(config, defaults) {
var key, subdefaults, subconfig;
for (key in defaults) {
subdefaults = defaults[key];
subconfig = config[key];
if ($.isPlainObject(subdefaults)) {
if (!$.isPlainObject(subconfig)) {
subconfig = config[key] = {};
}
defaultsUpdater(subconfig, subdefaults);
// } else if (subconfig === undefined) {
// config[key] = null;
// }
} else {
if (subconfig === undefined) {
config[key] = subdefaults;
}
}
}
} | [
"function",
"(",
"config",
",",
"defaults",
")",
"{",
"var",
"key",
",",
"subdefaults",
",",
"subconfig",
";",
"for",
"(",
"key",
"in",
"defaults",
")",
"{",
"subdefaults",
"=",
"defaults",
"[",
"key",
"]",
";",
"subconfig",
"=",
"config",
"[",
"key",
"]",
";",
"if",
"(",
"$",
".",
"isPlainObject",
"(",
"subdefaults",
")",
")",
"{",
"if",
"(",
"!",
"$",
".",
"isPlainObject",
"(",
"subconfig",
")",
")",
"{",
"subconfig",
"=",
"config",
"[",
"key",
"]",
"=",
"{",
"}",
";",
"}",
"defaultsUpdater",
"(",
"subconfig",
",",
"subdefaults",
")",
";",
"// } else if (subconfig === undefined) {",
"// config[key] = null;",
"// }",
"}",
"else",
"{",
"if",
"(",
"subconfig",
"===",
"undefined",
")",
"{",
"config",
"[",
"key",
"]",
"=",
"subdefaults",
";",
"}",
"}",
"}",
"}"
] | XXX maintain defaults with action? | [
"XXX",
"maintain",
"defaults",
"with",
"action?"
] | 7dc81080c6c28f34ad8e2334118ff416d2a004a0 | https://github.com/robgietema/twist/blob/7dc81080c6c28f34ad8e2334118ff416d2a004a0/public/libs/obviel/1.0b5/obviel-sync.js#L79-L98 |
|
54,211 | bitcoinnano/btcnano-wallet-service | bitcorenode/index.js | function(options) {
EventEmitter.call(this);
this.node = options.node;
this.https = options.https || this.node.https;
this.httpsOptions = options.httpsOptions || this.node.httpsOptions;
this.bwsPort = options.bwsPort || baseConfig.port;
this.messageBrokerPort = options.messageBrokerPort || 3380;
if (baseConfig.lockOpts) {
this.lockerPort = baseConfig.lockOpts.lockerServer.port;
}
this.lockerPort = options.lockerPort || this.lockerPort;
} | javascript | function(options) {
EventEmitter.call(this);
this.node = options.node;
this.https = options.https || this.node.https;
this.httpsOptions = options.httpsOptions || this.node.httpsOptions;
this.bwsPort = options.bwsPort || baseConfig.port;
this.messageBrokerPort = options.messageBrokerPort || 3380;
if (baseConfig.lockOpts) {
this.lockerPort = baseConfig.lockOpts.lockerServer.port;
}
this.lockerPort = options.lockerPort || this.lockerPort;
} | [
"function",
"(",
"options",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"node",
"=",
"options",
".",
"node",
";",
"this",
".",
"https",
"=",
"options",
".",
"https",
"||",
"this",
".",
"node",
".",
"https",
";",
"this",
".",
"httpsOptions",
"=",
"options",
".",
"httpsOptions",
"||",
"this",
".",
"node",
".",
"httpsOptions",
";",
"this",
".",
"bwsPort",
"=",
"options",
".",
"bwsPort",
"||",
"baseConfig",
".",
"port",
";",
"this",
".",
"messageBrokerPort",
"=",
"options",
".",
"messageBrokerPort",
"||",
"3380",
";",
"if",
"(",
"baseConfig",
".",
"lockOpts",
")",
"{",
"this",
".",
"lockerPort",
"=",
"baseConfig",
".",
"lockOpts",
".",
"lockerServer",
".",
"port",
";",
"}",
"this",
".",
"lockerPort",
"=",
"options",
".",
"lockerPort",
"||",
"this",
".",
"lockerPort",
";",
"}"
] | A Bitcore Node Service module
@param {Object} options
@param {Node} options.node - A reference to the Bitcore Node instance
-* @param {Boolean} options.https - Enable https for this module, defaults to node settings.
@param {Number} options.bwsPort - Port for Bitcore Wallet Service API
@param {Number} options.messageBrokerPort - Port for BWS message broker
@param {Number} options.lockerPort - Port for BWS locker port | [
"A",
"Bitcore",
"Node",
"Service",
"module"
] | cd69f5dc2cbfedbcaf4e379a2e1697a975c38eb2 | https://github.com/bitcoinnano/btcnano-wallet-service/blob/cd69f5dc2cbfedbcaf4e379a2e1697a975c38eb2/bitcorenode/index.js#L30-L42 |
|
54,212 | SolarNetwork/solarnetwork-d3 | src/api/loc/urlHelper.js | availableSourcesURL | function availableSourcesURL(startDate, endDate) {
var url = (baseURL() +'/location/datum/sources?locationId=' +locationId);
if ( startDate !== undefined ) {
url += '&start=' +encodeURIComponent(sn.format.dateFormat(startDate));
}
if ( endDate !== undefined ) {
url += '&end=' +encodeURIComponent(sn.format.dateFormat(endDate));
}
return url;
} | javascript | function availableSourcesURL(startDate, endDate) {
var url = (baseURL() +'/location/datum/sources?locationId=' +locationId);
if ( startDate !== undefined ) {
url += '&start=' +encodeURIComponent(sn.format.dateFormat(startDate));
}
if ( endDate !== undefined ) {
url += '&end=' +encodeURIComponent(sn.format.dateFormat(endDate));
}
return url;
} | [
"function",
"availableSourcesURL",
"(",
"startDate",
",",
"endDate",
")",
"{",
"var",
"url",
"=",
"(",
"baseURL",
"(",
")",
"+",
"'/location/datum/sources?locationId='",
"+",
"locationId",
")",
";",
"if",
"(",
"startDate",
"!==",
"undefined",
")",
"{",
"url",
"+=",
"'&start='",
"+",
"encodeURIComponent",
"(",
"sn",
".",
"format",
".",
"dateFormat",
"(",
"startDate",
")",
")",
";",
"}",
"if",
"(",
"endDate",
"!==",
"undefined",
")",
"{",
"url",
"+=",
"'&end='",
"+",
"encodeURIComponent",
"(",
"sn",
".",
"format",
".",
"dateFormat",
"(",
"endDate",
")",
")",
";",
"}",
"return",
"url",
";",
"}"
] | Get a available source IDs for this location, optionally limited to a date range.
@param {Date} startDate An optional start date to limit the results to.
@param {Date} endDate An optional end date to limit the results to.
@returns {String} the URL to find the available source
@memberOf sn.api.loc.locationUrlHelper
@preserve | [
"Get",
"a",
"available",
"source",
"IDs",
"for",
"this",
"location",
"optionally",
"limited",
"to",
"a",
"date",
"range",
"."
] | 26848b1c303b98b7c0ddeefb8c68c5f5bf78927e | https://github.com/SolarNetwork/solarnetwork-d3/blob/26848b1c303b98b7c0ddeefb8c68c5f5bf78927e/src/api/loc/urlHelper.js#L81-L90 |
54,213 | 75lb/string-tools | lib/string-tools.js | fill | function fill(fillWith, len){
var buffer = new Buffer(len);
buffer.fill(fillWith);
return buffer.toString();
} | javascript | function fill(fillWith, len){
var buffer = new Buffer(len);
buffer.fill(fillWith);
return buffer.toString();
} | [
"function",
"fill",
"(",
"fillWith",
",",
"len",
")",
"{",
"var",
"buffer",
"=",
"new",
"Buffer",
"(",
"len",
")",
";",
"buffer",
".",
"fill",
"(",
"fillWith",
")",
";",
"return",
"buffer",
".",
"toString",
"(",
")",
";",
"}"
] | Create a new string filled with the supplied character
@param {string} - the fill character
@param {number} - the length of the output string
@returns {string}
@example
```js
> s.fill("a", 10)
'aaaaaaaaaa'
> s.fill("ab", 10)
'aaaaaaaaaa'
```
@alias module:string-tools.fill | [
"Create",
"a",
"new",
"string",
"filled",
"with",
"the",
"supplied",
"character"
] | ff6afacd534681dd8f7a6716a499f8b126a2943c | https://github.com/75lb/string-tools/blob/ff6afacd534681dd8f7a6716a499f8b126a2943c/lib/string-tools.js#L49-L53 |
54,214 | 75lb/string-tools | lib/string-tools.js | padRight | function padRight(input, width, padWith){
padWith = padWith || " ";
input = String(input);
if (input.length < width){
return input + fill(padWith, width - input.length);
} else {
return input;
}
} | javascript | function padRight(input, width, padWith){
padWith = padWith || " ";
input = String(input);
if (input.length < width){
return input + fill(padWith, width - input.length);
} else {
return input;
}
} | [
"function",
"padRight",
"(",
"input",
",",
"width",
",",
"padWith",
")",
"{",
"padWith",
"=",
"padWith",
"||",
"\" \"",
";",
"input",
"=",
"String",
"(",
"input",
")",
";",
"if",
"(",
"input",
".",
"length",
"<",
"width",
")",
"{",
"return",
"input",
"+",
"fill",
"(",
"padWith",
",",
"width",
"-",
"input",
".",
"length",
")",
";",
"}",
"else",
"{",
"return",
"input",
";",
"}",
"}"
] | Add padding to the right of a string
@param {string} - the string to pad
@param {number} - the desired final width
@param {string} [padWith=" "] - the padding character
@returns {string}
@example
```js
> s.padRight("clive", 1)
'clive'
> s.padRight("clive", 1, "-")
'clive'
> s.padRight("clive", 10, "-")
'clive-----'
```
@alias module:string-tools.padRight | [
"Add",
"padding",
"to",
"the",
"right",
"of",
"a",
"string"
] | ff6afacd534681dd8f7a6716a499f8b126a2943c | https://github.com/75lb/string-tools/blob/ff6afacd534681dd8f7a6716a499f8b126a2943c/lib/string-tools.js#L72-L80 |
54,215 | 75lb/string-tools | lib/string-tools.js | repeat | function repeat(input, times){
var output = "";
for (var i = 0; i < times; i++){
output += input;
}
return output;
} | javascript | function repeat(input, times){
var output = "";
for (var i = 0; i < times; i++){
output += input;
}
return output;
} | [
"function",
"repeat",
"(",
"input",
",",
"times",
")",
"{",
"var",
"output",
"=",
"\"\"",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"times",
";",
"i",
"++",
")",
"{",
"output",
"+=",
"input",
";",
"}",
"return",
"output",
";",
"}"
] | returns the input string repeated the specified number of times
@param {string} - input string to repeat
@param {number} - the number of times to repeat
@returns {string}
@alias module:string-tools.repeat | [
"returns",
"the",
"input",
"string",
"repeated",
"the",
"specified",
"number",
"of",
"times"
] | ff6afacd534681dd8f7a6716a499f8b126a2943c | https://github.com/75lb/string-tools/blob/ff6afacd534681dd8f7a6716a499f8b126a2943c/lib/string-tools.js#L96-L102 |
54,216 | 75lb/string-tools | lib/string-tools.js | clipLeft | function clipLeft(input, width, prefix){
prefix = prefix || "...";
if (input.length > width){
return prefix + input.slice(-(width - prefix.length));
} else {
return input;
}
} | javascript | function clipLeft(input, width, prefix){
prefix = prefix || "...";
if (input.length > width){
return prefix + input.slice(-(width - prefix.length));
} else {
return input;
}
} | [
"function",
"clipLeft",
"(",
"input",
",",
"width",
",",
"prefix",
")",
"{",
"prefix",
"=",
"prefix",
"||",
"\"...\"",
";",
"if",
"(",
"input",
".",
"length",
">",
"width",
")",
"{",
"return",
"prefix",
"+",
"input",
".",
"slice",
"(",
"-",
"(",
"width",
"-",
"prefix",
".",
"length",
")",
")",
";",
"}",
"else",
"{",
"return",
"input",
";",
"}",
"}"
] | returns the input string clipped from the left side in order to meet the specified `width`
@param {string} - input string to repeat
@param {number} - the desired final width
@param [prefix=...] {string} - the prefix to replace the clipped region
@returns {string}
@alias module:string-tools.clipLeft | [
"returns",
"the",
"input",
"string",
"clipped",
"from",
"the",
"left",
"side",
"in",
"order",
"to",
"meet",
"the",
"specified",
"width"
] | ff6afacd534681dd8f7a6716a499f8b126a2943c | https://github.com/75lb/string-tools/blob/ff6afacd534681dd8f7a6716a499f8b126a2943c/lib/string-tools.js#L112-L119 |
54,217 | AndCake/zino | src/mustacheparser.js | handleStyles | function handleStyles(tagName, styles) {
styles = (styles || []).map(style => {
let code = style;
return code.replace(/[\r\n]*([^%\{;\}]+?)\{/gm, (global, match) => {
if (match.trim().match(/^@/)) {
return match + '{';
}
var selectors = match.split(',').map(selector => {
selector = selector.trim();
if (selector.match(/:host\b/) ||
selector.match(new RegExp(`^\\s*${tagName}\\b`)) ||
selector.match(/^\s*(?:(?:\d+%)|(?:from)|(?:to)|(?:@\w+)|\})\s*$/)) {
return selector;
}
return tagName + ' ' + selector;
});
return global.replace(match, selectors.join(','));
}).replace(/:host\b/gm, tagName) + '\n';
});
return styles;
} | javascript | function handleStyles(tagName, styles) {
styles = (styles || []).map(style => {
let code = style;
return code.replace(/[\r\n]*([^%\{;\}]+?)\{/gm, (global, match) => {
if (match.trim().match(/^@/)) {
return match + '{';
}
var selectors = match.split(',').map(selector => {
selector = selector.trim();
if (selector.match(/:host\b/) ||
selector.match(new RegExp(`^\\s*${tagName}\\b`)) ||
selector.match(/^\s*(?:(?:\d+%)|(?:from)|(?:to)|(?:@\w+)|\})\s*$/)) {
return selector;
}
return tagName + ' ' + selector;
});
return global.replace(match, selectors.join(','));
}).replace(/:host\b/gm, tagName) + '\n';
});
return styles;
} | [
"function",
"handleStyles",
"(",
"tagName",
",",
"styles",
")",
"{",
"styles",
"=",
"(",
"styles",
"||",
"[",
"]",
")",
".",
"map",
"(",
"style",
"=>",
"{",
"let",
"code",
"=",
"style",
";",
"return",
"code",
".",
"replace",
"(",
"/",
"[\\r\\n]*([^%\\{;\\}]+?)\\{",
"/",
"gm",
",",
"(",
"global",
",",
"match",
")",
"=>",
"{",
"if",
"(",
"match",
".",
"trim",
"(",
")",
".",
"match",
"(",
"/",
"^@",
"/",
")",
")",
"{",
"return",
"match",
"+",
"'{'",
";",
"}",
"var",
"selectors",
"=",
"match",
".",
"split",
"(",
"','",
")",
".",
"map",
"(",
"selector",
"=>",
"{",
"selector",
"=",
"selector",
".",
"trim",
"(",
")",
";",
"if",
"(",
"selector",
".",
"match",
"(",
"/",
":host\\b",
"/",
")",
"||",
"selector",
".",
"match",
"(",
"new",
"RegExp",
"(",
"`",
"\\\\",
"${",
"tagName",
"}",
"\\\\",
"`",
")",
")",
"||",
"selector",
".",
"match",
"(",
"/",
"^\\s*(?:(?:\\d+%)|(?:from)|(?:to)|(?:@\\w+)|\\})\\s*$",
"/",
")",
")",
"{",
"return",
"selector",
";",
"}",
"return",
"tagName",
"+",
"' '",
"+",
"selector",
";",
"}",
")",
";",
"return",
"global",
".",
"replace",
"(",
"match",
",",
"selectors",
".",
"join",
"(",
"','",
")",
")",
";",
"}",
")",
".",
"replace",
"(",
"/",
":host\\b",
"/",
"gm",
",",
"tagName",
")",
"+",
"'\\n'",
";",
"}",
")",
";",
"return",
"styles",
";",
"}"
] | parses style information from within a style tag makes sure it is localized | [
"parses",
"style",
"information",
"from",
"within",
"a",
"style",
"tag",
"makes",
"sure",
"it",
"is",
"localized"
] | a9d1de87ad80fe2d106fd84a0c20984c0f3ab125 | https://github.com/AndCake/zino/blob/a9d1de87ad80fe2d106fd84a0c20984c0f3ab125/src/mustacheparser.js#L126-L146 |
54,218 | AndCake/zino | src/mustacheparser.js | handleText | function handleText(text, isAttr) {
let match, result = '', lastIndex = 0;
let cat = isAttr ? ' + ' : ', ';
if (!text.match(syntax)) {
return result += "'" + text.substr(lastIndex).replace(/\n/g, '').replace(/'/g, '\\\'') + "'" + cat;
}
// locate mustache syntax within the text
while (match = syntax.exec(text)) {
if (match.index < lastIndex) continue;
let frag = text.substring(lastIndex, match.index).replace(/^\s+/g, '');
if (frag.length > 0) {
result += "'" + frag.replace(/\n/g, '').replace(/'/g, '\\\'') + "'" + cat;
}
lastIndex = match.index + match[0].length;
let key = match[1];
// of "{{#test}}" value will be "test"
let value = key.substr(1);
if (key[0] === '#') {
// handle block start
result += `spread(toArray(${getData()}, '${value}').map(function (e, i, a) {
var data$${level + 1} = merge({}, data${0 >= level ? '' : '$' + level}, {'.': e, '.index': i, '.length': a.length}, e);
return [].concat(`;
level += 1;
usesMerge = true;
usesSpread = true;
} else if (key[0] === '/') {
// handle block end
result += '\'\'); }))' + (isAttr ? '.join("")' : '') + cat;
level -= 1;
if (level < 0) {
throw new Error('Unexpected end of block: ' + key.substr(1));
}
} else if (key[0] === '^') {
// handle inverted block start
result += `(safeAccess(${getData()}, '${value}') && (typeof safeAccess(${getData()}, '${value}') === 'boolean' || safeAccess(${getData()}, '${value}').length > 0)) ? '' : spread([1].map(function() { var data$${level + 1} = merge({}, data${0 >= level ? '' : '$' + level}); return [].concat(`;
usesMerge = true;
usesSpread = true;
level += 1;
} else if (key[0] === '%') {
// handle style rendering "{{%myvar}}" - only to be used for attribute values!
result += key.substr(1).split(/\s*,\s*/).map(value => `renderStyle(safeAccess(${getData()}, '${value}'), ${getData()})`).join(' + ');
usesRenderStyle = true;
} else if (key[0] === '+') {
// handle deep data transfer "{{+myvar}}"
result += `safeAccess(${getData()}, '${value}')${cat}`;
} else if (key[0] !== '{' && key[0] !== '!') {
// handle non-escaping prints "{{{myvar}}}"
value = key;
result += `''+safeAccess(${getData()}, '${value}', true)${cat}`
} else if (key[0] !== '!') {
// regular prints "{{myvar}}"
result += `''+safeAccess(${getData()}, '${value}')${cat}`;
} // ignore comments
}
if (text.substr(lastIndex).length > 0) {
result += "'" + text.substr(lastIndex).replace(/\n/g, '').replace(/'/g, '\\\'') + "'" + cat;
}
return result;
} | javascript | function handleText(text, isAttr) {
let match, result = '', lastIndex = 0;
let cat = isAttr ? ' + ' : ', ';
if (!text.match(syntax)) {
return result += "'" + text.substr(lastIndex).replace(/\n/g, '').replace(/'/g, '\\\'') + "'" + cat;
}
// locate mustache syntax within the text
while (match = syntax.exec(text)) {
if (match.index < lastIndex) continue;
let frag = text.substring(lastIndex, match.index).replace(/^\s+/g, '');
if (frag.length > 0) {
result += "'" + frag.replace(/\n/g, '').replace(/'/g, '\\\'') + "'" + cat;
}
lastIndex = match.index + match[0].length;
let key = match[1];
// of "{{#test}}" value will be "test"
let value = key.substr(1);
if (key[0] === '#') {
// handle block start
result += `spread(toArray(${getData()}, '${value}').map(function (e, i, a) {
var data$${level + 1} = merge({}, data${0 >= level ? '' : '$' + level}, {'.': e, '.index': i, '.length': a.length}, e);
return [].concat(`;
level += 1;
usesMerge = true;
usesSpread = true;
} else if (key[0] === '/') {
// handle block end
result += '\'\'); }))' + (isAttr ? '.join("")' : '') + cat;
level -= 1;
if (level < 0) {
throw new Error('Unexpected end of block: ' + key.substr(1));
}
} else if (key[0] === '^') {
// handle inverted block start
result += `(safeAccess(${getData()}, '${value}') && (typeof safeAccess(${getData()}, '${value}') === 'boolean' || safeAccess(${getData()}, '${value}').length > 0)) ? '' : spread([1].map(function() { var data$${level + 1} = merge({}, data${0 >= level ? '' : '$' + level}); return [].concat(`;
usesMerge = true;
usesSpread = true;
level += 1;
} else if (key[0] === '%') {
// handle style rendering "{{%myvar}}" - only to be used for attribute values!
result += key.substr(1).split(/\s*,\s*/).map(value => `renderStyle(safeAccess(${getData()}, '${value}'), ${getData()})`).join(' + ');
usesRenderStyle = true;
} else if (key[0] === '+') {
// handle deep data transfer "{{+myvar}}"
result += `safeAccess(${getData()}, '${value}')${cat}`;
} else if (key[0] !== '{' && key[0] !== '!') {
// handle non-escaping prints "{{{myvar}}}"
value = key;
result += `''+safeAccess(${getData()}, '${value}', true)${cat}`
} else if (key[0] !== '!') {
// regular prints "{{myvar}}"
result += `''+safeAccess(${getData()}, '${value}')${cat}`;
} // ignore comments
}
if (text.substr(lastIndex).length > 0) {
result += "'" + text.substr(lastIndex).replace(/\n/g, '').replace(/'/g, '\\\'') + "'" + cat;
}
return result;
} | [
"function",
"handleText",
"(",
"text",
",",
"isAttr",
")",
"{",
"let",
"match",
",",
"result",
"=",
"''",
",",
"lastIndex",
"=",
"0",
";",
"let",
"cat",
"=",
"isAttr",
"?",
"' + '",
":",
"', '",
";",
"if",
"(",
"!",
"text",
".",
"match",
"(",
"syntax",
")",
")",
"{",
"return",
"result",
"+=",
"\"'\"",
"+",
"text",
".",
"substr",
"(",
"lastIndex",
")",
".",
"replace",
"(",
"/",
"\\n",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
"'",
"/",
"g",
",",
"'\\\\\\''",
")",
"+",
"\"'\"",
"+",
"cat",
";",
"}",
"// locate mustache syntax within the text",
"while",
"(",
"match",
"=",
"syntax",
".",
"exec",
"(",
"text",
")",
")",
"{",
"if",
"(",
"match",
".",
"index",
"<",
"lastIndex",
")",
"continue",
";",
"let",
"frag",
"=",
"text",
".",
"substring",
"(",
"lastIndex",
",",
"match",
".",
"index",
")",
".",
"replace",
"(",
"/",
"^\\s+",
"/",
"g",
",",
"''",
")",
";",
"if",
"(",
"frag",
".",
"length",
">",
"0",
")",
"{",
"result",
"+=",
"\"'\"",
"+",
"frag",
".",
"replace",
"(",
"/",
"\\n",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
"'",
"/",
"g",
",",
"'\\\\\\''",
")",
"+",
"\"'\"",
"+",
"cat",
";",
"}",
"lastIndex",
"=",
"match",
".",
"index",
"+",
"match",
"[",
"0",
"]",
".",
"length",
";",
"let",
"key",
"=",
"match",
"[",
"1",
"]",
";",
"// of \"{{#test}}\" value will be \"test\"",
"let",
"value",
"=",
"key",
".",
"substr",
"(",
"1",
")",
";",
"if",
"(",
"key",
"[",
"0",
"]",
"===",
"'#'",
")",
"{",
"// handle block start",
"result",
"+=",
"`",
"${",
"getData",
"(",
")",
"}",
"${",
"value",
"}",
"${",
"level",
"+",
"1",
"}",
"${",
"0",
">=",
"level",
"?",
"''",
":",
"'$'",
"+",
"level",
"}",
"`",
";",
"level",
"+=",
"1",
";",
"usesMerge",
"=",
"true",
";",
"usesSpread",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"key",
"[",
"0",
"]",
"===",
"'/'",
")",
"{",
"// handle block end",
"result",
"+=",
"'\\'\\'); }))'",
"+",
"(",
"isAttr",
"?",
"'.join(\"\")'",
":",
"''",
")",
"+",
"cat",
";",
"level",
"-=",
"1",
";",
"if",
"(",
"level",
"<",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unexpected end of block: '",
"+",
"key",
".",
"substr",
"(",
"1",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"key",
"[",
"0",
"]",
"===",
"'^'",
")",
"{",
"// handle inverted block start",
"result",
"+=",
"`",
"${",
"getData",
"(",
")",
"}",
"${",
"value",
"}",
"${",
"getData",
"(",
")",
"}",
"${",
"value",
"}",
"${",
"getData",
"(",
")",
"}",
"${",
"value",
"}",
"${",
"level",
"+",
"1",
"}",
"${",
"0",
">=",
"level",
"?",
"''",
":",
"'$'",
"+",
"level",
"}",
"`",
";",
"usesMerge",
"=",
"true",
";",
"usesSpread",
"=",
"true",
";",
"level",
"+=",
"1",
";",
"}",
"else",
"if",
"(",
"key",
"[",
"0",
"]",
"===",
"'%'",
")",
"{",
"// handle style rendering \"{{%myvar}}\" - only to be used for attribute values!",
"result",
"+=",
"key",
".",
"substr",
"(",
"1",
")",
".",
"split",
"(",
"/",
"\\s*,\\s*",
"/",
")",
".",
"map",
"(",
"value",
"=>",
"`",
"${",
"getData",
"(",
")",
"}",
"${",
"value",
"}",
"${",
"getData",
"(",
")",
"}",
"`",
")",
".",
"join",
"(",
"' + '",
")",
";",
"usesRenderStyle",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"key",
"[",
"0",
"]",
"===",
"'+'",
")",
"{",
"// handle deep data transfer \"{{+myvar}}\"",
"result",
"+=",
"`",
"${",
"getData",
"(",
")",
"}",
"${",
"value",
"}",
"${",
"cat",
"}",
"`",
";",
"}",
"else",
"if",
"(",
"key",
"[",
"0",
"]",
"!==",
"'{'",
"&&",
"key",
"[",
"0",
"]",
"!==",
"'!'",
")",
"{",
"// handle non-escaping prints \"{{{myvar}}}\"",
"value",
"=",
"key",
";",
"result",
"+=",
"`",
"${",
"getData",
"(",
")",
"}",
"${",
"value",
"}",
"${",
"cat",
"}",
"`",
"}",
"else",
"if",
"(",
"key",
"[",
"0",
"]",
"!==",
"'!'",
")",
"{",
"// regular prints \"{{myvar}}\"",
"result",
"+=",
"`",
"${",
"getData",
"(",
")",
"}",
"${",
"value",
"}",
"${",
"cat",
"}",
"`",
";",
"}",
"// ignore comments",
"}",
"if",
"(",
"text",
".",
"substr",
"(",
"lastIndex",
")",
".",
"length",
">",
"0",
")",
"{",
"result",
"+=",
"\"'\"",
"+",
"text",
".",
"substr",
"(",
"lastIndex",
")",
".",
"replace",
"(",
"/",
"\\n",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
"'",
"/",
"g",
",",
"'\\\\\\''",
")",
"+",
"\"'\"",
"+",
"cat",
";",
"}",
"return",
"result",
";",
"}"
] | text is the only place where mustache code can be found | [
"text",
"is",
"the",
"only",
"place",
"where",
"mustache",
"code",
"can",
"be",
"found"
] | a9d1de87ad80fe2d106fd84a0c20984c0f3ab125 | https://github.com/AndCake/zino/blob/a9d1de87ad80fe2d106fd84a0c20984c0f3ab125/src/mustacheparser.js#L166-L224 |
54,219 | AndCake/zino | src/mustacheparser.js | makeAttributes | function makeAttributes(attrs) {
let attributes = '{';
let attr;
while ((attr = attrRegExp.exec(attrs))) {
if (attributes !== '{') attributes += ', ';
attributes += '"' + attr[1].toLowerCase() + '": ' + handleText(attr[2] || attr[3] || '', true).replace(/\s*[,+]\s*$/g, '');
}
return attributes + '}';
} | javascript | function makeAttributes(attrs) {
let attributes = '{';
let attr;
while ((attr = attrRegExp.exec(attrs))) {
if (attributes !== '{') attributes += ', ';
attributes += '"' + attr[1].toLowerCase() + '": ' + handleText(attr[2] || attr[3] || '', true).replace(/\s*[,+]\s*$/g, '');
}
return attributes + '}';
} | [
"function",
"makeAttributes",
"(",
"attrs",
")",
"{",
"let",
"attributes",
"=",
"'{'",
";",
"let",
"attr",
";",
"while",
"(",
"(",
"attr",
"=",
"attrRegExp",
".",
"exec",
"(",
"attrs",
")",
")",
")",
"{",
"if",
"(",
"attributes",
"!==",
"'{'",
")",
"attributes",
"+=",
"', '",
";",
"attributes",
"+=",
"'\"'",
"+",
"attr",
"[",
"1",
"]",
".",
"toLowerCase",
"(",
")",
"+",
"'\": '",
"+",
"handleText",
"(",
"attr",
"[",
"2",
"]",
"||",
"attr",
"[",
"3",
"]",
"||",
"''",
",",
"true",
")",
".",
"replace",
"(",
"/",
"\\s*[,+]\\s*$",
"/",
"g",
",",
"''",
")",
";",
"}",
"return",
"attributes",
"+",
"'}'",
";",
"}"
] | generate attribute objects for vdom creation | [
"generate",
"attribute",
"objects",
"for",
"vdom",
"creation"
] | a9d1de87ad80fe2d106fd84a0c20984c0f3ab125 | https://github.com/AndCake/zino/blob/a9d1de87ad80fe2d106fd84a0c20984c0f3ab125/src/mustacheparser.js#L227-L236 |
54,220 | SilentCicero/wafr | src/utils/index.js | bytes32ToType | function bytes32ToType(type, value) {
switch (type) {
case 'address':
return `0x${ethUtil.stripHexPrefix(value).slice(24)}`;
case 'bool':
return (ethUtil.stripHexPrefix(value).slice(63) === '1');
case 'int':
return bytes32ToInt(value);
case 'uint':
return bytes32ToInt(value);
default:
return value;
}
} | javascript | function bytes32ToType(type, value) {
switch (type) {
case 'address':
return `0x${ethUtil.stripHexPrefix(value).slice(24)}`;
case 'bool':
return (ethUtil.stripHexPrefix(value).slice(63) === '1');
case 'int':
return bytes32ToInt(value);
case 'uint':
return bytes32ToInt(value);
default:
return value;
}
} | [
"function",
"bytes32ToType",
"(",
"type",
",",
"value",
")",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"'address'",
":",
"return",
"`",
"${",
"ethUtil",
".",
"stripHexPrefix",
"(",
"value",
")",
".",
"slice",
"(",
"24",
")",
"}",
"`",
";",
"case",
"'bool'",
":",
"return",
"(",
"ethUtil",
".",
"stripHexPrefix",
"(",
"value",
")",
".",
"slice",
"(",
"63",
")",
"===",
"'1'",
")",
";",
"case",
"'int'",
":",
"return",
"bytes32ToInt",
"(",
"value",
")",
";",
"case",
"'uint'",
":",
"return",
"bytes32ToInt",
"(",
"value",
")",
";",
"default",
":",
"return",
"value",
";",
"}",
"}"
] | bytes32 to type | [
"bytes32",
"to",
"type"
] | 2c7483feec5df346d8903cab5badc17143c3876d | https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/src/utils/index.js#L103-L116 |
54,221 | SilentCicero/wafr | src/utils/index.js | filenameInclude | function filenameInclude(filename, exclude, include) { // eslint-disable-line
var output = true; // eslint-disable-line
if (exclude) {
if (globToRegExp(exclude, { extended: true }).test(filename)
&& !globToRegExp(include || '', { extended: true }).test(filename)) {
output = false;
}
}
return output;
} | javascript | function filenameInclude(filename, exclude, include) { // eslint-disable-line
var output = true; // eslint-disable-line
if (exclude) {
if (globToRegExp(exclude, { extended: true }).test(filename)
&& !globToRegExp(include || '', { extended: true }).test(filename)) {
output = false;
}
}
return output;
} | [
"function",
"filenameInclude",
"(",
"filename",
",",
"exclude",
",",
"include",
")",
"{",
"// eslint-disable-line",
"var",
"output",
"=",
"true",
";",
"// eslint-disable-line",
"if",
"(",
"exclude",
")",
"{",
"if",
"(",
"globToRegExp",
"(",
"exclude",
",",
"{",
"extended",
":",
"true",
"}",
")",
".",
"test",
"(",
"filename",
")",
"&&",
"!",
"globToRegExp",
"(",
"include",
"||",
"''",
",",
"{",
"extended",
":",
"true",
"}",
")",
".",
"test",
"(",
"filename",
")",
")",
"{",
"output",
"=",
"false",
";",
"}",
"}",
"return",
"output",
";",
"}"
] | returns true if the filename should be included | [
"returns",
"true",
"if",
"the",
"filename",
"should",
"be",
"included"
] | 2c7483feec5df346d8903cab5badc17143c3876d | https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/src/utils/index.js#L124-L135 |
54,222 | SilentCicero/wafr | src/utils/index.js | allImportPaths | function allImportPaths(contractSource) {
const noCommentSource = strip.js(String(contractSource));
const rawImportStatements = execall(/^(\s*)((import)(.*?))("|')(.*?)("|')((;)|((.*?)(;)))$/gm, noCommentSource);
const importPaths = rawImportStatements
.map(v => String(execall(/("|')(.*?)("|')/g, v.match)[0].match)
.replace(/'/g, '')
.replace(/"/g, '')
.replace(/^\//, '')
.replace('./', '')
.trim());
return importPaths.filter(path => (path !== 'wafr/Test.sol'));
} | javascript | function allImportPaths(contractSource) {
const noCommentSource = strip.js(String(contractSource));
const rawImportStatements = execall(/^(\s*)((import)(.*?))("|')(.*?)("|')((;)|((.*?)(;)))$/gm, noCommentSource);
const importPaths = rawImportStatements
.map(v => String(execall(/("|')(.*?)("|')/g, v.match)[0].match)
.replace(/'/g, '')
.replace(/"/g, '')
.replace(/^\//, '')
.replace('./', '')
.trim());
return importPaths.filter(path => (path !== 'wafr/Test.sol'));
} | [
"function",
"allImportPaths",
"(",
"contractSource",
")",
"{",
"const",
"noCommentSource",
"=",
"strip",
".",
"js",
"(",
"String",
"(",
"contractSource",
")",
")",
";",
"const",
"rawImportStatements",
"=",
"execall",
"(",
"/",
"^(\\s*)((import)(.*?))(\"|')(.*?)(\"|')((;)|((.*?)(;)))$",
"/",
"gm",
",",
"noCommentSource",
")",
";",
"const",
"importPaths",
"=",
"rawImportStatements",
".",
"map",
"(",
"v",
"=>",
"String",
"(",
"execall",
"(",
"/",
"(\"|')(.*?)(\"|')",
"/",
"g",
",",
"v",
".",
"match",
")",
"[",
"0",
"]",
".",
"match",
")",
".",
"replace",
"(",
"/",
"'",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
"\"",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
"^\\/",
"/",
",",
"''",
")",
".",
"replace",
"(",
"'./'",
",",
"''",
")",
".",
"trim",
"(",
")",
")",
";",
"return",
"importPaths",
".",
"filter",
"(",
"path",
"=>",
"(",
"path",
"!==",
"'wafr/Test.sol'",
")",
")",
";",
"}"
] | get all import paths from contract source | [
"get",
"all",
"import",
"paths",
"from",
"contract",
"source"
] | 2c7483feec5df346d8903cab5badc17143c3876d | https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/src/utils/index.js#L138-L150 |
54,223 | SilentCicero/wafr | src/utils/index.js | buildDependencyTreeFromSources | function buildDependencyTreeFromSources(filenames, sourcesObject) {
const orgnizedFlat = {};
// build tree object
filenames.forEach(sourceFileName => {
orgnizedFlat[sourceFileName] = {
path: sourceFileName,
source: sourcesObject[sourceFileName],
dependencies: buildDependencyTreeFromSources(allImportPaths(sourcesObject[sourceFileName]), sourcesObject),
};
});
// return organized object
return orgnizedFlat;
} | javascript | function buildDependencyTreeFromSources(filenames, sourcesObject) {
const orgnizedFlat = {};
// build tree object
filenames.forEach(sourceFileName => {
orgnizedFlat[sourceFileName] = {
path: sourceFileName,
source: sourcesObject[sourceFileName],
dependencies: buildDependencyTreeFromSources(allImportPaths(sourcesObject[sourceFileName]), sourcesObject),
};
});
// return organized object
return orgnizedFlat;
} | [
"function",
"buildDependencyTreeFromSources",
"(",
"filenames",
",",
"sourcesObject",
")",
"{",
"const",
"orgnizedFlat",
"=",
"{",
"}",
";",
"// build tree object",
"filenames",
".",
"forEach",
"(",
"sourceFileName",
"=>",
"{",
"orgnizedFlat",
"[",
"sourceFileName",
"]",
"=",
"{",
"path",
":",
"sourceFileName",
",",
"source",
":",
"sourcesObject",
"[",
"sourceFileName",
"]",
",",
"dependencies",
":",
"buildDependencyTreeFromSources",
"(",
"allImportPaths",
"(",
"sourcesObject",
"[",
"sourceFileName",
"]",
")",
",",
"sourcesObject",
")",
",",
"}",
";",
"}",
")",
";",
"// return organized object",
"return",
"orgnizedFlat",
";",
"}"
] | build dependency tree, returns a complex object | [
"build",
"dependency",
"tree",
"returns",
"a",
"complex",
"object"
] | 2c7483feec5df346d8903cab5badc17143c3876d | https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/src/utils/index.js#L153-L167 |
54,224 | SilentCicero/wafr | src/utils/index.js | buildFlatSourcesObjectFromTreeObject | function buildFlatSourcesObjectFromTreeObject(treeObject) {
const currentOutputObject = Object.assign({});
currentOutputObject[treeObject.path] = treeObject.source;
Object.keys(treeObject.dependencies).forEach(dependantTreeObjectFileName => {
Object.assign(currentOutputObject, buildFlatSourcesObjectFromTreeObject(treeObject.dependencies[dependantTreeObjectFileName]));
});
return currentOutputObject;
} | javascript | function buildFlatSourcesObjectFromTreeObject(treeObject) {
const currentOutputObject = Object.assign({});
currentOutputObject[treeObject.path] = treeObject.source;
Object.keys(treeObject.dependencies).forEach(dependantTreeObjectFileName => {
Object.assign(currentOutputObject, buildFlatSourcesObjectFromTreeObject(treeObject.dependencies[dependantTreeObjectFileName]));
});
return currentOutputObject;
} | [
"function",
"buildFlatSourcesObjectFromTreeObject",
"(",
"treeObject",
")",
"{",
"const",
"currentOutputObject",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
")",
";",
"currentOutputObject",
"[",
"treeObject",
".",
"path",
"]",
"=",
"treeObject",
".",
"source",
";",
"Object",
".",
"keys",
"(",
"treeObject",
".",
"dependencies",
")",
".",
"forEach",
"(",
"dependantTreeObjectFileName",
"=>",
"{",
"Object",
".",
"assign",
"(",
"currentOutputObject",
",",
"buildFlatSourcesObjectFromTreeObject",
"(",
"treeObject",
".",
"dependencies",
"[",
"dependantTreeObjectFileName",
"]",
")",
")",
";",
"}",
")",
";",
"return",
"currentOutputObject",
";",
"}"
] | return flat source object from a specific tree root | [
"return",
"flat",
"source",
"object",
"from",
"a",
"specific",
"tree",
"root"
] | 2c7483feec5df346d8903cab5badc17143c3876d | https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/src/utils/index.js#L170-L179 |
54,225 | SilentCicero/wafr | src/utils/index.js | buildDependantsSourceTree | function buildDependantsSourceTree(sourceFileName, sourcesObject) {
const depsTree = buildDependencyTreeFromSources(Object.keys(sourcesObject), sourcesObject);
return buildFlatSourcesObjectFromTreeObject(depsTree[sourceFileName]);
} | javascript | function buildDependantsSourceTree(sourceFileName, sourcesObject) {
const depsTree = buildDependencyTreeFromSources(Object.keys(sourcesObject), sourcesObject);
return buildFlatSourcesObjectFromTreeObject(depsTree[sourceFileName]);
} | [
"function",
"buildDependantsSourceTree",
"(",
"sourceFileName",
",",
"sourcesObject",
")",
"{",
"const",
"depsTree",
"=",
"buildDependencyTreeFromSources",
"(",
"Object",
".",
"keys",
"(",
"sourcesObject",
")",
",",
"sourcesObject",
")",
";",
"return",
"buildFlatSourcesObjectFromTreeObject",
"(",
"depsTree",
"[",
"sourceFileName",
"]",
")",
";",
"}"
] | returns a source list object of all dependancies | [
"returns",
"a",
"source",
"list",
"object",
"of",
"all",
"dependancies"
] | 2c7483feec5df346d8903cab5badc17143c3876d | https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/src/utils/index.js#L182-L186 |
54,226 | SilentCicero/wafr | src/utils/index.js | getInputSources | function getInputSources(dirname, exclude, include, focusContractPath, callback) {
let filesRead = 0;
const sources = {};
// get all file names
dir.files(dirname, (filesError, files) => {
if (filesError) {
throwError(`while while getting input sources ${filesError}`);
}
// if no files in directory, then fire callback with empty sources
if (files.length === 0) {
callback(null, sources);
} else {
// read all files
dir.readFiles(dirname, (readFilesError, content, filename, next) => {
if (readFilesError) {
throwError(`while getting input sources ${readFilesError}`);
}
// parsed filename
const parsedDirName = dirname.replace('./', '');
const parsedFileName = filename.replace(parsedDirName, '').replace(/^\//, '');
const onlyFilename = filename.substr(filename.lastIndexOf('/') + 1);
// add input sources to output
if (filename.substr(filename.lastIndexOf('.') + 1) === 'sol'
&& filenameInclude(filename, exclude, include)
&& onlyFilename.charAt(0) !== '~'
&& onlyFilename.charAt(0) !== '#'
&& onlyFilename.charAt(0) !== '.') {
sources[parsedFileName] = content;
}
// increase files readFiles
filesRead += 1;
// process next file
if (filesRead === files.length) {
// filter sources by focus dependencies
if (focusContractPath) {
callback(null, buildDependantsSourceTree(focusContractPath, sources));
} else {
callback(null, sources);
}
} else {
next();
}
});
}
});
} | javascript | function getInputSources(dirname, exclude, include, focusContractPath, callback) {
let filesRead = 0;
const sources = {};
// get all file names
dir.files(dirname, (filesError, files) => {
if (filesError) {
throwError(`while while getting input sources ${filesError}`);
}
// if no files in directory, then fire callback with empty sources
if (files.length === 0) {
callback(null, sources);
} else {
// read all files
dir.readFiles(dirname, (readFilesError, content, filename, next) => {
if (readFilesError) {
throwError(`while getting input sources ${readFilesError}`);
}
// parsed filename
const parsedDirName = dirname.replace('./', '');
const parsedFileName = filename.replace(parsedDirName, '').replace(/^\//, '');
const onlyFilename = filename.substr(filename.lastIndexOf('/') + 1);
// add input sources to output
if (filename.substr(filename.lastIndexOf('.') + 1) === 'sol'
&& filenameInclude(filename, exclude, include)
&& onlyFilename.charAt(0) !== '~'
&& onlyFilename.charAt(0) !== '#'
&& onlyFilename.charAt(0) !== '.') {
sources[parsedFileName] = content;
}
// increase files readFiles
filesRead += 1;
// process next file
if (filesRead === files.length) {
// filter sources by focus dependencies
if (focusContractPath) {
callback(null, buildDependantsSourceTree(focusContractPath, sources));
} else {
callback(null, sources);
}
} else {
next();
}
});
}
});
} | [
"function",
"getInputSources",
"(",
"dirname",
",",
"exclude",
",",
"include",
",",
"focusContractPath",
",",
"callback",
")",
"{",
"let",
"filesRead",
"=",
"0",
";",
"const",
"sources",
"=",
"{",
"}",
";",
"// get all file names",
"dir",
".",
"files",
"(",
"dirname",
",",
"(",
"filesError",
",",
"files",
")",
"=>",
"{",
"if",
"(",
"filesError",
")",
"{",
"throwError",
"(",
"`",
"${",
"filesError",
"}",
"`",
")",
";",
"}",
"// if no files in directory, then fire callback with empty sources",
"if",
"(",
"files",
".",
"length",
"===",
"0",
")",
"{",
"callback",
"(",
"null",
",",
"sources",
")",
";",
"}",
"else",
"{",
"// read all files",
"dir",
".",
"readFiles",
"(",
"dirname",
",",
"(",
"readFilesError",
",",
"content",
",",
"filename",
",",
"next",
")",
"=>",
"{",
"if",
"(",
"readFilesError",
")",
"{",
"throwError",
"(",
"`",
"${",
"readFilesError",
"}",
"`",
")",
";",
"}",
"// parsed filename",
"const",
"parsedDirName",
"=",
"dirname",
".",
"replace",
"(",
"'./'",
",",
"''",
")",
";",
"const",
"parsedFileName",
"=",
"filename",
".",
"replace",
"(",
"parsedDirName",
",",
"''",
")",
".",
"replace",
"(",
"/",
"^\\/",
"/",
",",
"''",
")",
";",
"const",
"onlyFilename",
"=",
"filename",
".",
"substr",
"(",
"filename",
".",
"lastIndexOf",
"(",
"'/'",
")",
"+",
"1",
")",
";",
"// add input sources to output",
"if",
"(",
"filename",
".",
"substr",
"(",
"filename",
".",
"lastIndexOf",
"(",
"'.'",
")",
"+",
"1",
")",
"===",
"'sol'",
"&&",
"filenameInclude",
"(",
"filename",
",",
"exclude",
",",
"include",
")",
"&&",
"onlyFilename",
".",
"charAt",
"(",
"0",
")",
"!==",
"'~'",
"&&",
"onlyFilename",
".",
"charAt",
"(",
"0",
")",
"!==",
"'#'",
"&&",
"onlyFilename",
".",
"charAt",
"(",
"0",
")",
"!==",
"'.'",
")",
"{",
"sources",
"[",
"parsedFileName",
"]",
"=",
"content",
";",
"}",
"// increase files readFiles",
"filesRead",
"+=",
"1",
";",
"// process next file",
"if",
"(",
"filesRead",
"===",
"files",
".",
"length",
")",
"{",
"// filter sources by focus dependencies",
"if",
"(",
"focusContractPath",
")",
"{",
"callback",
"(",
"null",
",",
"buildDependantsSourceTree",
"(",
"focusContractPath",
",",
"sources",
")",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"sources",
")",
";",
"}",
"}",
"else",
"{",
"next",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | get all contract input sources | [
"get",
"all",
"contract",
"input",
"sources"
] | 2c7483feec5df346d8903cab5badc17143c3876d | https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/src/utils/index.js#L189-L240 |
54,227 | SilentCicero/wafr | src/utils/index.js | compareABIByMethodName | function compareABIByMethodName(methodObjectA, methodObjectB) {
if (methodObjectA.name < methodObjectB.name) {
return -1;
}
if (methodObjectA.name > methodObjectB.name) {
return 1;
}
return 0;
} | javascript | function compareABIByMethodName(methodObjectA, methodObjectB) {
if (methodObjectA.name < methodObjectB.name) {
return -1;
}
if (methodObjectA.name > methodObjectB.name) {
return 1;
}
return 0;
} | [
"function",
"compareABIByMethodName",
"(",
"methodObjectA",
",",
"methodObjectB",
")",
"{",
"if",
"(",
"methodObjectA",
".",
"name",
"<",
"methodObjectB",
".",
"name",
")",
"{",
"return",
"-",
"1",
";",
"}",
"if",
"(",
"methodObjectA",
".",
"name",
">",
"methodObjectB",
".",
"name",
")",
"{",
"return",
"1",
";",
"}",
"return",
"0",
";",
"}"
] | sort test method array | [
"sort",
"test",
"method",
"array"
] | 2c7483feec5df346d8903cab5badc17143c3876d | https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/src/utils/index.js#L281-L291 |
54,228 | SilentCicero/wafr | src/utils/index.js | errorEnhancement | function errorEnhancement(inputMessage) {
var message = inputMessage; // eslint-disable-line
var outputMessage = null; // eslint-disable-line
// if the input message is an array or object
if (inputMessage !== null
&& !isNaN(inputMessage)
&& typeof inputMessage !== 'string') {
message = JSON.stringify(inputMessage);
}
// gauentee string convertion, null and other..
message = String(message);
// if message includes
if (message.includes('Compiled contract not found')) {
outputMessage = 'This could be due to a contract with the same name being compiled. Wafr doesnt allow two contracts with the same name. Look to see if any of your contracts have the same name.';
}
// if message includes
if (message.includes('invalid JUMP')) {
outputMessage = `This can be caused by many things. One main cause is a 'throw' flag being used somewhere in execution.
This can be caused by:
1. A 'throw' flag being used somewhere in execution (a function your calling)
2. Sending ether to a contract which does not have the 'payable' modifier on the fallback:
function () payable {}
3. A send or transaction was out of gas
`;
}
// if message includes
if (message.includes('invalid opcode') || message.includes('invalid op code')) {
outputMessage = 'This can be caused by a contract which compiles fine, but doesnt execute properly in the Ethereum Virtual Machine. Such as using a `0x0` as an address.';
}
// if message includes
if (message.includes('out of gas')) {
outputMessage = `This error can be due to various scenarios:
1. A error caused somewhere in your contract
2. An error with the EVM module (npm: 'ethereumjs-vm')
3. An error caused by the wafr module
4. An error with the node simulation module (npm: 'ethereumjs-testrpc')
5. A wafr account actually being out of gas
6. The 'payable' flag not being used on a contract your sending ether too (common)
If you cannot resolve this issue with reasonable investigation,
report the error at:
http://github.com/SilentCicero/wafr/issues
If you believe the error is caused by the test node infrastructure,
report the error at:
http://github.com/ethereumjs/testrpc
If you believe the error is caused by the EVM module, report the error
at:
http://github.com/ethereumjs/ethereumjs-vm
`;
}
// return output message
return outputMessage;
} | javascript | function errorEnhancement(inputMessage) {
var message = inputMessage; // eslint-disable-line
var outputMessage = null; // eslint-disable-line
// if the input message is an array or object
if (inputMessage !== null
&& !isNaN(inputMessage)
&& typeof inputMessage !== 'string') {
message = JSON.stringify(inputMessage);
}
// gauentee string convertion, null and other..
message = String(message);
// if message includes
if (message.includes('Compiled contract not found')) {
outputMessage = 'This could be due to a contract with the same name being compiled. Wafr doesnt allow two contracts with the same name. Look to see if any of your contracts have the same name.';
}
// if message includes
if (message.includes('invalid JUMP')) {
outputMessage = `This can be caused by many things. One main cause is a 'throw' flag being used somewhere in execution.
This can be caused by:
1. A 'throw' flag being used somewhere in execution (a function your calling)
2. Sending ether to a contract which does not have the 'payable' modifier on the fallback:
function () payable {}
3. A send or transaction was out of gas
`;
}
// if message includes
if (message.includes('invalid opcode') || message.includes('invalid op code')) {
outputMessage = 'This can be caused by a contract which compiles fine, but doesnt execute properly in the Ethereum Virtual Machine. Such as using a `0x0` as an address.';
}
// if message includes
if (message.includes('out of gas')) {
outputMessage = `This error can be due to various scenarios:
1. A error caused somewhere in your contract
2. An error with the EVM module (npm: 'ethereumjs-vm')
3. An error caused by the wafr module
4. An error with the node simulation module (npm: 'ethereumjs-testrpc')
5. A wafr account actually being out of gas
6. The 'payable' flag not being used on a contract your sending ether too (common)
If you cannot resolve this issue with reasonable investigation,
report the error at:
http://github.com/SilentCicero/wafr/issues
If you believe the error is caused by the test node infrastructure,
report the error at:
http://github.com/ethereumjs/testrpc
If you believe the error is caused by the EVM module, report the error
at:
http://github.com/ethereumjs/ethereumjs-vm
`;
}
// return output message
return outputMessage;
} | [
"function",
"errorEnhancement",
"(",
"inputMessage",
")",
"{",
"var",
"message",
"=",
"inputMessage",
";",
"// eslint-disable-line",
"var",
"outputMessage",
"=",
"null",
";",
"// eslint-disable-line",
"// if the input message is an array or object",
"if",
"(",
"inputMessage",
"!==",
"null",
"&&",
"!",
"isNaN",
"(",
"inputMessage",
")",
"&&",
"typeof",
"inputMessage",
"!==",
"'string'",
")",
"{",
"message",
"=",
"JSON",
".",
"stringify",
"(",
"inputMessage",
")",
";",
"}",
"// gauentee string convertion, null and other..",
"message",
"=",
"String",
"(",
"message",
")",
";",
"// if message includes",
"if",
"(",
"message",
".",
"includes",
"(",
"'Compiled contract not found'",
")",
")",
"{",
"outputMessage",
"=",
"'This could be due to a contract with the same name being compiled. Wafr doesnt allow two contracts with the same name. Look to see if any of your contracts have the same name.'",
";",
"}",
"// if message includes",
"if",
"(",
"message",
".",
"includes",
"(",
"'invalid JUMP'",
")",
")",
"{",
"outputMessage",
"=",
"`",
"`",
";",
"}",
"// if message includes",
"if",
"(",
"message",
".",
"includes",
"(",
"'invalid opcode'",
")",
"||",
"message",
".",
"includes",
"(",
"'invalid op code'",
")",
")",
"{",
"outputMessage",
"=",
"'This can be caused by a contract which compiles fine, but doesnt execute properly in the Ethereum Virtual Machine. Such as using a `0x0` as an address.'",
";",
"}",
"// if message includes",
"if",
"(",
"message",
".",
"includes",
"(",
"'out of gas'",
")",
")",
"{",
"outputMessage",
"=",
"`",
"`",
";",
"}",
"// return output message",
"return",
"outputMessage",
";",
"}"
] | error enhancement, more information about bad errors | [
"error",
"enhancement",
"more",
"information",
"about",
"bad",
"errors"
] | 2c7483feec5df346d8903cab5badc17143c3876d | https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/src/utils/index.js#L298-L365 |
54,229 | SilentCicero/wafr | src/utils/index.js | increaseProviderTime | function increaseProviderTime(provider, time, callback) {
if (typeof time !== 'number') {
callback('error while increasing TestRPC provider time, time value must be a number.', null);
return;
}
provider.sendAsync({
method: 'evm_increaseTime',
params: [time],
}, (increaseTimeError) => {
if (increaseTimeError) {
callback(`error while increasing TestRPC provider time: ${JSON.stringify(increaseTimeError)}`, null);
} else {
provider.sendAsync({
method: 'evm_mine',
}, (mineError) => {
if (mineError) {
callback(`while mining block to increase time on TestRPC provider: ${JSON.stringify(mineError)}`, null);
} else {
callback(null, true);
}
});
}
});
} | javascript | function increaseProviderTime(provider, time, callback) {
if (typeof time !== 'number') {
callback('error while increasing TestRPC provider time, time value must be a number.', null);
return;
}
provider.sendAsync({
method: 'evm_increaseTime',
params: [time],
}, (increaseTimeError) => {
if (increaseTimeError) {
callback(`error while increasing TestRPC provider time: ${JSON.stringify(increaseTimeError)}`, null);
} else {
provider.sendAsync({
method: 'evm_mine',
}, (mineError) => {
if (mineError) {
callback(`while mining block to increase time on TestRPC provider: ${JSON.stringify(mineError)}`, null);
} else {
callback(null, true);
}
});
}
});
} | [
"function",
"increaseProviderTime",
"(",
"provider",
",",
"time",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"time",
"!==",
"'number'",
")",
"{",
"callback",
"(",
"'error while increasing TestRPC provider time, time value must be a number.'",
",",
"null",
")",
";",
"return",
";",
"}",
"provider",
".",
"sendAsync",
"(",
"{",
"method",
":",
"'evm_increaseTime'",
",",
"params",
":",
"[",
"time",
"]",
",",
"}",
",",
"(",
"increaseTimeError",
")",
"=>",
"{",
"if",
"(",
"increaseTimeError",
")",
"{",
"callback",
"(",
"`",
"${",
"JSON",
".",
"stringify",
"(",
"increaseTimeError",
")",
"}",
"`",
",",
"null",
")",
";",
"}",
"else",
"{",
"provider",
".",
"sendAsync",
"(",
"{",
"method",
":",
"'evm_mine'",
",",
"}",
",",
"(",
"mineError",
")",
"=>",
"{",
"if",
"(",
"mineError",
")",
"{",
"callback",
"(",
"`",
"${",
"JSON",
".",
"stringify",
"(",
"mineError",
")",
"}",
"`",
",",
"null",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"true",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | increase the testrpc provider time by a specific amount, then mine | [
"increase",
"the",
"testrpc",
"provider",
"time",
"by",
"a",
"specific",
"amount",
"then",
"mine"
] | 2c7483feec5df346d8903cab5badc17143c3876d | https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/src/utils/index.js#L384-L408 |
54,230 | SilentCicero/wafr | src/utils/index.js | increaseBlockRecursively | function increaseBlockRecursively(provider, count, total, callback) {
// if the count hits the total, stop the recursion
if (count >= total) {
callback(null, true);
} else {
// else mine a block
provider.sendAsync({
method: 'evm_mine',
}, (mineError) => {
if (mineError) {
callback(`while mining to increase block: ${JSON.stringify(mineError)}`, null);
} else {
increaseBlockRecursively(provider, count + 1, total, callback);
}
});
}
} | javascript | function increaseBlockRecursively(provider, count, total, callback) {
// if the count hits the total, stop the recursion
if (count >= total) {
callback(null, true);
} else {
// else mine a block
provider.sendAsync({
method: 'evm_mine',
}, (mineError) => {
if (mineError) {
callback(`while mining to increase block: ${JSON.stringify(mineError)}`, null);
} else {
increaseBlockRecursively(provider, count + 1, total, callback);
}
});
}
} | [
"function",
"increaseBlockRecursively",
"(",
"provider",
",",
"count",
",",
"total",
",",
"callback",
")",
"{",
"// if the count hits the total, stop the recursion",
"if",
"(",
"count",
">=",
"total",
")",
"{",
"callback",
"(",
"null",
",",
"true",
")",
";",
"}",
"else",
"{",
"// else mine a block",
"provider",
".",
"sendAsync",
"(",
"{",
"method",
":",
"'evm_mine'",
",",
"}",
",",
"(",
"mineError",
")",
"=>",
"{",
"if",
"(",
"mineError",
")",
"{",
"callback",
"(",
"`",
"${",
"JSON",
".",
"stringify",
"(",
"mineError",
")",
"}",
"`",
",",
"null",
")",
";",
"}",
"else",
"{",
"increaseBlockRecursively",
"(",
"provider",
",",
"count",
"+",
"1",
",",
"total",
",",
"callback",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | increase the TestRPC blocks by a specific count recursively | [
"increase",
"the",
"TestRPC",
"blocks",
"by",
"a",
"specific",
"count",
"recursively"
] | 2c7483feec5df346d8903cab5badc17143c3876d | https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/src/utils/index.js#L411-L427 |
54,231 | SilentCicero/wafr | src/utils/index.js | getBlockIncreaseFromName | function getBlockIncreaseFromName(methodName) {
const matchNumbers = String(methodName).match(/_increaseBlockBy(\d+)/);
if (matchNumbers !== null
&& typeof matchNumbers[1] === 'string') {
return parseInt(matchNumbers[1], 10);
}
return 0;
} | javascript | function getBlockIncreaseFromName(methodName) {
const matchNumbers = String(methodName).match(/_increaseBlockBy(\d+)/);
if (matchNumbers !== null
&& typeof matchNumbers[1] === 'string') {
return parseInt(matchNumbers[1], 10);
}
return 0;
} | [
"function",
"getBlockIncreaseFromName",
"(",
"methodName",
")",
"{",
"const",
"matchNumbers",
"=",
"String",
"(",
"methodName",
")",
".",
"match",
"(",
"/",
"_increaseBlockBy(\\d+)",
"/",
")",
";",
"if",
"(",
"matchNumbers",
"!==",
"null",
"&&",
"typeof",
"matchNumbers",
"[",
"1",
"]",
"===",
"'string'",
")",
"{",
"return",
"parseInt",
"(",
"matchNumbers",
"[",
"1",
"]",
",",
"10",
")",
";",
"}",
"return",
"0",
";",
"}"
] | get block increase value from method name | [
"get",
"block",
"increase",
"value",
"from",
"method",
"name"
] | 2c7483feec5df346d8903cab5badc17143c3876d | https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/src/utils/index.js#L435-L444 |
54,232 | SilentCicero/wafr | src/utils/index.js | getTimeIncreaseFromName | function getTimeIncreaseFromName(methodName) {
const matchNumbers = String(methodName).match(/_increaseTimeBy(\d+)/);
if (matchNumbers !== null
&& typeof matchNumbers[1] === 'string') {
return parseInt(matchNumbers[1], 10);
}
return 0;
} | javascript | function getTimeIncreaseFromName(methodName) {
const matchNumbers = String(methodName).match(/_increaseTimeBy(\d+)/);
if (matchNumbers !== null
&& typeof matchNumbers[1] === 'string') {
return parseInt(matchNumbers[1], 10);
}
return 0;
} | [
"function",
"getTimeIncreaseFromName",
"(",
"methodName",
")",
"{",
"const",
"matchNumbers",
"=",
"String",
"(",
"methodName",
")",
".",
"match",
"(",
"/",
"_increaseTimeBy(\\d+)",
"/",
")",
";",
"if",
"(",
"matchNumbers",
"!==",
"null",
"&&",
"typeof",
"matchNumbers",
"[",
"1",
"]",
"===",
"'string'",
")",
"{",
"return",
"parseInt",
"(",
"matchNumbers",
"[",
"1",
"]",
",",
"10",
")",
";",
"}",
"return",
"0",
";",
"}"
] | get time increase value from method name | [
"get",
"time",
"increase",
"value",
"from",
"method",
"name"
] | 2c7483feec5df346d8903cab5badc17143c3876d | https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/src/utils/index.js#L447-L456 |
54,233 | iolo/express-toybox | cors.js | cors | function cors(options) {
options = _.merge({}, DEF_CONFIG, options);
DEBUG && debug('configure http cors middleware', options);
return function (req, res, next) {
if (req.headers.origin) {
res.header('Access-Control-Allow-Origin', options.origin === '*' ? req.headers.origin : options.origin);
res.header('Access-Control-Allow-Methods', options.methods);
res.header('Access-Control-Allow-Headers', options.headers);
res.header('Access-Control-Allow-Credentials', options.credentials);
res.header('Access-Control-Max-Age', options.maxAge);
if ('OPTIONS' === req.method) {
// CORS pre-flight request -> no content
return res.send(errors.StatusCode.NO_CONTENT);
}
}
return next();
};
} | javascript | function cors(options) {
options = _.merge({}, DEF_CONFIG, options);
DEBUG && debug('configure http cors middleware', options);
return function (req, res, next) {
if (req.headers.origin) {
res.header('Access-Control-Allow-Origin', options.origin === '*' ? req.headers.origin : options.origin);
res.header('Access-Control-Allow-Methods', options.methods);
res.header('Access-Control-Allow-Headers', options.headers);
res.header('Access-Control-Allow-Credentials', options.credentials);
res.header('Access-Control-Max-Age', options.maxAge);
if ('OPTIONS' === req.method) {
// CORS pre-flight request -> no content
return res.send(errors.StatusCode.NO_CONTENT);
}
}
return next();
};
} | [
"function",
"cors",
"(",
"options",
")",
"{",
"options",
"=",
"_",
".",
"merge",
"(",
"{",
"}",
",",
"DEF_CONFIG",
",",
"options",
")",
";",
"DEBUG",
"&&",
"debug",
"(",
"'configure http cors middleware'",
",",
"options",
")",
";",
"return",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"req",
".",
"headers",
".",
"origin",
")",
"{",
"res",
".",
"header",
"(",
"'Access-Control-Allow-Origin'",
",",
"options",
".",
"origin",
"===",
"'*'",
"?",
"req",
".",
"headers",
".",
"origin",
":",
"options",
".",
"origin",
")",
";",
"res",
".",
"header",
"(",
"'Access-Control-Allow-Methods'",
",",
"options",
".",
"methods",
")",
";",
"res",
".",
"header",
"(",
"'Access-Control-Allow-Headers'",
",",
"options",
".",
"headers",
")",
";",
"res",
".",
"header",
"(",
"'Access-Control-Allow-Credentials'",
",",
"options",
".",
"credentials",
")",
";",
"res",
".",
"header",
"(",
"'Access-Control-Max-Age'",
",",
"options",
".",
"maxAge",
")",
";",
"if",
"(",
"'OPTIONS'",
"===",
"req",
".",
"method",
")",
"{",
"// CORS pre-flight request -> no content",
"return",
"res",
".",
"send",
"(",
"errors",
".",
"StatusCode",
".",
"NO_CONTENT",
")",
";",
"}",
"}",
"return",
"next",
"(",
")",
";",
"}",
";",
"}"
] | CORS middleware.
@param {*} options
@param {String} [options.origin='*']
@param {String} [options.methods]
@param {String} [options.headers]
@param {String} [options.credentials=false]
@param {String} [options.maxAge=24*60*60]
@returns {Function} connect/express middleware function
@see https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS | [
"CORS",
"middleware",
"."
] | c375a1388cfc167017e8dcd2325e71ca86ccb994 | https://github.com/iolo/express-toybox/blob/c375a1388cfc167017e8dcd2325e71ca86ccb994/cors.js#L31-L48 |
54,234 | jtheriault/code-copter | examples/analyzer-inline.spec.js | itSucks | function itSucks (fileSourceData) {
var errors = [];
for (let sample of fileSourceData) {
errors.push({
line: sample.line,
message: 'This code sucks: ' + sample.text
});
}
return {
// Too noisy to set ```errors: errors```
// It all sucks, so just say the sucking starts with the first one
errors: [{
line: errors.shift().line,
message: 'It sucks. Starting here.'
}],
pass: false
};
} | javascript | function itSucks (fileSourceData) {
var errors = [];
for (let sample of fileSourceData) {
errors.push({
line: sample.line,
message: 'This code sucks: ' + sample.text
});
}
return {
// Too noisy to set ```errors: errors```
// It all sucks, so just say the sucking starts with the first one
errors: [{
line: errors.shift().line,
message: 'It sucks. Starting here.'
}],
pass: false
};
} | [
"function",
"itSucks",
"(",
"fileSourceData",
")",
"{",
"var",
"errors",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"sample",
"of",
"fileSourceData",
")",
"{",
"errors",
".",
"push",
"(",
"{",
"line",
":",
"sample",
".",
"line",
",",
"message",
":",
"'This code sucks: '",
"+",
"sample",
".",
"text",
"}",
")",
";",
"}",
"return",
"{",
"// Too noisy to set ```errors: errors```",
"// It all sucks, so just say the sucking starts with the first one",
"errors",
":",
"[",
"{",
"line",
":",
"errors",
".",
"shift",
"(",
")",
".",
"line",
",",
"message",
":",
"'It sucks. Starting here.'",
"}",
"]",
",",
"pass",
":",
"false",
"}",
";",
"}"
] | A pretty harsh analyzer that passes NO files for the reason that "it sucks" starting on line 1.
@param {FileSourceData} fileSourceData - The file source data to analyze.
@returns {Object} An object consistent with a code-copter Analysis object bearing the inevitable message that the code in the analyzed file sucks. | [
"A",
"pretty",
"harsh",
"analyzer",
"that",
"passes",
"NO",
"files",
"for",
"the",
"reason",
"that",
"it",
"sucks",
"starting",
"on",
"line",
"1",
"."
] | e69f22e1c9de5d59d15958a09d732ce8d8b519fb | https://github.com/jtheriault/code-copter/blob/e69f22e1c9de5d59d15958a09d732ce8d8b519fb/examples/analyzer-inline.spec.js#L10-L29 |
54,235 | iolo/express-toybox | error404.js | error404 | function error404(options) {
options = _.merge({}, DEF_CONFIG, options);
// pre-compile underscore template if available
if (typeof options.template === 'string' && options.template.length > 0) {
options.template = _.template(options.template);
}
return function (req, res, next) {
var error = {
status: options.status,
code: options.code,
message: options.message,
cause: {path: req.path, url: req.url, originalUrl: req.originalUrl, baseUrl: req.baseUrl, query: req.query}
};
res.status(error.status);
switch (req.accepts(['json', 'html'])) {
case 'json':
return res.json(error);
case 'html':
if (typeof options.template === 'function') {
res.type('html');
return res.send(options.template({error: error}));
}
return res.render(options.view, {error: error});
}
return res.send(options.message);
};
} | javascript | function error404(options) {
options = _.merge({}, DEF_CONFIG, options);
// pre-compile underscore template if available
if (typeof options.template === 'string' && options.template.length > 0) {
options.template = _.template(options.template);
}
return function (req, res, next) {
var error = {
status: options.status,
code: options.code,
message: options.message,
cause: {path: req.path, url: req.url, originalUrl: req.originalUrl, baseUrl: req.baseUrl, query: req.query}
};
res.status(error.status);
switch (req.accepts(['json', 'html'])) {
case 'json':
return res.json(error);
case 'html':
if (typeof options.template === 'function') {
res.type('html');
return res.send(options.template({error: error}));
}
return res.render(options.view, {error: error});
}
return res.send(options.message);
};
} | [
"function",
"error404",
"(",
"options",
")",
"{",
"options",
"=",
"_",
".",
"merge",
"(",
"{",
"}",
",",
"DEF_CONFIG",
",",
"options",
")",
";",
"// pre-compile underscore template if available",
"if",
"(",
"typeof",
"options",
".",
"template",
"===",
"'string'",
"&&",
"options",
".",
"template",
".",
"length",
">",
"0",
")",
"{",
"options",
".",
"template",
"=",
"_",
".",
"template",
"(",
"options",
".",
"template",
")",
";",
"}",
"return",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"error",
"=",
"{",
"status",
":",
"options",
".",
"status",
",",
"code",
":",
"options",
".",
"code",
",",
"message",
":",
"options",
".",
"message",
",",
"cause",
":",
"{",
"path",
":",
"req",
".",
"path",
",",
"url",
":",
"req",
".",
"url",
",",
"originalUrl",
":",
"req",
".",
"originalUrl",
",",
"baseUrl",
":",
"req",
".",
"baseUrl",
",",
"query",
":",
"req",
".",
"query",
"}",
"}",
";",
"res",
".",
"status",
"(",
"error",
".",
"status",
")",
";",
"switch",
"(",
"req",
".",
"accepts",
"(",
"[",
"'json'",
",",
"'html'",
"]",
")",
")",
"{",
"case",
"'json'",
":",
"return",
"res",
".",
"json",
"(",
"error",
")",
";",
"case",
"'html'",
":",
"if",
"(",
"typeof",
"options",
".",
"template",
"===",
"'function'",
")",
"{",
"res",
".",
"type",
"(",
"'html'",
")",
";",
"return",
"res",
".",
"send",
"(",
"options",
".",
"template",
"(",
"{",
"error",
":",
"error",
"}",
")",
")",
";",
"}",
"return",
"res",
".",
"render",
"(",
"options",
".",
"view",
",",
"{",
"error",
":",
"error",
"}",
")",
";",
"}",
"return",
"res",
".",
"send",
"(",
"options",
".",
"message",
")",
";",
"}",
";",
"}"
] | express 404 error handler.
@param {*} options
@param {Number} [options.status=404]
@param {Number} [options.code=8404]
@param {String} [options.message='Not Found']
@param {String|Function} [options.template] lodash(underscore) micro template for html 404 error page.
@param {String} [options.view='errors/404'] express view path of html 404 error page.
@returns {Function} express request handler | [
"express",
"404",
"error",
"handler",
"."
] | c375a1388cfc167017e8dcd2325e71ca86ccb994 | https://github.com/iolo/express-toybox/blob/c375a1388cfc167017e8dcd2325e71ca86ccb994/error404.js#L30-L61 |
54,236 | haasz/laravel-mix-ext | src/logger.js | TemplateFileLog | function TemplateFileLog(src, target) {
this.templateFile = {
source: src,
target: target
};
this.isCompilationPerfect = true;
this.templateTagLogs = new Table({
chars: {
'top-mid': '',
'bottom-mid': '',
'middle': '',
'mid-mid': '',
},
style: {},
});
} | javascript | function TemplateFileLog(src, target) {
this.templateFile = {
source: src,
target: target
};
this.isCompilationPerfect = true;
this.templateTagLogs = new Table({
chars: {
'top-mid': '',
'bottom-mid': '',
'middle': '',
'mid-mid': '',
},
style: {},
});
} | [
"function",
"TemplateFileLog",
"(",
"src",
",",
"target",
")",
"{",
"this",
".",
"templateFile",
"=",
"{",
"source",
":",
"src",
",",
"target",
":",
"target",
"}",
";",
"this",
".",
"isCompilationPerfect",
"=",
"true",
";",
"this",
".",
"templateTagLogs",
"=",
"new",
"Table",
"(",
"{",
"chars",
":",
"{",
"'top-mid'",
":",
"''",
",",
"'bottom-mid'",
":",
"''",
",",
"'middle'",
":",
"''",
",",
"'mid-mid'",
":",
"''",
",",
"}",
",",
"style",
":",
"{",
"}",
",",
"}",
")",
";",
"}"
] | The TemplateFileLog type
Create a template file log.
@constructor
@param {string} src The source template file.
@param {string} target The compiled target file. | [
"The",
"TemplateFileLog",
"type"
] | bd1c794bdbf934dae233ab697dc5d5593d4b1124 | https://github.com/haasz/laravel-mix-ext/blob/bd1c794bdbf934dae233ab697dc5d5593d4b1124/src/logger.js#L153-L168 |
54,237 | gunins/stonewall | dist/es5/dev/widget/Constructor.js | render | function render(data) {
if (!this._rendered) {
if (this.template) {
if (data) {
this.data = data;
}
var options = this._options,
parentChildren = this._parentChildren,
decoder = new Decoder(this.template),
template = decoder.render(this.data);
if (this.el) {
var parent = this.el.parentNode;
if (parent) {
parent.replaceChild(template.fragment, this.el);
}
if (this.elGroup && this.elGroup.get(this.el)) {
this.elGroup.delete(this.el);
this.el = template.fragment;
this.elGroup.set(template.fragment, this);
}
} else {
this.el = template.fragment;
}
this.root = new dom.Element(template.fragment, {
name: 'root',
data: {}
});
this.children = applyElement(template.children, options);
applyParent(this, parentChildren, this.data);
this.bindings = setBinders(this.children, true);
if (this.data) {
this.applyBinders(this.data, this);
}
setRoutes(this.children, this.context);
addChildren(this, this.root);
this.rendered.apply(this, _toConsumableArray(this._arguments));
this._rendered = true;
} else {
var HTMLelement = document.createElement('div');
this.root = new dom.Element(HTMLelement, {
name: 'root',
data: {}
});
if (this.el) {
var _parent = this.el.parentNode;
if (_parent) {
_parent.replaceChild(HTMLelement, this.el);
}
}
this.el = HTMLelement;
this.children = {};
addChildren(this, this.root);
this.rendered.apply(this, _toConsumableArray(this._arguments));
this._rendered = true;
}
}
} | javascript | function render(data) {
if (!this._rendered) {
if (this.template) {
if (data) {
this.data = data;
}
var options = this._options,
parentChildren = this._parentChildren,
decoder = new Decoder(this.template),
template = decoder.render(this.data);
if (this.el) {
var parent = this.el.parentNode;
if (parent) {
parent.replaceChild(template.fragment, this.el);
}
if (this.elGroup && this.elGroup.get(this.el)) {
this.elGroup.delete(this.el);
this.el = template.fragment;
this.elGroup.set(template.fragment, this);
}
} else {
this.el = template.fragment;
}
this.root = new dom.Element(template.fragment, {
name: 'root',
data: {}
});
this.children = applyElement(template.children, options);
applyParent(this, parentChildren, this.data);
this.bindings = setBinders(this.children, true);
if (this.data) {
this.applyBinders(this.data, this);
}
setRoutes(this.children, this.context);
addChildren(this, this.root);
this.rendered.apply(this, _toConsumableArray(this._arguments));
this._rendered = true;
} else {
var HTMLelement = document.createElement('div');
this.root = new dom.Element(HTMLelement, {
name: 'root',
data: {}
});
if (this.el) {
var _parent = this.el.parentNode;
if (_parent) {
_parent.replaceChild(HTMLelement, this.el);
}
}
this.el = HTMLelement;
this.children = {};
addChildren(this, this.root);
this.rendered.apply(this, _toConsumableArray(this._arguments));
this._rendered = true;
}
}
} | [
"function",
"render",
"(",
"data",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_rendered",
")",
"{",
"if",
"(",
"this",
".",
"template",
")",
"{",
"if",
"(",
"data",
")",
"{",
"this",
".",
"data",
"=",
"data",
";",
"}",
"var",
"options",
"=",
"this",
".",
"_options",
",",
"parentChildren",
"=",
"this",
".",
"_parentChildren",
",",
"decoder",
"=",
"new",
"Decoder",
"(",
"this",
".",
"template",
")",
",",
"template",
"=",
"decoder",
".",
"render",
"(",
"this",
".",
"data",
")",
";",
"if",
"(",
"this",
".",
"el",
")",
"{",
"var",
"parent",
"=",
"this",
".",
"el",
".",
"parentNode",
";",
"if",
"(",
"parent",
")",
"{",
"parent",
".",
"replaceChild",
"(",
"template",
".",
"fragment",
",",
"this",
".",
"el",
")",
";",
"}",
"if",
"(",
"this",
".",
"elGroup",
"&&",
"this",
".",
"elGroup",
".",
"get",
"(",
"this",
".",
"el",
")",
")",
"{",
"this",
".",
"elGroup",
".",
"delete",
"(",
"this",
".",
"el",
")",
";",
"this",
".",
"el",
"=",
"template",
".",
"fragment",
";",
"this",
".",
"elGroup",
".",
"set",
"(",
"template",
".",
"fragment",
",",
"this",
")",
";",
"}",
"}",
"else",
"{",
"this",
".",
"el",
"=",
"template",
".",
"fragment",
";",
"}",
"this",
".",
"root",
"=",
"new",
"dom",
".",
"Element",
"(",
"template",
".",
"fragment",
",",
"{",
"name",
":",
"'root'",
",",
"data",
":",
"{",
"}",
"}",
")",
";",
"this",
".",
"children",
"=",
"applyElement",
"(",
"template",
".",
"children",
",",
"options",
")",
";",
"applyParent",
"(",
"this",
",",
"parentChildren",
",",
"this",
".",
"data",
")",
";",
"this",
".",
"bindings",
"=",
"setBinders",
"(",
"this",
".",
"children",
",",
"true",
")",
";",
"if",
"(",
"this",
".",
"data",
")",
"{",
"this",
".",
"applyBinders",
"(",
"this",
".",
"data",
",",
"this",
")",
";",
"}",
"setRoutes",
"(",
"this",
".",
"children",
",",
"this",
".",
"context",
")",
";",
"addChildren",
"(",
"this",
",",
"this",
".",
"root",
")",
";",
"this",
".",
"rendered",
".",
"apply",
"(",
"this",
",",
"_toConsumableArray",
"(",
"this",
".",
"_arguments",
")",
")",
";",
"this",
".",
"_rendered",
"=",
"true",
";",
"}",
"else",
"{",
"var",
"HTMLelement",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"this",
".",
"root",
"=",
"new",
"dom",
".",
"Element",
"(",
"HTMLelement",
",",
"{",
"name",
":",
"'root'",
",",
"data",
":",
"{",
"}",
"}",
")",
";",
"if",
"(",
"this",
".",
"el",
")",
"{",
"var",
"_parent",
"=",
"this",
".",
"el",
".",
"parentNode",
";",
"if",
"(",
"_parent",
")",
"{",
"_parent",
".",
"replaceChild",
"(",
"HTMLelement",
",",
"this",
".",
"el",
")",
";",
"}",
"}",
"this",
".",
"el",
"=",
"HTMLelement",
";",
"this",
".",
"children",
"=",
"{",
"}",
";",
"addChildren",
"(",
"this",
",",
"this",
".",
"root",
")",
";",
"this",
".",
"rendered",
".",
"apply",
"(",
"this",
",",
"_toConsumableArray",
"(",
"this",
".",
"_arguments",
")",
")",
";",
"this",
".",
"_rendered",
"=",
"true",
";",
"}",
"}",
"}"
] | method render called manually if flag async is true; @method render | [
"method",
"render",
"called",
"manually",
"if",
"flag",
"async",
"is",
"true",
";"
] | eebc6376f83115b6e29d4539582830e917f0e80e | https://github.com/gunins/stonewall/blob/eebc6376f83115b6e29d4539582830e917f0e80e/dist/es5/dev/widget/Constructor.js#L1285-L1346 |
54,238 | gunins/stonewall | dist/es5/dev/widget/Constructor.js | loadCss | function loadCss(url) {
if (this.context._cssReady.indexOf(url) === -1) {
this.context._cssReady.push(url);
var linkRef = document.createElement("link");
linkRef.setAttribute("rel", "stylesheet");
linkRef.setAttribute("type", "text/css");
linkRef.setAttribute("href", url);
if (typeof linkRef != "undefined") {
document.getElementsByTagName("head")[0].appendChild(linkRef);
}
}
} | javascript | function loadCss(url) {
if (this.context._cssReady.indexOf(url) === -1) {
this.context._cssReady.push(url);
var linkRef = document.createElement("link");
linkRef.setAttribute("rel", "stylesheet");
linkRef.setAttribute("type", "text/css");
linkRef.setAttribute("href", url);
if (typeof linkRef != "undefined") {
document.getElementsByTagName("head")[0].appendChild(linkRef);
}
}
} | [
"function",
"loadCss",
"(",
"url",
")",
"{",
"if",
"(",
"this",
".",
"context",
".",
"_cssReady",
".",
"indexOf",
"(",
"url",
")",
"===",
"-",
"1",
")",
"{",
"this",
".",
"context",
".",
"_cssReady",
".",
"push",
"(",
"url",
")",
";",
"var",
"linkRef",
"=",
"document",
".",
"createElement",
"(",
"\"link\"",
")",
";",
"linkRef",
".",
"setAttribute",
"(",
"\"rel\"",
",",
"\"stylesheet\"",
")",
";",
"linkRef",
".",
"setAttribute",
"(",
"\"type\"",
",",
"\"text/css\"",
")",
";",
"linkRef",
".",
"setAttribute",
"(",
"\"href\"",
",",
"url",
")",
";",
"if",
"(",
"typeof",
"linkRef",
"!=",
"\"undefined\"",
")",
"{",
"document",
".",
"getElementsByTagName",
"(",
"\"head\"",
")",
"[",
"0",
"]",
".",
"appendChild",
"(",
"linkRef",
")",
";",
"}",
"}",
"}"
] | Load external css style for third party modules. @method loadCss @param {string} url | [
"Load",
"external",
"css",
"style",
"for",
"third",
"party",
"modules",
"."
] | eebc6376f83115b6e29d4539582830e917f0e80e | https://github.com/gunins/stonewall/blob/eebc6376f83115b6e29d4539582830e917f0e80e/dist/es5/dev/widget/Constructor.js#L1394-L1405 |
54,239 | gunins/stonewall | dist/es5/dev/widget/Constructor.js | detach | function detach() {
if (!this._placeholder) {
this._placeholder = document.createElement(this.el.tagName);
}
if (!this._parent) {
this._parent = this.el.parentNode;
}
if (this.el && this._parent) {
this._parent.replaceChild(this._placeholder, this.el);
}
} | javascript | function detach() {
if (!this._placeholder) {
this._placeholder = document.createElement(this.el.tagName);
}
if (!this._parent) {
this._parent = this.el.parentNode;
}
if (this.el && this._parent) {
this._parent.replaceChild(this._placeholder, this.el);
}
} | [
"function",
"detach",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_placeholder",
")",
"{",
"this",
".",
"_placeholder",
"=",
"document",
".",
"createElement",
"(",
"this",
".",
"el",
".",
"tagName",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"_parent",
")",
"{",
"this",
".",
"_parent",
"=",
"this",
".",
"el",
".",
"parentNode",
";",
"}",
"if",
"(",
"this",
".",
"el",
"&&",
"this",
".",
"_parent",
")",
"{",
"this",
".",
"_parent",
".",
"replaceChild",
"(",
"this",
".",
"_placeholder",
",",
"this",
".",
"el",
")",
";",
"}",
"}"
] | Remove from parentNode @method detach | [
"Remove",
"from",
"parentNode"
] | eebc6376f83115b6e29d4539582830e917f0e80e | https://github.com/gunins/stonewall/blob/eebc6376f83115b6e29d4539582830e917f0e80e/dist/es5/dev/widget/Constructor.js#L1413-L1424 |
54,240 | gunins/stonewall | dist/es5/dev/widget/Constructor.js | destroy | function destroy() {
this.onDestroy();
this.eventBus.clear();
while (this._events.length > 0) {
this._events.shift().remove();
}
while (this._globalEvents.length > 0) {
this._globalEvents.shift().remove();
}
_destroy(this.children);
if (this.elGroup !== undefined && this.el !== undefined) {
this.elGroup.delete(this.el);
}
if (this.root && this.root.remove) {
this.root.remove();
}
delete this.el;
} | javascript | function destroy() {
this.onDestroy();
this.eventBus.clear();
while (this._events.length > 0) {
this._events.shift().remove();
}
while (this._globalEvents.length > 0) {
this._globalEvents.shift().remove();
}
_destroy(this.children);
if (this.elGroup !== undefined && this.el !== undefined) {
this.elGroup.delete(this.el);
}
if (this.root && this.root.remove) {
this.root.remove();
}
delete this.el;
} | [
"function",
"destroy",
"(",
")",
"{",
"this",
".",
"onDestroy",
"(",
")",
";",
"this",
".",
"eventBus",
".",
"clear",
"(",
")",
";",
"while",
"(",
"this",
".",
"_events",
".",
"length",
">",
"0",
")",
"{",
"this",
".",
"_events",
".",
"shift",
"(",
")",
".",
"remove",
"(",
")",
";",
"}",
"while",
"(",
"this",
".",
"_globalEvents",
".",
"length",
">",
"0",
")",
"{",
"this",
".",
"_globalEvents",
".",
"shift",
"(",
")",
".",
"remove",
"(",
")",
";",
"}",
"_destroy",
"(",
"this",
".",
"children",
")",
";",
"if",
"(",
"this",
".",
"elGroup",
"!==",
"undefined",
"&&",
"this",
".",
"el",
"!==",
"undefined",
")",
"{",
"this",
".",
"elGroup",
".",
"delete",
"(",
"this",
".",
"el",
")",
";",
"}",
"if",
"(",
"this",
".",
"root",
"&&",
"this",
".",
"root",
".",
"remove",
")",
"{",
"this",
".",
"root",
".",
"remove",
"(",
")",
";",
"}",
"delete",
"this",
".",
"el",
";",
"}"
] | Removing widget from Dom @method destroy | [
"Removing",
"widget",
"from",
"Dom"
] | eebc6376f83115b6e29d4539582830e917f0e80e | https://github.com/gunins/stonewall/blob/eebc6376f83115b6e29d4539582830e917f0e80e/dist/es5/dev/widget/Constructor.js#L1452-L1473 |
54,241 | gunins/stonewall | dist/es5/dev/widget/Constructor.js | addComponent | function addComponent(Component, options) {
var name = options.name,
container = options.container;
if (name === undefined) {
throw 'you have to define data.name for component.';
} else if (container === undefined) {
throw 'You have to define container for component.';
} else if (this.children[name] !== undefined) {
throw 'Component using name:' + name + '! already defined.';
}
var component = this.setComponent(Component, options),
instance = component.run(options.container);
instance.setContext(this.context);
this.children[name] = instance;
return instance;
} | javascript | function addComponent(Component, options) {
var name = options.name,
container = options.container;
if (name === undefined) {
throw 'you have to define data.name for component.';
} else if (container === undefined) {
throw 'You have to define container for component.';
} else if (this.children[name] !== undefined) {
throw 'Component using name:' + name + '! already defined.';
}
var component = this.setComponent(Component, options),
instance = component.run(options.container);
instance.setContext(this.context);
this.children[name] = instance;
return instance;
} | [
"function",
"addComponent",
"(",
"Component",
",",
"options",
")",
"{",
"var",
"name",
"=",
"options",
".",
"name",
",",
"container",
"=",
"options",
".",
"container",
";",
"if",
"(",
"name",
"===",
"undefined",
")",
"{",
"throw",
"'you have to define data.name for component.'",
";",
"}",
"else",
"if",
"(",
"container",
"===",
"undefined",
")",
"{",
"throw",
"'You have to define container for component.'",
";",
"}",
"else",
"if",
"(",
"this",
".",
"children",
"[",
"name",
"]",
"!==",
"undefined",
")",
"{",
"throw",
"'Component using name:'",
"+",
"name",
"+",
"'! already defined.'",
";",
"}",
"var",
"component",
"=",
"this",
".",
"setComponent",
"(",
"Component",
",",
"options",
")",
",",
"instance",
"=",
"component",
".",
"run",
"(",
"options",
".",
"container",
")",
";",
"instance",
".",
"setContext",
"(",
"this",
".",
"context",
")",
";",
"this",
".",
"children",
"[",
"name",
"]",
"=",
"instance",
";",
"return",
"instance",
";",
"}"
] | Adding Dynamic components @method addComponent @param {String} name @param {Constructor} Component @param {Element} container @param {Object} data (data attributes) @param {Object} children @param {Object} dataSet (Model for bindings) | [
"Adding",
"Dynamic",
"components"
] | eebc6376f83115b6e29d4539582830e917f0e80e | https://github.com/gunins/stonewall/blob/eebc6376f83115b6e29d4539582830e917f0e80e/dist/es5/dev/widget/Constructor.js#L1515-L1531 |
54,242 | tmpfs/ttycolor | lib/ansi.js | open | function open(code, attr) {
return attr ? ANSI_OPEN + attr + ';' + code + ANSI_FINAL
: ANSI_OPEN + code + ANSI_FINAL;
} | javascript | function open(code, attr) {
return attr ? ANSI_OPEN + attr + ';' + code + ANSI_FINAL
: ANSI_OPEN + code + ANSI_FINAL;
} | [
"function",
"open",
"(",
"code",
",",
"attr",
")",
"{",
"return",
"attr",
"?",
"ANSI_OPEN",
"+",
"attr",
"+",
"';'",
"+",
"code",
"+",
"ANSI_FINAL",
":",
"ANSI_OPEN",
"+",
"code",
"+",
"ANSI_FINAL",
";",
"}"
] | Open an escape sequence.
@param code The color code.
@param attr An optional attribute code. | [
"Open",
"an",
"escape",
"sequence",
"."
] | 4b72de7f61bfd922f227f3f4e7c61fb95ff9c023 | https://github.com/tmpfs/ttycolor/blob/4b72de7f61bfd922f227f3f4e7c61fb95ff9c023/lib/ansi.js#L14-L17 |
54,243 | tmpfs/ttycolor | lib/ansi.js | stringify | function stringify(value, code, attr, tag) {
var s = open(code, attr);
s += close(value, tag);
return s;
} | javascript | function stringify(value, code, attr, tag) {
var s = open(code, attr);
s += close(value, tag);
return s;
} | [
"function",
"stringify",
"(",
"value",
",",
"code",
",",
"attr",
",",
"tag",
")",
"{",
"var",
"s",
"=",
"open",
"(",
"code",
",",
"attr",
")",
";",
"s",
"+=",
"close",
"(",
"value",
",",
"tag",
")",
";",
"return",
"s",
";",
"}"
] | Low-level method for creating escaped string sequences.
@param value The value to escape.
@param code The color code.
@param attr An optional attribute code.
@param tag A specific closing tag to use. | [
"Low",
"-",
"level",
"method",
"for",
"creating",
"escaped",
"string",
"sequences",
"."
] | 4b72de7f61bfd922f227f3f4e7c61fb95ff9c023 | https://github.com/tmpfs/ttycolor/blob/4b72de7f61bfd922f227f3f4e7c61fb95ff9c023/lib/ansi.js#L36-L40 |
54,244 | tmpfs/ttycolor | lib/ansi.js | function(value, key, parent){
this.t = definition.colors; // table of color codes
this.v = value; // value wrapped by this instance
this.k = key; // property name, eg 'red'
this.p = parent; // parent
this.a = null; // attribute
} | javascript | function(value, key, parent){
this.t = definition.colors; // table of color codes
this.v = value; // value wrapped by this instance
this.k = key; // property name, eg 'red'
this.p = parent; // parent
this.a = null; // attribute
} | [
"function",
"(",
"value",
",",
"key",
",",
"parent",
")",
"{",
"this",
".",
"t",
"=",
"definition",
".",
"colors",
";",
"// table of color codes",
"this",
".",
"v",
"=",
"value",
";",
"// value wrapped by this instance",
"this",
".",
"k",
"=",
"key",
";",
"// property name, eg 'red'",
"this",
".",
"p",
"=",
"parent",
";",
"// parent",
"this",
".",
"a",
"=",
"null",
";",
"// attribute",
"}"
] | Chainable color builder.
@param value The underlying value to be escaped.
@param key The key for the code lookup.
@param parent A parent color instance. | [
"Chainable",
"color",
"builder",
"."
] | 4b72de7f61bfd922f227f3f4e7c61fb95ff9c023 | https://github.com/tmpfs/ttycolor/blob/4b72de7f61bfd922f227f3f4e7c61fb95ff9c023/lib/ansi.js#L49-L55 |
|
54,245 | dcodeIO/SourceCon | src/SourceCon.js | pack | function pack(id, type, body) {
var buf = new Buffer(body.length + 14);
buf.writeInt32LE(body.length + 10, 0);
buf.writeInt32LE(id, 4);
buf.writeInt32LE(type, 8);
body.copy(buf, 12);
buf[buf.length-2] = 0;
buf[buf.length-1] = 0;
return buf;
} | javascript | function pack(id, type, body) {
var buf = new Buffer(body.length + 14);
buf.writeInt32LE(body.length + 10, 0);
buf.writeInt32LE(id, 4);
buf.writeInt32LE(type, 8);
body.copy(buf, 12);
buf[buf.length-2] = 0;
buf[buf.length-1] = 0;
return buf;
} | [
"function",
"pack",
"(",
"id",
",",
"type",
",",
"body",
")",
"{",
"var",
"buf",
"=",
"new",
"Buffer",
"(",
"body",
".",
"length",
"+",
"14",
")",
";",
"buf",
".",
"writeInt32LE",
"(",
"body",
".",
"length",
"+",
"10",
",",
"0",
")",
";",
"buf",
".",
"writeInt32LE",
"(",
"id",
",",
"4",
")",
";",
"buf",
".",
"writeInt32LE",
"(",
"type",
",",
"8",
")",
";",
"body",
".",
"copy",
"(",
"buf",
",",
"12",
")",
";",
"buf",
"[",
"buf",
".",
"length",
"-",
"2",
"]",
"=",
"0",
";",
"buf",
"[",
"buf",
".",
"length",
"-",
"1",
"]",
"=",
"0",
";",
"return",
"buf",
";",
"}"
] | Creates a request packet.
@param {number} id Request id
@param {number} type Request type
@param {!Buffer} body Request data
@returns {!Buffer} | [
"Creates",
"a",
"request",
"packet",
"."
] | 20a800dc5d1599fd07e0076afdd7f017f7744def | https://github.com/dcodeIO/SourceCon/blob/20a800dc5d1599fd07e0076afdd7f017f7744def/src/SourceCon.js#L206-L215 |
54,246 | aledbf/deis-api | lib/limits.js | list | function list(appName, callback) {
if (!appName) {
return callback(ArgumentError('appName'));
}
var uri = format('/%s/apps/%s/config/', deis.version, appName);
commons.get(uri, function onListResponse(err, result) {
console.log(result);
callback(err, result ? extractLimits(result) : null);
});
} | javascript | function list(appName, callback) {
if (!appName) {
return callback(ArgumentError('appName'));
}
var uri = format('/%s/apps/%s/config/', deis.version, appName);
commons.get(uri, function onListResponse(err, result) {
console.log(result);
callback(err, result ? extractLimits(result) : null);
});
} | [
"function",
"list",
"(",
"appName",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"appName",
")",
"{",
"return",
"callback",
"(",
"ArgumentError",
"(",
"'appName'",
")",
")",
";",
"}",
"var",
"uri",
"=",
"format",
"(",
"'/%s/apps/%s/config/'",
",",
"deis",
".",
"version",
",",
"appName",
")",
";",
"commons",
".",
"get",
"(",
"uri",
",",
"function",
"onListResponse",
"(",
"err",
",",
"result",
")",
"{",
"console",
".",
"log",
"(",
"result",
")",
";",
"callback",
"(",
"err",
",",
"result",
"?",
"extractLimits",
"(",
"result",
")",
":",
"null",
")",
";",
"}",
")",
";",
"}"
] | list resource limits for an app | [
"list",
"resource",
"limits",
"for",
"an",
"app"
] | f0833789998032b11221a3a617bb566ade1fcc13 | https://github.com/aledbf/deis-api/blob/f0833789998032b11221a3a617bb566ade1fcc13/lib/limits.js#L30-L40 |
54,247 | aledbf/deis-api | lib/limits.js | set | function set(appName, limits, callback) {
if (!isObject(limits)) {
return callback(new Error('To set a variable pass an object'));
}
var keyValues = {};
if (limits.hasOwnProperty('memory')) {
keyValues.memory = limits.memory;
}
if (limits.hasOwnProperty('cpu')) {
keyValues.cpu = limits.cpu;
}
if (Object.keys(keyValues).length === 0) {
return callback(new Error('Only cpu and memory limits are valid'));
}
commons.post(format('/%s/apps/%s/config/', deis.version, appName), keyValues,
function onSetResponse(err, result) {
callback(err, result ? extractLimits(result) : null);
});
} | javascript | function set(appName, limits, callback) {
if (!isObject(limits)) {
return callback(new Error('To set a variable pass an object'));
}
var keyValues = {};
if (limits.hasOwnProperty('memory')) {
keyValues.memory = limits.memory;
}
if (limits.hasOwnProperty('cpu')) {
keyValues.cpu = limits.cpu;
}
if (Object.keys(keyValues).length === 0) {
return callback(new Error('Only cpu and memory limits are valid'));
}
commons.post(format('/%s/apps/%s/config/', deis.version, appName), keyValues,
function onSetResponse(err, result) {
callback(err, result ? extractLimits(result) : null);
});
} | [
"function",
"set",
"(",
"appName",
",",
"limits",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"isObject",
"(",
"limits",
")",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'To set a variable pass an object'",
")",
")",
";",
"}",
"var",
"keyValues",
"=",
"{",
"}",
";",
"if",
"(",
"limits",
".",
"hasOwnProperty",
"(",
"'memory'",
")",
")",
"{",
"keyValues",
".",
"memory",
"=",
"limits",
".",
"memory",
";",
"}",
"if",
"(",
"limits",
".",
"hasOwnProperty",
"(",
"'cpu'",
")",
")",
"{",
"keyValues",
".",
"cpu",
"=",
"limits",
".",
"cpu",
";",
"}",
"if",
"(",
"Object",
".",
"keys",
"(",
"keyValues",
")",
".",
"length",
"===",
"0",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'Only cpu and memory limits are valid'",
")",
")",
";",
"}",
"commons",
".",
"post",
"(",
"format",
"(",
"'/%s/apps/%s/config/'",
",",
"deis",
".",
"version",
",",
"appName",
")",
",",
"keyValues",
",",
"function",
"onSetResponse",
"(",
"err",
",",
"result",
")",
"{",
"callback",
"(",
"err",
",",
"result",
"?",
"extractLimits",
"(",
"result",
")",
":",
"null",
")",
";",
"}",
")",
";",
"}"
] | set resource limits for an app | [
"set",
"resource",
"limits",
"for",
"an",
"app"
] | f0833789998032b11221a3a617bb566ade1fcc13 | https://github.com/aledbf/deis-api/blob/f0833789998032b11221a3a617bb566ade1fcc13/lib/limits.js#L45-L68 |
54,248 | aledbf/deis-api | lib/limits.js | unset | function unset(appName, limitType, procType, callback) {
if (!appName) {
return callback(ArgumentError('appName'));
}
if (!limitType) {
return callback(ArgumentError('limitType'));
}
if (!procType) {
return callback(ArgumentError('procType'));
}
var keyValues = {};
if (limitType === 'memory') {
keyValues.memory = {};
keyValues.memory[procType] = null;
}
if (limitType === 'cpu') {
keyValues.cpu = {};
keyValues.cpu[procType] = null;
}
commons.post(format('/%s/apps/%s/config/', deis.version, appName), keyValues,
function onUnsetResponse(err, result) {
console.log(result);
callback(err, result ? extractLimits(result) : null);
});
} | javascript | function unset(appName, limitType, procType, callback) {
if (!appName) {
return callback(ArgumentError('appName'));
}
if (!limitType) {
return callback(ArgumentError('limitType'));
}
if (!procType) {
return callback(ArgumentError('procType'));
}
var keyValues = {};
if (limitType === 'memory') {
keyValues.memory = {};
keyValues.memory[procType] = null;
}
if (limitType === 'cpu') {
keyValues.cpu = {};
keyValues.cpu[procType] = null;
}
commons.post(format('/%s/apps/%s/config/', deis.version, appName), keyValues,
function onUnsetResponse(err, result) {
console.log(result);
callback(err, result ? extractLimits(result) : null);
});
} | [
"function",
"unset",
"(",
"appName",
",",
"limitType",
",",
"procType",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"appName",
")",
"{",
"return",
"callback",
"(",
"ArgumentError",
"(",
"'appName'",
")",
")",
";",
"}",
"if",
"(",
"!",
"limitType",
")",
"{",
"return",
"callback",
"(",
"ArgumentError",
"(",
"'limitType'",
")",
")",
";",
"}",
"if",
"(",
"!",
"procType",
")",
"{",
"return",
"callback",
"(",
"ArgumentError",
"(",
"'procType'",
")",
")",
";",
"}",
"var",
"keyValues",
"=",
"{",
"}",
";",
"if",
"(",
"limitType",
"===",
"'memory'",
")",
"{",
"keyValues",
".",
"memory",
"=",
"{",
"}",
";",
"keyValues",
".",
"memory",
"[",
"procType",
"]",
"=",
"null",
";",
"}",
"if",
"(",
"limitType",
"===",
"'cpu'",
")",
"{",
"keyValues",
".",
"cpu",
"=",
"{",
"}",
";",
"keyValues",
".",
"cpu",
"[",
"procType",
"]",
"=",
"null",
";",
"}",
"commons",
".",
"post",
"(",
"format",
"(",
"'/%s/apps/%s/config/'",
",",
"deis",
".",
"version",
",",
"appName",
")",
",",
"keyValues",
",",
"function",
"onUnsetResponse",
"(",
"err",
",",
"result",
")",
"{",
"console",
".",
"log",
"(",
"result",
")",
";",
"callback",
"(",
"err",
",",
"result",
"?",
"extractLimits",
"(",
"result",
")",
":",
"null",
")",
";",
"}",
")",
";",
"}"
] | unset resource limits for an app | [
"unset",
"resource",
"limits",
"for",
"an",
"app"
] | f0833789998032b11221a3a617bb566ade1fcc13 | https://github.com/aledbf/deis-api/blob/f0833789998032b11221a3a617bb566ade1fcc13/lib/limits.js#L73-L103 |
54,249 | SolarNetwork/solarnetwork-d3 | src/format/util.js | sn_format_fmt | function sn_format_fmt() {
if ( !arguments.length ) {
return;
}
var i = 0,
formatted = arguments[i],
regexp,
replaceValue;
for ( i = 1; i < arguments.length; i += 1 ) {
regexp = new RegExp('\\{'+(i-1)+'\\}', 'gi');
replaceValue = arguments[i];
if ( replaceValue instanceof Date ) {
replaceValue = (replaceValue.getUTCHours() === 0 && replaceValue.getMinutes() === 0
? sn.format.dateFormat(replaceValue) : sn.format.dateTimeFormatURL(replaceValue));
}
formatted = formatted.replace(regexp, replaceValue);
}
return formatted;
} | javascript | function sn_format_fmt() {
if ( !arguments.length ) {
return;
}
var i = 0,
formatted = arguments[i],
regexp,
replaceValue;
for ( i = 1; i < arguments.length; i += 1 ) {
regexp = new RegExp('\\{'+(i-1)+'\\}', 'gi');
replaceValue = arguments[i];
if ( replaceValue instanceof Date ) {
replaceValue = (replaceValue.getUTCHours() === 0 && replaceValue.getMinutes() === 0
? sn.format.dateFormat(replaceValue) : sn.format.dateTimeFormatURL(replaceValue));
}
formatted = formatted.replace(regexp, replaceValue);
}
return formatted;
} | [
"function",
"sn_format_fmt",
"(",
")",
"{",
"if",
"(",
"!",
"arguments",
".",
"length",
")",
"{",
"return",
";",
"}",
"var",
"i",
"=",
"0",
",",
"formatted",
"=",
"arguments",
"[",
"i",
"]",
",",
"regexp",
",",
"replaceValue",
";",
"for",
"(",
"i",
"=",
"1",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"regexp",
"=",
"new",
"RegExp",
"(",
"'\\\\{'",
"+",
"(",
"i",
"-",
"1",
")",
"+",
"'\\\\}'",
",",
"'gi'",
")",
";",
"replaceValue",
"=",
"arguments",
"[",
"i",
"]",
";",
"if",
"(",
"replaceValue",
"instanceof",
"Date",
")",
"{",
"replaceValue",
"=",
"(",
"replaceValue",
".",
"getUTCHours",
"(",
")",
"===",
"0",
"&&",
"replaceValue",
".",
"getMinutes",
"(",
")",
"===",
"0",
"?",
"sn",
".",
"format",
".",
"dateFormat",
"(",
"replaceValue",
")",
":",
"sn",
".",
"format",
".",
"dateTimeFormatURL",
"(",
"replaceValue",
")",
")",
";",
"}",
"formatted",
"=",
"formatted",
".",
"replace",
"(",
"regexp",
",",
"replaceValue",
")",
";",
"}",
"return",
"formatted",
";",
"}"
] | Helper to be able to use placeholders even on iOS, where console.log doesn't support them.
@param {String} Message template.
@param {Object[]} Optional parameters to replace in the message.
@preserve | [
"Helper",
"to",
"be",
"able",
"to",
"use",
"placeholders",
"even",
"on",
"iOS",
"where",
"console",
".",
"log",
"doesn",
"t",
"support",
"them",
"."
] | 26848b1c303b98b7c0ddeefb8c68c5f5bf78927e | https://github.com/SolarNetwork/solarnetwork-d3/blob/26848b1c303b98b7c0ddeefb8c68c5f5bf78927e/src/format/util.js#L12-L30 |
54,250 | pagespace/pagespace | static/bower_components/angular-schema-form/dist/schema-form.js | function(args) {
if (args.form.ngModelOptions && Object.keys(args.form.ngModelOptions).length > 0) {
args.fieldFrag.firstChild.setAttribute('ng-model-options', JSON.stringify(args.form.ngModelOptions));
}
} | javascript | function(args) {
if (args.form.ngModelOptions && Object.keys(args.form.ngModelOptions).length > 0) {
args.fieldFrag.firstChild.setAttribute('ng-model-options', JSON.stringify(args.form.ngModelOptions));
}
} | [
"function",
"(",
"args",
")",
"{",
"if",
"(",
"args",
".",
"form",
".",
"ngModelOptions",
"&&",
"Object",
".",
"keys",
"(",
"args",
".",
"form",
".",
"ngModelOptions",
")",
".",
"length",
">",
"0",
")",
"{",
"args",
".",
"fieldFrag",
".",
"firstChild",
".",
"setAttribute",
"(",
"'ng-model-options'",
",",
"JSON",
".",
"stringify",
"(",
"args",
".",
"form",
".",
"ngModelOptions",
")",
")",
";",
"}",
"}"
] | Patch on ngModelOptions, since it doesn't like waiting for its value. | [
"Patch",
"on",
"ngModelOptions",
"since",
"it",
"doesn",
"t",
"like",
"waiting",
"for",
"its",
"value",
"."
] | 943c45ddd9aaa4f3136e1ba4c2593aa0289daf43 | https://github.com/pagespace/pagespace/blob/943c45ddd9aaa4f3136e1ba4c2593aa0289daf43/static/bower_components/angular-schema-form/dist/schema-form.js#L148-L152 |
|
54,251 | pagespace/pagespace | static/bower_components/angular-schema-form/dist/schema-form.js | function(items, path, state) {
return build(items, decorator, templateFn, slots, path, state, lookup);
} | javascript | function(items, path, state) {
return build(items, decorator, templateFn, slots, path, state, lookup);
} | [
"function",
"(",
"items",
",",
"path",
",",
"state",
")",
"{",
"return",
"build",
"(",
"items",
",",
"decorator",
",",
"templateFn",
",",
"slots",
",",
"path",
",",
"state",
",",
"lookup",
")",
";",
"}"
] | Recursive build fn | [
"Recursive",
"build",
"fn"
] | 943c45ddd9aaa4f3136e1ba4c2593aa0289daf43 | https://github.com/pagespace/pagespace/blob/943c45ddd9aaa4f3136e1ba4c2593aa0289daf43/static/bower_components/angular-schema-form/dist/schema-form.js#L306-L308 |
|
54,252 | pagespace/pagespace | static/bower_components/angular-schema-form/dist/schema-form.js | function(form, decorator, slots, lookup) {
return build(form, decorator, function(form, field) {
if (form.type === 'template') {
return form.template;
}
return $templateCache.get(field.template);
}, slots, undefined, undefined, lookup);
} | javascript | function(form, decorator, slots, lookup) {
return build(form, decorator, function(form, field) {
if (form.type === 'template') {
return form.template;
}
return $templateCache.get(field.template);
}, slots, undefined, undefined, lookup);
} | [
"function",
"(",
"form",
",",
"decorator",
",",
"slots",
",",
"lookup",
")",
"{",
"return",
"build",
"(",
"form",
",",
"decorator",
",",
"function",
"(",
"form",
",",
"field",
")",
"{",
"if",
"(",
"form",
".",
"type",
"===",
"'template'",
")",
"{",
"return",
"form",
".",
"template",
";",
"}",
"return",
"$templateCache",
".",
"get",
"(",
"field",
".",
"template",
")",
";",
"}",
",",
"slots",
",",
"undefined",
",",
"undefined",
",",
"lookup",
")",
";",
"}"
] | Builds a form from a canonical form definition | [
"Builds",
"a",
"form",
"from",
"a",
"canonical",
"form",
"definition"
] | 943c45ddd9aaa4f3136e1ba4c2593aa0289daf43 | https://github.com/pagespace/pagespace/blob/943c45ddd9aaa4f3136e1ba4c2593aa0289daf43/static/bower_components/angular-schema-form/dist/schema-form.js#L335-L343 |
|
54,253 | pagespace/pagespace | static/bower_components/angular-schema-form/dist/schema-form.js | function(name, form) {
//schemaDecorator is alias for whatever is set as default
if (name === 'sfDecorator') {
name = defaultDecorator;
}
var decorator = decorators[name];
if (decorator[form.type]) {
return decorator[form.type].template;
}
//try default
return decorator['default'].template;
} | javascript | function(name, form) {
//schemaDecorator is alias for whatever is set as default
if (name === 'sfDecorator') {
name = defaultDecorator;
}
var decorator = decorators[name];
if (decorator[form.type]) {
return decorator[form.type].template;
}
//try default
return decorator['default'].template;
} | [
"function",
"(",
"name",
",",
"form",
")",
"{",
"//schemaDecorator is alias for whatever is set as default",
"if",
"(",
"name",
"===",
"'sfDecorator'",
")",
"{",
"name",
"=",
"defaultDecorator",
";",
"}",
"var",
"decorator",
"=",
"decorators",
"[",
"name",
"]",
";",
"if",
"(",
"decorator",
"[",
"form",
".",
"type",
"]",
")",
"{",
"return",
"decorator",
"[",
"form",
".",
"type",
"]",
".",
"template",
";",
"}",
"//try default",
"return",
"decorator",
"[",
"'default'",
"]",
".",
"template",
";",
"}"
] | Map template after decorator and type. | [
"Map",
"template",
"after",
"decorator",
"and",
"type",
"."
] | 943c45ddd9aaa4f3136e1ba4c2593aa0289daf43 | https://github.com/pagespace/pagespace/blob/943c45ddd9aaa4f3136e1ba4c2593aa0289daf43/static/bower_components/angular-schema-form/dist/schema-form.js#L358-L371 |
|
54,254 | pagespace/pagespace | static/bower_components/angular-schema-form/dist/schema-form.js | function(enm) {
var titleMap = []; //canonical titleMap format is a list.
enm.forEach(function(name) {
titleMap.push({name: name, value: name});
});
return titleMap;
} | javascript | function(enm) {
var titleMap = []; //canonical titleMap format is a list.
enm.forEach(function(name) {
titleMap.push({name: name, value: name});
});
return titleMap;
} | [
"function",
"(",
"enm",
")",
"{",
"var",
"titleMap",
"=",
"[",
"]",
";",
"//canonical titleMap format is a list.",
"enm",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"titleMap",
".",
"push",
"(",
"{",
"name",
":",
"name",
",",
"value",
":",
"name",
"}",
")",
";",
"}",
")",
";",
"return",
"titleMap",
";",
"}"
] | Creates an default titleMap list from an enum, i.e. a list of strings. | [
"Creates",
"an",
"default",
"titleMap",
"list",
"from",
"an",
"enum",
"i",
".",
"e",
".",
"a",
"list",
"of",
"strings",
"."
] | 943c45ddd9aaa4f3136e1ba4c2593aa0289daf43 | https://github.com/pagespace/pagespace/blob/943c45ddd9aaa4f3136e1ba4c2593aa0289daf43/static/bower_components/angular-schema-form/dist/schema-form.js#L1022-L1028 |
|
54,255 | pagespace/pagespace | static/bower_components/angular-schema-form/dist/schema-form.js | function(titleMap, originalEnum) {
if (!angular.isArray(titleMap)) {
var canonical = [];
if (originalEnum) {
angular.forEach(originalEnum, function(value, index) {
canonical.push({name: titleMap[value], value: value});
});
} else {
angular.forEach(titleMap, function(name, value) {
canonical.push({name: name, value: value});
});
}
return canonical;
}
return titleMap;
} | javascript | function(titleMap, originalEnum) {
if (!angular.isArray(titleMap)) {
var canonical = [];
if (originalEnum) {
angular.forEach(originalEnum, function(value, index) {
canonical.push({name: titleMap[value], value: value});
});
} else {
angular.forEach(titleMap, function(name, value) {
canonical.push({name: name, value: value});
});
}
return canonical;
}
return titleMap;
} | [
"function",
"(",
"titleMap",
",",
"originalEnum",
")",
"{",
"if",
"(",
"!",
"angular",
".",
"isArray",
"(",
"titleMap",
")",
")",
"{",
"var",
"canonical",
"=",
"[",
"]",
";",
"if",
"(",
"originalEnum",
")",
"{",
"angular",
".",
"forEach",
"(",
"originalEnum",
",",
"function",
"(",
"value",
",",
"index",
")",
"{",
"canonical",
".",
"push",
"(",
"{",
"name",
":",
"titleMap",
"[",
"value",
"]",
",",
"value",
":",
"value",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"angular",
".",
"forEach",
"(",
"titleMap",
",",
"function",
"(",
"name",
",",
"value",
")",
"{",
"canonical",
".",
"push",
"(",
"{",
"name",
":",
"name",
",",
"value",
":",
"value",
"}",
")",
";",
"}",
")",
";",
"}",
"return",
"canonical",
";",
"}",
"return",
"titleMap",
";",
"}"
] | Takes a titleMap in either object or list format and returns one in in the list format. | [
"Takes",
"a",
"titleMap",
"in",
"either",
"object",
"or",
"list",
"format",
"and",
"returns",
"one",
"in",
"in",
"the",
"list",
"format",
"."
] | 943c45ddd9aaa4f3136e1ba4c2593aa0289daf43 | https://github.com/pagespace/pagespace/blob/943c45ddd9aaa4f3136e1ba4c2593aa0289daf43/static/bower_components/angular-schema-form/dist/schema-form.js#L1032-L1047 |
|
54,256 | pagespace/pagespace | static/bower_components/angular-schema-form/dist/schema-form.js | function(name, schema, options) {
options = options || {};
var f = options.global && options.global.formDefaults ?
angular.copy(options.global.formDefaults) : {};
if (options.global && options.global.supressPropertyTitles === true) {
f.title = schema.title;
} else {
f.title = schema.title || name;
}
if (schema.description) { f.description = schema.description; }
if (options.required === true || schema.required === true) { f.required = true; }
if (schema.maxLength) { f.maxlength = schema.maxLength; }
if (schema.minLength) { f.minlength = schema.minLength; }
if (schema.readOnly || schema.readonly) { f.readonly = true; }
if (schema.minimum) { f.minimum = schema.minimum + (schema.exclusiveMinimum ? 1 : 0); }
if (schema.maximum) { f.maximum = schema.maximum - (schema.exclusiveMaximum ? 1 : 0); }
// Non standard attributes (DONT USE DEPRECATED)
// If you must set stuff like this in the schema use the x-schema-form attribute
if (schema.validationMessage) { f.validationMessage = schema.validationMessage; }
if (schema.enumNames) { f.titleMap = canonicalTitleMap(schema.enumNames, schema['enum']); }
f.schema = schema;
// Ng model options doesn't play nice with undefined, might be defined
// globally though
f.ngModelOptions = f.ngModelOptions || {};
return f;
} | javascript | function(name, schema, options) {
options = options || {};
var f = options.global && options.global.formDefaults ?
angular.copy(options.global.formDefaults) : {};
if (options.global && options.global.supressPropertyTitles === true) {
f.title = schema.title;
} else {
f.title = schema.title || name;
}
if (schema.description) { f.description = schema.description; }
if (options.required === true || schema.required === true) { f.required = true; }
if (schema.maxLength) { f.maxlength = schema.maxLength; }
if (schema.minLength) { f.minlength = schema.minLength; }
if (schema.readOnly || schema.readonly) { f.readonly = true; }
if (schema.minimum) { f.minimum = schema.minimum + (schema.exclusiveMinimum ? 1 : 0); }
if (schema.maximum) { f.maximum = schema.maximum - (schema.exclusiveMaximum ? 1 : 0); }
// Non standard attributes (DONT USE DEPRECATED)
// If you must set stuff like this in the schema use the x-schema-form attribute
if (schema.validationMessage) { f.validationMessage = schema.validationMessage; }
if (schema.enumNames) { f.titleMap = canonicalTitleMap(schema.enumNames, schema['enum']); }
f.schema = schema;
// Ng model options doesn't play nice with undefined, might be defined
// globally though
f.ngModelOptions = f.ngModelOptions || {};
return f;
} | [
"function",
"(",
"name",
",",
"schema",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"f",
"=",
"options",
".",
"global",
"&&",
"options",
".",
"global",
".",
"formDefaults",
"?",
"angular",
".",
"copy",
"(",
"options",
".",
"global",
".",
"formDefaults",
")",
":",
"{",
"}",
";",
"if",
"(",
"options",
".",
"global",
"&&",
"options",
".",
"global",
".",
"supressPropertyTitles",
"===",
"true",
")",
"{",
"f",
".",
"title",
"=",
"schema",
".",
"title",
";",
"}",
"else",
"{",
"f",
".",
"title",
"=",
"schema",
".",
"title",
"||",
"name",
";",
"}",
"if",
"(",
"schema",
".",
"description",
")",
"{",
"f",
".",
"description",
"=",
"schema",
".",
"description",
";",
"}",
"if",
"(",
"options",
".",
"required",
"===",
"true",
"||",
"schema",
".",
"required",
"===",
"true",
")",
"{",
"f",
".",
"required",
"=",
"true",
";",
"}",
"if",
"(",
"schema",
".",
"maxLength",
")",
"{",
"f",
".",
"maxlength",
"=",
"schema",
".",
"maxLength",
";",
"}",
"if",
"(",
"schema",
".",
"minLength",
")",
"{",
"f",
".",
"minlength",
"=",
"schema",
".",
"minLength",
";",
"}",
"if",
"(",
"schema",
".",
"readOnly",
"||",
"schema",
".",
"readonly",
")",
"{",
"f",
".",
"readonly",
"=",
"true",
";",
"}",
"if",
"(",
"schema",
".",
"minimum",
")",
"{",
"f",
".",
"minimum",
"=",
"schema",
".",
"minimum",
"+",
"(",
"schema",
".",
"exclusiveMinimum",
"?",
"1",
":",
"0",
")",
";",
"}",
"if",
"(",
"schema",
".",
"maximum",
")",
"{",
"f",
".",
"maximum",
"=",
"schema",
".",
"maximum",
"-",
"(",
"schema",
".",
"exclusiveMaximum",
"?",
"1",
":",
"0",
")",
";",
"}",
"// Non standard attributes (DONT USE DEPRECATED)",
"// If you must set stuff like this in the schema use the x-schema-form attribute",
"if",
"(",
"schema",
".",
"validationMessage",
")",
"{",
"f",
".",
"validationMessage",
"=",
"schema",
".",
"validationMessage",
";",
"}",
"if",
"(",
"schema",
".",
"enumNames",
")",
"{",
"f",
".",
"titleMap",
"=",
"canonicalTitleMap",
"(",
"schema",
".",
"enumNames",
",",
"schema",
"[",
"'enum'",
"]",
")",
";",
"}",
"f",
".",
"schema",
"=",
"schema",
";",
"// Ng model options doesn't play nice with undefined, might be defined",
"// globally though",
"f",
".",
"ngModelOptions",
"=",
"f",
".",
"ngModelOptions",
"||",
"{",
"}",
";",
"return",
"f",
";",
"}"
] | Creates a form object with all common properties | [
"Creates",
"a",
"form",
"object",
"with",
"all",
"common",
"properties"
] | 943c45ddd9aaa4f3136e1ba4c2593aa0289daf43 | https://github.com/pagespace/pagespace/blob/943c45ddd9aaa4f3136e1ba4c2593aa0289daf43/static/bower_components/angular-schema-form/dist/schema-form.js#L1071-L1100 |
|
54,257 | pagespace/pagespace | static/bower_components/angular-schema-form/dist/schema-form.js | function(arr) {
scope.titleMapValues = [];
arr = arr || [];
form.titleMap.forEach(function(item) {
scope.titleMapValues.push(arr.indexOf(item.value) !== -1);
});
} | javascript | function(arr) {
scope.titleMapValues = [];
arr = arr || [];
form.titleMap.forEach(function(item) {
scope.titleMapValues.push(arr.indexOf(item.value) !== -1);
});
} | [
"function",
"(",
"arr",
")",
"{",
"scope",
".",
"titleMapValues",
"=",
"[",
"]",
";",
"arr",
"=",
"arr",
"||",
"[",
"]",
";",
"form",
".",
"titleMap",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"scope",
".",
"titleMapValues",
".",
"push",
"(",
"arr",
".",
"indexOf",
"(",
"item",
".",
"value",
")",
"!==",
"-",
"1",
")",
";",
"}",
")",
";",
"}"
] | We watch the model for changes and the titleMapValues to reflect the modelArray | [
"We",
"watch",
"the",
"model",
"for",
"changes",
"and",
"the",
"titleMapValues",
"to",
"reflect",
"the",
"modelArray"
] | 943c45ddd9aaa4f3136e1ba4c2593aa0289daf43 | https://github.com/pagespace/pagespace/blob/943c45ddd9aaa4f3136e1ba4c2593aa0289daf43/static/bower_components/angular-schema-form/dist/schema-form.js#L1787-L1794 |
|
54,258 | pagespace/pagespace | static/bower_components/angular-schema-form/dist/schema-form.js | function() {
//scope.modelArray = modelArray;
scope.modelArray = scope.$eval(attrs.sfNewArray);
// validateField method is exported by schema-validate
if (scope.ngModel && scope.ngModel.$pristine && scope.firstDigest &&
(!scope.options || scope.options.validateOnRender !== true)) {
return;
} else if (scope.validateField) {
scope.validateField();
}
} | javascript | function() {
//scope.modelArray = modelArray;
scope.modelArray = scope.$eval(attrs.sfNewArray);
// validateField method is exported by schema-validate
if (scope.ngModel && scope.ngModel.$pristine && scope.firstDigest &&
(!scope.options || scope.options.validateOnRender !== true)) {
return;
} else if (scope.validateField) {
scope.validateField();
}
} | [
"function",
"(",
")",
"{",
"//scope.modelArray = modelArray;",
"scope",
".",
"modelArray",
"=",
"scope",
".",
"$eval",
"(",
"attrs",
".",
"sfNewArray",
")",
";",
"// validateField method is exported by schema-validate",
"if",
"(",
"scope",
".",
"ngModel",
"&&",
"scope",
".",
"ngModel",
".",
"$pristine",
"&&",
"scope",
".",
"firstDigest",
"&&",
"(",
"!",
"scope",
".",
"options",
"||",
"scope",
".",
"options",
".",
"validateOnRender",
"!==",
"true",
")",
")",
"{",
"return",
";",
"}",
"else",
"if",
"(",
"scope",
".",
"validateField",
")",
"{",
"scope",
".",
"validateField",
"(",
")",
";",
"}",
"}"
] | We need to have a ngModel to hook into validation. It doesn't really play well with arrays though so we both need to trigger validation and onChange. So we watch the value as well. But watching an array can be tricky. We wan't to know when it changes so we can validate, | [
"We",
"need",
"to",
"have",
"a",
"ngModel",
"to",
"hook",
"into",
"validation",
".",
"It",
"doesn",
"t",
"really",
"play",
"well",
"with",
"arrays",
"though",
"so",
"we",
"both",
"need",
"to",
"trigger",
"validation",
"and",
"onChange",
".",
"So",
"we",
"watch",
"the",
"value",
"as",
"well",
".",
"But",
"watching",
"an",
"array",
"can",
"be",
"tricky",
".",
"We",
"wan",
"t",
"to",
"know",
"when",
"it",
"changes",
"so",
"we",
"can",
"validate"
] | 943c45ddd9aaa4f3136e1ba4c2593aa0289daf43 | https://github.com/pagespace/pagespace/blob/943c45ddd9aaa4f3136e1ba4c2593aa0289daf43/static/bower_components/angular-schema-form/dist/schema-form.js#L2285-L2295 |
|
54,259 | pagespace/pagespace | static/bower_components/angular-schema-form/dist/schema-form.js | function() {
var model = scope.modelArray;
if (!model) {
var selection = sfPath.parse(attrs.sfNewArray);
model = [];
sel(selection, scope, model);
scope.modelArray = model;
}
return model;
} | javascript | function() {
var model = scope.modelArray;
if (!model) {
var selection = sfPath.parse(attrs.sfNewArray);
model = [];
sel(selection, scope, model);
scope.modelArray = model;
}
return model;
} | [
"function",
"(",
")",
"{",
"var",
"model",
"=",
"scope",
".",
"modelArray",
";",
"if",
"(",
"!",
"model",
")",
"{",
"var",
"selection",
"=",
"sfPath",
".",
"parse",
"(",
"attrs",
".",
"sfNewArray",
")",
";",
"model",
"=",
"[",
"]",
";",
"sel",
"(",
"selection",
",",
"scope",
",",
"model",
")",
";",
"scope",
".",
"modelArray",
"=",
"model",
";",
"}",
"return",
"model",
";",
"}"
] | If model is undefined make sure it gets set. | [
"If",
"model",
"is",
"undefined",
"make",
"sure",
"it",
"gets",
"set",
"."
] | 943c45ddd9aaa4f3136e1ba4c2593aa0289daf43 | https://github.com/pagespace/pagespace/blob/943c45ddd9aaa4f3136e1ba4c2593aa0289daf43/static/bower_components/angular-schema-form/dist/schema-form.js#L2308-L2317 |
|
54,260 | pagespace/pagespace | static/bower_components/angular-schema-form/dist/schema-form.js | function(schema, form) {
var asyncTemplates = [];
var merged = schemaForm.merge(schema, form, ignore, scope.options, undefined, asyncTemplates);
if (asyncTemplates.length > 0) {
// Pre load all async templates and put them on the form for the builder to use.
$q.all(asyncTemplates.map(function(form) {
return $http.get(form.templateUrl, {cache: $templateCache}).then(function(res) {
form.template = res.data;
});
})).then(function() {
internalRender(schema, form, merged);
});
} else {
internalRender(schema, form, merged);
}
} | javascript | function(schema, form) {
var asyncTemplates = [];
var merged = schemaForm.merge(schema, form, ignore, scope.options, undefined, asyncTemplates);
if (asyncTemplates.length > 0) {
// Pre load all async templates and put them on the form for the builder to use.
$q.all(asyncTemplates.map(function(form) {
return $http.get(form.templateUrl, {cache: $templateCache}).then(function(res) {
form.template = res.data;
});
})).then(function() {
internalRender(schema, form, merged);
});
} else {
internalRender(schema, form, merged);
}
} | [
"function",
"(",
"schema",
",",
"form",
")",
"{",
"var",
"asyncTemplates",
"=",
"[",
"]",
";",
"var",
"merged",
"=",
"schemaForm",
".",
"merge",
"(",
"schema",
",",
"form",
",",
"ignore",
",",
"scope",
".",
"options",
",",
"undefined",
",",
"asyncTemplates",
")",
";",
"if",
"(",
"asyncTemplates",
".",
"length",
">",
"0",
")",
"{",
"// Pre load all async templates and put them on the form for the builder to use.",
"$q",
".",
"all",
"(",
"asyncTemplates",
".",
"map",
"(",
"function",
"(",
"form",
")",
"{",
"return",
"$http",
".",
"get",
"(",
"form",
".",
"templateUrl",
",",
"{",
"cache",
":",
"$templateCache",
"}",
")",
".",
"then",
"(",
"function",
"(",
"res",
")",
"{",
"form",
".",
"template",
"=",
"res",
".",
"data",
";",
"}",
")",
";",
"}",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"internalRender",
"(",
"schema",
",",
"form",
",",
"merged",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"internalRender",
"(",
"schema",
",",
"form",
",",
"merged",
")",
";",
"}",
"}"
] | Common renderer function, can either be triggered by a watch or by an event. | [
"Common",
"renderer",
"function",
"can",
"either",
"be",
"triggered",
"by",
"a",
"watch",
"or",
"by",
"an",
"event",
"."
] | 943c45ddd9aaa4f3136e1ba4c2593aa0289daf43 | https://github.com/pagespace/pagespace/blob/943c45ddd9aaa4f3136e1ba4c2593aa0289daf43/static/bower_components/angular-schema-form/dist/schema-form.js#L2580-L2599 |
|
54,261 | pagespace/pagespace | static/bower_components/angular-schema-form/dist/schema-form.js | function(viewValue) {
//console.log('validate called', viewValue)
//Still might be undefined
if (!form) {
return viewValue;
}
// Omit TV4 validation
if (scope.options && scope.options.tv4Validation === false) {
return viewValue;
}
var result = sfValidator.validate(form, viewValue);
//console.log('result is', result)
// Since we might have different tv4 errors we must clear all
// errors that start with tv4-
Object.keys(ngModel.$error)
.filter(function(k) { return k.indexOf('tv4-') === 0; })
.forEach(function(k) { ngModel.$setValidity(k, true); });
if (!result.valid) {
// it is invalid, return undefined (no model update)
ngModel.$setValidity('tv4-' + result.error.code, false);
error = result.error;
// In Angular 1.3+ return the viewValue, otherwise we inadvertenly
// will trigger a 'parse' error.
// we will stop the model value from updating with our own $validator
// later.
if (ngModel.$validators) {
return viewValue;
}
// Angular 1.2 on the other hand lacks $validators and don't add a 'parse' error.
return undefined;
}
return viewValue;
} | javascript | function(viewValue) {
//console.log('validate called', viewValue)
//Still might be undefined
if (!form) {
return viewValue;
}
// Omit TV4 validation
if (scope.options && scope.options.tv4Validation === false) {
return viewValue;
}
var result = sfValidator.validate(form, viewValue);
//console.log('result is', result)
// Since we might have different tv4 errors we must clear all
// errors that start with tv4-
Object.keys(ngModel.$error)
.filter(function(k) { return k.indexOf('tv4-') === 0; })
.forEach(function(k) { ngModel.$setValidity(k, true); });
if (!result.valid) {
// it is invalid, return undefined (no model update)
ngModel.$setValidity('tv4-' + result.error.code, false);
error = result.error;
// In Angular 1.3+ return the viewValue, otherwise we inadvertenly
// will trigger a 'parse' error.
// we will stop the model value from updating with our own $validator
// later.
if (ngModel.$validators) {
return viewValue;
}
// Angular 1.2 on the other hand lacks $validators and don't add a 'parse' error.
return undefined;
}
return viewValue;
} | [
"function",
"(",
"viewValue",
")",
"{",
"//console.log('validate called', viewValue)",
"//Still might be undefined",
"if",
"(",
"!",
"form",
")",
"{",
"return",
"viewValue",
";",
"}",
"// Omit TV4 validation",
"if",
"(",
"scope",
".",
"options",
"&&",
"scope",
".",
"options",
".",
"tv4Validation",
"===",
"false",
")",
"{",
"return",
"viewValue",
";",
"}",
"var",
"result",
"=",
"sfValidator",
".",
"validate",
"(",
"form",
",",
"viewValue",
")",
";",
"//console.log('result is', result)",
"// Since we might have different tv4 errors we must clear all",
"// errors that start with tv4-",
"Object",
".",
"keys",
"(",
"ngModel",
".",
"$error",
")",
".",
"filter",
"(",
"function",
"(",
"k",
")",
"{",
"return",
"k",
".",
"indexOf",
"(",
"'tv4-'",
")",
"===",
"0",
";",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"k",
")",
"{",
"ngModel",
".",
"$setValidity",
"(",
"k",
",",
"true",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"result",
".",
"valid",
")",
"{",
"// it is invalid, return undefined (no model update)",
"ngModel",
".",
"$setValidity",
"(",
"'tv4-'",
"+",
"result",
".",
"error",
".",
"code",
",",
"false",
")",
";",
"error",
"=",
"result",
".",
"error",
";",
"// In Angular 1.3+ return the viewValue, otherwise we inadvertenly",
"// will trigger a 'parse' error.",
"// we will stop the model value from updating with our own $validator",
"// later.",
"if",
"(",
"ngModel",
".",
"$validators",
")",
"{",
"return",
"viewValue",
";",
"}",
"// Angular 1.2 on the other hand lacks $validators and don't add a 'parse' error.",
"return",
"undefined",
";",
"}",
"return",
"viewValue",
";",
"}"
] | Validate against the schema. | [
"Validate",
"against",
"the",
"schema",
"."
] | 943c45ddd9aaa4f3136e1ba4c2593aa0289daf43 | https://github.com/pagespace/pagespace/blob/943c45ddd9aaa4f3136e1ba4c2593aa0289daf43/static/bower_components/angular-schema-form/dist/schema-form.js#L2749-L2785 |
|
54,262 | newworldcode/waterline-jsonapi | lib/utils.js | get_association_keys | function get_association_keys(collection) {
// Loop over the keys, filter irrelevant ones and fetch alias'
return Object.keys(collection._attributes || collection.attributes)
// We only care about attributes with model, collection or foreignKey properties.
.filter(key =>
collection._attributes[key].hasOwnProperty("model") ||
collection._attributes[key].hasOwnProperty("collection") ||
(
collection._attributes[key].hasOwnProperty("foreignKey") &&
collection._attributes[key].hasOwnProperty("references")
)
)
} | javascript | function get_association_keys(collection) {
// Loop over the keys, filter irrelevant ones and fetch alias'
return Object.keys(collection._attributes || collection.attributes)
// We only care about attributes with model, collection or foreignKey properties.
.filter(key =>
collection._attributes[key].hasOwnProperty("model") ||
collection._attributes[key].hasOwnProperty("collection") ||
(
collection._attributes[key].hasOwnProperty("foreignKey") &&
collection._attributes[key].hasOwnProperty("references")
)
)
} | [
"function",
"get_association_keys",
"(",
"collection",
")",
"{",
"// Loop over the keys, filter irrelevant ones and fetch alias'",
"return",
"Object",
".",
"keys",
"(",
"collection",
".",
"_attributes",
"||",
"collection",
".",
"attributes",
")",
"// We only care about attributes with model, collection or foreignKey properties.",
".",
"filter",
"(",
"key",
"=>",
"collection",
".",
"_attributes",
"[",
"key",
"]",
".",
"hasOwnProperty",
"(",
"\"model\"",
")",
"||",
"collection",
".",
"_attributes",
"[",
"key",
"]",
".",
"hasOwnProperty",
"(",
"\"collection\"",
")",
"||",
"(",
"collection",
".",
"_attributes",
"[",
"key",
"]",
".",
"hasOwnProperty",
"(",
"\"foreignKey\"",
")",
"&&",
"collection",
".",
"_attributes",
"[",
"key",
"]",
".",
"hasOwnProperty",
"(",
"\"references\"",
")",
")",
")",
"}"
] | Get the keys that are associations.
@param {Waterline.Collection} collection to get keys from.
@return {Array} Array of the keys that have model, collection or foreignKey properties. | [
"Get",
"the",
"keys",
"that",
"are",
"associations",
"."
] | 9e198cf0f80f1905354b101d2315f205b43f6dcd | https://github.com/newworldcode/waterline-jsonapi/blob/9e198cf0f80f1905354b101d2315f205b43f6dcd/lib/utils.js#L8-L20 |
54,263 | newworldcode/waterline-jsonapi | lib/utils.js | get_associated_collections | function get_associated_collections(collection) {
const map = new Map()
get_association_keys(collection)
// Return the identity to the related resource.
.forEach(key => {
// Get the attributes
const collection_attributes = collection._attributes[key]
// Most of the time, it's a one to one
// relationship so it's not an array.
let is_array = false
// But sometimes, it's a one to many
// so array must be true.
if (collection_attributes.hasOwnProperty("collection")) {
is_array = true
}
// Set the values.
map.set(key, { is_array, collection })
})
return map
} | javascript | function get_associated_collections(collection) {
const map = new Map()
get_association_keys(collection)
// Return the identity to the related resource.
.forEach(key => {
// Get the attributes
const collection_attributes = collection._attributes[key]
// Most of the time, it's a one to one
// relationship so it's not an array.
let is_array = false
// But sometimes, it's a one to many
// so array must be true.
if (collection_attributes.hasOwnProperty("collection")) {
is_array = true
}
// Set the values.
map.set(key, { is_array, collection })
})
return map
} | [
"function",
"get_associated_collections",
"(",
"collection",
")",
"{",
"const",
"map",
"=",
"new",
"Map",
"(",
")",
"get_association_keys",
"(",
"collection",
")",
"// Return the identity to the related resource.",
".",
"forEach",
"(",
"key",
"=>",
"{",
"// Get the attributes",
"const",
"collection_attributes",
"=",
"collection",
".",
"_attributes",
"[",
"key",
"]",
"// Most of the time, it's a one to one",
"// relationship so it's not an array.",
"let",
"is_array",
"=",
"false",
"// But sometimes, it's a one to many",
"// so array must be true.",
"if",
"(",
"collection_attributes",
".",
"hasOwnProperty",
"(",
"\"collection\"",
")",
")",
"{",
"is_array",
"=",
"true",
"}",
"// Set the values.",
"map",
".",
"set",
"(",
"key",
",",
"{",
"is_array",
",",
"collection",
"}",
")",
"}",
")",
"return",
"map",
"}"
] | Get the collections assigned to each association
within the collection.
@param {Waterline.Collection} collection to get associations from.
@return {Map} Map of the collections that have `model|collection` properties and their type. | [
"Get",
"the",
"collections",
"assigned",
"to",
"each",
"association",
"within",
"the",
"collection",
"."
] | 9e198cf0f80f1905354b101d2315f205b43f6dcd | https://github.com/newworldcode/waterline-jsonapi/blob/9e198cf0f80f1905354b101d2315f205b43f6dcd/lib/utils.js#L28-L52 |
54,264 | yoshuawuyts/inject-lr-script-stream | index.js | streamInjectLrScript | function streamInjectLrScript (opts) {
opts = opts || {}
assert.equal(typeof opts, 'object')
const protocol = opts.protocol || 'http'
const host = opts.host || 'localhost'
const port = opts.port || 35729
var lrTag = '<script type="text/javascript"'
lrTag += 'src="'
lrTag += protocol
lrTag += '://'
lrTag += host
lrTag += ':'
lrTag += port
lrTag += '/livereload.js?snipver=1">'
lrTag += '</script>'
return hyperstream({ body: { _appendHtml: lrTag } })
} | javascript | function streamInjectLrScript (opts) {
opts = opts || {}
assert.equal(typeof opts, 'object')
const protocol = opts.protocol || 'http'
const host = opts.host || 'localhost'
const port = opts.port || 35729
var lrTag = '<script type="text/javascript"'
lrTag += 'src="'
lrTag += protocol
lrTag += '://'
lrTag += host
lrTag += ':'
lrTag += port
lrTag += '/livereload.js?snipver=1">'
lrTag += '</script>'
return hyperstream({ body: { _appendHtml: lrTag } })
} | [
"function",
"streamInjectLrScript",
"(",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
"assert",
".",
"equal",
"(",
"typeof",
"opts",
",",
"'object'",
")",
"const",
"protocol",
"=",
"opts",
".",
"protocol",
"||",
"'http'",
"const",
"host",
"=",
"opts",
".",
"host",
"||",
"'localhost'",
"const",
"port",
"=",
"opts",
".",
"port",
"||",
"35729",
"var",
"lrTag",
"=",
"'<script type=\"text/javascript\"'",
"lrTag",
"+=",
"'src=\"'",
"lrTag",
"+=",
"protocol",
"lrTag",
"+=",
"'://'",
"lrTag",
"+=",
"host",
"lrTag",
"+=",
"':'",
"lrTag",
"+=",
"port",
"lrTag",
"+=",
"'/livereload.js?snipver=1\">'",
"lrTag",
"+=",
"'</script>'",
"return",
"hyperstream",
"(",
"{",
"body",
":",
"{",
"_appendHtml",
":",
"lrTag",
"}",
"}",
")",
"}"
] | Streamingly inject a livereload script into html obj -> stream | [
"Streamingly",
"inject",
"a",
"livereload",
"script",
"into",
"html",
"obj",
"-",
">",
"stream"
] | 87460e8c5c812789597d4a42d76e66607cc9bcb4 | https://github.com/yoshuawuyts/inject-lr-script-stream/blob/87460e8c5c812789597d4a42d76e66607cc9bcb4/index.js#L8-L28 |
54,265 | fent/node-streamin | lib/index.js | isStream | function isStream(io) {
return typeof io === 'object' &&
(
// Readable stream.
(typeof io.pipe === 'function' && typeof io.readable === 'boolean' &&
io.readable) ||
// Writable stream.
(typeof io.write === 'function' && typeof io.writable === 'boolean' &&
io.writable)
);
} | javascript | function isStream(io) {
return typeof io === 'object' &&
(
// Readable stream.
(typeof io.pipe === 'function' && typeof io.readable === 'boolean' &&
io.readable) ||
// Writable stream.
(typeof io.write === 'function' && typeof io.writable === 'boolean' &&
io.writable)
);
} | [
"function",
"isStream",
"(",
"io",
")",
"{",
"return",
"typeof",
"io",
"===",
"'object'",
"&&",
"(",
"// Readable stream.",
"(",
"typeof",
"io",
".",
"pipe",
"===",
"'function'",
"&&",
"typeof",
"io",
".",
"readable",
"===",
"'boolean'",
"&&",
"io",
".",
"readable",
")",
"||",
"// Writable stream.",
"(",
"typeof",
"io",
".",
"write",
"===",
"'function'",
"&&",
"typeof",
"io",
".",
"writable",
"===",
"'boolean'",
"&&",
"io",
".",
"writable",
")",
")",
";",
"}"
] | Returns true if `io` is a stream.
@param {Stream|Object} io
@return {Boolean} | [
"Returns",
"true",
"if",
"io",
"is",
"a",
"stream",
"."
] | be71158a6758805bc146b3047c444eafa8c0c3c2 | https://github.com/fent/node-streamin/blob/be71158a6758805bc146b3047c444eafa8c0c3c2/lib/index.js#L13-L23 |
54,266 | SolarNetwork/solarnetwork-d3 | src/api/node/urlHelper.js | reportableIntervalURL | function reportableIntervalURL(sourceIds) {
var url = (baseURL() +'/range/interval?nodeId=' +nodeId);
if ( Array.isArray(sourceIds) ) {
url += '&sourceIds=' + sourceIds.map(function(e) { return encodeURIComponent(e); }).join(',');
}
return url;
} | javascript | function reportableIntervalURL(sourceIds) {
var url = (baseURL() +'/range/interval?nodeId=' +nodeId);
if ( Array.isArray(sourceIds) ) {
url += '&sourceIds=' + sourceIds.map(function(e) { return encodeURIComponent(e); }).join(',');
}
return url;
} | [
"function",
"reportableIntervalURL",
"(",
"sourceIds",
")",
"{",
"var",
"url",
"=",
"(",
"baseURL",
"(",
")",
"+",
"'/range/interval?nodeId='",
"+",
"nodeId",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"sourceIds",
")",
")",
"{",
"url",
"+=",
"'&sourceIds='",
"+",
"sourceIds",
".",
"map",
"(",
"function",
"(",
"e",
")",
"{",
"return",
"encodeURIComponent",
"(",
"e",
")",
";",
"}",
")",
".",
"join",
"(",
"','",
")",
";",
"}",
"return",
"url",
";",
"}"
] | Get a URL for the "reportable interval" for this node, optionally limited to a specific source ID.
@param {Array} sourceIds An array of source IDs to limit query to. If not provided then all available
sources will be returned.
@returns {String} the URL to find the reportable interval
@memberOf sn.api.node.nodeUrlHelper | [
"Get",
"a",
"URL",
"for",
"the",
"reportable",
"interval",
"for",
"this",
"node",
"optionally",
"limited",
"to",
"a",
"specific",
"source",
"ID",
"."
] | 26848b1c303b98b7c0ddeefb8c68c5f5bf78927e | https://github.com/SolarNetwork/solarnetwork-d3/blob/26848b1c303b98b7c0ddeefb8c68c5f5bf78927e/src/api/node/urlHelper.js#L60-L66 |
54,267 | insin/concur | lib/concur.js | mixin | function mixin(dest, src) {
if (type(src) == 'function') {
extend(dest, src.prototype)
}
else {
extend(dest, src)
}
} | javascript | function mixin(dest, src) {
if (type(src) == 'function') {
extend(dest, src.prototype)
}
else {
extend(dest, src)
}
} | [
"function",
"mixin",
"(",
"dest",
",",
"src",
")",
"{",
"if",
"(",
"type",
"(",
"src",
")",
"==",
"'function'",
")",
"{",
"extend",
"(",
"dest",
",",
"src",
".",
"prototype",
")",
"}",
"else",
"{",
"extend",
"(",
"dest",
",",
"src",
")",
"}",
"}"
] | Mixes in properties from one object to another. If the source object is a
Function, its prototype is mixed in instead. | [
"Mixes",
"in",
"properties",
"from",
"one",
"object",
"to",
"another",
".",
"If",
"the",
"source",
"object",
"is",
"a",
"Function",
"its",
"prototype",
"is",
"mixed",
"in",
"instead",
"."
] | 86e816f1a0cb90ec227371bee065cc76e7234b7c | https://github.com/insin/concur/blob/86e816f1a0cb90ec227371bee065cc76e7234b7c/lib/concur.js#L31-L38 |
54,268 | insin/concur | lib/concur.js | inheritFrom | function inheritFrom(parentConstructor, childConstructor, prototypeProps, constructorProps) {
// Create a child constructor if one wasn't given
if (childConstructor == null) {
childConstructor = function() {
parentConstructor.apply(this, arguments)
}
}
// Make sure the new prototype has the correct constructor set up
prototypeProps.constructor = childConstructor
// Base constructors should only have the properties they're defined with
if (parentConstructor !== Concur) {
// Inherit the parent's prototype
inherits(childConstructor, parentConstructor)
childConstructor.__super__ = parentConstructor.prototype
}
// Add prototype properties - this is why we took a copy of the child
// constructor reference in extend() - if a .constructor had been passed as a
// __mixins__ and overitten prototypeProps.constructor, these properties would
// be getting set on the mixed-in constructor's prototype.
extend(childConstructor.prototype, prototypeProps)
// Add constructor properties
extend(childConstructor, constructorProps)
return childConstructor
} | javascript | function inheritFrom(parentConstructor, childConstructor, prototypeProps, constructorProps) {
// Create a child constructor if one wasn't given
if (childConstructor == null) {
childConstructor = function() {
parentConstructor.apply(this, arguments)
}
}
// Make sure the new prototype has the correct constructor set up
prototypeProps.constructor = childConstructor
// Base constructors should only have the properties they're defined with
if (parentConstructor !== Concur) {
// Inherit the parent's prototype
inherits(childConstructor, parentConstructor)
childConstructor.__super__ = parentConstructor.prototype
}
// Add prototype properties - this is why we took a copy of the child
// constructor reference in extend() - if a .constructor had been passed as a
// __mixins__ and overitten prototypeProps.constructor, these properties would
// be getting set on the mixed-in constructor's prototype.
extend(childConstructor.prototype, prototypeProps)
// Add constructor properties
extend(childConstructor, constructorProps)
return childConstructor
} | [
"function",
"inheritFrom",
"(",
"parentConstructor",
",",
"childConstructor",
",",
"prototypeProps",
",",
"constructorProps",
")",
"{",
"// Create a child constructor if one wasn't given",
"if",
"(",
"childConstructor",
"==",
"null",
")",
"{",
"childConstructor",
"=",
"function",
"(",
")",
"{",
"parentConstructor",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
"}",
"}",
"// Make sure the new prototype has the correct constructor set up",
"prototypeProps",
".",
"constructor",
"=",
"childConstructor",
"// Base constructors should only have the properties they're defined with",
"if",
"(",
"parentConstructor",
"!==",
"Concur",
")",
"{",
"// Inherit the parent's prototype",
"inherits",
"(",
"childConstructor",
",",
"parentConstructor",
")",
"childConstructor",
".",
"__super__",
"=",
"parentConstructor",
".",
"prototype",
"}",
"// Add prototype properties - this is why we took a copy of the child",
"// constructor reference in extend() - if a .constructor had been passed as a",
"// __mixins__ and overitten prototypeProps.constructor, these properties would",
"// be getting set on the mixed-in constructor's prototype.",
"extend",
"(",
"childConstructor",
".",
"prototype",
",",
"prototypeProps",
")",
"// Add constructor properties",
"extend",
"(",
"childConstructor",
",",
"constructorProps",
")",
"return",
"childConstructor",
"}"
] | Inherits another constructor's prototype and sets its prototype and
constructor properties in one fell swoop.
If a child constructor is not provided via prototypeProps.constructor,
a new constructor will be created. | [
"Inherits",
"another",
"constructor",
"s",
"prototype",
"and",
"sets",
"its",
"prototype",
"and",
"constructor",
"properties",
"in",
"one",
"fell",
"swoop",
"."
] | 86e816f1a0cb90ec227371bee065cc76e7234b7c | https://github.com/insin/concur/blob/86e816f1a0cb90ec227371bee065cc76e7234b7c/lib/concur.js#L64-L92 |
54,269 | spacemaus/postvox | vox-common/hubclient.js | saveUserProfileInCache | function saveUserProfileInCache(userProfile) {
var old = userProfileCache.peek(userProfile.nick);
if (old && old.updatedAt > userProfile.updatedAt) {
return;
}
userProfileCache.set(userProfile.nick, userProfile);
} | javascript | function saveUserProfileInCache(userProfile) {
var old = userProfileCache.peek(userProfile.nick);
if (old && old.updatedAt > userProfile.updatedAt) {
return;
}
userProfileCache.set(userProfile.nick, userProfile);
} | [
"function",
"saveUserProfileInCache",
"(",
"userProfile",
")",
"{",
"var",
"old",
"=",
"userProfileCache",
".",
"peek",
"(",
"userProfile",
".",
"nick",
")",
";",
"if",
"(",
"old",
"&&",
"old",
".",
"updatedAt",
">",
"userProfile",
".",
"updatedAt",
")",
"{",
"return",
";",
"}",
"userProfileCache",
".",
"set",
"(",
"userProfile",
".",
"nick",
",",
"userProfile",
")",
";",
"}"
] | Caches the UserProfile, but only if it is newer than the existing cached
version. | [
"Caches",
"the",
"UserProfile",
"but",
"only",
"if",
"it",
"is",
"newer",
"than",
"the",
"existing",
"cached",
"version",
"."
] | de98e5ed37edaee1b1edadf93e15eb8f8d21f457 | https://github.com/spacemaus/postvox/blob/de98e5ed37edaee1b1edadf93e15eb8f8d21f457/vox-common/hubclient.js#L40-L46 |
54,270 | chrishayesmu/DubBotBase | src/dubtrack.js | Bot | function Bot(credentials, globalObject, initializationCompleteCallback) {
LOG.info("Attempting to log in with email {}", credentials.username);
new DubAPI(credentials, (function(err, _bot) {
if (err) {
throw new Error("Error occurred when logging in: " + err);
}
this.bot = _bot;
LOG.info("Logged in successfully");
// Set up an error handler so errors don't cause the bot to crash
this.bot.on('error', function(err) {
LOG.error("Unhandled error occurred; swallowing it so bot keeps running. Error: {}", err);
});
// Reconnect the bot automatically if it disconnects
this.bot.on('disconnected', (function(roomName) {
LOG.warn("Disconnected from room {}. Reconnecting..", roomName);
this.connect(roomName);
}).bind(this));
// Set up custom event handling to insulate us from changes in the dubtrack API
this.eventHandlers = {};
for (var eventKey in Types.Event) {
var eventName = Types.Event[eventKey];
this.eventHandlers[eventName] = [];
}
if (globalObject.config.DubBotBase.logAllEvents) {
LOG.info("Logging of all events is enabled. Setting up logging event handlers.");
for (var eventKey in Types.Event) {
var eventName = Types.Event[eventKey];
LOG.info("Hooking into eventKey {}, eventName {}", eventKey, eventName);
this.bot.on(eventName, (function(name) {
return function(event) {
LOG.info("event '{}' has JSON payload: {}", name, event);
};
})(eventName));
}
}
for (var eventKey in Types.Event) {
var eventName = Types.Event[eventKey];
var translatorFunction = _eventTranslatorMap[eventName];
this.bot.on(eventName, _createEventDispatcher(eventName, translatorFunction, globalObject).bind(this));
}
if (initializationCompleteCallback) {
initializationCompleteCallback(this);
}
}).bind(this));
} | javascript | function Bot(credentials, globalObject, initializationCompleteCallback) {
LOG.info("Attempting to log in with email {}", credentials.username);
new DubAPI(credentials, (function(err, _bot) {
if (err) {
throw new Error("Error occurred when logging in: " + err);
}
this.bot = _bot;
LOG.info("Logged in successfully");
// Set up an error handler so errors don't cause the bot to crash
this.bot.on('error', function(err) {
LOG.error("Unhandled error occurred; swallowing it so bot keeps running. Error: {}", err);
});
// Reconnect the bot automatically if it disconnects
this.bot.on('disconnected', (function(roomName) {
LOG.warn("Disconnected from room {}. Reconnecting..", roomName);
this.connect(roomName);
}).bind(this));
// Set up custom event handling to insulate us from changes in the dubtrack API
this.eventHandlers = {};
for (var eventKey in Types.Event) {
var eventName = Types.Event[eventKey];
this.eventHandlers[eventName] = [];
}
if (globalObject.config.DubBotBase.logAllEvents) {
LOG.info("Logging of all events is enabled. Setting up logging event handlers.");
for (var eventKey in Types.Event) {
var eventName = Types.Event[eventKey];
LOG.info("Hooking into eventKey {}, eventName {}", eventKey, eventName);
this.bot.on(eventName, (function(name) {
return function(event) {
LOG.info("event '{}' has JSON payload: {}", name, event);
};
})(eventName));
}
}
for (var eventKey in Types.Event) {
var eventName = Types.Event[eventKey];
var translatorFunction = _eventTranslatorMap[eventName];
this.bot.on(eventName, _createEventDispatcher(eventName, translatorFunction, globalObject).bind(this));
}
if (initializationCompleteCallback) {
initializationCompleteCallback(this);
}
}).bind(this));
} | [
"function",
"Bot",
"(",
"credentials",
",",
"globalObject",
",",
"initializationCompleteCallback",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Attempting to log in with email {}\"",
",",
"credentials",
".",
"username",
")",
";",
"new",
"DubAPI",
"(",
"credentials",
",",
"(",
"function",
"(",
"err",
",",
"_bot",
")",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Error occurred when logging in: \"",
"+",
"err",
")",
";",
"}",
"this",
".",
"bot",
"=",
"_bot",
";",
"LOG",
".",
"info",
"(",
"\"Logged in successfully\"",
")",
";",
"// Set up an error handler so errors don't cause the bot to crash",
"this",
".",
"bot",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Unhandled error occurred; swallowing it so bot keeps running. Error: {}\"",
",",
"err",
")",
";",
"}",
")",
";",
"// Reconnect the bot automatically if it disconnects",
"this",
".",
"bot",
".",
"on",
"(",
"'disconnected'",
",",
"(",
"function",
"(",
"roomName",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"Disconnected from room {}. Reconnecting..\"",
",",
"roomName",
")",
";",
"this",
".",
"connect",
"(",
"roomName",
")",
";",
"}",
")",
".",
"bind",
"(",
"this",
")",
")",
";",
"// Set up custom event handling to insulate us from changes in the dubtrack API",
"this",
".",
"eventHandlers",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"eventKey",
"in",
"Types",
".",
"Event",
")",
"{",
"var",
"eventName",
"=",
"Types",
".",
"Event",
"[",
"eventKey",
"]",
";",
"this",
".",
"eventHandlers",
"[",
"eventName",
"]",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"globalObject",
".",
"config",
".",
"DubBotBase",
".",
"logAllEvents",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Logging of all events is enabled. Setting up logging event handlers.\"",
")",
";",
"for",
"(",
"var",
"eventKey",
"in",
"Types",
".",
"Event",
")",
"{",
"var",
"eventName",
"=",
"Types",
".",
"Event",
"[",
"eventKey",
"]",
";",
"LOG",
".",
"info",
"(",
"\"Hooking into eventKey {}, eventName {}\"",
",",
"eventKey",
",",
"eventName",
")",
";",
"this",
".",
"bot",
".",
"on",
"(",
"eventName",
",",
"(",
"function",
"(",
"name",
")",
"{",
"return",
"function",
"(",
"event",
")",
"{",
"LOG",
".",
"info",
"(",
"\"event '{}' has JSON payload: {}\"",
",",
"name",
",",
"event",
")",
";",
"}",
";",
"}",
")",
"(",
"eventName",
")",
")",
";",
"}",
"}",
"for",
"(",
"var",
"eventKey",
"in",
"Types",
".",
"Event",
")",
"{",
"var",
"eventName",
"=",
"Types",
".",
"Event",
"[",
"eventKey",
"]",
";",
"var",
"translatorFunction",
"=",
"_eventTranslatorMap",
"[",
"eventName",
"]",
";",
"this",
".",
"bot",
".",
"on",
"(",
"eventName",
",",
"_createEventDispatcher",
"(",
"eventName",
",",
"translatorFunction",
",",
"globalObject",
")",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"if",
"(",
"initializationCompleteCallback",
")",
"{",
"initializationCompleteCallback",
"(",
"this",
")",
";",
"}",
"}",
")",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Creates a new instance of the bot which will automatically connect to dubtrack.fm
and set up some event handling. | [
"Creates",
"a",
"new",
"instance",
"of",
"the",
"bot",
"which",
"will",
"automatically",
"connect",
"to",
"dubtrack",
".",
"fm",
"and",
"set",
"up",
"some",
"event",
"handling",
"."
] | 0e4b5e65531c23293d22ac766850c802b1266e48 | https://github.com/chrishayesmu/DubBotBase/blob/0e4b5e65531c23293d22ac766850c802b1266e48/src/dubtrack.js#L42-L96 |
54,271 | chrishayesmu/DubBotBase | src/dubtrack.js | _createEventDispatcher | function _createEventDispatcher(internalEventName, translator, globalObject) {
return function(event) {
var handlers = this.eventHandlers[internalEventName];
if (!translator) {
LOG.error("Could not find a translator for internalEventName {}", internalEventName);
return;
}
var internalObject = translator(event);
if (!internalObject) {
return;
}
internalObject.eventName = internalEventName;
for (var i = 0; i < handlers.length; i++) {
handlers[i].callback.call(handlers[i].context, internalObject, globalObject);
}
};
} | javascript | function _createEventDispatcher(internalEventName, translator, globalObject) {
return function(event) {
var handlers = this.eventHandlers[internalEventName];
if (!translator) {
LOG.error("Could not find a translator for internalEventName {}", internalEventName);
return;
}
var internalObject = translator(event);
if (!internalObject) {
return;
}
internalObject.eventName = internalEventName;
for (var i = 0; i < handlers.length; i++) {
handlers[i].callback.call(handlers[i].context, internalObject, globalObject);
}
};
} | [
"function",
"_createEventDispatcher",
"(",
"internalEventName",
",",
"translator",
",",
"globalObject",
")",
"{",
"return",
"function",
"(",
"event",
")",
"{",
"var",
"handlers",
"=",
"this",
".",
"eventHandlers",
"[",
"internalEventName",
"]",
";",
"if",
"(",
"!",
"translator",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Could not find a translator for internalEventName {}\"",
",",
"internalEventName",
")",
";",
"return",
";",
"}",
"var",
"internalObject",
"=",
"translator",
"(",
"event",
")",
";",
"if",
"(",
"!",
"internalObject",
")",
"{",
"return",
";",
"}",
"internalObject",
".",
"eventName",
"=",
"internalEventName",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"handlers",
".",
"length",
";",
"i",
"++",
")",
"{",
"handlers",
"[",
"i",
"]",
".",
"callback",
".",
"call",
"(",
"handlers",
"[",
"i",
"]",
".",
"context",
",",
"internalObject",
",",
"globalObject",
")",
";",
"}",
"}",
";",
"}"
] | Creates a function which dispatches the given event to its listeners.
@param {string} internalEventName - The event name from the Event enum
@param {function} translator - A function which translates from the DubAPI event to an internal model
@param {object} globalObject - The object representing global application state
@returns {function} An event dispatcher function appropriate to the event | [
"Creates",
"a",
"function",
"which",
"dispatches",
"the",
"given",
"event",
"to",
"its",
"listeners",
"."
] | 0e4b5e65531c23293d22ac766850c802b1266e48 | https://github.com/chrishayesmu/DubBotBase/blob/0e4b5e65531c23293d22ac766850c802b1266e48/src/dubtrack.js#L309-L330 |
54,272 | gyandeeps/load-perf | lib/cli.js | printResults | function printResults(results){
var output = "";
var dependenciesTimes = [];
var devDependenciesTimes = [];
dependenciesTimes = Object.keys(results.moduleTimes.dependencies).map(function(depen){
var val = results.moduleTimes.dependencies[depen];
return [
chalk.gray(depen),
" : ",
chalk.white(val === -1 ? "Cannot be required" : val)
];
});
devDependenciesTimes = Object.keys(results.moduleTimes.devDependencies).map(function(depen){
var val = results.moduleTimes.devDependencies[depen];
return [
chalk.gray(depen),
" : ",
chalk.white(val === -1 ? "Cannot be required" : val)
];
});
if(dependenciesTimes.length > 0){
output += chalk.white("Dependencies: \n");
output += table(dependenciesTimes, {align: ["l", "l"]});
}
if(devDependenciesTimes.length > 0){
output += chalk.white("\n\nDevDependencies: \n");
output += table(devDependenciesTimes, {align : ["l", "l"]});
}
output += chalk.white("\n\nModule load time: " + (results.loadTime === -1 ? "Cannot be required" : results.loadTime));
console.log(output);
} | javascript | function printResults(results){
var output = "";
var dependenciesTimes = [];
var devDependenciesTimes = [];
dependenciesTimes = Object.keys(results.moduleTimes.dependencies).map(function(depen){
var val = results.moduleTimes.dependencies[depen];
return [
chalk.gray(depen),
" : ",
chalk.white(val === -1 ? "Cannot be required" : val)
];
});
devDependenciesTimes = Object.keys(results.moduleTimes.devDependencies).map(function(depen){
var val = results.moduleTimes.devDependencies[depen];
return [
chalk.gray(depen),
" : ",
chalk.white(val === -1 ? "Cannot be required" : val)
];
});
if(dependenciesTimes.length > 0){
output += chalk.white("Dependencies: \n");
output += table(dependenciesTimes, {align: ["l", "l"]});
}
if(devDependenciesTimes.length > 0){
output += chalk.white("\n\nDevDependencies: \n");
output += table(devDependenciesTimes, {align : ["l", "l"]});
}
output += chalk.white("\n\nModule load time: " + (results.loadTime === -1 ? "Cannot be required" : results.loadTime));
console.log(output);
} | [
"function",
"printResults",
"(",
"results",
")",
"{",
"var",
"output",
"=",
"\"\"",
";",
"var",
"dependenciesTimes",
"=",
"[",
"]",
";",
"var",
"devDependenciesTimes",
"=",
"[",
"]",
";",
"dependenciesTimes",
"=",
"Object",
".",
"keys",
"(",
"results",
".",
"moduleTimes",
".",
"dependencies",
")",
".",
"map",
"(",
"function",
"(",
"depen",
")",
"{",
"var",
"val",
"=",
"results",
".",
"moduleTimes",
".",
"dependencies",
"[",
"depen",
"]",
";",
"return",
"[",
"chalk",
".",
"gray",
"(",
"depen",
")",
",",
"\" : \"",
",",
"chalk",
".",
"white",
"(",
"val",
"===",
"-",
"1",
"?",
"\"Cannot be required\"",
":",
"val",
")",
"]",
";",
"}",
")",
";",
"devDependenciesTimes",
"=",
"Object",
".",
"keys",
"(",
"results",
".",
"moduleTimes",
".",
"devDependencies",
")",
".",
"map",
"(",
"function",
"(",
"depen",
")",
"{",
"var",
"val",
"=",
"results",
".",
"moduleTimes",
".",
"devDependencies",
"[",
"depen",
"]",
";",
"return",
"[",
"chalk",
".",
"gray",
"(",
"depen",
")",
",",
"\" : \"",
",",
"chalk",
".",
"white",
"(",
"val",
"===",
"-",
"1",
"?",
"\"Cannot be required\"",
":",
"val",
")",
"]",
";",
"}",
")",
";",
"if",
"(",
"dependenciesTimes",
".",
"length",
">",
"0",
")",
"{",
"output",
"+=",
"chalk",
".",
"white",
"(",
"\"Dependencies: \\n\"",
")",
";",
"output",
"+=",
"table",
"(",
"dependenciesTimes",
",",
"{",
"align",
":",
"[",
"\"l\"",
",",
"\"l\"",
"]",
"}",
")",
";",
"}",
"if",
"(",
"devDependenciesTimes",
".",
"length",
">",
"0",
")",
"{",
"output",
"+=",
"chalk",
".",
"white",
"(",
"\"\\n\\nDevDependencies: \\n\"",
")",
";",
"output",
"+=",
"table",
"(",
"devDependenciesTimes",
",",
"{",
"align",
":",
"[",
"\"l\"",
",",
"\"l\"",
"]",
"}",
")",
";",
"}",
"output",
"+=",
"chalk",
".",
"white",
"(",
"\"\\n\\nModule load time: \"",
"+",
"(",
"results",
".",
"loadTime",
"===",
"-",
"1",
"?",
"\"Cannot be required\"",
":",
"results",
".",
"loadTime",
")",
")",
";",
"console",
".",
"log",
"(",
"output",
")",
";",
"}"
] | Prints the results of the run to the console
@param {object} results - Results object from main
@returns {void} | [
"Prints",
"the",
"results",
"of",
"the",
"run",
"to",
"the",
"console"
] | 045eb27e79699db621f57175db7e62e3857c10c0 | https://github.com/gyandeeps/load-perf/blob/045eb27e79699db621f57175db7e62e3857c10c0/lib/cli.js#L18-L55 |
54,273 | gyandeeps/load-perf | lib/cli.js | execute | function execute(args){
var options = optionator.parse(args);
if(options.help){
console.log(optionator.generateHelp());
}
else if(options.version){
console.log("v" + require("../package.json").version);
}
else{
printResults(loadPerf(options));
}
} | javascript | function execute(args){
var options = optionator.parse(args);
if(options.help){
console.log(optionator.generateHelp());
}
else if(options.version){
console.log("v" + require("../package.json").version);
}
else{
printResults(loadPerf(options));
}
} | [
"function",
"execute",
"(",
"args",
")",
"{",
"var",
"options",
"=",
"optionator",
".",
"parse",
"(",
"args",
")",
";",
"if",
"(",
"options",
".",
"help",
")",
"{",
"console",
".",
"log",
"(",
"optionator",
".",
"generateHelp",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"options",
".",
"version",
")",
"{",
"console",
".",
"log",
"(",
"\"v\"",
"+",
"require",
"(",
"\"../package.json\"",
")",
".",
"version",
")",
";",
"}",
"else",
"{",
"printResults",
"(",
"loadPerf",
"(",
"options",
")",
")",
";",
"}",
"}"
] | Executes the grouch based on the options passed in.
@param {string|Array|Object} args - The arguments to process.
@returns {void} | [
"Executes",
"the",
"grouch",
"based",
"on",
"the",
"options",
"passed",
"in",
"."
] | 045eb27e79699db621f57175db7e62e3857c10c0 | https://github.com/gyandeeps/load-perf/blob/045eb27e79699db621f57175db7e62e3857c10c0/lib/cli.js#L62-L74 |
54,274 | msemenistyi/grunt-grep | tasks/grep.js | grepLines | function grepLines(src, ext, destFile){
src = grunt.util.normalizelf(src);
var lines = src.split(grunt.util.linefeed),
dest = [],
//pattern for all comments containing denotation
denotationPattern = updatePattern({
pattern: options.pattern,
ext: ext,
isDenotationPattern: true}),
//pattern for one-line grep usage
pattern = updatePattern({
pattern: options.pattern,
ext: ext}),
//patterns for multi-line grep usage
startPattern = updatePattern({
pattern:options.pattern,
augmentPattern: options.startPattern,
ext: ext}),
endPattern = updatePattern({
pattern: options.pattern,
augmentPattern: options.endPattern,
ext: ext});
if (pattern !== false){
var startedRemoving;
//loop over each line looking for either pattern or denotation comments
lines.forEach(function(line) {
if (!startedRemoving){
//looking for one-line or start of multi-line pattern
if (line.search(startPattern) === -1 ){
//looking for one-line or start of one-line pattern
if (line.search(pattern) === -1 ){
//looking for denotation comments
if (options.removeDenotationComments && line.search(denotationPattern) !== -1){
var lineDenotationLess = line.replace(new RegExp(denotationPattern), '');
dest.push(lineDenotationLess);
} else {
//none of patterns found
dest.push(line);
}
}
} else{
//multi-line found
startedRemoving = true;
}
} else {
//looking for end of multi-line pattern
if (line.search(endPattern) !== -1 ){
startedRemoving = false;
}
}
});
var destText = dest.join(grunt.util.linefeed);
if (grunt.file.exists(destFile)){
if (!options.fileOverride){
grunt.fail.warn('File "' + destFile + '" already exists, though is specified as a dest file. ' +
'Turn on option "fileOverride" so that old file is removed first.');
} else {
grunt.file.delete(destFile);
}
}
grunt.file.write(destFile, destText);
grunt.log.writeln('File "' + destFile + '" created.');
} else {
grunt.log.warn('Pattern for \'' + task.target + '\' should be a string.');
}
} | javascript | function grepLines(src, ext, destFile){
src = grunt.util.normalizelf(src);
var lines = src.split(grunt.util.linefeed),
dest = [],
//pattern for all comments containing denotation
denotationPattern = updatePattern({
pattern: options.pattern,
ext: ext,
isDenotationPattern: true}),
//pattern for one-line grep usage
pattern = updatePattern({
pattern: options.pattern,
ext: ext}),
//patterns for multi-line grep usage
startPattern = updatePattern({
pattern:options.pattern,
augmentPattern: options.startPattern,
ext: ext}),
endPattern = updatePattern({
pattern: options.pattern,
augmentPattern: options.endPattern,
ext: ext});
if (pattern !== false){
var startedRemoving;
//loop over each line looking for either pattern or denotation comments
lines.forEach(function(line) {
if (!startedRemoving){
//looking for one-line or start of multi-line pattern
if (line.search(startPattern) === -1 ){
//looking for one-line or start of one-line pattern
if (line.search(pattern) === -1 ){
//looking for denotation comments
if (options.removeDenotationComments && line.search(denotationPattern) !== -1){
var lineDenotationLess = line.replace(new RegExp(denotationPattern), '');
dest.push(lineDenotationLess);
} else {
//none of patterns found
dest.push(line);
}
}
} else{
//multi-line found
startedRemoving = true;
}
} else {
//looking for end of multi-line pattern
if (line.search(endPattern) !== -1 ){
startedRemoving = false;
}
}
});
var destText = dest.join(grunt.util.linefeed);
if (grunt.file.exists(destFile)){
if (!options.fileOverride){
grunt.fail.warn('File "' + destFile + '" already exists, though is specified as a dest file. ' +
'Turn on option "fileOverride" so that old file is removed first.');
} else {
grunt.file.delete(destFile);
}
}
grunt.file.write(destFile, destText);
grunt.log.writeln('File "' + destFile + '" created.');
} else {
grunt.log.warn('Pattern for \'' + task.target + '\' should be a string.');
}
} | [
"function",
"grepLines",
"(",
"src",
",",
"ext",
",",
"destFile",
")",
"{",
"src",
"=",
"grunt",
".",
"util",
".",
"normalizelf",
"(",
"src",
")",
";",
"var",
"lines",
"=",
"src",
".",
"split",
"(",
"grunt",
".",
"util",
".",
"linefeed",
")",
",",
"dest",
"=",
"[",
"]",
",",
"//pattern for all comments containing denotation",
"denotationPattern",
"=",
"updatePattern",
"(",
"{",
"pattern",
":",
"options",
".",
"pattern",
",",
"ext",
":",
"ext",
",",
"isDenotationPattern",
":",
"true",
"}",
")",
",",
"//pattern for one-line grep usage",
"pattern",
"=",
"updatePattern",
"(",
"{",
"pattern",
":",
"options",
".",
"pattern",
",",
"ext",
":",
"ext",
"}",
")",
",",
"//patterns for multi-line grep usage",
"startPattern",
"=",
"updatePattern",
"(",
"{",
"pattern",
":",
"options",
".",
"pattern",
",",
"augmentPattern",
":",
"options",
".",
"startPattern",
",",
"ext",
":",
"ext",
"}",
")",
",",
"endPattern",
"=",
"updatePattern",
"(",
"{",
"pattern",
":",
"options",
".",
"pattern",
",",
"augmentPattern",
":",
"options",
".",
"endPattern",
",",
"ext",
":",
"ext",
"}",
")",
";",
"if",
"(",
"pattern",
"!==",
"false",
")",
"{",
"var",
"startedRemoving",
";",
"//loop over each line looking for either pattern or denotation comments",
"lines",
".",
"forEach",
"(",
"function",
"(",
"line",
")",
"{",
"if",
"(",
"!",
"startedRemoving",
")",
"{",
"//looking for one-line or start of multi-line pattern ",
"if",
"(",
"line",
".",
"search",
"(",
"startPattern",
")",
"===",
"-",
"1",
")",
"{",
"//looking for one-line or start of one-line pattern ",
"if",
"(",
"line",
".",
"search",
"(",
"pattern",
")",
"===",
"-",
"1",
")",
"{",
"//looking for denotation comments ",
"if",
"(",
"options",
".",
"removeDenotationComments",
"&&",
"line",
".",
"search",
"(",
"denotationPattern",
")",
"!==",
"-",
"1",
")",
"{",
"var",
"lineDenotationLess",
"=",
"line",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"denotationPattern",
")",
",",
"''",
")",
";",
"dest",
".",
"push",
"(",
"lineDenotationLess",
")",
";",
"}",
"else",
"{",
"//none of patterns found",
"dest",
".",
"push",
"(",
"line",
")",
";",
"}",
"}",
"}",
"else",
"{",
"//multi-line found",
"startedRemoving",
"=",
"true",
";",
"}",
"}",
"else",
"{",
"//looking for end of multi-line pattern ",
"if",
"(",
"line",
".",
"search",
"(",
"endPattern",
")",
"!==",
"-",
"1",
")",
"{",
"startedRemoving",
"=",
"false",
";",
"}",
"}",
"}",
")",
";",
"var",
"destText",
"=",
"dest",
".",
"join",
"(",
"grunt",
".",
"util",
".",
"linefeed",
")",
";",
"if",
"(",
"grunt",
".",
"file",
".",
"exists",
"(",
"destFile",
")",
")",
"{",
"if",
"(",
"!",
"options",
".",
"fileOverride",
")",
"{",
"grunt",
".",
"fail",
".",
"warn",
"(",
"'File \"'",
"+",
"destFile",
"+",
"'\" already exists, though is specified as a dest file. '",
"+",
"'Turn on option \"fileOverride\" so that old file is removed first.'",
")",
";",
"}",
"else",
"{",
"grunt",
".",
"file",
".",
"delete",
"(",
"destFile",
")",
";",
"}",
"}",
"grunt",
".",
"file",
".",
"write",
"(",
"destFile",
",",
"destText",
")",
";",
"grunt",
".",
"log",
".",
"writeln",
"(",
"'File \"'",
"+",
"destFile",
"+",
"'\" created.'",
")",
";",
"}",
"else",
"{",
"grunt",
".",
"log",
".",
"warn",
"(",
"'Pattern for \\''",
"+",
"task",
".",
"target",
"+",
"'\\' should be a string.'",
")",
";",
"}",
"}"
] | go through file and remove lines matching patterns, both single- and multi-line | [
"go",
"through",
"file",
"and",
"remove",
"lines",
"matching",
"patterns",
"both",
"single",
"-",
"and",
"multi",
"-",
"line"
] | d21530a8a7dd35e60d672118dc15d1e8c26035b2 | https://github.com/msemenistyi/grunt-grep/blob/d21530a8a7dd35e60d672118dc15d1e8c26035b2/tasks/grep.js#L83-L149 |
54,275 | joaquimserafim/superagent-bunyan | index.js | onResponse | function onResponse (res) {
endTime = getTimeMs(endTime)
res = Object.assign(res, { opDuration: endTime })
if (res.error) {
appendRes = res
} else {
log.info(
{
res: res,
duration: endTime
},
'end of the request'
)
}
} | javascript | function onResponse (res) {
endTime = getTimeMs(endTime)
res = Object.assign(res, { opDuration: endTime })
if (res.error) {
appendRes = res
} else {
log.info(
{
res: res,
duration: endTime
},
'end of the request'
)
}
} | [
"function",
"onResponse",
"(",
"res",
")",
"{",
"endTime",
"=",
"getTimeMs",
"(",
"endTime",
")",
"res",
"=",
"Object",
".",
"assign",
"(",
"res",
",",
"{",
"opDuration",
":",
"endTime",
"}",
")",
"if",
"(",
"res",
".",
"error",
")",
"{",
"appendRes",
"=",
"res",
"}",
"else",
"{",
"log",
".",
"info",
"(",
"{",
"res",
":",
"res",
",",
"duration",
":",
"endTime",
"}",
",",
"'end of the request'",
")",
"}",
"}"
] | in case of res.error should fallback to the error emitter and should pass the res object | [
"in",
"case",
"of",
"res",
".",
"error",
"should",
"fallback",
"to",
"the",
"error",
"emitter",
"and",
"should",
"pass",
"the",
"res",
"object"
] | b19ba4415cdb9933d78d50043468965cddc2d681 | https://github.com/joaquimserafim/superagent-bunyan/blob/b19ba4415cdb9933d78d50043468965cddc2d681/index.js#L78-L94 |
54,276 | ForbesLindesay/code-mirror | mode/puppet.js | define | function define(style, string) {
var split = string.split(' ');
for (var i = 0; i < split.length; i++) {
words[split[i]] = style;
}
} | javascript | function define(style, string) {
var split = string.split(' ');
for (var i = 0; i < split.length; i++) {
words[split[i]] = style;
}
} | [
"function",
"define",
"(",
"style",
",",
"string",
")",
"{",
"var",
"split",
"=",
"string",
".",
"split",
"(",
"' '",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"split",
".",
"length",
";",
"i",
"++",
")",
"{",
"words",
"[",
"split",
"[",
"i",
"]",
"]",
"=",
"style",
";",
"}",
"}"
] | Takes a string of words separated by spaces and adds them as keys with the value of the first argument 'style' | [
"Takes",
"a",
"string",
"of",
"words",
"separated",
"by",
"spaces",
"and",
"adds",
"them",
"as",
"keys",
"with",
"the",
"value",
"of",
"the",
"first",
"argument",
"style"
] | d790ea213aa354756adc7d4d9fcfffcfdc2f1278 | https://github.com/ForbesLindesay/code-mirror/blob/d790ea213aa354756adc7d4d9fcfffcfdc2f1278/mode/puppet.js#L10-L15 |
54,277 | goliatone/winston-honeybadger | lib/wiston-honeybadger.js | Honey | function Honey(options) {
options = options || {};
assert.isString(options.apiKey, 'Honeybadger transport needs an "apiKey" config option');
this.name = 'honeybadger';
this.apiKey = options.apiKey;
if(!options.logger) {
options.logger = console;
}
this.remote = new Badger(options);
winston.Transport.call(this, options);
} | javascript | function Honey(options) {
options = options || {};
assert.isString(options.apiKey, 'Honeybadger transport needs an "apiKey" config option');
this.name = 'honeybadger';
this.apiKey = options.apiKey;
if(!options.logger) {
options.logger = console;
}
this.remote = new Badger(options);
winston.Transport.call(this, options);
} | [
"function",
"Honey",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"assert",
".",
"isString",
"(",
"options",
".",
"apiKey",
",",
"'Honeybadger transport needs an \"apiKey\" config option'",
")",
";",
"this",
".",
"name",
"=",
"'honeybadger'",
";",
"this",
".",
"apiKey",
"=",
"options",
".",
"apiKey",
";",
"if",
"(",
"!",
"options",
".",
"logger",
")",
"{",
"options",
".",
"logger",
"=",
"console",
";",
"}",
"this",
".",
"remote",
"=",
"new",
"Badger",
"(",
"options",
")",
";",
"winston",
".",
"Transport",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"}"
] | Honeybadger transport constructor.
@param {Object} options Config object
@throws Error If options.apiKey is not present | [
"Honeybadger",
"transport",
"constructor",
"."
] | dd1b36949dd4581ba6c231c2eba47932e6bb1a66 | https://github.com/goliatone/winston-honeybadger/blob/dd1b36949dd4581ba6c231c2eba47932e6bb1a66/lib/wiston-honeybadger.js#L22-L37 |
54,278 | fczbkk/parse-relative-time | lib/index.js | parseInput | function parseInput(input) {
var match = re.exec(input);
if (match !== null) {
var _match = _slicedToArray(match, 6),
pre_keyword = _match[1],
operator_keyword = _match[2],
value = _match[3],
unit = _match[4],
post_keyword = _match[5];
if (pre_keyword && post_keyword || pre_keyword && operator_keyword || post_keyword && operator_keyword) {
return null;
}
return {
value: sanitizeValue({
value: value,
operator_keyword: operator_keyword,
post_keyword: post_keyword
}),
unit: unit
};
}
return null;
} | javascript | function parseInput(input) {
var match = re.exec(input);
if (match !== null) {
var _match = _slicedToArray(match, 6),
pre_keyword = _match[1],
operator_keyword = _match[2],
value = _match[3],
unit = _match[4],
post_keyword = _match[5];
if (pre_keyword && post_keyword || pre_keyword && operator_keyword || post_keyword && operator_keyword) {
return null;
}
return {
value: sanitizeValue({
value: value,
operator_keyword: operator_keyword,
post_keyword: post_keyword
}),
unit: unit
};
}
return null;
} | [
"function",
"parseInput",
"(",
"input",
")",
"{",
"var",
"match",
"=",
"re",
".",
"exec",
"(",
"input",
")",
";",
"if",
"(",
"match",
"!==",
"null",
")",
"{",
"var",
"_match",
"=",
"_slicedToArray",
"(",
"match",
",",
"6",
")",
",",
"pre_keyword",
"=",
"_match",
"[",
"1",
"]",
",",
"operator_keyword",
"=",
"_match",
"[",
"2",
"]",
",",
"value",
"=",
"_match",
"[",
"3",
"]",
",",
"unit",
"=",
"_match",
"[",
"4",
"]",
",",
"post_keyword",
"=",
"_match",
"[",
"5",
"]",
";",
"if",
"(",
"pre_keyword",
"&&",
"post_keyword",
"||",
"pre_keyword",
"&&",
"operator_keyword",
"||",
"post_keyword",
"&&",
"operator_keyword",
")",
"{",
"return",
"null",
";",
"}",
"return",
"{",
"value",
":",
"sanitizeValue",
"(",
"{",
"value",
":",
"value",
",",
"operator_keyword",
":",
"operator_keyword",
",",
"post_keyword",
":",
"post_keyword",
"}",
")",
",",
"unit",
":",
"unit",
"}",
";",
"}",
"return",
"null",
";",
"}"
] | Parses value and unit from human-readable relative time.
@param {string} input
@return {parsed_input | null} Returns `null` if input can not be parsed. | [
"Parses",
"value",
"and",
"unit",
"from",
"human",
"-",
"readable",
"relative",
"time",
"."
] | 77f197c2b94ab07a51ac688f52b2b3c08c6a49bd | https://github.com/fczbkk/parse-relative-time/blob/77f197c2b94ab07a51ac688f52b2b3c08c6a49bd/lib/index.js#L58-L84 |
54,279 | fczbkk/parse-relative-time | lib/index.js | sanitizeValue | function sanitizeValue(_ref) {
var value = _ref.value,
operator_keyword = _ref.operator_keyword,
post_keyword = _ref.post_keyword;
return parseInt(value, 10) * getMultiplier({
operator_keyword: operator_keyword,
post_keyword: post_keyword
});
} | javascript | function sanitizeValue(_ref) {
var value = _ref.value,
operator_keyword = _ref.operator_keyword,
post_keyword = _ref.post_keyword;
return parseInt(value, 10) * getMultiplier({
operator_keyword: operator_keyword,
post_keyword: post_keyword
});
} | [
"function",
"sanitizeValue",
"(",
"_ref",
")",
"{",
"var",
"value",
"=",
"_ref",
".",
"value",
",",
"operator_keyword",
"=",
"_ref",
".",
"operator_keyword",
",",
"post_keyword",
"=",
"_ref",
".",
"post_keyword",
";",
"return",
"parseInt",
"(",
"value",
",",
"10",
")",
"*",
"getMultiplier",
"(",
"{",
"operator_keyword",
":",
"operator_keyword",
",",
"post_keyword",
":",
"post_keyword",
"}",
")",
";",
"}"
] | Makes sure that the value is a number.
@param {object} config
@param {string} config.value
@param {operator_keyword} [config.operator_keyword]
@param {post_keyword} [config.post_keyword]
@return {number} | [
"Makes",
"sure",
"that",
"the",
"value",
"is",
"a",
"number",
"."
] | 77f197c2b94ab07a51ac688f52b2b3c08c6a49bd | https://github.com/fczbkk/parse-relative-time/blob/77f197c2b94ab07a51ac688f52b2b3c08c6a49bd/lib/index.js#L95-L103 |
54,280 | fczbkk/parse-relative-time | lib/index.js | getMultiplier | function getMultiplier(_ref2) {
var operator_keyword = _ref2.operator_keyword,
post_keyword = _ref2.post_keyword;
return operator_keyword === '-' || post_keyword === 'ago' ? -1 : 1;
} | javascript | function getMultiplier(_ref2) {
var operator_keyword = _ref2.operator_keyword,
post_keyword = _ref2.post_keyword;
return operator_keyword === '-' || post_keyword === 'ago' ? -1 : 1;
} | [
"function",
"getMultiplier",
"(",
"_ref2",
")",
"{",
"var",
"operator_keyword",
"=",
"_ref2",
".",
"operator_keyword",
",",
"post_keyword",
"=",
"_ref2",
".",
"post_keyword",
";",
"return",
"operator_keyword",
"===",
"'-'",
"||",
"post_keyword",
"===",
"'ago'",
"?",
"-",
"1",
":",
"1",
";",
"}"
] | Gets multiplier based on whether the value is in past or future.
@param {object} config
@param {operator_keyword} config.operator_keyword
@param {post_keyword} config.post_keyword
@return {number} | [
"Gets",
"multiplier",
"based",
"on",
"whether",
"the",
"value",
"is",
"in",
"past",
"or",
"future",
"."
] | 77f197c2b94ab07a51ac688f52b2b3c08c6a49bd | https://github.com/fczbkk/parse-relative-time/blob/77f197c2b94ab07a51ac688f52b2b3c08c6a49bd/lib/index.js#L113-L117 |
54,281 | fczbkk/parse-relative-time | lib/index.js | _default | function _default(input) {
var parsed_input = parseInput(input);
if (parsed_input !== null) {
var value = parsed_input.value,
unit = parsed_input.unit;
return relative_time_units[unit] * value;
}
return null;
} | javascript | function _default(input) {
var parsed_input = parseInput(input);
if (parsed_input !== null) {
var value = parsed_input.value,
unit = parsed_input.unit;
return relative_time_units[unit] * value;
}
return null;
} | [
"function",
"_default",
"(",
"input",
")",
"{",
"var",
"parsed_input",
"=",
"parseInput",
"(",
"input",
")",
";",
"if",
"(",
"parsed_input",
"!==",
"null",
")",
"{",
"var",
"value",
"=",
"parsed_input",
".",
"value",
",",
"unit",
"=",
"parsed_input",
".",
"unit",
";",
"return",
"relative_time_units",
"[",
"unit",
"]",
"*",
"value",
";",
"}",
"return",
"null",
";",
"}"
] | Parse simple relative time in human readable format to milliseconds.
@name parseRelativeTime
@param {string} input - Human readable format of relative time
@returns {null | number}
@example
parseRelativeTime('2 days'); // --> 172800000
parseRelativeTime('-2 days');
parseRelativeTime('in 2 days');
parseRelativeTime('2 days ago'); | [
"Parse",
"simple",
"relative",
"time",
"in",
"human",
"readable",
"format",
"to",
"milliseconds",
"."
] | 77f197c2b94ab07a51ac688f52b2b3c08c6a49bd | https://github.com/fczbkk/parse-relative-time/blob/77f197c2b94ab07a51ac688f52b2b3c08c6a49bd/lib/index.js#L131-L141 |
54,282 | Strider-CD/strider-runner-core | lib/job.js | function (text, plugin) {
debug(`Job "${this.id}" comments:`, plugin || '<no plugin>', text);
this.status('command.comment', {
comment: text,
plugin: plugin,
time: new Date()
});
} | javascript | function (text, plugin) {
debug(`Job "${this.id}" comments:`, plugin || '<no plugin>', text);
this.status('command.comment', {
comment: text,
plugin: plugin,
time: new Date()
});
} | [
"function",
"(",
"text",
",",
"plugin",
")",
"{",
"debug",
"(",
"`",
"${",
"this",
".",
"id",
"}",
"`",
",",
"plugin",
"||",
"'<no plugin>'",
",",
"text",
")",
";",
"this",
".",
"status",
"(",
"'command.comment'",
",",
"{",
"comment",
":",
"text",
",",
"plugin",
":",
"plugin",
",",
"time",
":",
"new",
"Date",
"(",
")",
"}",
")",
";",
"}"
] | command execution stuff | [
"command",
"execution",
"stuff"
] | 6fb14677186fb2d3becdf10fd8d14f09c3184a0c | https://github.com/Strider-CD/strider-runner-core/blob/6fb14677186fb2d3becdf10fd8d14f09c3184a0c/lib/job.js#L165-L172 |
|
54,283 | Strider-CD/strider-runner-core | lib/job.js | function (pluginName, env, path) {
var self = this;
var context = {
status: this.status.bind(this),
out: this.out.bind(this),
comment: function (text) {
self.comment(text, pluginName);
},
cmd: function (cmd, next) {
if (typeof(cmd) === 'string' || cmd.command) {
cmd = {cmd: cmd};
}
cmd.env = _.extend({}, env, {
PATH: getPath(path),
HOME: process.env.HOME || (process.env.HOMEDRIVE + process.env.HOMEPATH),
LANG: process.env.LANG,
SSH_AUTH_SOCK: process.env.SSH_AUTH_SOCK,
PAAS_NAME: 'strider'
}, cmd.env || {});
return self.cmd(cmd, pluginName, next);
},
// update pluginData
data: function (data, method, path) {
self.status('plugin-data', {
plugin: pluginName,
data: data,
method: method,
path: path
});
},
dataDir: this.config.dataDir,
baseDir: this.config.baseDir,
cacheDir: this.config.cacheDir,
cachier: this.config.cachier(pluginName),
io: this.io,
plugin: pluginName,
phase: this.phase,
job: this.job,
branch: this.job.ref.branch,
project: this.project,
runnerId: (
this.config.branchConfig
&& this.config.branchConfig.runner
&& this.config.branchConfig.runner.id || 'unkown'
)
};
return context;
} | javascript | function (pluginName, env, path) {
var self = this;
var context = {
status: this.status.bind(this),
out: this.out.bind(this),
comment: function (text) {
self.comment(text, pluginName);
},
cmd: function (cmd, next) {
if (typeof(cmd) === 'string' || cmd.command) {
cmd = {cmd: cmd};
}
cmd.env = _.extend({}, env, {
PATH: getPath(path),
HOME: process.env.HOME || (process.env.HOMEDRIVE + process.env.HOMEPATH),
LANG: process.env.LANG,
SSH_AUTH_SOCK: process.env.SSH_AUTH_SOCK,
PAAS_NAME: 'strider'
}, cmd.env || {});
return self.cmd(cmd, pluginName, next);
},
// update pluginData
data: function (data, method, path) {
self.status('plugin-data', {
plugin: pluginName,
data: data,
method: method,
path: path
});
},
dataDir: this.config.dataDir,
baseDir: this.config.baseDir,
cacheDir: this.config.cacheDir,
cachier: this.config.cachier(pluginName),
io: this.io,
plugin: pluginName,
phase: this.phase,
job: this.job,
branch: this.job.ref.branch,
project: this.project,
runnerId: (
this.config.branchConfig
&& this.config.branchConfig.runner
&& this.config.branchConfig.runner.id || 'unkown'
)
};
return context;
} | [
"function",
"(",
"pluginName",
",",
"env",
",",
"path",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"context",
"=",
"{",
"status",
":",
"this",
".",
"status",
".",
"bind",
"(",
"this",
")",
",",
"out",
":",
"this",
".",
"out",
".",
"bind",
"(",
"this",
")",
",",
"comment",
":",
"function",
"(",
"text",
")",
"{",
"self",
".",
"comment",
"(",
"text",
",",
"pluginName",
")",
";",
"}",
",",
"cmd",
":",
"function",
"(",
"cmd",
",",
"next",
")",
"{",
"if",
"(",
"typeof",
"(",
"cmd",
")",
"===",
"'string'",
"||",
"cmd",
".",
"command",
")",
"{",
"cmd",
"=",
"{",
"cmd",
":",
"cmd",
"}",
";",
"}",
"cmd",
".",
"env",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"env",
",",
"{",
"PATH",
":",
"getPath",
"(",
"path",
")",
",",
"HOME",
":",
"process",
".",
"env",
".",
"HOME",
"||",
"(",
"process",
".",
"env",
".",
"HOMEDRIVE",
"+",
"process",
".",
"env",
".",
"HOMEPATH",
")",
",",
"LANG",
":",
"process",
".",
"env",
".",
"LANG",
",",
"SSH_AUTH_SOCK",
":",
"process",
".",
"env",
".",
"SSH_AUTH_SOCK",
",",
"PAAS_NAME",
":",
"'strider'",
"}",
",",
"cmd",
".",
"env",
"||",
"{",
"}",
")",
";",
"return",
"self",
".",
"cmd",
"(",
"cmd",
",",
"pluginName",
",",
"next",
")",
";",
"}",
",",
"// update pluginData",
"data",
":",
"function",
"(",
"data",
",",
"method",
",",
"path",
")",
"{",
"self",
".",
"status",
"(",
"'plugin-data'",
",",
"{",
"plugin",
":",
"pluginName",
",",
"data",
":",
"data",
",",
"method",
":",
"method",
",",
"path",
":",
"path",
"}",
")",
";",
"}",
",",
"dataDir",
":",
"this",
".",
"config",
".",
"dataDir",
",",
"baseDir",
":",
"this",
".",
"config",
".",
"baseDir",
",",
"cacheDir",
":",
"this",
".",
"config",
".",
"cacheDir",
",",
"cachier",
":",
"this",
".",
"config",
".",
"cachier",
"(",
"pluginName",
")",
",",
"io",
":",
"this",
".",
"io",
",",
"plugin",
":",
"pluginName",
",",
"phase",
":",
"this",
".",
"phase",
",",
"job",
":",
"this",
".",
"job",
",",
"branch",
":",
"this",
".",
"job",
".",
"ref",
".",
"branch",
",",
"project",
":",
"this",
".",
"project",
",",
"runnerId",
":",
"(",
"this",
".",
"config",
".",
"branchConfig",
"&&",
"this",
".",
"config",
".",
"branchConfig",
".",
"runner",
"&&",
"this",
".",
"config",
".",
"branchConfig",
".",
"runner",
".",
"id",
"||",
"'unkown'",
")",
"}",
";",
"return",
"context",
";",
"}"
] | job running stuff | [
"job",
"running",
"stuff"
] | 6fb14677186fb2d3becdf10fd8d14f09c3184a0c | https://github.com/Strider-CD/strider-runner-core/blob/6fb14677186fb2d3becdf10fd8d14f09c3184a0c/lib/job.js#L296-L352 |
|
54,284 | serganus/RunGruntTask | index.js | RunGruntTask | function RunGruntTask(taskname,absolutePath) {
var exec = require('child_process').exec;
var gruntarg = ' --gruntfile ';
var space = ' ';
if (os === 'Windows_NT') {
gruntPath = 'node_modules\\grunt-cli\\bin\\grunt' || absolutePath;
var ShellTask = gruntPath + space + gruntarg + gruntfile + space + taskname;
var GruntTask = new shell(ShellTask);
GruntTask.on('output', function(data) {
console.log(data);
});
GruntTask.on('end', function(code) {
console.log("Execution done");
});
}
if (os === 'Darwin' || os === 'Linux') {
gruntPath = 'node_modules/grunt-cli/bin/grunt';
var child = exec(gruntPath + gruntarg + gruntfile + space + taskname, function(error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
var stdout = error;
return stdout;
} else {
console.log('stdout: ' + stdout);
return stdout;
}
});
}
} | javascript | function RunGruntTask(taskname,absolutePath) {
var exec = require('child_process').exec;
var gruntarg = ' --gruntfile ';
var space = ' ';
if (os === 'Windows_NT') {
gruntPath = 'node_modules\\grunt-cli\\bin\\grunt' || absolutePath;
var ShellTask = gruntPath + space + gruntarg + gruntfile + space + taskname;
var GruntTask = new shell(ShellTask);
GruntTask.on('output', function(data) {
console.log(data);
});
GruntTask.on('end', function(code) {
console.log("Execution done");
});
}
if (os === 'Darwin' || os === 'Linux') {
gruntPath = 'node_modules/grunt-cli/bin/grunt';
var child = exec(gruntPath + gruntarg + gruntfile + space + taskname, function(error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
var stdout = error;
return stdout;
} else {
console.log('stdout: ' + stdout);
return stdout;
}
});
}
} | [
"function",
"RunGruntTask",
"(",
"taskname",
",",
"absolutePath",
")",
"{",
"var",
"exec",
"=",
"require",
"(",
"'child_process'",
")",
".",
"exec",
";",
"var",
"gruntarg",
"=",
"' --gruntfile '",
";",
"var",
"space",
"=",
"' '",
";",
"if",
"(",
"os",
"===",
"'Windows_NT'",
")",
"{",
"gruntPath",
"=",
"'node_modules\\\\grunt-cli\\\\bin\\\\grunt'",
"||",
"absolutePath",
";",
"var",
"ShellTask",
"=",
"gruntPath",
"+",
"space",
"+",
"gruntarg",
"+",
"gruntfile",
"+",
"space",
"+",
"taskname",
";",
"var",
"GruntTask",
"=",
"new",
"shell",
"(",
"ShellTask",
")",
";",
"GruntTask",
".",
"on",
"(",
"'output'",
",",
"function",
"(",
"data",
")",
"{",
"console",
".",
"log",
"(",
"data",
")",
";",
"}",
")",
";",
"GruntTask",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
"code",
")",
"{",
"console",
".",
"log",
"(",
"\"Execution done\"",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"os",
"===",
"'Darwin'",
"||",
"os",
"===",
"'Linux'",
")",
"{",
"gruntPath",
"=",
"'node_modules/grunt-cli/bin/grunt'",
";",
"var",
"child",
"=",
"exec",
"(",
"gruntPath",
"+",
"gruntarg",
"+",
"gruntfile",
"+",
"space",
"+",
"taskname",
",",
"function",
"(",
"error",
",",
"stdout",
",",
"stderr",
")",
"{",
"if",
"(",
"error",
"!==",
"null",
")",
"{",
"console",
".",
"log",
"(",
"'exec error: '",
"+",
"error",
")",
";",
"var",
"stdout",
"=",
"error",
";",
"return",
"stdout",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'stdout: '",
"+",
"stdout",
")",
";",
"return",
"stdout",
";",
"}",
"}",
")",
";",
"}",
"}"
] | This would look for the GruntFile.js in your application structure | [
"This",
"would",
"look",
"for",
"the",
"GruntFile",
".",
"js",
"in",
"your",
"application",
"structure"
] | ce9d002524e63b7ea5a88e4f2cfba3cbbc5f80a9 | https://github.com/serganus/RunGruntTask/blob/ce9d002524e63b7ea5a88e4f2cfba3cbbc5f80a9/index.js#L7-L38 |
54,285 | brycebaril/transaction-tracer | examples/lib/worker.js | fetch | function fetch(url, id) {
var req = http.request(url, function (res) {
res.pipe(terminus.concat(function (contents) {
tx.end(id, {type: "fetch", url: url, code: res.statusCode})
}))
})
req.end()
} | javascript | function fetch(url, id) {
var req = http.request(url, function (res) {
res.pipe(terminus.concat(function (contents) {
tx.end(id, {type: "fetch", url: url, code: res.statusCode})
}))
})
req.end()
} | [
"function",
"fetch",
"(",
"url",
",",
"id",
")",
"{",
"var",
"req",
"=",
"http",
".",
"request",
"(",
"url",
",",
"function",
"(",
"res",
")",
"{",
"res",
".",
"pipe",
"(",
"terminus",
".",
"concat",
"(",
"function",
"(",
"contents",
")",
"{",
"tx",
".",
"end",
"(",
"id",
",",
"{",
"type",
":",
"\"fetch\"",
",",
"url",
":",
"url",
",",
"code",
":",
"res",
".",
"statusCode",
"}",
")",
"}",
")",
")",
"}",
")",
"req",
".",
"end",
"(",
")",
"}"
] | passing the id here not because that's a good practice but intead to show that the transaction tracer is idempotent accross requires by different files. it would probably make more sense to simply have all the tracing logic in one of the two places used here for a real application. | [
"passing",
"the",
"id",
"here",
"not",
"because",
"that",
"s",
"a",
"good",
"practice",
"but",
"intead",
"to",
"show",
"that",
"the",
"transaction",
"tracer",
"is",
"idempotent",
"accross",
"requires",
"by",
"different",
"files",
".",
"it",
"would",
"probably",
"make",
"more",
"sense",
"to",
"simply",
"have",
"all",
"the",
"tracing",
"logic",
"in",
"one",
"of",
"the",
"two",
"places",
"used",
"here",
"for",
"a",
"real",
"application",
"."
] | f3c4a33b5e1cea940be08589297e7555c40fe1d7 | https://github.com/brycebaril/transaction-tracer/blob/f3c4a33b5e1cea940be08589297e7555c40fe1d7/examples/lib/worker.js#L12-L19 |
54,286 | doowb/ask-once | index.js | Ask | function Ask(options) {
if (!(this instanceof Ask)) {
return new Ask(options);
}
this.options = options || {};
this.questions = utils.questions(this.options.questions);
var store = this.options.store;
var name = store && store.name;
if (!name) name = 'ask-once.' + utils.project(process.cwd());
this.answers = utils.store(name, store);
this.previous = utils.store(name + '.previous', this.answers.options);
Object.defineProperty(this, 'data', {
enumerable: true,
get: function () {
return this.answers.data;
}
});
} | javascript | function Ask(options) {
if (!(this instanceof Ask)) {
return new Ask(options);
}
this.options = options || {};
this.questions = utils.questions(this.options.questions);
var store = this.options.store;
var name = store && store.name;
if (!name) name = 'ask-once.' + utils.project(process.cwd());
this.answers = utils.store(name, store);
this.previous = utils.store(name + '.previous', this.answers.options);
Object.defineProperty(this, 'data', {
enumerable: true,
get: function () {
return this.answers.data;
}
});
} | [
"function",
"Ask",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Ask",
")",
")",
"{",
"return",
"new",
"Ask",
"(",
"options",
")",
";",
"}",
"this",
".",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"questions",
"=",
"utils",
".",
"questions",
"(",
"this",
".",
"options",
".",
"questions",
")",
";",
"var",
"store",
"=",
"this",
".",
"options",
".",
"store",
";",
"var",
"name",
"=",
"store",
"&&",
"store",
".",
"name",
";",
"if",
"(",
"!",
"name",
")",
"name",
"=",
"'ask-once.'",
"+",
"utils",
".",
"project",
"(",
"process",
".",
"cwd",
"(",
")",
")",
";",
"this",
".",
"answers",
"=",
"utils",
".",
"store",
"(",
"name",
",",
"store",
")",
";",
"this",
".",
"previous",
"=",
"utils",
".",
"store",
"(",
"name",
"+",
"'.previous'",
",",
"this",
".",
"answers",
".",
"options",
")",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'data'",
",",
"{",
"enumerable",
":",
"true",
",",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"answers",
".",
"data",
";",
"}",
"}",
")",
";",
"}"
] | Returns a question-asking function that only asks a question
if the answer is not already stored, or if forced.
```js
var ask = new Ask({questions: questions});
```
@param {Object} `options`
@param {Object} `options.questions` (optional) Options to be passed to [question-cache][]
@param {Object} `options.store` (optional) Options to be passed to [data-store][]
@api public | [
"Returns",
"a",
"question",
"-",
"asking",
"function",
"that",
"only",
"asks",
"a",
"question",
"if",
"the",
"answer",
"is",
"not",
"already",
"stored",
"or",
"if",
"forced",
"."
] | 622d18243be7485fda965a87cd3467f6790eafef | https://github.com/doowb/ask-once/blob/622d18243be7485fda965a87cd3467f6790eafef/index.js#L27-L48 |
54,287 | JimmyRobz/mokuai | utils/basename.js | basename | function basename(file){
var extname = path.extname(file);
return path.basename(file, extname);
} | javascript | function basename(file){
var extname = path.extname(file);
return path.basename(file, extname);
} | [
"function",
"basename",
"(",
"file",
")",
"{",
"var",
"extname",
"=",
"path",
".",
"extname",
"(",
"file",
")",
";",
"return",
"path",
".",
"basename",
"(",
"file",
",",
"extname",
")",
";",
"}"
] | Utility function to get basename of file | [
"Utility",
"function",
"to",
"get",
"basename",
"of",
"file"
] | 02ba6dfd6fb61b4a124e15a8252cff7e940132ac | https://github.com/JimmyRobz/mokuai/blob/02ba6dfd6fb61b4a124e15a8252cff7e940132ac/utils/basename.js#L4-L7 |
54,288 | supercrabtree/tie-dye | hexToRgb.js | hexToRgb | function hexToRgb(hex) {
var match = hex.toString(16).match(/[a-f0-9]{6}/i);
if (!match) {
return {r: 0, g: 0, b: 0};
}
var integer = parseInt(match[0], 16);
var r = (integer >> 16) & 0xFF;
var g = (integer >> 8) & 0xFF;
var b = integer & 0xFF;
return {
r: r,
g: g,
b: b
};
} | javascript | function hexToRgb(hex) {
var match = hex.toString(16).match(/[a-f0-9]{6}/i);
if (!match) {
return {r: 0, g: 0, b: 0};
}
var integer = parseInt(match[0], 16);
var r = (integer >> 16) & 0xFF;
var g = (integer >> 8) & 0xFF;
var b = integer & 0xFF;
return {
r: r,
g: g,
b: b
};
} | [
"function",
"hexToRgb",
"(",
"hex",
")",
"{",
"var",
"match",
"=",
"hex",
".",
"toString",
"(",
"16",
")",
".",
"match",
"(",
"/",
"[a-f0-9]{6}",
"/",
"i",
")",
";",
"if",
"(",
"!",
"match",
")",
"{",
"return",
"{",
"r",
":",
"0",
",",
"g",
":",
"0",
",",
"b",
":",
"0",
"}",
";",
"}",
"var",
"integer",
"=",
"parseInt",
"(",
"match",
"[",
"0",
"]",
",",
"16",
")",
";",
"var",
"r",
"=",
"(",
"integer",
">>",
"16",
")",
"&",
"0xFF",
";",
"var",
"g",
"=",
"(",
"integer",
">>",
"8",
")",
"&",
"0xFF",
";",
"var",
"b",
"=",
"integer",
"&",
"0xFF",
";",
"return",
"{",
"r",
":",
"r",
",",
"g",
":",
"g",
",",
"b",
":",
"b",
"}",
";",
"}"
] | Convert a color from hexidecimal to RGB
@param {string} hex - A string containing six hexidecimal characters
@returns {object} With the signature {r: 0-255, g: 0-255, b: 0-255} | [
"Convert",
"a",
"color",
"from",
"hexidecimal",
"to",
"RGB"
] | 1bf045767ce1a3fcf88450fbf95f72b5646f63df | https://github.com/supercrabtree/tie-dye/blob/1bf045767ce1a3fcf88450fbf95f72b5646f63df/hexToRgb.js#L7-L25 |
54,289 | jobsteven/promisify-git | index.js | function (dir_path) {
return fs.statAsync(dir_path)
.call('isDirectory')
.then(function (isDirectory) {
if (isDirectory) {
return fs.readdirAsync(dir_path)
.map(function (file_name) {
var file_path = dir_path + '/' + file_name;
return fs.statAsync(file_path)
.then(function (stat) {
return {
isDirectory: stat.isDirectory(),
file_path: file_path
}
})
})
.reduce(function (files, file_item) {
if (file_item.isDirectory) {
return getFilesByDir(file_item.file_path)
.then(function (subDirFiles) {
return files.concat(subDirFiles)
})
}
files.push(file_item.file_path);
return files
}, [])
}
throw new Error('Please input a valid directory!');
})
} | javascript | function (dir_path) {
return fs.statAsync(dir_path)
.call('isDirectory')
.then(function (isDirectory) {
if (isDirectory) {
return fs.readdirAsync(dir_path)
.map(function (file_name) {
var file_path = dir_path + '/' + file_name;
return fs.statAsync(file_path)
.then(function (stat) {
return {
isDirectory: stat.isDirectory(),
file_path: file_path
}
})
})
.reduce(function (files, file_item) {
if (file_item.isDirectory) {
return getFilesByDir(file_item.file_path)
.then(function (subDirFiles) {
return files.concat(subDirFiles)
})
}
files.push(file_item.file_path);
return files
}, [])
}
throw new Error('Please input a valid directory!');
})
} | [
"function",
"(",
"dir_path",
")",
"{",
"return",
"fs",
".",
"statAsync",
"(",
"dir_path",
")",
".",
"call",
"(",
"'isDirectory'",
")",
".",
"then",
"(",
"function",
"(",
"isDirectory",
")",
"{",
"if",
"(",
"isDirectory",
")",
"{",
"return",
"fs",
".",
"readdirAsync",
"(",
"dir_path",
")",
".",
"map",
"(",
"function",
"(",
"file_name",
")",
"{",
"var",
"file_path",
"=",
"dir_path",
"+",
"'/'",
"+",
"file_name",
";",
"return",
"fs",
".",
"statAsync",
"(",
"file_path",
")",
".",
"then",
"(",
"function",
"(",
"stat",
")",
"{",
"return",
"{",
"isDirectory",
":",
"stat",
".",
"isDirectory",
"(",
")",
",",
"file_path",
":",
"file_path",
"}",
"}",
")",
"}",
")",
".",
"reduce",
"(",
"function",
"(",
"files",
",",
"file_item",
")",
"{",
"if",
"(",
"file_item",
".",
"isDirectory",
")",
"{",
"return",
"getFilesByDir",
"(",
"file_item",
".",
"file_path",
")",
".",
"then",
"(",
"function",
"(",
"subDirFiles",
")",
"{",
"return",
"files",
".",
"concat",
"(",
"subDirFiles",
")",
"}",
")",
"}",
"files",
".",
"push",
"(",
"file_item",
".",
"file_path",
")",
";",
"return",
"files",
"}",
",",
"[",
"]",
")",
"}",
"throw",
"new",
"Error",
"(",
"'Please input a valid directory!'",
")",
";",
"}",
")",
"}"
] | get all file in a directory recursively | [
"get",
"all",
"file",
"in",
"a",
"directory",
"recursively"
] | 86dab46e33f35eced2bc5f290f1959060253e32c | https://github.com/jobsteven/promisify-git/blob/86dab46e33f35eced2bc5f290f1959060253e32c/index.js#L45-L74 |
|
54,290 | azendal/argon | argon/association.js | hasMany | function hasMany(config) {
var association;
association = {
type : 'HAS_MANY',
name : config.name || config,
cardinality : 'many',
targetModel : config.targetModel || config,
localProperty : config.localProperty || 'id',
targetProperty : config.targetProperty || (config + 'Id')
};
this.prototype[association.name] = function(callback){
var model = this;
var targetModel = window;
association.targetModel.split('.').forEach(function (property) {
targetModel = targetModel[property];
});
targetModel.all(function (data) {
var result = data.filter(function (instance) {
return instance[association.targetProperty] === model[association.localProperty];
});
if (callback) {
callback(result);
}
});
};
return this;
} | javascript | function hasMany(config) {
var association;
association = {
type : 'HAS_MANY',
name : config.name || config,
cardinality : 'many',
targetModel : config.targetModel || config,
localProperty : config.localProperty || 'id',
targetProperty : config.targetProperty || (config + 'Id')
};
this.prototype[association.name] = function(callback){
var model = this;
var targetModel = window;
association.targetModel.split('.').forEach(function (property) {
targetModel = targetModel[property];
});
targetModel.all(function (data) {
var result = data.filter(function (instance) {
return instance[association.targetProperty] === model[association.localProperty];
});
if (callback) {
callback(result);
}
});
};
return this;
} | [
"function",
"hasMany",
"(",
"config",
")",
"{",
"var",
"association",
";",
"association",
"=",
"{",
"type",
":",
"'HAS_MANY'",
",",
"name",
":",
"config",
".",
"name",
"||",
"config",
",",
"cardinality",
":",
"'many'",
",",
"targetModel",
":",
"config",
".",
"targetModel",
"||",
"config",
",",
"localProperty",
":",
"config",
".",
"localProperty",
"||",
"'id'",
",",
"targetProperty",
":",
"config",
".",
"targetProperty",
"||",
"(",
"config",
"+",
"'Id'",
")",
"}",
";",
"this",
".",
"prototype",
"[",
"association",
".",
"name",
"]",
"=",
"function",
"(",
"callback",
")",
"{",
"var",
"model",
"=",
"this",
";",
"var",
"targetModel",
"=",
"window",
";",
"association",
".",
"targetModel",
".",
"split",
"(",
"'.'",
")",
".",
"forEach",
"(",
"function",
"(",
"property",
")",
"{",
"targetModel",
"=",
"targetModel",
"[",
"property",
"]",
";",
"}",
")",
";",
"targetModel",
".",
"all",
"(",
"function",
"(",
"data",
")",
"{",
"var",
"result",
"=",
"data",
".",
"filter",
"(",
"function",
"(",
"instance",
")",
"{",
"return",
"instance",
"[",
"association",
".",
"targetProperty",
"]",
"===",
"model",
"[",
"association",
".",
"localProperty",
"]",
";",
"}",
")",
";",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"result",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"return",
"this",
";",
"}"
] | Creates a hasMany method on the class running the method, this creates the "associationName"
method on the object running the method. This is a factory method
@method <public> hasMany
@argument <required> [Object] ({}) config
@return this | [
"Creates",
"a",
"hasMany",
"method",
"on",
"the",
"class",
"running",
"the",
"method",
"this",
"creates",
"the",
"associationName",
"method",
"on",
"the",
"object",
"running",
"the",
"method",
".",
"This",
"is",
"a",
"factory",
"method"
] | 0cfd3a3b3731b69abca55c956c757476779ec1bd | https://github.com/azendal/argon/blob/0cfd3a3b3731b69abca55c956c757476779ec1bd/argon/association.js#L53-L81 |
54,291 | dan-nl/yeoman-prompting-helpers | src/prompting-helper.js | promptingHelper | function promptingHelper( generator, generator_prompts ) {
var prompts = filterPrompts( generator.options.PromptAnswers, generator_prompts );
return generator.prompt( prompts )
.then(
function ( answers ) {
addPromptAnswers( generator.options.PromptAnswers, answers );
}
);
} | javascript | function promptingHelper( generator, generator_prompts ) {
var prompts = filterPrompts( generator.options.PromptAnswers, generator_prompts );
return generator.prompt( prompts )
.then(
function ( answers ) {
addPromptAnswers( generator.options.PromptAnswers, answers );
}
);
} | [
"function",
"promptingHelper",
"(",
"generator",
",",
"generator_prompts",
")",
"{",
"var",
"prompts",
"=",
"filterPrompts",
"(",
"generator",
".",
"options",
".",
"PromptAnswers",
",",
"generator_prompts",
")",
";",
"return",
"generator",
".",
"prompt",
"(",
"prompts",
")",
".",
"then",
"(",
"function",
"(",
"answers",
")",
"{",
"addPromptAnswers",
"(",
"generator",
".",
"options",
".",
"PromptAnswers",
",",
"answers",
")",
";",
"}",
")",
";",
"}"
] | filters prompts for a generator
compares prompts in the provided generator_prompts with those in generator.options.PromptAnswers.
if a prompt.name already exists in generator.options.PromptAnswers.answers, then it’s not
presented again to the user. the generator can retrieve the previously answered prompt with
generator.options.PromptAnswers.get( prompt.name )
@param {Object} generator
@param {Array} generator_prompts
@returns {Promise} | [
"filters",
"prompts",
"for",
"a",
"generator"
] | 6b698989f7350f736705bae66d8481d01512612c | https://github.com/dan-nl/yeoman-prompting-helpers/blob/6b698989f7350f736705bae66d8481d01512612c/src/prompting-helper.js#L21-L30 |
54,292 | reid/onyx | lib/onyx.js | xfer | function xfer (res, files, cb) {
var file = files.shift();
if (!file) {
return cb(null);
}
fs.createReadStream(file
).on("data", function (chunk) {
res.write(chunk);
}).on("error", cb
).on("close", function xferClose () {
xfer(res, files, cb);
});
} | javascript | function xfer (res, files, cb) {
var file = files.shift();
if (!file) {
return cb(null);
}
fs.createReadStream(file
).on("data", function (chunk) {
res.write(chunk);
}).on("error", cb
).on("close", function xferClose () {
xfer(res, files, cb);
});
} | [
"function",
"xfer",
"(",
"res",
",",
"files",
",",
"cb",
")",
"{",
"var",
"file",
"=",
"files",
".",
"shift",
"(",
")",
";",
"if",
"(",
"!",
"file",
")",
"{",
"return",
"cb",
"(",
"null",
")",
";",
"}",
"fs",
".",
"createReadStream",
"(",
"file",
")",
".",
"on",
"(",
"\"data\"",
",",
"function",
"(",
"chunk",
")",
"{",
"res",
".",
"write",
"(",
"chunk",
")",
";",
"}",
")",
".",
"on",
"(",
"\"error\"",
",",
"cb",
")",
".",
"on",
"(",
"\"close\"",
",",
"function",
"xferClose",
"(",
")",
"{",
"xfer",
"(",
"res",
",",
"files",
",",
"cb",
")",
";",
"}",
")",
";",
"}"
] | Implementation of the actual file transfer. | [
"Implementation",
"of",
"the",
"actual",
"file",
"transfer",
"."
] | 25fd002b4389e62f4a8bf3eabb8a2c9c9b06f8a0 | https://github.com/reid/onyx/blob/25fd002b4389e62f4a8bf3eabb8a2c9c9b06f8a0/lib/onyx.js#L116-L130 |
54,293 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/plugins/floatpanel/plugin.js | function( editor, parentElement, definition, level ) {
definition.forceIFrame = 1;
// In case of editor with floating toolbar append panels that should float
// to the main UI element.
if ( definition.toolbarRelated && editor.elementMode == CKEDITOR.ELEMENT_MODE_INLINE )
parentElement = CKEDITOR.document.getById( 'cke_' + editor.name );
var doc = parentElement.getDocument(),
panel = getPanel( editor, doc, parentElement, definition, level || 0 ),
element = panel.element,
iframe = element.getFirst(),
that = this;
// Disable native browser menu. (#4825)
element.disableContextMenu();
this.element = element;
this._ = {
editor: editor,
// The panel that will be floating.
panel: panel,
parentElement: parentElement,
definition: definition,
document: doc,
iframe: iframe,
children: [],
dir: editor.lang.dir
};
editor.on( 'mode', hide );
editor.on( 'resize', hide );
// Window resize doesn't cause hide on blur. (#9800)
// [iOS] Poping up keyboard triggers window resize
// which leads to undesired panel hides.
if ( !CKEDITOR.env.iOS )
doc.getWindow().on( 'resize', hide );
// We need a wrapper because events implementation doesn't allow to attach
// one listener more than once for the same event on the same object.
// Remember that floatPanel#hide is shared between all instances.
function hide() {
that.hide();
}
} | javascript | function( editor, parentElement, definition, level ) {
definition.forceIFrame = 1;
// In case of editor with floating toolbar append panels that should float
// to the main UI element.
if ( definition.toolbarRelated && editor.elementMode == CKEDITOR.ELEMENT_MODE_INLINE )
parentElement = CKEDITOR.document.getById( 'cke_' + editor.name );
var doc = parentElement.getDocument(),
panel = getPanel( editor, doc, parentElement, definition, level || 0 ),
element = panel.element,
iframe = element.getFirst(),
that = this;
// Disable native browser menu. (#4825)
element.disableContextMenu();
this.element = element;
this._ = {
editor: editor,
// The panel that will be floating.
panel: panel,
parentElement: parentElement,
definition: definition,
document: doc,
iframe: iframe,
children: [],
dir: editor.lang.dir
};
editor.on( 'mode', hide );
editor.on( 'resize', hide );
// Window resize doesn't cause hide on blur. (#9800)
// [iOS] Poping up keyboard triggers window resize
// which leads to undesired panel hides.
if ( !CKEDITOR.env.iOS )
doc.getWindow().on( 'resize', hide );
// We need a wrapper because events implementation doesn't allow to attach
// one listener more than once for the same event on the same object.
// Remember that floatPanel#hide is shared between all instances.
function hide() {
that.hide();
}
} | [
"function",
"(",
"editor",
",",
"parentElement",
",",
"definition",
",",
"level",
")",
"{",
"definition",
".",
"forceIFrame",
"=",
"1",
";",
"// In case of editor with floating toolbar append panels that should float\r",
"// to the main UI element.\r",
"if",
"(",
"definition",
".",
"toolbarRelated",
"&&",
"editor",
".",
"elementMode",
"==",
"CKEDITOR",
".",
"ELEMENT_MODE_INLINE",
")",
"parentElement",
"=",
"CKEDITOR",
".",
"document",
".",
"getById",
"(",
"'cke_'",
"+",
"editor",
".",
"name",
")",
";",
"var",
"doc",
"=",
"parentElement",
".",
"getDocument",
"(",
")",
",",
"panel",
"=",
"getPanel",
"(",
"editor",
",",
"doc",
",",
"parentElement",
",",
"definition",
",",
"level",
"||",
"0",
")",
",",
"element",
"=",
"panel",
".",
"element",
",",
"iframe",
"=",
"element",
".",
"getFirst",
"(",
")",
",",
"that",
"=",
"this",
";",
"// Disable native browser menu. (#4825)\r",
"element",
".",
"disableContextMenu",
"(",
")",
";",
"this",
".",
"element",
"=",
"element",
";",
"this",
".",
"_",
"=",
"{",
"editor",
":",
"editor",
",",
"// The panel that will be floating.\r",
"panel",
":",
"panel",
",",
"parentElement",
":",
"parentElement",
",",
"definition",
":",
"definition",
",",
"document",
":",
"doc",
",",
"iframe",
":",
"iframe",
",",
"children",
":",
"[",
"]",
",",
"dir",
":",
"editor",
".",
"lang",
".",
"dir",
"}",
";",
"editor",
".",
"on",
"(",
"'mode'",
",",
"hide",
")",
";",
"editor",
".",
"on",
"(",
"'resize'",
",",
"hide",
")",
";",
"// Window resize doesn't cause hide on blur. (#9800)\r",
"// [iOS] Poping up keyboard triggers window resize\r",
"// which leads to undesired panel hides.\r",
"if",
"(",
"!",
"CKEDITOR",
".",
"env",
".",
"iOS",
")",
"doc",
".",
"getWindow",
"(",
")",
".",
"on",
"(",
"'resize'",
",",
"hide",
")",
";",
"// We need a wrapper because events implementation doesn't allow to attach\r",
"// one listener more than once for the same event on the same object.\r",
"// Remember that floatPanel#hide is shared between all instances.\r",
"function",
"hide",
"(",
")",
"{",
"that",
".",
"hide",
"(",
")",
";",
"}",
"}"
] | Creates a floatPanel class instance.
@constructor
@param {CKEDITOR.editor} editor
@param {CKEDITOR.dom.element} parentElement
@param {Object} definition Definition of the panel that will be floating.
@param {Number} level | [
"Creates",
"a",
"floatPanel",
"class",
"instance",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/floatpanel/plugin.js#L50-L96 |
|
54,294 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/plugins/floatpanel/plugin.js | function() {
// Webkit requires to blur any previous focused page element, in
// order to properly fire the "focus" event.
if ( CKEDITOR.env.webkit ) {
var active = CKEDITOR.document.getActive();
active && !active.equals( this._.iframe ) && active.$.blur();
}
// Restore last focused element or simply focus panel window.
var focus = this._.lastFocused || this._.iframe.getFrameDocument().getWindow();
focus.focus();
} | javascript | function() {
// Webkit requires to blur any previous focused page element, in
// order to properly fire the "focus" event.
if ( CKEDITOR.env.webkit ) {
var active = CKEDITOR.document.getActive();
active && !active.equals( this._.iframe ) && active.$.blur();
}
// Restore last focused element or simply focus panel window.
var focus = this._.lastFocused || this._.iframe.getFrameDocument().getWindow();
focus.focus();
} | [
"function",
"(",
")",
"{",
"// Webkit requires to blur any previous focused page element, in\r",
"// order to properly fire the \"focus\" event.\r",
"if",
"(",
"CKEDITOR",
".",
"env",
".",
"webkit",
")",
"{",
"var",
"active",
"=",
"CKEDITOR",
".",
"document",
".",
"getActive",
"(",
")",
";",
"active",
"&&",
"!",
"active",
".",
"equals",
"(",
"this",
".",
"_",
".",
"iframe",
")",
"&&",
"active",
".",
"$",
".",
"blur",
"(",
")",
";",
"}",
"// Restore last focused element or simply focus panel window.\r",
"var",
"focus",
"=",
"this",
".",
"_",
".",
"lastFocused",
"||",
"this",
".",
"_",
".",
"iframe",
".",
"getFrameDocument",
"(",
")",
".",
"getWindow",
"(",
")",
";",
"focus",
".",
"focus",
"(",
")",
";",
"}"
] | Restores last focused element or simply focus panel window. | [
"Restores",
"last",
"focused",
"element",
"or",
"simply",
"focus",
"panel",
"window",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/floatpanel/plugin.js#L427-L438 |
|
54,295 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/plugins/floatpanel/plugin.js | function( panel, blockName, offsetParent, corner, offsetX, offsetY ) {
// Skip reshowing of child which is already visible.
if ( this._.activeChild == panel && panel._.panel._.offsetParentId == offsetParent.getId() )
return;
this.hideChild();
panel.onHide = CKEDITOR.tools.bind( function() {
// Use a timeout, so we give time for this menu to get
// potentially focused.
CKEDITOR.tools.setTimeout( function() {
if ( !this._.focused )
this.hide();
}, 0, this );
}, this );
this._.activeChild = panel;
this._.focused = false;
panel.showBlock( blockName, offsetParent, corner, offsetX, offsetY );
this.blur();
/* #3767 IE: Second level menu may not have borders */
if ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) {
setTimeout( function() {
panel.element.getChild( 0 ).$.style.cssText += '';
}, 100 );
}
} | javascript | function( panel, blockName, offsetParent, corner, offsetX, offsetY ) {
// Skip reshowing of child which is already visible.
if ( this._.activeChild == panel && panel._.panel._.offsetParentId == offsetParent.getId() )
return;
this.hideChild();
panel.onHide = CKEDITOR.tools.bind( function() {
// Use a timeout, so we give time for this menu to get
// potentially focused.
CKEDITOR.tools.setTimeout( function() {
if ( !this._.focused )
this.hide();
}, 0, this );
}, this );
this._.activeChild = panel;
this._.focused = false;
panel.showBlock( blockName, offsetParent, corner, offsetX, offsetY );
this.blur();
/* #3767 IE: Second level menu may not have borders */
if ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) {
setTimeout( function() {
panel.element.getChild( 0 ).$.style.cssText += '';
}, 100 );
}
} | [
"function",
"(",
"panel",
",",
"blockName",
",",
"offsetParent",
",",
"corner",
",",
"offsetX",
",",
"offsetY",
")",
"{",
"// Skip reshowing of child which is already visible.\r",
"if",
"(",
"this",
".",
"_",
".",
"activeChild",
"==",
"panel",
"&&",
"panel",
".",
"_",
".",
"panel",
".",
"_",
".",
"offsetParentId",
"==",
"offsetParent",
".",
"getId",
"(",
")",
")",
"return",
";",
"this",
".",
"hideChild",
"(",
")",
";",
"panel",
".",
"onHide",
"=",
"CKEDITOR",
".",
"tools",
".",
"bind",
"(",
"function",
"(",
")",
"{",
"// Use a timeout, so we give time for this menu to get\r",
"// potentially focused.\r",
"CKEDITOR",
".",
"tools",
".",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_",
".",
"focused",
")",
"this",
".",
"hide",
"(",
")",
";",
"}",
",",
"0",
",",
"this",
")",
";",
"}",
",",
"this",
")",
";",
"this",
".",
"_",
".",
"activeChild",
"=",
"panel",
";",
"this",
".",
"_",
".",
"focused",
"=",
"false",
";",
"panel",
".",
"showBlock",
"(",
"blockName",
",",
"offsetParent",
",",
"corner",
",",
"offsetX",
",",
"offsetY",
")",
";",
"this",
".",
"blur",
"(",
")",
";",
"/* #3767 IE: Second level menu may not have borders */",
"if",
"(",
"CKEDITOR",
".",
"env",
".",
"ie7Compat",
"||",
"CKEDITOR",
".",
"env",
".",
"ie6Compat",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"panel",
".",
"element",
".",
"getChild",
"(",
"0",
")",
".",
"$",
".",
"style",
".",
"cssText",
"+=",
"''",
";",
"}",
",",
"100",
")",
";",
"}",
"}"
] | Shows specified panel as a child of one block of this one.
@param {CKEDITOR.ui.floatPanel} panel
@param {String} blockName
@param {CKEDITOR.dom.element} offsetParent Positioned parent.
@param {Number} corner
* For LTR (left to right) oriented editor:
* `1` = top-left
* `2` = top-right
* `3` = bottom-right
* `4` = bottom-left
* For RTL (right to left):
* `1` = top-right
* `2` = top-left
* `3` = bottom-left
* `4` = bottom-right
@param {Number} [offsetX=0]
@param {Number} [offsetY=0]
@todo | [
"Shows",
"specified",
"panel",
"as",
"a",
"child",
"of",
"one",
"block",
"of",
"this",
"one",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/floatpanel/plugin.js#L515-L543 |
|
54,296 | olizilla/instagrab | bin/instagrab.js | grabUrls | function grabUrls (opts) {
opts.shortcode.forEach(function (shortcode) {
instagrab.url(shortcode, opts.size, function (err, url) {
console.log(err || url)
})
})
} | javascript | function grabUrls (opts) {
opts.shortcode.forEach(function (shortcode) {
instagrab.url(shortcode, opts.size, function (err, url) {
console.log(err || url)
})
})
} | [
"function",
"grabUrls",
"(",
"opts",
")",
"{",
"opts",
".",
"shortcode",
".",
"forEach",
"(",
"function",
"(",
"shortcode",
")",
"{",
"instagrab",
".",
"url",
"(",
"shortcode",
",",
"opts",
".",
"size",
",",
"function",
"(",
"err",
",",
"url",
")",
"{",
"console",
".",
"log",
"(",
"err",
"||",
"url",
")",
"}",
")",
"}",
")",
"}"
] | Log out the urls. | [
"Log",
"out",
"the",
"urls",
"."
] | fe21a57a0aeecacaaa37eccc9d06822889d78ba6 | https://github.com/olizilla/instagrab/blob/fe21a57a0aeecacaaa37eccc9d06822889d78ba6/bin/instagrab.js#L86-L92 |
54,297 | olizilla/instagrab | bin/instagrab.js | grabImages | function grabImages (opts) {
if (!opts.quiet) console.log(multiline(function () {/*
_ _| | |
| __ \ __| __| _` | _` | __| _` | __ \
| | | \__ \ | ( | ( | | ( | | |
___| _| _| ____/ \__| \__,_| \__, | _| \__,_| _.__/
|___/
*/}))
opts.shortcode.forEach(function (shortcode) {
// set up the sink
var filename = instagrab.filename(shortcode, opts.size)
var filepath = path.join(process.cwd(), filename)
var toFile = fs.createWriteStream(filepath)
toFile.on('error', onSaveError(shortcode))
toFile.on('finish', function onSaved () {
if (this.quiet) return;
console.log('grabbed: ', filename)
})
// grab the bits
return instagrab(shortcode, opts.size)
.on('error', onGrabError(shortcode))
.pipe(toFile)
})
} | javascript | function grabImages (opts) {
if (!opts.quiet) console.log(multiline(function () {/*
_ _| | |
| __ \ __| __| _` | _` | __| _` | __ \
| | | \__ \ | ( | ( | | ( | | |
___| _| _| ____/ \__| \__,_| \__, | _| \__,_| _.__/
|___/
*/}))
opts.shortcode.forEach(function (shortcode) {
// set up the sink
var filename = instagrab.filename(shortcode, opts.size)
var filepath = path.join(process.cwd(), filename)
var toFile = fs.createWriteStream(filepath)
toFile.on('error', onSaveError(shortcode))
toFile.on('finish', function onSaved () {
if (this.quiet) return;
console.log('grabbed: ', filename)
})
// grab the bits
return instagrab(shortcode, opts.size)
.on('error', onGrabError(shortcode))
.pipe(toFile)
})
} | [
"function",
"grabImages",
"(",
"opts",
")",
"{",
"if",
"(",
"!",
"opts",
".",
"quiet",
")",
"console",
".",
"log",
"(",
"multiline",
"(",
"function",
"(",
")",
"{",
"/*\n\n _ _| | |\n | __ \\ __| __| _` | _` | __| _` | __ \\\n | | | \\__ \\ | ( | ( | | ( | | |\n ___| _| _| ____/ \\__| \\__,_| \\__, | _| \\__,_| _.__/\n |___/\n\n*/",
"}",
")",
")",
"opts",
".",
"shortcode",
".",
"forEach",
"(",
"function",
"(",
"shortcode",
")",
"{",
"// set up the sink",
"var",
"filename",
"=",
"instagrab",
".",
"filename",
"(",
"shortcode",
",",
"opts",
".",
"size",
")",
"var",
"filepath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"filename",
")",
"var",
"toFile",
"=",
"fs",
".",
"createWriteStream",
"(",
"filepath",
")",
"toFile",
".",
"on",
"(",
"'error'",
",",
"onSaveError",
"(",
"shortcode",
")",
")",
"toFile",
".",
"on",
"(",
"'finish'",
",",
"function",
"onSaved",
"(",
")",
"{",
"if",
"(",
"this",
".",
"quiet",
")",
"return",
";",
"console",
".",
"log",
"(",
"'grabbed: '",
",",
"filename",
")",
"}",
")",
"// grab the bits",
"return",
"instagrab",
"(",
"shortcode",
",",
"opts",
".",
"size",
")",
".",
"on",
"(",
"'error'",
",",
"onGrabError",
"(",
"shortcode",
")",
")",
".",
"pipe",
"(",
"toFile",
")",
"}",
")",
"}"
] | otherwise, start the fanfare and save the images | [
"otherwise",
"start",
"the",
"fanfare",
"and",
"save",
"the",
"images"
] | fe21a57a0aeecacaaa37eccc9d06822889d78ba6 | https://github.com/olizilla/instagrab/blob/fe21a57a0aeecacaaa37eccc9d06822889d78ba6/bin/instagrab.js#L95-L122 |
54,298 | meisterplayer/js-dev | gulp/copy.js | createCopy | function createCopy(inPath, outPath) {
if (!inPath) {
throw new Error('Input path(s) argument is required');
}
if (!outPath) {
throw new Error('Output path argument is required');
}
return function copyFiles() {
return gulp.src(inPath).pipe(gulp.dest(outPath));
};
} | javascript | function createCopy(inPath, outPath) {
if (!inPath) {
throw new Error('Input path(s) argument is required');
}
if (!outPath) {
throw new Error('Output path argument is required');
}
return function copyFiles() {
return gulp.src(inPath).pipe(gulp.dest(outPath));
};
} | [
"function",
"createCopy",
"(",
"inPath",
",",
"outPath",
")",
"{",
"if",
"(",
"!",
"inPath",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Input path(s) argument is required'",
")",
";",
"}",
"if",
"(",
"!",
"outPath",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Output path argument is required'",
")",
";",
"}",
"return",
"function",
"copyFiles",
"(",
")",
"{",
"return",
"gulp",
".",
"src",
"(",
"inPath",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"outPath",
")",
")",
";",
"}",
";",
"}"
] | Higher order function to create gulp function that copies files from one location to another.
@param {string|string[]} inPath The globs to the files that need to be copied
@param {string} outPath The destination path for the copies
@return {function} Function that can be used as a gulp task | [
"Higher",
"order",
"function",
"to",
"create",
"gulp",
"function",
"that",
"copies",
"files",
"from",
"one",
"location",
"to",
"another",
"."
] | c2646678c49dcdaa120ba3f24824da52b0c63e31 | https://github.com/meisterplayer/js-dev/blob/c2646678c49dcdaa120ba3f24824da52b0c63e31/gulp/copy.js#L9-L21 |
54,299 | restorecommerce/service-config | index.js | logConfigFile | function logConfigFile(configFile, logger) {
let message;
if (process.env.WORKER_ID !== undefined) {
message = `Worker ${process.env.WORKER_ID} uses configuration file: ${configFile}`;
} else {
message = `Supervisor uses configuration file: ${configFile}`;
}
if (logger && logger.verbose) {
logger.verbose(message);
} else {
// eslint-disable-next-line no-console
console.log(message);
}
} | javascript | function logConfigFile(configFile, logger) {
let message;
if (process.env.WORKER_ID !== undefined) {
message = `Worker ${process.env.WORKER_ID} uses configuration file: ${configFile}`;
} else {
message = `Supervisor uses configuration file: ${configFile}`;
}
if (logger && logger.verbose) {
logger.verbose(message);
} else {
// eslint-disable-next-line no-console
console.log(message);
}
} | [
"function",
"logConfigFile",
"(",
"configFile",
",",
"logger",
")",
"{",
"let",
"message",
";",
"if",
"(",
"process",
".",
"env",
".",
"WORKER_ID",
"!==",
"undefined",
")",
"{",
"message",
"=",
"`",
"${",
"process",
".",
"env",
".",
"WORKER_ID",
"}",
"${",
"configFile",
"}",
"`",
";",
"}",
"else",
"{",
"message",
"=",
"`",
"${",
"configFile",
"}",
"`",
";",
"}",
"if",
"(",
"logger",
"&&",
"logger",
".",
"verbose",
")",
"{",
"logger",
".",
"verbose",
"(",
"message",
")",
";",
"}",
"else",
"{",
"// eslint-disable-next-line no-console",
"console",
".",
"log",
"(",
"message",
")",
";",
"}",
"}"
] | log config file usages | [
"log",
"config",
"file",
"usages"
] | f7ae2183ceaf78e2b6cb9d426c8606b71377ea87 | https://github.com/restorecommerce/service-config/blob/f7ae2183ceaf78e2b6cb9d426c8606b71377ea87/index.js#L9-L22 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.