repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
wecodemore/grunt-githooks
|
lib/githooks.js
|
function() {
var hookPath = path.resolve(this.options.dest, this.hookName);
var existingCode = this.getHookContent(hookPath);
if (existingCode) {
this.validateScriptLanguage(existingCode);
}
var hookContent;
if(this.hasMarkers(existingCode)) {
hookContent = this.insertBindingCode(existingCode);
} else {
hookContent = this.appendBindingCode(existingCode);
}
fs.writeFileSync(hookPath, hookContent);
fs.chmodSync(hookPath, '755');
}
|
javascript
|
function() {
var hookPath = path.resolve(this.options.dest, this.hookName);
var existingCode = this.getHookContent(hookPath);
if (existingCode) {
this.validateScriptLanguage(existingCode);
}
var hookContent;
if(this.hasMarkers(existingCode)) {
hookContent = this.insertBindingCode(existingCode);
} else {
hookContent = this.appendBindingCode(existingCode);
}
fs.writeFileSync(hookPath, hookContent);
fs.chmodSync(hookPath, '755');
}
|
[
"function",
"(",
")",
"{",
"var",
"hookPath",
"=",
"path",
".",
"resolve",
"(",
"this",
".",
"options",
".",
"dest",
",",
"this",
".",
"hookName",
")",
";",
"var",
"existingCode",
"=",
"this",
".",
"getHookContent",
"(",
"hookPath",
")",
";",
"if",
"(",
"existingCode",
")",
"{",
"this",
".",
"validateScriptLanguage",
"(",
"existingCode",
")",
";",
"}",
"var",
"hookContent",
";",
"if",
"(",
"this",
".",
"hasMarkers",
"(",
"existingCode",
")",
")",
"{",
"hookContent",
"=",
"this",
".",
"insertBindingCode",
"(",
"existingCode",
")",
";",
"}",
"else",
"{",
"hookContent",
"=",
"this",
".",
"appendBindingCode",
"(",
"existingCode",
")",
";",
"}",
"fs",
".",
"writeFileSync",
"(",
"hookPath",
",",
"hookContent",
")",
";",
"fs",
".",
"chmodSync",
"(",
"hookPath",
",",
"'755'",
")",
";",
"}"
] |
Creates the hook
@method create
|
[
"Creates",
"the",
"hook"
] |
8a026d6b9529c7923e734960813d1f54315a8e47
|
https://github.com/wecodemore/grunt-githooks/blob/8a026d6b9529c7923e734960813d1f54315a8e47/lib/githooks.js#L48-L68
|
train
|
|
wecodemore/grunt-githooks
|
lib/githooks.js
|
function () {
var template = this.loadTemplate(this.options.template);
var bindingCode = template({
hook: this.hookName,
command: this.options.command,
task: this.taskNames,
preventExit: this.options.preventExit,
args: this.options.args,
gruntfileDirectory: process.cwd(),
options: this.options
});
return this.options.startMarker + '\n' + bindingCode + '\n' + this.options.endMarker;
}
|
javascript
|
function () {
var template = this.loadTemplate(this.options.template);
var bindingCode = template({
hook: this.hookName,
command: this.options.command,
task: this.taskNames,
preventExit: this.options.preventExit,
args: this.options.args,
gruntfileDirectory: process.cwd(),
options: this.options
});
return this.options.startMarker + '\n' + bindingCode + '\n' + this.options.endMarker;
}
|
[
"function",
"(",
")",
"{",
"var",
"template",
"=",
"this",
".",
"loadTemplate",
"(",
"this",
".",
"options",
".",
"template",
")",
";",
"var",
"bindingCode",
"=",
"template",
"(",
"{",
"hook",
":",
"this",
".",
"hookName",
",",
"command",
":",
"this",
".",
"options",
".",
"command",
",",
"task",
":",
"this",
".",
"taskNames",
",",
"preventExit",
":",
"this",
".",
"options",
".",
"preventExit",
",",
"args",
":",
"this",
".",
"options",
".",
"args",
",",
"gruntfileDirectory",
":",
"process",
".",
"cwd",
"(",
")",
",",
"options",
":",
"this",
".",
"options",
"}",
")",
";",
"return",
"this",
".",
"options",
".",
"startMarker",
"+",
"'\\n'",
"+",
"\\n",
"+",
"bindingCode",
"+",
"'\\n'",
";",
"}"
] |
Creates the code that will run the grunt task from the hook
@method createBindingCode
@param task {String}
@param templatePath {Object}
|
[
"Creates",
"the",
"code",
"that",
"will",
"run",
"the",
"grunt",
"task",
"from",
"the",
"hook"
] |
8a026d6b9529c7923e734960813d1f54315a8e47
|
https://github.com/wecodemore/grunt-githooks/blob/8a026d6b9529c7923e734960813d1f54315a8e47/lib/githooks.js#L128-L142
|
train
|
|
jonschlinkert/utils
|
lib/object/merge.js
|
merge
|
function merge(o) {
if (!isPlainObject(o)) { return {}; }
var args = arguments;
var len = args.length - 1;
for (var i = 0; i < len; i++) {
var obj = args[i + 1];
if (isPlainObject(obj)) {
for (var key in obj) {
if (hasOwn(obj, key)) {
if (isPlainObject(obj[key])) {
o[key] = merge(o[key], obj[key]);
} else {
o[key] = obj[key];
}
}
}
}
}
return o;
}
|
javascript
|
function merge(o) {
if (!isPlainObject(o)) { return {}; }
var args = arguments;
var len = args.length - 1;
for (var i = 0; i < len; i++) {
var obj = args[i + 1];
if (isPlainObject(obj)) {
for (var key in obj) {
if (hasOwn(obj, key)) {
if (isPlainObject(obj[key])) {
o[key] = merge(o[key], obj[key]);
} else {
o[key] = obj[key];
}
}
}
}
}
return o;
}
|
[
"function",
"merge",
"(",
"o",
")",
"{",
"if",
"(",
"!",
"isPlainObject",
"(",
"o",
")",
")",
"{",
"return",
"{",
"}",
";",
"}",
"var",
"args",
"=",
"arguments",
";",
"var",
"len",
"=",
"args",
".",
"length",
"-",
"1",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"obj",
"=",
"args",
"[",
"i",
"+",
"1",
"]",
";",
"if",
"(",
"isPlainObject",
"(",
"obj",
")",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"obj",
")",
"{",
"if",
"(",
"hasOwn",
"(",
"obj",
",",
"key",
")",
")",
"{",
"if",
"(",
"isPlainObject",
"(",
"obj",
"[",
"key",
"]",
")",
")",
"{",
"o",
"[",
"key",
"]",
"=",
"merge",
"(",
"o",
"[",
"key",
"]",
",",
"obj",
"[",
"key",
"]",
")",
";",
"}",
"else",
"{",
"o",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
";",
"}",
"}",
"}",
"}",
"}",
"return",
"o",
";",
"}"
] |
Recursively combine the properties of `o` with the
properties of other `objects`.
@name .merge
@param {Object} `o` The target object. Pass an empty object to shallow clone.
@param {Object} `objects`
@return {Object}
@api public
|
[
"Recursively",
"combine",
"the",
"properties",
"of",
"o",
"with",
"the",
"properties",
"of",
"other",
"objects",
"."
] |
1eae0cbeef81123e4dc29d0ac1db04f7a2a09a4b
|
https://github.com/jonschlinkert/utils/blob/1eae0cbeef81123e4dc29d0ac1db04f7a2a09a4b/lib/object/merge.js#L23-L44
|
train
|
feonit/olap-cube-js
|
examples/product-table/component/tree-table.js
|
function(obj) {
const keys = Object.keys(obj).sort(function(key1, key2) {
return key1 === 'id' ? false : key1 > key2;
});
return keys;
}
|
javascript
|
function(obj) {
const keys = Object.keys(obj).sort(function(key1, key2) {
return key1 === 'id' ? false : key1 > key2;
});
return keys;
}
|
[
"function",
"(",
"obj",
")",
"{",
"const",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"sort",
"(",
"function",
"(",
"key1",
",",
"key2",
")",
"{",
"return",
"key1",
"===",
"'id'",
"?",
"false",
":",
"key1",
">",
"key2",
";",
"}",
")",
";",
"return",
"keys",
";",
"}"
] |
Sort where param id placed in first column
|
[
"Sort",
"where",
"param",
"id",
"placed",
"in",
"first",
"column"
] |
13f32aac2ff9f472b0f1cd237f24eece53eaf2e3
|
https://github.com/feonit/olap-cube-js/blob/13f32aac2ff9f472b0f1cd237f24eece53eaf2e3/examples/product-table/component/tree-table.js#L50-L55
|
train
|
|
feonit/olap-cube-js
|
src/Cube.js
|
unfilled
|
function unfilled(cube) {
const tuples = Cube.cartesian(cube);
const unfilled = [];
tuples.forEach(tuple => {
const members = this.dice(tuple).getFacts(tuple);
if (members.length === 0) {
unfilled.push(tuple)
}
});
return unfilled;
}
|
javascript
|
function unfilled(cube) {
const tuples = Cube.cartesian(cube);
const unfilled = [];
tuples.forEach(tuple => {
const members = this.dice(tuple).getFacts(tuple);
if (members.length === 0) {
unfilled.push(tuple)
}
});
return unfilled;
}
|
[
"function",
"unfilled",
"(",
"cube",
")",
"{",
"const",
"tuples",
"=",
"Cube",
".",
"cartesian",
"(",
"cube",
")",
";",
"const",
"unfilled",
"=",
"[",
"]",
";",
"tuples",
".",
"forEach",
"(",
"tuple",
"=>",
"{",
"const",
"members",
"=",
"this",
".",
"dice",
"(",
"tuple",
")",
".",
"getFacts",
"(",
"tuple",
")",
";",
"if",
"(",
"members",
".",
"length",
"===",
"0",
")",
"{",
"unfilled",
".",
"push",
"(",
"tuple",
")",
"}",
"}",
")",
";",
"return",
"unfilled",
";",
"}"
] |
Unfilled - list of tuples, in accordance with which there is not a single member
@@param {Cube} cube
|
[
"Unfilled",
"-",
"list",
"of",
"tuples",
"in",
"accordance",
"with",
"which",
"there",
"is",
"not",
"a",
"single",
"member"
] |
13f32aac2ff9f472b0f1cd237f24eece53eaf2e3
|
https://github.com/feonit/olap-cube-js/blob/13f32aac2ff9f472b0f1cd237f24eece53eaf2e3/src/Cube.js#L704-L714
|
train
|
Beh01der/node-grok
|
lib/index.js
|
resolveFieldNames
|
function resolveFieldNames (pattern) {
if(!pattern) { return; }
var nestLevel = 0;
var inRangeDef = 0;
var matched;
while ((matched = nestedFieldNamesRegex.exec(pattern.resolved)) !== null) {
switch(matched[0]) {
case '(': { if(!inRangeDef) { ++nestLevel; pattern.fields.push(null); } break; }
case '\\(': break; // can be ignored
case '\\)': break; // can be ignored
case ')': { if(!inRangeDef) { --nestLevel; } break; }
case '[': { ++inRangeDef; break; }
case '\\[': break; // can be ignored
case '\\]': break; // can be ignored
case ']': { --inRangeDef; break; }
case '(?:': // fallthrough // group not captured
case '(?>': // fallthrough // atomic group
case '(?!': // fallthrough // negative look-ahead
case '(?<!': { if(!inRangeDef) { ++nestLevel; } break; } // negative look-behind
default: { ++nestLevel; pattern.fields.push(matched[2]); break; }
}
}
return pattern;
}
|
javascript
|
function resolveFieldNames (pattern) {
if(!pattern) { return; }
var nestLevel = 0;
var inRangeDef = 0;
var matched;
while ((matched = nestedFieldNamesRegex.exec(pattern.resolved)) !== null) {
switch(matched[0]) {
case '(': { if(!inRangeDef) { ++nestLevel; pattern.fields.push(null); } break; }
case '\\(': break; // can be ignored
case '\\)': break; // can be ignored
case ')': { if(!inRangeDef) { --nestLevel; } break; }
case '[': { ++inRangeDef; break; }
case '\\[': break; // can be ignored
case '\\]': break; // can be ignored
case ']': { --inRangeDef; break; }
case '(?:': // fallthrough // group not captured
case '(?>': // fallthrough // atomic group
case '(?!': // fallthrough // negative look-ahead
case '(?<!': { if(!inRangeDef) { ++nestLevel; } break; } // negative look-behind
default: { ++nestLevel; pattern.fields.push(matched[2]); break; }
}
}
return pattern;
}
|
[
"function",
"resolveFieldNames",
"(",
"pattern",
")",
"{",
"if",
"(",
"!",
"pattern",
")",
"{",
"return",
";",
"}",
"var",
"nestLevel",
"=",
"0",
";",
"var",
"inRangeDef",
"=",
"0",
";",
"var",
"matched",
";",
"while",
"(",
"(",
"matched",
"=",
"nestedFieldNamesRegex",
".",
"exec",
"(",
"pattern",
".",
"resolved",
")",
")",
"!==",
"null",
")",
"{",
"switch",
"(",
"matched",
"[",
"0",
"]",
")",
"{",
"case",
"'('",
":",
"{",
"if",
"(",
"!",
"inRangeDef",
")",
"{",
"++",
"nestLevel",
";",
"pattern",
".",
"fields",
".",
"push",
"(",
"null",
")",
";",
"}",
"break",
";",
"}",
"case",
"'\\\\('",
":",
"\\\\",
"break",
";",
"case",
"'\\\\)'",
":",
"\\\\",
"break",
";",
"case",
"')'",
":",
"{",
"if",
"(",
"!",
"inRangeDef",
")",
"{",
"--",
"nestLevel",
";",
"}",
"break",
";",
"}",
"case",
"'['",
":",
"{",
"++",
"inRangeDef",
";",
"break",
";",
"}",
"case",
"'\\\\['",
":",
"\\\\",
"break",
";",
"case",
"'\\\\]'",
":",
"\\\\",
"break",
";",
"case",
"']'",
":",
"{",
"--",
"inRangeDef",
";",
"break",
";",
"}",
"case",
"'(?:'",
":",
"}",
"}",
"case",
"'(?>'",
":",
"}"
] |
create mapping table for the fieldNames to capture
|
[
"create",
"mapping",
"table",
"for",
"the",
"fieldNames",
"to",
"capture"
] |
f427727fb4d9ebb56b56f5c795837dc943c545ae
|
https://github.com/Beh01der/node-grok/blob/f427727fb4d9ebb56b56f5c795837dc943c545ae/lib/index.js#L111-L136
|
train
|
rasmusbe/wp-pot
|
index.js
|
setDefaultOptions
|
function setDefaultOptions (options) {
const defaultOptions = {
src: '**/*.php',
globOpts: {},
destFile: 'translations.pot',
commentKeyword: 'translators:',
headers: {
'X-Poedit-Basepath': '..',
'X-Poedit-SourceCharset': 'UTF-8',
'X-Poedit-SearchPath-0': '.',
'X-Poedit-SearchPathExcluded-0': '*.js'
},
defaultHeaders: true,
noFilePaths: false,
writeFile: true,
gettextFunctions: [
{ name: '__' },
{ name: '_e' },
{ name: '_ex', context: 2 },
{ name: '_n', plural: 2 },
{ name: '_n_noop', plural: 2 },
{ name: '_nx', plural: 2, context: 4 },
{ name: '_nx_noop', plural: 2, context: 3 },
{ name: '_x', context: 2 },
{ name: 'esc_attr__' },
{ name: 'esc_attr_e' },
{ name: 'esc_attr_x', context: 2 },
{ name: 'esc_html__' },
{ name: 'esc_html_e' },
{ name: 'esc_html_x', context: 2 }
]
};
if (options.headers === false) {
options.defaultHeaders = false;
}
options = Object.assign({}, defaultOptions, options);
if (!options.package) {
options.package = options.domain || 'unnamed project';
}
const functionCalls = {
valid: [],
contextPosition: {},
pluralPosition: {}
};
options.gettextFunctions.forEach(function (methodObject) {
functionCalls.valid.push(methodObject.name);
if (methodObject.plural) {
functionCalls.pluralPosition[ methodObject.name ] = methodObject.plural;
}
if (methodObject.context) {
functionCalls.contextPosition[ methodObject.name ] = methodObject.context;
}
});
options.functionCalls = functionCalls;
return options;
}
|
javascript
|
function setDefaultOptions (options) {
const defaultOptions = {
src: '**/*.php',
globOpts: {},
destFile: 'translations.pot',
commentKeyword: 'translators:',
headers: {
'X-Poedit-Basepath': '..',
'X-Poedit-SourceCharset': 'UTF-8',
'X-Poedit-SearchPath-0': '.',
'X-Poedit-SearchPathExcluded-0': '*.js'
},
defaultHeaders: true,
noFilePaths: false,
writeFile: true,
gettextFunctions: [
{ name: '__' },
{ name: '_e' },
{ name: '_ex', context: 2 },
{ name: '_n', plural: 2 },
{ name: '_n_noop', plural: 2 },
{ name: '_nx', plural: 2, context: 4 },
{ name: '_nx_noop', plural: 2, context: 3 },
{ name: '_x', context: 2 },
{ name: 'esc_attr__' },
{ name: 'esc_attr_e' },
{ name: 'esc_attr_x', context: 2 },
{ name: 'esc_html__' },
{ name: 'esc_html_e' },
{ name: 'esc_html_x', context: 2 }
]
};
if (options.headers === false) {
options.defaultHeaders = false;
}
options = Object.assign({}, defaultOptions, options);
if (!options.package) {
options.package = options.domain || 'unnamed project';
}
const functionCalls = {
valid: [],
contextPosition: {},
pluralPosition: {}
};
options.gettextFunctions.forEach(function (methodObject) {
functionCalls.valid.push(methodObject.name);
if (methodObject.plural) {
functionCalls.pluralPosition[ methodObject.name ] = methodObject.plural;
}
if (methodObject.context) {
functionCalls.contextPosition[ methodObject.name ] = methodObject.context;
}
});
options.functionCalls = functionCalls;
return options;
}
|
[
"function",
"setDefaultOptions",
"(",
"options",
")",
"{",
"const",
"defaultOptions",
"=",
"{",
"src",
":",
"'**/*.php'",
",",
"globOpts",
":",
"{",
"}",
",",
"destFile",
":",
"'translations.pot'",
",",
"commentKeyword",
":",
"'translators:'",
",",
"headers",
":",
"{",
"'X-Poedit-Basepath'",
":",
"'..'",
",",
"'X-Poedit-SourceCharset'",
":",
"'UTF-8'",
",",
"'X-Poedit-SearchPath-0'",
":",
"'.'",
",",
"'X-Poedit-SearchPathExcluded-0'",
":",
"'*.js'",
"}",
",",
"defaultHeaders",
":",
"true",
",",
"noFilePaths",
":",
"false",
",",
"writeFile",
":",
"true",
",",
"gettextFunctions",
":",
"[",
"{",
"name",
":",
"'__'",
"}",
",",
"{",
"name",
":",
"'_e'",
"}",
",",
"{",
"name",
":",
"'_ex'",
",",
"context",
":",
"2",
"}",
",",
"{",
"name",
":",
"'_n'",
",",
"plural",
":",
"2",
"}",
",",
"{",
"name",
":",
"'_n_noop'",
",",
"plural",
":",
"2",
"}",
",",
"{",
"name",
":",
"'_nx'",
",",
"plural",
":",
"2",
",",
"context",
":",
"4",
"}",
",",
"{",
"name",
":",
"'_nx_noop'",
",",
"plural",
":",
"2",
",",
"context",
":",
"3",
"}",
",",
"{",
"name",
":",
"'_x'",
",",
"context",
":",
"2",
"}",
",",
"{",
"name",
":",
"'esc_attr__'",
"}",
",",
"{",
"name",
":",
"'esc_attr_e'",
"}",
",",
"{",
"name",
":",
"'esc_attr_x'",
",",
"context",
":",
"2",
"}",
",",
"{",
"name",
":",
"'esc_html__'",
"}",
",",
"{",
"name",
":",
"'esc_html_e'",
"}",
",",
"{",
"name",
":",
"'esc_html_x'",
",",
"context",
":",
"2",
"}",
"]",
"}",
";",
"if",
"(",
"options",
".",
"headers",
"===",
"false",
")",
"{",
"options",
".",
"defaultHeaders",
"=",
"false",
";",
"}",
"options",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"defaultOptions",
",",
"options",
")",
";",
"if",
"(",
"!",
"options",
".",
"package",
")",
"{",
"options",
".",
"package",
"=",
"options",
".",
"domain",
"||",
"'unnamed project'",
";",
"}",
"const",
"functionCalls",
"=",
"{",
"valid",
":",
"[",
"]",
",",
"contextPosition",
":",
"{",
"}",
",",
"pluralPosition",
":",
"{",
"}",
"}",
";",
"options",
".",
"gettextFunctions",
".",
"forEach",
"(",
"function",
"(",
"methodObject",
")",
"{",
"functionCalls",
".",
"valid",
".",
"push",
"(",
"methodObject",
".",
"name",
")",
";",
"if",
"(",
"methodObject",
".",
"plural",
")",
"{",
"functionCalls",
".",
"pluralPosition",
"[",
"methodObject",
".",
"name",
"]",
"=",
"methodObject",
".",
"plural",
";",
"}",
"if",
"(",
"methodObject",
".",
"context",
")",
"{",
"functionCalls",
".",
"contextPosition",
"[",
"methodObject",
".",
"name",
"]",
"=",
"methodObject",
".",
"context",
";",
"}",
"}",
")",
";",
"options",
".",
"functionCalls",
"=",
"functionCalls",
";",
"return",
"options",
";",
"}"
] |
Set default options
@param {object} options
@return {object}
|
[
"Set",
"default",
"options"
] |
84d7779978196be08628ce716a8b189bc31b6469
|
https://github.com/rasmusbe/wp-pot/blob/84d7779978196be08628ce716a8b189bc31b6469/index.js#L18-L81
|
train
|
rasmusbe/wp-pot
|
index.js
|
keywordsListStrings
|
function keywordsListStrings (gettextFunctions) {
const methodStrings = [];
for (const getTextFunction of gettextFunctions) {
let methodString = getTextFunction.name;
if (getTextFunction.plural || getTextFunction.context) {
methodString += ':1';
}
if (getTextFunction.plural) {
methodString += `,${getTextFunction.plural}`;
}
if (getTextFunction.context) {
methodString += `,${getTextFunction.context}c`;
}
methodStrings.push(methodString);
}
return methodStrings;
}
|
javascript
|
function keywordsListStrings (gettextFunctions) {
const methodStrings = [];
for (const getTextFunction of gettextFunctions) {
let methodString = getTextFunction.name;
if (getTextFunction.plural || getTextFunction.context) {
methodString += ':1';
}
if (getTextFunction.plural) {
methodString += `,${getTextFunction.plural}`;
}
if (getTextFunction.context) {
methodString += `,${getTextFunction.context}c`;
}
methodStrings.push(methodString);
}
return methodStrings;
}
|
[
"function",
"keywordsListStrings",
"(",
"gettextFunctions",
")",
"{",
"const",
"methodStrings",
"=",
"[",
"]",
";",
"for",
"(",
"const",
"getTextFunction",
"of",
"gettextFunctions",
")",
"{",
"let",
"methodString",
"=",
"getTextFunction",
".",
"name",
";",
"if",
"(",
"getTextFunction",
".",
"plural",
"||",
"getTextFunction",
".",
"context",
")",
"{",
"methodString",
"+=",
"':1'",
";",
"}",
"if",
"(",
"getTextFunction",
".",
"plural",
")",
"{",
"methodString",
"+=",
"`",
"${",
"getTextFunction",
".",
"plural",
"}",
"`",
";",
"}",
"if",
"(",
"getTextFunction",
".",
"context",
")",
"{",
"methodString",
"+=",
"`",
"${",
"getTextFunction",
".",
"context",
"}",
"`",
";",
"}",
"methodStrings",
".",
"push",
"(",
"methodString",
")",
";",
"}",
"return",
"methodStrings",
";",
"}"
] |
Generate string for header from gettext function
@param {object} gettextFunctions
@return {Array}
|
[
"Generate",
"string",
"for",
"header",
"from",
"gettext",
"function"
] |
84d7779978196be08628ce716a8b189bc31b6469
|
https://github.com/rasmusbe/wp-pot/blob/84d7779978196be08628ce716a8b189bc31b6469/index.js#L90-L110
|
train
|
sethwebster/ember-cli-new-version
|
index.js
|
function(app/*, parentAddon*/) {
this._super.included.apply(this, arguments);
this._options = app.options.newVersion || {};
if (this._options.enabled === true) {
this._options.fileName = this._options.fileName || 'VERSION.txt';
this._options.prepend = this._options.prepend || '';
this._options.useAppVersion = this._options.useAppVersion || false;
}
}
|
javascript
|
function(app/*, parentAddon*/) {
this._super.included.apply(this, arguments);
this._options = app.options.newVersion || {};
if (this._options.enabled === true) {
this._options.fileName = this._options.fileName || 'VERSION.txt';
this._options.prepend = this._options.prepend || '';
this._options.useAppVersion = this._options.useAppVersion || false;
}
}
|
[
"function",
"(",
"app",
")",
"{",
"this",
".",
"_super",
".",
"included",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"this",
".",
"_options",
"=",
"app",
".",
"options",
".",
"newVersion",
"||",
"{",
"}",
";",
"if",
"(",
"this",
".",
"_options",
".",
"enabled",
"===",
"true",
")",
"{",
"this",
".",
"_options",
".",
"fileName",
"=",
"this",
".",
"_options",
".",
"fileName",
"||",
"'VERSION.txt'",
";",
"this",
".",
"_options",
".",
"prepend",
"=",
"this",
".",
"_options",
".",
"prepend",
"||",
"''",
";",
"this",
".",
"_options",
".",
"useAppVersion",
"=",
"this",
".",
"_options",
".",
"useAppVersion",
"||",
"false",
";",
"}",
"}"
] |
Store `ember-cli-build.js` options
|
[
"Store",
"ember",
"-",
"cli",
"-",
"build",
".",
"js",
"options"
] |
c1ce9cfda5757f8d198356bc8a9166b639df1696
|
https://github.com/sethwebster/ember-cli-new-version/blob/c1ce9cfda5757f8d198356bc8a9166b639df1696/index.js#L12-L21
|
train
|
|
sethwebster/ember-cli-new-version
|
index.js
|
function() {
let detectedVersion;
if (this._options.useAppVersion && this._appVersion) {
detectedVersion = this._appVersion;
}
if (!detectedVersion) {
detectedVersion = this.parent.pkg.version;
}
if (detectedVersion && this._options.enabled) {
const fileName = this._options.fileName;
this.ui.writeLine(`Created ${fileName} with ${detectedVersion}`);
return writeFile(fileName, detectedVersion);
}
}
|
javascript
|
function() {
let detectedVersion;
if (this._options.useAppVersion && this._appVersion) {
detectedVersion = this._appVersion;
}
if (!detectedVersion) {
detectedVersion = this.parent.pkg.version;
}
if (detectedVersion && this._options.enabled) {
const fileName = this._options.fileName;
this.ui.writeLine(`Created ${fileName} with ${detectedVersion}`);
return writeFile(fileName, detectedVersion);
}
}
|
[
"function",
"(",
")",
"{",
"let",
"detectedVersion",
";",
"if",
"(",
"this",
".",
"_options",
".",
"useAppVersion",
"&&",
"this",
".",
"_appVersion",
")",
"{",
"detectedVersion",
"=",
"this",
".",
"_appVersion",
";",
"}",
"if",
"(",
"!",
"detectedVersion",
")",
"{",
"detectedVersion",
"=",
"this",
".",
"parent",
".",
"pkg",
".",
"version",
";",
"}",
"if",
"(",
"detectedVersion",
"&&",
"this",
".",
"_options",
".",
"enabled",
")",
"{",
"const",
"fileName",
"=",
"this",
".",
"_options",
".",
"fileName",
";",
"this",
".",
"ui",
".",
"writeLine",
"(",
"`",
"${",
"fileName",
"}",
"${",
"detectedVersion",
"}",
"`",
")",
";",
"return",
"writeFile",
"(",
"fileName",
",",
"detectedVersion",
")",
";",
"}",
"}"
] |
Write version file
based on
- ember-cli-app-version if installed
- package.json of consuming application or
|
[
"Write",
"version",
"file"
] |
c1ce9cfda5757f8d198356bc8a9166b639df1696
|
https://github.com/sethwebster/ember-cli-new-version/blob/c1ce9cfda5757f8d198356bc8a9166b639df1696/index.js#L37-L54
|
train
|
|
ynab/ynab-sdk-js
|
dist/esm/api.js
|
function (budget_id, data, options) {
var localVarFetchArgs = TransactionsApiFetchParamCreator(configuration).createTransaction(budget_id, data, options);
return function (fetchFunction) {
if (fetchFunction === void 0) { fetchFunction = fetch; }
return fetchFunction(configuration.basePath + localVarFetchArgs.url, localVarFetchArgs.options).then(function (response) {
if (response.status >= 200 && response.status < 300) {
return response.json();
}
else {
return response.json().then(function (e) {
return Promise.reject(e);
});
}
});
};
}
|
javascript
|
function (budget_id, data, options) {
var localVarFetchArgs = TransactionsApiFetchParamCreator(configuration).createTransaction(budget_id, data, options);
return function (fetchFunction) {
if (fetchFunction === void 0) { fetchFunction = fetch; }
return fetchFunction(configuration.basePath + localVarFetchArgs.url, localVarFetchArgs.options).then(function (response) {
if (response.status >= 200 && response.status < 300) {
return response.json();
}
else {
return response.json().then(function (e) {
return Promise.reject(e);
});
}
});
};
}
|
[
"function",
"(",
"budget_id",
",",
"data",
",",
"options",
")",
"{",
"var",
"localVarFetchArgs",
"=",
"TransactionsApiFetchParamCreator",
"(",
"configuration",
")",
".",
"createTransaction",
"(",
"budget_id",
",",
"data",
",",
"options",
")",
";",
"return",
"function",
"(",
"fetchFunction",
")",
"{",
"if",
"(",
"fetchFunction",
"===",
"void",
"0",
")",
"{",
"fetchFunction",
"=",
"fetch",
";",
"}",
"return",
"fetchFunction",
"(",
"configuration",
".",
"basePath",
"+",
"localVarFetchArgs",
".",
"url",
",",
"localVarFetchArgs",
".",
"options",
")",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"if",
"(",
"response",
".",
"status",
">=",
"200",
"&&",
"response",
".",
"status",
"<",
"300",
")",
"{",
"return",
"response",
".",
"json",
"(",
")",
";",
"}",
"else",
"{",
"return",
"response",
".",
"json",
"(",
")",
".",
"then",
"(",
"function",
"(",
"e",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"e",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"}"
] |
Creates a single transaction or multiple transactions. If you provide a body containing a 'transaction' object, a single transaction will be created and if you provide a body containing a 'transactions' array, multiple transactions will be created.
@summary Create a single transaction or multiple transactions
@param {string} budget_id - The id of the budget (\"last-used\" can also be used to specify the last used budget)
@param {SaveTransactionsWrapper} data - The transaction or transactions to create. To create a single transaction you can specify a value for the 'transaction' object and to create multiple transactions you can specify an array of 'transactions'. It is expected that you will only provide a value for one of these objects.
@param {*} [options] - Override http request options.
@throws {RequiredError}
|
[
"Creates",
"a",
"single",
"transaction",
"or",
"multiple",
"transactions",
".",
"If",
"you",
"provide",
"a",
"body",
"containing",
"a",
"transaction",
"object",
"a",
"single",
"transaction",
"will",
"be",
"created",
"and",
"if",
"you",
"provide",
"a",
"body",
"containing",
"a",
"transactions",
"array",
"multiple",
"transactions",
"will",
"be",
"created",
"."
] |
2f1d9ec766e526ffd14c543ca2b3b3244782a878
|
https://github.com/ynab/ynab-sdk-js/blob/2f1d9ec766e526ffd14c543ca2b3b3244782a878/dist/esm/api.js#L2683-L2698
|
train
|
|
ynab/ynab-sdk-js
|
dist/esm/api.js
|
function (budget_id, account_id, since_date, type, last_knowledge_of_server, options) {
return TransactionsApiFp(configuration).getTransactionsByAccount(budget_id, account_id, since_date, type, last_knowledge_of_server, options)();
}
|
javascript
|
function (budget_id, account_id, since_date, type, last_knowledge_of_server, options) {
return TransactionsApiFp(configuration).getTransactionsByAccount(budget_id, account_id, since_date, type, last_knowledge_of_server, options)();
}
|
[
"function",
"(",
"budget_id",
",",
"account_id",
",",
"since_date",
",",
"type",
",",
"last_knowledge_of_server",
",",
"options",
")",
"{",
"return",
"TransactionsApiFp",
"(",
"configuration",
")",
".",
"getTransactionsByAccount",
"(",
"budget_id",
",",
"account_id",
",",
"since_date",
",",
"type",
",",
"last_knowledge_of_server",
",",
"options",
")",
"(",
")",
";",
"}"
] |
Returns all transactions for a specified account
@summary List account transactions
@param {string} budget_id - The id of the budget (\"last-used\" can also be used to specify the last used budget)
@param {string} account_id - The id of the account
@param {Date} [since_date] - If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30).
@param {'uncategorized' | 'unapproved'} [type] - If specified, only transactions of the specified type will be included. 'uncategorized' and 'unapproved' are currently supported.
@param {number} [last_knowledge_of_server] - The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included.
@param {*} [options] - Override http request options.
@throws {RequiredError}
|
[
"Returns",
"all",
"transactions",
"for",
"a",
"specified",
"account"
] |
2f1d9ec766e526ffd14c543ca2b3b3244782a878
|
https://github.com/ynab/ynab-sdk-js/blob/2f1d9ec766e526ffd14c543ca2b3b3244782a878/dist/esm/api.js#L2933-L2935
|
train
|
|
ynab/ynab-sdk-js
|
dist/esm/api.js
|
function (budget_id, category_id, since_date, type, last_knowledge_of_server, options) {
return TransactionsApiFp(configuration).getTransactionsByCategory(budget_id, category_id, since_date, type, last_knowledge_of_server, options)();
}
|
javascript
|
function (budget_id, category_id, since_date, type, last_knowledge_of_server, options) {
return TransactionsApiFp(configuration).getTransactionsByCategory(budget_id, category_id, since_date, type, last_knowledge_of_server, options)();
}
|
[
"function",
"(",
"budget_id",
",",
"category_id",
",",
"since_date",
",",
"type",
",",
"last_knowledge_of_server",
",",
"options",
")",
"{",
"return",
"TransactionsApiFp",
"(",
"configuration",
")",
".",
"getTransactionsByCategory",
"(",
"budget_id",
",",
"category_id",
",",
"since_date",
",",
"type",
",",
"last_knowledge_of_server",
",",
"options",
")",
"(",
")",
";",
"}"
] |
Returns all transactions for a specified category
@summary List category transactions
@param {string} budget_id - The id of the budget (\"last-used\" can also be used to specify the last used budget)
@param {string} category_id - The id of the category
@param {Date} [since_date] - If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30).
@param {'uncategorized' | 'unapproved'} [type] - If specified, only transactions of the specified type will be included. 'uncategorized' and 'unapproved' are currently supported.
@param {number} [last_knowledge_of_server] - The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included.
@param {*} [options] - Override http request options.
@throws {RequiredError}
|
[
"Returns",
"all",
"transactions",
"for",
"a",
"specified",
"category"
] |
2f1d9ec766e526ffd14c543ca2b3b3244782a878
|
https://github.com/ynab/ynab-sdk-js/blob/2f1d9ec766e526ffd14c543ca2b3b3244782a878/dist/esm/api.js#L2947-L2949
|
train
|
|
ARMmbed/mbed-cloud-sdk-javascript
|
gulpfile.js
|
bundle
|
function bundle(srcFiles, destDir, optionsFn) {
return gulp.src(srcFiles, {
read: false
})
.pipe(tap(function(file) {
var options = {};
if (optionsFn) options = optionsFn(file);
var fileName = options.fileName || path.basename(file.path);
if (options.standalone)
console.log(`Creating ${options.standalone} in ${destDir}/${fileName}`);
else
console.log(`Creating ${destDir}/${fileName}`);
file.contents = browserify(file.path, options)
.ignore("buffer")
.ignore("dotenv")
.bundle()
.on("error", function (err) {
console.log(err);
});
file.path = path.join(file.base, fileName);
}))
.pipe(buffer())
.pipe(sourcemaps.init({
loadMaps: true
}))
.pipe(uglify({
preserveComments: function(node, comment) {
return comment.value.includes("Copyright Arm");
}
}))
.pipe(sourcemaps.write(".", {
sourceRoot: path.relative(destDir, nodeDir)
}))
.pipe(gulp.dest(destDir));
}
|
javascript
|
function bundle(srcFiles, destDir, optionsFn) {
return gulp.src(srcFiles, {
read: false
})
.pipe(tap(function(file) {
var options = {};
if (optionsFn) options = optionsFn(file);
var fileName = options.fileName || path.basename(file.path);
if (options.standalone)
console.log(`Creating ${options.standalone} in ${destDir}/${fileName}`);
else
console.log(`Creating ${destDir}/${fileName}`);
file.contents = browserify(file.path, options)
.ignore("buffer")
.ignore("dotenv")
.bundle()
.on("error", function (err) {
console.log(err);
});
file.path = path.join(file.base, fileName);
}))
.pipe(buffer())
.pipe(sourcemaps.init({
loadMaps: true
}))
.pipe(uglify({
preserveComments: function(node, comment) {
return comment.value.includes("Copyright Arm");
}
}))
.pipe(sourcemaps.write(".", {
sourceRoot: path.relative(destDir, nodeDir)
}))
.pipe(gulp.dest(destDir));
}
|
[
"function",
"bundle",
"(",
"srcFiles",
",",
"destDir",
",",
"optionsFn",
")",
"{",
"return",
"gulp",
".",
"src",
"(",
"srcFiles",
",",
"{",
"read",
":",
"false",
"}",
")",
".",
"pipe",
"(",
"tap",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"options",
"=",
"{",
"}",
";",
"if",
"(",
"optionsFn",
")",
"options",
"=",
"optionsFn",
"(",
"file",
")",
";",
"var",
"fileName",
"=",
"options",
".",
"fileName",
"||",
"path",
".",
"basename",
"(",
"file",
".",
"path",
")",
";",
"if",
"(",
"options",
".",
"standalone",
")",
"console",
".",
"log",
"(",
"`",
"${",
"options",
".",
"standalone",
"}",
"${",
"destDir",
"}",
"${",
"fileName",
"}",
"`",
")",
";",
"else",
"console",
".",
"log",
"(",
"`",
"${",
"destDir",
"}",
"${",
"fileName",
"}",
"`",
")",
";",
"file",
".",
"contents",
"=",
"browserify",
"(",
"file",
".",
"path",
",",
"options",
")",
".",
"ignore",
"(",
"\"buffer\"",
")",
".",
"ignore",
"(",
"\"dotenv\"",
")",
".",
"bundle",
"(",
")",
".",
"on",
"(",
"\"error\"",
",",
"function",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"err",
")",
";",
"}",
")",
";",
"file",
".",
"path",
"=",
"path",
".",
"join",
"(",
"file",
".",
"base",
",",
"fileName",
")",
";",
"}",
")",
")",
".",
"pipe",
"(",
"buffer",
"(",
")",
")",
".",
"pipe",
"(",
"sourcemaps",
".",
"init",
"(",
"{",
"loadMaps",
":",
"true",
"}",
")",
")",
".",
"pipe",
"(",
"uglify",
"(",
"{",
"preserveComments",
":",
"function",
"(",
"node",
",",
"comment",
")",
"{",
"return",
"comment",
".",
"value",
".",
"includes",
"(",
"\"Copyright Arm\"",
")",
";",
"}",
"}",
")",
")",
".",
"pipe",
"(",
"sourcemaps",
".",
"write",
"(",
"\".\"",
",",
"{",
"sourceRoot",
":",
"path",
".",
"relative",
"(",
"destDir",
",",
"nodeDir",
")",
"}",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"destDir",
")",
")",
";",
"}"
] |
Browserify helper function
|
[
"Browserify",
"helper",
"function"
] |
4db65166edca0b768c89cc6fb22be0582e5aeee1
|
https://github.com/ARMmbed/mbed-cloud-sdk-javascript/blob/4db65166edca0b768c89cc6fb22be0582e5aeee1/gulpfile.js#L22-L58
|
train
|
ARMmbed/mbed-cloud-sdk-javascript
|
examples/node/webhook-subscriptions.js
|
subscribe
|
function subscribe() {
// starts to receive values after device regsiters
connect.subscribe.resourceValues({ resourcePaths: ["/3200/0/5501"] })
.addListener((res) => logData(res, "OnRegistration"))
.addLocalFilter(res => res.payload >= 20);
// starts to reveive values immediatley
connect.subscribe.resourceValues({ resourcePaths: ["/3200/0/5501"] }, "OnValueUpdate")
.addListener((res) => logData(res, "OnValueUpdate"));
}
|
javascript
|
function subscribe() {
// starts to receive values after device regsiters
connect.subscribe.resourceValues({ resourcePaths: ["/3200/0/5501"] })
.addListener((res) => logData(res, "OnRegistration"))
.addLocalFilter(res => res.payload >= 20);
// starts to reveive values immediatley
connect.subscribe.resourceValues({ resourcePaths: ["/3200/0/5501"] }, "OnValueUpdate")
.addListener((res) => logData(res, "OnValueUpdate"));
}
|
[
"function",
"subscribe",
"(",
")",
"{",
"connect",
".",
"subscribe",
".",
"resourceValues",
"(",
"{",
"resourcePaths",
":",
"[",
"\"/3200/0/5501\"",
"]",
"}",
")",
".",
"addListener",
"(",
"(",
"res",
")",
"=>",
"logData",
"(",
"res",
",",
"\"OnRegistration\"",
")",
")",
".",
"addLocalFilter",
"(",
"res",
"=>",
"res",
".",
"payload",
">=",
"20",
")",
";",
"connect",
".",
"subscribe",
".",
"resourceValues",
"(",
"{",
"resourcePaths",
":",
"[",
"\"/3200/0/5501\"",
"]",
"}",
",",
"\"OnValueUpdate\"",
")",
".",
"addListener",
"(",
"(",
"res",
")",
"=>",
"logData",
"(",
"res",
",",
"\"OnValueUpdate\"",
")",
")",
";",
"}"
] |
subscribe to the button resource
|
[
"subscribe",
"to",
"the",
"button",
"resource"
] |
4db65166edca0b768c89cc6fb22be0582e5aeee1
|
https://github.com/ARMmbed/mbed-cloud-sdk-javascript/blob/4db65166edca0b768c89cc6fb22be0582e5aeee1/examples/node/webhook-subscriptions.js#L43-L52
|
train
|
ARMmbed/mbed-cloud-sdk-javascript
|
examples/node/config.js
|
parseCommandLine
|
function parseCommandLine() {
var commands = process.argv.slice(2);
var args = {};
for (var i = 0; i < commands.length; i++) {
var match = commands[i].match(/^--(.+)=(.+)$/);
if (match)
args[match[1]] = match[2];
else if (i < commands.length - 1 && commands[i].substr(0, 1) === "-") {
args[commands[i].substr(1)] = commands[i + 1];
i++;
}
else if (i === 0) args[commandKey] = commands[i];
else if (i === 1) args[commandHost] = commands[i];
}
return args;
}
|
javascript
|
function parseCommandLine() {
var commands = process.argv.slice(2);
var args = {};
for (var i = 0; i < commands.length; i++) {
var match = commands[i].match(/^--(.+)=(.+)$/);
if (match)
args[match[1]] = match[2];
else if (i < commands.length - 1 && commands[i].substr(0, 1) === "-") {
args[commands[i].substr(1)] = commands[i + 1];
i++;
}
else if (i === 0) args[commandKey] = commands[i];
else if (i === 1) args[commandHost] = commands[i];
}
return args;
}
|
[
"function",
"parseCommandLine",
"(",
")",
"{",
"var",
"commands",
"=",
"process",
".",
"argv",
".",
"slice",
"(",
"2",
")",
";",
"var",
"args",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"commands",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"match",
"=",
"commands",
"[",
"i",
"]",
".",
"match",
"(",
"/",
"^--(.+)=(.+)$",
"/",
")",
";",
"if",
"(",
"match",
")",
"args",
"[",
"match",
"[",
"1",
"]",
"]",
"=",
"match",
"[",
"2",
"]",
";",
"else",
"if",
"(",
"i",
"<",
"commands",
".",
"length",
"-",
"1",
"&&",
"commands",
"[",
"i",
"]",
".",
"substr",
"(",
"0",
",",
"1",
")",
"===",
"\"-\"",
")",
"{",
"args",
"[",
"commands",
"[",
"i",
"]",
".",
"substr",
"(",
"1",
")",
"]",
"=",
"commands",
"[",
"i",
"+",
"1",
"]",
";",
"i",
"++",
";",
"}",
"else",
"if",
"(",
"i",
"===",
"0",
")",
"args",
"[",
"commandKey",
"]",
"=",
"commands",
"[",
"i",
"]",
";",
"else",
"if",
"(",
"i",
"===",
"1",
")",
"args",
"[",
"commandHost",
"]",
"=",
"commands",
"[",
"i",
"]",
";",
"}",
"return",
"args",
";",
"}"
] |
Parse command line arguments
|
[
"Parse",
"command",
"line",
"arguments"
] |
4db65166edca0b768c89cc6fb22be0582e5aeee1
|
https://github.com/ARMmbed/mbed-cloud-sdk-javascript/blob/4db65166edca0b768c89cc6fb22be0582e5aeee1/examples/node/config.js#L24-L41
|
train
|
ARMmbed/mbed-cloud-sdk-javascript
|
examples/node/certificate-header.js
|
checkCertificate
|
function checkCertificate() {
return certificates.listCertificates({
filter: {
type: "developer"
}
})
.then(certs => {
var certificate = certs.data.find(cert => {
return cert.name === certificateName;
});
if (certificate) {
return new Promise((resolve, reject) => {
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Developer certificate already exists, overwrite? [y/N] ", answer => {
rl.close();
if (answer === "y") {
return certificate.delete()
.then(() => {
resolve();
});
} else {
reject();
}
});
});
}
});
}
|
javascript
|
function checkCertificate() {
return certificates.listCertificates({
filter: {
type: "developer"
}
})
.then(certs => {
var certificate = certs.data.find(cert => {
return cert.name === certificateName;
});
if (certificate) {
return new Promise((resolve, reject) => {
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Developer certificate already exists, overwrite? [y/N] ", answer => {
rl.close();
if (answer === "y") {
return certificate.delete()
.then(() => {
resolve();
});
} else {
reject();
}
});
});
}
});
}
|
[
"function",
"checkCertificate",
"(",
")",
"{",
"return",
"certificates",
".",
"listCertificates",
"(",
"{",
"filter",
":",
"{",
"type",
":",
"\"developer\"",
"}",
"}",
")",
".",
"then",
"(",
"certs",
"=>",
"{",
"var",
"certificate",
"=",
"certs",
".",
"data",
".",
"find",
"(",
"cert",
"=>",
"{",
"return",
"cert",
".",
"name",
"===",
"certificateName",
";",
"}",
")",
";",
"if",
"(",
"certificate",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"var",
"rl",
"=",
"readline",
".",
"createInterface",
"(",
"{",
"input",
":",
"process",
".",
"stdin",
",",
"output",
":",
"process",
".",
"stdout",
"}",
")",
";",
"rl",
".",
"question",
"(",
"\"Developer certificate already exists, overwrite? [y/N] \"",
",",
"answer",
"=>",
"{",
"rl",
".",
"close",
"(",
")",
";",
"if",
"(",
"answer",
"===",
"\"y\"",
")",
"{",
"return",
"certificate",
".",
"delete",
"(",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"reject",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Check for existing certificate with the same name
|
[
"Check",
"for",
"existing",
"certificate",
"with",
"the",
"same",
"name"
] |
4db65166edca0b768c89cc6fb22be0582e5aeee1
|
https://github.com/ARMmbed/mbed-cloud-sdk-javascript/blob/4db65166edca0b768c89cc6fb22be0582e5aeee1/examples/node/certificate-header.js#L31-L63
|
train
|
blueberryapps/react-svg-icon-generator
|
src/helpers/svgoBrowser.js
|
extendConfig
|
function extendConfig(defaults, config) {
var key;
// plugins
if (config.plugins) {
config.plugins.forEach(function(item) {
// {}
if (typeof item === 'object') {
key = Object.keys(item)[0];
// custom
if (typeof item[key] === 'object' && item[key].fn && typeof item[key].fn === 'function') {
defaults.plugins.push(setupCustomPlugin(key, item[key]));
} else {
defaults.plugins.forEach(function(plugin) {
if (plugin.name === key) {
// name: {}
if (typeof item[key] === 'object') {
plugin.params = EXTEND({}, plugin.params || {}, item[key]);
plugin.active = true;
// name: false
} else if (item[key] === false) {
plugin.active = false;
// name: true
} else if (item[key] === true) {
plugin.active = true;
}
}
});
}
}
});
}
defaults.multipass = config.multipass;
// svg2js
if (config.svg2js) {
defaults.svg2js = config.svg2js;
}
// js2svg
if (config.js2svg) {
defaults.js2svg = config.js2svg;
}
return defaults;
}
|
javascript
|
function extendConfig(defaults, config) {
var key;
// plugins
if (config.plugins) {
config.plugins.forEach(function(item) {
// {}
if (typeof item === 'object') {
key = Object.keys(item)[0];
// custom
if (typeof item[key] === 'object' && item[key].fn && typeof item[key].fn === 'function') {
defaults.plugins.push(setupCustomPlugin(key, item[key]));
} else {
defaults.plugins.forEach(function(plugin) {
if (plugin.name === key) {
// name: {}
if (typeof item[key] === 'object') {
plugin.params = EXTEND({}, plugin.params || {}, item[key]);
plugin.active = true;
// name: false
} else if (item[key] === false) {
plugin.active = false;
// name: true
} else if (item[key] === true) {
plugin.active = true;
}
}
});
}
}
});
}
defaults.multipass = config.multipass;
// svg2js
if (config.svg2js) {
defaults.svg2js = config.svg2js;
}
// js2svg
if (config.js2svg) {
defaults.js2svg = config.js2svg;
}
return defaults;
}
|
[
"function",
"extendConfig",
"(",
"defaults",
",",
"config",
")",
"{",
"var",
"key",
";",
"if",
"(",
"config",
".",
"plugins",
")",
"{",
"config",
".",
"plugins",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"if",
"(",
"typeof",
"item",
"===",
"'object'",
")",
"{",
"key",
"=",
"Object",
".",
"keys",
"(",
"item",
")",
"[",
"0",
"]",
";",
"if",
"(",
"typeof",
"item",
"[",
"key",
"]",
"===",
"'object'",
"&&",
"item",
"[",
"key",
"]",
".",
"fn",
"&&",
"typeof",
"item",
"[",
"key",
"]",
".",
"fn",
"===",
"'function'",
")",
"{",
"defaults",
".",
"plugins",
".",
"push",
"(",
"setupCustomPlugin",
"(",
"key",
",",
"item",
"[",
"key",
"]",
")",
")",
";",
"}",
"else",
"{",
"defaults",
".",
"plugins",
".",
"forEach",
"(",
"function",
"(",
"plugin",
")",
"{",
"if",
"(",
"plugin",
".",
"name",
"===",
"key",
")",
"{",
"if",
"(",
"typeof",
"item",
"[",
"key",
"]",
"===",
"'object'",
")",
"{",
"plugin",
".",
"params",
"=",
"EXTEND",
"(",
"{",
"}",
",",
"plugin",
".",
"params",
"||",
"{",
"}",
",",
"item",
"[",
"key",
"]",
")",
";",
"plugin",
".",
"active",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"item",
"[",
"key",
"]",
"===",
"false",
")",
"{",
"plugin",
".",
"active",
"=",
"false",
";",
"}",
"else",
"if",
"(",
"item",
"[",
"key",
"]",
"===",
"true",
")",
"{",
"plugin",
".",
"active",
"=",
"true",
";",
"}",
"}",
"}",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"defaults",
".",
"multipass",
"=",
"config",
".",
"multipass",
";",
"if",
"(",
"config",
".",
"svg2js",
")",
"{",
"defaults",
".",
"svg2js",
"=",
"config",
".",
"svg2js",
";",
"}",
"if",
"(",
"config",
".",
"js2svg",
")",
"{",
"defaults",
".",
"js2svg",
"=",
"config",
".",
"js2svg",
";",
"}",
"return",
"defaults",
";",
"}"
] |
Extend plugins with the custom config object.
@param {Array} plugins input plugins
@param {Object} config config
@return {Array} output plugins
|
[
"Extend",
"plugins",
"with",
"the",
"custom",
"config",
"object",
"."
] |
f2fc99241027fa19fe3153f5f66eb9c5d9ad8fb2
|
https://github.com/blueberryapps/react-svg-icon-generator/blob/f2fc99241027fa19fe3153f5f66eb9c5d9ad8fb2/src/helpers/svgoBrowser.js#L171-L230
|
train
|
blueberryapps/react-svg-icon-generator
|
src/helpers/svgoBrowser.js
|
setupCustomPlugin
|
function setupCustomPlugin(name, plugin) {
plugin.active = true;
plugin.params = EXTEND({}, plugin.params || {});
plugin.name = name;
return plugin;
}
|
javascript
|
function setupCustomPlugin(name, plugin) {
plugin.active = true;
plugin.params = EXTEND({}, plugin.params || {});
plugin.name = name;
return plugin;
}
|
[
"function",
"setupCustomPlugin",
"(",
"name",
",",
"plugin",
")",
"{",
"plugin",
".",
"active",
"=",
"true",
";",
"plugin",
".",
"params",
"=",
"EXTEND",
"(",
"{",
"}",
",",
"plugin",
".",
"params",
"||",
"{",
"}",
")",
";",
"plugin",
".",
"name",
"=",
"name",
";",
"return",
"plugin",
";",
"}"
] |
Setup and enable a custom plugin
@param {String} plugin name
@param {Object} custom plugin
@return {Array} enabled plugin
|
[
"Setup",
"and",
"enable",
"a",
"custom",
"plugin"
] |
f2fc99241027fa19fe3153f5f66eb9c5d9ad8fb2
|
https://github.com/blueberryapps/react-svg-icon-generator/blob/f2fc99241027fa19fe3153f5f66eb9c5d9ad8fb2/src/helpers/svgoBrowser.js#L239-L245
|
train
|
blueberryapps/react-svg-icon-generator
|
src/helpers/svgoBrowser.js
|
optimizePluginsArray
|
function optimizePluginsArray(plugins) {
var prev;
return plugins.reduce(function(plugins, item) {
if (prev && item.type == prev[0].type) {
prev.push(item);
} else {
plugins.push(prev = [item]);
}
return plugins;
}, []);
}
|
javascript
|
function optimizePluginsArray(plugins) {
var prev;
return plugins.reduce(function(plugins, item) {
if (prev && item.type == prev[0].type) {
prev.push(item);
} else {
plugins.push(prev = [item]);
}
return plugins;
}, []);
}
|
[
"function",
"optimizePluginsArray",
"(",
"plugins",
")",
"{",
"var",
"prev",
";",
"return",
"plugins",
".",
"reduce",
"(",
"function",
"(",
"plugins",
",",
"item",
")",
"{",
"if",
"(",
"prev",
"&&",
"item",
".",
"type",
"==",
"prev",
"[",
"0",
"]",
".",
"type",
")",
"{",
"prev",
".",
"push",
"(",
"item",
")",
";",
"}",
"else",
"{",
"plugins",
".",
"push",
"(",
"prev",
"=",
"[",
"item",
"]",
")",
";",
"}",
"return",
"plugins",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] |
Try to group sequential elements of plugins array.
@param {Object} plugins input plugins
@return {Array} output plugins
|
[
"Try",
"to",
"group",
"sequential",
"elements",
"of",
"plugins",
"array",
"."
] |
f2fc99241027fa19fe3153f5f66eb9c5d9ad8fb2
|
https://github.com/blueberryapps/react-svg-icon-generator/blob/f2fc99241027fa19fe3153f5f66eb9c5d9ad8fb2/src/helpers/svgoBrowser.js#L253-L266
|
train
|
gentics/gentics-ui-core
|
gulpfile.js
|
buildDocsTasks
|
function buildDocsTasks() {
if(npmArgs.remain.indexOf('gentics-ui-core') === -1) {
return new Promise(gulp.series(
cleanDocsFolder,
copyDocsFiles,
copyJekyllConfig
));
}
return resolvePromiseDummy();
}
|
javascript
|
function buildDocsTasks() {
if(npmArgs.remain.indexOf('gentics-ui-core') === -1) {
return new Promise(gulp.series(
cleanDocsFolder,
copyDocsFiles,
copyJekyllConfig
));
}
return resolvePromiseDummy();
}
|
[
"function",
"buildDocsTasks",
"(",
")",
"{",
"if",
"(",
"npmArgs",
".",
"remain",
".",
"indexOf",
"(",
"'gentics-ui-core'",
")",
"===",
"-",
"1",
")",
"{",
"return",
"new",
"Promise",
"(",
"gulp",
".",
"series",
"(",
"cleanDocsFolder",
",",
"copyDocsFiles",
",",
"copyJekyllConfig",
")",
")",
";",
"}",
"return",
"resolvePromiseDummy",
"(",
")",
";",
"}"
] |
Run only when gentics-ui-core is building
|
[
"Run",
"only",
"when",
"gentics",
"-",
"ui",
"-",
"core",
"is",
"building"
] |
42872a304f828ca2dd85d4fbf698b35762261e19
|
https://github.com/gentics/gentics-ui-core/blob/42872a304f828ca2dd85d4fbf698b35762261e19/gulpfile.js#L45-L54
|
train
|
gentics/gentics-ui-core
|
gulpfile.js
|
buildUiCoreTasks
|
function buildUiCoreTasks() {
if(npmArgs.remain.indexOf('gentics-ui-core') !== -1) {
return new Promise(gulp.series(compileDistStyles, copyDistReadme));
}
return resolvePromiseDummy();
}
|
javascript
|
function buildUiCoreTasks() {
if(npmArgs.remain.indexOf('gentics-ui-core') !== -1) {
return new Promise(gulp.series(compileDistStyles, copyDistReadme));
}
return resolvePromiseDummy();
}
|
[
"function",
"buildUiCoreTasks",
"(",
")",
"{",
"if",
"(",
"npmArgs",
".",
"remain",
".",
"indexOf",
"(",
"'gentics-ui-core'",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"new",
"Promise",
"(",
"gulp",
".",
"series",
"(",
"compileDistStyles",
",",
"copyDistReadme",
")",
")",
";",
"}",
"return",
"resolvePromiseDummy",
"(",
")",
";",
"}"
] |
Run only when gentics-ui-core is not building
|
[
"Run",
"only",
"when",
"gentics",
"-",
"ui",
"-",
"core",
"is",
"not",
"building"
] |
42872a304f828ca2dd85d4fbf698b35762261e19
|
https://github.com/gentics/gentics-ui-core/blob/42872a304f828ca2dd85d4fbf698b35762261e19/gulpfile.js#L57-L62
|
train
|
gentics/gentics-ui-core
|
gulpfile.js
|
copyJekyllConfig
|
function copyJekyllConfig() {
return streamToPromise(
gulp.src(paths.src.jekyll)
.pipe(rename('_config.yaml'))
.pipe(gulp.dest(paths.out.docs.base))
);
}
|
javascript
|
function copyJekyllConfig() {
return streamToPromise(
gulp.src(paths.src.jekyll)
.pipe(rename('_config.yaml'))
.pipe(gulp.dest(paths.out.docs.base))
);
}
|
[
"function",
"copyJekyllConfig",
"(",
")",
"{",
"return",
"streamToPromise",
"(",
"gulp",
".",
"src",
"(",
"paths",
".",
"src",
".",
"jekyll",
")",
".",
"pipe",
"(",
"rename",
"(",
"'_config.yaml'",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"paths",
".",
"out",
".",
"docs",
".",
"base",
")",
")",
")",
";",
"}"
] |
Copy GH Pages publish configuration
|
[
"Copy",
"GH",
"Pages",
"publish",
"configuration"
] |
42872a304f828ca2dd85d4fbf698b35762261e19
|
https://github.com/gentics/gentics-ui-core/blob/42872a304f828ca2dd85d4fbf698b35762261e19/gulpfile.js#L76-L82
|
train
|
feross/cross-zip
|
index.js
|
copyToTemp
|
function copyToTemp () {
fs.readFile(inPath, function (err, inFile) {
if (err) return cb(err)
var tmpPath = path.join(os.tmpdir(), 'cross-zip-' + Date.now())
fs.mkdir(tmpPath, function (err) {
if (err) return cb(err)
fs.writeFile(path.join(tmpPath, path.basename(inPath)), inFile, function (err) {
if (err) return cb(err)
inPath = tmpPath
doZip()
})
})
})
}
|
javascript
|
function copyToTemp () {
fs.readFile(inPath, function (err, inFile) {
if (err) return cb(err)
var tmpPath = path.join(os.tmpdir(), 'cross-zip-' + Date.now())
fs.mkdir(tmpPath, function (err) {
if (err) return cb(err)
fs.writeFile(path.join(tmpPath, path.basename(inPath)), inFile, function (err) {
if (err) return cb(err)
inPath = tmpPath
doZip()
})
})
})
}
|
[
"function",
"copyToTemp",
"(",
")",
"{",
"fs",
".",
"readFile",
"(",
"inPath",
",",
"function",
"(",
"err",
",",
"inFile",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"var",
"tmpPath",
"=",
"path",
".",
"join",
"(",
"os",
".",
"tmpdir",
"(",
")",
",",
"'cross-zip-'",
"+",
"Date",
".",
"now",
"(",
")",
")",
"fs",
".",
"mkdir",
"(",
"tmpPath",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"fs",
".",
"writeFile",
"(",
"path",
".",
"join",
"(",
"tmpPath",
",",
"path",
".",
"basename",
"(",
"inPath",
")",
")",
",",
"inFile",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"inPath",
"=",
"tmpPath",
"doZip",
"(",
")",
"}",
")",
"}",
")",
"}",
")",
"}"
] |
Windows zip command cannot zip files, only directories. So move the file into a temporary directory before zipping.
|
[
"Windows",
"zip",
"command",
"cannot",
"zip",
"files",
"only",
"directories",
".",
"So",
"move",
"the",
"file",
"into",
"a",
"temporary",
"directory",
"before",
"zipping",
"."
] |
854c4088102572273fa836035f22b710b078f226
|
https://github.com/feross/cross-zip/blob/854c4088102572273fa836035f22b710b078f226/index.js#L31-L44
|
train
|
Kitware/wslink
|
js/src/WebsocketConnection/session.js
|
getAttachment
|
function getAttachment(binaryKey) {
// console.log('Adding binary attachment', binaryKey);
const index = attachments.findIndex((att) => (att.key === binaryKey));
if (index !== -1) {
const result = attachments[index].data;
// TODO if attachment is sent mulitple times, we shouldn't remove it yet.
attachments.splice(index, 1);
return result;
}
console.error('Binary attachment key found without matching attachment');
return null;
}
|
javascript
|
function getAttachment(binaryKey) {
// console.log('Adding binary attachment', binaryKey);
const index = attachments.findIndex((att) => (att.key === binaryKey));
if (index !== -1) {
const result = attachments[index].data;
// TODO if attachment is sent mulitple times, we shouldn't remove it yet.
attachments.splice(index, 1);
return result;
}
console.error('Binary attachment key found without matching attachment');
return null;
}
|
[
"function",
"getAttachment",
"(",
"binaryKey",
")",
"{",
"const",
"index",
"=",
"attachments",
".",
"findIndex",
"(",
"(",
"att",
")",
"=>",
"(",
"att",
".",
"key",
"===",
"binaryKey",
")",
")",
";",
"if",
"(",
"index",
"!==",
"-",
"1",
")",
"{",
"const",
"result",
"=",
"attachments",
"[",
"index",
"]",
".",
"data",
";",
"attachments",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"return",
"result",
";",
"}",
"console",
".",
"error",
"(",
"'Binary attachment key found without matching attachment'",
")",
";",
"return",
"null",
";",
"}"
] |
split out to support a message with a bare binary attachment.
|
[
"split",
"out",
"to",
"support",
"a",
"message",
"with",
"a",
"bare",
"binary",
"attachment",
"."
] |
a98f732bcdcdb536288cd54d43d8697ff8d5d842
|
https://github.com/Kitware/wslink/blob/a98f732bcdcdb536288cd54d43d8697ff8d5d842/js/src/WebsocketConnection/session.js#L133-L144
|
train
|
Rantanen/node-mumble
|
lib/MumbleSocket.js
|
function( socket ) {
var self = this;
this.buffers = [];
this.readers = [];
this.length = 0;
this.socket = socket;
// Register the data callback to receive data from Mumble server.
socket.on( 'data', function( data ) {
self.receiveData( data );
} );
}
|
javascript
|
function( socket ) {
var self = this;
this.buffers = [];
this.readers = [];
this.length = 0;
this.socket = socket;
// Register the data callback to receive data from Mumble server.
socket.on( 'data', function( data ) {
self.receiveData( data );
} );
}
|
[
"function",
"(",
"socket",
")",
"{",
"var",
"self",
"=",
"this",
";",
"this",
".",
"buffers",
"=",
"[",
"]",
";",
"this",
".",
"readers",
"=",
"[",
"]",
";",
"this",
".",
"length",
"=",
"0",
";",
"this",
".",
"socket",
"=",
"socket",
";",
"socket",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"self",
".",
"receiveData",
"(",
"data",
")",
";",
"}",
")",
";",
"}"
] |
Mumble network protocol wrapper for an SSL socket
@private
@constructor
@this {MumbleSocket}
@param {Socket} socket
SSL socket to be wrapped.
The socket must be connected to the Mumble server.
|
[
"Mumble",
"network",
"protocol",
"wrapper",
"for",
"an",
"SSL",
"socket"
] |
c36e50339f2a8bad466816fdf6df967039a6312c
|
https://github.com/Rantanen/node-mumble/blob/c36e50339f2a8bad466816fdf6df967039a6312c/lib/MumbleSocket.js#L15-L26
|
train
|
|
Rantanen/node-mumble
|
lib/Channel.js
|
function( data, client ) {
this.client = client;
/**
* @summary Linked channels
*
* @name Channel#links
* @type Channel[]
*/
this.links = [];
/**
* @summary Child channels
*
* @name Channel#children
* @type Channel[]
*/
this.children = [];
/**
* @summary Users in the channel
*
* @name Channel#users
* @type User[]
*/
this.users = [];
this._checkParent( data ); // Needs to be done seperate
this._applyProperties( data );
// TODO: Description
}
|
javascript
|
function( data, client ) {
this.client = client;
/**
* @summary Linked channels
*
* @name Channel#links
* @type Channel[]
*/
this.links = [];
/**
* @summary Child channels
*
* @name Channel#children
* @type Channel[]
*/
this.children = [];
/**
* @summary Users in the channel
*
* @name Channel#users
* @type User[]
*/
this.users = [];
this._checkParent( data ); // Needs to be done seperate
this._applyProperties( data );
// TODO: Description
}
|
[
"function",
"(",
"data",
",",
"client",
")",
"{",
"this",
".",
"client",
"=",
"client",
";",
"this",
".",
"links",
"=",
"[",
"]",
";",
"this",
".",
"children",
"=",
"[",
"]",
";",
"this",
".",
"users",
"=",
"[",
"]",
";",
"this",
".",
"_checkParent",
"(",
"data",
")",
";",
"this",
".",
"_applyProperties",
"(",
"data",
")",
";",
"}"
] |
Single channel on the server.
@param {Object} data - Channel data.
@param {MumbleClient} client - Mumble client that owns the channel.
|
[
"Single",
"channel",
"on",
"the",
"server",
"."
] |
c36e50339f2a8bad466816fdf6df967039a6312c
|
https://github.com/Rantanen/node-mumble/blob/c36e50339f2a8bad466816fdf6df967039a6312c/lib/Channel.js#L13-L45
|
train
|
|
percy/ember-percy
|
index.js
|
parseMissingResources
|
function parseMissingResources(response) {
return response.body.data &&
response.body.data.relationships &&
response.body.data.relationships['missing-resources'] &&
response.body.data.relationships['missing-resources'].data || [];
}
|
javascript
|
function parseMissingResources(response) {
return response.body.data &&
response.body.data.relationships &&
response.body.data.relationships['missing-resources'] &&
response.body.data.relationships['missing-resources'].data || [];
}
|
[
"function",
"parseMissingResources",
"(",
"response",
")",
"{",
"return",
"response",
".",
"body",
".",
"data",
"&&",
"response",
".",
"body",
".",
"data",
".",
"relationships",
"&&",
"response",
".",
"body",
".",
"data",
".",
"relationships",
"[",
"'missing-resources'",
"]",
"&&",
"response",
".",
"body",
".",
"data",
".",
"relationships",
"[",
"'missing-resources'",
"]",
".",
"data",
"||",
"[",
"]",
";",
"}"
] |
Helper method to parse missing-resources from an API response.
|
[
"Helper",
"method",
"to",
"parse",
"missing",
"-",
"resources",
"from",
"an",
"API",
"response",
"."
] |
0bb3ec9febbc406e0e03f0db84236d811d09fdb6
|
https://github.com/percy/ember-percy/blob/0bb3ec9febbc406e0e03f0db84236d811d09fdb6/index.js#L28-L33
|
train
|
percy/ember-percy
|
index.js
|
function(buildOutputDirectory) {
createPercyBuildInvoked = true;
var token = process.env.PERCY_TOKEN;
var apiUrl = process.env.PERCY_API; // Optional.
// Disable if Percy is explicitly disabled or if this is not an 'ember test' run.
if (process.env.PERCY_ENABLE == '0' || process.env.EMBER_ENV !== 'test') {
isPercyEnabled = false;
}
if (token && isPercyEnabled) {
console.warn('[percy] Percy is running.');
percyClient = new PercyClient({
token: token,
apiUrl: apiUrl,
clientInfo: this._clientInfo(),
environmentInfo: this._environmentInfo(),
});
} else {
isPercyEnabled = false;
if (!token) {
console.warn(
'[percy][WARNING] Percy is disabled, no PERCY_TOKEN environment variable found.')
}
}
if (!isPercyEnabled) { return; }
var resources = percyClient.gatherBuildResources(buildOutputDirectory, {
baseUrlPath: percyConfig.baseUrlPath,
skippedPathRegexes: SKIPPED_ASSETS,
});
// Initialize the percy client and a new build.
percyBuildPromise = percyClient.createBuild({resources: resources});
// Return a promise and only resolve when all build resources are uploaded, which
// ensures that the output build dir is still available to be read from before deleted.
return new Promise(function(resolve) {
percyBuildPromise.then(
function(buildResponse) {
var percyBuildData = buildResponse.body.data;
console.log('\n[percy] Build created:', percyBuildData.attributes['web-url']);
// Upload all missing build resources.
var missingResources = parseMissingResources(buildResponse);
if (missingResources && missingResources.length > 0) {
// Note that duplicate resources with the same SHA will get clobbered here into this
// hash, but that is ok since we only use this to access the content below for upload.
var hashToResource = {};
resources.forEach(function(resource) {
hashToResource[resource.sha] = resource;
});
var missingResourcesIndex = 0;
var promiseGenerator = function() {
var missingResource = missingResources[missingResourcesIndex];
missingResourcesIndex++;
if (missingResource) {
var resource = hashToResource[missingResource.id];
var content = fs.readFileSync(resource.localPath);
// Start the build resource upload and add it to a collection we can block on later
// because build resources must be fully uploaded before snapshots are finalized.
var promise = percyClient.uploadResource(percyBuildData.id, content);
promise.then(function() {
console.log('\n[percy] Uploaded new build resource: ' + resource.resourceUrl);
}, handlePercyFailure);
buildResourceUploadPromises.push(promise);
return promise;
} else {
// Trigger the pool to end.
return null;
}
}
// We do this in a promise pool for two reasons: 1) to limit the number of files that
// are held in memory concurrently, and 2) without a pool, all upload promises are
// created at the same time and request-promise timeout settings begin immediately,
// which timeboxes ALL uploads to finish within one timeout period. With a pool, we
// defer creation of the upload promises, which makes timeouts apply more individually.
var concurrency = 2;
var pool = new PromisePool(promiseGenerator, concurrency);
// Wait for all build resource uploads before we allow the addon build step to complete.
// If an upload failed, resolve anyway to unblock the building process.
pool.start().then(resolve, resolve);
} else {
// No missing resources.
resolve();
}
},
function(error) {
handlePercyFailure(error);
// If Percy build creation fails, resolve anyway to unblock the building process.
resolve();
}
);
});
}
|
javascript
|
function(buildOutputDirectory) {
createPercyBuildInvoked = true;
var token = process.env.PERCY_TOKEN;
var apiUrl = process.env.PERCY_API; // Optional.
// Disable if Percy is explicitly disabled or if this is not an 'ember test' run.
if (process.env.PERCY_ENABLE == '0' || process.env.EMBER_ENV !== 'test') {
isPercyEnabled = false;
}
if (token && isPercyEnabled) {
console.warn('[percy] Percy is running.');
percyClient = new PercyClient({
token: token,
apiUrl: apiUrl,
clientInfo: this._clientInfo(),
environmentInfo: this._environmentInfo(),
});
} else {
isPercyEnabled = false;
if (!token) {
console.warn(
'[percy][WARNING] Percy is disabled, no PERCY_TOKEN environment variable found.')
}
}
if (!isPercyEnabled) { return; }
var resources = percyClient.gatherBuildResources(buildOutputDirectory, {
baseUrlPath: percyConfig.baseUrlPath,
skippedPathRegexes: SKIPPED_ASSETS,
});
// Initialize the percy client and a new build.
percyBuildPromise = percyClient.createBuild({resources: resources});
// Return a promise and only resolve when all build resources are uploaded, which
// ensures that the output build dir is still available to be read from before deleted.
return new Promise(function(resolve) {
percyBuildPromise.then(
function(buildResponse) {
var percyBuildData = buildResponse.body.data;
console.log('\n[percy] Build created:', percyBuildData.attributes['web-url']);
// Upload all missing build resources.
var missingResources = parseMissingResources(buildResponse);
if (missingResources && missingResources.length > 0) {
// Note that duplicate resources with the same SHA will get clobbered here into this
// hash, but that is ok since we only use this to access the content below for upload.
var hashToResource = {};
resources.forEach(function(resource) {
hashToResource[resource.sha] = resource;
});
var missingResourcesIndex = 0;
var promiseGenerator = function() {
var missingResource = missingResources[missingResourcesIndex];
missingResourcesIndex++;
if (missingResource) {
var resource = hashToResource[missingResource.id];
var content = fs.readFileSync(resource.localPath);
// Start the build resource upload and add it to a collection we can block on later
// because build resources must be fully uploaded before snapshots are finalized.
var promise = percyClient.uploadResource(percyBuildData.id, content);
promise.then(function() {
console.log('\n[percy] Uploaded new build resource: ' + resource.resourceUrl);
}, handlePercyFailure);
buildResourceUploadPromises.push(promise);
return promise;
} else {
// Trigger the pool to end.
return null;
}
}
// We do this in a promise pool for two reasons: 1) to limit the number of files that
// are held in memory concurrently, and 2) without a pool, all upload promises are
// created at the same time and request-promise timeout settings begin immediately,
// which timeboxes ALL uploads to finish within one timeout period. With a pool, we
// defer creation of the upload promises, which makes timeouts apply more individually.
var concurrency = 2;
var pool = new PromisePool(promiseGenerator, concurrency);
// Wait for all build resource uploads before we allow the addon build step to complete.
// If an upload failed, resolve anyway to unblock the building process.
pool.start().then(resolve, resolve);
} else {
// No missing resources.
resolve();
}
},
function(error) {
handlePercyFailure(error);
// If Percy build creation fails, resolve anyway to unblock the building process.
resolve();
}
);
});
}
|
[
"function",
"(",
"buildOutputDirectory",
")",
"{",
"createPercyBuildInvoked",
"=",
"true",
";",
"var",
"token",
"=",
"process",
".",
"env",
".",
"PERCY_TOKEN",
";",
"var",
"apiUrl",
"=",
"process",
".",
"env",
".",
"PERCY_API",
";",
"if",
"(",
"process",
".",
"env",
".",
"PERCY_ENABLE",
"==",
"'0'",
"||",
"process",
".",
"env",
".",
"EMBER_ENV",
"!==",
"'test'",
")",
"{",
"isPercyEnabled",
"=",
"false",
";",
"}",
"if",
"(",
"token",
"&&",
"isPercyEnabled",
")",
"{",
"console",
".",
"warn",
"(",
"'[percy] Percy is running.'",
")",
";",
"percyClient",
"=",
"new",
"PercyClient",
"(",
"{",
"token",
":",
"token",
",",
"apiUrl",
":",
"apiUrl",
",",
"clientInfo",
":",
"this",
".",
"_clientInfo",
"(",
")",
",",
"environmentInfo",
":",
"this",
".",
"_environmentInfo",
"(",
")",
",",
"}",
")",
";",
"}",
"else",
"{",
"isPercyEnabled",
"=",
"false",
";",
"if",
"(",
"!",
"token",
")",
"{",
"console",
".",
"warn",
"(",
"'[percy][WARNING] Percy is disabled, no PERCY_TOKEN environment variable found.'",
")",
"}",
"}",
"if",
"(",
"!",
"isPercyEnabled",
")",
"{",
"return",
";",
"}",
"var",
"resources",
"=",
"percyClient",
".",
"gatherBuildResources",
"(",
"buildOutputDirectory",
",",
"{",
"baseUrlPath",
":",
"percyConfig",
".",
"baseUrlPath",
",",
"skippedPathRegexes",
":",
"SKIPPED_ASSETS",
",",
"}",
")",
";",
"percyBuildPromise",
"=",
"percyClient",
".",
"createBuild",
"(",
"{",
"resources",
":",
"resources",
"}",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
")",
"{",
"percyBuildPromise",
".",
"then",
"(",
"function",
"(",
"buildResponse",
")",
"{",
"var",
"percyBuildData",
"=",
"buildResponse",
".",
"body",
".",
"data",
";",
"console",
".",
"log",
"(",
"'\\n[percy] Build created:'",
",",
"\\n",
")",
";",
"percyBuildData",
".",
"attributes",
"[",
"'web-url'",
"]",
"var",
"missingResources",
"=",
"parseMissingResources",
"(",
"buildResponse",
")",
";",
"}",
",",
"if",
"(",
"missingResources",
"&&",
"missingResources",
".",
"length",
">",
"0",
")",
"{",
"var",
"hashToResource",
"=",
"{",
"}",
";",
"resources",
".",
"forEach",
"(",
"function",
"(",
"resource",
")",
"{",
"hashToResource",
"[",
"resource",
".",
"sha",
"]",
"=",
"resource",
";",
"}",
")",
";",
"var",
"missingResourcesIndex",
"=",
"0",
";",
"var",
"promiseGenerator",
"=",
"function",
"(",
")",
"{",
"var",
"missingResource",
"=",
"missingResources",
"[",
"missingResourcesIndex",
"]",
";",
"missingResourcesIndex",
"++",
";",
"if",
"(",
"missingResource",
")",
"{",
"var",
"resource",
"=",
"hashToResource",
"[",
"missingResource",
".",
"id",
"]",
";",
"var",
"content",
"=",
"fs",
".",
"readFileSync",
"(",
"resource",
".",
"localPath",
")",
";",
"var",
"promise",
"=",
"percyClient",
".",
"uploadResource",
"(",
"percyBuildData",
".",
"id",
",",
"content",
")",
";",
"promise",
".",
"then",
"(",
"function",
"(",
")",
"{",
"console",
".",
"log",
"(",
"'\\n[percy] Uploaded new build resource: '",
"+",
"\\n",
")",
";",
"}",
",",
"resource",
".",
"resourceUrl",
")",
";",
"handlePercyFailure",
"buildResourceUploadPromises",
".",
"push",
"(",
"promise",
")",
";",
"}",
"else",
"return",
"promise",
";",
"}",
"{",
"return",
"null",
";",
"}",
"var",
"concurrency",
"=",
"2",
";",
"var",
"pool",
"=",
"new",
"PromisePool",
"(",
"promiseGenerator",
",",
"concurrency",
")",
";",
"}",
"else",
"pool",
".",
"start",
"(",
")",
".",
"then",
"(",
"resolve",
",",
"resolve",
")",
";",
")",
";",
"}",
")",
";",
"}"
] |
Create a Percy build and upload missing build resources.
|
[
"Create",
"a",
"Percy",
"build",
"and",
"upload",
"missing",
"build",
"resources",
"."
] |
0bb3ec9febbc406e0e03f0db84236d811d09fdb6
|
https://github.com/percy/ember-percy/blob/0bb3ec9febbc406e0e03f0db84236d811d09fdb6/index.js#L147-L252
|
train
|
|
percy/ember-percy
|
addon/snapshot.js
|
setAttributeValues
|
function setAttributeValues(dom) {
// List of input types here https://www.w3.org/TR/html5/forms.html#the-input-element
// Limit scope to inputs only as textareas do not retain their value when cloned
let elems = dom.find(
`input[type=text], input[type=search], input[type=tel], input[type=url], input[type=email],
input[type=password], input[type=number], input[type=checkbox], input[type=radio]`
);
percyJQuery(elems).each(function() {
let elem = percyJQuery(this);
switch(elem.attr('type')) {
case 'checkbox':
case 'radio':
if (elem.is(':checked')) {
elem.attr('checked', '');
}
break;
default:
elem.attr('value', elem.val());
}
});
return dom;
}
|
javascript
|
function setAttributeValues(dom) {
// List of input types here https://www.w3.org/TR/html5/forms.html#the-input-element
// Limit scope to inputs only as textareas do not retain their value when cloned
let elems = dom.find(
`input[type=text], input[type=search], input[type=tel], input[type=url], input[type=email],
input[type=password], input[type=number], input[type=checkbox], input[type=radio]`
);
percyJQuery(elems).each(function() {
let elem = percyJQuery(this);
switch(elem.attr('type')) {
case 'checkbox':
case 'radio':
if (elem.is(':checked')) {
elem.attr('checked', '');
}
break;
default:
elem.attr('value', elem.val());
}
});
return dom;
}
|
[
"function",
"setAttributeValues",
"(",
"dom",
")",
"{",
"let",
"elems",
"=",
"dom",
".",
"find",
"(",
"`",
"`",
")",
";",
"percyJQuery",
"(",
"elems",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"let",
"elem",
"=",
"percyJQuery",
"(",
"this",
")",
";",
"switch",
"(",
"elem",
".",
"attr",
"(",
"'type'",
")",
")",
"{",
"case",
"'checkbox'",
":",
"case",
"'radio'",
":",
"if",
"(",
"elem",
".",
"is",
"(",
"':checked'",
")",
")",
"{",
"elem",
".",
"attr",
"(",
"'checked'",
",",
"''",
")",
";",
"}",
"break",
";",
"default",
":",
"elem",
".",
"attr",
"(",
"'value'",
",",
"elem",
".",
"val",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"dom",
";",
"}"
] |
Set the property value into the attribute value for snapshotting inputs
|
[
"Set",
"the",
"property",
"value",
"into",
"the",
"attribute",
"value",
"for",
"snapshotting",
"inputs"
] |
0bb3ec9febbc406e0e03f0db84236d811d09fdb6
|
https://github.com/percy/ember-percy/blob/0bb3ec9febbc406e0e03f0db84236d811d09fdb6/addon/snapshot.js#L24-L48
|
train
|
stealjs/transpile
|
lib/global/slim.js
|
makeNormalizer
|
function makeNormalizer(load, options) {
if (options && (options.normalizeMap || options.normalize)) {
return function(name) {
return optionsNormalize(options, name, load.name, load.address);
};
} else {
return function(name) {
return name;
};
}
}
|
javascript
|
function makeNormalizer(load, options) {
if (options && (options.normalizeMap || options.normalize)) {
return function(name) {
return optionsNormalize(options, name, load.name, load.address);
};
} else {
return function(name) {
return name;
};
}
}
|
[
"function",
"makeNormalizer",
"(",
"load",
",",
"options",
")",
"{",
"if",
"(",
"options",
"&&",
"(",
"options",
".",
"normalizeMap",
"||",
"options",
".",
"normalize",
")",
")",
"{",
"return",
"function",
"(",
"name",
")",
"{",
"return",
"optionsNormalize",
"(",
"options",
",",
"name",
",",
"load",
".",
"name",
",",
"load",
".",
"address",
")",
";",
"}",
";",
"}",
"else",
"{",
"return",
"function",
"(",
"name",
")",
"{",
"return",
"name",
";",
"}",
";",
"}",
"}"
] |
Returns a `normalize` function given the `load` and `options`
|
[
"Returns",
"a",
"normalize",
"function",
"given",
"the",
"load",
"and",
"options"
] |
307c7566976d08e0f637a600115cd7e7b67cc9d7
|
https://github.com/stealjs/transpile/blob/307c7566976d08e0f637a600115cd7e7b67cc9d7/lib/global/slim.js#L48-L58
|
train
|
stealjs/transpile
|
lib/get_ast.js
|
getAst
|
function getAst(load, sourceMapFileName){
if(load.ast) {
return load.ast;
}
var fileName = sourceMapFileName || load.map && load.map.file;
load.ast = esprima.parse(load.source.toString(), {
loc: true,
source: fileName || load.address
});
if(load.map) {
sourceMapToAst(load.ast, load.map);
}
return load.ast;
}
|
javascript
|
function getAst(load, sourceMapFileName){
if(load.ast) {
return load.ast;
}
var fileName = sourceMapFileName || load.map && load.map.file;
load.ast = esprima.parse(load.source.toString(), {
loc: true,
source: fileName || load.address
});
if(load.map) {
sourceMapToAst(load.ast, load.map);
}
return load.ast;
}
|
[
"function",
"getAst",
"(",
"load",
",",
"sourceMapFileName",
")",
"{",
"if",
"(",
"load",
".",
"ast",
")",
"{",
"return",
"load",
".",
"ast",
";",
"}",
"var",
"fileName",
"=",
"sourceMapFileName",
"||",
"load",
".",
"map",
"&&",
"load",
".",
"map",
".",
"file",
";",
"load",
".",
"ast",
"=",
"esprima",
".",
"parse",
"(",
"load",
".",
"source",
".",
"toString",
"(",
")",
",",
"{",
"loc",
":",
"true",
",",
"source",
":",
"fileName",
"||",
"load",
".",
"address",
"}",
")",
";",
"if",
"(",
"load",
".",
"map",
")",
"{",
"sourceMapToAst",
"(",
"load",
".",
"ast",
",",
"load",
".",
"map",
")",
";",
"}",
"return",
"load",
".",
"ast",
";",
"}"
] |
Get the ast for a load or create one if it doesn't exist.
|
[
"Get",
"the",
"ast",
"for",
"a",
"load",
"or",
"create",
"one",
"if",
"it",
"doesn",
"t",
"exist",
"."
] |
307c7566976d08e0f637a600115cd7e7b67cc9d7
|
https://github.com/stealjs/transpile/blob/307c7566976d08e0f637a600115cd7e7b67cc9d7/lib/get_ast.js#L9-L26
|
train
|
stealjs/transpile
|
lib/cjs_amd.js
|
visitRequireArgument
|
function visitRequireArgument(ast, cb) {
types.visit(ast, {
visitCallExpression: function(path) {
if (this.isRequireExpression(path.node)) {
var arg = path.getValueProperty("arguments")[0];
if (n.Literal.check(arg)) {
cb(arg);
}
}
this.traverse(path);
},
isRequireExpression(node) {
return n.Identifier.check(node.callee) && node.callee.name === "require";
}
});
}
|
javascript
|
function visitRequireArgument(ast, cb) {
types.visit(ast, {
visitCallExpression: function(path) {
if (this.isRequireExpression(path.node)) {
var arg = path.getValueProperty("arguments")[0];
if (n.Literal.check(arg)) {
cb(arg);
}
}
this.traverse(path);
},
isRequireExpression(node) {
return n.Identifier.check(node.callee) && node.callee.name === "require";
}
});
}
|
[
"function",
"visitRequireArgument",
"(",
"ast",
",",
"cb",
")",
"{",
"types",
".",
"visit",
"(",
"ast",
",",
"{",
"visitCallExpression",
":",
"function",
"(",
"path",
")",
"{",
"if",
"(",
"this",
".",
"isRequireExpression",
"(",
"path",
".",
"node",
")",
")",
"{",
"var",
"arg",
"=",
"path",
".",
"getValueProperty",
"(",
"\"arguments\"",
")",
"[",
"0",
"]",
";",
"if",
"(",
"n",
".",
"Literal",
".",
"check",
"(",
"arg",
")",
")",
"{",
"cb",
"(",
"arg",
")",
";",
"}",
"}",
"this",
".",
"traverse",
"(",
"path",
")",
";",
"}",
",",
"isRequireExpression",
"(",
"node",
")",
"{",
"return",
"n",
".",
"Identifier",
".",
"check",
"(",
"node",
".",
"callee",
")",
"&&",
"node",
".",
"callee",
".",
"name",
"===",
"\"require\"",
";",
"}",
"}",
")",
";",
"}"
] |
Given an ast, calls the visitor with the first argument of each `require` call
@param {Object} ast - The ast to walk
@param {Function} cb - The visitor function called on each match
|
[
"Given",
"an",
"ast",
"calls",
"the",
"visitor",
"with",
"the",
"first",
"argument",
"of",
"each",
"require",
"call"
] |
307c7566976d08e0f637a600115cd7e7b67cc9d7
|
https://github.com/stealjs/transpile/blob/307c7566976d08e0f637a600115cd7e7b67cc9d7/lib/cjs_amd.js#L46-L64
|
train
|
stealjs/transpile
|
lib/cjs_amd.js
|
collectDependenciesIds
|
function collectDependenciesIds(ast) {
var ids = [];
visitRequireArgument(ast, function(argument) {
ids.push(argument.value);
});
return ids;
}
|
javascript
|
function collectDependenciesIds(ast) {
var ids = [];
visitRequireArgument(ast, function(argument) {
ids.push(argument.value);
});
return ids;
}
|
[
"function",
"collectDependenciesIds",
"(",
"ast",
")",
"{",
"var",
"ids",
"=",
"[",
"]",
";",
"visitRequireArgument",
"(",
"ast",
",",
"function",
"(",
"argument",
")",
"{",
"ids",
".",
"push",
"(",
"argument",
".",
"value",
")",
";",
"}",
")",
";",
"return",
"ids",
";",
"}"
] |
Given an AST, returns the module identifiers passed to `require` calls
@param {Object} ast - The ast to walk
@return {Array.<String>} The module identifiers
|
[
"Given",
"an",
"AST",
"returns",
"the",
"module",
"identifiers",
"passed",
"to",
"require",
"calls"
] |
307c7566976d08e0f637a600115cd7e7b67cc9d7
|
https://github.com/stealjs/transpile/blob/307c7566976d08e0f637a600115cd7e7b67cc9d7/lib/cjs_amd.js#L88-L96
|
train
|
stealjs/transpile
|
main.js
|
endsWith
|
function endsWith(source, dest, path) {
return (
path[path.length - 2] === source &&
path[path.length - 1] === dest
);
}
|
javascript
|
function endsWith(source, dest, path) {
return (
path[path.length - 2] === source &&
path[path.length - 1] === dest
);
}
|
[
"function",
"endsWith",
"(",
"source",
",",
"dest",
",",
"path",
")",
"{",
"return",
"(",
"path",
"[",
"path",
".",
"length",
"-",
"2",
"]",
"===",
"source",
"&&",
"path",
"[",
"path",
".",
"length",
"-",
"1",
"]",
"===",
"dest",
")",
";",
"}"
] |
Whether the last step of the transform is from "source" to "dest"
@param {string} source - The source code format
@param {string} dest - The destination format
@param {Array.<string>} path - Path of format transformations
@return {Boolean} true if "source" -> "dest" is the last step
|
[
"Whether",
"the",
"last",
"step",
"of",
"the",
"transform",
"is",
"from",
"source",
"to",
"dest"
] |
307c7566976d08e0f637a600115cd7e7b67cc9d7
|
https://github.com/stealjs/transpile/blob/307c7566976d08e0f637a600115cd7e7b67cc9d7/main.js#L43-L48
|
train
|
stealjs/transpile
|
main.js
|
function(from, to) {
var path;
bfs(from || "es6", formatsTransformsGraph, function(cur) {
if (cur.node === to) {
path = cur.path;
return false;
}
});
return path;
}
|
javascript
|
function(from, to) {
var path;
bfs(from || "es6", formatsTransformsGraph, function(cur) {
if (cur.node === to) {
path = cur.path;
return false;
}
});
return path;
}
|
[
"function",
"(",
"from",
",",
"to",
")",
"{",
"var",
"path",
";",
"bfs",
"(",
"from",
"||",
"\"es6\"",
",",
"formatsTransformsGraph",
",",
"function",
"(",
"cur",
")",
"{",
"if",
"(",
"cur",
".",
"node",
"===",
"to",
")",
"{",
"path",
"=",
"cur",
".",
"path",
";",
"return",
"false",
";",
"}",
"}",
")",
";",
"return",
"path",
";",
"}"
] |
Whether it's possible to transform the source format to the dest format
@param {string} from The format of the source, e.g: "es6"
@parem {string} to the format of the output code, e.g: "amd"
@return {?Array} The "path" of formats needed to transform
from the source code to the dest format
|
[
"Whether",
"it",
"s",
"possible",
"to",
"transform",
"the",
"source",
"format",
"to",
"the",
"dest",
"format"
] |
307c7566976d08e0f637a600115cd7e7b67cc9d7
|
https://github.com/stealjs/transpile/blob/307c7566976d08e0f637a600115cd7e7b67cc9d7/main.js#L105-L114
|
train
|
|
stealjs/transpile
|
lib/amd/slim.js
|
hasNestedDefine
|
function hasNestedDefine(ast) {
var result = false;
types.visit(ast, {
visitCallExpression: function(path) {
if (this.isDefineExpression(path)) {
result = true;
this.abort();
}
this.traverse(path);
},
// whether a non top level `define(` is call in the AST
isDefineExpression: function(path) {
return (
n.Identifier.check(path.node.callee) &&
path.node.callee.name === "define" &&
!n.Program.check(path.parent.parent.node)
);
}
});
return result;
}
|
javascript
|
function hasNestedDefine(ast) {
var result = false;
types.visit(ast, {
visitCallExpression: function(path) {
if (this.isDefineExpression(path)) {
result = true;
this.abort();
}
this.traverse(path);
},
// whether a non top level `define(` is call in the AST
isDefineExpression: function(path) {
return (
n.Identifier.check(path.node.callee) &&
path.node.callee.name === "define" &&
!n.Program.check(path.parent.parent.node)
);
}
});
return result;
}
|
[
"function",
"hasNestedDefine",
"(",
"ast",
")",
"{",
"var",
"result",
"=",
"false",
";",
"types",
".",
"visit",
"(",
"ast",
",",
"{",
"visitCallExpression",
":",
"function",
"(",
"path",
")",
"{",
"if",
"(",
"this",
".",
"isDefineExpression",
"(",
"path",
")",
")",
"{",
"result",
"=",
"true",
";",
"this",
".",
"abort",
"(",
")",
";",
"}",
"this",
".",
"traverse",
"(",
"path",
")",
";",
"}",
",",
"isDefineExpression",
":",
"function",
"(",
"path",
")",
"{",
"return",
"(",
"n",
".",
"Identifier",
".",
"check",
"(",
"path",
".",
"node",
".",
"callee",
")",
"&&",
"path",
".",
"node",
".",
"callee",
".",
"name",
"===",
"\"define\"",
"&&",
"!",
"n",
".",
"Program",
".",
"check",
"(",
"path",
".",
"parent",
".",
"parent",
".",
"node",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"result",
";",
"}"
] |
Whether there is a non top level `define` function call in the AST
@param {Object} ast - The AST to be checked
@return {boolean}
|
[
"Whether",
"there",
"is",
"a",
"non",
"top",
"level",
"define",
"function",
"call",
"in",
"the",
"AST"
] |
307c7566976d08e0f637a600115cd7e7b67cc9d7
|
https://github.com/stealjs/transpile/blob/307c7566976d08e0f637a600115cd7e7b67cc9d7/lib/amd/slim.js#L45-L69
|
train
|
stealjs/transpile
|
lib/amd/slim.js
|
function(path) {
return (
n.Identifier.check(path.node.callee) &&
path.node.callee.name === "define" &&
!n.Program.check(path.parent.parent.node)
);
}
|
javascript
|
function(path) {
return (
n.Identifier.check(path.node.callee) &&
path.node.callee.name === "define" &&
!n.Program.check(path.parent.parent.node)
);
}
|
[
"function",
"(",
"path",
")",
"{",
"return",
"(",
"n",
".",
"Identifier",
".",
"check",
"(",
"path",
".",
"node",
".",
"callee",
")",
"&&",
"path",
".",
"node",
".",
"callee",
".",
"name",
"===",
"\"define\"",
"&&",
"!",
"n",
".",
"Program",
".",
"check",
"(",
"path",
".",
"parent",
".",
"parent",
".",
"node",
")",
")",
";",
"}"
] |
whether a non top level `define(` is call in the AST
|
[
"whether",
"a",
"non",
"top",
"level",
"define",
"(",
"is",
"call",
"in",
"the",
"AST"
] |
307c7566976d08e0f637a600115cd7e7b67cc9d7
|
https://github.com/stealjs/transpile/blob/307c7566976d08e0f637a600115cd7e7b67cc9d7/lib/amd/slim.js#L59-L65
|
train
|
|
stealjs/transpile
|
lib/amd/slim.js
|
hasDefineAmdReference
|
function hasDefineAmdReference(ast) {
var result = false;
types.visit(ast, {
visitMemberExpression: function(path) {
if (this.isDefineAmd(path.node)) {
result = true;
this.abort();
}
this.traverse(path);
},
isDefineAmd: function(node) {
return (
n.Identifier.check(node.object) &&
node.object.name === "define" &&
n.Identifier.check(node.property) &&
node.property.name === "amd"
);
}
});
return result;
}
|
javascript
|
function hasDefineAmdReference(ast) {
var result = false;
types.visit(ast, {
visitMemberExpression: function(path) {
if (this.isDefineAmd(path.node)) {
result = true;
this.abort();
}
this.traverse(path);
},
isDefineAmd: function(node) {
return (
n.Identifier.check(node.object) &&
node.object.name === "define" &&
n.Identifier.check(node.property) &&
node.property.name === "amd"
);
}
});
return result;
}
|
[
"function",
"hasDefineAmdReference",
"(",
"ast",
")",
"{",
"var",
"result",
"=",
"false",
";",
"types",
".",
"visit",
"(",
"ast",
",",
"{",
"visitMemberExpression",
":",
"function",
"(",
"path",
")",
"{",
"if",
"(",
"this",
".",
"isDefineAmd",
"(",
"path",
".",
"node",
")",
")",
"{",
"result",
"=",
"true",
";",
"this",
".",
"abort",
"(",
")",
";",
"}",
"this",
".",
"traverse",
"(",
"path",
")",
";",
"}",
",",
"isDefineAmd",
":",
"function",
"(",
"node",
")",
"{",
"return",
"(",
"n",
".",
"Identifier",
".",
"check",
"(",
"node",
".",
"object",
")",
"&&",
"node",
".",
"object",
".",
"name",
"===",
"\"define\"",
"&&",
"n",
".",
"Identifier",
".",
"check",
"(",
"node",
".",
"property",
")",
"&&",
"node",
".",
"property",
".",
"name",
"===",
"\"amd\"",
")",
";",
"}",
"}",
")",
";",
"return",
"result",
";",
"}"
] |
Whether there is a `define.amd` member expression on the AST
@param {Object} ast - The AST to be checked
@return {boolean}
|
[
"Whether",
"there",
"is",
"a",
"define",
".",
"amd",
"member",
"expression",
"on",
"the",
"AST"
] |
307c7566976d08e0f637a600115cd7e7b67cc9d7
|
https://github.com/stealjs/transpile/blob/307c7566976d08e0f637a600115cd7e7b67cc9d7/lib/amd/slim.js#L76-L100
|
train
|
stealjs/transpile
|
lib/amd/slim.js
|
function(path) {
return (
this.isDefineExpression(path.node) &&
n.Program.check(path.parent.parent.node) &&
n.ExpressionStatement.check(path.parent.node)
);
}
|
javascript
|
function(path) {
return (
this.isDefineExpression(path.node) &&
n.Program.check(path.parent.parent.node) &&
n.ExpressionStatement.check(path.parent.node)
);
}
|
[
"function",
"(",
"path",
")",
"{",
"return",
"(",
"this",
".",
"isDefineExpression",
"(",
"path",
".",
"node",
")",
"&&",
"n",
".",
"Program",
".",
"check",
"(",
"path",
".",
"parent",
".",
"parent",
".",
"node",
")",
"&&",
"n",
".",
"ExpressionStatement",
".",
"check",
"(",
"path",
".",
"parent",
".",
"node",
")",
")",
";",
"}"
] |
checks if `define` is invoked at the top-level.
|
[
"checks",
"if",
"define",
"is",
"invoked",
"at",
"the",
"top",
"-",
"level",
"."
] |
307c7566976d08e0f637a600115cd7e7b67cc9d7
|
https://github.com/stealjs/transpile/blob/307c7566976d08e0f637a600115cd7e7b67cc9d7/lib/amd/slim.js#L137-L143
|
train
|
|
stealjs/transpile
|
lib/amd/slim.js
|
function(args) {
var result = { id: null, factory: null, dependencies: [] };
switch (args.length) {
// define(factory);
case 1:
result.factory = getFactory(args[0]);
break;
// define(id || dependencies, factory);
case 2:
if (this.isNamed(args)) {
assign(result, {
id: args[0],
factory: getFactory(args[1])
});
} else {
assign(result, {
dependencies: args[0],
factory: getFactory(args[1])
});
}
break;
// define(id, dependencies, factory);
case 3:
assign(result, {
id: args[0],
dependencies: args[1],
factory: getFactory(args[2])
});
break;
default:
throw new Error("Invalid `define` function signature");
}
// set the `isCjsWrapper` flag
result.isCjsWrapper =
n.ArrayExpression.check(result.dependencies) &&
result.dependencies.elements.length
? this.usesCjsRequireExports(result.dependencies)
: this.isCjsSimplifiedWrapper(result.factory);
return result;
}
|
javascript
|
function(args) {
var result = { id: null, factory: null, dependencies: [] };
switch (args.length) {
// define(factory);
case 1:
result.factory = getFactory(args[0]);
break;
// define(id || dependencies, factory);
case 2:
if (this.isNamed(args)) {
assign(result, {
id: args[0],
factory: getFactory(args[1])
});
} else {
assign(result, {
dependencies: args[0],
factory: getFactory(args[1])
});
}
break;
// define(id, dependencies, factory);
case 3:
assign(result, {
id: args[0],
dependencies: args[1],
factory: getFactory(args[2])
});
break;
default:
throw new Error("Invalid `define` function signature");
}
// set the `isCjsWrapper` flag
result.isCjsWrapper =
n.ArrayExpression.check(result.dependencies) &&
result.dependencies.elements.length
? this.usesCjsRequireExports(result.dependencies)
: this.isCjsSimplifiedWrapper(result.factory);
return result;
}
|
[
"function",
"(",
"args",
")",
"{",
"var",
"result",
"=",
"{",
"id",
":",
"null",
",",
"factory",
":",
"null",
",",
"dependencies",
":",
"[",
"]",
"}",
";",
"switch",
"(",
"args",
".",
"length",
")",
"{",
"case",
"1",
":",
"result",
".",
"factory",
"=",
"getFactory",
"(",
"args",
"[",
"0",
"]",
")",
";",
"break",
";",
"case",
"2",
":",
"if",
"(",
"this",
".",
"isNamed",
"(",
"args",
")",
")",
"{",
"assign",
"(",
"result",
",",
"{",
"id",
":",
"args",
"[",
"0",
"]",
",",
"factory",
":",
"getFactory",
"(",
"args",
"[",
"1",
"]",
")",
"}",
")",
";",
"}",
"else",
"{",
"assign",
"(",
"result",
",",
"{",
"dependencies",
":",
"args",
"[",
"0",
"]",
",",
"factory",
":",
"getFactory",
"(",
"args",
"[",
"1",
"]",
")",
"}",
")",
";",
"}",
"break",
";",
"case",
"3",
":",
"assign",
"(",
"result",
",",
"{",
"id",
":",
"args",
"[",
"0",
"]",
",",
"dependencies",
":",
"args",
"[",
"1",
"]",
",",
"factory",
":",
"getFactory",
"(",
"args",
"[",
"2",
"]",
")",
"}",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"\"Invalid `define` function signature\"",
")",
";",
"}",
"result",
".",
"isCjsWrapper",
"=",
"n",
".",
"ArrayExpression",
".",
"check",
"(",
"result",
".",
"dependencies",
")",
"&&",
"result",
".",
"dependencies",
".",
"elements",
".",
"length",
"?",
"this",
".",
"usesCjsRequireExports",
"(",
"result",
".",
"dependencies",
")",
":",
"this",
".",
"isCjsSimplifiedWrapper",
"(",
"result",
".",
"factory",
")",
";",
"return",
"result",
";",
"}"
] |
The AMD define arguments AST nodes as an object
@typedef {Object} DefineArguments
@property {?string} id - The module if of the module being defined
@property {Array.<string>} dependencies - Array of modules ids dependencies
@property {!Function} factory - Module's factory function
@property {boolean} isCjsWrapper - Whether factory function is AMD's
simplified CommonJS wrapping.
Returns an object with the arguments of the define function
@param {Array} args - The AST node of the `define` call arguments
@return {DefineArguments} An object with AMD's define function arguments
|
[
"The",
"AMD",
"define",
"arguments",
"AST",
"nodes",
"as",
"an",
"object"
] |
307c7566976d08e0f637a600115cd7e7b67cc9d7
|
https://github.com/stealjs/transpile/blob/307c7566976d08e0f637a600115cd7e7b67cc9d7/lib/amd/slim.js#L203-L248
|
train
|
|
stealjs/transpile
|
lib/amd/slim.js
|
getFactory
|
function getFactory(arg) {
return n.ObjectExpression.check(arg)
? slimBuilder.makeFactoryFromObject(arg)
: arg;
}
|
javascript
|
function getFactory(arg) {
return n.ObjectExpression.check(arg)
? slimBuilder.makeFactoryFromObject(arg)
: arg;
}
|
[
"function",
"getFactory",
"(",
"arg",
")",
"{",
"return",
"n",
".",
"ObjectExpression",
".",
"check",
"(",
"arg",
")",
"?",
"slimBuilder",
".",
"makeFactoryFromObject",
"(",
"arg",
")",
":",
"arg",
";",
"}"
] |
Normalizes the factory function if the object shorthand was used
@param {Object} arg - The AST node of the argument where the
"factory" function should be found.
@return {Object} The AST node of the factory function.
|
[
"Normalizes",
"the",
"factory",
"function",
"if",
"the",
"object",
"shorthand",
"was",
"used"
] |
307c7566976d08e0f637a600115cd7e7b67cc9d7
|
https://github.com/stealjs/transpile/blob/307c7566976d08e0f637a600115cd7e7b67cc9d7/lib/amd/slim.js#L260-L264
|
train
|
chaijs/chai-json-schema
|
index.js
|
valueStrim
|
function valueStrim(value, cutoff) {
var strimLimit = typeof cutoff === 'undefined' ? 60 : cutoff;
var t = typeof value;
if (t === 'function') {
return '[function]';
}
if (t === 'object') {
value = JSON.stringify(value);
if (value.length > strimLimit) {
value = value.substr(0, strimLimit) + '...';
}
return value;
}
if (t === 'string') {
if (value.length > strimLimit) {
return JSON.stringify(value.substr(0, strimLimit)) + '...';
}
return JSON.stringify(value);
}
return '' + value;
}
|
javascript
|
function valueStrim(value, cutoff) {
var strimLimit = typeof cutoff === 'undefined' ? 60 : cutoff;
var t = typeof value;
if (t === 'function') {
return '[function]';
}
if (t === 'object') {
value = JSON.stringify(value);
if (value.length > strimLimit) {
value = value.substr(0, strimLimit) + '...';
}
return value;
}
if (t === 'string') {
if (value.length > strimLimit) {
return JSON.stringify(value.substr(0, strimLimit)) + '...';
}
return JSON.stringify(value);
}
return '' + value;
}
|
[
"function",
"valueStrim",
"(",
"value",
",",
"cutoff",
")",
"{",
"var",
"strimLimit",
"=",
"typeof",
"cutoff",
"===",
"'undefined'",
"?",
"60",
":",
"cutoff",
";",
"var",
"t",
"=",
"typeof",
"value",
";",
"if",
"(",
"t",
"===",
"'function'",
")",
"{",
"return",
"'[function]'",
";",
"}",
"if",
"(",
"t",
"===",
"'object'",
")",
"{",
"value",
"=",
"JSON",
".",
"stringify",
"(",
"value",
")",
";",
"if",
"(",
"value",
".",
"length",
">",
"strimLimit",
")",
"{",
"value",
"=",
"value",
".",
"substr",
"(",
"0",
",",
"strimLimit",
")",
"+",
"'...'",
";",
"}",
"return",
"value",
";",
"}",
"if",
"(",
"t",
"===",
"'string'",
")",
"{",
"if",
"(",
"value",
".",
"length",
">",
"strimLimit",
")",
"{",
"return",
"JSON",
".",
"stringify",
"(",
"value",
".",
"substr",
"(",
"0",
",",
"strimLimit",
")",
")",
"+",
"'...'",
";",
"}",
"return",
"JSON",
".",
"stringify",
"(",
"value",
")",
";",
"}",
"return",
"''",
"+",
"value",
";",
"}"
] |
make a compact debug string from any object
|
[
"make",
"a",
"compact",
"debug",
"string",
"from",
"any",
"object"
] |
82939b7663f0e741813ffb85479a1e1c2923a57c
|
https://github.com/chaijs/chai-json-schema/blob/82939b7663f0e741813ffb85479a1e1c2923a57c/index.js#L50-L71
|
train
|
chaijs/chai-json-schema
|
index.js
|
function (error, data, schema, indent) {
var schemaValue;
var dataValue;
var schemaLabel;
// assemble error string
var ret = '';
ret += '\n' + indent + error.message;
schemaLabel = extractSchemaLabel(schema, 60);
if (schemaLabel) {
ret += '\n' + indent + ' schema: ' + schemaLabel;
}
if (error.schemaPath) {
schemaValue = jsonpointer.get(schema, error.schemaPath);
ret += '\n' + indent + ' rule: ' + error.schemaPath + ' -> ' + valueStrim(schemaValue);
}
if (error.dataPath) {
dataValue = jsonpointer.get(data, error.dataPath);
ret += '\n' + indent + ' field: ' + error.dataPath + ' -> ' + utils.type(dataValue) + ': ' + valueStrim(dataValue);
}
// sub errors are not implemented (yet?)
// https://github.com/chaijs/chai-json-schema/issues/3
/*if (error.subErrors) {
forEachI(error.subErrors, function (error) {
ret += formatResult(error, data, schema, indent + indent);
});
}*/
return ret;
}
|
javascript
|
function (error, data, schema, indent) {
var schemaValue;
var dataValue;
var schemaLabel;
// assemble error string
var ret = '';
ret += '\n' + indent + error.message;
schemaLabel = extractSchemaLabel(schema, 60);
if (schemaLabel) {
ret += '\n' + indent + ' schema: ' + schemaLabel;
}
if (error.schemaPath) {
schemaValue = jsonpointer.get(schema, error.schemaPath);
ret += '\n' + indent + ' rule: ' + error.schemaPath + ' -> ' + valueStrim(schemaValue);
}
if (error.dataPath) {
dataValue = jsonpointer.get(data, error.dataPath);
ret += '\n' + indent + ' field: ' + error.dataPath + ' -> ' + utils.type(dataValue) + ': ' + valueStrim(dataValue);
}
// sub errors are not implemented (yet?)
// https://github.com/chaijs/chai-json-schema/issues/3
/*if (error.subErrors) {
forEachI(error.subErrors, function (error) {
ret += formatResult(error, data, schema, indent + indent);
});
}*/
return ret;
}
|
[
"function",
"(",
"error",
",",
"data",
",",
"schema",
",",
"indent",
")",
"{",
"var",
"schemaValue",
";",
"var",
"dataValue",
";",
"var",
"schemaLabel",
";",
"var",
"ret",
"=",
"''",
";",
"ret",
"+=",
"'\\n'",
"+",
"\\n",
"+",
"indent",
";",
"error",
".",
"message",
"schemaLabel",
"=",
"extractSchemaLabel",
"(",
"schema",
",",
"60",
")",
";",
"if",
"(",
"schemaLabel",
")",
"{",
"ret",
"+=",
"'\\n'",
"+",
"\\n",
"+",
"indent",
"+",
"' schema: '",
";",
"}",
"schemaLabel",
"if",
"(",
"error",
".",
"schemaPath",
")",
"{",
"schemaValue",
"=",
"jsonpointer",
".",
"get",
"(",
"schema",
",",
"error",
".",
"schemaPath",
")",
";",
"ret",
"+=",
"'\\n'",
"+",
"\\n",
"+",
"indent",
"+",
"' rule: '",
"+",
"error",
".",
"schemaPath",
"+",
"' -> '",
";",
"}",
"}"
] |
print validation errors
|
[
"print",
"validation",
"errors"
] |
82939b7663f0e741813ffb85479a1e1c2923a57c
|
https://github.com/chaijs/chai-json-schema/blob/82939b7663f0e741813ffb85479a1e1c2923a57c/index.js#L92-L122
|
train
|
|
yusinto/ld-redux
|
lib/init.js
|
initFlags
|
function initFlags(flags, dispatch) {
var flagValues = { isLDReady: false };
for (var flag in flags) {
var camelCasedKey = (0, _lodash2.default)(flag);
flagValues[camelCasedKey] = flags[flag];
}
dispatch((0, _actions.setFlags)(flagValues));
}
|
javascript
|
function initFlags(flags, dispatch) {
var flagValues = { isLDReady: false };
for (var flag in flags) {
var camelCasedKey = (0, _lodash2.default)(flag);
flagValues[camelCasedKey] = flags[flag];
}
dispatch((0, _actions.setFlags)(flagValues));
}
|
[
"function",
"initFlags",
"(",
"flags",
",",
"dispatch",
")",
"{",
"var",
"flagValues",
"=",
"{",
"isLDReady",
":",
"false",
"}",
";",
"for",
"(",
"var",
"flag",
"in",
"flags",
")",
"{",
"var",
"camelCasedKey",
"=",
"(",
"0",
",",
"_lodash2",
".",
"default",
")",
"(",
"flag",
")",
";",
"flagValues",
"[",
"camelCasedKey",
"]",
"=",
"flags",
"[",
"flag",
"]",
";",
"}",
"dispatch",
"(",
"(",
"0",
",",
"_actions",
".",
"setFlags",
")",
"(",
"flagValues",
")",
")",
";",
"}"
] |
initialise flags with default values in ld redux store
|
[
"initialise",
"flags",
"with",
"default",
"values",
"in",
"ld",
"redux",
"store"
] |
5097b18812fb1cf10268de5d5d58ca4828b187d2
|
https://github.com/yusinto/ld-redux/blob/5097b18812fb1cf10268de5d5d58ca4828b187d2/lib/init.js#L34-L41
|
train
|
yusinto/ld-redux
|
lib/init.js
|
setFlags
|
function setFlags(flags, dispatch) {
var flagValues = { isLDReady: true };
for (var flag in flags) {
var camelCasedKey = (0, _lodash2.default)(flag);
flagValues[camelCasedKey] = ldClient.variation(flag, flags[flag]);
}
dispatch((0, _actions.setFlags)(flagValues));
}
|
javascript
|
function setFlags(flags, dispatch) {
var flagValues = { isLDReady: true };
for (var flag in flags) {
var camelCasedKey = (0, _lodash2.default)(flag);
flagValues[camelCasedKey] = ldClient.variation(flag, flags[flag]);
}
dispatch((0, _actions.setFlags)(flagValues));
}
|
[
"function",
"setFlags",
"(",
"flags",
",",
"dispatch",
")",
"{",
"var",
"flagValues",
"=",
"{",
"isLDReady",
":",
"true",
"}",
";",
"for",
"(",
"var",
"flag",
"in",
"flags",
")",
"{",
"var",
"camelCasedKey",
"=",
"(",
"0",
",",
"_lodash2",
".",
"default",
")",
"(",
"flag",
")",
";",
"flagValues",
"[",
"camelCasedKey",
"]",
"=",
"ldClient",
".",
"variation",
"(",
"flag",
",",
"flags",
"[",
"flag",
"]",
")",
";",
"}",
"dispatch",
"(",
"(",
"0",
",",
"_actions",
".",
"setFlags",
")",
"(",
"flagValues",
")",
")",
";",
"}"
] |
set flags with real values from ld server
|
[
"set",
"flags",
"with",
"real",
"values",
"from",
"ld",
"server"
] |
5097b18812fb1cf10268de5d5d58ca4828b187d2
|
https://github.com/yusinto/ld-redux/blob/5097b18812fb1cf10268de5d5d58ca4828b187d2/lib/init.js#L44-L51
|
train
|
fresheneesz/mongo-parse
|
mapValues.js
|
obj
|
function obj(/*key,value, key,value ...*/) {
var result = {}
for(var n=0; n<arguments.length; n+=2) {
result[arguments[n]] = arguments[n+1]
}
return result
}
|
javascript
|
function obj(/*key,value, key,value ...*/) {
var result = {}
for(var n=0; n<arguments.length; n+=2) {
result[arguments[n]] = arguments[n+1]
}
return result
}
|
[
"function",
"obj",
"(",
")",
"{",
"var",
"result",
"=",
"{",
"}",
"for",
"(",
"var",
"n",
"=",
"0",
";",
"n",
"<",
"arguments",
".",
"length",
";",
"n",
"+=",
"2",
")",
"{",
"result",
"[",
"arguments",
"[",
"n",
"]",
"]",
"=",
"arguments",
"[",
"n",
"+",
"1",
"]",
"}",
"return",
"result",
"}"
] |
builds an object immediate where keys can be expressions
|
[
"builds",
"an",
"object",
"immediate",
"where",
"keys",
"can",
"be",
"expressions"
] |
c11bb6ac860ad1b9b30ccd1936ab0ca28d4e5d6b
|
https://github.com/fresheneesz/mongo-parse/blob/c11bb6ac860ad1b9b30ccd1936ab0ca28d4e5d6b/mapValues.js#L79-L85
|
train
|
fresheneesz/mongo-parse
|
mapValues.js
|
addOperator
|
function addOperator(obj, field, operator, operand) {
if(obj[field] === undefined) {
obj[field] = {}
}
obj[field][operator] = operand
}
|
javascript
|
function addOperator(obj, field, operator, operand) {
if(obj[field] === undefined) {
obj[field] = {}
}
obj[field][operator] = operand
}
|
[
"function",
"addOperator",
"(",
"obj",
",",
"field",
",",
"operator",
",",
"operand",
")",
"{",
"if",
"(",
"obj",
"[",
"field",
"]",
"===",
"undefined",
")",
"{",
"obj",
"[",
"field",
"]",
"=",
"{",
"}",
"}",
"obj",
"[",
"field",
"]",
"[",
"operator",
"]",
"=",
"operand",
"}"
] |
adds an operator to a field, handling the case where there is already another operator there
|
[
"adds",
"an",
"operator",
"to",
"a",
"field",
"handling",
"the",
"case",
"where",
"there",
"is",
"already",
"another",
"operator",
"there"
] |
c11bb6ac860ad1b9b30ccd1936ab0ca28d4e5d6b
|
https://github.com/fresheneesz/mongo-parse/blob/c11bb6ac860ad1b9b30ccd1936ab0ca28d4e5d6b/mapValues.js#L88-L94
|
train
|
fresheneesz/mongo-parse
|
matches.js
|
mongoEqual
|
function mongoEqual(documentValue,queryOperand) {
if(documentValue instanceof Array) {
if(!(queryOperand instanceof Array))
return false
if(documentValue.length !== queryOperand.length) {
return false
} else {
return documentValue.reduce(function(previousValue, currentValue, index) {
return previousValue && mongoEqual(currentValue,queryOperand[index])
}, true)
}
} else if(documentValue instanceof Object) {
if(!(queryOperand instanceof Object))
return false
var aKeys = Object.keys(documentValue)
var bKeys = Object.keys(queryOperand)
if(aKeys.length !== bKeys.length) {
return false
} else {
for(var n=0; n<aKeys.length; n++) {
if(aKeys[n] !== bKeys[n]) return false
var key = aKeys[n]
var aVal = documentValue[key]
var bVal = queryOperand[key]
if(!mongoEqual(aVal,bVal)) {
return false
}
}
// else
return true
}
} else {
if(queryOperand === null) {
return documentValue === undefined || documentValue === null
} else {
return documentValue===queryOperand
}
}
}
|
javascript
|
function mongoEqual(documentValue,queryOperand) {
if(documentValue instanceof Array) {
if(!(queryOperand instanceof Array))
return false
if(documentValue.length !== queryOperand.length) {
return false
} else {
return documentValue.reduce(function(previousValue, currentValue, index) {
return previousValue && mongoEqual(currentValue,queryOperand[index])
}, true)
}
} else if(documentValue instanceof Object) {
if(!(queryOperand instanceof Object))
return false
var aKeys = Object.keys(documentValue)
var bKeys = Object.keys(queryOperand)
if(aKeys.length !== bKeys.length) {
return false
} else {
for(var n=0; n<aKeys.length; n++) {
if(aKeys[n] !== bKeys[n]) return false
var key = aKeys[n]
var aVal = documentValue[key]
var bVal = queryOperand[key]
if(!mongoEqual(aVal,bVal)) {
return false
}
}
// else
return true
}
} else {
if(queryOperand === null) {
return documentValue === undefined || documentValue === null
} else {
return documentValue===queryOperand
}
}
}
|
[
"function",
"mongoEqual",
"(",
"documentValue",
",",
"queryOperand",
")",
"{",
"if",
"(",
"documentValue",
"instanceof",
"Array",
")",
"{",
"if",
"(",
"!",
"(",
"queryOperand",
"instanceof",
"Array",
")",
")",
"return",
"false",
"if",
"(",
"documentValue",
".",
"length",
"!==",
"queryOperand",
".",
"length",
")",
"{",
"return",
"false",
"}",
"else",
"{",
"return",
"documentValue",
".",
"reduce",
"(",
"function",
"(",
"previousValue",
",",
"currentValue",
",",
"index",
")",
"{",
"return",
"previousValue",
"&&",
"mongoEqual",
"(",
"currentValue",
",",
"queryOperand",
"[",
"index",
"]",
")",
"}",
",",
"true",
")",
"}",
"}",
"else",
"if",
"(",
"documentValue",
"instanceof",
"Object",
")",
"{",
"if",
"(",
"!",
"(",
"queryOperand",
"instanceof",
"Object",
")",
")",
"return",
"false",
"var",
"aKeys",
"=",
"Object",
".",
"keys",
"(",
"documentValue",
")",
"var",
"bKeys",
"=",
"Object",
".",
"keys",
"(",
"queryOperand",
")",
"if",
"(",
"aKeys",
".",
"length",
"!==",
"bKeys",
".",
"length",
")",
"{",
"return",
"false",
"}",
"else",
"{",
"for",
"(",
"var",
"n",
"=",
"0",
";",
"n",
"<",
"aKeys",
".",
"length",
";",
"n",
"++",
")",
"{",
"if",
"(",
"aKeys",
"[",
"n",
"]",
"!==",
"bKeys",
"[",
"n",
"]",
")",
"return",
"false",
"var",
"key",
"=",
"aKeys",
"[",
"n",
"]",
"var",
"aVal",
"=",
"documentValue",
"[",
"key",
"]",
"var",
"bVal",
"=",
"queryOperand",
"[",
"key",
"]",
"if",
"(",
"!",
"mongoEqual",
"(",
"aVal",
",",
"bVal",
")",
")",
"{",
"return",
"false",
"}",
"}",
"return",
"true",
"}",
"}",
"else",
"{",
"if",
"(",
"queryOperand",
"===",
"null",
")",
"{",
"return",
"documentValue",
"===",
"undefined",
"||",
"documentValue",
"===",
"null",
"}",
"else",
"{",
"return",
"documentValue",
"===",
"queryOperand",
"}",
"}",
"}"
] |
matches any value, with mongo's special brand of very strict object equality and weird null matching
|
[
"matches",
"any",
"value",
"with",
"mongo",
"s",
"special",
"brand",
"of",
"very",
"strict",
"object",
"equality",
"and",
"weird",
"null",
"matching"
] |
c11bb6ac860ad1b9b30ccd1936ab0ca28d4e5d6b
|
https://github.com/fresheneesz/mongo-parse/blob/c11bb6ac860ad1b9b30ccd1936ab0ca28d4e5d6b/matches.js#L208-L250
|
train
|
fresheneesz/mongo-parse
|
mongoParse.js
|
sortCompare
|
function sortCompare(a,b,sortProperty) {
var aVal = DotNotationPointers(a, sortProperty)[0].val // todo: figure out what mongo does with multiple matching sort properties
var bVal = DotNotationPointers(b, sortProperty)[0].val
if(aVal > bVal) {
return 1
} else if(aVal < bVal) {
return -1
} else {
return 0
}
}
|
javascript
|
function sortCompare(a,b,sortProperty) {
var aVal = DotNotationPointers(a, sortProperty)[0].val // todo: figure out what mongo does with multiple matching sort properties
var bVal = DotNotationPointers(b, sortProperty)[0].val
if(aVal > bVal) {
return 1
} else if(aVal < bVal) {
return -1
} else {
return 0
}
}
|
[
"function",
"sortCompare",
"(",
"a",
",",
"b",
",",
"sortProperty",
")",
"{",
"var",
"aVal",
"=",
"DotNotationPointers",
"(",
"a",
",",
"sortProperty",
")",
"[",
"0",
"]",
".",
"val",
"var",
"bVal",
"=",
"DotNotationPointers",
"(",
"b",
",",
"sortProperty",
")",
"[",
"0",
"]",
".",
"val",
"if",
"(",
"aVal",
">",
"bVal",
")",
"{",
"return",
"1",
"}",
"else",
"if",
"(",
"aVal",
"<",
"bVal",
")",
"{",
"return",
"-",
"1",
"}",
"else",
"{",
"return",
"0",
"}",
"}"
] |
compares two documents by a single sort property
|
[
"compares",
"two",
"documents",
"by",
"a",
"single",
"sort",
"property"
] |
c11bb6ac860ad1b9b30ccd1936ab0ca28d4e5d6b
|
https://github.com/fresheneesz/mongo-parse/blob/c11bb6ac860ad1b9b30ccd1936ab0ca28d4e5d6b/mongoParse.js#L56-L67
|
train
|
fresheneesz/mongo-parse
|
mongoParse.js
|
parseFieldOperator
|
function parseFieldOperator(field, operator, operand) {
if(operator === '$elemMatch') {
var elemMatchInfo = parseElemMatch(operand)
var innerParts = elemMatchInfo.parts
var implicitField = elemMatchInfo.implicitField
} else if(operator === '$not') {
var innerParts = parseNot(field, operand)
} else {
var innerParts = []
}
return new Part(field, operator, operand, innerParts, implicitField)
}
|
javascript
|
function parseFieldOperator(field, operator, operand) {
if(operator === '$elemMatch') {
var elemMatchInfo = parseElemMatch(operand)
var innerParts = elemMatchInfo.parts
var implicitField = elemMatchInfo.implicitField
} else if(operator === '$not') {
var innerParts = parseNot(field, operand)
} else {
var innerParts = []
}
return new Part(field, operator, operand, innerParts, implicitField)
}
|
[
"function",
"parseFieldOperator",
"(",
"field",
",",
"operator",
",",
"operand",
")",
"{",
"if",
"(",
"operator",
"===",
"'$elemMatch'",
")",
"{",
"var",
"elemMatchInfo",
"=",
"parseElemMatch",
"(",
"operand",
")",
"var",
"innerParts",
"=",
"elemMatchInfo",
".",
"parts",
"var",
"implicitField",
"=",
"elemMatchInfo",
".",
"implicitField",
"}",
"else",
"if",
"(",
"operator",
"===",
"'$not'",
")",
"{",
"var",
"innerParts",
"=",
"parseNot",
"(",
"field",
",",
"operand",
")",
"}",
"else",
"{",
"var",
"innerParts",
"=",
"[",
"]",
"}",
"return",
"new",
"Part",
"(",
"field",
",",
"operator",
",",
"operand",
",",
"innerParts",
",",
"implicitField",
")",
"}"
] |
returns a Part object
|
[
"returns",
"a",
"Part",
"object"
] |
c11bb6ac860ad1b9b30ccd1936ab0ca28d4e5d6b
|
https://github.com/fresheneesz/mongo-parse/blob/c11bb6ac860ad1b9b30ccd1936ab0ca28d4e5d6b/mongoParse.js#L256-L267
|
train
|
PSeitz/yamaha-nodejs
|
simpleCommands.js
|
addBasicInfoWrapper
|
function addBasicInfoWrapper(basicInfo) {
Yamaha.prototype[basicInfo] = function(zone) {
return this.getBasicInfo(zone).then(function(result) {
return result[basicInfo]();
});
};
}
|
javascript
|
function addBasicInfoWrapper(basicInfo) {
Yamaha.prototype[basicInfo] = function(zone) {
return this.getBasicInfo(zone).then(function(result) {
return result[basicInfo]();
});
};
}
|
[
"function",
"addBasicInfoWrapper",
"(",
"basicInfo",
")",
"{",
"Yamaha",
".",
"prototype",
"[",
"basicInfo",
"]",
"=",
"function",
"(",
"zone",
")",
"{",
"return",
"this",
".",
"getBasicInfo",
"(",
"zone",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"return",
"result",
"[",
"basicInfo",
"]",
"(",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] |
Add direct functions for basic info
|
[
"Add",
"direct",
"functions",
"for",
"basic",
"info"
] |
1937285ce937d6f351ccf019c97ee7910dcc6be3
|
https://github.com/PSeitz/yamaha-nodejs/blob/1937285ce937d6f351ccf019c97ee7910dcc6be3/simpleCommands.js#L450-L456
|
train
|
madhums/node-view-helpers
|
index.js
|
formatDate
|
function formatDate(date) {
date = new Date(date);
var monthNames = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'June',
'July',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
return (
monthNames[date.getMonth()] +
' ' +
date.getDate() +
', ' +
date.getFullYear()
);
}
|
javascript
|
function formatDate(date) {
date = new Date(date);
var monthNames = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'June',
'July',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
return (
monthNames[date.getMonth()] +
' ' +
date.getDate() +
', ' +
date.getFullYear()
);
}
|
[
"function",
"formatDate",
"(",
"date",
")",
"{",
"date",
"=",
"new",
"Date",
"(",
"date",
")",
";",
"var",
"monthNames",
"=",
"[",
"'Jan'",
",",
"'Feb'",
",",
"'Mar'",
",",
"'Apr'",
",",
"'May'",
",",
"'June'",
",",
"'July'",
",",
"'Aug'",
",",
"'Sep'",
",",
"'Oct'",
",",
"'Nov'",
",",
"'Dec'",
"]",
";",
"return",
"(",
"monthNames",
"[",
"date",
".",
"getMonth",
"(",
")",
"]",
"+",
"' '",
"+",
"date",
".",
"getDate",
"(",
")",
"+",
"', '",
"+",
"date",
".",
"getFullYear",
"(",
")",
")",
";",
"}"
] |
Format date helper
@param {Date} date
@return {String}
@api private
|
[
"Format",
"date",
"helper"
] |
de13d6a3ed7326104a38307eae658153e0628ecf
|
https://github.com/madhums/node-view-helpers/blob/de13d6a3ed7326104a38307eae658153e0628ecf/index.js#L112-L135
|
train
|
madhums/node-view-helpers
|
index.js
|
formatDatetime
|
function formatDatetime(date) {
date = new Date(date);
var hour = date.getHours();
var minutes =
date.getMinutes() < 10
? '0' + date.getMinutes().toString()
: date.getMinutes();
return formatDate(date) + ' ' + hour + ':' + minutes;
}
|
javascript
|
function formatDatetime(date) {
date = new Date(date);
var hour = date.getHours();
var minutes =
date.getMinutes() < 10
? '0' + date.getMinutes().toString()
: date.getMinutes();
return formatDate(date) + ' ' + hour + ':' + minutes;
}
|
[
"function",
"formatDatetime",
"(",
"date",
")",
"{",
"date",
"=",
"new",
"Date",
"(",
"date",
")",
";",
"var",
"hour",
"=",
"date",
".",
"getHours",
"(",
")",
";",
"var",
"minutes",
"=",
"date",
".",
"getMinutes",
"(",
")",
"<",
"10",
"?",
"'0'",
"+",
"date",
".",
"getMinutes",
"(",
")",
".",
"toString",
"(",
")",
":",
"date",
".",
"getMinutes",
"(",
")",
";",
"return",
"formatDate",
"(",
"date",
")",
"+",
"' '",
"+",
"hour",
"+",
"':'",
"+",
"minutes",
";",
"}"
] |
Format date time helper
@param {Date} date
@return {String}
@api private
|
[
"Format",
"date",
"time",
"helper"
] |
de13d6a3ed7326104a38307eae658153e0628ecf
|
https://github.com/madhums/node-view-helpers/blob/de13d6a3ed7326104a38307eae658153e0628ecf/index.js#L145-L154
|
train
|
primus/forwarded-for
|
index.js
|
Forwarded
|
function Forwarded(ip, port, secured) {
this.ip = ip || '127.0.0.1';
this.secure = !!secured;
this.port = +port || 0;
}
|
javascript
|
function Forwarded(ip, port, secured) {
this.ip = ip || '127.0.0.1';
this.secure = !!secured;
this.port = +port || 0;
}
|
[
"function",
"Forwarded",
"(",
"ip",
",",
"port",
",",
"secured",
")",
"{",
"this",
".",
"ip",
"=",
"ip",
"||",
"'127.0.0.1'",
";",
"this",
".",
"secure",
"=",
"!",
"!",
"secured",
";",
"this",
".",
"port",
"=",
"+",
"port",
"||",
"0",
";",
"}"
] |
Forwarded instance.
@constructor
@param {String} ip The IP address.
@param {Number} port The port number.
@param {Boolean} secured The connection was secured.
@api private
|
[
"Forwarded",
"instance",
"."
] |
108afd0458c65b304907f6398bcff48ce83e7761
|
https://github.com/primus/forwarded-for/blob/108afd0458c65b304907f6398bcff48ce83e7761/index.js#L14-L18
|
train
|
primus/forwarded-for
|
index.js
|
forwarded
|
function forwarded(headers, whitelist) {
var ports, port, proto, ips, ip, length = proxies.length, i = 0;
for (; i < length; i++) {
if (!(proxies[i].ip in headers)) continue;
ports = (headers[proxies[i].port] || '').split(',');
ips = (headers[proxies[i].ip] || '').match(pattern);
proto = (headers[proxies[i].proto] || 'http');
//
// As these headers can potentially be set by a 1337H4X0R we need to ensure
// that all supplied values are valid IP addresses. If we receive a none
// IP value inside the IP header field we are going to assume that this
// header has been compromised and should be ignored
//
if (!ips || !ips.every(net.isIP)) return;
port = ports.shift(); // Extract the first port as it's the "source" port.
ip = ips.shift(); // Extract the first IP as it's the "source" IP.
//
// If we were given a white list, we need to ensure that the proxies that
// we're given are known and allowed.
//
if (whitelist && whitelist.length && !ips.every(function every(ip) {
return ~whitelist.indexOf(ip);
})) return;
//
// Shift the most recently found proxy header to the front of the proxies
// array. This optimizes future calls, placing the most commonly found headers
// near the front of the array.
//
if (i !== 0) {
proxies.unshift(proxies.splice(i, 1)[0]);
}
//
// We've gotten a match on a HTTP header, we need to parse it further as it
// could consist of multiple hops. The pattern for multiple hops is:
//
// client, proxy, proxy, proxy, etc.
//
// So extracting the first IP should be sufficient. There are SSL
// terminators like the once's that is used by `fastly.com` which set their
// HTTPS header to `1` as an indication that the connection was secure.
// (This reduces bandwidth)
//
return new Forwarded(ip, port, proto === '1' || proto === 'https');
}
}
|
javascript
|
function forwarded(headers, whitelist) {
var ports, port, proto, ips, ip, length = proxies.length, i = 0;
for (; i < length; i++) {
if (!(proxies[i].ip in headers)) continue;
ports = (headers[proxies[i].port] || '').split(',');
ips = (headers[proxies[i].ip] || '').match(pattern);
proto = (headers[proxies[i].proto] || 'http');
//
// As these headers can potentially be set by a 1337H4X0R we need to ensure
// that all supplied values are valid IP addresses. If we receive a none
// IP value inside the IP header field we are going to assume that this
// header has been compromised and should be ignored
//
if (!ips || !ips.every(net.isIP)) return;
port = ports.shift(); // Extract the first port as it's the "source" port.
ip = ips.shift(); // Extract the first IP as it's the "source" IP.
//
// If we were given a white list, we need to ensure that the proxies that
// we're given are known and allowed.
//
if (whitelist && whitelist.length && !ips.every(function every(ip) {
return ~whitelist.indexOf(ip);
})) return;
//
// Shift the most recently found proxy header to the front of the proxies
// array. This optimizes future calls, placing the most commonly found headers
// near the front of the array.
//
if (i !== 0) {
proxies.unshift(proxies.splice(i, 1)[0]);
}
//
// We've gotten a match on a HTTP header, we need to parse it further as it
// could consist of multiple hops. The pattern for multiple hops is:
//
// client, proxy, proxy, proxy, etc.
//
// So extracting the first IP should be sufficient. There are SSL
// terminators like the once's that is used by `fastly.com` which set their
// HTTPS header to `1` as an indication that the connection was secure.
// (This reduces bandwidth)
//
return new Forwarded(ip, port, proto === '1' || proto === 'https');
}
}
|
[
"function",
"forwarded",
"(",
"headers",
",",
"whitelist",
")",
"{",
"var",
"ports",
",",
"port",
",",
"proto",
",",
"ips",
",",
"ip",
",",
"length",
"=",
"proxies",
".",
"length",
",",
"i",
"=",
"0",
";",
"for",
"(",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"(",
"proxies",
"[",
"i",
"]",
".",
"ip",
"in",
"headers",
")",
")",
"continue",
";",
"ports",
"=",
"(",
"headers",
"[",
"proxies",
"[",
"i",
"]",
".",
"port",
"]",
"||",
"''",
")",
".",
"split",
"(",
"','",
")",
";",
"ips",
"=",
"(",
"headers",
"[",
"proxies",
"[",
"i",
"]",
".",
"ip",
"]",
"||",
"''",
")",
".",
"match",
"(",
"pattern",
")",
";",
"proto",
"=",
"(",
"headers",
"[",
"proxies",
"[",
"i",
"]",
".",
"proto",
"]",
"||",
"'http'",
")",
";",
"if",
"(",
"!",
"ips",
"||",
"!",
"ips",
".",
"every",
"(",
"net",
".",
"isIP",
")",
")",
"return",
";",
"port",
"=",
"ports",
".",
"shift",
"(",
")",
";",
"ip",
"=",
"ips",
".",
"shift",
"(",
")",
";",
"if",
"(",
"whitelist",
"&&",
"whitelist",
".",
"length",
"&&",
"!",
"ips",
".",
"every",
"(",
"function",
"every",
"(",
"ip",
")",
"{",
"return",
"~",
"whitelist",
".",
"indexOf",
"(",
"ip",
")",
";",
"}",
")",
")",
"return",
";",
"if",
"(",
"i",
"!==",
"0",
")",
"{",
"proxies",
".",
"unshift",
"(",
"proxies",
".",
"splice",
"(",
"i",
",",
"1",
")",
"[",
"0",
"]",
")",
";",
"}",
"return",
"new",
"Forwarded",
"(",
"ip",
",",
"port",
",",
"proto",
"===",
"'1'",
"||",
"proto",
"===",
"'https'",
")",
";",
"}",
"}"
] |
Search the headers for a possible match against a known proxy header.
@param {Object} headers The received HTTP headers.
@param {Array} whitelist White list of proxies that should be checked.
@returns {Forwarded|Undefined} A Forwarded address object or nothing.
@api private
|
[
"Search",
"the",
"headers",
"for",
"a",
"possible",
"match",
"against",
"a",
"known",
"proxy",
"header",
"."
] |
108afd0458c65b304907f6398bcff48ce83e7761
|
https://github.com/primus/forwarded-for/blob/108afd0458c65b304907f6398bcff48ce83e7761/index.js#L67-L118
|
train
|
primus/forwarded-for
|
index.js
|
parse
|
function parse(obj, headers, whitelist) {
var proxied = forwarded(headers || {}, whitelist)
, connection = obj.connection
, socket = connection
? connection.socket
: obj.socket;
//
// We should always be testing for HTTP headers as remoteAddress would point
// to proxies.
//
if (proxied) return proxied;
// Check for the property on our given object.
if ('object' === typeof obj) {
if ('remoteAddress' in obj) {
return new Forwarded(
obj.remoteAddress,
obj.remotePort,
'secure' in obj ? obj.secure : obj.encrypted
);
}
// Edge case for Socket.IO 0.9
if ('object' === typeof obj.address && obj.address.address) {
return new Forwarded(
obj.address.address,
obj.address.port,
'secure' in obj ? obj.secure : obj.encrypted
);
}
}
if ('object' === typeof connection && 'remoteAddress' in connection) {
return new Forwarded(
connection.remoteAddress,
connection.remotePort,
'secure' in connection ? connection.secure : connection.encrypted
);
}
if ('object' === typeof socket && 'remoteAddress' in socket) {
return new Forwarded(
socket.remoteAddress,
socket.remoteAddress,
'secure' in socket ? socket.secure : socket.encrypted
);
}
return new Forwarded();
}
|
javascript
|
function parse(obj, headers, whitelist) {
var proxied = forwarded(headers || {}, whitelist)
, connection = obj.connection
, socket = connection
? connection.socket
: obj.socket;
//
// We should always be testing for HTTP headers as remoteAddress would point
// to proxies.
//
if (proxied) return proxied;
// Check for the property on our given object.
if ('object' === typeof obj) {
if ('remoteAddress' in obj) {
return new Forwarded(
obj.remoteAddress,
obj.remotePort,
'secure' in obj ? obj.secure : obj.encrypted
);
}
// Edge case for Socket.IO 0.9
if ('object' === typeof obj.address && obj.address.address) {
return new Forwarded(
obj.address.address,
obj.address.port,
'secure' in obj ? obj.secure : obj.encrypted
);
}
}
if ('object' === typeof connection && 'remoteAddress' in connection) {
return new Forwarded(
connection.remoteAddress,
connection.remotePort,
'secure' in connection ? connection.secure : connection.encrypted
);
}
if ('object' === typeof socket && 'remoteAddress' in socket) {
return new Forwarded(
socket.remoteAddress,
socket.remoteAddress,
'secure' in socket ? socket.secure : socket.encrypted
);
}
return new Forwarded();
}
|
[
"function",
"parse",
"(",
"obj",
",",
"headers",
",",
"whitelist",
")",
"{",
"var",
"proxied",
"=",
"forwarded",
"(",
"headers",
"||",
"{",
"}",
",",
"whitelist",
")",
",",
"connection",
"=",
"obj",
".",
"connection",
",",
"socket",
"=",
"connection",
"?",
"connection",
".",
"socket",
":",
"obj",
".",
"socket",
";",
"if",
"(",
"proxied",
")",
"return",
"proxied",
";",
"if",
"(",
"'object'",
"===",
"typeof",
"obj",
")",
"{",
"if",
"(",
"'remoteAddress'",
"in",
"obj",
")",
"{",
"return",
"new",
"Forwarded",
"(",
"obj",
".",
"remoteAddress",
",",
"obj",
".",
"remotePort",
",",
"'secure'",
"in",
"obj",
"?",
"obj",
".",
"secure",
":",
"obj",
".",
"encrypted",
")",
";",
"}",
"if",
"(",
"'object'",
"===",
"typeof",
"obj",
".",
"address",
"&&",
"obj",
".",
"address",
".",
"address",
")",
"{",
"return",
"new",
"Forwarded",
"(",
"obj",
".",
"address",
".",
"address",
",",
"obj",
".",
"address",
".",
"port",
",",
"'secure'",
"in",
"obj",
"?",
"obj",
".",
"secure",
":",
"obj",
".",
"encrypted",
")",
";",
"}",
"}",
"if",
"(",
"'object'",
"===",
"typeof",
"connection",
"&&",
"'remoteAddress'",
"in",
"connection",
")",
"{",
"return",
"new",
"Forwarded",
"(",
"connection",
".",
"remoteAddress",
",",
"connection",
".",
"remotePort",
",",
"'secure'",
"in",
"connection",
"?",
"connection",
".",
"secure",
":",
"connection",
".",
"encrypted",
")",
";",
"}",
"if",
"(",
"'object'",
"===",
"typeof",
"socket",
"&&",
"'remoteAddress'",
"in",
"socket",
")",
"{",
"return",
"new",
"Forwarded",
"(",
"socket",
".",
"remoteAddress",
",",
"socket",
".",
"remoteAddress",
",",
"'secure'",
"in",
"socket",
"?",
"socket",
".",
"secure",
":",
"socket",
".",
"encrypted",
")",
";",
"}",
"return",
"new",
"Forwarded",
"(",
")",
";",
"}"
] |
Parse out the address information..
@param {Object} obj A socket like object that could contain a `remoteAddress`.
@param {Object} headers The received HTTP headers.
@param {Array} whitelist White list
@returns {Forwarded} A Forwarded address object.
@api private
|
[
"Parse",
"out",
"the",
"address",
"information",
".."
] |
108afd0458c65b304907f6398bcff48ce83e7761
|
https://github.com/primus/forwarded-for/blob/108afd0458c65b304907f6398bcff48ce83e7761/index.js#L129-L179
|
train
|
Pearson-Higher-Ed/elements-sdk
|
src/components/PhoneNumber/components/Input.js
|
parse_partial_number
|
function parse_partial_number(value, country_code, metadata)
{
// "As you type" formatter
const formatter = new as_you_type(country_code, metadata)
// Input partially entered phone number
formatter.input('+' + getPhoneCode(country_code) + value)
// Return the parsed partial phone number
// (has `.national_number`, `.country`, etc)
return formatter
}
|
javascript
|
function parse_partial_number(value, country_code, metadata)
{
// "As you type" formatter
const formatter = new as_you_type(country_code, metadata)
// Input partially entered phone number
formatter.input('+' + getPhoneCode(country_code) + value)
// Return the parsed partial phone number
// (has `.national_number`, `.country`, etc)
return formatter
}
|
[
"function",
"parse_partial_number",
"(",
"value",
",",
"country_code",
",",
"metadata",
")",
"{",
"const",
"formatter",
"=",
"new",
"as_you_type",
"(",
"country_code",
",",
"metadata",
")",
"formatter",
".",
"input",
"(",
"'+'",
"+",
"getPhoneCode",
"(",
"country_code",
")",
"+",
"value",
")",
"return",
"formatter",
"}"
] |
Parses a partially entered phone number and returns the national number so far. Not using `libphonenumber-js`'s `parse` function here because `parse` only works when the number is fully entered, and this one is for partially entered number.
|
[
"Parses",
"a",
"partially",
"entered",
"phone",
"number",
"and",
"returns",
"the",
"national",
"number",
"so",
"far",
".",
"Not",
"using",
"libphonenumber",
"-",
"js",
"s",
"parse",
"function",
"here",
"because",
"parse",
"only",
"works",
"when",
"the",
"number",
"is",
"fully",
"entered",
"and",
"this",
"one",
"is",
"for",
"partially",
"entered",
"number",
"."
] |
3d2fbda6dc110ff244b141c37a5171ec2fb222c3
|
https://github.com/Pearson-Higher-Ed/elements-sdk/blob/3d2fbda6dc110ff244b141c37a5171ec2fb222c3/src/components/PhoneNumber/components/Input.js#L1136-L1147
|
train
|
Pearson-Higher-Ed/elements-sdk
|
src/components/PhoneNumber/components/Input.js
|
e164
|
function e164(value, country_code, metadata)
{
if (!value)
{
return undefined
}
// If the phone number is being input in an international format
if (value[0] === '+')
{
// If it's just the `+` sign
if (value.length === 1)
{
return undefined
}
// If there are some digits, the `value` is returned as is
return value
}
// For non-international phone number a country code is required
if (!country_code)
{
return undefined
}
// The phone number is being input in a country-specific format
const partial_national_number = parse_partial_number(value, country_code).national_number
if (!partial_national_number)
{
return undefined
}
// The value is converted to international plaintext
return format(partial_national_number, country_code, 'International_plaintext', metadata)
}
|
javascript
|
function e164(value, country_code, metadata)
{
if (!value)
{
return undefined
}
// If the phone number is being input in an international format
if (value[0] === '+')
{
// If it's just the `+` sign
if (value.length === 1)
{
return undefined
}
// If there are some digits, the `value` is returned as is
return value
}
// For non-international phone number a country code is required
if (!country_code)
{
return undefined
}
// The phone number is being input in a country-specific format
const partial_national_number = parse_partial_number(value, country_code).national_number
if (!partial_national_number)
{
return undefined
}
// The value is converted to international plaintext
return format(partial_national_number, country_code, 'International_plaintext', metadata)
}
|
[
"function",
"e164",
"(",
"value",
",",
"country_code",
",",
"metadata",
")",
"{",
"if",
"(",
"!",
"value",
")",
"{",
"return",
"undefined",
"}",
"if",
"(",
"value",
"[",
"0",
"]",
"===",
"'+'",
")",
"{",
"if",
"(",
"value",
".",
"length",
"===",
"1",
")",
"{",
"return",
"undefined",
"}",
"return",
"value",
"}",
"if",
"(",
"!",
"country_code",
")",
"{",
"return",
"undefined",
"}",
"const",
"partial_national_number",
"=",
"parse_partial_number",
"(",
"value",
",",
"country_code",
")",
".",
"national_number",
"if",
"(",
"!",
"partial_national_number",
")",
"{",
"return",
"undefined",
"}",
"return",
"format",
"(",
"partial_national_number",
",",
"country_code",
",",
"'International_plaintext'",
",",
"metadata",
")",
"}"
] |
Converts `value` to E.164 phone number format
|
[
"Converts",
"value",
"to",
"E",
".",
"164",
"phone",
"number",
"format"
] |
3d2fbda6dc110ff244b141c37a5171ec2fb222c3
|
https://github.com/Pearson-Higher-Ed/elements-sdk/blob/3d2fbda6dc110ff244b141c37a5171ec2fb222c3/src/components/PhoneNumber/components/Input.js#L1150-L1187
|
train
|
Pearson-Higher-Ed/elements-sdk
|
src/components/PhoneNumber/components/Input.js
|
get_country_option_icon
|
function get_country_option_icon(countryCode, { flags, flagsPath, flagComponent })
{
if (flags === false)
{
return undefined
}
if (flags && flags[countryCode])
{
return flags[countryCode]
}
return React.createElement(flagComponent, { countryCode, flagsPath })
}
|
javascript
|
function get_country_option_icon(countryCode, { flags, flagsPath, flagComponent })
{
if (flags === false)
{
return undefined
}
if (flags && flags[countryCode])
{
return flags[countryCode]
}
return React.createElement(flagComponent, { countryCode, flagsPath })
}
|
[
"function",
"get_country_option_icon",
"(",
"countryCode",
",",
"{",
"flags",
",",
"flagsPath",
",",
"flagComponent",
"}",
")",
"{",
"if",
"(",
"flags",
"===",
"false",
")",
"{",
"return",
"undefined",
"}",
"if",
"(",
"flags",
"&&",
"flags",
"[",
"countryCode",
"]",
")",
"{",
"return",
"flags",
"[",
"countryCode",
"]",
"}",
"return",
"React",
".",
"createElement",
"(",
"flagComponent",
",",
"{",
"countryCode",
",",
"flagsPath",
"}",
")",
"}"
] |
Gets country flag element by country code
|
[
"Gets",
"country",
"flag",
"element",
"by",
"country",
"code"
] |
3d2fbda6dc110ff244b141c37a5171ec2fb222c3
|
https://github.com/Pearson-Higher-Ed/elements-sdk/blob/3d2fbda6dc110ff244b141c37a5171ec2fb222c3/src/components/PhoneNumber/components/Input.js#L1190-L1203
|
train
|
Pearson-Higher-Ed/elements-sdk
|
src/components/PhoneNumber/components/Input.js
|
should_add_international_option
|
function should_add_international_option(properties)
{
const { countries, international } = properties
// If this behaviour is explicitly set, then do as it says.
if (international !== undefined)
{
return international
}
// If `countries` is empty,
// then only "International" option is available, so add it.
if (countries.length === 0)
{
return true
}
// If `countries` is a single allowed country,
// then don't add the "International" option
// because it would make no sense.
if (countries.length === 1)
{
return false
}
// Show the "International" option by default
return true
}
|
javascript
|
function should_add_international_option(properties)
{
const { countries, international } = properties
// If this behaviour is explicitly set, then do as it says.
if (international !== undefined)
{
return international
}
// If `countries` is empty,
// then only "International" option is available, so add it.
if (countries.length === 0)
{
return true
}
// If `countries` is a single allowed country,
// then don't add the "International" option
// because it would make no sense.
if (countries.length === 1)
{
return false
}
// Show the "International" option by default
return true
}
|
[
"function",
"should_add_international_option",
"(",
"properties",
")",
"{",
"const",
"{",
"countries",
",",
"international",
"}",
"=",
"properties",
"if",
"(",
"international",
"!==",
"undefined",
")",
"{",
"return",
"international",
"}",
"if",
"(",
"countries",
".",
"length",
"===",
"0",
")",
"{",
"return",
"true",
"}",
"if",
"(",
"countries",
".",
"length",
"===",
"1",
")",
"{",
"return",
"false",
"}",
"return",
"true",
"}"
] |
Whether to add the "International" option to the list of countries
|
[
"Whether",
"to",
"add",
"the",
"International",
"option",
"to",
"the",
"list",
"of",
"countries"
] |
3d2fbda6dc110ff244b141c37a5171ec2fb222c3
|
https://github.com/Pearson-Higher-Ed/elements-sdk/blob/3d2fbda6dc110ff244b141c37a5171ec2fb222c3/src/components/PhoneNumber/components/Input.js#L1206-L1233
|
train
|
Pearson-Higher-Ed/elements-sdk
|
src/components/PhoneNumber/components/Input.js
|
could_phone_number_belong_to_country
|
function could_phone_number_belong_to_country(phone_number, country_code, metadata)
{
// Strip the leading `+`
const phone_number_digits = phone_number.slice('+'.length)
for (const country_phone_code of Object.keys(metadata.country_phone_code_to_countries))
{
const possible_country_phone_code = phone_number_digits.substring(0, country_phone_code.length)
if (country_phone_code.indexOf(possible_country_phone_code) === 0)
{
// This country phone code is possible.
// Does the given country correspond to this country phone code.
if (metadata.country_phone_code_to_countries[country_phone_code].indexOf(country_code) >= 0)
{
return true
}
}
}
}
|
javascript
|
function could_phone_number_belong_to_country(phone_number, country_code, metadata)
{
// Strip the leading `+`
const phone_number_digits = phone_number.slice('+'.length)
for (const country_phone_code of Object.keys(metadata.country_phone_code_to_countries))
{
const possible_country_phone_code = phone_number_digits.substring(0, country_phone_code.length)
if (country_phone_code.indexOf(possible_country_phone_code) === 0)
{
// This country phone code is possible.
// Does the given country correspond to this country phone code.
if (metadata.country_phone_code_to_countries[country_phone_code].indexOf(country_code) >= 0)
{
return true
}
}
}
}
|
[
"function",
"could_phone_number_belong_to_country",
"(",
"phone_number",
",",
"country_code",
",",
"metadata",
")",
"{",
"const",
"phone_number_digits",
"=",
"phone_number",
".",
"slice",
"(",
"'+'",
".",
"length",
")",
"for",
"(",
"const",
"country_phone_code",
"of",
"Object",
".",
"keys",
"(",
"metadata",
".",
"country_phone_code_to_countries",
")",
")",
"{",
"const",
"possible_country_phone_code",
"=",
"phone_number_digits",
".",
"substring",
"(",
"0",
",",
"country_phone_code",
".",
"length",
")",
"if",
"(",
"country_phone_code",
".",
"indexOf",
"(",
"possible_country_phone_code",
")",
"===",
"0",
")",
"{",
"if",
"(",
"metadata",
".",
"country_phone_code_to_countries",
"[",
"country_phone_code",
"]",
".",
"indexOf",
"(",
"country_code",
")",
">=",
"0",
")",
"{",
"return",
"true",
"}",
"}",
"}",
"}"
] |
Is it possible that the partially entered phone number belongs to the given country
|
[
"Is",
"it",
"possible",
"that",
"the",
"partially",
"entered",
"phone",
"number",
"belongs",
"to",
"the",
"given",
"country"
] |
3d2fbda6dc110ff244b141c37a5171ec2fb222c3
|
https://github.com/Pearson-Higher-Ed/elements-sdk/blob/3d2fbda6dc110ff244b141c37a5171ec2fb222c3/src/components/PhoneNumber/components/Input.js#L1236-L1254
|
train
|
Pearson-Higher-Ed/elements-sdk
|
src/components/PhoneNumber/components/Input.js
|
normalize_country_code
|
function normalize_country_code(country, dictionary)
{
// Normalize `country` if it's an empty string
if (country === '')
{
country = undefined
}
// No country is selected ("International")
if (country === undefined || country === null)
{
return country
}
// Check that `country` code exists
if (dictionary[country] || default_dictionary[country])
{
return country
}
throw new Error(`Unknown country: "${country}"`)
}
|
javascript
|
function normalize_country_code(country, dictionary)
{
// Normalize `country` if it's an empty string
if (country === '')
{
country = undefined
}
// No country is selected ("International")
if (country === undefined || country === null)
{
return country
}
// Check that `country` code exists
if (dictionary[country] || default_dictionary[country])
{
return country
}
throw new Error(`Unknown country: "${country}"`)
}
|
[
"function",
"normalize_country_code",
"(",
"country",
",",
"dictionary",
")",
"{",
"if",
"(",
"country",
"===",
"''",
")",
"{",
"country",
"=",
"undefined",
"}",
"if",
"(",
"country",
"===",
"undefined",
"||",
"country",
"===",
"null",
")",
"{",
"return",
"country",
"}",
"if",
"(",
"dictionary",
"[",
"country",
"]",
"||",
"default_dictionary",
"[",
"country",
"]",
")",
"{",
"return",
"country",
"}",
"throw",
"new",
"Error",
"(",
"`",
"${",
"country",
"}",
"`",
")",
"}"
] |
Validates country code
|
[
"Validates",
"country",
"code"
] |
3d2fbda6dc110ff244b141c37a5171ec2fb222c3
|
https://github.com/Pearson-Higher-Ed/elements-sdk/blob/3d2fbda6dc110ff244b141c37a5171ec2fb222c3/src/components/PhoneNumber/components/Input.js#L1277-L1298
|
train
|
jarrodconnolly/sequelize-slugify
|
lib/sequelize-slugify.js
|
function (instance, sourceFields) {
var slugParts = sourceFields.map(function (slugSourceField) {
return instance[slugSourceField];
});
var options = (slugOptions && slugOptions.slugOptions) || { lower: true};
return slug(slugParts.join(' '), options);
}
|
javascript
|
function (instance, sourceFields) {
var slugParts = sourceFields.map(function (slugSourceField) {
return instance[slugSourceField];
});
var options = (slugOptions && slugOptions.slugOptions) || { lower: true};
return slug(slugParts.join(' '), options);
}
|
[
"function",
"(",
"instance",
",",
"sourceFields",
")",
"{",
"var",
"slugParts",
"=",
"sourceFields",
".",
"map",
"(",
"function",
"(",
"slugSourceField",
")",
"{",
"return",
"instance",
"[",
"slugSourceField",
"]",
";",
"}",
")",
";",
"var",
"options",
"=",
"(",
"slugOptions",
"&&",
"slugOptions",
".",
"slugOptions",
")",
"||",
"{",
"lower",
":",
"true",
"}",
";",
"return",
"slug",
"(",
"slugParts",
".",
"join",
"(",
"' '",
")",
",",
"options",
")",
";",
"}"
] |
takes the array of source fields from the model instance and builds the slug
|
[
"takes",
"the",
"array",
"of",
"source",
"fields",
"from",
"the",
"model",
"instance",
"and",
"builds",
"the",
"slug"
] |
1138e1bbca04cd7a9e7f7caca4ef18dfc512b041
|
https://github.com/jarrodconnolly/sequelize-slugify/blob/1138e1bbca04cd7a9e7f7caca4ef18dfc512b041/lib/sequelize-slugify.js#L17-L24
|
train
|
|
jarrodconnolly/sequelize-slugify
|
lib/sequelize-slugify.js
|
function (slug) {
var query = { where: {} };
query.where[slugColumn] = slug;
return Model.findOne(query).then(function (model) {
return model === null;
});
}
|
javascript
|
function (slug) {
var query = { where: {} };
query.where[slugColumn] = slug;
return Model.findOne(query).then(function (model) {
return model === null;
});
}
|
[
"function",
"(",
"slug",
")",
"{",
"var",
"query",
"=",
"{",
"where",
":",
"{",
"}",
"}",
";",
"query",
".",
"where",
"[",
"slugColumn",
"]",
"=",
"slug",
";",
"return",
"Model",
".",
"findOne",
"(",
"query",
")",
".",
"then",
"(",
"function",
"(",
"model",
")",
"{",
"return",
"model",
"===",
"null",
";",
"}",
")",
";",
"}"
] |
Checks whether or not the slug is already in use.
@param slug The slug to check for uniqueness.
@return True if the slug is unique, false otherwise.
|
[
"Checks",
"whether",
"or",
"not",
"the",
"slug",
"is",
"already",
"in",
"use",
"."
] |
1138e1bbca04cd7a9e7f7caca4ef18dfc512b041
|
https://github.com/jarrodconnolly/sequelize-slugify/blob/1138e1bbca04cd7a9e7f7caca4ef18dfc512b041/lib/sequelize-slugify.js#L32-L39
|
train
|
|
jarrodconnolly/sequelize-slugify
|
lib/sequelize-slugify.js
|
function (instance, sourceFields, suffixFields) {
return (function suffixHelper(instance, sourceFields, suffixFields, suffixCount) {
if (!suffixFields || !Array.isArray(suffixFields)) {
return Promise.resolve(null);
}
if (suffixCount > suffixFields.length) {
return Promise.resolve(slugifyFields(instance, slugOptions.source.concat(suffixFields.slice(0))));
}
var slug = slugifyFields(instance, slugOptions.source.concat(suffixFields.slice(0, suffixCount)));
return checkSlug(slug).then(function (isUnique) {
if (isUnique) {
return slug;
}
return suffixHelper(instance, sourceFields, suffixFields, suffixCount + 1);
});
})(instance, sourceFields, suffixFields, 1);
}
|
javascript
|
function (instance, sourceFields, suffixFields) {
return (function suffixHelper(instance, sourceFields, suffixFields, suffixCount) {
if (!suffixFields || !Array.isArray(suffixFields)) {
return Promise.resolve(null);
}
if (suffixCount > suffixFields.length) {
return Promise.resolve(slugifyFields(instance, slugOptions.source.concat(suffixFields.slice(0))));
}
var slug = slugifyFields(instance, slugOptions.source.concat(suffixFields.slice(0, suffixCount)));
return checkSlug(slug).then(function (isUnique) {
if (isUnique) {
return slug;
}
return suffixHelper(instance, sourceFields, suffixFields, suffixCount + 1);
});
})(instance, sourceFields, suffixFields, 1);
}
|
[
"function",
"(",
"instance",
",",
"sourceFields",
",",
"suffixFields",
")",
"{",
"return",
"(",
"function",
"suffixHelper",
"(",
"instance",
",",
"sourceFields",
",",
"suffixFields",
",",
"suffixCount",
")",
"{",
"if",
"(",
"!",
"suffixFields",
"||",
"!",
"Array",
".",
"isArray",
"(",
"suffixFields",
")",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"null",
")",
";",
"}",
"if",
"(",
"suffixCount",
">",
"suffixFields",
".",
"length",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"slugifyFields",
"(",
"instance",
",",
"slugOptions",
".",
"source",
".",
"concat",
"(",
"suffixFields",
".",
"slice",
"(",
"0",
")",
")",
")",
")",
";",
"}",
"var",
"slug",
"=",
"slugifyFields",
"(",
"instance",
",",
"slugOptions",
".",
"source",
".",
"concat",
"(",
"suffixFields",
".",
"slice",
"(",
"0",
",",
"suffixCount",
")",
")",
")",
";",
"return",
"checkSlug",
"(",
"slug",
")",
".",
"then",
"(",
"function",
"(",
"isUnique",
")",
"{",
"if",
"(",
"isUnique",
")",
"{",
"return",
"slug",
";",
"}",
"return",
"suffixHelper",
"(",
"instance",
",",
"sourceFields",
",",
"suffixFields",
",",
"suffixCount",
"+",
"1",
")",
";",
"}",
")",
";",
"}",
")",
"(",
"instance",
",",
"sourceFields",
",",
"suffixFields",
",",
"1",
")",
";",
"}"
] |
Adds on additional suffixes based on the specified suffix fields.
@param instance The model instance to use.
@param sourceFields An array of source fields to use to generate the base slug.
@param suffixFields An array of suffix fields to use to generate the additional slug suffixes.
@return A promise that resolves to a slug once a unique one is found or all of the suffix fields have been exhausted. Returns null if no suffix fields are provided.
|
[
"Adds",
"on",
"additional",
"suffixes",
"based",
"on",
"the",
"specified",
"suffix",
"fields",
"."
] |
1138e1bbca04cd7a9e7f7caca4ef18dfc512b041
|
https://github.com/jarrodconnolly/sequelize-slugify/blob/1138e1bbca04cd7a9e7f7caca4ef18dfc512b041/lib/sequelize-slugify.js#L49-L69
|
train
|
|
cdmbase/fullstack-pro
|
tools/cli/helpers/util.js
|
renameFiles
|
function renameFiles(destinationPath, moduleName) {
const Module = pascalize(moduleName);
// change to destination directory
shell.cd(destinationPath);
// rename files
shell.ls('-Rl', '.').forEach(entry => {
if (entry.isFile()) {
shell.mv(entry.name, entry.name.replace('Module', Module));
}
});
// replace module names
shell.ls('-Rl', '.').forEach(entry => {
if (entry.isFile()) {
shell.sed('-i', /\$module\$/g, moduleName, entry.name);
shell.sed('-i', /\$_module\$/g, decamelize(moduleName), entry.name);
shell.sed('-i', /\$Module\$/g, Module, entry.name);
shell.sed('-i', /\$MoDuLe\$/g, startCase(moduleName), entry.name);
shell.sed('-i', /\$MODULE\$/g, moduleName.toUpperCase(), entry.name);
}
});
}
|
javascript
|
function renameFiles(destinationPath, moduleName) {
const Module = pascalize(moduleName);
// change to destination directory
shell.cd(destinationPath);
// rename files
shell.ls('-Rl', '.').forEach(entry => {
if (entry.isFile()) {
shell.mv(entry.name, entry.name.replace('Module', Module));
}
});
// replace module names
shell.ls('-Rl', '.').forEach(entry => {
if (entry.isFile()) {
shell.sed('-i', /\$module\$/g, moduleName, entry.name);
shell.sed('-i', /\$_module\$/g, decamelize(moduleName), entry.name);
shell.sed('-i', /\$Module\$/g, Module, entry.name);
shell.sed('-i', /\$MoDuLe\$/g, startCase(moduleName), entry.name);
shell.sed('-i', /\$MODULE\$/g, moduleName.toUpperCase(), entry.name);
}
});
}
|
[
"function",
"renameFiles",
"(",
"destinationPath",
",",
"moduleName",
")",
"{",
"const",
"Module",
"=",
"pascalize",
"(",
"moduleName",
")",
";",
"shell",
".",
"cd",
"(",
"destinationPath",
")",
";",
"shell",
".",
"ls",
"(",
"'-Rl'",
",",
"'.'",
")",
".",
"forEach",
"(",
"entry",
"=>",
"{",
"if",
"(",
"entry",
".",
"isFile",
"(",
")",
")",
"{",
"shell",
".",
"mv",
"(",
"entry",
".",
"name",
",",
"entry",
".",
"name",
".",
"replace",
"(",
"'Module'",
",",
"Module",
")",
")",
";",
"}",
"}",
")",
";",
"shell",
".",
"ls",
"(",
"'-Rl'",
",",
"'.'",
")",
".",
"forEach",
"(",
"entry",
"=>",
"{",
"if",
"(",
"entry",
".",
"isFile",
"(",
")",
")",
"{",
"shell",
".",
"sed",
"(",
"'-i'",
",",
"/",
"\\$module\\$",
"/",
"g",
",",
"moduleName",
",",
"entry",
".",
"name",
")",
";",
"shell",
".",
"sed",
"(",
"'-i'",
",",
"/",
"\\$_module\\$",
"/",
"g",
",",
"decamelize",
"(",
"moduleName",
")",
",",
"entry",
".",
"name",
")",
";",
"shell",
".",
"sed",
"(",
"'-i'",
",",
"/",
"\\$Module\\$",
"/",
"g",
",",
"Module",
",",
"entry",
".",
"name",
")",
";",
"shell",
".",
"sed",
"(",
"'-i'",
",",
"/",
"\\$MoDuLe\\$",
"/",
"g",
",",
"startCase",
"(",
"moduleName",
")",
",",
"entry",
".",
"name",
")",
";",
"shell",
".",
"sed",
"(",
"'-i'",
",",
"/",
"\\$MODULE\\$",
"/",
"g",
",",
"moduleName",
".",
"toUpperCase",
"(",
")",
",",
"entry",
".",
"name",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Renames the templates in the destination directory.
@param destinationPath - The destination path of a new module.
@param moduleName - The name of a new module.
|
[
"Renames",
"the",
"templates",
"in",
"the",
"destination",
"directory",
"."
] |
6068d060443f2ab7a26e72f95f5f3b66194892eb
|
https://github.com/cdmbase/fullstack-pro/blob/6068d060443f2ab7a26e72f95f5f3b66194892eb/tools/cli/helpers/util.js#L24-L47
|
train
|
moreartyjs/moreartyjs
|
src/Util.js
|
function (f, cont) {
var result = f();
if (result && typeof result.always === 'function') {
result.always(cont);
} else {
cont();
}
}
|
javascript
|
function (f, cont) {
var result = f();
if (result && typeof result.always === 'function') {
result.always(cont);
} else {
cont();
}
}
|
[
"function",
"(",
"f",
",",
"cont",
")",
"{",
"var",
"result",
"=",
"f",
"(",
")",
";",
"if",
"(",
"result",
"&&",
"typeof",
"result",
".",
"always",
"===",
"'function'",
")",
"{",
"result",
".",
"always",
"(",
"cont",
")",
";",
"}",
"else",
"{",
"cont",
"(",
")",
";",
"}",
"}"
] |
Execute function f, then function cont. If f returns a promise, cont is executed when the promise resolves.
@param {Function} f function to execute first
@param {Function} cont function to execute after f
@memberOf Util
|
[
"Execute",
"function",
"f",
"then",
"function",
"cont",
".",
"If",
"f",
"returns",
"a",
"promise",
"cont",
"is",
"executed",
"when",
"the",
"promise",
"resolves",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Util.js#L67-L74
|
train
|
|
moreartyjs/moreartyjs
|
src/Util.js
|
function (arr, pred) {
for (var i = 0; i < arr.length; i++) {
var value = arr[i];
if (pred(value, i, arr)) {
return value;
}
}
return null;
}
|
javascript
|
function (arr, pred) {
for (var i = 0; i < arr.length; i++) {
var value = arr[i];
if (pred(value, i, arr)) {
return value;
}
}
return null;
}
|
[
"function",
"(",
"arr",
",",
"pred",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"value",
"=",
"arr",
"[",
"i",
"]",
";",
"if",
"(",
"pred",
"(",
"value",
",",
"i",
",",
"arr",
")",
")",
"{",
"return",
"value",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
Find array element satisfying the predicate.
@param {Array} arr array
@param {Function} pred predicate accepting current value, index, original array
@return {*} found value or null
@memberOf Util
|
[
"Find",
"array",
"element",
"satisfying",
"the",
"predicate",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Util.js#L97-L105
|
train
|
|
moreartyjs/moreartyjs
|
src/Util.js
|
function (path1, path2) {
return path1.length === 0 ? path2 :
(path2.length === 0 ? path1 : path1.concat(path2));
}
|
javascript
|
function (path1, path2) {
return path1.length === 0 ? path2 :
(path2.length === 0 ? path1 : path1.concat(path2));
}
|
[
"function",
"(",
"path1",
",",
"path2",
")",
"{",
"return",
"path1",
".",
"length",
"===",
"0",
"?",
"path2",
":",
"(",
"path2",
".",
"length",
"===",
"0",
"?",
"path1",
":",
"path1",
".",
"concat",
"(",
"path2",
")",
")",
";",
"}"
] |
Join two array paths.
@param {Array} path1 array of string and numbers
@param {Array} path2 array of string and numbers
@returns {Array} joined path
@memberOf Util
|
[
"Join",
"two",
"array",
"paths",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Util.js#L176-L179
|
train
|
|
moreartyjs/moreartyjs
|
src/Util.js
|
function (target, firstSource) {
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
var hasPendingException = false;
var pendingException;
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null)
continue;
var keysArray = Object.keys(Object(nextSource));
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
try {
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable)
to[nextKey] = nextSource[nextKey];
} catch (e) {
if (!hasPendingException) {
hasPendingException = true;
pendingException = e;
}
}
}
if (hasPendingException)
throw pendingException;
}
return to;
}
|
javascript
|
function (target, firstSource) {
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
var hasPendingException = false;
var pendingException;
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null)
continue;
var keysArray = Object.keys(Object(nextSource));
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
try {
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable)
to[nextKey] = nextSource[nextKey];
} catch (e) {
if (!hasPendingException) {
hasPendingException = true;
pendingException = e;
}
}
}
if (hasPendingException)
throw pendingException;
}
return to;
}
|
[
"function",
"(",
"target",
",",
"firstSource",
")",
"{",
"if",
"(",
"target",
"===",
"undefined",
"||",
"target",
"===",
"null",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Cannot convert first argument to object'",
")",
";",
"}",
"var",
"to",
"=",
"Object",
"(",
"target",
")",
";",
"var",
"hasPendingException",
"=",
"false",
";",
"var",
"pendingException",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"nextSource",
"=",
"arguments",
"[",
"i",
"]",
";",
"if",
"(",
"nextSource",
"===",
"undefined",
"||",
"nextSource",
"===",
"null",
")",
"continue",
";",
"var",
"keysArray",
"=",
"Object",
".",
"keys",
"(",
"Object",
"(",
"nextSource",
")",
")",
";",
"for",
"(",
"var",
"nextIndex",
"=",
"0",
",",
"len",
"=",
"keysArray",
".",
"length",
";",
"nextIndex",
"<",
"len",
";",
"nextIndex",
"++",
")",
"{",
"var",
"nextKey",
"=",
"keysArray",
"[",
"nextIndex",
"]",
";",
"try",
"{",
"var",
"desc",
"=",
"Object",
".",
"getOwnPropertyDescriptor",
"(",
"nextSource",
",",
"nextKey",
")",
";",
"if",
"(",
"desc",
"!==",
"undefined",
"&&",
"desc",
".",
"enumerable",
")",
"to",
"[",
"nextKey",
"]",
"=",
"nextSource",
"[",
"nextKey",
"]",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"!",
"hasPendingException",
")",
"{",
"hasPendingException",
"=",
"true",
";",
"pendingException",
"=",
"e",
";",
"}",
"}",
"}",
"if",
"(",
"hasPendingException",
")",
"throw",
"pendingException",
";",
"}",
"return",
"to",
";",
"}"
] |
ES6 Object.assign.
@see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
|
[
"ES6",
"Object",
".",
"assign",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Util.js#L183-L217
|
train
|
|
moreartyjs/moreartyjs
|
src/util/Callback.js
|
function (binding, subpath, f) {
var args = Util.resolveArgs(
arguments,
'binding', function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, '?f'
);
return function (event) {
var value = event.target.value;
binding.set(args.subpath, args.f ? args.f(value) : value);
};
}
|
javascript
|
function (binding, subpath, f) {
var args = Util.resolveArgs(
arguments,
'binding', function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, '?f'
);
return function (event) {
var value = event.target.value;
binding.set(args.subpath, args.f ? args.f(value) : value);
};
}
|
[
"function",
"(",
"binding",
",",
"subpath",
",",
"f",
")",
"{",
"var",
"args",
"=",
"Util",
".",
"resolveArgs",
"(",
"arguments",
",",
"'binding'",
",",
"function",
"(",
"x",
")",
"{",
"return",
"Util",
".",
"canRepresentSubpath",
"(",
"x",
")",
"?",
"'subpath'",
":",
"null",
";",
"}",
",",
"'?f'",
")",
";",
"return",
"function",
"(",
"event",
")",
"{",
"var",
"value",
"=",
"event",
".",
"target",
".",
"value",
";",
"binding",
".",
"set",
"(",
"args",
".",
"subpath",
",",
"args",
".",
"f",
"?",
"args",
".",
"f",
"(",
"value",
")",
":",
"value",
")",
";",
"}",
";",
"}"
] |
Create callback used to set binding value on an event.
@param {Binding} binding binding
@param {String|Array} [subpath] subpath as a dot-separated string or an array of strings and numbers
@param {Function} [f] value transformer
@returns {Function} callback
@memberOf Callback
|
[
"Create",
"callback",
"used",
"to",
"set",
"binding",
"value",
"on",
"an",
"event",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/util/Callback.js#L16-L26
|
train
|
|
moreartyjs/moreartyjs
|
src/util/Callback.js
|
function (binding, subpath, pred) {
var args = Util.resolveArgs(
arguments,
'binding', function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, '?pred'
);
return function (event) {
var value = event.target.value;
if (!args.pred || args.pred(value)) {
binding.remove(args.subpath);
}
};
}
|
javascript
|
function (binding, subpath, pred) {
var args = Util.resolveArgs(
arguments,
'binding', function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, '?pred'
);
return function (event) {
var value = event.target.value;
if (!args.pred || args.pred(value)) {
binding.remove(args.subpath);
}
};
}
|
[
"function",
"(",
"binding",
",",
"subpath",
",",
"pred",
")",
"{",
"var",
"args",
"=",
"Util",
".",
"resolveArgs",
"(",
"arguments",
",",
"'binding'",
",",
"function",
"(",
"x",
")",
"{",
"return",
"Util",
".",
"canRepresentSubpath",
"(",
"x",
")",
"?",
"'subpath'",
":",
"null",
";",
"}",
",",
"'?pred'",
")",
";",
"return",
"function",
"(",
"event",
")",
"{",
"var",
"value",
"=",
"event",
".",
"target",
".",
"value",
";",
"if",
"(",
"!",
"args",
".",
"pred",
"||",
"args",
".",
"pred",
"(",
"value",
")",
")",
"{",
"binding",
".",
"remove",
"(",
"args",
".",
"subpath",
")",
";",
"}",
"}",
";",
"}"
] |
Create callback used to delete binding value on an event.
@param {Binding} binding binding
@param {String|String[]} [subpath] subpath as a dot-separated string or an array of strings and numbers
@param {Function} [pred] predicate
@returns {Function} callback
@memberOf Callback
|
[
"Create",
"callback",
"used",
"to",
"delete",
"binding",
"value",
"on",
"an",
"event",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/util/Callback.js#L34-L46
|
train
|
|
moreartyjs/moreartyjs
|
src/util/Callback.js
|
function (cb, key, shiftKey, ctrlKey) {
var effectiveShiftKey = shiftKey || false;
var effectiveCtrlKey = ctrlKey || false;
return function (event) {
var keyMatched = typeof key === 'string' ?
event.key === key :
Util.find(key, function (k) { return k === event.key; });
if (keyMatched && event.shiftKey === effectiveShiftKey && event.ctrlKey === effectiveCtrlKey) {
cb(event);
}
};
}
|
javascript
|
function (cb, key, shiftKey, ctrlKey) {
var effectiveShiftKey = shiftKey || false;
var effectiveCtrlKey = ctrlKey || false;
return function (event) {
var keyMatched = typeof key === 'string' ?
event.key === key :
Util.find(key, function (k) { return k === event.key; });
if (keyMatched && event.shiftKey === effectiveShiftKey && event.ctrlKey === effectiveCtrlKey) {
cb(event);
}
};
}
|
[
"function",
"(",
"cb",
",",
"key",
",",
"shiftKey",
",",
"ctrlKey",
")",
"{",
"var",
"effectiveShiftKey",
"=",
"shiftKey",
"||",
"false",
";",
"var",
"effectiveCtrlKey",
"=",
"ctrlKey",
"||",
"false",
";",
"return",
"function",
"(",
"event",
")",
"{",
"var",
"keyMatched",
"=",
"typeof",
"key",
"===",
"'string'",
"?",
"event",
".",
"key",
"===",
"key",
":",
"Util",
".",
"find",
"(",
"key",
",",
"function",
"(",
"k",
")",
"{",
"return",
"k",
"===",
"event",
".",
"key",
";",
"}",
")",
";",
"if",
"(",
"keyMatched",
"&&",
"event",
".",
"shiftKey",
"===",
"effectiveShiftKey",
"&&",
"event",
".",
"ctrlKey",
"===",
"effectiveCtrlKey",
")",
"{",
"cb",
"(",
"event",
")",
";",
"}",
"}",
";",
"}"
] |
Create callback invoked when specified key combination is pressed.
@param {Function} cb callback
@param {String|Array} key key
@param {Boolean} [shiftKey] shift key flag
@param {Boolean} [ctrlKey] ctrl key flag
@returns {Function} callback
@memberOf Callback
|
[
"Create",
"callback",
"invoked",
"when",
"specified",
"key",
"combination",
"is",
"pressed",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/util/Callback.js#L55-L67
|
train
|
|
moreartyjs/moreartyjs
|
src/History.js
|
function (binding) {
var historyBinding = getHistoryBinding(binding);
var undo = historyBinding.get('undo');
return !!undo && !undo.isEmpty();
}
|
javascript
|
function (binding) {
var historyBinding = getHistoryBinding(binding);
var undo = historyBinding.get('undo');
return !!undo && !undo.isEmpty();
}
|
[
"function",
"(",
"binding",
")",
"{",
"var",
"historyBinding",
"=",
"getHistoryBinding",
"(",
"binding",
")",
";",
"var",
"undo",
"=",
"historyBinding",
".",
"get",
"(",
"'undo'",
")",
";",
"return",
"!",
"!",
"undo",
"&&",
"!",
"undo",
".",
"isEmpty",
"(",
")",
";",
"}"
] |
Check if history has undo information.
@param {Binding} binding binding
@returns {Boolean}
@memberOf History
|
[
"Check",
"if",
"history",
"has",
"undo",
"information",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/History.js#L118-L122
|
train
|
|
moreartyjs/moreartyjs
|
src/History.js
|
function (binding) {
var historyBinding = getHistoryBinding(binding);
var redo = historyBinding.get('redo');
return !!redo && !redo.isEmpty();
}
|
javascript
|
function (binding) {
var historyBinding = getHistoryBinding(binding);
var redo = historyBinding.get('redo');
return !!redo && !redo.isEmpty();
}
|
[
"function",
"(",
"binding",
")",
"{",
"var",
"historyBinding",
"=",
"getHistoryBinding",
"(",
"binding",
")",
";",
"var",
"redo",
"=",
"historyBinding",
".",
"get",
"(",
"'redo'",
")",
";",
"return",
"!",
"!",
"redo",
"&&",
"!",
"redo",
".",
"isEmpty",
"(",
")",
";",
"}"
] |
Check if history has redo information.
@param {Binding} binding binding
@returns {Boolean}
@memberOf History
|
[
"Check",
"if",
"history",
"has",
"redo",
"information",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/History.js#L128-L132
|
train
|
|
moreartyjs/moreartyjs
|
src/History.js
|
function (binding) {
var historyBinding = getHistoryBinding(binding);
var listenerId = historyBinding.get('listenerId');
var undoBinding = historyBinding.sub('undo');
var redoBinding = historyBinding.sub('redo');
return revert(binding, undoBinding, redoBinding, listenerId, 'oldValue');
}
|
javascript
|
function (binding) {
var historyBinding = getHistoryBinding(binding);
var listenerId = historyBinding.get('listenerId');
var undoBinding = historyBinding.sub('undo');
var redoBinding = historyBinding.sub('redo');
return revert(binding, undoBinding, redoBinding, listenerId, 'oldValue');
}
|
[
"function",
"(",
"binding",
")",
"{",
"var",
"historyBinding",
"=",
"getHistoryBinding",
"(",
"binding",
")",
";",
"var",
"listenerId",
"=",
"historyBinding",
".",
"get",
"(",
"'listenerId'",
")",
";",
"var",
"undoBinding",
"=",
"historyBinding",
".",
"sub",
"(",
"'undo'",
")",
";",
"var",
"redoBinding",
"=",
"historyBinding",
".",
"sub",
"(",
"'redo'",
")",
";",
"return",
"revert",
"(",
"binding",
",",
"undoBinding",
",",
"redoBinding",
",",
"listenerId",
",",
"'oldValue'",
")",
";",
"}"
] |
Revert to previous state.
@param {Binding} binding binding
@returns {Boolean} true, if binding has undo information
@memberOf History
|
[
"Revert",
"to",
"previous",
"state",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/History.js#L138-L144
|
train
|
|
ChristianMurphy/postcss-combine-duplicated-selectors
|
src/index.js
|
normalizeAttributes
|
function normalizeAttributes(selector) {
selector.walkAttributes((node) => {
if (node.value) {
// remove quotes
node.value = node.value.replace(/'|\\'|"|\\"/g, '');
}
});
}
|
javascript
|
function normalizeAttributes(selector) {
selector.walkAttributes((node) => {
if (node.value) {
// remove quotes
node.value = node.value.replace(/'|\\'|"|\\"/g, '');
}
});
}
|
[
"function",
"normalizeAttributes",
"(",
"selector",
")",
"{",
"selector",
".",
"walkAttributes",
"(",
"(",
"node",
")",
"=>",
"{",
"if",
"(",
"node",
".",
"value",
")",
"{",
"node",
".",
"value",
"=",
"node",
".",
"value",
".",
"replace",
"(",
"/",
"'|\\\\'|\"|\\\\\"",
"/",
"g",
",",
"''",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Ensure that attributes with different quotes match.
@param {Object} selector - postcss selector node
|
[
"Ensure",
"that",
"attributes",
"with",
"different",
"quotes",
"match",
"."
] |
9a36f2fd55f8bb3ea6429ae871be4e1251608ea6
|
https://github.com/ChristianMurphy/postcss-combine-duplicated-selectors/blob/9a36f2fd55f8bb3ea6429ae871be4e1251608ea6/src/index.js#L9-L16
|
train
|
ChristianMurphy/postcss-combine-duplicated-selectors
|
src/index.js
|
sortGroups
|
function sortGroups(selector) {
selector.each((subSelector) => {
subSelector.nodes.sort((a, b) => {
// different types cannot be sorted
if (a.type !== b.type) {
return 0;
}
// sort alphabetically
return a.value < b.value ? -1 : 1;
});
});
selector.sort((a, b) => (a.nodes.join('') < b.nodes.join('') ? -1 : 1));
}
|
javascript
|
function sortGroups(selector) {
selector.each((subSelector) => {
subSelector.nodes.sort((a, b) => {
// different types cannot be sorted
if (a.type !== b.type) {
return 0;
}
// sort alphabetically
return a.value < b.value ? -1 : 1;
});
});
selector.sort((a, b) => (a.nodes.join('') < b.nodes.join('') ? -1 : 1));
}
|
[
"function",
"sortGroups",
"(",
"selector",
")",
"{",
"selector",
".",
"each",
"(",
"(",
"subSelector",
")",
"=>",
"{",
"subSelector",
".",
"nodes",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"if",
"(",
"a",
".",
"type",
"!==",
"b",
".",
"type",
")",
"{",
"return",
"0",
";",
"}",
"return",
"a",
".",
"value",
"<",
"b",
".",
"value",
"?",
"-",
"1",
":",
"1",
";",
"}",
")",
";",
"}",
")",
";",
"selector",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"(",
"a",
".",
"nodes",
".",
"join",
"(",
"''",
")",
"<",
"b",
".",
"nodes",
".",
"join",
"(",
"''",
")",
"?",
"-",
"1",
":",
"1",
")",
")",
";",
"}"
] |
Sort class and id groups alphabetically
@param {Object} selector - postcss selector node
|
[
"Sort",
"class",
"and",
"id",
"groups",
"alphabetically"
] |
9a36f2fd55f8bb3ea6429ae871be4e1251608ea6
|
https://github.com/ChristianMurphy/postcss-combine-duplicated-selectors/blob/9a36f2fd55f8bb3ea6429ae871be4e1251608ea6/src/index.js#L22-L36
|
train
|
ChristianMurphy/postcss-combine-duplicated-selectors
|
src/index.js
|
removeDupProperties
|
function removeDupProperties(selector) {
// Remove duplicated properties from bottom to top ()
for (let actIndex = selector.nodes.length - 1; actIndex >= 1; actIndex--) {
for (let befIndex = actIndex - 1; befIndex >= 0; befIndex--) {
if (selector.nodes[actIndex].prop === selector.nodes[befIndex].prop) {
selector.nodes[befIndex].remove();
actIndex--;
}
}
}
}
|
javascript
|
function removeDupProperties(selector) {
// Remove duplicated properties from bottom to top ()
for (let actIndex = selector.nodes.length - 1; actIndex >= 1; actIndex--) {
for (let befIndex = actIndex - 1; befIndex >= 0; befIndex--) {
if (selector.nodes[actIndex].prop === selector.nodes[befIndex].prop) {
selector.nodes[befIndex].remove();
actIndex--;
}
}
}
}
|
[
"function",
"removeDupProperties",
"(",
"selector",
")",
"{",
"for",
"(",
"let",
"actIndex",
"=",
"selector",
".",
"nodes",
".",
"length",
"-",
"1",
";",
"actIndex",
">=",
"1",
";",
"actIndex",
"--",
")",
"{",
"for",
"(",
"let",
"befIndex",
"=",
"actIndex",
"-",
"1",
";",
"befIndex",
">=",
"0",
";",
"befIndex",
"--",
")",
"{",
"if",
"(",
"selector",
".",
"nodes",
"[",
"actIndex",
"]",
".",
"prop",
"===",
"selector",
".",
"nodes",
"[",
"befIndex",
"]",
".",
"prop",
")",
"{",
"selector",
".",
"nodes",
"[",
"befIndex",
"]",
".",
"remove",
"(",
")",
";",
"actIndex",
"--",
";",
"}",
"}",
"}",
"}"
] |
Remove duplicated properties
@param {Object} selector - postcss selector node
|
[
"Remove",
"duplicated",
"properties"
] |
9a36f2fd55f8bb3ea6429ae871be4e1251608ea6
|
https://github.com/ChristianMurphy/postcss-combine-duplicated-selectors/blob/9a36f2fd55f8bb3ea6429ae871be4e1251608ea6/src/index.js#L42-L52
|
train
|
moreartyjs/moreartyjs
|
src/Binding.js
|
function (path, sharedInternals) {
/** @private */
this._path = path || EMPTY_PATH;
/** @protected
* @ignore */
this._sharedInternals = sharedInternals || {};
if (!this._sharedInternals.listeners) {
this._sharedInternals.listeners = {};
}
if (!this._sharedInternals.cache) {
this._sharedInternals.cache = {};
}
}
|
javascript
|
function (path, sharedInternals) {
/** @private */
this._path = path || EMPTY_PATH;
/** @protected
* @ignore */
this._sharedInternals = sharedInternals || {};
if (!this._sharedInternals.listeners) {
this._sharedInternals.listeners = {};
}
if (!this._sharedInternals.cache) {
this._sharedInternals.cache = {};
}
}
|
[
"function",
"(",
"path",
",",
"sharedInternals",
")",
"{",
"this",
".",
"_path",
"=",
"path",
"||",
"EMPTY_PATH",
";",
"this",
".",
"_sharedInternals",
"=",
"sharedInternals",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"this",
".",
"_sharedInternals",
".",
"listeners",
")",
"{",
"this",
".",
"_sharedInternals",
".",
"listeners",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"!",
"this",
".",
"_sharedInternals",
".",
"cache",
")",
"{",
"this",
".",
"_sharedInternals",
".",
"cache",
"=",
"{",
"}",
";",
"}",
"}"
] |
Binding constructor.
@param {String[]} [path] binding path, empty array if omitted
@param {Object} [sharedInternals] shared relative bindings internals:
<ul>
<li>backingValue - backing value;</li>
<li>metaBinding - meta binding;</li>
<li>metaBindingListenerId - meta binding listener id;</li>
<li>listeners - change listeners;</li>
<li>cache - bindings cache.</li>
</ul>
@public
@class Binding
@classdesc Wraps immutable collection. Provides convenient read-write access to nested values.
Allows to create sub-bindings (or views) narrowed to a subpath and sharing the same backing value.
Changes to these bindings are mutually visible.
<p>Terminology:
<ul>
<li>
(sub)path - path to a value within nested associative data structure, example: 'path.t.0.some.value';
</li>
<li>
backing value - value shared by all bindings created using [sub]{@link Binding#sub} method.
</li>
</ul>
<p>Features:
<ul>
<li>can create sub-bindings sharing same backing value. Sub-binding can only modify values down its subpath;</li>
<li>allows to conveniently modify nested values: assign, update with a function, remove, and so on;</li>
<li>can attach change listeners to a specific subpath;</li>
<li>can perform multiple changes atomically in respect of listener notification.</li>
</ul>
@see Binding.init
|
[
"Binding",
"constructor",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Binding.js#L290-L305
|
train
|
|
moreartyjs/moreartyjs
|
src/Binding.js
|
function (newBackingValue) {
var newSharedInternals = {};
Util.assign(newSharedInternals, this._sharedInternals);
newSharedInternals.backingValue = newBackingValue;
return new Binding(this._path, newSharedInternals);
}
|
javascript
|
function (newBackingValue) {
var newSharedInternals = {};
Util.assign(newSharedInternals, this._sharedInternals);
newSharedInternals.backingValue = newBackingValue;
return new Binding(this._path, newSharedInternals);
}
|
[
"function",
"(",
"newBackingValue",
")",
"{",
"var",
"newSharedInternals",
"=",
"{",
"}",
";",
"Util",
".",
"assign",
"(",
"newSharedInternals",
",",
"this",
".",
"_sharedInternals",
")",
";",
"newSharedInternals",
".",
"backingValue",
"=",
"newBackingValue",
";",
"return",
"new",
"Binding",
"(",
"this",
".",
"_path",
",",
"newSharedInternals",
")",
";",
"}"
] |
Update backing value.
@param {Immutable.Map} newBackingValue new backing value
@return {Binding} new binding instance, original is unaffected
|
[
"Update",
"backing",
"value",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Binding.js#L359-L364
|
train
|
|
moreartyjs/moreartyjs
|
src/Binding.js
|
function (alternativeBackingValue, compare) {
var value = this.get();
var alternativeValue = alternativeBackingValue ? alternativeBackingValue.getIn(this._path) : undefined;
return compare ?
!compare(value, alternativeValue) :
!(value === alternativeValue || (Util.undefinedOrNull(value) && Util.undefinedOrNull(alternativeValue)));
}
|
javascript
|
function (alternativeBackingValue, compare) {
var value = this.get();
var alternativeValue = alternativeBackingValue ? alternativeBackingValue.getIn(this._path) : undefined;
return compare ?
!compare(value, alternativeValue) :
!(value === alternativeValue || (Util.undefinedOrNull(value) && Util.undefinedOrNull(alternativeValue)));
}
|
[
"function",
"(",
"alternativeBackingValue",
",",
"compare",
")",
"{",
"var",
"value",
"=",
"this",
".",
"get",
"(",
")",
";",
"var",
"alternativeValue",
"=",
"alternativeBackingValue",
"?",
"alternativeBackingValue",
".",
"getIn",
"(",
"this",
".",
"_path",
")",
":",
"undefined",
";",
"return",
"compare",
"?",
"!",
"compare",
"(",
"value",
",",
"alternativeValue",
")",
":",
"!",
"(",
"value",
"===",
"alternativeValue",
"||",
"(",
"Util",
".",
"undefinedOrNull",
"(",
"value",
")",
"&&",
"Util",
".",
"undefinedOrNull",
"(",
"alternativeValue",
")",
")",
")",
";",
"}"
] |
Check if binding value is changed in alternative backing value.
@param {Immutable.Map} alternativeBackingValue alternative backing value
@param {Function} [compare] alternative compare function, does reference equality check if omitted
|
[
"Check",
"if",
"binding",
"value",
"is",
"changed",
"in",
"alternative",
"backing",
"value",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Binding.js#L369-L375
|
train
|
|
moreartyjs/moreartyjs
|
src/Binding.js
|
function (subpath) {
if (!this._sharedInternals.metaBinding) {
var metaBinding = Binding.init(Imm.Map());
linkMeta(this, metaBinding);
this._sharedInternals.metaBinding = metaBinding;
}
var effectiveSubpath = subpath ? Util.joinPaths([Util.META_NODE], asArrayPath(subpath)) : [Util.META_NODE];
var thisPath = this.getPath();
var absolutePath = thisPath.length > 0 ? Util.joinPaths(thisPath, effectiveSubpath) : effectiveSubpath;
return this._sharedInternals.metaBinding.sub(absolutePath);
}
|
javascript
|
function (subpath) {
if (!this._sharedInternals.metaBinding) {
var metaBinding = Binding.init(Imm.Map());
linkMeta(this, metaBinding);
this._sharedInternals.metaBinding = metaBinding;
}
var effectiveSubpath = subpath ? Util.joinPaths([Util.META_NODE], asArrayPath(subpath)) : [Util.META_NODE];
var thisPath = this.getPath();
var absolutePath = thisPath.length > 0 ? Util.joinPaths(thisPath, effectiveSubpath) : effectiveSubpath;
return this._sharedInternals.metaBinding.sub(absolutePath);
}
|
[
"function",
"(",
"subpath",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_sharedInternals",
".",
"metaBinding",
")",
"{",
"var",
"metaBinding",
"=",
"Binding",
".",
"init",
"(",
"Imm",
".",
"Map",
"(",
")",
")",
";",
"linkMeta",
"(",
"this",
",",
"metaBinding",
")",
";",
"this",
".",
"_sharedInternals",
".",
"metaBinding",
"=",
"metaBinding",
";",
"}",
"var",
"effectiveSubpath",
"=",
"subpath",
"?",
"Util",
".",
"joinPaths",
"(",
"[",
"Util",
".",
"META_NODE",
"]",
",",
"asArrayPath",
"(",
"subpath",
")",
")",
":",
"[",
"Util",
".",
"META_NODE",
"]",
";",
"var",
"thisPath",
"=",
"this",
".",
"getPath",
"(",
")",
";",
"var",
"absolutePath",
"=",
"thisPath",
".",
"length",
">",
"0",
"?",
"Util",
".",
"joinPaths",
"(",
"thisPath",
",",
"effectiveSubpath",
")",
":",
"effectiveSubpath",
";",
"return",
"this",
".",
"_sharedInternals",
".",
"metaBinding",
".",
"sub",
"(",
"absolutePath",
")",
";",
"}"
] |
Get binding's meta binding.
@param {String|Array} [subpath] subpath as a dot-separated string or an array of strings and numbers;
b.meta('path') is equivalent to b.meta().sub('path')
@returns {Binding} meta binding or undefined
|
[
"Get",
"binding",
"s",
"meta",
"binding",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Binding.js#L389-L400
|
train
|
|
moreartyjs/moreartyjs
|
src/Binding.js
|
function (subpath) {
var value = this.sub(subpath).get();
return Imm.Iterable.isIterable(value) ? value.toJS() : value;
}
|
javascript
|
function (subpath) {
var value = this.sub(subpath).get();
return Imm.Iterable.isIterable(value) ? value.toJS() : value;
}
|
[
"function",
"(",
"subpath",
")",
"{",
"var",
"value",
"=",
"this",
".",
"sub",
"(",
"subpath",
")",
".",
"get",
"(",
")",
";",
"return",
"Imm",
".",
"Iterable",
".",
"isIterable",
"(",
"value",
")",
"?",
"value",
".",
"toJS",
"(",
")",
":",
"value",
";",
"}"
] |
Convert to JS representation.
@param {String|Array} [subpath] subpath as a dot-separated string or an array of strings and numbers
@return {*} JS representation of data at subpath
|
[
"Convert",
"to",
"JS",
"representation",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Binding.js#L420-L423
|
train
|
|
moreartyjs/moreartyjs
|
src/Binding.js
|
function (subpath) {
var pathAsArray = asArrayPath(subpath);
var absolutePath = Util.joinPaths(this._path, pathAsArray);
if (absolutePath.length > 0) {
var absolutePathAsString = asStringPath(absolutePath);
var cached = this._sharedInternals.cache[absolutePathAsString];
if (cached) {
return cached;
} else {
var subBinding = new Binding(absolutePath, this._sharedInternals);
this._sharedInternals.cache[absolutePathAsString] = subBinding;
return subBinding;
}
} else {
return this;
}
}
|
javascript
|
function (subpath) {
var pathAsArray = asArrayPath(subpath);
var absolutePath = Util.joinPaths(this._path, pathAsArray);
if (absolutePath.length > 0) {
var absolutePathAsString = asStringPath(absolutePath);
var cached = this._sharedInternals.cache[absolutePathAsString];
if (cached) {
return cached;
} else {
var subBinding = new Binding(absolutePath, this._sharedInternals);
this._sharedInternals.cache[absolutePathAsString] = subBinding;
return subBinding;
}
} else {
return this;
}
}
|
[
"function",
"(",
"subpath",
")",
"{",
"var",
"pathAsArray",
"=",
"asArrayPath",
"(",
"subpath",
")",
";",
"var",
"absolutePath",
"=",
"Util",
".",
"joinPaths",
"(",
"this",
".",
"_path",
",",
"pathAsArray",
")",
";",
"if",
"(",
"absolutePath",
".",
"length",
">",
"0",
")",
"{",
"var",
"absolutePathAsString",
"=",
"asStringPath",
"(",
"absolutePath",
")",
";",
"var",
"cached",
"=",
"this",
".",
"_sharedInternals",
".",
"cache",
"[",
"absolutePathAsString",
"]",
";",
"if",
"(",
"cached",
")",
"{",
"return",
"cached",
";",
"}",
"else",
"{",
"var",
"subBinding",
"=",
"new",
"Binding",
"(",
"absolutePath",
",",
"this",
".",
"_sharedInternals",
")",
";",
"this",
".",
"_sharedInternals",
".",
"cache",
"[",
"absolutePathAsString",
"]",
"=",
"subBinding",
";",
"return",
"subBinding",
";",
"}",
"}",
"else",
"{",
"return",
"this",
";",
"}",
"}"
] |
Bind to subpath. Both bindings share the same backing value. Changes are mutually visible.
@param {String|Array} [subpath] subpath as a dot-separated string or an array of strings and numbers
@return {Binding} new binding instance, original is unaffected
|
[
"Bind",
"to",
"subpath",
".",
"Both",
"bindings",
"share",
"the",
"same",
"backing",
"value",
".",
"Changes",
"are",
"mutually",
"visible",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Binding.js#L428-L445
|
train
|
|
moreartyjs/moreartyjs
|
src/Binding.js
|
function (subpath, cb) {
var args = Util.resolveArgs(
arguments, function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, 'cb'
);
var listenerId = generateListenerId();
var pathAsString = asStringPath(Util.joinPaths(this._path, asArrayPath(args.subpath || '')));
var samePathListeners = this._sharedInternals.listeners[pathAsString];
var listenerDescriptor = { cb: args.cb, disabled: false };
if (samePathListeners) {
samePathListeners[listenerId] = listenerDescriptor;
} else {
var listeners = {};
listeners[listenerId] = listenerDescriptor;
this._sharedInternals.listeners[pathAsString] = listeners;
}
return listenerId;
}
|
javascript
|
function (subpath, cb) {
var args = Util.resolveArgs(
arguments, function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, 'cb'
);
var listenerId = generateListenerId();
var pathAsString = asStringPath(Util.joinPaths(this._path, asArrayPath(args.subpath || '')));
var samePathListeners = this._sharedInternals.listeners[pathAsString];
var listenerDescriptor = { cb: args.cb, disabled: false };
if (samePathListeners) {
samePathListeners[listenerId] = listenerDescriptor;
} else {
var listeners = {};
listeners[listenerId] = listenerDescriptor;
this._sharedInternals.listeners[pathAsString] = listeners;
}
return listenerId;
}
|
[
"function",
"(",
"subpath",
",",
"cb",
")",
"{",
"var",
"args",
"=",
"Util",
".",
"resolveArgs",
"(",
"arguments",
",",
"function",
"(",
"x",
")",
"{",
"return",
"Util",
".",
"canRepresentSubpath",
"(",
"x",
")",
"?",
"'subpath'",
":",
"null",
";",
"}",
",",
"'cb'",
")",
";",
"var",
"listenerId",
"=",
"generateListenerId",
"(",
")",
";",
"var",
"pathAsString",
"=",
"asStringPath",
"(",
"Util",
".",
"joinPaths",
"(",
"this",
".",
"_path",
",",
"asArrayPath",
"(",
"args",
".",
"subpath",
"||",
"''",
")",
")",
")",
";",
"var",
"samePathListeners",
"=",
"this",
".",
"_sharedInternals",
".",
"listeners",
"[",
"pathAsString",
"]",
";",
"var",
"listenerDescriptor",
"=",
"{",
"cb",
":",
"args",
".",
"cb",
",",
"disabled",
":",
"false",
"}",
";",
"if",
"(",
"samePathListeners",
")",
"{",
"samePathListeners",
"[",
"listenerId",
"]",
"=",
"listenerDescriptor",
";",
"}",
"else",
"{",
"var",
"listeners",
"=",
"{",
"}",
";",
"listeners",
"[",
"listenerId",
"]",
"=",
"listenerDescriptor",
";",
"this",
".",
"_sharedInternals",
".",
"listeners",
"[",
"pathAsString",
"]",
"=",
"listeners",
";",
"}",
"return",
"listenerId",
";",
"}"
] |
Add change listener.
@param {String|Array} [subpath] subpath as a dot-separated string or an array of strings and numbers
@param {Function} cb function receiving changes descriptor
@return {String} unique id which should be used to un-register the listener
@see ChangesDescriptor
|
[
"Add",
"change",
"listener",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Binding.js#L507-L524
|
train
|
|
moreartyjs/moreartyjs
|
src/Binding.js
|
function (subpath, cb) {
var args = Util.resolveArgs(
arguments, function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, 'cb'
);
var self = this;
var listenerId = self.addListener(args.subpath, function () {
self.removeListener(listenerId);
args.cb();
});
return listenerId;
}
|
javascript
|
function (subpath, cb) {
var args = Util.resolveArgs(
arguments, function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, 'cb'
);
var self = this;
var listenerId = self.addListener(args.subpath, function () {
self.removeListener(listenerId);
args.cb();
});
return listenerId;
}
|
[
"function",
"(",
"subpath",
",",
"cb",
")",
"{",
"var",
"args",
"=",
"Util",
".",
"resolveArgs",
"(",
"arguments",
",",
"function",
"(",
"x",
")",
"{",
"return",
"Util",
".",
"canRepresentSubpath",
"(",
"x",
")",
"?",
"'subpath'",
":",
"null",
";",
"}",
",",
"'cb'",
")",
";",
"var",
"self",
"=",
"this",
";",
"var",
"listenerId",
"=",
"self",
".",
"addListener",
"(",
"args",
".",
"subpath",
",",
"function",
"(",
")",
"{",
"self",
".",
"removeListener",
"(",
"listenerId",
")",
";",
"args",
".",
"cb",
"(",
")",
";",
"}",
")",
";",
"return",
"listenerId",
";",
"}"
] |
Add change listener triggered only once.
@param {String|Array} [subpath] subpath as a dot-separated string or an array of strings and numbers
@param {Function} cb function receiving changes descriptor
@return {String} unique id which should be used to un-register the listener
@see ChangesDescriptor
|
[
"Add",
"change",
"listener",
"triggered",
"only",
"once",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Binding.js#L531-L542
|
train
|
|
moreartyjs/moreartyjs
|
src/Binding.js
|
function (listenerId, f) {
var samePathListeners = findSamePathListeners(this, listenerId);
if (samePathListeners) {
var descriptor = samePathListeners[listenerId];
descriptor.disabled = true;
Util.afterComplete(f, function () { descriptor.disabled = false; });
} else {
f();
}
return this;
}
|
javascript
|
function (listenerId, f) {
var samePathListeners = findSamePathListeners(this, listenerId);
if (samePathListeners) {
var descriptor = samePathListeners[listenerId];
descriptor.disabled = true;
Util.afterComplete(f, function () { descriptor.disabled = false; });
} else {
f();
}
return this;
}
|
[
"function",
"(",
"listenerId",
",",
"f",
")",
"{",
"var",
"samePathListeners",
"=",
"findSamePathListeners",
"(",
"this",
",",
"listenerId",
")",
";",
"if",
"(",
"samePathListeners",
")",
"{",
"var",
"descriptor",
"=",
"samePathListeners",
"[",
"listenerId",
"]",
";",
"descriptor",
".",
"disabled",
"=",
"true",
";",
"Util",
".",
"afterComplete",
"(",
"f",
",",
"function",
"(",
")",
"{",
"descriptor",
".",
"disabled",
"=",
"false",
";",
"}",
")",
";",
"}",
"else",
"{",
"f",
"(",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Execute function with listener temporarily disabled. Correctly handles functions returning promises.
@param {String} listenerId listener id
@param {Function} f function to execute
@return {Binding} this binding
|
[
"Execute",
"function",
"with",
"listener",
"temporarily",
"disabled",
".",
"Correctly",
"handles",
"functions",
"returning",
"promises",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Binding.js#L564-L574
|
train
|
|
moreartyjs/moreartyjs
|
src/Binding.js
|
function (binding, promise) {
/** @private */
this._binding = binding;
/** @private */
this._queuedUpdates = [];
/** @private */
this._finishedUpdates = [];
/** @private */
this._committed = false;
/** @private */
this._cancelled = false;
/** @private */
this._hasChanges = false;
/** @private */
this._hasMetaChanges = false;
if (promise) {
var self = this;
promise.then(Util.identity, function () {
if (!self.isCancelled()) {
self.cancel();
}
});
}
}
|
javascript
|
function (binding, promise) {
/** @private */
this._binding = binding;
/** @private */
this._queuedUpdates = [];
/** @private */
this._finishedUpdates = [];
/** @private */
this._committed = false;
/** @private */
this._cancelled = false;
/** @private */
this._hasChanges = false;
/** @private */
this._hasMetaChanges = false;
if (promise) {
var self = this;
promise.then(Util.identity, function () {
if (!self.isCancelled()) {
self.cancel();
}
});
}
}
|
[
"function",
"(",
"binding",
",",
"promise",
")",
"{",
"this",
".",
"_binding",
"=",
"binding",
";",
"this",
".",
"_queuedUpdates",
"=",
"[",
"]",
";",
"this",
".",
"_finishedUpdates",
"=",
"[",
"]",
";",
"this",
".",
"_committed",
"=",
"false",
";",
"this",
".",
"_cancelled",
"=",
"false",
";",
"this",
".",
"_hasChanges",
"=",
"false",
";",
"this",
".",
"_hasMetaChanges",
"=",
"false",
";",
"if",
"(",
"promise",
")",
"{",
"var",
"self",
"=",
"this",
";",
"promise",
".",
"then",
"(",
"Util",
".",
"identity",
",",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"self",
".",
"isCancelled",
"(",
")",
")",
"{",
"self",
".",
"cancel",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] |
Transaction context constructor.
@param {Binding} binding binding
@param {Promise} [promise] ES6 promise
@public
@class TransactionContext
@classdesc Transaction context.
|
[
"Transaction",
"context",
"constructor",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Binding.js#L605-L632
|
train
|
|
moreartyjs/moreartyjs
|
src/Binding.js
|
function (binding, subpath) {
var args = Util.resolveArgs(
arguments,
function (x) { return x instanceof Binding ? 'binding' : null; }, '?subpath'
);
addDeletion(this, args.binding || this._binding, asArrayPath(args.subpath));
return this;
}
|
javascript
|
function (binding, subpath) {
var args = Util.resolveArgs(
arguments,
function (x) { return x instanceof Binding ? 'binding' : null; }, '?subpath'
);
addDeletion(this, args.binding || this._binding, asArrayPath(args.subpath));
return this;
}
|
[
"function",
"(",
"binding",
",",
"subpath",
")",
"{",
"var",
"args",
"=",
"Util",
".",
"resolveArgs",
"(",
"arguments",
",",
"function",
"(",
"x",
")",
"{",
"return",
"x",
"instanceof",
"Binding",
"?",
"'binding'",
":",
"null",
";",
"}",
",",
"'?subpath'",
")",
";",
"addDeletion",
"(",
"this",
",",
"args",
".",
"binding",
"||",
"this",
".",
"_binding",
",",
"asArrayPath",
"(",
"args",
".",
"subpath",
")",
")",
";",
"return",
"this",
";",
"}"
] |
Remove value.
@param {Binding} [binding] binding to apply update to
@param {String|Array} [subpath] subpath as a dot-separated string or an array of strings and numbers
@return {TransactionContext} updated transaction context
|
[
"Remove",
"value",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Binding.js#L786-L793
|
train
|
|
moreartyjs/moreartyjs
|
src/Morearty.js
|
function (binding, metaBinding, options) {
/** @private */
this._initialMetaState = metaBinding.get();
/** @private */
this._previousMetaState = null;
/** @private */
this._metaBinding = metaBinding;
/** @protected
* @ignore */
this._metaChanged = false;
/** @private */
this._initialState = binding.get();
/** @protected
* @ignore */
this._previousState = null;
/** @private */
this._stateBinding = binding;
/** @protected
* @ignore */
this._stateChanged = false;
/** @private */
this._options = options;
/** @private */
this._renderQueued = false;
/** @private */
this._fullUpdateQueued = false;
/** @protected
* @ignore */
this._fullUpdateInProgress = false;
/** @private */
this._componentQueue = [];
/** @private */
this._lastComponentQueueId = 0;
}
|
javascript
|
function (binding, metaBinding, options) {
/** @private */
this._initialMetaState = metaBinding.get();
/** @private */
this._previousMetaState = null;
/** @private */
this._metaBinding = metaBinding;
/** @protected
* @ignore */
this._metaChanged = false;
/** @private */
this._initialState = binding.get();
/** @protected
* @ignore */
this._previousState = null;
/** @private */
this._stateBinding = binding;
/** @protected
* @ignore */
this._stateChanged = false;
/** @private */
this._options = options;
/** @private */
this._renderQueued = false;
/** @private */
this._fullUpdateQueued = false;
/** @protected
* @ignore */
this._fullUpdateInProgress = false;
/** @private */
this._componentQueue = [];
/** @private */
this._lastComponentQueueId = 0;
}
|
[
"function",
"(",
"binding",
",",
"metaBinding",
",",
"options",
")",
"{",
"this",
".",
"_initialMetaState",
"=",
"metaBinding",
".",
"get",
"(",
")",
";",
"this",
".",
"_previousMetaState",
"=",
"null",
";",
"this",
".",
"_metaBinding",
"=",
"metaBinding",
";",
"this",
".",
"_metaChanged",
"=",
"false",
";",
"this",
".",
"_initialState",
"=",
"binding",
".",
"get",
"(",
")",
";",
"this",
".",
"_previousState",
"=",
"null",
";",
"this",
".",
"_stateBinding",
"=",
"binding",
";",
"this",
".",
"_stateChanged",
"=",
"false",
";",
"this",
".",
"_options",
"=",
"options",
";",
"this",
".",
"_renderQueued",
"=",
"false",
";",
"this",
".",
"_fullUpdateQueued",
"=",
"false",
";",
"this",
".",
"_fullUpdateInProgress",
"=",
"false",
";",
"this",
".",
"_componentQueue",
"=",
"[",
"]",
";",
"this",
".",
"_lastComponentQueueId",
"=",
"0",
";",
"}"
] |
Morearty context constructor.
@param {Binding} binding state binding
@param {Binding} metaBinding meta state binding
@param {Object} options options
@public
@class Context
@classdesc Represents Morearty context.
<p>Exposed modules:
<ul>
<li>[Util]{@link Util};</li>
<li>[Binding]{@link Binding};</li>
<li>[History]{@link History};</li>
<li>[Callback]{@link Callback};</li>
<li>[DOM]{@link DOM}.</li>
</ul>
|
[
"Morearty",
"context",
"constructor",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Morearty.js#L240-L277
|
train
|
|
moreartyjs/moreartyjs
|
src/Morearty.js
|
function (subpath, options) {
var args = Util.resolveArgs(
arguments,
function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, '?options'
);
var pathAsArray = args.subpath ? Binding.asArrayPath(args.subpath) : [];
var tx = this.getBinding().atomically();
tx.set(pathAsArray, this._initialState.getIn(pathAsArray));
var effectiveOptions = args.options || {};
if (effectiveOptions.resetMeta !== false) {
tx.set(this.getMetaBinding(), pathAsArray, this._initialMetaState.getIn(pathAsArray));
}
tx.commit({ notify: effectiveOptions.notify });
}
|
javascript
|
function (subpath, options) {
var args = Util.resolveArgs(
arguments,
function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, '?options'
);
var pathAsArray = args.subpath ? Binding.asArrayPath(args.subpath) : [];
var tx = this.getBinding().atomically();
tx.set(pathAsArray, this._initialState.getIn(pathAsArray));
var effectiveOptions = args.options || {};
if (effectiveOptions.resetMeta !== false) {
tx.set(this.getMetaBinding(), pathAsArray, this._initialMetaState.getIn(pathAsArray));
}
tx.commit({ notify: effectiveOptions.notify });
}
|
[
"function",
"(",
"subpath",
",",
"options",
")",
"{",
"var",
"args",
"=",
"Util",
".",
"resolveArgs",
"(",
"arguments",
",",
"function",
"(",
"x",
")",
"{",
"return",
"Util",
".",
"canRepresentSubpath",
"(",
"x",
")",
"?",
"'subpath'",
":",
"null",
";",
"}",
",",
"'?options'",
")",
";",
"var",
"pathAsArray",
"=",
"args",
".",
"subpath",
"?",
"Binding",
".",
"asArrayPath",
"(",
"args",
".",
"subpath",
")",
":",
"[",
"]",
";",
"var",
"tx",
"=",
"this",
".",
"getBinding",
"(",
")",
".",
"atomically",
"(",
")",
";",
"tx",
".",
"set",
"(",
"pathAsArray",
",",
"this",
".",
"_initialState",
".",
"getIn",
"(",
"pathAsArray",
")",
")",
";",
"var",
"effectiveOptions",
"=",
"args",
".",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"effectiveOptions",
".",
"resetMeta",
"!==",
"false",
")",
"{",
"tx",
".",
"set",
"(",
"this",
".",
"getMetaBinding",
"(",
")",
",",
"pathAsArray",
",",
"this",
".",
"_initialMetaState",
".",
"getIn",
"(",
"pathAsArray",
")",
")",
";",
"}",
"tx",
".",
"commit",
"(",
"{",
"notify",
":",
"effectiveOptions",
".",
"notify",
"}",
")",
";",
"}"
] |
Revert to initial state.
@param {String|Array} [subpath] subpath as a dot-separated string or an array of strings and numbers
@param {Object} [options] options object
@param {Boolean} [options.notify=true] should listeners be notified
@param {Boolean} [options.resetMeta=true] should meta state be reverted
|
[
"Revert",
"to",
"initial",
"state",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Morearty.js#L332-L349
|
train
|
|
moreartyjs/moreartyjs
|
src/Morearty.js
|
function (newState, newMetaState, options) {
var args = Util.resolveArgs(
arguments,
'newState', function (x) { return Imm.Map.isMap(x) ? 'newMetaState' : null; }, '?options'
);
var effectiveOptions = args.options || {};
var tx = this.getBinding().atomically();
tx.set(newState);
if (args.newMetaState) tx.set(this.getMetaBinding(), args.newMetaState);
tx.commit({ notify: effectiveOptions.notify });
}
|
javascript
|
function (newState, newMetaState, options) {
var args = Util.resolveArgs(
arguments,
'newState', function (x) { return Imm.Map.isMap(x) ? 'newMetaState' : null; }, '?options'
);
var effectiveOptions = args.options || {};
var tx = this.getBinding().atomically();
tx.set(newState);
if (args.newMetaState) tx.set(this.getMetaBinding(), args.newMetaState);
tx.commit({ notify: effectiveOptions.notify });
}
|
[
"function",
"(",
"newState",
",",
"newMetaState",
",",
"options",
")",
"{",
"var",
"args",
"=",
"Util",
".",
"resolveArgs",
"(",
"arguments",
",",
"'newState'",
",",
"function",
"(",
"x",
")",
"{",
"return",
"Imm",
".",
"Map",
".",
"isMap",
"(",
"x",
")",
"?",
"'newMetaState'",
":",
"null",
";",
"}",
",",
"'?options'",
")",
";",
"var",
"effectiveOptions",
"=",
"args",
".",
"options",
"||",
"{",
"}",
";",
"var",
"tx",
"=",
"this",
".",
"getBinding",
"(",
")",
".",
"atomically",
"(",
")",
";",
"tx",
".",
"set",
"(",
"newState",
")",
";",
"if",
"(",
"args",
".",
"newMetaState",
")",
"tx",
".",
"set",
"(",
"this",
".",
"getMetaBinding",
"(",
")",
",",
"args",
".",
"newMetaState",
")",
";",
"tx",
".",
"commit",
"(",
"{",
"notify",
":",
"effectiveOptions",
".",
"notify",
"}",
")",
";",
"}"
] |
Replace whole state with new value.
@param {Immutable.Map} newState new state
@param {Immutable.Map} [newMetaState] new meta state
@param {Object} [options] options object
@param {Boolean} [options.notify=true] should listeners be notified
|
[
"Replace",
"whole",
"state",
"with",
"new",
"value",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Morearty.js#L356-L370
|
train
|
|
moreartyjs/moreartyjs
|
src/Morearty.js
|
function (binding, subpath, compare) {
var args = Util.resolveArgs(
arguments,
'binding', function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, '?compare'
);
return args.binding.sub(args.subpath).isChanged(this._previousState, args.compare || Imm.is);
}
|
javascript
|
function (binding, subpath, compare) {
var args = Util.resolveArgs(
arguments,
'binding', function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, '?compare'
);
return args.binding.sub(args.subpath).isChanged(this._previousState, args.compare || Imm.is);
}
|
[
"function",
"(",
"binding",
",",
"subpath",
",",
"compare",
")",
"{",
"var",
"args",
"=",
"Util",
".",
"resolveArgs",
"(",
"arguments",
",",
"'binding'",
",",
"function",
"(",
"x",
")",
"{",
"return",
"Util",
".",
"canRepresentSubpath",
"(",
"x",
")",
"?",
"'subpath'",
":",
"null",
";",
"}",
",",
"'?compare'",
")",
";",
"return",
"args",
".",
"binding",
".",
"sub",
"(",
"args",
".",
"subpath",
")",
".",
"isChanged",
"(",
"this",
".",
"_previousState",
",",
"args",
".",
"compare",
"||",
"Imm",
".",
"is",
")",
";",
"}"
] |
Check if binding value was changed on last re-render.
@param {Binding} binding binding
@param {String|Array} [subpath] subpath as a dot-separated string or an array of strings and numbers
@param {Function} [compare] compare function, '===' for primitives / Immutable.is for collections by default
|
[
"Check",
"if",
"binding",
"value",
"was",
"changed",
"on",
"last",
"re",
"-",
"render",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Morearty.js#L376-L383
|
train
|
|
moreartyjs/moreartyjs
|
src/Morearty.js
|
function (rootComp, reactContext) {
var ctx = this;
var effectiveReactContext = reactContext || {};
effectiveReactContext.morearty = ctx;
return React.createClass({
displayName: 'Bootstrap',
childContextTypes: {
morearty: React.PropTypes.instanceOf(Context).isRequired
},
getChildContext: function () {
return effectiveReactContext;
},
componentWillMount: function () {
ctx.init(this);
},
render: function () {
var effectiveProps = Util.assign({}, {binding: ctx.getBinding()}, this.props);
return React.createFactory(rootComp)(effectiveProps);
}
});
}
|
javascript
|
function (rootComp, reactContext) {
var ctx = this;
var effectiveReactContext = reactContext || {};
effectiveReactContext.morearty = ctx;
return React.createClass({
displayName: 'Bootstrap',
childContextTypes: {
morearty: React.PropTypes.instanceOf(Context).isRequired
},
getChildContext: function () {
return effectiveReactContext;
},
componentWillMount: function () {
ctx.init(this);
},
render: function () {
var effectiveProps = Util.assign({}, {binding: ctx.getBinding()}, this.props);
return React.createFactory(rootComp)(effectiveProps);
}
});
}
|
[
"function",
"(",
"rootComp",
",",
"reactContext",
")",
"{",
"var",
"ctx",
"=",
"this",
";",
"var",
"effectiveReactContext",
"=",
"reactContext",
"||",
"{",
"}",
";",
"effectiveReactContext",
".",
"morearty",
"=",
"ctx",
";",
"return",
"React",
".",
"createClass",
"(",
"{",
"displayName",
":",
"'Bootstrap'",
",",
"childContextTypes",
":",
"{",
"morearty",
":",
"React",
".",
"PropTypes",
".",
"instanceOf",
"(",
"Context",
")",
".",
"isRequired",
"}",
",",
"getChildContext",
":",
"function",
"(",
")",
"{",
"return",
"effectiveReactContext",
";",
"}",
",",
"componentWillMount",
":",
"function",
"(",
")",
"{",
"ctx",
".",
"init",
"(",
"this",
")",
";",
"}",
",",
"render",
":",
"function",
"(",
")",
"{",
"var",
"effectiveProps",
"=",
"Util",
".",
"assign",
"(",
"{",
"}",
",",
"{",
"binding",
":",
"ctx",
".",
"getBinding",
"(",
")",
"}",
",",
"this",
".",
"props",
")",
";",
"return",
"React",
".",
"createFactory",
"(",
"rootComp",
")",
"(",
"effectiveProps",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Create Morearty bootstrap component ready for rendering.
@param {*} rootComp root application component
@param {Object} [reactContext] custom React context (will be enriched with Morearty-specific data)
@return {*} Morearty bootstrap component
|
[
"Create",
"Morearty",
"bootstrap",
"component",
"ready",
"for",
"rendering",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Morearty.js#L512-L539
|
train
|
|
moreartyjs/moreartyjs
|
src/Morearty.js
|
function (name) {
var ctx = this.getMoreartyContext();
return getBinding(this.props, name).withBackingValue(ctx._previousState).get();
}
|
javascript
|
function (name) {
var ctx = this.getMoreartyContext();
return getBinding(this.props, name).withBackingValue(ctx._previousState).get();
}
|
[
"function",
"(",
"name",
")",
"{",
"var",
"ctx",
"=",
"this",
".",
"getMoreartyContext",
"(",
")",
";",
"return",
"getBinding",
"(",
"this",
".",
"props",
",",
"name",
")",
".",
"withBackingValue",
"(",
"ctx",
".",
"_previousState",
")",
".",
"get",
"(",
")",
";",
"}"
] |
Get component previous state value.
@param {String} [name] binding name (can only be used with multi-binding state)
@return {*} previous component state value
|
[
"Get",
"component",
"previous",
"state",
"value",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Morearty.js#L636-L639
|
train
|
|
moreartyjs/moreartyjs
|
src/Morearty.js
|
function (binding, cb) {
if (!this.observedBindings) {
this.observedBindings = [];
}
var bindingPath = binding.getPath();
if (!Util.find(this.observedBindings, function (b) { return b.getPath() === bindingPath; })) {
this.observedBindings.push(binding);
setupObservedBindingListener(this, binding);
}
return cb ? cb(binding.get()) : undefined;
}
|
javascript
|
function (binding, cb) {
if (!this.observedBindings) {
this.observedBindings = [];
}
var bindingPath = binding.getPath();
if (!Util.find(this.observedBindings, function (b) { return b.getPath() === bindingPath; })) {
this.observedBindings.push(binding);
setupObservedBindingListener(this, binding);
}
return cb ? cb(binding.get()) : undefined;
}
|
[
"function",
"(",
"binding",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"this",
".",
"observedBindings",
")",
"{",
"this",
".",
"observedBindings",
"=",
"[",
"]",
";",
"}",
"var",
"bindingPath",
"=",
"binding",
".",
"getPath",
"(",
")",
";",
"if",
"(",
"!",
"Util",
".",
"find",
"(",
"this",
".",
"observedBindings",
",",
"function",
"(",
"b",
")",
"{",
"return",
"b",
".",
"getPath",
"(",
")",
"===",
"bindingPath",
";",
"}",
")",
")",
"{",
"this",
".",
"observedBindings",
".",
"push",
"(",
"binding",
")",
";",
"setupObservedBindingListener",
"(",
"this",
",",
"binding",
")",
";",
"}",
"return",
"cb",
"?",
"cb",
"(",
"binding",
".",
"get",
"(",
")",
")",
":",
"undefined",
";",
"}"
] |
Consider specified binding for changes when rendering. Registering same binding twice has no effect.
@param {Binding} binding
@param {Function} [cb] optional callback receiving binding value
@return {*} undefined if cb argument is ommitted, cb invocation result otherwise
|
[
"Consider",
"specified",
"binding",
"for",
"changes",
"when",
"rendering",
".",
"Registering",
"same",
"binding",
"twice",
"has",
"no",
"effect",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Morearty.js#L645-L657
|
train
|
|
moreartyjs/moreartyjs
|
src/Morearty.js
|
function (binding, subpath, cb) {
var args = Util.resolveArgs(
arguments,
function (x) { return x instanceof Binding ? 'binding' : null; },
function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; },
'cb'
);
if (!this._bindingListenerRemovers) {
this._bindingListenerRemovers = [];
}
var effectiveBinding = args.binding || this.getDefaultBinding();
if (!effectiveBinding) {
return console.warn('Morearty: cannot attach binding listener to a component without default binding');
}
var listenerId = effectiveBinding.addListener(args.subpath, args.cb);
this._bindingListenerRemovers.push(function () {
effectiveBinding.removeListener(listenerId);
});
return listenerId;
}
|
javascript
|
function (binding, subpath, cb) {
var args = Util.resolveArgs(
arguments,
function (x) { return x instanceof Binding ? 'binding' : null; },
function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; },
'cb'
);
if (!this._bindingListenerRemovers) {
this._bindingListenerRemovers = [];
}
var effectiveBinding = args.binding || this.getDefaultBinding();
if (!effectiveBinding) {
return console.warn('Morearty: cannot attach binding listener to a component without default binding');
}
var listenerId = effectiveBinding.addListener(args.subpath, args.cb);
this._bindingListenerRemovers.push(function () {
effectiveBinding.removeListener(listenerId);
});
return listenerId;
}
|
[
"function",
"(",
"binding",
",",
"subpath",
",",
"cb",
")",
"{",
"var",
"args",
"=",
"Util",
".",
"resolveArgs",
"(",
"arguments",
",",
"function",
"(",
"x",
")",
"{",
"return",
"x",
"instanceof",
"Binding",
"?",
"'binding'",
":",
"null",
";",
"}",
",",
"function",
"(",
"x",
")",
"{",
"return",
"Util",
".",
"canRepresentSubpath",
"(",
"x",
")",
"?",
"'subpath'",
":",
"null",
";",
"}",
",",
"'cb'",
")",
";",
"if",
"(",
"!",
"this",
".",
"_bindingListenerRemovers",
")",
"{",
"this",
".",
"_bindingListenerRemovers",
"=",
"[",
"]",
";",
"}",
"var",
"effectiveBinding",
"=",
"args",
".",
"binding",
"||",
"this",
".",
"getDefaultBinding",
"(",
")",
";",
"if",
"(",
"!",
"effectiveBinding",
")",
"{",
"return",
"console",
".",
"warn",
"(",
"'Morearty: cannot attach binding listener to a component without default binding'",
")",
";",
"}",
"var",
"listenerId",
"=",
"effectiveBinding",
".",
"addListener",
"(",
"args",
".",
"subpath",
",",
"args",
".",
"cb",
")",
";",
"this",
".",
"_bindingListenerRemovers",
".",
"push",
"(",
"function",
"(",
")",
"{",
"effectiveBinding",
".",
"removeListener",
"(",
"listenerId",
")",
";",
"}",
")",
";",
"return",
"listenerId",
";",
"}"
] |
Add binding listener. Listener will be automatically removed on unmount.
@param {Binding} [binding] binding to attach listener to, default binding if omitted
@param {String|Array} [subpath] subpath as a dot-separated string or an array of strings and numbers
@param {Function} cb function receiving changes descriptor
@return {String} listener id
|
[
"Add",
"binding",
"listener",
".",
"Listener",
"will",
"be",
"automatically",
"removed",
"on",
"unmount",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Morearty.js#L696-L718
|
train
|
|
moreartyjs/moreartyjs
|
src/Morearty.js
|
function (spec) {
var initialState, initialMetaState, options;
if (arguments.length <= 1) {
var effectiveSpec = spec || {};
initialState = effectiveSpec.initialState;
initialMetaState = effectiveSpec.initialMetaState;
options = effectiveSpec.options;
} else {
console.warn(
'Passing multiple arguments to createContext is deprecated. Use single object form instead.'
);
initialState = arguments[0];
initialMetaState = arguments[1];
options = arguments[2];
}
var ensureImmutable = function (state) {
return Imm.Iterable.isIterable(state) ? state : Imm.fromJS(state);
};
var state = ensureImmutable(initialState || {});
var metaState = ensureImmutable(initialMetaState || {});
var metaBinding = Binding.init(metaState);
var binding = Binding.init(state, metaBinding);
var effectiveOptions = options || {};
return new Context(binding, metaBinding, {
requestAnimationFrameEnabled: effectiveOptions.requestAnimationFrameEnabled !== false,
renderOnce: effectiveOptions.renderOnce || false,
stopOnRenderError: effectiveOptions.stopOnRenderError || false,
logger: effectiveOptions.logger || defaultLogger
});
}
|
javascript
|
function (spec) {
var initialState, initialMetaState, options;
if (arguments.length <= 1) {
var effectiveSpec = spec || {};
initialState = effectiveSpec.initialState;
initialMetaState = effectiveSpec.initialMetaState;
options = effectiveSpec.options;
} else {
console.warn(
'Passing multiple arguments to createContext is deprecated. Use single object form instead.'
);
initialState = arguments[0];
initialMetaState = arguments[1];
options = arguments[2];
}
var ensureImmutable = function (state) {
return Imm.Iterable.isIterable(state) ? state : Imm.fromJS(state);
};
var state = ensureImmutable(initialState || {});
var metaState = ensureImmutable(initialMetaState || {});
var metaBinding = Binding.init(metaState);
var binding = Binding.init(state, metaBinding);
var effectiveOptions = options || {};
return new Context(binding, metaBinding, {
requestAnimationFrameEnabled: effectiveOptions.requestAnimationFrameEnabled !== false,
renderOnce: effectiveOptions.renderOnce || false,
stopOnRenderError: effectiveOptions.stopOnRenderError || false,
logger: effectiveOptions.logger || defaultLogger
});
}
|
[
"function",
"(",
"spec",
")",
"{",
"var",
"initialState",
",",
"initialMetaState",
",",
"options",
";",
"if",
"(",
"arguments",
".",
"length",
"<=",
"1",
")",
"{",
"var",
"effectiveSpec",
"=",
"spec",
"||",
"{",
"}",
";",
"initialState",
"=",
"effectiveSpec",
".",
"initialState",
";",
"initialMetaState",
"=",
"effectiveSpec",
".",
"initialMetaState",
";",
"options",
"=",
"effectiveSpec",
".",
"options",
";",
"}",
"else",
"{",
"console",
".",
"warn",
"(",
"'Passing multiple arguments to createContext is deprecated. Use single object form instead.'",
")",
";",
"initialState",
"=",
"arguments",
"[",
"0",
"]",
";",
"initialMetaState",
"=",
"arguments",
"[",
"1",
"]",
";",
"options",
"=",
"arguments",
"[",
"2",
"]",
";",
"}",
"var",
"ensureImmutable",
"=",
"function",
"(",
"state",
")",
"{",
"return",
"Imm",
".",
"Iterable",
".",
"isIterable",
"(",
"state",
")",
"?",
"state",
":",
"Imm",
".",
"fromJS",
"(",
"state",
")",
";",
"}",
";",
"var",
"state",
"=",
"ensureImmutable",
"(",
"initialState",
"||",
"{",
"}",
")",
";",
"var",
"metaState",
"=",
"ensureImmutable",
"(",
"initialMetaState",
"||",
"{",
"}",
")",
";",
"var",
"metaBinding",
"=",
"Binding",
".",
"init",
"(",
"metaState",
")",
";",
"var",
"binding",
"=",
"Binding",
".",
"init",
"(",
"state",
",",
"metaBinding",
")",
";",
"var",
"effectiveOptions",
"=",
"options",
"||",
"{",
"}",
";",
"return",
"new",
"Context",
"(",
"binding",
",",
"metaBinding",
",",
"{",
"requestAnimationFrameEnabled",
":",
"effectiveOptions",
".",
"requestAnimationFrameEnabled",
"!==",
"false",
",",
"renderOnce",
":",
"effectiveOptions",
".",
"renderOnce",
"||",
"false",
",",
"stopOnRenderError",
":",
"effectiveOptions",
".",
"stopOnRenderError",
"||",
"false",
",",
"logger",
":",
"effectiveOptions",
".",
"logger",
"||",
"defaultLogger",
"}",
")",
";",
"}"
] |
Create Morearty context.
@param {Object} [spec] spec object
@param {Immutable.Map|Object} [spec.initialState={}] initial state
@param {Immutable.Map|Object} [spec.initialMetaState={}] initial meta-state
@param {Object} [spec.options={}] options object
@param {Boolean} [spec.options.requestAnimationFrameEnabled=true] enable rendering in requestAnimationFrame
@param {Boolean} [spec.options.renderOnce=false]
ensure render is executed only once (useful for server-side rendering to save resources),
any further state updates are ignored
@param {Boolean} [spec.options.stopOnRenderError=false] stop on errors during render
@param {Object} [spec.options.logger=undefined] an optional logger object for reporting errors
@param {function} [spec.options.logger.error] function accepting error message and optional cause
@return {Context}
@memberOf Morearty
|
[
"Create",
"Morearty",
"context",
"."
] |
297dfd7c4562b4668da1dfb33a9a607cec8a8fe3
|
https://github.com/moreartyjs/moreartyjs/blob/297dfd7c4562b4668da1dfb33a9a607cec8a8fe3/src/Morearty.js#L752-L786
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.