repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
marcelog/Nami | src/message/action.js | ConfbridgeMute | function ConfbridgeMute(conference, channel) {
ConfbridgeMute.super_.call(this, 'ConfbridgeMute');
this.set('Conference', conference);
this.set('Channel', channel);
} | javascript | function ConfbridgeMute(conference, channel) {
ConfbridgeMute.super_.call(this, 'ConfbridgeMute');
this.set('Conference', conference);
this.set('Channel', channel);
} | [
"function",
"ConfbridgeMute",
"(",
"conference",
",",
"channel",
")",
"{",
"ConfbridgeMute",
".",
"super_",
".",
"call",
"(",
"this",
",",
"'ConfbridgeMute'",
")",
";",
"this",
".",
"set",
"(",
"'Conference'",
",",
"conference",
")",
";",
"this",
".",
"set",
"(",
"'Channel'",
",",
"channel",
")",
";",
"}"
] | ConfbridgeMute Action.
@constructor
@see Action(String)
@param {String} conference room. The value of the "conference" key.
@param {String} Channel. The value of the "Channel" key.
@augments Action | [
"ConfbridgeMute",
"Action",
"."
] | ccf22f09e17c1ac5ae68e09af1bc77ea6cf106a1 | https://github.com/marcelog/Nami/blob/ccf22f09e17c1ac5ae68e09af1bc77ea6cf106a1/src/message/action.js#L1129-L1133 | train |
marcelog/Nami | src/message/action.js | ConfbridgeUnmute | function ConfbridgeUnmute(conference, channel) {
ConfbridgeUnmute.super_.call(this, 'ConfbridgeUnmute');
this.set('Conference', conference);
this.set('Channel', channel);
} | javascript | function ConfbridgeUnmute(conference, channel) {
ConfbridgeUnmute.super_.call(this, 'ConfbridgeUnmute');
this.set('Conference', conference);
this.set('Channel', channel);
} | [
"function",
"ConfbridgeUnmute",
"(",
"conference",
",",
"channel",
")",
"{",
"ConfbridgeUnmute",
".",
"super_",
".",
"call",
"(",
"this",
",",
"'ConfbridgeUnmute'",
")",
";",
"this",
".",
"set",
"(",
"'Conference'",
",",
"conference",
")",
";",
"this",
".",
"set",
"(",
"'Channel'",
",",
"channel",
")",
";",
"}"
] | ConfbridgeUnmute Action.
@constructor
@see Action(String)
@param {String} conference room. The value of the "conference" key.
@param {String} Channel. The value of the "Channel" key.
@augments Action | [
"ConfbridgeUnmute",
"Action",
"."
] | ccf22f09e17c1ac5ae68e09af1bc77ea6cf106a1 | https://github.com/marcelog/Nami/blob/ccf22f09e17c1ac5ae68e09af1bc77ea6cf106a1/src/message/action.js#L1143-L1147 | train |
marcelog/Nami | src/message/action.js | AGI | function AGI(channel, command, commandId) {
AGI.super_.call(this, 'AGI');
this.set('Channel', channel);
this.set('Command', command);
this.set('CommandID', commandId);
} | javascript | function AGI(channel, command, commandId) {
AGI.super_.call(this, 'AGI');
this.set('Channel', channel);
this.set('Command', command);
this.set('CommandID', commandId);
} | [
"function",
"AGI",
"(",
"channel",
",",
"command",
",",
"commandId",
")",
"{",
"AGI",
".",
"super_",
".",
"call",
"(",
"this",
",",
"'AGI'",
")",
";",
"this",
".",
"set",
"(",
"'Channel'",
",",
"channel",
")",
";",
"this",
".",
"set",
"(",
"'Command'",
",",
"command",
")",
";",
"this",
".",
"set",
"(",
"'CommandID'",
",",
"commandId",
")",
";",
"}"
] | AGI Action.
@constructor
@see Action(String)
@see https://wiki.asterisk.org/wiki/display/AST/ManagerAction_AGI
@param {String} Channel that is currently in Async AGI.
@param {String} Application to execute.
@param {String} This will be sent back in CommandID header of AsyncAGI exec event notification.
@augments Action | [
"AGI",
"Action",
"."
] | ccf22f09e17c1ac5ae68e09af1bc77ea6cf106a1 | https://github.com/marcelog/Nami/blob/ccf22f09e17c1ac5ae68e09af1bc77ea6cf106a1/src/message/action.js#L1159-L1164 | train |
marcelog/Nami | src/message/action.js | BlindTransfer | function BlindTransfer(channel, context, extension) {
BlindTransfer.super_.call(this, 'BlindTransfer');
this.set('Channel', channel);
this.set('Context', context);
this.set('Exten', extension);
} | javascript | function BlindTransfer(channel, context, extension) {
BlindTransfer.super_.call(this, 'BlindTransfer');
this.set('Channel', channel);
this.set('Context', context);
this.set('Exten', extension);
} | [
"function",
"BlindTransfer",
"(",
"channel",
",",
"context",
",",
"extension",
")",
"{",
"BlindTransfer",
".",
"super_",
".",
"call",
"(",
"this",
",",
"'BlindTransfer'",
")",
";",
"this",
".",
"set",
"(",
"'Channel'",
",",
"channel",
")",
";",
"this",
".",
"set",
"(",
"'Context'",
",",
"context",
")",
";",
"this",
".",
"set",
"(",
"'Exten'",
",",
"extension",
")",
";",
"}"
] | BlindTransfer Action.
@constructor
@see Action(String)
@see https://wiki.asterisk.org/wiki/display/AST/Asterisk+12+ManagerAction_BlindTransfer
@param {String} Source channel that wants to transfer the target channel.
@param {String} Context to transfer the target channel to.
@param {String} Extension inside the context to transfer the target channel to.
@augments Action | [
"BlindTransfer",
"Action",
"."
] | ccf22f09e17c1ac5ae68e09af1bc77ea6cf106a1 | https://github.com/marcelog/Nami/blob/ccf22f09e17c1ac5ae68e09af1bc77ea6cf106a1/src/message/action.js#L1176-L1181 | train |
marcelog/Nami | src/message/action.js | Filter | function Filter(operation, filter) {
Filter.super_.call(this, 'Filter');
this.set('Operation', operation);
this.set('Filter', filter);
} | javascript | function Filter(operation, filter) {
Filter.super_.call(this, 'Filter');
this.set('Operation', operation);
this.set('Filter', filter);
} | [
"function",
"Filter",
"(",
"operation",
",",
"filter",
")",
"{",
"Filter",
".",
"super_",
".",
"call",
"(",
"this",
",",
"'Filter'",
")",
";",
"this",
".",
"set",
"(",
"'Operation'",
",",
"operation",
")",
";",
"this",
".",
"set",
"(",
"'Filter'",
",",
"filter",
")",
";",
"}"
] | Filter Action.
@constructor
@param {String} operation. The value of the "Operation" key.
@param {String} filter. The value of the "Filter" key.
@see Action(String)
@see See <a href="https://wiki.asterisk.org/wiki/display/AST/Asterisk+11+ManagerAction_Filter">https://wiki.asterisk.org/wiki/display/AST/Asterisk+11+ManagerAction_Filter</a>.
@augments Action | [
"Filter",
"Action",
"."
] | ccf22f09e17c1ac5ae68e09af1bc77ea6cf106a1 | https://github.com/marcelog/Nami/blob/ccf22f09e17c1ac5ae68e09af1bc77ea6cf106a1/src/message/action.js#L1192-L1196 | train |
marcelog/Nami | src/nami.js | Nami | function Nami(amiData) {
var self = this;
Nami.super_.call(this);
this.logLevel = 3; // debug level by default.
var genericLog = function(minLevel, fun, msg) {
if(self.logLevel >= minLevel) {
fun(msg);
}
};
this.logger = amiData.logger || {
error: function(msg) { genericLog(0, console.error, msg)},
warn: function(msg) { genericLog(1, console.warn, msg)},
info: function(msg) { genericLog(2, console.info, msg)},
debug: function(msg) { genericLog(3, console.log, msg)}
};
this.connected = false;
this.amiData = amiData;
this.EOL = "\r\n";
this.EOM = this.EOL + this.EOL;
this.welcomeMessage = "Asterisk Call Manager/.*" + this.EOL;
this.received = false;
this.responses = { };
this.callbacks = { };
this.on('namiRawMessage', this.onRawMessage);
this.on('namiRawResponse', this.onRawResponse);
this.on('namiRawEvent', this.onRawEvent);
} | javascript | function Nami(amiData) {
var self = this;
Nami.super_.call(this);
this.logLevel = 3; // debug level by default.
var genericLog = function(minLevel, fun, msg) {
if(self.logLevel >= minLevel) {
fun(msg);
}
};
this.logger = amiData.logger || {
error: function(msg) { genericLog(0, console.error, msg)},
warn: function(msg) { genericLog(1, console.warn, msg)},
info: function(msg) { genericLog(2, console.info, msg)},
debug: function(msg) { genericLog(3, console.log, msg)}
};
this.connected = false;
this.amiData = amiData;
this.EOL = "\r\n";
this.EOM = this.EOL + this.EOL;
this.welcomeMessage = "Asterisk Call Manager/.*" + this.EOL;
this.received = false;
this.responses = { };
this.callbacks = { };
this.on('namiRawMessage', this.onRawMessage);
this.on('namiRawResponse', this.onRawResponse);
this.on('namiRawEvent', this.onRawEvent);
} | [
"function",
"Nami",
"(",
"amiData",
")",
"{",
"var",
"self",
"=",
"this",
";",
"Nami",
".",
"super_",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"logLevel",
"=",
"3",
";",
"var",
"genericLog",
"=",
"function",
"(",
"minLevel",
",",
"fun",
",",
"msg",
")",
"{",
"if",
"(",
"self",
".",
"logLevel",
">=",
"minLevel",
")",
"{",
"fun",
"(",
"msg",
")",
";",
"}",
"}",
";",
"this",
".",
"logger",
"=",
"amiData",
".",
"logger",
"||",
"{",
"error",
":",
"function",
"(",
"msg",
")",
"{",
"genericLog",
"(",
"0",
",",
"console",
".",
"error",
",",
"msg",
")",
"}",
",",
"warn",
":",
"function",
"(",
"msg",
")",
"{",
"genericLog",
"(",
"1",
",",
"console",
".",
"warn",
",",
"msg",
")",
"}",
",",
"info",
":",
"function",
"(",
"msg",
")",
"{",
"genericLog",
"(",
"2",
",",
"console",
".",
"info",
",",
"msg",
")",
"}",
",",
"debug",
":",
"function",
"(",
"msg",
")",
"{",
"genericLog",
"(",
"3",
",",
"console",
".",
"log",
",",
"msg",
")",
"}",
"}",
";",
"this",
".",
"connected",
"=",
"false",
";",
"this",
".",
"amiData",
"=",
"amiData",
";",
"this",
".",
"EOL",
"=",
"\"\\r\\n\"",
";",
"\\r",
"\\n",
"this",
".",
"EOM",
"=",
"this",
".",
"EOL",
"+",
"this",
".",
"EOL",
";",
"this",
".",
"welcomeMessage",
"=",
"\"Asterisk Call Manager/.*\"",
"+",
"this",
".",
"EOL",
";",
"this",
".",
"received",
"=",
"false",
";",
"this",
".",
"responses",
"=",
"{",
"}",
";",
"this",
".",
"callbacks",
"=",
"{",
"}",
";",
"this",
".",
"on",
"(",
"'namiRawMessage'",
",",
"this",
".",
"onRawMessage",
")",
";",
"}"
] | Nami client.
@constructor
@param {object} amiData The configuration for ami.
@augments EventEmitter | [
"Nami",
"client",
"."
] | ccf22f09e17c1ac5ae68e09af1bc77ea6cf106a1 | https://github.com/marcelog/Nami/blob/ccf22f09e17c1ac5ae68e09af1bc77ea6cf106a1/src/nami.js#L41-L68 | train |
Gandi/react-translate | src/tools/negociateLocale.js | simpleIntersection | function simpleIntersection(array1, array2) {
return array1
// Remove falsy elements
.filter(el => el)
// Match elements belonging in the two arrays
.filter(el => array2.indexOf(el) !== -1)
// Remove duplicates
.filter((el, idx, arr) => arr.indexOf(el) === idx);
} | javascript | function simpleIntersection(array1, array2) {
return array1
// Remove falsy elements
.filter(el => el)
// Match elements belonging in the two arrays
.filter(el => array2.indexOf(el) !== -1)
// Remove duplicates
.filter((el, idx, arr) => arr.indexOf(el) === idx);
} | [
"function",
"simpleIntersection",
"(",
"array1",
",",
"array2",
")",
"{",
"return",
"array1",
".",
"filter",
"(",
"el",
"=>",
"el",
")",
".",
"filter",
"(",
"el",
"=>",
"array2",
".",
"indexOf",
"(",
"el",
")",
"!==",
"-",
"1",
")",
".",
"filter",
"(",
"(",
"el",
",",
"idx",
",",
"arr",
")",
"=>",
"arr",
".",
"indexOf",
"(",
"el",
")",
"===",
"idx",
")",
";",
"}"
] | Simple truthy-only, unique intersection function of two arrays.
@param Array array1
@param Array array2
@return Array | [
"Simple",
"truthy",
"-",
"only",
"unique",
"intersection",
"function",
"of",
"two",
"arrays",
"."
] | 17f376a71883141fab87b3c9a0ce71ce6b958842 | https://github.com/Gandi/react-translate/blob/17f376a71883141fab87b3c9a0ce71ce6b958842/src/tools/negociateLocale.js#L9-L17 | train |
vega/vega-view | src/bind.js | generate | function generate(bind, el, param, value) {
var div = element('div', {'class': BindClass});
div.appendChild(element('span',
{'class': NameClass},
(param.name || param.signal)
));
el.appendChild(div);
var input = form;
switch (param.input) {
case 'checkbox': input = checkbox; break;
case 'select': input = select; break;
case 'radio': input = radio; break;
case 'range': input = range; break;
}
input(bind, div, param, value);
} | javascript | function generate(bind, el, param, value) {
var div = element('div', {'class': BindClass});
div.appendChild(element('span',
{'class': NameClass},
(param.name || param.signal)
));
el.appendChild(div);
var input = form;
switch (param.input) {
case 'checkbox': input = checkbox; break;
case 'select': input = select; break;
case 'radio': input = radio; break;
case 'range': input = range; break;
}
input(bind, div, param, value);
} | [
"function",
"generate",
"(",
"bind",
",",
"el",
",",
"param",
",",
"value",
")",
"{",
"var",
"div",
"=",
"element",
"(",
"'div'",
",",
"{",
"'class'",
":",
"BindClass",
"}",
")",
";",
"div",
".",
"appendChild",
"(",
"element",
"(",
"'span'",
",",
"{",
"'class'",
":",
"NameClass",
"}",
",",
"(",
"param",
".",
"name",
"||",
"param",
".",
"signal",
")",
")",
")",
";",
"el",
".",
"appendChild",
"(",
"div",
")",
";",
"var",
"input",
"=",
"form",
";",
"switch",
"(",
"param",
".",
"input",
")",
"{",
"case",
"'checkbox'",
":",
"input",
"=",
"checkbox",
";",
"break",
";",
"case",
"'select'",
":",
"input",
"=",
"select",
";",
"break",
";",
"case",
"'radio'",
":",
"input",
"=",
"radio",
";",
"break",
";",
"case",
"'range'",
":",
"input",
"=",
"range",
";",
"break",
";",
"}",
"input",
"(",
"bind",
",",
"div",
",",
"param",
",",
"value",
")",
";",
"}"
] | Generate an HTML input form element and bind it to a signal. | [
"Generate",
"an",
"HTML",
"input",
"form",
"element",
"and",
"bind",
"it",
"to",
"a",
"signal",
"."
] | 44b373a104d5b8c9757a91c827d91865e88c63e7 | https://github.com/vega/vega-view/blob/44b373a104d5b8c9757a91c827d91865e88c63e7/src/bind.js#L63-L82 | train |
vega/vega-view | src/bind.js | form | function form(bind, el, param, value) {
var node = element('input');
for (var key in param) {
if (key !== 'signal' && key !== 'element') {
node.setAttribute(key === 'input' ? 'type' : key, param[key]);
}
}
node.setAttribute('name', param.signal);
node.value = value;
el.appendChild(node);
node.addEventListener('input', function() {
bind.update(node.value);
});
bind.elements = [node];
bind.set = function(value) { node.value = value; };
} | javascript | function form(bind, el, param, value) {
var node = element('input');
for (var key in param) {
if (key !== 'signal' && key !== 'element') {
node.setAttribute(key === 'input' ? 'type' : key, param[key]);
}
}
node.setAttribute('name', param.signal);
node.value = value;
el.appendChild(node);
node.addEventListener('input', function() {
bind.update(node.value);
});
bind.elements = [node];
bind.set = function(value) { node.value = value; };
} | [
"function",
"form",
"(",
"bind",
",",
"el",
",",
"param",
",",
"value",
")",
"{",
"var",
"node",
"=",
"element",
"(",
"'input'",
")",
";",
"for",
"(",
"var",
"key",
"in",
"param",
")",
"{",
"if",
"(",
"key",
"!==",
"'signal'",
"&&",
"key",
"!==",
"'element'",
")",
"{",
"node",
".",
"setAttribute",
"(",
"key",
"===",
"'input'",
"?",
"'type'",
":",
"key",
",",
"param",
"[",
"key",
"]",
")",
";",
"}",
"}",
"node",
".",
"setAttribute",
"(",
"'name'",
",",
"param",
".",
"signal",
")",
";",
"node",
".",
"value",
"=",
"value",
";",
"el",
".",
"appendChild",
"(",
"node",
")",
";",
"node",
".",
"addEventListener",
"(",
"'input'",
",",
"function",
"(",
")",
"{",
"bind",
".",
"update",
"(",
"node",
".",
"value",
")",
";",
"}",
")",
";",
"bind",
".",
"elements",
"=",
"[",
"node",
"]",
";",
"bind",
".",
"set",
"=",
"function",
"(",
"value",
")",
"{",
"node",
".",
"value",
"=",
"value",
";",
"}",
";",
"}"
] | Generates an arbitrary input form element.
The input type is controlled via user-provided parameters. | [
"Generates",
"an",
"arbitrary",
"input",
"form",
"element",
".",
"The",
"input",
"type",
"is",
"controlled",
"via",
"user",
"-",
"provided",
"parameters",
"."
] | 44b373a104d5b8c9757a91c827d91865e88c63e7 | https://github.com/vega/vega-view/blob/44b373a104d5b8c9757a91c827d91865e88c63e7/src/bind.js#L88-L107 | train |
vega/vega-view | src/bind.js | checkbox | function checkbox(bind, el, param, value) {
var attr = {type: 'checkbox', name: param.signal};
if (value) attr.checked = true;
var node = element('input', attr);
el.appendChild(node);
node.addEventListener('change', function() {
bind.update(node.checked);
});
bind.elements = [node];
bind.set = function(value) { node.checked = !!value || null; }
} | javascript | function checkbox(bind, el, param, value) {
var attr = {type: 'checkbox', name: param.signal};
if (value) attr.checked = true;
var node = element('input', attr);
el.appendChild(node);
node.addEventListener('change', function() {
bind.update(node.checked);
});
bind.elements = [node];
bind.set = function(value) { node.checked = !!value || null; }
} | [
"function",
"checkbox",
"(",
"bind",
",",
"el",
",",
"param",
",",
"value",
")",
"{",
"var",
"attr",
"=",
"{",
"type",
":",
"'checkbox'",
",",
"name",
":",
"param",
".",
"signal",
"}",
";",
"if",
"(",
"value",
")",
"attr",
".",
"checked",
"=",
"true",
";",
"var",
"node",
"=",
"element",
"(",
"'input'",
",",
"attr",
")",
";",
"el",
".",
"appendChild",
"(",
"node",
")",
";",
"node",
".",
"addEventListener",
"(",
"'change'",
",",
"function",
"(",
")",
"{",
"bind",
".",
"update",
"(",
"node",
".",
"checked",
")",
";",
"}",
")",
";",
"bind",
".",
"elements",
"=",
"[",
"node",
"]",
";",
"bind",
".",
"set",
"=",
"function",
"(",
"value",
")",
"{",
"node",
".",
"checked",
"=",
"!",
"!",
"value",
"||",
"null",
";",
"}",
"}"
] | Generates a checkbox input element. | [
"Generates",
"a",
"checkbox",
"input",
"element",
"."
] | 44b373a104d5b8c9757a91c827d91865e88c63e7 | https://github.com/vega/vega-view/blob/44b373a104d5b8c9757a91c827d91865e88c63e7/src/bind.js#L112-L125 | train |
vega/vega-view | src/bind.js | select | function select(bind, el, param, value) {
var node = element('select', {name: param.signal});
param.options.forEach(function(option) {
var attr = {value: option};
if (valuesEqual(option, value)) attr.selected = true;
node.appendChild(element('option', attr, option+''));
});
el.appendChild(node);
node.addEventListener('change', function() {
bind.update(param.options[node.selectedIndex]);
});
bind.elements = [node];
bind.set = function(value) {
for (var i=0, n=param.options.length; i<n; ++i) {
if (valuesEqual(param.options[i], value)) {
node.selectedIndex = i; return;
}
}
};
} | javascript | function select(bind, el, param, value) {
var node = element('select', {name: param.signal});
param.options.forEach(function(option) {
var attr = {value: option};
if (valuesEqual(option, value)) attr.selected = true;
node.appendChild(element('option', attr, option+''));
});
el.appendChild(node);
node.addEventListener('change', function() {
bind.update(param.options[node.selectedIndex]);
});
bind.elements = [node];
bind.set = function(value) {
for (var i=0, n=param.options.length; i<n; ++i) {
if (valuesEqual(param.options[i], value)) {
node.selectedIndex = i; return;
}
}
};
} | [
"function",
"select",
"(",
"bind",
",",
"el",
",",
"param",
",",
"value",
")",
"{",
"var",
"node",
"=",
"element",
"(",
"'select'",
",",
"{",
"name",
":",
"param",
".",
"signal",
"}",
")",
";",
"param",
".",
"options",
".",
"forEach",
"(",
"function",
"(",
"option",
")",
"{",
"var",
"attr",
"=",
"{",
"value",
":",
"option",
"}",
";",
"if",
"(",
"valuesEqual",
"(",
"option",
",",
"value",
")",
")",
"attr",
".",
"selected",
"=",
"true",
";",
"node",
".",
"appendChild",
"(",
"element",
"(",
"'option'",
",",
"attr",
",",
"option",
"+",
"''",
")",
")",
";",
"}",
")",
";",
"el",
".",
"appendChild",
"(",
"node",
")",
";",
"node",
".",
"addEventListener",
"(",
"'change'",
",",
"function",
"(",
")",
"{",
"bind",
".",
"update",
"(",
"param",
".",
"options",
"[",
"node",
".",
"selectedIndex",
"]",
")",
";",
"}",
")",
";",
"bind",
".",
"elements",
"=",
"[",
"node",
"]",
";",
"bind",
".",
"set",
"=",
"function",
"(",
"value",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"param",
".",
"options",
".",
"length",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"if",
"(",
"valuesEqual",
"(",
"param",
".",
"options",
"[",
"i",
"]",
",",
"value",
")",
")",
"{",
"node",
".",
"selectedIndex",
"=",
"i",
";",
"return",
";",
"}",
"}",
"}",
";",
"}"
] | Generates a selection list input element. | [
"Generates",
"a",
"selection",
"list",
"input",
"element",
"."
] | 44b373a104d5b8c9757a91c827d91865e88c63e7 | https://github.com/vega/vega-view/blob/44b373a104d5b8c9757a91c827d91865e88c63e7/src/bind.js#L130-L153 | train |
vega/vega-view | src/bind.js | radio | function radio(bind, el, param, value) {
var group = element('span', {'class': RadioClass});
el.appendChild(group);
bind.elements = param.options.map(function(option) {
var id = OptionClass + param.signal + '-' + option;
var attr = {
id: id,
type: 'radio',
name: param.signal,
value: option
};
if (valuesEqual(option, value)) attr.checked = true;
var input = element('input', attr);
input.addEventListener('change', function() {
bind.update(option);
});
group.appendChild(input);
group.appendChild(element('label', {'for': id}, option+''));
return input;
});
bind.set = function(value) {
var nodes = bind.elements,
i = 0,
n = nodes.length;
for (; i<n; ++i) {
if (valuesEqual(nodes[i].value, value)) nodes[i].checked = true;
}
};
} | javascript | function radio(bind, el, param, value) {
var group = element('span', {'class': RadioClass});
el.appendChild(group);
bind.elements = param.options.map(function(option) {
var id = OptionClass + param.signal + '-' + option;
var attr = {
id: id,
type: 'radio',
name: param.signal,
value: option
};
if (valuesEqual(option, value)) attr.checked = true;
var input = element('input', attr);
input.addEventListener('change', function() {
bind.update(option);
});
group.appendChild(input);
group.appendChild(element('label', {'for': id}, option+''));
return input;
});
bind.set = function(value) {
var nodes = bind.elements,
i = 0,
n = nodes.length;
for (; i<n; ++i) {
if (valuesEqual(nodes[i].value, value)) nodes[i].checked = true;
}
};
} | [
"function",
"radio",
"(",
"bind",
",",
"el",
",",
"param",
",",
"value",
")",
"{",
"var",
"group",
"=",
"element",
"(",
"'span'",
",",
"{",
"'class'",
":",
"RadioClass",
"}",
")",
";",
"el",
".",
"appendChild",
"(",
"group",
")",
";",
"bind",
".",
"elements",
"=",
"param",
".",
"options",
".",
"map",
"(",
"function",
"(",
"option",
")",
"{",
"var",
"id",
"=",
"OptionClass",
"+",
"param",
".",
"signal",
"+",
"'-'",
"+",
"option",
";",
"var",
"attr",
"=",
"{",
"id",
":",
"id",
",",
"type",
":",
"'radio'",
",",
"name",
":",
"param",
".",
"signal",
",",
"value",
":",
"option",
"}",
";",
"if",
"(",
"valuesEqual",
"(",
"option",
",",
"value",
")",
")",
"attr",
".",
"checked",
"=",
"true",
";",
"var",
"input",
"=",
"element",
"(",
"'input'",
",",
"attr",
")",
";",
"input",
".",
"addEventListener",
"(",
"'change'",
",",
"function",
"(",
")",
"{",
"bind",
".",
"update",
"(",
"option",
")",
";",
"}",
")",
";",
"group",
".",
"appendChild",
"(",
"input",
")",
";",
"group",
".",
"appendChild",
"(",
"element",
"(",
"'label'",
",",
"{",
"'for'",
":",
"id",
"}",
",",
"option",
"+",
"''",
")",
")",
";",
"return",
"input",
";",
"}",
")",
";",
"bind",
".",
"set",
"=",
"function",
"(",
"value",
")",
"{",
"var",
"nodes",
"=",
"bind",
".",
"elements",
",",
"i",
"=",
"0",
",",
"n",
"=",
"nodes",
".",
"length",
";",
"for",
"(",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"if",
"(",
"valuesEqual",
"(",
"nodes",
"[",
"i",
"]",
".",
"value",
",",
"value",
")",
")",
"nodes",
"[",
"i",
"]",
".",
"checked",
"=",
"true",
";",
"}",
"}",
";",
"}"
] | Generates a radio button group. | [
"Generates",
"a",
"radio",
"button",
"group",
"."
] | 44b373a104d5b8c9757a91c827d91865e88c63e7 | https://github.com/vega/vega-view/blob/44b373a104d5b8c9757a91c827d91865e88c63e7/src/bind.js#L158-L194 | train |
vega/vega-view | src/bind.js | range | function range(bind, el, param, value) {
value = value !== undefined ? value : ((+param.max) + (+param.min)) / 2;
var min = param.min || Math.min(0, +value) || 0,
max = param.max || Math.max(100, +value) || 100,
step = param.step || tickStep(min, max, 100);
var node = element('input', {
type: 'range',
name: param.signal,
min: min,
max: max,
step: step
});
node.value = value;
var label = element('label', {}, +value);
el.appendChild(node);
el.appendChild(label);
function update() {
label.textContent = node.value;
bind.update(+node.value);
}
// subscribe to both input and change
node.addEventListener('input', update);
node.addEventListener('change', update);
bind.elements = [node];
bind.set = function(value) {
node.value = value;
label.textContent = value;
};
} | javascript | function range(bind, el, param, value) {
value = value !== undefined ? value : ((+param.max) + (+param.min)) / 2;
var min = param.min || Math.min(0, +value) || 0,
max = param.max || Math.max(100, +value) || 100,
step = param.step || tickStep(min, max, 100);
var node = element('input', {
type: 'range',
name: param.signal,
min: min,
max: max,
step: step
});
node.value = value;
var label = element('label', {}, +value);
el.appendChild(node);
el.appendChild(label);
function update() {
label.textContent = node.value;
bind.update(+node.value);
}
// subscribe to both input and change
node.addEventListener('input', update);
node.addEventListener('change', update);
bind.elements = [node];
bind.set = function(value) {
node.value = value;
label.textContent = value;
};
} | [
"function",
"range",
"(",
"bind",
",",
"el",
",",
"param",
",",
"value",
")",
"{",
"value",
"=",
"value",
"!==",
"undefined",
"?",
"value",
":",
"(",
"(",
"+",
"param",
".",
"max",
")",
"+",
"(",
"+",
"param",
".",
"min",
")",
")",
"/",
"2",
";",
"var",
"min",
"=",
"param",
".",
"min",
"||",
"Math",
".",
"min",
"(",
"0",
",",
"+",
"value",
")",
"||",
"0",
",",
"max",
"=",
"param",
".",
"max",
"||",
"Math",
".",
"max",
"(",
"100",
",",
"+",
"value",
")",
"||",
"100",
",",
"step",
"=",
"param",
".",
"step",
"||",
"tickStep",
"(",
"min",
",",
"max",
",",
"100",
")",
";",
"var",
"node",
"=",
"element",
"(",
"'input'",
",",
"{",
"type",
":",
"'range'",
",",
"name",
":",
"param",
".",
"signal",
",",
"min",
":",
"min",
",",
"max",
":",
"max",
",",
"step",
":",
"step",
"}",
")",
";",
"node",
".",
"value",
"=",
"value",
";",
"var",
"label",
"=",
"element",
"(",
"'label'",
",",
"{",
"}",
",",
"+",
"value",
")",
";",
"el",
".",
"appendChild",
"(",
"node",
")",
";",
"el",
".",
"appendChild",
"(",
"label",
")",
";",
"function",
"update",
"(",
")",
"{",
"label",
".",
"textContent",
"=",
"node",
".",
"value",
";",
"bind",
".",
"update",
"(",
"+",
"node",
".",
"value",
")",
";",
"}",
"node",
".",
"addEventListener",
"(",
"'input'",
",",
"update",
")",
";",
"node",
".",
"addEventListener",
"(",
"'change'",
",",
"update",
")",
";",
"bind",
".",
"elements",
"=",
"[",
"node",
"]",
";",
"bind",
".",
"set",
"=",
"function",
"(",
"value",
")",
"{",
"node",
".",
"value",
"=",
"value",
";",
"label",
".",
"textContent",
"=",
"value",
";",
"}",
";",
"}"
] | Generates a slider input element. | [
"Generates",
"a",
"slider",
"input",
"element",
"."
] | 44b373a104d5b8c9757a91c827d91865e88c63e7 | https://github.com/vega/vega-view/blob/44b373a104d5b8c9757a91c827d91865e88c63e7/src/bind.js#L199-L234 | train |
paulkr/quietflow.js | lib/quietflow.js | randCol | function randCol (r, g, b, a) {
return "rgba(" + Math.floor(Math.random() * r).toString() + "," +
Math.floor(Math.random() * g).toString() + "," +
Math.floor(Math.random() * b).toString() + "," + a + ")";
} | javascript | function randCol (r, g, b, a) {
return "rgba(" + Math.floor(Math.random() * r).toString() + "," +
Math.floor(Math.random() * g).toString() + "," +
Math.floor(Math.random() * b).toString() + "," + a + ")";
} | [
"function",
"randCol",
"(",
"r",
",",
"g",
",",
"b",
",",
"a",
")",
"{",
"return",
"\"rgba(\"",
"+",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"r",
")",
".",
"toString",
"(",
")",
"+",
"\",\"",
"+",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"g",
")",
".",
"toString",
"(",
")",
"+",
"\",\"",
"+",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"b",
")",
".",
"toString",
"(",
")",
"+",
"\",\"",
"+",
"a",
"+",
"\")\"",
";",
"}"
] | quietflow.js
Paul Krishnamurthy 2016
https://paulkr.com
[email protected] | [
"quietflow",
".",
"js",
"Paul",
"Krishnamurthy",
"2016"
] | 0e0b11eb3abfd8e550d9c636e791b0d22240a7b0 | https://github.com/paulkr/quietflow.js/blob/0e0b11eb3abfd8e550d9c636e791b0d22240a7b0/lib/quietflow.js#L9-L13 | train |
paulkr/quietflow.js | lib/quietflow.js | render | function render (callback) {
if (effectAttrs.speed !== undefined) {
setTimeout(function () {
id = requestAnimationFrame(callback);
}, effectAttrs.speed);
} else {
id = requestAnimationFrame(callback);
}
} | javascript | function render (callback) {
if (effectAttrs.speed !== undefined) {
setTimeout(function () {
id = requestAnimationFrame(callback);
}, effectAttrs.speed);
} else {
id = requestAnimationFrame(callback);
}
} | [
"function",
"render",
"(",
"callback",
")",
"{",
"if",
"(",
"effectAttrs",
".",
"speed",
"!==",
"undefined",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"id",
"=",
"requestAnimationFrame",
"(",
"callback",
")",
";",
"}",
",",
"effectAttrs",
".",
"speed",
")",
";",
"}",
"else",
"{",
"id",
"=",
"requestAnimationFrame",
"(",
"callback",
")",
";",
"}",
"}"
] | Render based on interval or automatically | [
"Render",
"based",
"on",
"interval",
"or",
"automatically"
] | 0e0b11eb3abfd8e550d9c636e791b0d22240a7b0 | https://github.com/paulkr/quietflow.js/blob/0e0b11eb3abfd8e550d9c636e791b0d22240a7b0/lib/quietflow.js#L167-L176 | train |
macedigital/express-xml-bodyparser | lib/types/xml.js | xmlparser | function xmlparser(options) {
var parserOptions = util._extend({
async: false,
explicitArray: true,
normalize: true,
normalizeTags: true,
trim: true
}, options || {});
return xmlbodyparser;
/**
* Provide connect/express-style middleware
*
* @param {IncomingMessage} req
* @param {ServerResponse} res
* @param {Function} next
* @return {*}
*/
function xmlbodyparser(req, res, next) {
var data = '';
var parser = new xml2js.Parser(parserOptions);
/**
* @param {Error} err
* @param {Object} [xml]
*/
var responseHandler = function (err, xml) {
if (err) {
err.status = 400;
return next(err);
}
req.body = xml || req.body;
req.rawBody = data;
next();
};
if (req._body) {
return next();
}
req.body = req.body || {};
if (!hasBody(req) || !module.exports.regexp.test(mime(req))) {
return next();
}
req._body = true;
// explicitly cast incoming to string
req.setEncoding('utf-8');
req.on('data', function (chunk) {
data += chunk;
});
// in case `parseString` callback never was called, ensure response is sent
parser.saxParser.onend = function() {
if (req.complete && req.rawBody === undefined) {
return responseHandler(null);
}
};
req.on('end', function () {
// invalid xml, length required
if (data.trim().length === 0) {
return next(error(411));
}
parser.parseString(data, responseHandler);
});
}
} | javascript | function xmlparser(options) {
var parserOptions = util._extend({
async: false,
explicitArray: true,
normalize: true,
normalizeTags: true,
trim: true
}, options || {});
return xmlbodyparser;
/**
* Provide connect/express-style middleware
*
* @param {IncomingMessage} req
* @param {ServerResponse} res
* @param {Function} next
* @return {*}
*/
function xmlbodyparser(req, res, next) {
var data = '';
var parser = new xml2js.Parser(parserOptions);
/**
* @param {Error} err
* @param {Object} [xml]
*/
var responseHandler = function (err, xml) {
if (err) {
err.status = 400;
return next(err);
}
req.body = xml || req.body;
req.rawBody = data;
next();
};
if (req._body) {
return next();
}
req.body = req.body || {};
if (!hasBody(req) || !module.exports.regexp.test(mime(req))) {
return next();
}
req._body = true;
// explicitly cast incoming to string
req.setEncoding('utf-8');
req.on('data', function (chunk) {
data += chunk;
});
// in case `parseString` callback never was called, ensure response is sent
parser.saxParser.onend = function() {
if (req.complete && req.rawBody === undefined) {
return responseHandler(null);
}
};
req.on('end', function () {
// invalid xml, length required
if (data.trim().length === 0) {
return next(error(411));
}
parser.parseString(data, responseHandler);
});
}
} | [
"function",
"xmlparser",
"(",
"options",
")",
"{",
"var",
"parserOptions",
"=",
"util",
".",
"_extend",
"(",
"{",
"async",
":",
"false",
",",
"explicitArray",
":",
"true",
",",
"normalize",
":",
"true",
",",
"normalizeTags",
":",
"true",
",",
"trim",
":",
"true",
"}",
",",
"options",
"||",
"{",
"}",
")",
";",
"return",
"xmlbodyparser",
";",
"function",
"xmlbodyparser",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"data",
"=",
"''",
";",
"var",
"parser",
"=",
"new",
"xml2js",
".",
"Parser",
"(",
"parserOptions",
")",
";",
"var",
"responseHandler",
"=",
"function",
"(",
"err",
",",
"xml",
")",
"{",
"if",
"(",
"err",
")",
"{",
"err",
".",
"status",
"=",
"400",
";",
"return",
"next",
"(",
"err",
")",
";",
"}",
"req",
".",
"body",
"=",
"xml",
"||",
"req",
".",
"body",
";",
"req",
".",
"rawBody",
"=",
"data",
";",
"next",
"(",
")",
";",
"}",
";",
"if",
"(",
"req",
".",
"_body",
")",
"{",
"return",
"next",
"(",
")",
";",
"}",
"req",
".",
"body",
"=",
"req",
".",
"body",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"hasBody",
"(",
"req",
")",
"||",
"!",
"module",
".",
"exports",
".",
"regexp",
".",
"test",
"(",
"mime",
"(",
"req",
")",
")",
")",
"{",
"return",
"next",
"(",
")",
";",
"}",
"req",
".",
"_body",
"=",
"true",
";",
"req",
".",
"setEncoding",
"(",
"'utf-8'",
")",
";",
"req",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"data",
"+=",
"chunk",
";",
"}",
")",
";",
"parser",
".",
"saxParser",
".",
"onend",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"req",
".",
"complete",
"&&",
"req",
".",
"rawBody",
"===",
"undefined",
")",
"{",
"return",
"responseHandler",
"(",
"null",
")",
";",
"}",
"}",
";",
"req",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"data",
".",
"trim",
"(",
")",
".",
"length",
"===",
"0",
")",
"{",
"return",
"next",
"(",
"error",
"(",
"411",
")",
")",
";",
"}",
"parser",
".",
"parseString",
"(",
"data",
",",
"responseHandler",
")",
";",
"}",
")",
";",
"}",
"}"
] | Expose configuration for xml-bodyparser middleware
@api public
@param {Object} [options] Parser options
@return {Function} | [
"Expose",
"configuration",
"for",
"xml",
"-",
"bodyparser",
"middleware"
] | 65de9f64ccf0e5b66754bfafb425e4602612ad31 | https://github.com/macedigital/express-xml-bodyparser/blob/65de9f64ccf0e5b66754bfafb425e4602612ad31/lib/types/xml.js#L27-L107 | train |
macedigital/express-xml-bodyparser | lib/types/xml.js | hasBody | function hasBody(req) {
var encoding = 'transfer-encoding' in req.headers;
var length = 'content-length' in req.headers && req.headers['content-length'] !== '0';
return encoding || length;
} | javascript | function hasBody(req) {
var encoding = 'transfer-encoding' in req.headers;
var length = 'content-length' in req.headers && req.headers['content-length'] !== '0';
return encoding || length;
} | [
"function",
"hasBody",
"(",
"req",
")",
"{",
"var",
"encoding",
"=",
"'transfer-encoding'",
"in",
"req",
".",
"headers",
";",
"var",
"length",
"=",
"'content-length'",
"in",
"req",
".",
"headers",
"&&",
"req",
".",
"headers",
"[",
"'content-length'",
"]",
"!==",
"'0'",
";",
"return",
"encoding",
"||",
"length",
";",
"}"
] | Test whether request has body
@see connect.utils
@param {IncomingMessage} req
@return {boolean} | [
"Test",
"whether",
"request",
"has",
"body"
] | 65de9f64ccf0e5b66754bfafb425e4602612ad31 | https://github.com/macedigital/express-xml-bodyparser/blob/65de9f64ccf0e5b66754bfafb425e4602612ad31/lib/types/xml.js#L117-L121 | train |
caroso1222/amazon-autocomplete | src/amazon-autocomplete.js | _processOnKeyUp__noWords | function _processOnKeyUp__noWords(evt) {
let key = evt.keyCode || evt.which;
let char = String.fromCharCode(key);
if (key == 13) {
this._onSelectedCB(this._input.value);
}else if (/[a-zA-Z0-9-_ ]/.test(char) || key === 8){
let prefix = this._input.value;
if (prefix != '')
this._keyListenerDebounced(prefix);
}
} | javascript | function _processOnKeyUp__noWords(evt) {
let key = evt.keyCode || evt.which;
let char = String.fromCharCode(key);
if (key == 13) {
this._onSelectedCB(this._input.value);
}else if (/[a-zA-Z0-9-_ ]/.test(char) || key === 8){
let prefix = this._input.value;
if (prefix != '')
this._keyListenerDebounced(prefix);
}
} | [
"function",
"_processOnKeyUp__noWords",
"(",
"evt",
")",
"{",
"let",
"key",
"=",
"evt",
".",
"keyCode",
"||",
"evt",
".",
"which",
";",
"let",
"char",
"=",
"String",
".",
"fromCharCode",
"(",
"key",
")",
";",
"if",
"(",
"key",
"==",
"13",
")",
"{",
"this",
".",
"_onSelectedCB",
"(",
"this",
".",
"_input",
".",
"value",
")",
";",
"}",
"else",
"if",
"(",
"/",
"[a-zA-Z0-9-_ ]",
"/",
".",
"test",
"(",
"char",
")",
"||",
"key",
"===",
"8",
")",
"{",
"let",
"prefix",
"=",
"this",
".",
"_input",
".",
"value",
";",
"if",
"(",
"prefix",
"!=",
"''",
")",
"this",
".",
"_keyListenerDebounced",
"(",
"prefix",
")",
";",
"}",
"}"
] | Listen to a keyup event on the search input. This function will NOT handle navigation
inside the words ui widget.
@param {event} evt - Keyup event | [
"Listen",
"to",
"a",
"keyup",
"event",
"on",
"the",
"search",
"input",
".",
"This",
"function",
"will",
"NOT",
"handle",
"navigation",
"inside",
"the",
"words",
"ui",
"widget",
"."
] | 1638b787296b6e248687b263e9e12a472470972d | https://github.com/caroso1222/amazon-autocomplete/blob/1638b787296b6e248687b263e9e12a472470972d/src/amazon-autocomplete.js#L213-L223 | train |
caroso1222/amazon-autocomplete | src/amazon-autocomplete.js | _processOnKeyUp | function _processOnKeyUp(evt) {
let key = evt.keyCode || evt.which;
let char = String.fromCharCode(key);
let self = this;
if (key === 38) {
if (self._idx > 0) {
_unselectWord(self._words[self._idx]);
self._idx--;
}
self._words[self._idx].className += ' ac__word--selected';
} else if (key == 40) {
if (self._idx < self._words.length - 1) {
_unselectWord(self._words[self._idx]);
self._idx++;
}
self._words[self._idx].className += ' ac__word--selected';
} else if (key == 13) {
if (self._words.length && self._idx > -1)
self._onSelectedCB(_getStringFromWordElement(self._words[self._idx]));
else
self._onSelectedCB(self._input.value);
} else if (/[a-zA-Z0-9-_ ]/.test(char) || key === 8) {
self._idx = -1;
let prefix = self._input.value;
if (prefix != '')
self._keyListenerDebounced(prefix);
else
_flushWordsContainer.call(self);
}
} | javascript | function _processOnKeyUp(evt) {
let key = evt.keyCode || evt.which;
let char = String.fromCharCode(key);
let self = this;
if (key === 38) {
if (self._idx > 0) {
_unselectWord(self._words[self._idx]);
self._idx--;
}
self._words[self._idx].className += ' ac__word--selected';
} else if (key == 40) {
if (self._idx < self._words.length - 1) {
_unselectWord(self._words[self._idx]);
self._idx++;
}
self._words[self._idx].className += ' ac__word--selected';
} else if (key == 13) {
if (self._words.length && self._idx > -1)
self._onSelectedCB(_getStringFromWordElement(self._words[self._idx]));
else
self._onSelectedCB(self._input.value);
} else if (/[a-zA-Z0-9-_ ]/.test(char) || key === 8) {
self._idx = -1;
let prefix = self._input.value;
if (prefix != '')
self._keyListenerDebounced(prefix);
else
_flushWordsContainer.call(self);
}
} | [
"function",
"_processOnKeyUp",
"(",
"evt",
")",
"{",
"let",
"key",
"=",
"evt",
".",
"keyCode",
"||",
"evt",
".",
"which",
";",
"let",
"char",
"=",
"String",
".",
"fromCharCode",
"(",
"key",
")",
";",
"let",
"self",
"=",
"this",
";",
"if",
"(",
"key",
"===",
"38",
")",
"{",
"if",
"(",
"self",
".",
"_idx",
">",
"0",
")",
"{",
"_unselectWord",
"(",
"self",
".",
"_words",
"[",
"self",
".",
"_idx",
"]",
")",
";",
"self",
".",
"_idx",
"--",
";",
"}",
"self",
".",
"_words",
"[",
"self",
".",
"_idx",
"]",
".",
"className",
"+=",
"' ac__word--selected'",
";",
"}",
"else",
"if",
"(",
"key",
"==",
"40",
")",
"{",
"if",
"(",
"self",
".",
"_idx",
"<",
"self",
".",
"_words",
".",
"length",
"-",
"1",
")",
"{",
"_unselectWord",
"(",
"self",
".",
"_words",
"[",
"self",
".",
"_idx",
"]",
")",
";",
"self",
".",
"_idx",
"++",
";",
"}",
"self",
".",
"_words",
"[",
"self",
".",
"_idx",
"]",
".",
"className",
"+=",
"' ac__word--selected'",
";",
"}",
"else",
"if",
"(",
"key",
"==",
"13",
")",
"{",
"if",
"(",
"self",
".",
"_words",
".",
"length",
"&&",
"self",
".",
"_idx",
">",
"-",
"1",
")",
"self",
".",
"_onSelectedCB",
"(",
"_getStringFromWordElement",
"(",
"self",
".",
"_words",
"[",
"self",
".",
"_idx",
"]",
")",
")",
";",
"else",
"self",
".",
"_onSelectedCB",
"(",
"self",
".",
"_input",
".",
"value",
")",
";",
"}",
"else",
"if",
"(",
"/",
"[a-zA-Z0-9-_ ]",
"/",
".",
"test",
"(",
"char",
")",
"||",
"key",
"===",
"8",
")",
"{",
"self",
".",
"_idx",
"=",
"-",
"1",
";",
"let",
"prefix",
"=",
"self",
".",
"_input",
".",
"value",
";",
"if",
"(",
"prefix",
"!=",
"''",
")",
"self",
".",
"_keyListenerDebounced",
"(",
"prefix",
")",
";",
"else",
"_flushWordsContainer",
".",
"call",
"(",
"self",
")",
";",
"}",
"}"
] | Listen to a keyup event on the search input. This function will handle navigation
inside the words ui widget by listening to up and down arrows.
@param {event} evt - Keyup event | [
"Listen",
"to",
"a",
"keyup",
"event",
"on",
"the",
"search",
"input",
".",
"This",
"function",
"will",
"handle",
"navigation",
"inside",
"the",
"words",
"ui",
"widget",
"by",
"listening",
"to",
"up",
"and",
"down",
"arrows",
"."
] | 1638b787296b6e248687b263e9e12a472470972d | https://github.com/caroso1222/amazon-autocomplete/blob/1638b787296b6e248687b263e9e12a472470972d/src/amazon-autocomplete.js#L231-L260 | train |
caroso1222/amazon-autocomplete | src/amazon-autocomplete.js | _buildScriptContainer | function _buildScriptContainer(){
let parent = document.getElementById('ac__script');
if (parent == null){
parent = document.createElement('div');
parent.id = 'ac__script';
parent.appendChild(document.createElement('script'));
document.body.appendChild(parent);
}
} | javascript | function _buildScriptContainer(){
let parent = document.getElementById('ac__script');
if (parent == null){
parent = document.createElement('div');
parent.id = 'ac__script';
parent.appendChild(document.createElement('script'));
document.body.appendChild(parent);
}
} | [
"function",
"_buildScriptContainer",
"(",
")",
"{",
"let",
"parent",
"=",
"document",
".",
"getElementById",
"(",
"'ac__script'",
")",
";",
"if",
"(",
"parent",
"==",
"null",
")",
"{",
"parent",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"parent",
".",
"id",
"=",
"'ac__script'",
";",
"parent",
".",
"appendChild",
"(",
"document",
".",
"createElement",
"(",
"'script'",
")",
")",
";",
"document",
".",
"body",
".",
"appendChild",
"(",
"parent",
")",
";",
"}",
"}"
] | Create the script tag needed to fetch the suggestions and append it to the DOM | [
"Create",
"the",
"script",
"tag",
"needed",
"to",
"fetch",
"the",
"suggestions",
"and",
"append",
"it",
"to",
"the",
"DOM"
] | 1638b787296b6e248687b263e9e12a472470972d | https://github.com/caroso1222/amazon-autocomplete/blob/1638b787296b6e248687b263e9e12a472470972d/src/amazon-autocomplete.js#L265-L273 | train |
caroso1222/amazon-autocomplete | src/amazon-autocomplete.js | _paintWords | function _paintWords(prefix, words){
_flushWordsContainer.call(this);
this._words = [];
let docFrag = document.createDocumentFragment();
for (let i = 0; i < words.length; i++){
let wordElement = document.createElement('p');
wordElement.className = 'ac__word';
wordElement.style.cursor = 'pointer';
let prefixElement = document.createElement('span');
prefixElement.className = 'ac__prefix';
prefixElement.style.pointerEvents = 'none';
let suffix = document.createTextNode(words[i].slice(prefix.length));
prefixElement.appendChild(document.createTextNode(prefix));
wordElement.appendChild(prefixElement);
wordElement.appendChild(suffix);
docFrag.appendChild(wordElement);
this._words.push(wordElement);
}
this._container.appendChild(docFrag);
} | javascript | function _paintWords(prefix, words){
_flushWordsContainer.call(this);
this._words = [];
let docFrag = document.createDocumentFragment();
for (let i = 0; i < words.length; i++){
let wordElement = document.createElement('p');
wordElement.className = 'ac__word';
wordElement.style.cursor = 'pointer';
let prefixElement = document.createElement('span');
prefixElement.className = 'ac__prefix';
prefixElement.style.pointerEvents = 'none';
let suffix = document.createTextNode(words[i].slice(prefix.length));
prefixElement.appendChild(document.createTextNode(prefix));
wordElement.appendChild(prefixElement);
wordElement.appendChild(suffix);
docFrag.appendChild(wordElement);
this._words.push(wordElement);
}
this._container.appendChild(docFrag);
} | [
"function",
"_paintWords",
"(",
"prefix",
",",
"words",
")",
"{",
"_flushWordsContainer",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"_words",
"=",
"[",
"]",
";",
"let",
"docFrag",
"=",
"document",
".",
"createDocumentFragment",
"(",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"words",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"wordElement",
"=",
"document",
".",
"createElement",
"(",
"'p'",
")",
";",
"wordElement",
".",
"className",
"=",
"'ac__word'",
";",
"wordElement",
".",
"style",
".",
"cursor",
"=",
"'pointer'",
";",
"let",
"prefixElement",
"=",
"document",
".",
"createElement",
"(",
"'span'",
")",
";",
"prefixElement",
".",
"className",
"=",
"'ac__prefix'",
";",
"prefixElement",
".",
"style",
".",
"pointerEvents",
"=",
"'none'",
";",
"let",
"suffix",
"=",
"document",
".",
"createTextNode",
"(",
"words",
"[",
"i",
"]",
".",
"slice",
"(",
"prefix",
".",
"length",
")",
")",
";",
"prefixElement",
".",
"appendChild",
"(",
"document",
".",
"createTextNode",
"(",
"prefix",
")",
")",
";",
"wordElement",
".",
"appendChild",
"(",
"prefixElement",
")",
";",
"wordElement",
".",
"appendChild",
"(",
"suffix",
")",
";",
"docFrag",
".",
"appendChild",
"(",
"wordElement",
")",
";",
"this",
".",
"_words",
".",
"push",
"(",
"wordElement",
")",
";",
"}",
"this",
".",
"_container",
".",
"appendChild",
"(",
"docFrag",
")",
";",
"}"
] | Build the ui widget that shows the words under the search html input
@param {string} prefix - The letters written by the user in the html search input
@param {Array<string>} words - The list of words that must be painted inside the widget | [
"Build",
"the",
"ui",
"widget",
"that",
"shows",
"the",
"words",
"under",
"the",
"search",
"html",
"input"
] | 1638b787296b6e248687b263e9e12a472470972d | https://github.com/caroso1222/amazon-autocomplete/blob/1638b787296b6e248687b263e9e12a472470972d/src/amazon-autocomplete.js#L281-L300 | train |
caroso1222/amazon-autocomplete | src/amazon-autocomplete.js | _getSuggestions | function _getSuggestions(prefix) {
let scriptContainer = document.getElementById('ac__script');
let newScript = document.createElement('script');
newScript.src = 'http://completion.amazon.com/search/complete?search-alias=aps&client=amazon-search-ui&mkt=1&q='+prefix+'&callback=AmazonAutocomplete.AmazonJSONPCallbackHandler_'+this._id;
scriptContainer.replaceChild(newScript, scriptContainer.firstChild);
} | javascript | function _getSuggestions(prefix) {
let scriptContainer = document.getElementById('ac__script');
let newScript = document.createElement('script');
newScript.src = 'http://completion.amazon.com/search/complete?search-alias=aps&client=amazon-search-ui&mkt=1&q='+prefix+'&callback=AmazonAutocomplete.AmazonJSONPCallbackHandler_'+this._id;
scriptContainer.replaceChild(newScript, scriptContainer.firstChild);
} | [
"function",
"_getSuggestions",
"(",
"prefix",
")",
"{",
"let",
"scriptContainer",
"=",
"document",
".",
"getElementById",
"(",
"'ac__script'",
")",
";",
"let",
"newScript",
"=",
"document",
".",
"createElement",
"(",
"'script'",
")",
";",
"newScript",
".",
"src",
"=",
"'http://completion.amazon.com/search/complete?search-alias=aps&client=amazon-search-ui&mkt=1&q='",
"+",
"prefix",
"+",
"'&callback=AmazonAutocomplete.AmazonJSONPCallbackHandler_'",
"+",
"this",
".",
"_id",
";",
"scriptContainer",
".",
"replaceChild",
"(",
"newScript",
",",
"scriptContainer",
".",
"firstChild",
")",
";",
"}"
] | Replace the fetching script tag with a new one to get the autocompletion suggestions
for the desired prefix
@param {string} prefix - The letters written by the user in the html search input | [
"Replace",
"the",
"fetching",
"script",
"tag",
"with",
"a",
"new",
"one",
"to",
"get",
"the",
"autocompletion",
"suggestions",
"for",
"the",
"desired",
"prefix"
] | 1638b787296b6e248687b263e9e12a472470972d | https://github.com/caroso1222/amazon-autocomplete/blob/1638b787296b6e248687b263e9e12a472470972d/src/amazon-autocomplete.js#L308-L313 | train |
watson-virtual-agents/chat-widget | examples/basic-custom-layout/src/index.js | layoutInit | function layoutInit() {
IBMChat.subscribe('layout:choose', function(data) {
var widget = new Choose(data);
widgets[data.uuid] = widget;
});
IBMChat.subscribe('layout:confirm', function(data) {
var widget = new Choose(data);
widgets[data.uuid] = widget;
});
} | javascript | function layoutInit() {
IBMChat.subscribe('layout:choose', function(data) {
var widget = new Choose(data);
widgets[data.uuid] = widget;
});
IBMChat.subscribe('layout:confirm', function(data) {
var widget = new Choose(data);
widgets[data.uuid] = widget;
});
} | [
"function",
"layoutInit",
"(",
")",
"{",
"IBMChat",
".",
"subscribe",
"(",
"'layout:choose'",
",",
"function",
"(",
"data",
")",
"{",
"var",
"widget",
"=",
"new",
"Choose",
"(",
"data",
")",
";",
"widgets",
"[",
"data",
".",
"uuid",
"]",
"=",
"widget",
";",
"}",
")",
";",
"IBMChat",
".",
"subscribe",
"(",
"'layout:confirm'",
",",
"function",
"(",
"data",
")",
"{",
"var",
"widget",
"=",
"new",
"Choose",
"(",
"data",
")",
";",
"widgets",
"[",
"data",
".",
"uuid",
"]",
"=",
"widget",
";",
"}",
")",
";",
"}"
] | our layout's init function. We subscribe to both 'choose' and 'confirm' layout events so this is used to render both. | [
"our",
"layout",
"s",
"init",
"function",
".",
"We",
"subscribe",
"to",
"both",
"choose",
"and",
"confirm",
"layout",
"events",
"so",
"this",
"is",
"used",
"to",
"render",
"both",
"."
] | 4792b46a8330ff5f4a4fd232d8ebc8bb877c303c | https://github.com/watson-virtual-agents/chat-widget/blob/4792b46a8330ff5f4a4fd232d8ebc8bb877c303c/examples/basic-custom-layout/src/index.js#L138-L147 | train |
mariocasciaro/scatter | lib/Resolver.js | requireExtended | function requireExtended(name) {
var module = require(name);
if (module && module.__esModule === true && typeof module.default !== 'undefined') {
if (typeof module.__module !== 'undefined') {
// if __module is specified as a named export, add it to the default export
_.defaults(module.default, {__module: module.__module})
}
return module.default;
}
return module;
} | javascript | function requireExtended(name) {
var module = require(name);
if (module && module.__esModule === true && typeof module.default !== 'undefined') {
if (typeof module.__module !== 'undefined') {
// if __module is specified as a named export, add it to the default export
_.defaults(module.default, {__module: module.__module})
}
return module.default;
}
return module;
} | [
"function",
"requireExtended",
"(",
"name",
")",
"{",
"var",
"module",
"=",
"require",
"(",
"name",
")",
";",
"if",
"(",
"module",
"&&",
"module",
".",
"__esModule",
"===",
"true",
"&&",
"typeof",
"module",
".",
"default",
"!==",
"'undefined'",
")",
"{",
"if",
"(",
"typeof",
"module",
".",
"__module",
"!==",
"'undefined'",
")",
"{",
"_",
".",
"defaults",
"(",
"module",
".",
"default",
",",
"{",
"__module",
":",
"module",
".",
"__module",
"}",
")",
"}",
"return",
"module",
".",
"default",
";",
"}",
"return",
"module",
";",
"}"
] | Extended require to support loading Babel6 transpiled ES6 modules, which have their default export under the
"default" key | [
"Extended",
"require",
"to",
"support",
"loading",
"Babel6",
"transpiled",
"ES6",
"modules",
"which",
"have",
"their",
"default",
"export",
"under",
"the",
"default",
"key"
] | 96d05f47c410264f3cc7b549c0fe6f20bbfa6090 | https://github.com/mariocasciaro/scatter/blob/96d05f47c410264f3cc7b549c0fe6f20bbfa6090/lib/Resolver.js#L15-L25 | train |
delian/node-unifiapi | lib/cloud-request.js | CloudRequest | function CloudRequest(options) {
if (!(this instanceof CloudRequest)) return new CloudRequest(options);
merge(this, defaultOptions, options);
if (this.debug) debug.enabled = true;
if (typeof this.request === 'undefined') {
this.jar = request.jar();
this.request = request.defaults({ jar: this.jar });
if (this.debugNet) {
this.request.debug = true;
require('request-debug')(this.request);
}
}
debug('CloudAPI-request initialized with options %o', options);
} | javascript | function CloudRequest(options) {
if (!(this instanceof CloudRequest)) return new CloudRequest(options);
merge(this, defaultOptions, options);
if (this.debug) debug.enabled = true;
if (typeof this.request === 'undefined') {
this.jar = request.jar();
this.request = request.defaults({ jar: this.jar });
if (this.debugNet) {
this.request.debug = true;
require('request-debug')(this.request);
}
}
debug('CloudAPI-request initialized with options %o', options);
} | [
"function",
"CloudRequest",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"CloudRequest",
")",
")",
"return",
"new",
"CloudRequest",
"(",
"options",
")",
";",
"merge",
"(",
"this",
",",
"defaultOptions",
",",
"options",
")",
";",
"if",
"(",
"this",
".",
"debug",
")",
"debug",
".",
"enabled",
"=",
"true",
";",
"if",
"(",
"typeof",
"this",
".",
"request",
"===",
"'undefined'",
")",
"{",
"this",
".",
"jar",
"=",
"request",
".",
"jar",
"(",
")",
";",
"this",
".",
"request",
"=",
"request",
".",
"defaults",
"(",
"{",
"jar",
":",
"this",
".",
"jar",
"}",
")",
";",
"if",
"(",
"this",
".",
"debugNet",
")",
"{",
"this",
".",
"request",
".",
"debug",
"=",
"true",
";",
"require",
"(",
"'request-debug'",
")",
"(",
"this",
".",
"request",
")",
";",
"}",
"}",
"debug",
"(",
"'CloudAPI-request initialized with options %o'",
",",
"options",
")",
";",
"}"
] | Unifi Cloud API interface
@param {object} options Default settings for the cloud access
@param {string} options.deviceId defailt device id. Optional
@param {string} options.username cloud username
@param {string} options.password cloud password
@param {string} options.baseUrl default url for the cloud. Optional
@param {boolean} options.debug debug log. Optional. default false
@param {boolean} options.gzip If gzip is enabled for the cloud messages. Optional. default true
@returns CloudRequest | [
"Unifi",
"Cloud",
"API",
"interface"
] | 048e06716deffa30ec963824d99fe2815b79b30f | https://github.com/delian/node-unifiapi/blob/048e06716deffa30ec963824d99fe2815b79b30f/lib/cloud-request.js#L33-L46 | train |
delian/node-unifiapi | index.js | UnifiAPI | function UnifiAPI(options) {
if (!(this instanceof UnifiAPI)) return new UnifiAPI(options);
merge(this, defaultOptions, options);
this.debugging(this.debug);
if (typeof this.net === 'undefined') {
this.net = new UnifiRequest(merge(true, defaultOptions, options));
}
debug('UnifiAPI Initialized with options %o', options);
} | javascript | function UnifiAPI(options) {
if (!(this instanceof UnifiAPI)) return new UnifiAPI(options);
merge(this, defaultOptions, options);
this.debugging(this.debug);
if (typeof this.net === 'undefined') {
this.net = new UnifiRequest(merge(true, defaultOptions, options));
}
debug('UnifiAPI Initialized with options %o', options);
} | [
"function",
"UnifiAPI",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"UnifiAPI",
")",
")",
"return",
"new",
"UnifiAPI",
"(",
"options",
")",
";",
"merge",
"(",
"this",
",",
"defaultOptions",
",",
"options",
")",
";",
"this",
".",
"debugging",
"(",
"this",
".",
"debug",
")",
";",
"if",
"(",
"typeof",
"this",
".",
"net",
"===",
"'undefined'",
")",
"{",
"this",
".",
"net",
"=",
"new",
"UnifiRequest",
"(",
"merge",
"(",
"true",
",",
"defaultOptions",
",",
"options",
")",
")",
";",
"}",
"debug",
"(",
"'UnifiAPI Initialized with options %o'",
",",
"options",
")",
";",
"}"
] | The main class and the initialization of the Unifi Access
@param {object} options the options during initialization
@param {string} options.baseUrl the URL where the Unifi controller is. Default https://127.0.0.1:8443
@param {string} options.username default username
@param {string} options.password default password
@param {string} options.site default site. Default is "default"
@param {boolean} options.debug if the debug log is enabled
@param {boolean} options.debugNet if the debug of the request module is enabled
@returns this
@example let UnifiAPI = require('node-unifiapi');
let unifi = UnifiAPI({
baseUrl: 'https://127.0.0.1:8443', // The URL of the Unifi Controller
username: 'ubnt',
password: 'ubnt',
// debug: true, // More debug of the API (uses the debug module)
// debugNet: true // Debug of the network requests (uses request module)
}); | [
"The",
"main",
"class",
"and",
"the",
"initialization",
"of",
"the",
"Unifi",
"Access"
] | 048e06716deffa30ec963824d99fe2815b79b30f | https://github.com/delian/node-unifiapi/blob/048e06716deffa30ec963824d99fe2815b79b30f/index.js#L35-L43 | train |
mgutz/execSync | index.js | run | function run(cmd) {
try {
if (isWindows)
cmd = 'cmd /C ' + cmd;
var code = shell.exec(cmd);
return code;
} catch (err) {
if (err) {
console.error(err)
}
return 1;
}
} | javascript | function run(cmd) {
try {
if (isWindows)
cmd = 'cmd /C ' + cmd;
var code = shell.exec(cmd);
return code;
} catch (err) {
if (err) {
console.error(err)
}
return 1;
}
} | [
"function",
"run",
"(",
"cmd",
")",
"{",
"try",
"{",
"if",
"(",
"isWindows",
")",
"cmd",
"=",
"'cmd /C '",
"+",
"cmd",
";",
"var",
"code",
"=",
"shell",
".",
"exec",
"(",
"cmd",
")",
";",
"return",
"code",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"err",
")",
"}",
"return",
"1",
";",
"}",
"}"
] | Runs `cmd` synchronously returning the exit code. | [
"Runs",
"cmd",
"synchronously",
"returning",
"the",
"exit",
"code",
"."
] | a441123572111c1fb225c91b019e0b28f35f4ccd | https://github.com/mgutz/execSync/blob/a441123572111c1fb225c91b019e0b28f35f4ccd/index.js#L36-L48 | train |
mgutz/execSync | index.js | exec | function exec(command) {
var tempName = temp.path({suffix: '.exec'});
var cmd;
if (isWindows)
cmd = command + ' > ' + tempName + ' 2>&1';
else
cmd = '(' + command + ') > ' + tempName + ' 2>&1';
var code = run(cmd);
var text;
if (fs.existsSync(tempName)) {
try {
text = fs.readFileSync(tempName, 'utf8');
fs.unlink(tempName);
} catch (err) {
throw new Error('ERROR: could not delete capture file');
}
} else {
throw new Error('ERROR: output not captured');
}
return {
code: code,
stdout: text
}
} | javascript | function exec(command) {
var tempName = temp.path({suffix: '.exec'});
var cmd;
if (isWindows)
cmd = command + ' > ' + tempName + ' 2>&1';
else
cmd = '(' + command + ') > ' + tempName + ' 2>&1';
var code = run(cmd);
var text;
if (fs.existsSync(tempName)) {
try {
text = fs.readFileSync(tempName, 'utf8');
fs.unlink(tempName);
} catch (err) {
throw new Error('ERROR: could not delete capture file');
}
} else {
throw new Error('ERROR: output not captured');
}
return {
code: code,
stdout: text
}
} | [
"function",
"exec",
"(",
"command",
")",
"{",
"var",
"tempName",
"=",
"temp",
".",
"path",
"(",
"{",
"suffix",
":",
"'.exec'",
"}",
")",
";",
"var",
"cmd",
";",
"if",
"(",
"isWindows",
")",
"cmd",
"=",
"command",
"+",
"' > '",
"+",
"tempName",
"+",
"' 2>&1'",
";",
"else",
"cmd",
"=",
"'('",
"+",
"command",
"+",
"') > '",
"+",
"tempName",
"+",
"' 2>&1'",
";",
"var",
"code",
"=",
"run",
"(",
"cmd",
")",
";",
"var",
"text",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"tempName",
")",
")",
"{",
"try",
"{",
"text",
"=",
"fs",
".",
"readFileSync",
"(",
"tempName",
",",
"'utf8'",
")",
";",
"fs",
".",
"unlink",
"(",
"tempName",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"'ERROR: could not delete capture file'",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'ERROR: output not captured'",
")",
";",
"}",
"return",
"{",
"code",
":",
"code",
",",
"stdout",
":",
"text",
"}",
"}"
] | Executes `command` synchronously capturing the output.
This is a wrapper around `run` function. | [
"Executes",
"command",
"synchronously",
"capturing",
"the",
"output",
"."
] | a441123572111c1fb225c91b019e0b28f35f4ccd | https://github.com/mgutz/execSync/blob/a441123572111c1fb225c91b019e0b28f35f4ccd/index.js#L56-L82 | train |
yaru22/angular-timeago | dist/angular-timeago.js | resolvePastAndFuture | function resolvePastAndFuture(past, future, future5) {
return function(d, millis) {
var isFuture = millis < 0;
if (!isFuture) {
return past;
} else {
if (d <= 4) {
return future;
} else {
return future5;
}
}
};
} | javascript | function resolvePastAndFuture(past, future, future5) {
return function(d, millis) {
var isFuture = millis < 0;
if (!isFuture) {
return past;
} else {
if (d <= 4) {
return future;
} else {
return future5;
}
}
};
} | [
"function",
"resolvePastAndFuture",
"(",
"past",
",",
"future",
",",
"future5",
")",
"{",
"return",
"function",
"(",
"d",
",",
"millis",
")",
"{",
"var",
"isFuture",
"=",
"millis",
"<",
"0",
";",
"if",
"(",
"!",
"isFuture",
")",
"{",
"return",
"past",
";",
"}",
"else",
"{",
"if",
"(",
"d",
"<=",
"4",
")",
"{",
"return",
"future",
";",
"}",
"else",
"{",
"return",
"future5",
";",
"}",
"}",
"}",
";",
"}"
] | Czech language uses 2 different versions for future based on the digit being
lower than 5 or not. | [
"Czech",
"language",
"uses",
"2",
"different",
"versions",
"for",
"future",
"based",
"on",
"the",
"digit",
"being",
"lower",
"than",
"5",
"or",
"not",
"."
] | 04546d06ac81fc7c22f4374c238744cf268e02de | https://github.com/yaru22/angular-timeago/blob/04546d06ac81fc7c22f4374c238744cf268e02de/dist/angular-timeago.js#L43-L57 | train |
ditesh/node-poplib | main.js | onData | function onData(data) {
data = data.toString("ascii");
bufferedData += data;
if (debug) console.log("Server: " + util.inspect(data));
if (checkResp === true) {
if (bufferedData.substr(0, 3) === "+OK") {
checkResp = false;
response = true;
} else if (bufferedData.substr(0, 4) === "-ERR") {
checkResp = false;
response = false;
// The following is only used for SASL
} else if (multiline === false) {
checkResp = false;
response = true;
}
}
if (checkResp === false) {
if (multiline === true && (response === false || bufferedData.substr(bufferedData.length-5) === "\r\n.\r\n")) {
// Make a copy to avoid race conditions
var responseCopy = response;
var bufferedDataCopy = bufferedData;
response = null;
checkResp = true;
multiline = false;
bufferedData = "";
callback(responseCopy, bufferedDataCopy);
} else if (multiline === false) {
// Make a copy to avoid race conditions
var responseCopy = response;
var bufferedDataCopy = bufferedData;
response = null;
checkResp = true;
multiline = false;
bufferedData = "";
callback(responseCopy, bufferedDataCopy);
}
}
} | javascript | function onData(data) {
data = data.toString("ascii");
bufferedData += data;
if (debug) console.log("Server: " + util.inspect(data));
if (checkResp === true) {
if (bufferedData.substr(0, 3) === "+OK") {
checkResp = false;
response = true;
} else if (bufferedData.substr(0, 4) === "-ERR") {
checkResp = false;
response = false;
// The following is only used for SASL
} else if (multiline === false) {
checkResp = false;
response = true;
}
}
if (checkResp === false) {
if (multiline === true && (response === false || bufferedData.substr(bufferedData.length-5) === "\r\n.\r\n")) {
// Make a copy to avoid race conditions
var responseCopy = response;
var bufferedDataCopy = bufferedData;
response = null;
checkResp = true;
multiline = false;
bufferedData = "";
callback(responseCopy, bufferedDataCopy);
} else if (multiline === false) {
// Make a copy to avoid race conditions
var responseCopy = response;
var bufferedDataCopy = bufferedData;
response = null;
checkResp = true;
multiline = false;
bufferedData = "";
callback(responseCopy, bufferedDataCopy);
}
}
} | [
"function",
"onData",
"(",
"data",
")",
"{",
"data",
"=",
"data",
".",
"toString",
"(",
"\"ascii\"",
")",
";",
"bufferedData",
"+=",
"data",
";",
"if",
"(",
"debug",
")",
"console",
".",
"log",
"(",
"\"Server: \"",
"+",
"util",
".",
"inspect",
"(",
"data",
")",
")",
";",
"if",
"(",
"checkResp",
"===",
"true",
")",
"{",
"if",
"(",
"bufferedData",
".",
"substr",
"(",
"0",
",",
"3",
")",
"===",
"\"+OK\"",
")",
"{",
"checkResp",
"=",
"false",
";",
"response",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"bufferedData",
".",
"substr",
"(",
"0",
",",
"4",
")",
"===",
"\"-ERR\"",
")",
"{",
"checkResp",
"=",
"false",
";",
"response",
"=",
"false",
";",
"}",
"else",
"if",
"(",
"multiline",
"===",
"false",
")",
"{",
"checkResp",
"=",
"false",
";",
"response",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"checkResp",
"===",
"false",
")",
"{",
"if",
"(",
"multiline",
"===",
"true",
"&&",
"(",
"response",
"===",
"false",
"||",
"bufferedData",
".",
"substr",
"(",
"bufferedData",
".",
"length",
"-",
"5",
")",
"===",
"\"\\r\\n.\\r\\n\"",
")",
")",
"\\r",
"else",
"\\n",
"}",
"}"
] | Private methods follow Event handlers follow | [
"Private",
"methods",
"follow",
"Event",
"handlers",
"follow"
] | be1e7265b166dd016e93227dc8d548afe4dc4b75 | https://github.com/ditesh/node-poplib/blob/be1e7265b166dd016e93227dc8d548afe4dc4b75/main.js#L198-L256 | train |
ggoodman/angular-drag-drop | src/angular-drag-drop.js | loadStyles | function loadStyles(css, doc) {
// default to the global `document` object
if (!doc) doc = document;
var head = doc.head || doc.getElementsByTagName('head')[0];
// no <head> node? create one...
if (!head) {
head = doc.createElement('head');
var body = doc.body || doc.getElementsByTagName('body')[0];
if (body) {
body.parentNode.insertBefore(head, body);
} else {
doc.documentElement.appendChild(head);
}
}
var style = doc.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
// IE
style.styleSheet.cssText = css;
} else {
// the world
style.appendChild(doc.createTextNode(css));
}
head.appendChild(style);
return style;
} | javascript | function loadStyles(css, doc) {
// default to the global `document` object
if (!doc) doc = document;
var head = doc.head || doc.getElementsByTagName('head')[0];
// no <head> node? create one...
if (!head) {
head = doc.createElement('head');
var body = doc.body || doc.getElementsByTagName('body')[0];
if (body) {
body.parentNode.insertBefore(head, body);
} else {
doc.documentElement.appendChild(head);
}
}
var style = doc.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
// IE
style.styleSheet.cssText = css;
} else {
// the world
style.appendChild(doc.createTextNode(css));
}
head.appendChild(style);
return style;
} | [
"function",
"loadStyles",
"(",
"css",
",",
"doc",
")",
"{",
"if",
"(",
"!",
"doc",
")",
"doc",
"=",
"document",
";",
"var",
"head",
"=",
"doc",
".",
"head",
"||",
"doc",
".",
"getElementsByTagName",
"(",
"'head'",
")",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"head",
")",
"{",
"head",
"=",
"doc",
".",
"createElement",
"(",
"'head'",
")",
";",
"var",
"body",
"=",
"doc",
".",
"body",
"||",
"doc",
".",
"getElementsByTagName",
"(",
"'body'",
")",
"[",
"0",
"]",
";",
"if",
"(",
"body",
")",
"{",
"body",
".",
"parentNode",
".",
"insertBefore",
"(",
"head",
",",
"body",
")",
";",
"}",
"else",
"{",
"doc",
".",
"documentElement",
".",
"appendChild",
"(",
"head",
")",
";",
"}",
"}",
"var",
"style",
"=",
"doc",
".",
"createElement",
"(",
"'style'",
")",
";",
"style",
".",
"type",
"=",
"'text/css'",
";",
"if",
"(",
"style",
".",
"styleSheet",
")",
"{",
"style",
".",
"styleSheet",
".",
"cssText",
"=",
"css",
";",
"}",
"else",
"{",
"style",
".",
"appendChild",
"(",
"doc",
".",
"createTextNode",
"(",
"css",
")",
")",
";",
"}",
"head",
".",
"appendChild",
"(",
"style",
")",
";",
"return",
"style",
";",
"}"
] | Load styles into the head element
Source: https://github.com/webmodules/load-styles/blob/master/index.js | [
"Load",
"styles",
"into",
"the",
"head",
"element"
] | bc62b0985bcbcfef5bbf36350aebd631ffd272a1 | https://github.com/ggoodman/angular-drag-drop/blob/bc62b0985bcbcfef5bbf36350aebd631ffd272a1/src/angular-drag-drop.js#L62-L91 | train |
jonschlinkert/examples | examples/layouts/index.js | Engine | function Engine(options) {
Options.call(this, options);
this.views = {};
this.defaultTemplates();
this.defaultOptions();
if (this.enabled('debug')) {
this.debug();
}
} | javascript | function Engine(options) {
Options.call(this, options);
this.views = {};
this.defaultTemplates();
this.defaultOptions();
if (this.enabled('debug')) {
this.debug();
}
} | [
"function",
"Engine",
"(",
"options",
")",
"{",
"Options",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"this",
".",
"views",
"=",
"{",
"}",
";",
"this",
".",
"defaultTemplates",
"(",
")",
";",
"this",
".",
"defaultOptions",
"(",
")",
";",
"if",
"(",
"this",
".",
"enabled",
"(",
"'debug'",
")",
")",
"{",
"this",
".",
"debug",
"(",
")",
";",
"}",
"}"
] | Example application using load-templates
```js
var Engine = require('engine');
var engine = new Engine();
```
@param {[type]} options | [
"Example",
"application",
"using",
"load",
"-",
"templates"
] | da15141b6b2c38197bafa1b771aa65e331d10fab | https://github.com/jonschlinkert/examples/blob/da15141b6b2c38197bafa1b771aa65e331d10fab/examples/layouts/index.js#L26-L35 | train |
audiojs/pcm-convert | index.js | normalize | function normalize (obj) {
if (!obj.dtype) {
obj.dtype = defaultDtype[obj.type] || 'array'
}
//provide limits
switch (obj.dtype) {
case 'float32':
case 'float64':
case 'audiobuffer':
case 'ndsamples':
case 'ndarray':
obj.min = -1
obj.max = 1
break;
case 'uint8':
obj.min = 0
obj.max = 255
break;
case 'uint16':
obj.min = 0
obj.max = 65535
break;
case 'uint32':
obj.min = 0
obj.max = 4294967295
break;
case 'int8':
obj.min = -128
obj.max = 127
break;
case 'int16':
obj.min = -32768
obj.max = 32767
break;
case 'int32':
obj.min = -2147483648
obj.max = 2147483647
break;
default:
obj.min = -1
obj.max = 1
break;
}
return obj
} | javascript | function normalize (obj) {
if (!obj.dtype) {
obj.dtype = defaultDtype[obj.type] || 'array'
}
//provide limits
switch (obj.dtype) {
case 'float32':
case 'float64':
case 'audiobuffer':
case 'ndsamples':
case 'ndarray':
obj.min = -1
obj.max = 1
break;
case 'uint8':
obj.min = 0
obj.max = 255
break;
case 'uint16':
obj.min = 0
obj.max = 65535
break;
case 'uint32':
obj.min = 0
obj.max = 4294967295
break;
case 'int8':
obj.min = -128
obj.max = 127
break;
case 'int16':
obj.min = -32768
obj.max = 32767
break;
case 'int32':
obj.min = -2147483648
obj.max = 2147483647
break;
default:
obj.min = -1
obj.max = 1
break;
}
return obj
} | [
"function",
"normalize",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"obj",
".",
"dtype",
")",
"{",
"obj",
".",
"dtype",
"=",
"defaultDtype",
"[",
"obj",
".",
"type",
"]",
"||",
"'array'",
"}",
"switch",
"(",
"obj",
".",
"dtype",
")",
"{",
"case",
"'float32'",
":",
"case",
"'float64'",
":",
"case",
"'audiobuffer'",
":",
"case",
"'ndsamples'",
":",
"case",
"'ndarray'",
":",
"obj",
".",
"min",
"=",
"-",
"1",
"obj",
".",
"max",
"=",
"1",
"break",
";",
"case",
"'uint8'",
":",
"obj",
".",
"min",
"=",
"0",
"obj",
".",
"max",
"=",
"255",
"break",
";",
"case",
"'uint16'",
":",
"obj",
".",
"min",
"=",
"0",
"obj",
".",
"max",
"=",
"65535",
"break",
";",
"case",
"'uint32'",
":",
"obj",
".",
"min",
"=",
"0",
"obj",
".",
"max",
"=",
"4294967295",
"break",
";",
"case",
"'int8'",
":",
"obj",
".",
"min",
"=",
"-",
"128",
"obj",
".",
"max",
"=",
"127",
"break",
";",
"case",
"'int16'",
":",
"obj",
".",
"min",
"=",
"-",
"32768",
"obj",
".",
"max",
"=",
"32767",
"break",
";",
"case",
"'int32'",
":",
"obj",
".",
"min",
"=",
"-",
"2147483648",
"obj",
".",
"max",
"=",
"2147483647",
"break",
";",
"default",
":",
"obj",
".",
"min",
"=",
"-",
"1",
"obj",
".",
"max",
"=",
"1",
"break",
";",
"}",
"return",
"obj",
"}"
] | make sure all format properties are present | [
"make",
"sure",
"all",
"format",
"properties",
"are",
"present"
] | 35b0c5c0c2537962269cbad389d9c614244cc37d | https://github.com/audiojs/pcm-convert/blob/35b0c5c0c2537962269cbad389d9c614244cc37d/index.js#L239-L285 | train |
snowplow/snowplow-nodejs-tracker | lib/tracker.js | tracker | function tracker(emitters, namespace, appId, encodeBase64) {
if (!(emitters instanceof Array)) {
emitters = [emitters];
}
encodeBase64 = encodeBase64 !== false;
var trackerCore = core(encodeBase64, sendPayload);
trackerCore.setPlatform('srv'); // default platform
trackerCore.setTrackerVersion('node-' + version);
trackerCore.setTrackerNamespace(namespace);
trackerCore.setAppId(appId);
/**
* Send the payload for an event to the endpoint
*
* @param object payload Dictionary of name-value pairs for the querystring
*/
function sendPayload(payload) {
var builtPayload = payload.build();
for (var i=0; i<emitters.length; i++) {
emitters[i].input(builtPayload);
}
}
var trackEcommerceTransaction = trackerCore.trackEcommerceTransaction;
/**
* Track an ecommerce transaction and all items in that transaction
* Each item is represented by a dictionary which may have the following fields:
* 1. string sku Required. SKU code of the item.
* 2. string name Optional. Name of the item.
* 3. string category Optional. Category of the item.
* 4. string price Required. Price of the item.
* 5. string quantity Required. Purchase quantity.
* 6. array context Optional. Custom context relating to the item.
* 7. number tstamp Optional. Timestamp for the item.
*
* @param string orderId Required. Internal unique order id number for this transaction.
* @param string affiliation Optional. Partner or store affiliation.
* @param string total Required. Total amount of the transaction.
* @param string tax Optional. Tax amount of the transaction.
* @param string shipping Optional. Shipping charge for the transaction.
* @param string city Optional. City to associate with transaction.
* @param string state Optional. State to associate with transaction.
* @param string country Optional. Country to associate with transaction.
* @param string currency Optional. Currency to associate with this transaction.
* @param array items Optional. Items which make up the transaction.
* @param array context Optional. Context relating to the event.
* @param number tstamp Optional. Timestamp for the event.
*/
trackerCore.trackEcommerceTransaction = function (orderId, affiliation, total, tax, shipping, city, state, country, currency, items, context, tstamp) {
trackEcommerceTransaction(
orderId,
affiliation,
total,
tax,
shipping,
city,
state,
country,
currency,
context,
tstamp
);
if (items) {
for (var i=0; i<items.length; i++) {
var item = items[i];
trackerCore.trackEcommerceTransactionItem(
orderId,
item.sku,
item.name,
item.category,
item.price,
item.quantity,
currency,
item.context,
tstamp
);
}
}
};
return trackerCore;
} | javascript | function tracker(emitters, namespace, appId, encodeBase64) {
if (!(emitters instanceof Array)) {
emitters = [emitters];
}
encodeBase64 = encodeBase64 !== false;
var trackerCore = core(encodeBase64, sendPayload);
trackerCore.setPlatform('srv'); // default platform
trackerCore.setTrackerVersion('node-' + version);
trackerCore.setTrackerNamespace(namespace);
trackerCore.setAppId(appId);
/**
* Send the payload for an event to the endpoint
*
* @param object payload Dictionary of name-value pairs for the querystring
*/
function sendPayload(payload) {
var builtPayload = payload.build();
for (var i=0; i<emitters.length; i++) {
emitters[i].input(builtPayload);
}
}
var trackEcommerceTransaction = trackerCore.trackEcommerceTransaction;
/**
* Track an ecommerce transaction and all items in that transaction
* Each item is represented by a dictionary which may have the following fields:
* 1. string sku Required. SKU code of the item.
* 2. string name Optional. Name of the item.
* 3. string category Optional. Category of the item.
* 4. string price Required. Price of the item.
* 5. string quantity Required. Purchase quantity.
* 6. array context Optional. Custom context relating to the item.
* 7. number tstamp Optional. Timestamp for the item.
*
* @param string orderId Required. Internal unique order id number for this transaction.
* @param string affiliation Optional. Partner or store affiliation.
* @param string total Required. Total amount of the transaction.
* @param string tax Optional. Tax amount of the transaction.
* @param string shipping Optional. Shipping charge for the transaction.
* @param string city Optional. City to associate with transaction.
* @param string state Optional. State to associate with transaction.
* @param string country Optional. Country to associate with transaction.
* @param string currency Optional. Currency to associate with this transaction.
* @param array items Optional. Items which make up the transaction.
* @param array context Optional. Context relating to the event.
* @param number tstamp Optional. Timestamp for the event.
*/
trackerCore.trackEcommerceTransaction = function (orderId, affiliation, total, tax, shipping, city, state, country, currency, items, context, tstamp) {
trackEcommerceTransaction(
orderId,
affiliation,
total,
tax,
shipping,
city,
state,
country,
currency,
context,
tstamp
);
if (items) {
for (var i=0; i<items.length; i++) {
var item = items[i];
trackerCore.trackEcommerceTransactionItem(
orderId,
item.sku,
item.name,
item.category,
item.price,
item.quantity,
currency,
item.context,
tstamp
);
}
}
};
return trackerCore;
} | [
"function",
"tracker",
"(",
"emitters",
",",
"namespace",
",",
"appId",
",",
"encodeBase64",
")",
"{",
"if",
"(",
"!",
"(",
"emitters",
"instanceof",
"Array",
")",
")",
"{",
"emitters",
"=",
"[",
"emitters",
"]",
";",
"}",
"encodeBase64",
"=",
"encodeBase64",
"!==",
"false",
";",
"var",
"trackerCore",
"=",
"core",
"(",
"encodeBase64",
",",
"sendPayload",
")",
";",
"trackerCore",
".",
"setPlatform",
"(",
"'srv'",
")",
";",
"trackerCore",
".",
"setTrackerVersion",
"(",
"'node-'",
"+",
"version",
")",
";",
"trackerCore",
".",
"setTrackerNamespace",
"(",
"namespace",
")",
";",
"trackerCore",
".",
"setAppId",
"(",
"appId",
")",
";",
"function",
"sendPayload",
"(",
"payload",
")",
"{",
"var",
"builtPayload",
"=",
"payload",
".",
"build",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"emitters",
".",
"length",
";",
"i",
"++",
")",
"{",
"emitters",
"[",
"i",
"]",
".",
"input",
"(",
"builtPayload",
")",
";",
"}",
"}",
"var",
"trackEcommerceTransaction",
"=",
"trackerCore",
".",
"trackEcommerceTransaction",
";",
"trackerCore",
".",
"trackEcommerceTransaction",
"=",
"function",
"(",
"orderId",
",",
"affiliation",
",",
"total",
",",
"tax",
",",
"shipping",
",",
"city",
",",
"state",
",",
"country",
",",
"currency",
",",
"items",
",",
"context",
",",
"tstamp",
")",
"{",
"trackEcommerceTransaction",
"(",
"orderId",
",",
"affiliation",
",",
"total",
",",
"tax",
",",
"shipping",
",",
"city",
",",
"state",
",",
"country",
",",
"currency",
",",
"context",
",",
"tstamp",
")",
";",
"if",
"(",
"items",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"items",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"item",
"=",
"items",
"[",
"i",
"]",
";",
"trackerCore",
".",
"trackEcommerceTransactionItem",
"(",
"orderId",
",",
"item",
".",
"sku",
",",
"item",
".",
"name",
",",
"item",
".",
"category",
",",
"item",
".",
"price",
",",
"item",
".",
"quantity",
",",
"currency",
",",
"item",
".",
"context",
",",
"tstamp",
")",
";",
"}",
"}",
"}",
";",
"return",
"trackerCore",
";",
"}"
] | Snowplow Node.js Tracker
@param string or array emitters The emitter or emitters to which events will be sent
@param string namespace The namespace of the tracker
@param string appId The application ID
@param boolean encodeBase64 Whether unstructured events and custom contexts should be base 64 encoded | [
"Snowplow",
"Node",
".",
"js",
"Tracker"
] | 2e11ed5ebef6a5560d0d6b4e0dd5d011e7d3772b | https://github.com/snowplow/snowplow-nodejs-tracker/blob/2e11ed5ebef6a5560d0d6b4e0dd5d011e7d3772b/lib/tracker.js#L27-L111 | train |
snowplow/snowplow-nodejs-tracker | lib/tracker.js | sendPayload | function sendPayload(payload) {
var builtPayload = payload.build();
for (var i=0; i<emitters.length; i++) {
emitters[i].input(builtPayload);
}
} | javascript | function sendPayload(payload) {
var builtPayload = payload.build();
for (var i=0; i<emitters.length; i++) {
emitters[i].input(builtPayload);
}
} | [
"function",
"sendPayload",
"(",
"payload",
")",
"{",
"var",
"builtPayload",
"=",
"payload",
".",
"build",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"emitters",
".",
"length",
";",
"i",
"++",
")",
"{",
"emitters",
"[",
"i",
"]",
".",
"input",
"(",
"builtPayload",
")",
";",
"}",
"}"
] | Send the payload for an event to the endpoint
@param object payload Dictionary of name-value pairs for the querystring | [
"Send",
"the",
"payload",
"for",
"an",
"event",
"to",
"the",
"endpoint"
] | 2e11ed5ebef6a5560d0d6b4e0dd5d011e7d3772b | https://github.com/snowplow/snowplow-nodejs-tracker/blob/2e11ed5ebef6a5560d0d6b4e0dd5d011e7d3772b/lib/tracker.js#L44-L49 | train |
snowplow/snowplow-nodejs-tracker | lib/emitter.js | emitter | function emitter(endpoint, protocol, port, method, bufferSize, callback, agentOptions) {
protocol = (protocol || 'http').toLowerCase();
method = (method || 'get').toLowerCase();
if (bufferSize === null || typeof bufferSize === 'undefined') {
bufferSize = method === 'get' ? 0 : 10;
}
var portString = port ? ':' + port : '';
var path = method === 'get' ? '/i' : '/com.snowplowanalytics.snowplow/tp2';
var targetUrl = protocol + '://' + endpoint + portString + path;
var buffer = [];
/**
* Send all events queued in the buffer to the collector
*/
function flush() {
var temp = buffer;
buffer = [];
if (method === 'post') {
var postJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-0',
data: temp.map(valuesToStrings)
};
request.post({
url: targetUrl,
json: postJson,
agentOptions: agentOptions,
headers: {
'content-type': 'application/json; charset=utf-8'
}
}, callback);
} else {
for (var i=0; i<temp.length; i++) {
request.get({
url: targetUrl,
agentOptions: agentOptions,
qs: temp[i]
}, callback);
}
}
}
return {
flush: flush,
input: function (payload) {
buffer.push(payload);
if (buffer.length >= bufferSize) {
flush();
}
}
};
} | javascript | function emitter(endpoint, protocol, port, method, bufferSize, callback, agentOptions) {
protocol = (protocol || 'http').toLowerCase();
method = (method || 'get').toLowerCase();
if (bufferSize === null || typeof bufferSize === 'undefined') {
bufferSize = method === 'get' ? 0 : 10;
}
var portString = port ? ':' + port : '';
var path = method === 'get' ? '/i' : '/com.snowplowanalytics.snowplow/tp2';
var targetUrl = protocol + '://' + endpoint + portString + path;
var buffer = [];
/**
* Send all events queued in the buffer to the collector
*/
function flush() {
var temp = buffer;
buffer = [];
if (method === 'post') {
var postJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-0',
data: temp.map(valuesToStrings)
};
request.post({
url: targetUrl,
json: postJson,
agentOptions: agentOptions,
headers: {
'content-type': 'application/json; charset=utf-8'
}
}, callback);
} else {
for (var i=0; i<temp.length; i++) {
request.get({
url: targetUrl,
agentOptions: agentOptions,
qs: temp[i]
}, callback);
}
}
}
return {
flush: flush,
input: function (payload) {
buffer.push(payload);
if (buffer.length >= bufferSize) {
flush();
}
}
};
} | [
"function",
"emitter",
"(",
"endpoint",
",",
"protocol",
",",
"port",
",",
"method",
",",
"bufferSize",
",",
"callback",
",",
"agentOptions",
")",
"{",
"protocol",
"=",
"(",
"protocol",
"||",
"'http'",
")",
".",
"toLowerCase",
"(",
")",
";",
"method",
"=",
"(",
"method",
"||",
"'get'",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"bufferSize",
"===",
"null",
"||",
"typeof",
"bufferSize",
"===",
"'undefined'",
")",
"{",
"bufferSize",
"=",
"method",
"===",
"'get'",
"?",
"0",
":",
"10",
";",
"}",
"var",
"portString",
"=",
"port",
"?",
"':'",
"+",
"port",
":",
"''",
";",
"var",
"path",
"=",
"method",
"===",
"'get'",
"?",
"'/i'",
":",
"'/com.snowplowanalytics.snowplow/tp2'",
";",
"var",
"targetUrl",
"=",
"protocol",
"+",
"'://'",
"+",
"endpoint",
"+",
"portString",
"+",
"path",
";",
"var",
"buffer",
"=",
"[",
"]",
";",
"function",
"flush",
"(",
")",
"{",
"var",
"temp",
"=",
"buffer",
";",
"buffer",
"=",
"[",
"]",
";",
"if",
"(",
"method",
"===",
"'post'",
")",
"{",
"var",
"postJson",
"=",
"{",
"schema",
":",
"'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-0'",
",",
"data",
":",
"temp",
".",
"map",
"(",
"valuesToStrings",
")",
"}",
";",
"request",
".",
"post",
"(",
"{",
"url",
":",
"targetUrl",
",",
"json",
":",
"postJson",
",",
"agentOptions",
":",
"agentOptions",
",",
"headers",
":",
"{",
"'content-type'",
":",
"'application/json; charset=utf-8'",
"}",
"}",
",",
"callback",
")",
";",
"}",
"else",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"temp",
".",
"length",
";",
"i",
"++",
")",
"{",
"request",
".",
"get",
"(",
"{",
"url",
":",
"targetUrl",
",",
"agentOptions",
":",
"agentOptions",
",",
"qs",
":",
"temp",
"[",
"i",
"]",
"}",
",",
"callback",
")",
";",
"}",
"}",
"}",
"return",
"{",
"flush",
":",
"flush",
",",
"input",
":",
"function",
"(",
"payload",
")",
"{",
"buffer",
".",
"push",
"(",
"payload",
")",
";",
"if",
"(",
"buffer",
".",
"length",
">=",
"bufferSize",
")",
"{",
"flush",
"(",
")",
";",
"}",
"}",
"}",
";",
"}"
] | Create an emitter object which will send events to a collector
@param string endpoint The collector to which events will be sent
@param string protocol "http" or "https"
@param number port The port for requests to use
@param string method "get" or "post"
@param number bufferSize Number of events which can be queued before flush is called
@param function callback Callback passed to the request function
@param agentOptions configuration for http.Agent class | [
"Create",
"an",
"emitter",
"object",
"which",
"will",
"send",
"events",
"to",
"a",
"collector"
] | 2e11ed5ebef6a5560d0d6b4e0dd5d011e7d3772b | https://github.com/snowplow/snowplow-nodejs-tracker/blob/2e11ed5ebef6a5560d0d6b4e0dd5d011e7d3772b/lib/emitter.js#L29-L80 | train |
snowplow/snowplow-nodejs-tracker | lib/emitter.js | flush | function flush() {
var temp = buffer;
buffer = [];
if (method === 'post') {
var postJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-0',
data: temp.map(valuesToStrings)
};
request.post({
url: targetUrl,
json: postJson,
agentOptions: agentOptions,
headers: {
'content-type': 'application/json; charset=utf-8'
}
}, callback);
} else {
for (var i=0; i<temp.length; i++) {
request.get({
url: targetUrl,
agentOptions: agentOptions,
qs: temp[i]
}, callback);
}
}
} | javascript | function flush() {
var temp = buffer;
buffer = [];
if (method === 'post') {
var postJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-0',
data: temp.map(valuesToStrings)
};
request.post({
url: targetUrl,
json: postJson,
agentOptions: agentOptions,
headers: {
'content-type': 'application/json; charset=utf-8'
}
}, callback);
} else {
for (var i=0; i<temp.length; i++) {
request.get({
url: targetUrl,
agentOptions: agentOptions,
qs: temp[i]
}, callback);
}
}
} | [
"function",
"flush",
"(",
")",
"{",
"var",
"temp",
"=",
"buffer",
";",
"buffer",
"=",
"[",
"]",
";",
"if",
"(",
"method",
"===",
"'post'",
")",
"{",
"var",
"postJson",
"=",
"{",
"schema",
":",
"'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-0'",
",",
"data",
":",
"temp",
".",
"map",
"(",
"valuesToStrings",
")",
"}",
";",
"request",
".",
"post",
"(",
"{",
"url",
":",
"targetUrl",
",",
"json",
":",
"postJson",
",",
"agentOptions",
":",
"agentOptions",
",",
"headers",
":",
"{",
"'content-type'",
":",
"'application/json; charset=utf-8'",
"}",
"}",
",",
"callback",
")",
";",
"}",
"else",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"temp",
".",
"length",
";",
"i",
"++",
")",
"{",
"request",
".",
"get",
"(",
"{",
"url",
":",
"targetUrl",
",",
"agentOptions",
":",
"agentOptions",
",",
"qs",
":",
"temp",
"[",
"i",
"]",
"}",
",",
"callback",
")",
";",
"}",
"}",
"}"
] | Send all events queued in the buffer to the collector | [
"Send",
"all",
"events",
"queued",
"in",
"the",
"buffer",
"to",
"the",
"collector"
] | 2e11ed5ebef6a5560d0d6b4e0dd5d011e7d3772b | https://github.com/snowplow/snowplow-nodejs-tracker/blob/2e11ed5ebef6a5560d0d6b4e0dd5d011e7d3772b/lib/emitter.js#L43-L69 | train |
snowplow/snowplow-nodejs-tracker | lib/emitter.js | valuesToStrings | function valuesToStrings(payload) {
var stringifiedPayload = {};
for (var key in payload) {
if (payload.hasOwnProperty(key)) {
stringifiedPayload[key] = payload[key].toString();
}
}
return stringifiedPayload;
} | javascript | function valuesToStrings(payload) {
var stringifiedPayload = {};
for (var key in payload) {
if (payload.hasOwnProperty(key)) {
stringifiedPayload[key] = payload[key].toString();
}
}
return stringifiedPayload;
} | [
"function",
"valuesToStrings",
"(",
"payload",
")",
"{",
"var",
"stringifiedPayload",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"payload",
")",
"{",
"if",
"(",
"payload",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"stringifiedPayload",
"[",
"key",
"]",
"=",
"payload",
"[",
"key",
"]",
".",
"toString",
"(",
")",
";",
"}",
"}",
"return",
"stringifiedPayload",
";",
"}"
] | Convert all fields in a payload dictionary to strings
@param object payload Payload on which the new dictionary is based | [
"Convert",
"all",
"fields",
"in",
"a",
"payload",
"dictionary",
"to",
"strings"
] | 2e11ed5ebef6a5560d0d6b4e0dd5d011e7d3772b | https://github.com/snowplow/snowplow-nodejs-tracker/blob/2e11ed5ebef6a5560d0d6b4e0dd5d011e7d3772b/lib/emitter.js#L87-L95 | train |
jarradseers/express-load | lib/express-load.js | function(entity, options) {
options = options || {};
options.checkext = options.checkext || checkext;
options.extlist = options.extlist || extlist;
options.logFormat = options.logFormat || '%s: %s';
options.logger = options.logger || console;
options.ignore = options.ignore || false;
options.cwd = options.cwd || '';
this.options = options;
this.scripts = [];
if (!(options.extlist instanceof RegExp) && options.extlist instanceof Array){
this.__log('Converting extension list to regular expression');
options.extlist = new RegExp('(.*)(' + options.extlist.join('$|').replace(/\./g,'\\.') + ')');
};
this.__log('Using regular expression' + options.extlist + 'for extenstion matching');
this.then(entity);
return this;
} | javascript | function(entity, options) {
options = options || {};
options.checkext = options.checkext || checkext;
options.extlist = options.extlist || extlist;
options.logFormat = options.logFormat || '%s: %s';
options.logger = options.logger || console;
options.ignore = options.ignore || false;
options.cwd = options.cwd || '';
this.options = options;
this.scripts = [];
if (!(options.extlist instanceof RegExp) && options.extlist instanceof Array){
this.__log('Converting extension list to regular expression');
options.extlist = new RegExp('(.*)(' + options.extlist.join('$|').replace(/\./g,'\\.') + ')');
};
this.__log('Using regular expression' + options.extlist + 'for extenstion matching');
this.then(entity);
return this;
} | [
"function",
"(",
"entity",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"checkext",
"=",
"options",
".",
"checkext",
"||",
"checkext",
";",
"options",
".",
"extlist",
"=",
"options",
".",
"extlist",
"||",
"extlist",
";",
"options",
".",
"logFormat",
"=",
"options",
".",
"logFormat",
"||",
"'%s: %s'",
";",
"options",
".",
"logger",
"=",
"options",
".",
"logger",
"||",
"console",
";",
"options",
".",
"ignore",
"=",
"options",
".",
"ignore",
"||",
"false",
";",
"options",
".",
"cwd",
"=",
"options",
".",
"cwd",
"||",
"''",
";",
"this",
".",
"options",
"=",
"options",
";",
"this",
".",
"scripts",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"(",
"options",
".",
"extlist",
"instanceof",
"RegExp",
")",
"&&",
"options",
".",
"extlist",
"instanceof",
"Array",
")",
"{",
"this",
".",
"__log",
"(",
"'Converting extension list to regular expression'",
")",
";",
"options",
".",
"extlist",
"=",
"new",
"RegExp",
"(",
"'(.*)('",
"+",
"options",
".",
"extlist",
".",
"join",
"(",
"'$|'",
")",
".",
"replace",
"(",
"/",
"\\.",
"/",
"g",
",",
"'\\\\.'",
")",
"+",
"\\\\",
")",
";",
"}",
"')'",
";",
"this",
".",
"__log",
"(",
"'Using regular expression'",
"+",
"options",
".",
"extlist",
"+",
"'for extenstion matching'",
")",
";",
"this",
".",
"then",
"(",
"entity",
")",
";",
"}"
] | ExpressLoad constructor. | [
"ExpressLoad",
"constructor",
"."
] | 29f0ad3ac6e09ee7bb5f8e70f952dbf16cb262ad | https://github.com/jarradseers/express-load/blob/29f0ad3ac6e09ee7bb5f8e70f952dbf16cb262ad/lib/express-load.js#L35-L54 | train |
|
jarradseers/express-load | lib/express-load.js | createNamespace | function createNamespace(parent, parts) {
var part = getName(parts.shift());
if (!parent[part]) {
parent[part] = {};
}
if (parts.length) {
parent = createNamespace(parent[part], parts);
}
return parent;
} | javascript | function createNamespace(parent, parts) {
var part = getName(parts.shift());
if (!parent[part]) {
parent[part] = {};
}
if (parts.length) {
parent = createNamespace(parent[part], parts);
}
return parent;
} | [
"function",
"createNamespace",
"(",
"parent",
",",
"parts",
")",
"{",
"var",
"part",
"=",
"getName",
"(",
"parts",
".",
"shift",
"(",
")",
")",
";",
"if",
"(",
"!",
"parent",
"[",
"part",
"]",
")",
"{",
"parent",
"[",
"part",
"]",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"parts",
".",
"length",
")",
"{",
"parent",
"=",
"createNamespace",
"(",
"parent",
"[",
"part",
"]",
",",
"parts",
")",
";",
"}",
"return",
"parent",
";",
"}"
] | Create Namespace function - creates a namespace map.
@param parent {Object} Current register.
@param parts {Array} Namespace location map.
@return parent {Object} current namespace. | [
"Create",
"Namespace",
"function",
"-",
"creates",
"a",
"namespace",
"map",
"."
] | 29f0ad3ac6e09ee7bb5f8e70f952dbf16cb262ad | https://github.com/jarradseers/express-load/blob/29f0ad3ac6e09ee7bb5f8e70f952dbf16cb262ad/lib/express-load.js#L148-L161 | train |
jarradseers/express-load | lib/express-load.js | getName | function getName(script) {
var script = path.basename(script, path.extname(script)).replace(/[^a-zA-Z0-9]/g, '.')
, parts = script.split('.')
, name = parts.shift();
if (parts.length) {
for (var p in parts) {
name += parts[p].charAt(0).toUpperCase() + parts[p].substr(1, parts[p].length);
}
}
return name;
} | javascript | function getName(script) {
var script = path.basename(script, path.extname(script)).replace(/[^a-zA-Z0-9]/g, '.')
, parts = script.split('.')
, name = parts.shift();
if (parts.length) {
for (var p in parts) {
name += parts[p].charAt(0).toUpperCase() + parts[p].substr(1, parts[p].length);
}
}
return name;
} | [
"function",
"getName",
"(",
"script",
")",
"{",
"var",
"script",
"=",
"path",
".",
"basename",
"(",
"script",
",",
"path",
".",
"extname",
"(",
"script",
")",
")",
".",
"replace",
"(",
"/",
"[^a-zA-Z0-9]",
"/",
"g",
",",
"'.'",
")",
",",
"parts",
"=",
"script",
".",
"split",
"(",
"'.'",
")",
",",
"name",
"=",
"parts",
".",
"shift",
"(",
")",
";",
"if",
"(",
"parts",
".",
"length",
")",
"{",
"for",
"(",
"var",
"p",
"in",
"parts",
")",
"{",
"name",
"+=",
"parts",
"[",
"p",
"]",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"parts",
"[",
"p",
"]",
".",
"substr",
"(",
"1",
",",
"parts",
"[",
"p",
"]",
".",
"length",
")",
";",
"}",
"}",
"return",
"name",
";",
"}"
] | Get Name - formats name into method-friendly version from script path.
@param script {String} Script location.
@return name {String} Name of script. | [
"Get",
"Name",
"-",
"formats",
"name",
"into",
"method",
"-",
"friendly",
"version",
"from",
"script",
"path",
"."
] | 29f0ad3ac6e09ee7bb5f8e70f952dbf16cb262ad | https://github.com/jarradseers/express-load/blob/29f0ad3ac6e09ee7bb5f8e70f952dbf16cb262ad/lib/express-load.js#L170-L182 | train |
samuelneff/sequelize-auto-ts | lib/sequelize-types.js | assertValidFieldType | function assertValidFieldType(pojoName, fieldName, pojo, expectedType) {
var value = pojo[fieldName];
var actualType = typeof value;
if (value === undefined || value === null) {
return;
}
switch (expectedType) {
case BOOLEAN_TYPE:
if (actualType !== BOOLEAN_TYPE && actualType !== NUMBER_TYPE) {
err();
}
pojo[fieldName] = Boolean(value);
return;
case NUMBER_TYPE:
if (actualType === NUMBER_TYPE) {
return;
}
if (actualType === STRING_TYPE) {
var newValue = parseFloat(value);
if (isNaN(newValue)) {
err();
}
pojo[fieldName] = newValue;
}
return;
case STRING_TYPE:
if (actualType !== STRING_TYPE) {
pojo[fieldName] = value.toString();
}
return;
case DATE_EXPECTED_TYPE:
var getTime = value.getTime;
if (typeof getTime === FUNCTION_TYPE) {
var timeValue = value.getTime();
if (isNaN(timeValue)) {
err();
}
if (!(value instanceof Date)) {
pojo[fieldName] = new Date(timeValue);
}
return;
}
if (actualType === STRING_TYPE) {
var newDate = new Date(value);
if (!isNaN(newDate.getTime())) {
pojo[fieldName] = newDate;
return;
}
}
err();
return;
case BUFFER_EXPECTED_TYPE:
if (!BUFFER_EXISTS) {
return;
}
if (!(value instanceof Buffer)) {
err();
}
return;
}
// one pojo of array of array of pojos?
if (expectedType.length > 3 && expectedType.substr(expectedType.length - 2, 2) === '[]') {
var individualPojoType = expectedType.substr(0, expectedType.length - 6);
var asserter_1 = asserters[individualPojoType];
if (typeof asserter_1 !== FUNCTION_TYPE) {
err();
}
if (isNaN(value.length)) {
err();
}
for (var i = 0; i < value.length; i++) {
try {
asserter_1(value[i], true);
}
catch (e) {
err('Error at index \'' + i + '\': ' + e.message);
}
}
// all instances valid
return;
}
var asserter = asserters[expectedType.substr(0, expectedType.length - 4)];
if (typeof asserter !== FUNCTION_TYPE) {
expectedTypeErr();
}
try {
asserter(value, true);
}
catch (e) {
err(e.message);
}
function err(extraMessage) {
var message = 'Invalid ' + pojoName + ' provided. Field \'' + fieldName + '\' with value \'' + safeValue(value) + '\' is not a valid \'' + expectedType + '\'.';
if (extraMessage !== undefined) {
message += ' ' + extraMessage;
}
throw new Error(message);
}
function expectedTypeErr() {
throw new Error('Cannot validate \'' + pojoName + '\' field \'' + fieldName + '\' since expected type provided \'' + expectedType + '\' is not understood.');
}
} | javascript | function assertValidFieldType(pojoName, fieldName, pojo, expectedType) {
var value = pojo[fieldName];
var actualType = typeof value;
if (value === undefined || value === null) {
return;
}
switch (expectedType) {
case BOOLEAN_TYPE:
if (actualType !== BOOLEAN_TYPE && actualType !== NUMBER_TYPE) {
err();
}
pojo[fieldName] = Boolean(value);
return;
case NUMBER_TYPE:
if (actualType === NUMBER_TYPE) {
return;
}
if (actualType === STRING_TYPE) {
var newValue = parseFloat(value);
if (isNaN(newValue)) {
err();
}
pojo[fieldName] = newValue;
}
return;
case STRING_TYPE:
if (actualType !== STRING_TYPE) {
pojo[fieldName] = value.toString();
}
return;
case DATE_EXPECTED_TYPE:
var getTime = value.getTime;
if (typeof getTime === FUNCTION_TYPE) {
var timeValue = value.getTime();
if (isNaN(timeValue)) {
err();
}
if (!(value instanceof Date)) {
pojo[fieldName] = new Date(timeValue);
}
return;
}
if (actualType === STRING_TYPE) {
var newDate = new Date(value);
if (!isNaN(newDate.getTime())) {
pojo[fieldName] = newDate;
return;
}
}
err();
return;
case BUFFER_EXPECTED_TYPE:
if (!BUFFER_EXISTS) {
return;
}
if (!(value instanceof Buffer)) {
err();
}
return;
}
// one pojo of array of array of pojos?
if (expectedType.length > 3 && expectedType.substr(expectedType.length - 2, 2) === '[]') {
var individualPojoType = expectedType.substr(0, expectedType.length - 6);
var asserter_1 = asserters[individualPojoType];
if (typeof asserter_1 !== FUNCTION_TYPE) {
err();
}
if (isNaN(value.length)) {
err();
}
for (var i = 0; i < value.length; i++) {
try {
asserter_1(value[i], true);
}
catch (e) {
err('Error at index \'' + i + '\': ' + e.message);
}
}
// all instances valid
return;
}
var asserter = asserters[expectedType.substr(0, expectedType.length - 4)];
if (typeof asserter !== FUNCTION_TYPE) {
expectedTypeErr();
}
try {
asserter(value, true);
}
catch (e) {
err(e.message);
}
function err(extraMessage) {
var message = 'Invalid ' + pojoName + ' provided. Field \'' + fieldName + '\' with value \'' + safeValue(value) + '\' is not a valid \'' + expectedType + '\'.';
if (extraMessage !== undefined) {
message += ' ' + extraMessage;
}
throw new Error(message);
}
function expectedTypeErr() {
throw new Error('Cannot validate \'' + pojoName + '\' field \'' + fieldName + '\' since expected type provided \'' + expectedType + '\' is not understood.');
}
} | [
"function",
"assertValidFieldType",
"(",
"pojoName",
",",
"fieldName",
",",
"pojo",
",",
"expectedType",
")",
"{",
"var",
"value",
"=",
"pojo",
"[",
"fieldName",
"]",
";",
"var",
"actualType",
"=",
"typeof",
"value",
";",
"if",
"(",
"value",
"===",
"undefined",
"||",
"value",
"===",
"null",
")",
"{",
"return",
";",
"}",
"switch",
"(",
"expectedType",
")",
"{",
"case",
"BOOLEAN_TYPE",
":",
"if",
"(",
"actualType",
"!==",
"BOOLEAN_TYPE",
"&&",
"actualType",
"!==",
"NUMBER_TYPE",
")",
"{",
"err",
"(",
")",
";",
"}",
"pojo",
"[",
"fieldName",
"]",
"=",
"Boolean",
"(",
"value",
")",
";",
"return",
";",
"case",
"NUMBER_TYPE",
":",
"if",
"(",
"actualType",
"===",
"NUMBER_TYPE",
")",
"{",
"return",
";",
"}",
"if",
"(",
"actualType",
"===",
"STRING_TYPE",
")",
"{",
"var",
"newValue",
"=",
"parseFloat",
"(",
"value",
")",
";",
"if",
"(",
"isNaN",
"(",
"newValue",
")",
")",
"{",
"err",
"(",
")",
";",
"}",
"pojo",
"[",
"fieldName",
"]",
"=",
"newValue",
";",
"}",
"return",
";",
"case",
"STRING_TYPE",
":",
"if",
"(",
"actualType",
"!==",
"STRING_TYPE",
")",
"{",
"pojo",
"[",
"fieldName",
"]",
"=",
"value",
".",
"toString",
"(",
")",
";",
"}",
"return",
";",
"case",
"DATE_EXPECTED_TYPE",
":",
"var",
"getTime",
"=",
"value",
".",
"getTime",
";",
"if",
"(",
"typeof",
"getTime",
"===",
"FUNCTION_TYPE",
")",
"{",
"var",
"timeValue",
"=",
"value",
".",
"getTime",
"(",
")",
";",
"if",
"(",
"isNaN",
"(",
"timeValue",
")",
")",
"{",
"err",
"(",
")",
";",
"}",
"if",
"(",
"!",
"(",
"value",
"instanceof",
"Date",
")",
")",
"{",
"pojo",
"[",
"fieldName",
"]",
"=",
"new",
"Date",
"(",
"timeValue",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"actualType",
"===",
"STRING_TYPE",
")",
"{",
"var",
"newDate",
"=",
"new",
"Date",
"(",
"value",
")",
";",
"if",
"(",
"!",
"isNaN",
"(",
"newDate",
".",
"getTime",
"(",
")",
")",
")",
"{",
"pojo",
"[",
"fieldName",
"]",
"=",
"newDate",
";",
"return",
";",
"}",
"}",
"err",
"(",
")",
";",
"return",
";",
"case",
"BUFFER_EXPECTED_TYPE",
":",
"if",
"(",
"!",
"BUFFER_EXISTS",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"(",
"value",
"instanceof",
"Buffer",
")",
")",
"{",
"err",
"(",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"expectedType",
".",
"length",
">",
"3",
"&&",
"expectedType",
".",
"substr",
"(",
"expectedType",
".",
"length",
"-",
"2",
",",
"2",
")",
"===",
"'[]'",
")",
"{",
"var",
"individualPojoType",
"=",
"expectedType",
".",
"substr",
"(",
"0",
",",
"expectedType",
".",
"length",
"-",
"6",
")",
";",
"var",
"asserter_1",
"=",
"asserters",
"[",
"individualPojoType",
"]",
";",
"if",
"(",
"typeof",
"asserter_1",
"!==",
"FUNCTION_TYPE",
")",
"{",
"err",
"(",
")",
";",
"}",
"if",
"(",
"isNaN",
"(",
"value",
".",
"length",
")",
")",
"{",
"err",
"(",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"value",
".",
"length",
";",
"i",
"++",
")",
"{",
"try",
"{",
"asserter_1",
"(",
"value",
"[",
"i",
"]",
",",
"true",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"err",
"(",
"'Error at index \\''",
"+",
"\\'",
"+",
"i",
"+",
"'\\': '",
")",
";",
"}",
"}",
"\\'",
"}",
"e",
".",
"message",
"return",
";",
"var",
"asserter",
"=",
"asserters",
"[",
"expectedType",
".",
"substr",
"(",
"0",
",",
"expectedType",
".",
"length",
"-",
"4",
")",
"]",
";",
"if",
"(",
"typeof",
"asserter",
"!==",
"FUNCTION_TYPE",
")",
"{",
"expectedTypeErr",
"(",
")",
";",
"}",
"try",
"{",
"asserter",
"(",
"value",
",",
"true",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"err",
"(",
"e",
".",
"message",
")",
";",
"}",
"}"
] | in node exists, in js not, so only validate in node | [
"in",
"node",
"exists",
"in",
"js",
"not",
"so",
"only",
"validate",
"in",
"node"
] | da509c78be696536a1a4bd31a8f141cd1ff14d70 | https://github.com/samuelneff/sequelize-auto-ts/blob/da509c78be696536a1a4bd31a8f141cd1ff14d70/lib/sequelize-types.js#L43-L144 | train |
haydn/json-api-store | dist/ajax.js | getCORSRequest | function getCORSRequest() {
var xhr = new root.XMLHttpRequest();
if ('withCredentials' in xhr) {
return xhr;
} else if (!!root.XDomainRequest) {
return new XDomainRequest();
} else {
throw new Error('CORS is not supported by your browser');
}
} | javascript | function getCORSRequest() {
var xhr = new root.XMLHttpRequest();
if ('withCredentials' in xhr) {
return xhr;
} else if (!!root.XDomainRequest) {
return new XDomainRequest();
} else {
throw new Error('CORS is not supported by your browser');
}
} | [
"function",
"getCORSRequest",
"(",
")",
"{",
"var",
"xhr",
"=",
"new",
"root",
".",
"XMLHttpRequest",
"(",
")",
";",
"if",
"(",
"'withCredentials'",
"in",
"xhr",
")",
"{",
"return",
"xhr",
";",
"}",
"else",
"if",
"(",
"!",
"!",
"root",
".",
"XDomainRequest",
")",
"{",
"return",
"new",
"XDomainRequest",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'CORS is not supported by your browser'",
")",
";",
"}",
"}"
] | Get CORS support even for older IE | [
"Get",
"CORS",
"support",
"even",
"for",
"older",
"IE"
] | fc36a38e7c37b276198daa00e7a285adeda67c41 | https://github.com/haydn/json-api-store/blob/fc36a38e7c37b276198daa00e7a285adeda67c41/dist/ajax.js#L61-L70 | train |
andris9/xoauth2 | src/xoauth2.js | toBase64URL | function toBase64URL(data) {
if (typeof data === 'string') {
data = new Buffer(data);
}
return data.toString('base64')
.replace(/=+/g, '') // remove '='s
.replace(/\+/g, '-') // '+' → '-'
.replace(/\//g, '_'); // '/' → '_'
} | javascript | function toBase64URL(data) {
if (typeof data === 'string') {
data = new Buffer(data);
}
return data.toString('base64')
.replace(/=+/g, '') // remove '='s
.replace(/\+/g, '-') // '+' → '-'
.replace(/\//g, '_'); // '/' → '_'
} | [
"function",
"toBase64URL",
"(",
"data",
")",
"{",
"if",
"(",
"typeof",
"data",
"===",
"'string'",
")",
"{",
"data",
"=",
"new",
"Buffer",
"(",
"data",
")",
";",
"}",
"return",
"data",
".",
"toString",
"(",
"'base64'",
")",
".",
"replace",
"(",
"/",
"=+",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
"\\+",
"/",
"g",
",",
"'-'",
")",
".",
"replace",
"(",
"/",
"\\/",
"/",
"g",
",",
"'_'",
")",
";",
"}"
] | Encodes a buffer or a string into Base64url format
@param {Buffer|String} data The data to convert
@return {String} The encoded string | [
"Encodes",
"a",
"buffer",
"or",
"a",
"string",
"into",
"Base64url",
"format"
] | 168af721b39bcccf8fa380809c426abe8f9092ab | https://github.com/andris9/xoauth2/blob/168af721b39bcccf8fa380809c426abe8f9092ab/src/xoauth2.js#L266-L275 | train |
rubenv/angular-debounce | dist/angular-debounce.js | ping | function ping() {
result = fn.apply(context || this, args || []);
context = args = null;
executed = true;
} | javascript | function ping() {
result = fn.apply(context || this, args || []);
context = args = null;
executed = true;
} | [
"function",
"ping",
"(",
")",
"{",
"result",
"=",
"fn",
".",
"apply",
"(",
"context",
"||",
"this",
",",
"args",
"||",
"[",
"]",
")",
";",
"context",
"=",
"args",
"=",
"null",
";",
"executed",
"=",
"true",
";",
"}"
] | Execute the callback function | [
"Execute",
"the",
"callback",
"function"
] | 5213c7c6d6d663c7033967757d0df3a3238fad12 | https://github.com/rubenv/angular-debounce/blob/5213c7c6d6d663c7033967757d0df3a3238fad12/dist/angular-debounce.js#L8-L12 | train |
rubenv/angular-debounce | dist/angular-debounce.js | wrapper | function wrapper() {
context = this;
args = arguments;
if (!no_postpone) {
cancel();
timeout = $timeout(ping, wait);
} else if (executed) {
executed = false;
timeout = $timeout(ping, wait);
}
} | javascript | function wrapper() {
context = this;
args = arguments;
if (!no_postpone) {
cancel();
timeout = $timeout(ping, wait);
} else if (executed) {
executed = false;
timeout = $timeout(ping, wait);
}
} | [
"function",
"wrapper",
"(",
")",
"{",
"context",
"=",
"this",
";",
"args",
"=",
"arguments",
";",
"if",
"(",
"!",
"no_postpone",
")",
"{",
"cancel",
"(",
")",
";",
"timeout",
"=",
"$timeout",
"(",
"ping",
",",
"wait",
")",
";",
"}",
"else",
"if",
"(",
"executed",
")",
"{",
"executed",
"=",
"false",
";",
"timeout",
"=",
"$timeout",
"(",
"ping",
",",
"wait",
")",
";",
"}",
"}"
] | This is the actual result of the debounce call. It is a wrapper function which you can invoke multiple times and which will only be called once every "wait" milliseconds. | [
"This",
"is",
"the",
"actual",
"result",
"of",
"the",
"debounce",
"call",
".",
"It",
"is",
"a",
"wrapper",
"function",
"which",
"you",
"can",
"invoke",
"multiple",
"times",
"and",
"which",
"will",
"only",
"be",
"called",
"once",
"every",
"wait",
"milliseconds",
"."
] | 5213c7c6d6d663c7033967757d0df3a3238fad12 | https://github.com/rubenv/angular-debounce/blob/5213c7c6d6d663c7033967757d0df3a3238fad12/dist/angular-debounce.js#L23-L33 | train |
tinganho/express-request-language | index.js | set | function set(props, req, language) {
if(language) {
req.language = language;
}
else {
language = req.language = acceptLanguage.get(req.headers['accept-language']);
}
if(typeof props.localizations === 'function') {
req.localizations = props.localizations(language);
}
} | javascript | function set(props, req, language) {
if(language) {
req.language = language;
}
else {
language = req.language = acceptLanguage.get(req.headers['accept-language']);
}
if(typeof props.localizations === 'function') {
req.localizations = props.localizations(language);
}
} | [
"function",
"set",
"(",
"props",
",",
"req",
",",
"language",
")",
"{",
"if",
"(",
"language",
")",
"{",
"req",
".",
"language",
"=",
"language",
";",
"}",
"else",
"{",
"language",
"=",
"req",
".",
"language",
"=",
"acceptLanguage",
".",
"get",
"(",
"req",
".",
"headers",
"[",
"'accept-language'",
"]",
")",
";",
"}",
"if",
"(",
"typeof",
"props",
".",
"localizations",
"===",
"'function'",
")",
"{",
"req",
".",
"localizations",
"=",
"props",
".",
"localizations",
"(",
"language",
")",
";",
"}",
"}"
] | Set locals and call localizations
@param {Object} props requestLanguage.props
@param {Object} req Express request
@param {String} language
@return void
@private | [
"Set",
"locals",
"and",
"call",
"localizations"
] | 7e3c9bc0f5aa5a743a409c9f8ed1c8a9428e3a98 | https://github.com/tinganho/express-request-language/blob/7e3c9bc0f5aa5a743a409c9f8ed1c8a9428e3a98/index.js#L18-L29 | train |
NDMAC/apk-updater | lib/updater.js | enable | function enable(app, route, repoDir){
expressApp = app;
routePfx = route;
if(repoDir){
reader.setRepoDir(repoDir);
}
app.post(route, androidUpdate.updater);
app.get(route, function (req, res){
res.send(reader.available());
});
} | javascript | function enable(app, route, repoDir){
expressApp = app;
routePfx = route;
if(repoDir){
reader.setRepoDir(repoDir);
}
app.post(route, androidUpdate.updater);
app.get(route, function (req, res){
res.send(reader.available());
});
} | [
"function",
"enable",
"(",
"app",
",",
"route",
",",
"repoDir",
")",
"{",
"expressApp",
"=",
"app",
";",
"routePfx",
"=",
"route",
";",
"if",
"(",
"repoDir",
")",
"{",
"reader",
".",
"setRepoDir",
"(",
"repoDir",
")",
";",
"}",
"app",
".",
"post",
"(",
"route",
",",
"androidUpdate",
".",
"updater",
")",
";",
"app",
".",
"get",
"(",
"route",
",",
"function",
"(",
"req",
",",
"res",
")",
"{",
"res",
".",
"send",
"(",
"reader",
".",
"available",
"(",
")",
")",
";",
"}",
")",
";",
"}"
] | Enable auto apk updater for provided Express application and route.
@param {@Object} app parent Express application
@param {@String} route route prefix for current updater
@param {@String} repoDir path for apk directory | [
"Enable",
"auto",
"apk",
"updater",
"for",
"provided",
"Express",
"application",
"and",
"route",
"."
] | fe25dc03c2f0b5830c7bc85ca1e5a5a25659d1e0 | https://github.com/NDMAC/apk-updater/blob/fe25dc03c2f0b5830c7bc85ca1e5a5a25659d1e0/lib/updater.js#L56-L67 | train |
Revln9/react-agenda | src/dragAndDropHelper.js | DragDropTouch | function DragDropTouch() {
this._lastClick = 0;
// enforce singleton pattern
if (DragDropTouch._instance) {
throw 'DragDropTouch instance already created.';
}
// listen to touch events
if ('ontouchstart' in document) {
var d = document, ts = this._touchstart.bind(this), tm = this._touchmove.bind(this), te = this._touchend.bind(this);
d.addEventListener('touchstart', ts);
d.addEventListener('touchmove', tm);
d.addEventListener('touchend', te);
d.addEventListener('touchcancel', te);
}
} | javascript | function DragDropTouch() {
this._lastClick = 0;
// enforce singleton pattern
if (DragDropTouch._instance) {
throw 'DragDropTouch instance already created.';
}
// listen to touch events
if ('ontouchstart' in document) {
var d = document, ts = this._touchstart.bind(this), tm = this._touchmove.bind(this), te = this._touchend.bind(this);
d.addEventListener('touchstart', ts);
d.addEventListener('touchmove', tm);
d.addEventListener('touchend', te);
d.addEventListener('touchcancel', te);
}
} | [
"function",
"DragDropTouch",
"(",
")",
"{",
"this",
".",
"_lastClick",
"=",
"0",
";",
"if",
"(",
"DragDropTouch",
".",
"_instance",
")",
"{",
"throw",
"'DragDropTouch instance already created.'",
";",
"}",
"if",
"(",
"'ontouchstart'",
"in",
"document",
")",
"{",
"var",
"d",
"=",
"document",
",",
"ts",
"=",
"this",
".",
"_touchstart",
".",
"bind",
"(",
"this",
")",
",",
"tm",
"=",
"this",
".",
"_touchmove",
".",
"bind",
"(",
"this",
")",
",",
"te",
"=",
"this",
".",
"_touchend",
".",
"bind",
"(",
"this",
")",
";",
"d",
".",
"addEventListener",
"(",
"'touchstart'",
",",
"ts",
")",
";",
"d",
".",
"addEventListener",
"(",
"'touchmove'",
",",
"tm",
")",
";",
"d",
".",
"addEventListener",
"(",
"'touchend'",
",",
"te",
")",
";",
"d",
".",
"addEventListener",
"(",
"'touchcancel'",
",",
"te",
")",
";",
"}",
"}"
] | Initializes the single instance of the @see:DragDropTouch class. | [
"Initializes",
"the",
"single",
"instance",
"of",
"the"
] | cec65d061aa8a0d14f86f9d254c7e80e3826ab30 | https://github.com/Revln9/react-agenda/blob/cec65d061aa8a0d14f86f9d254c7e80e3826ab30/src/dragAndDropHelper.js#L134-L148 | train |
cssinjs/jss-compose | src/index.js | registerClass | function registerClass(rule, className) {
// Skip falsy values
if (!className) return true
// Support array of class names `{composes: ['foo', 'bar']}`
if (Array.isArray(className)) {
for (let index = 0; index < className.length; index++) {
const isSetted = registerClass(rule, className[index])
if (!isSetted) return false
}
return true
}
// Support space separated class names `{composes: 'foo bar'}`
if (className.indexOf(' ') > -1) {
return registerClass(rule, className.split(' '))
}
const {parent} = rule.options
// It is a ref to a local rule.
if (className[0] === '$') {
const refRule = parent.getRule(className.substr(1))
if (!refRule) {
warning(false, '[JSS] Referenced rule is not defined. \r\n%s', rule)
return false
}
if (refRule === rule) {
warning(false, '[JSS] Cyclic composition detected. \r\n%s', rule)
return false
}
parent.classes[rule.key] += ` ${parent.classes[refRule.key]}`
return true
}
rule.options.parent.classes[rule.key] += ` ${className}`
return true
} | javascript | function registerClass(rule, className) {
// Skip falsy values
if (!className) return true
// Support array of class names `{composes: ['foo', 'bar']}`
if (Array.isArray(className)) {
for (let index = 0; index < className.length; index++) {
const isSetted = registerClass(rule, className[index])
if (!isSetted) return false
}
return true
}
// Support space separated class names `{composes: 'foo bar'}`
if (className.indexOf(' ') > -1) {
return registerClass(rule, className.split(' '))
}
const {parent} = rule.options
// It is a ref to a local rule.
if (className[0] === '$') {
const refRule = parent.getRule(className.substr(1))
if (!refRule) {
warning(false, '[JSS] Referenced rule is not defined. \r\n%s', rule)
return false
}
if (refRule === rule) {
warning(false, '[JSS] Cyclic composition detected. \r\n%s', rule)
return false
}
parent.classes[rule.key] += ` ${parent.classes[refRule.key]}`
return true
}
rule.options.parent.classes[rule.key] += ` ${className}`
return true
} | [
"function",
"registerClass",
"(",
"rule",
",",
"className",
")",
"{",
"if",
"(",
"!",
"className",
")",
"return",
"true",
"if",
"(",
"Array",
".",
"isArray",
"(",
"className",
")",
")",
"{",
"for",
"(",
"let",
"index",
"=",
"0",
";",
"index",
"<",
"className",
".",
"length",
";",
"index",
"++",
")",
"{",
"const",
"isSetted",
"=",
"registerClass",
"(",
"rule",
",",
"className",
"[",
"index",
"]",
")",
"if",
"(",
"!",
"isSetted",
")",
"return",
"false",
"}",
"return",
"true",
"}",
"if",
"(",
"className",
".",
"indexOf",
"(",
"' '",
")",
">",
"-",
"1",
")",
"{",
"return",
"registerClass",
"(",
"rule",
",",
"className",
".",
"split",
"(",
"' '",
")",
")",
"}",
"const",
"{",
"parent",
"}",
"=",
"rule",
".",
"options",
"if",
"(",
"className",
"[",
"0",
"]",
"===",
"'$'",
")",
"{",
"const",
"refRule",
"=",
"parent",
".",
"getRule",
"(",
"className",
".",
"substr",
"(",
"1",
")",
")",
"if",
"(",
"!",
"refRule",
")",
"{",
"warning",
"(",
"false",
",",
"'[JSS] Referenced rule is not defined. \\r\\n%s'",
",",
"\\r",
")",
"\\n",
"}",
"rule",
"return",
"false",
"if",
"(",
"refRule",
"===",
"rule",
")",
"{",
"warning",
"(",
"false",
",",
"'[JSS] Cyclic composition detected. \\r\\n%s'",
",",
"\\r",
")",
"\\n",
"}",
"}",
"rule",
"return",
"false",
"}"
] | Set selector.
@param {Object} original rule
@param {String} className class string
@return {Boolean} flag, indicating function was successfull or not | [
"Set",
"selector",
"."
] | c5052cb99e69a00faa556c0ca06194f1bf2b79ea | https://github.com/cssinjs/jss-compose/blob/c5052cb99e69a00faa556c0ca06194f1bf2b79ea/src/index.js#L10-L53 | train |
sapegin/grunt-bower-concat | lib/dependencyTools.js | buildDependencyGraph | function buildDependencyGraph(module, dependencies, graph) {
if (module && !graph[module]) {
graph[module] = [];
}
var dependencyNames = Object.keys(dependencies);
dependencyNames.forEach(function(dependencyName) {
var dependency = dependencies[dependencyName];
if (module && graph[module].indexOf(dependencyName) === -1) {
graph[module].push(dependencyName);
}
// Traverse down to this dependency dependencies:
// Dependency-ception.
if (dependency.dependencies) {
buildDependencyGraph(dependencyName, dependency.dependencies, graph);
}
});
} | javascript | function buildDependencyGraph(module, dependencies, graph) {
if (module && !graph[module]) {
graph[module] = [];
}
var dependencyNames = Object.keys(dependencies);
dependencyNames.forEach(function(dependencyName) {
var dependency = dependencies[dependencyName];
if (module && graph[module].indexOf(dependencyName) === -1) {
graph[module].push(dependencyName);
}
// Traverse down to this dependency dependencies:
// Dependency-ception.
if (dependency.dependencies) {
buildDependencyGraph(dependencyName, dependency.dependencies, graph);
}
});
} | [
"function",
"buildDependencyGraph",
"(",
"module",
",",
"dependencies",
",",
"graph",
")",
"{",
"if",
"(",
"module",
"&&",
"!",
"graph",
"[",
"module",
"]",
")",
"{",
"graph",
"[",
"module",
"]",
"=",
"[",
"]",
";",
"}",
"var",
"dependencyNames",
"=",
"Object",
".",
"keys",
"(",
"dependencies",
")",
";",
"dependencyNames",
".",
"forEach",
"(",
"function",
"(",
"dependencyName",
")",
"{",
"var",
"dependency",
"=",
"dependencies",
"[",
"dependencyName",
"]",
";",
"if",
"(",
"module",
"&&",
"graph",
"[",
"module",
"]",
".",
"indexOf",
"(",
"dependencyName",
")",
"===",
"-",
"1",
")",
"{",
"graph",
"[",
"module",
"]",
".",
"push",
"(",
"dependencyName",
")",
";",
"}",
"if",
"(",
"dependency",
".",
"dependencies",
")",
"{",
"buildDependencyGraph",
"(",
"dependencyName",
",",
"dependency",
".",
"dependencies",
",",
"graph",
")",
";",
"}",
"}",
")",
";",
"}"
] | Builds up a dependency graph for using a simple object structure containing the modules as keys and using arrays
as dependecy descriptors. | [
"Builds",
"up",
"a",
"dependency",
"graph",
"for",
"using",
"a",
"simple",
"object",
"structure",
"containing",
"the",
"modules",
"as",
"keys",
"and",
"using",
"arrays",
"as",
"dependecy",
"descriptors",
"."
] | 06a94b5de8a192f28444d6d7231dd2036bf46725 | https://github.com/sapegin/grunt-bower-concat/blob/06a94b5de8a192f28444d6d7231dd2036bf46725/lib/dependencyTools.js#L6-L25 | train |
sapegin/grunt-bower-concat | lib/dependencyTools.js | resolveDependencyGraph | function resolveDependencyGraph(module, resolved, unresolved, dependencies) {
var moduleDependencies;
if (module) {
moduleDependencies = dependencies[module];
if (!moduleDependencies) {
throw new Error('Component ' + module + ' not installed. Try bower install --save ' + module);
}
unresolved.push(module);
}
else {
moduleDependencies = Object.keys(dependencies);
}
moduleDependencies.forEach(function(moduleDependency) {
if (resolved.indexOf(moduleDependency) === -1) {
if (unresolved.indexOf(moduleDependency) !== -1) {
throw new Error('Circular reference detected for ' + module + ' - ' + moduleDependency);
}
resolveDependencyGraph(moduleDependency, resolved, unresolved, dependencies);
}
});
if (module) {
resolved.push(module);
unresolved = unresolved.splice(unresolved.indexOf(module), 1);
}
} | javascript | function resolveDependencyGraph(module, resolved, unresolved, dependencies) {
var moduleDependencies;
if (module) {
moduleDependencies = dependencies[module];
if (!moduleDependencies) {
throw new Error('Component ' + module + ' not installed. Try bower install --save ' + module);
}
unresolved.push(module);
}
else {
moduleDependencies = Object.keys(dependencies);
}
moduleDependencies.forEach(function(moduleDependency) {
if (resolved.indexOf(moduleDependency) === -1) {
if (unresolved.indexOf(moduleDependency) !== -1) {
throw new Error('Circular reference detected for ' + module + ' - ' + moduleDependency);
}
resolveDependencyGraph(moduleDependency, resolved, unresolved, dependencies);
}
});
if (module) {
resolved.push(module);
unresolved = unresolved.splice(unresolved.indexOf(module), 1);
}
} | [
"function",
"resolveDependencyGraph",
"(",
"module",
",",
"resolved",
",",
"unresolved",
",",
"dependencies",
")",
"{",
"var",
"moduleDependencies",
";",
"if",
"(",
"module",
")",
"{",
"moduleDependencies",
"=",
"dependencies",
"[",
"module",
"]",
";",
"if",
"(",
"!",
"moduleDependencies",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Component '",
"+",
"module",
"+",
"' not installed. Try bower install --save '",
"+",
"module",
")",
";",
"}",
"unresolved",
".",
"push",
"(",
"module",
")",
";",
"}",
"else",
"{",
"moduleDependencies",
"=",
"Object",
".",
"keys",
"(",
"dependencies",
")",
";",
"}",
"moduleDependencies",
".",
"forEach",
"(",
"function",
"(",
"moduleDependency",
")",
"{",
"if",
"(",
"resolved",
".",
"indexOf",
"(",
"moduleDependency",
")",
"===",
"-",
"1",
")",
"{",
"if",
"(",
"unresolved",
".",
"indexOf",
"(",
"moduleDependency",
")",
"!==",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Circular reference detected for '",
"+",
"module",
"+",
"' - '",
"+",
"moduleDependency",
")",
";",
"}",
"resolveDependencyGraph",
"(",
"moduleDependency",
",",
"resolved",
",",
"unresolved",
",",
"dependencies",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"module",
")",
"{",
"resolved",
".",
"push",
"(",
"module",
")",
";",
"unresolved",
"=",
"unresolved",
".",
"splice",
"(",
"unresolved",
".",
"indexOf",
"(",
"module",
")",
",",
"1",
")",
";",
"}",
"}"
] | Resolves a graph of dependencies into a flat, ordered array.
The arrays ordering ensures, that a dependecy of another module comes before the module itself.
This algorithem is adapted from the pseudo code example available here:
http://www.electricmonk.nl/log/2008/08/07/dependency-resolving-algorithm/ | [
"Resolves",
"a",
"graph",
"of",
"dependencies",
"into",
"a",
"flat",
"ordered",
"array",
"."
] | 06a94b5de8a192f28444d6d7231dd2036bf46725 | https://github.com/sapegin/grunt-bower-concat/blob/06a94b5de8a192f28444d6d7231dd2036bf46725/lib/dependencyTools.js#L35-L62 | train |
sapegin/grunt-bower-concat | lib/configTools.js | extractDestData | function extractDestData(data) {
if (destinationConfigExists(data)) {
if (data.dest instanceof Object) {
return extractMultiDestValues(data.dest);
}
else {
return extractBackportDestination(data.dest);
}
}
return [];
} | javascript | function extractDestData(data) {
if (destinationConfigExists(data)) {
if (data.dest instanceof Object) {
return extractMultiDestValues(data.dest);
}
else {
return extractBackportDestination(data.dest);
}
}
return [];
} | [
"function",
"extractDestData",
"(",
"data",
")",
"{",
"if",
"(",
"destinationConfigExists",
"(",
"data",
")",
")",
"{",
"if",
"(",
"data",
".",
"dest",
"instanceof",
"Object",
")",
"{",
"return",
"extractMultiDestValues",
"(",
"data",
".",
"dest",
")",
";",
"}",
"else",
"{",
"return",
"extractBackportDestination",
"(",
"data",
".",
"dest",
")",
";",
"}",
"}",
"return",
"[",
"]",
";",
"}"
] | Returns all dest, cssDest, jsDest, scssDest ... Configs
@param {Object} an Object of possible configs wich should be filtered and extracted
@return {Array} the config prefix (or file extension). For example css for cssDest, or js for dest. | [
"Returns",
"all",
"dest",
"cssDest",
"jsDest",
"scssDest",
"...",
"Configs"
] | 06a94b5de8a192f28444d6d7231dd2036bf46725 | https://github.com/sapegin/grunt-bower-concat/blob/06a94b5de8a192f28444d6d7231dd2036bf46725/lib/configTools.js#L19-L31 | train |
sapegin/grunt-bower-concat | tasks/bower-concat.js | concatenateAndWriteFile | function concatenateAndWriteFile(files, destination, separator) {
if (!destination || !files || !files.length) return;
files = _.map(files, process);
var src = files.join(separator || grunt.util.linefeed);
grunt.file.write(destination, src);
grunt.log.writeln('File ' + destination.cyan + ' created.');
} | javascript | function concatenateAndWriteFile(files, destination, separator) {
if (!destination || !files || !files.length) return;
files = _.map(files, process);
var src = files.join(separator || grunt.util.linefeed);
grunt.file.write(destination, src);
grunt.log.writeln('File ' + destination.cyan + ' created.');
} | [
"function",
"concatenateAndWriteFile",
"(",
"files",
",",
"destination",
",",
"separator",
")",
"{",
"if",
"(",
"!",
"destination",
"||",
"!",
"files",
"||",
"!",
"files",
".",
"length",
")",
"return",
";",
"files",
"=",
"_",
".",
"map",
"(",
"files",
",",
"process",
")",
";",
"var",
"src",
"=",
"files",
".",
"join",
"(",
"separator",
"||",
"grunt",
".",
"util",
".",
"linefeed",
")",
";",
"grunt",
".",
"file",
".",
"write",
"(",
"destination",
",",
"src",
")",
";",
"grunt",
".",
"log",
".",
"writeln",
"(",
"'File '",
"+",
"destination",
".",
"cyan",
"+",
"' created.'",
")",
";",
"}"
] | Concatenates and writes a file
@param {Array} files File contents
@param {String} destination File destination
@param {String} separator Files joined on this string | [
"Concatenates",
"and",
"writes",
"a",
"file"
] | 06a94b5de8a192f28444d6d7231dd2036bf46725 | https://github.com/sapegin/grunt-bower-concat/blob/06a94b5de8a192f28444d6d7231dd2036bf46725/tasks/bower-concat.js#L78-L86 | train |
sapegin/grunt-bower-concat | tasks/bower-concat.js | bowerList | function bowerList(kind) {
return function(done) {
var params = _.extend({}, bowerOptions);
params[kind] = true;
bower.commands.list(params, {offline: true})
.on('error', grunt.fail.fatal.bind(grunt.fail))
.on('end', function(data) {
done(null, data); // null means "no error" for async.parallel
});
};
} | javascript | function bowerList(kind) {
return function(done) {
var params = _.extend({}, bowerOptions);
params[kind] = true;
bower.commands.list(params, {offline: true})
.on('error', grunt.fail.fatal.bind(grunt.fail))
.on('end', function(data) {
done(null, data); // null means "no error" for async.parallel
});
};
} | [
"function",
"bowerList",
"(",
"kind",
")",
"{",
"return",
"function",
"(",
"done",
")",
"{",
"var",
"params",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"bowerOptions",
")",
";",
"params",
"[",
"kind",
"]",
"=",
"true",
";",
"bower",
".",
"commands",
".",
"list",
"(",
"params",
",",
"{",
"offline",
":",
"true",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"grunt",
".",
"fail",
".",
"fatal",
".",
"bind",
"(",
"grunt",
".",
"fail",
")",
")",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
"data",
")",
"{",
"done",
"(",
"null",
",",
"data",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] | Returns function that invokes `list` command of Bower API.
Should be used inside async.parallel.
@param {String} kind map|paths
@return {Function} | [
"Returns",
"function",
"that",
"invokes",
"list",
"command",
"of",
"Bower",
"API",
".",
"Should",
"be",
"used",
"inside",
"async",
".",
"parallel",
"."
] | 06a94b5de8a192f28444d6d7231dd2036bf46725 | https://github.com/sapegin/grunt-bower-concat/blob/06a94b5de8a192f28444d6d7231dd2036bf46725/tasks/bower-concat.js#L176-L186 | train |
sapegin/grunt-bower-concat | tasks/bower-concat.js | expandForAll | function expandForAll(array, makeMask) {
var files = [];
ensureArray(array).forEach(function(item) {
files = files.concat(grunt.file.expand(makeMask(item)));
});
return files;
} | javascript | function expandForAll(array, makeMask) {
var files = [];
ensureArray(array).forEach(function(item) {
files = files.concat(grunt.file.expand(makeMask(item)));
});
return files;
} | [
"function",
"expandForAll",
"(",
"array",
",",
"makeMask",
")",
"{",
"var",
"files",
"=",
"[",
"]",
";",
"ensureArray",
"(",
"array",
")",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"files",
"=",
"files",
".",
"concat",
"(",
"grunt",
".",
"file",
".",
"expand",
"(",
"makeMask",
"(",
"item",
")",
")",
")",
";",
"}",
")",
";",
"return",
"files",
";",
"}"
] | Runs grunt.file.expand for every array item and returns combined array.
@param {Array|String} array Masks (can be single string mask).
@param {Function} makeMask function(mask) { return mask; }
@return {Array} All found files. | [
"Runs",
"grunt",
".",
"file",
".",
"expand",
"for",
"every",
"array",
"item",
"and",
"returns",
"combined",
"array",
"."
] | 06a94b5de8a192f28444d6d7231dd2036bf46725 | https://github.com/sapegin/grunt-bower-concat/blob/06a94b5de8a192f28444d6d7231dd2036bf46725/tasks/bower-concat.js#L410-L416 | train |
sapegin/grunt-bower-concat | tasks/bower-concat.js | joinPathWith | function joinPathWith(prepend, append) {
return function(pathPart) {
// path.join(prepend..., pathPart, append...)
var params = ensureArray(prepend || []).concat([pathPart], ensureArray(append || []));
return path.join.apply(path, params);
};
} | javascript | function joinPathWith(prepend, append) {
return function(pathPart) {
// path.join(prepend..., pathPart, append...)
var params = ensureArray(prepend || []).concat([pathPart], ensureArray(append || []));
return path.join.apply(path, params);
};
} | [
"function",
"joinPathWith",
"(",
"prepend",
",",
"append",
")",
"{",
"return",
"function",
"(",
"pathPart",
")",
"{",
"var",
"params",
"=",
"ensureArray",
"(",
"prepend",
"||",
"[",
"]",
")",
".",
"concat",
"(",
"[",
"pathPart",
"]",
",",
"ensureArray",
"(",
"append",
"||",
"[",
"]",
")",
")",
";",
"return",
"path",
".",
"join",
".",
"apply",
"(",
"path",
",",
"params",
")",
";",
"}",
";",
"}"
] | Path joiner function factory. Returns function that prepends `pathPart` with `prepend` and appends it with `append`.
@param {Array|String} [prepend] Path parts that will be added before `pathPart`.
@param {Array|String} [append] Path parts that will be added after `pathPart`.
@return {Function} function(pathPart) {} | [
"Path",
"joiner",
"function",
"factory",
".",
"Returns",
"function",
"that",
"prepends",
"pathPart",
"with",
"prepend",
"and",
"appends",
"it",
"with",
"append",
"."
] | 06a94b5de8a192f28444d6d7231dd2036bf46725 | https://github.com/sapegin/grunt-bower-concat/blob/06a94b5de8a192f28444d6d7231dd2036bf46725/tasks/bower-concat.js#L425-L431 | train |
sapegin/grunt-bower-concat | tasks/bower-concat.js | isFileExtension | function isFileExtension(filepath, extension) {
return typeof filepath === 'string' && path.extname(filepath) === extension && fs.existsSync(filepath) &&
fs.lstatSync(filepath).isFile()
;
} | javascript | function isFileExtension(filepath, extension) {
return typeof filepath === 'string' && path.extname(filepath) === extension && fs.existsSync(filepath) &&
fs.lstatSync(filepath).isFile()
;
} | [
"function",
"isFileExtension",
"(",
"filepath",
",",
"extension",
")",
"{",
"return",
"typeof",
"filepath",
"===",
"'string'",
"&&",
"path",
".",
"extname",
"(",
"filepath",
")",
"===",
"extension",
"&&",
"fs",
".",
"existsSync",
"(",
"filepath",
")",
"&&",
"fs",
".",
"lstatSync",
"(",
"filepath",
")",
".",
"isFile",
"(",
")",
";",
"}"
] | Check whether specified path exists, is a file and has .js extension.
@param {String} filepath Path of a file.
@param {String} extension Extension to check for, including the`.`.
@return {Boolean} | [
"Check",
"whether",
"specified",
"path",
"exists",
"is",
"a",
"file",
"and",
"has",
".",
"js",
"extension",
"."
] | 06a94b5de8a192f28444d6d7231dd2036bf46725 | https://github.com/sapegin/grunt-bower-concat/blob/06a94b5de8a192f28444d6d7231dd2036bf46725/tasks/bower-concat.js#L440-L444 | train |
sapegin/grunt-bower-concat | tasks/bower-concat.js | getFileSize | function getFileSize(filepath, options) {
var stats = fs.statSync(filepath);
return filesize(stats.size, options);
} | javascript | function getFileSize(filepath, options) {
var stats = fs.statSync(filepath);
return filesize(stats.size, options);
} | [
"function",
"getFileSize",
"(",
"filepath",
",",
"options",
")",
"{",
"var",
"stats",
"=",
"fs",
".",
"statSync",
"(",
"filepath",
")",
";",
"return",
"filesize",
"(",
"stats",
".",
"size",
",",
"options",
")",
";",
"}"
] | Get size of a file in readable format.
@param {String} filepath Path of a file.
@param {Object} options [Optional] Filesize function flags.
@return {String} Readable file size. | [
"Get",
"size",
"of",
"a",
"file",
"in",
"readable",
"format",
"."
] | 06a94b5de8a192f28444d6d7231dd2036bf46725 | https://github.com/sapegin/grunt-bower-concat/blob/06a94b5de8a192f28444d6d7231dd2036bf46725/tasks/bower-concat.js#L453-L456 | train |
sapegin/grunt-bower-concat | tasks/bower-concat.js | toFileStats | function toFileStats(componentName, filepath) {
return {
src: path.relative(bowerDir, filepath),
component: componentName,
size: getFileSize(filepath)
};
} | javascript | function toFileStats(componentName, filepath) {
return {
src: path.relative(bowerDir, filepath),
component: componentName,
size: getFileSize(filepath)
};
} | [
"function",
"toFileStats",
"(",
"componentName",
",",
"filepath",
")",
"{",
"return",
"{",
"src",
":",
"path",
".",
"relative",
"(",
"bowerDir",
",",
"filepath",
")",
",",
"component",
":",
"componentName",
",",
"size",
":",
"getFileSize",
"(",
"filepath",
")",
"}",
";",
"}"
] | Wrap filepath with related component name and file size.
@param {String} componentName Name of component related to a file.
@param {String} filepath Path of a file.
@return {Object} fileStats | [
"Wrap",
"filepath",
"with",
"related",
"component",
"name",
"and",
"file",
"size",
"."
] | 06a94b5de8a192f28444d6d7231dd2036bf46725 | https://github.com/sapegin/grunt-bower-concat/blob/06a94b5de8a192f28444d6d7231dd2036bf46725/tasks/bower-concat.js#L465-L471 | train |
sapegin/grunt-bower-concat | tasks/bower-concat.js | logGroupStats | function logGroupStats(groupName, groupOrder, groupDest, files) {
if (!groupDest) {
return false;
}
if (!grunt.option('no-color')) {
groupDest = groupDest.cyan;
}
grunt.verbose.subhead('%s: -> %s', groupName, groupDest);
groupOrder.forEach(function(component) {
if (_.isArray(files[component]) && files[component].length) {
files[component].forEach(function(file) {
if (!grunt.option('no-color')) {
file.component = file.component.yellow;
file.size = file.size.green;
}
grunt.verbose.writeln(' ./%s [%s] - %s', file.src, file.component, file.size);
});
}
});
} | javascript | function logGroupStats(groupName, groupOrder, groupDest, files) {
if (!groupDest) {
return false;
}
if (!grunt.option('no-color')) {
groupDest = groupDest.cyan;
}
grunt.verbose.subhead('%s: -> %s', groupName, groupDest);
groupOrder.forEach(function(component) {
if (_.isArray(files[component]) && files[component].length) {
files[component].forEach(function(file) {
if (!grunt.option('no-color')) {
file.component = file.component.yellow;
file.size = file.size.green;
}
grunt.verbose.writeln(' ./%s [%s] - %s', file.src, file.component, file.size);
});
}
});
} | [
"function",
"logGroupStats",
"(",
"groupName",
",",
"groupOrder",
",",
"groupDest",
",",
"files",
")",
"{",
"if",
"(",
"!",
"groupDest",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"grunt",
".",
"option",
"(",
"'no-color'",
")",
")",
"{",
"groupDest",
"=",
"groupDest",
".",
"cyan",
";",
"}",
"grunt",
".",
"verbose",
".",
"subhead",
"(",
"'%s: -> %s'",
",",
"groupName",
",",
"groupDest",
")",
";",
"groupOrder",
".",
"forEach",
"(",
"function",
"(",
"component",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"files",
"[",
"component",
"]",
")",
"&&",
"files",
"[",
"component",
"]",
".",
"length",
")",
"{",
"files",
"[",
"component",
"]",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"if",
"(",
"!",
"grunt",
".",
"option",
"(",
"'no-color'",
")",
")",
"{",
"file",
".",
"component",
"=",
"file",
".",
"component",
".",
"yellow",
";",
"file",
".",
"size",
"=",
"file",
".",
"size",
".",
"green",
";",
"}",
"grunt",
".",
"verbose",
".",
"writeln",
"(",
"' ./%s [%s] - %s'",
",",
"file",
".",
"src",
",",
"file",
".",
"component",
",",
"file",
".",
"size",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | Verbose print list of files for a group.
@param {String} groupName Name of a files group.
@param {Array} groupOrder Order of components.
@param {String} groupDest Path to result of concatenation.
@param {Object} files Map of components fileStats | [
"Verbose",
"print",
"list",
"of",
"files",
"for",
"a",
"group",
"."
] | 06a94b5de8a192f28444d6d7231dd2036bf46725 | https://github.com/sapegin/grunt-bower-concat/blob/06a94b5de8a192f28444d6d7231dd2036bf46725/tasks/bower-concat.js#L481-L504 | train |
borschik/borschik | lib/freeze.js | freezeAllProcessDir | function freezeAllProcessDir(dir, basePath, result) {
fs.readdirSync(dir).forEach(function(file) {
file = PATH.resolve(dir, file);
var stat = fs.statSync(file);
if (stat.isFile()) {
freezeAllProcessFile(file, basePath, result);
} else if (stat.isDirectory()) {
freezeAllProcessDir(file, basePath, result);
}
});
} | javascript | function freezeAllProcessDir(dir, basePath, result) {
fs.readdirSync(dir).forEach(function(file) {
file = PATH.resolve(dir, file);
var stat = fs.statSync(file);
if (stat.isFile()) {
freezeAllProcessFile(file, basePath, result);
} else if (stat.isDirectory()) {
freezeAllProcessDir(file, basePath, result);
}
});
} | [
"function",
"freezeAllProcessDir",
"(",
"dir",
",",
"basePath",
",",
"result",
")",
"{",
"fs",
".",
"readdirSync",
"(",
"dir",
")",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"file",
"=",
"PATH",
".",
"resolve",
"(",
"dir",
",",
"file",
")",
";",
"var",
"stat",
"=",
"fs",
".",
"statSync",
"(",
"file",
")",
";",
"if",
"(",
"stat",
".",
"isFile",
"(",
")",
")",
"{",
"freezeAllProcessFile",
"(",
"file",
",",
"basePath",
",",
"result",
")",
";",
"}",
"else",
"if",
"(",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"freezeAllProcessDir",
"(",
"file",
",",
"basePath",
",",
"result",
")",
";",
"}",
"}",
")",
";",
"}"
] | Read dir recursivly and process files
@param dir
@param basePath
@param {Object} result Result JSON | [
"Read",
"dir",
"recursivly",
"and",
"process",
"files"
] | 5a0f06669113b9f5e4337c5f2fc9d2b321ee7b85 | https://github.com/borschik/borschik/blob/5a0f06669113b9f5e4337c5f2fc9d2b321ee7b85/lib/freeze.js#L253-L264 | train |
borschik/borschik | lib/freeze.js | mkpath | function mkpath(path) {
var dirs = path.split(PATH.sep);
var _path = '';
var winDisk = /^\w{1}:\\$/;
dirs.forEach(function(dir) {
dir = dir || PATH.sep;
if (dir) {
_path = _path ? PATH.join(_path, dir) : dir;
// fs.mkdirSync('/') raises EISDIR (invalid operation) exception on OSX 10.8.4/node 0.10
// fs.mkdirSync('D:\\') raises EPERM (operation not permitted) exception on Windows 7/node 0.10
// not tested in other configurations
if (_path === '/' || winDisk.test(PATH.resolve(dir))) {
return;
}
// @see https://github.com/veged/borschik/issues/90
try {
fs.mkdirSync(_path);
} catch(e) {
// ignore EEXIST error
if (e.code !== 'EEXIST') {
throw new Error(e)
}
}
}
});
} | javascript | function mkpath(path) {
var dirs = path.split(PATH.sep);
var _path = '';
var winDisk = /^\w{1}:\\$/;
dirs.forEach(function(dir) {
dir = dir || PATH.sep;
if (dir) {
_path = _path ? PATH.join(_path, dir) : dir;
// fs.mkdirSync('/') raises EISDIR (invalid operation) exception on OSX 10.8.4/node 0.10
// fs.mkdirSync('D:\\') raises EPERM (operation not permitted) exception on Windows 7/node 0.10
// not tested in other configurations
if (_path === '/' || winDisk.test(PATH.resolve(dir))) {
return;
}
// @see https://github.com/veged/borschik/issues/90
try {
fs.mkdirSync(_path);
} catch(e) {
// ignore EEXIST error
if (e.code !== 'EEXIST') {
throw new Error(e)
}
}
}
});
} | [
"function",
"mkpath",
"(",
"path",
")",
"{",
"var",
"dirs",
"=",
"path",
".",
"split",
"(",
"PATH",
".",
"sep",
")",
";",
"var",
"_path",
"=",
"''",
";",
"var",
"winDisk",
"=",
"/",
"^\\w{1}:\\\\$",
"/",
";",
"dirs",
".",
"forEach",
"(",
"function",
"(",
"dir",
")",
"{",
"dir",
"=",
"dir",
"||",
"PATH",
".",
"sep",
";",
"if",
"(",
"dir",
")",
"{",
"_path",
"=",
"_path",
"?",
"PATH",
".",
"join",
"(",
"_path",
",",
"dir",
")",
":",
"dir",
";",
"if",
"(",
"_path",
"===",
"'/'",
"||",
"winDisk",
".",
"test",
"(",
"PATH",
".",
"resolve",
"(",
"dir",
")",
")",
")",
"{",
"return",
";",
"}",
"try",
"{",
"fs",
".",
"mkdirSync",
"(",
"_path",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"code",
"!==",
"'EEXIST'",
")",
"{",
"throw",
"new",
"Error",
"(",
"e",
")",
"}",
"}",
"}",
"}",
")",
";",
"}"
] | Make dirs if not exists.
@param {String} path Path to make. | [
"Make",
"dirs",
"if",
"not",
"exists",
"."
] | 5a0f06669113b9f5e4337c5f2fc9d2b321ee7b85 | https://github.com/borschik/borschik/blob/5a0f06669113b9f5e4337c5f2fc9d2b321ee7b85/lib/freeze.js#L416-L442 | train |
borschik/borschik | lib/freeze.js | save | function save(filePath, content) {
mkpath(PATH.dirname(filePath));
fs.writeFileSync(filePath, content);
} | javascript | function save(filePath, content) {
mkpath(PATH.dirname(filePath));
fs.writeFileSync(filePath, content);
} | [
"function",
"save",
"(",
"filePath",
",",
"content",
")",
"{",
"mkpath",
"(",
"PATH",
".",
"dirname",
"(",
"filePath",
")",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"filePath",
",",
"content",
")",
";",
"}"
] | Save file and make dirs if needed.
@param {String} filePath File path to save.
@param {String} content File content to save. | [
"Save",
"file",
"and",
"make",
"dirs",
"if",
"needed",
"."
] | 5a0f06669113b9f5e4337c5f2fc9d2b321ee7b85 | https://github.com/borschik/borschik/blob/5a0f06669113b9f5e4337c5f2fc9d2b321ee7b85/lib/freeze.js#L450-L453 | train |
borschik/borschik | lib/freeze.js | subArrayJoin | function subArrayJoin(a, separator, from, to) {
return a.slice(from, to + 1).join(separator);
} | javascript | function subArrayJoin(a, separator, from, to) {
return a.slice(from, to + 1).join(separator);
} | [
"function",
"subArrayJoin",
"(",
"a",
",",
"separator",
",",
"from",
",",
"to",
")",
"{",
"return",
"a",
".",
"slice",
"(",
"from",
",",
"to",
"+",
"1",
")",
".",
"join",
"(",
"separator",
")",
";",
"}"
] | Join part of array.
@param {Array} a Array to join.
@param {String} separator Separator to use in join.
@param {Number} from Join start index.
@param {Number} to Join finish index.
@returns {String} Joined array string. | [
"Join",
"part",
"of",
"array",
"."
] | 5a0f06669113b9f5e4337c5f2fc9d2b321ee7b85 | https://github.com/borschik/borschik/blob/5a0f06669113b9f5e4337c5f2fc9d2b321ee7b85/lib/freeze.js#L541-L543 | train |
borschik/borschik | lib/freeze.js | arraySplice | function arraySplice(a1, from, to, a2) {
var aL = a1.slice(0, from);
var aR = a1.slice(to);
return aL.concat(a2).concat(aR);
} | javascript | function arraySplice(a1, from, to, a2) {
var aL = a1.slice(0, from);
var aR = a1.slice(to);
return aL.concat(a2).concat(aR);
} | [
"function",
"arraySplice",
"(",
"a1",
",",
"from",
",",
"to",
",",
"a2",
")",
"{",
"var",
"aL",
"=",
"a1",
".",
"slice",
"(",
"0",
",",
"from",
")",
";",
"var",
"aR",
"=",
"a1",
".",
"slice",
"(",
"to",
")",
";",
"return",
"aL",
".",
"concat",
"(",
"a2",
")",
".",
"concat",
"(",
"aR",
")",
";",
"}"
] | Splice array replacing it's elements by another array.
@param {Array} a1 Array to splice.
@param {Number} from Splice start index.
@param {Number} to Splice finish index.
@param {Array} a2 Array to inject.
@returns {Array} New array. | [
"Splice",
"array",
"replacing",
"it",
"s",
"elements",
"by",
"another",
"array",
"."
] | 5a0f06669113b9f5e4337c5f2fc9d2b321ee7b85 | https://github.com/borschik/borschik/blob/5a0f06669113b9f5e4337c5f2fc9d2b321ee7b85/lib/freeze.js#L554-L559 | train |
borschik/borschik | lib/freeze.js | setNestingLevel | function setNestingLevel(config, dir, rawValue) {
// config can have value "0", so we can't use "!config[dir]"
if ( !(dir in config) ) {
config[dir] = Math.max(parseInt(rawValue, 10) || 0, 0);
}
} | javascript | function setNestingLevel(config, dir, rawValue) {
// config can have value "0", so we can't use "!config[dir]"
if ( !(dir in config) ) {
config[dir] = Math.max(parseInt(rawValue, 10) || 0, 0);
}
} | [
"function",
"setNestingLevel",
"(",
"config",
",",
"dir",
",",
"rawValue",
")",
"{",
"if",
"(",
"!",
"(",
"dir",
"in",
"config",
")",
")",
"{",
"config",
"[",
"dir",
"]",
"=",
"Math",
".",
"max",
"(",
"parseInt",
"(",
"rawValue",
",",
"10",
")",
"||",
"0",
",",
"0",
")",
";",
"}",
"}"
] | Parse and set nesting level in config object
@param {object} config Nesting level config
@param {string} dir Path to directory
@param {string} rawValue Raw value from config (.borschik) | [
"Parse",
"and",
"set",
"nesting",
"level",
"in",
"config",
"object"
] | 5a0f06669113b9f5e4337c5f2fc9d2b321ee7b85 | https://github.com/borschik/borschik/blob/5a0f06669113b9f5e4337c5f2fc9d2b321ee7b85/lib/freeze.js#L577-L582 | train |
borschik/borschik | lib/error.js | function(lines, error) {
var lineNumber = error.line - 1;
var result = [
renderLine(lineNumber, lines[lineNumber]),
renderPointer(error.col)
];
var i = lineNumber - 1;
var linesAround = 2;
while (i >= 0 && i >= (lineNumber - linesAround)) {
result.unshift(renderLine(i, lines[i]));
i--;
}
i = lineNumber + 1;
while (i < lines.length && i <= (lineNumber + linesAround)) {
result.push(renderLine(i, lines[i]));
i++;
}
result.unshift(error.message + " (line: " + error.line + ", col: " + error.col + ", pos: " + error.pos + ")");
return result.join('\n');
} | javascript | function(lines, error) {
var lineNumber = error.line - 1;
var result = [
renderLine(lineNumber, lines[lineNumber]),
renderPointer(error.col)
];
var i = lineNumber - 1;
var linesAround = 2;
while (i >= 0 && i >= (lineNumber - linesAround)) {
result.unshift(renderLine(i, lines[i]));
i--;
}
i = lineNumber + 1;
while (i < lines.length && i <= (lineNumber + linesAround)) {
result.push(renderLine(i, lines[i]));
i++;
}
result.unshift(error.message + " (line: " + error.line + ", col: " + error.col + ", pos: " + error.pos + ")");
return result.join('\n');
} | [
"function",
"(",
"lines",
",",
"error",
")",
"{",
"var",
"lineNumber",
"=",
"error",
".",
"line",
"-",
"1",
";",
"var",
"result",
"=",
"[",
"renderLine",
"(",
"lineNumber",
",",
"lines",
"[",
"lineNumber",
"]",
")",
",",
"renderPointer",
"(",
"error",
".",
"col",
")",
"]",
";",
"var",
"i",
"=",
"lineNumber",
"-",
"1",
";",
"var",
"linesAround",
"=",
"2",
";",
"while",
"(",
"i",
">=",
"0",
"&&",
"i",
">=",
"(",
"lineNumber",
"-",
"linesAround",
")",
")",
"{",
"result",
".",
"unshift",
"(",
"renderLine",
"(",
"i",
",",
"lines",
"[",
"i",
"]",
")",
")",
";",
"i",
"--",
";",
"}",
"i",
"=",
"lineNumber",
"+",
"1",
";",
"while",
"(",
"i",
"<",
"lines",
".",
"length",
"&&",
"i",
"<=",
"(",
"lineNumber",
"+",
"linesAround",
")",
")",
"{",
"result",
".",
"push",
"(",
"renderLine",
"(",
"i",
",",
"lines",
"[",
"i",
"]",
")",
")",
";",
"i",
"++",
";",
"}",
"result",
".",
"unshift",
"(",
"error",
".",
"message",
"+",
"\" (line: \"",
"+",
"error",
".",
"line",
"+",
"\", col: \"",
"+",
"error",
".",
"col",
"+",
"\", pos: \"",
"+",
"error",
".",
"pos",
"+",
"\")\"",
")",
";",
"return",
"result",
".",
"join",
"(",
"'\\n'",
")",
";",
"}"
] | Create error message with explanation
@example
```
Error: Unexpected token: name (foo) (line: 7437, col: 12, pos: 312592)
7435 | };
7436 | } else {
7437 | let foo = 'bar';
--------------------^
7438 | result = {
7439 | result: 0
```
@param lines
@param error | [
"Create",
"error",
"message",
"with",
"explanation"
] | 5a0f06669113b9f5e4337c5f2fc9d2b321ee7b85 | https://github.com/borschik/borschik/blob/5a0f06669113b9f5e4337c5f2fc9d2b321ee7b85/lib/error.js#L21-L41 | train |
|
Wildhoney/ngDroplet | dist/ng-droplet.js | parseJSON | function parseJSON(str) {
var result;
try {
result = $scope.options.parserFn(str);
} catch (e) {
return str;
}
return result;
} | javascript | function parseJSON(str) {
var result;
try {
result = $scope.options.parserFn(str);
} catch (e) {
return str;
}
return result;
} | [
"function",
"parseJSON",
"(",
"str",
")",
"{",
"var",
"result",
";",
"try",
"{",
"result",
"=",
"$scope",
".",
"options",
".",
"parserFn",
"(",
"str",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"str",
";",
"}",
"return",
"result",
";",
"}"
] | Parse the response, and then emit the event passing along the response and the uploaded files! | [
"Parse",
"the",
"response",
"and",
"then",
"emit",
"the",
"event",
"passing",
"along",
"the",
"response",
"and",
"the",
"uploaded",
"files!"
] | a68f11f5e47a43784e036e1603447402cb3239d6 | https://github.com/Wildhoney/ngDroplet/blob/a68f11f5e47a43784e036e1603447402cb3239d6/dist/ng-droplet.js#L303-L311 | train |
Wildhoney/ngDroplet | dist/ng-droplet.js | error | function error() {
this.httpRequest.upload.onerror = function onError() {
$scope.$apply(function apply() {
$scope.finishedUploading();
$scope.isError = true;
var response = $scope.options.parserFn(this.httpRequest.responseText);
$rootScope.$broadcast('$dropletError', response);
$scope.onError({ response: response });
this.deferred.reject(response);
}.bind(this));
}.bind(this);
} | javascript | function error() {
this.httpRequest.upload.onerror = function onError() {
$scope.$apply(function apply() {
$scope.finishedUploading();
$scope.isError = true;
var response = $scope.options.parserFn(this.httpRequest.responseText);
$rootScope.$broadcast('$dropletError', response);
$scope.onError({ response: response });
this.deferred.reject(response);
}.bind(this));
}.bind(this);
} | [
"function",
"error",
"(",
")",
"{",
"this",
".",
"httpRequest",
".",
"upload",
".",
"onerror",
"=",
"function",
"onError",
"(",
")",
"{",
"$scope",
".",
"$apply",
"(",
"function",
"apply",
"(",
")",
"{",
"$scope",
".",
"finishedUploading",
"(",
")",
";",
"$scope",
".",
"isError",
"=",
"true",
";",
"var",
"response",
"=",
"$scope",
".",
"options",
".",
"parserFn",
"(",
"this",
".",
"httpRequest",
".",
"responseText",
")",
";",
"$rootScope",
".",
"$broadcast",
"(",
"'$dropletError'",
",",
"response",
")",
";",
"$scope",
".",
"onError",
"(",
"{",
"response",
":",
"response",
"}",
")",
";",
"this",
".",
"deferred",
".",
"reject",
"(",
"response",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
";",
"}"
] | Invoked when an error is thrown when uploading the files.
@method error
@return {void} | [
"Invoked",
"when",
"an",
"error",
"is",
"thrown",
"when",
"uploading",
"the",
"files",
"."
] | a68f11f5e47a43784e036e1603447402cb3239d6 | https://github.com/Wildhoney/ngDroplet/blob/a68f11f5e47a43784e036e1603447402cb3239d6/dist/ng-droplet.js#L349-L367 | train |
Wildhoney/ngDroplet | dist/ng-droplet.js | progress | function progress() {
var requestLength = $scope.getRequestLength(this.files);
this.httpRequest.upload.onprogress = function onProgress(event) {
$scope.$apply(function apply() {
if (event.lengthComputable) {
// Update the progress object.
$scope.requestProgress.percent = Math.round((event.loaded / requestLength) * 100);
$scope.requestProgress.loaded = event.loaded;
$scope.requestProgress.total = requestLength;
}
});
};
} | javascript | function progress() {
var requestLength = $scope.getRequestLength(this.files);
this.httpRequest.upload.onprogress = function onProgress(event) {
$scope.$apply(function apply() {
if (event.lengthComputable) {
// Update the progress object.
$scope.requestProgress.percent = Math.round((event.loaded / requestLength) * 100);
$scope.requestProgress.loaded = event.loaded;
$scope.requestProgress.total = requestLength;
}
});
};
} | [
"function",
"progress",
"(",
")",
"{",
"var",
"requestLength",
"=",
"$scope",
".",
"getRequestLength",
"(",
"this",
".",
"files",
")",
";",
"this",
".",
"httpRequest",
".",
"upload",
".",
"onprogress",
"=",
"function",
"onProgress",
"(",
"event",
")",
"{",
"$scope",
".",
"$apply",
"(",
"function",
"apply",
"(",
")",
"{",
"if",
"(",
"event",
".",
"lengthComputable",
")",
"{",
"$scope",
".",
"requestProgress",
".",
"percent",
"=",
"Math",
".",
"round",
"(",
"(",
"event",
".",
"loaded",
"/",
"requestLength",
")",
"*",
"100",
")",
";",
"$scope",
".",
"requestProgress",
".",
"loaded",
"=",
"event",
".",
"loaded",
";",
"$scope",
".",
"requestProgress",
".",
"total",
"=",
"requestLength",
";",
"}",
"}",
")",
";",
"}",
";",
"}"
] | Invoked each time there's a progress update on the files being uploaded.
@method progress
@return {void} | [
"Invoked",
"each",
"time",
"there",
"s",
"a",
"progress",
"update",
"on",
"the",
"files",
"being",
"uploaded",
"."
] | a68f11f5e47a43784e036e1603447402cb3239d6 | https://github.com/Wildhoney/ngDroplet/blob/a68f11f5e47a43784e036e1603447402cb3239d6/dist/ng-droplet.js#L375-L396 | train |
linnovate/meanio | lib/core_modules/module/util.js | walk | function walk(wpath, type, excludeDir, callback) {
// regex - any chars, then dash type, 's' is optional, with .js or .coffee extension, case-insensitive
// e.g. articles-MODEL.js or mypackage-routes.coffee
var rgx = new RegExp('(.*)-' + type + '(s?).(js|coffee)$', 'i');
if (!fs.existsSync(wpath)) return;
fs.readdirSync(wpath).forEach(function(file) {
var newPath = path.join(wpath, file);
var stat = fs.statSync(newPath);
if (stat.isFile() && (rgx.test(file) || (baseRgx.test(file)) && ~newPath.indexOf(type))) {
// if (!rgx.test(file)) console.log(' Consider updating filename:', newPath);
callback(newPath);
} else if (stat.isDirectory() && file !== excludeDir && ~newPath.indexOf(type)) {
walk(newPath, type, excludeDir, callback);
}
});
} | javascript | function walk(wpath, type, excludeDir, callback) {
// regex - any chars, then dash type, 's' is optional, with .js or .coffee extension, case-insensitive
// e.g. articles-MODEL.js or mypackage-routes.coffee
var rgx = new RegExp('(.*)-' + type + '(s?).(js|coffee)$', 'i');
if (!fs.existsSync(wpath)) return;
fs.readdirSync(wpath).forEach(function(file) {
var newPath = path.join(wpath, file);
var stat = fs.statSync(newPath);
if (stat.isFile() && (rgx.test(file) || (baseRgx.test(file)) && ~newPath.indexOf(type))) {
// if (!rgx.test(file)) console.log(' Consider updating filename:', newPath);
callback(newPath);
} else if (stat.isDirectory() && file !== excludeDir && ~newPath.indexOf(type)) {
walk(newPath, type, excludeDir, callback);
}
});
} | [
"function",
"walk",
"(",
"wpath",
",",
"type",
",",
"excludeDir",
",",
"callback",
")",
"{",
"var",
"rgx",
"=",
"new",
"RegExp",
"(",
"'(.*)-'",
"+",
"type",
"+",
"'(s?).(js|coffee)$'",
",",
"'i'",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"wpath",
")",
")",
"return",
";",
"fs",
".",
"readdirSync",
"(",
"wpath",
")",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"newPath",
"=",
"path",
".",
"join",
"(",
"wpath",
",",
"file",
")",
";",
"var",
"stat",
"=",
"fs",
".",
"statSync",
"(",
"newPath",
")",
";",
"if",
"(",
"stat",
".",
"isFile",
"(",
")",
"&&",
"(",
"rgx",
".",
"test",
"(",
"file",
")",
"||",
"(",
"baseRgx",
".",
"test",
"(",
"file",
")",
")",
"&&",
"~",
"newPath",
".",
"indexOf",
"(",
"type",
")",
")",
")",
"{",
"callback",
"(",
"newPath",
")",
";",
"}",
"else",
"if",
"(",
"stat",
".",
"isDirectory",
"(",
")",
"&&",
"file",
"!==",
"excludeDir",
"&&",
"~",
"newPath",
".",
"indexOf",
"(",
"type",
")",
")",
"{",
"walk",
"(",
"newPath",
",",
"type",
",",
"excludeDir",
",",
"callback",
")",
";",
"}",
"}",
")",
";",
"}"
] | recursively walk modules path and callback for each file | [
"recursively",
"walk",
"modules",
"path",
"and",
"callback",
"for",
"each",
"file"
] | 21504436d0ab1b1155f9040c4fa1d962a0fc203e | https://github.com/linnovate/meanio/blob/21504436d0ab1b1155f9040c4fa1d962a0fc203e/lib/core_modules/module/util.js#L11-L26 | train |
linnovate/meanio | lib/core_modules/module/util.js | preload | function preload(gpath, type) {
glob.sync(gpath).forEach(function(file) {
walk(file, type, null, require);
});
} | javascript | function preload(gpath, type) {
glob.sync(gpath).forEach(function(file) {
walk(file, type, null, require);
});
} | [
"function",
"preload",
"(",
"gpath",
",",
"type",
")",
"{",
"glob",
".",
"sync",
"(",
"gpath",
")",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"walk",
"(",
"file",
",",
"type",
",",
"null",
",",
"require",
")",
";",
"}",
")",
";",
"}"
] | ability to preload requirements for tests | [
"ability",
"to",
"preload",
"requirements",
"for",
"tests"
] | 21504436d0ab1b1155f9040c4fa1d962a0fc203e | https://github.com/linnovate/meanio/blob/21504436d0ab1b1155f9040c4fa1d962a0fc203e/lib/core_modules/module/util.js#L29-L33 | train |
padolsey/SIML | vendor/twtl.js | findAssertionSourceInTrace | function findAssertionSourceInTrace(trace) {
var found = null;
for (var i = 0, l = trace.length; i < l; ++i) {
if (
trace[i].file === stSkipStart.file &&
trace[i].line >= stSkipStart.line &&
trace[i].line <= stSkipEnd.line
) {
break;
}
found = trace[i];
}
return found;
} | javascript | function findAssertionSourceInTrace(trace) {
var found = null;
for (var i = 0, l = trace.length; i < l; ++i) {
if (
trace[i].file === stSkipStart.file &&
trace[i].line >= stSkipStart.line &&
trace[i].line <= stSkipEnd.line
) {
break;
}
found = trace[i];
}
return found;
} | [
"function",
"findAssertionSourceInTrace",
"(",
"trace",
")",
"{",
"var",
"found",
"=",
"null",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"trace",
".",
"length",
";",
"i",
"<",
"l",
";",
"++",
"i",
")",
"{",
"if",
"(",
"trace",
"[",
"i",
"]",
".",
"file",
"===",
"stSkipStart",
".",
"file",
"&&",
"trace",
"[",
"i",
"]",
".",
"line",
">=",
"stSkipStart",
".",
"line",
"&&",
"trace",
"[",
"i",
"]",
".",
"line",
"<=",
"stSkipEnd",
".",
"line",
")",
"{",
"break",
";",
"}",
"found",
"=",
"trace",
"[",
"i",
"]",
";",
"}",
"return",
"found",
";",
"}"
] | Find an assertion's likely 'source' by removing any references to twtl
in the stack trace | [
"Find",
"an",
"assertion",
"s",
"likely",
"source",
"by",
"removing",
"any",
"references",
"to",
"twtl",
"in",
"the",
"stack",
"trace"
] | 1b3b34bfdedb4335cacc46410c5b5b417829c1ef | https://github.com/padolsey/SIML/blob/1b3b34bfdedb4335cacc46410c5b5b417829c1ef/vendor/twtl.js#L19-L36 | train |
linnovate/meanio | lib/core_modules/module/events.js | prepArgs | function prepArgs(args, name, event, defaults) {
args = Array.from(args);
var namespace = [name];
if (!Array.isArray(event)) {
event = event.split(delimiter);
}
namespace = namespace.concat(event);
args.shift();//remove the event
args.unshift(namespace);
if (defaults) {
args.push(defaults);
}
return args;
} | javascript | function prepArgs(args, name, event, defaults) {
args = Array.from(args);
var namespace = [name];
if (!Array.isArray(event)) {
event = event.split(delimiter);
}
namespace = namespace.concat(event);
args.shift();//remove the event
args.unshift(namespace);
if (defaults) {
args.push(defaults);
}
return args;
} | [
"function",
"prepArgs",
"(",
"args",
",",
"name",
",",
"event",
",",
"defaults",
")",
"{",
"args",
"=",
"Array",
".",
"from",
"(",
"args",
")",
";",
"var",
"namespace",
"=",
"[",
"name",
"]",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"event",
")",
")",
"{",
"event",
"=",
"event",
".",
"split",
"(",
"delimiter",
")",
";",
"}",
"namespace",
"=",
"namespace",
".",
"concat",
"(",
"event",
")",
";",
"args",
".",
"shift",
"(",
")",
";",
"args",
".",
"unshift",
"(",
"namespace",
")",
";",
"if",
"(",
"defaults",
")",
"{",
"args",
".",
"push",
"(",
"defaults",
")",
";",
"}",
"return",
"args",
";",
"}"
] | Helps in preparing our arguments for passing to emit and emitAsync
@param args
@param name
@param defaults
@returns {*} | [
"Helps",
"in",
"preparing",
"our",
"arguments",
"for",
"passing",
"to",
"emit",
"and",
"emitAsync"
] | 21504436d0ab1b1155f9040c4fa1d962a0fc203e | https://github.com/linnovate/meanio/blob/21504436d0ab1b1155f9040c4fa1d962a0fc203e/lib/core_modules/module/events.js#L125-L142 | train |
splunk/splunk-bunyan-logger | index.js | function (config) {
/** @type {SplunkLogger} */
this.logger = new SplunkLogger(config);
// If using the common logger's default name, change it
if (this.logger.config.name.match("splunk-javascript-logging/\\d+\\.\\d+\\.\\d+")) {
this.logger.config.name = "splunk-bunyan-logger/0.10.1";
}
// Overwrite the common library's error callback
var that = this;
this.logger.error = function(err, context) {
that.emit("error", err, context);
};
/* jshint unused:false */
/**
* A callback function called after sending a request to Splunk:
* <code>function(err, response, body)</code>. Defaults
* to an empty function.
*
* @type {function}
*/
this.send = function(err, resp, body) {};
} | javascript | function (config) {
/** @type {SplunkLogger} */
this.logger = new SplunkLogger(config);
// If using the common logger's default name, change it
if (this.logger.config.name.match("splunk-javascript-logging/\\d+\\.\\d+\\.\\d+")) {
this.logger.config.name = "splunk-bunyan-logger/0.10.1";
}
// Overwrite the common library's error callback
var that = this;
this.logger.error = function(err, context) {
that.emit("error", err, context);
};
/* jshint unused:false */
/**
* A callback function called after sending a request to Splunk:
* <code>function(err, response, body)</code>. Defaults
* to an empty function.
*
* @type {function}
*/
this.send = function(err, resp, body) {};
} | [
"function",
"(",
"config",
")",
"{",
"this",
".",
"logger",
"=",
"new",
"SplunkLogger",
"(",
"config",
")",
";",
"if",
"(",
"this",
".",
"logger",
".",
"config",
".",
"name",
".",
"match",
"(",
"\"splunk-javascript-logging/\\\\d+\\\\.\\\\d+\\\\.\\\\d+\"",
")",
")",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"}"
] | A class that implements a raw writable stream.
@property {object} config - Configuration settings for this <code>SplunkStream</code> instance.
@property {object[]} contextQueue - Queue of <code>context</code> objects to be sent to Splunk.
@property {function} error - A callback function for errors: <code>function(err, context)</code>.
Defaults to <code>console.log</code> both values;
@param {object} config - Configuration settings for a new [SplunkLogger]{@link SplunkLogger}.
@param {string} config.token - HTTP Event Collector token, required.
@param {string} [config.name=splunk-javascript-logging/0.10.1] - Name for this logger.
@param {string} [config.host=localhost] - Hostname or IP address of Splunk server.
@param {string} [config.maxRetries=0] - How many times to retry when HTTP POST to Splunk fails.
@param {string} [config.path=/services/collector/event/1.0] - URL path to send data to on the Splunk server.
@param {string} [config.protocol=https] - Protocol used to communicate with the Splunk server, <code>http</code> or <code>https</code>.
@param {number} [config.port=8088] - HTTP Event Collector port on the Splunk server.
@param {string} [config.url] - URL string to pass to {@link https://nodejs.org/api/url.html#url_url_parsing|url.parse}. This will try to set
<code>host</code>, <code>path</code>, <code>protocol</code>, <code>port</code>, <code>url</code>. Any of these values will be overwritten if
the corresponding property is set on <code>config</code>.
@param {string} [config.level=info] - Logging level to use, will show up as the <code>severity</code> field of an event, see
[SplunkLogger.levels]{@link SplunkLogger#levels} for common levels.
@param {number} [config.batchInterval=0] - Automatically flush events after this many milliseconds.
When set to a non-positive value, events will be sent one by one. This setting is ignored when non-positive.
@param {number} [config.maxBatchSize=0] - Automatically flush events after the size of queued
events exceeds this many bytes. This setting is ignored when non-positive.
@param {number} [config.maxBatchCount=1] - Automatically flush events after this many
events have been queued. Defaults to flush immediately on sending an event. This setting is ignored when non-positive.
@constructor
@implements {@link https://nodejs.org/api/stream.html#stream_class_stream_writable|Stream.Writable} | [
"A",
"class",
"that",
"implements",
"a",
"raw",
"writable",
"stream",
"."
] | 82d0811f3b08cb5bdc64a21c932a0e558804a58b | https://github.com/splunk/splunk-bunyan-logger/blob/82d0811f3b08cb5bdc64a21c932a0e558804a58b/index.js#L53-L77 | train |
|
splunk/splunk-bunyan-logger | index.js | function (level) {
switch(level) {
case 10:
return module.exports.levels.TRACE;
case 20:
return module.exports.levels.DEBUG;
case 40:
return module.exports.levels.WARN;
case 50:
return module.exports.levels.ERROR;
case 60:
return module.exports.levels.FATAL;
default:
return module.exports.levels.INFO;
}
} | javascript | function (level) {
switch(level) {
case 10:
return module.exports.levels.TRACE;
case 20:
return module.exports.levels.DEBUG;
case 40:
return module.exports.levels.WARN;
case 50:
return module.exports.levels.ERROR;
case 60:
return module.exports.levels.FATAL;
default:
return module.exports.levels.INFO;
}
} | [
"function",
"(",
"level",
")",
"{",
"switch",
"(",
"level",
")",
"{",
"case",
"10",
":",
"return",
"module",
".",
"exports",
".",
"levels",
".",
"TRACE",
";",
"case",
"20",
":",
"return",
"module",
".",
"exports",
".",
"levels",
".",
"DEBUG",
";",
"case",
"40",
":",
"return",
"module",
".",
"exports",
".",
"levels",
".",
"WARN",
";",
"case",
"50",
":",
"return",
"module",
".",
"exports",
".",
"levels",
".",
"ERROR",
";",
"case",
"60",
":",
"return",
"module",
".",
"exports",
".",
"levels",
".",
"FATAL",
";",
"default",
":",
"return",
"module",
".",
"exports",
".",
"levels",
".",
"INFO",
";",
"}",
"}"
] | Translates a Bunyan logging level number to the name of the level.
@param {number} level - A Bunyan logging level integer. See {@link SplunkBunyanLogger.levels}
@returns {string}
@memberof SplunkBunyanLogger | [
"Translates",
"a",
"Bunyan",
"logging",
"level",
"number",
"to",
"the",
"name",
"of",
"the",
"level",
"."
] | 82d0811f3b08cb5bdc64a21c932a0e558804a58b | https://github.com/splunk/splunk-bunyan-logger/blob/82d0811f3b08cb5bdc64a21c932a0e558804a58b/index.js#L174-L189 | train |
|
konitter/gulp-combine-media-queries | index.js | function(declarations) {
var strCss = '';
if (declarations.type === 'declaration') {
strCss += '\n\t' + processDeclaration(declarations);
} else if (declarations.type === 'comment') {
strCss += ' ' + processComment(declarations);
}
return strCss;
} | javascript | function(declarations) {
var strCss = '';
if (declarations.type === 'declaration') {
strCss += '\n\t' + processDeclaration(declarations);
} else if (declarations.type === 'comment') {
strCss += ' ' + processComment(declarations);
}
return strCss;
} | [
"function",
"(",
"declarations",
")",
"{",
"var",
"strCss",
"=",
"''",
";",
"if",
"(",
"declarations",
".",
"type",
"===",
"'declaration'",
")",
"{",
"strCss",
"+=",
"'\\n\\t'",
"+",
"\\n",
";",
"}",
"else",
"\\t",
"processDeclaration",
"(",
"declarations",
")",
"}"
] | Check declarations type | [
"Check",
"declarations",
"type"
] | fdd106764f19aee522ca3eb2a86217d6462541a4 | https://github.com/konitter/gulp-combine-media-queries/blob/fdd106764f19aee522ca3eb2a86217d6462541a4/index.js#L46-L54 | train |
|
konitter/gulp-combine-media-queries | index.js | function(rule) {
var strCss = '';
strCss += rule.selectors.join(',\n') + ' {';
rule.declarations.forEach(function(rules) {
strCss += commentOrDeclaration(rules);
});
strCss += '\n}\n\n';
return strCss;
} | javascript | function(rule) {
var strCss = '';
strCss += rule.selectors.join(',\n') + ' {';
rule.declarations.forEach(function(rules) {
strCss += commentOrDeclaration(rules);
});
strCss += '\n}\n\n';
return strCss;
} | [
"function",
"(",
"rule",
")",
"{",
"var",
"strCss",
"=",
"''",
";",
"strCss",
"+=",
"rule",
".",
"selectors",
".",
"join",
"(",
"',\\n'",
")",
"+",
"\\n",
";",
"' {'",
"rule",
".",
"declarations",
".",
"forEach",
"(",
"function",
"(",
"rules",
")",
"{",
"strCss",
"+=",
"commentOrDeclaration",
"(",
"rules",
")",
";",
"}",
")",
";",
"strCss",
"+=",
"'\\n}\\n\\n'",
";",
"}"
] | Process normal CSS rule | [
"Process",
"normal",
"CSS",
"rule"
] | fdd106764f19aee522ca3eb2a86217d6462541a4 | https://github.com/konitter/gulp-combine-media-queries/blob/fdd106764f19aee522ca3eb2a86217d6462541a4/index.js#L57-L65 | train |
|
konitter/gulp-combine-media-queries | index.js | function(rule) {
var strCss = '';
if (rule.type === 'rule') {
strCss += processRule(rule);
} else if (rule.type === 'comment') {
strCss += processComment(rule) + '\n\n';
}
return strCss;
} | javascript | function(rule) {
var strCss = '';
if (rule.type === 'rule') {
strCss += processRule(rule);
} else if (rule.type === 'comment') {
strCss += processComment(rule) + '\n\n';
}
return strCss;
} | [
"function",
"(",
"rule",
")",
"{",
"var",
"strCss",
"=",
"''",
";",
"if",
"(",
"rule",
".",
"type",
"===",
"'rule'",
")",
"{",
"strCss",
"+=",
"processRule",
"(",
"rule",
")",
";",
"}",
"else",
"if",
"(",
"rule",
".",
"type",
"===",
"'comment'",
")",
"{",
"strCss",
"+=",
"processComment",
"(",
"rule",
")",
"+",
"'\\n\\n'",
";",
"}",
"\\n",
"}"
] | Check rule type | [
"Check",
"rule",
"type"
] | fdd106764f19aee522ca3eb2a86217d6462541a4 | https://github.com/konitter/gulp-combine-media-queries/blob/fdd106764f19aee522ca3eb2a86217d6462541a4/index.js#L68-L76 | train |
|
konitter/gulp-combine-media-queries | index.js | function(frame) {
var strCss = '';
if (frame.type === 'keyframe') {
strCss += frame.values.join(',') + ' {';
frame.declarations.forEach(function(declaration) {
strCss += commentOrDeclaration(declaration);
});
strCss += '\n}\n\n';
} else if (frame.type === 'comment') {
strCss += processComment(frame) + '\n\n';
}
return strCss;
} | javascript | function(frame) {
var strCss = '';
if (frame.type === 'keyframe') {
strCss += frame.values.join(',') + ' {';
frame.declarations.forEach(function(declaration) {
strCss += commentOrDeclaration(declaration);
});
strCss += '\n}\n\n';
} else if (frame.type === 'comment') {
strCss += processComment(frame) + '\n\n';
}
return strCss;
} | [
"function",
"(",
"frame",
")",
"{",
"var",
"strCss",
"=",
"''",
";",
"if",
"(",
"frame",
".",
"type",
"===",
"'keyframe'",
")",
"{",
"strCss",
"+=",
"frame",
".",
"values",
".",
"join",
"(",
"','",
")",
"+",
"' {'",
";",
"frame",
".",
"declarations",
".",
"forEach",
"(",
"function",
"(",
"declaration",
")",
"{",
"strCss",
"+=",
"commentOrDeclaration",
"(",
"declaration",
")",
";",
"}",
")",
";",
"strCss",
"+=",
"'\\n}\\n\\n'",
";",
"}",
"else",
"\\n",
"\\n",
"}"
] | Check keyframe type | [
"Check",
"keyframe",
"type"
] | fdd106764f19aee522ca3eb2a86217d6462541a4 | https://github.com/konitter/gulp-combine-media-queries/blob/fdd106764f19aee522ca3eb2a86217d6462541a4/index.js#L79-L91 | train |
|
konitter/gulp-combine-media-queries | index.js | function(media) {
var strCss = '';
strCss += '@media ' + media.rule + ' {\n\n';
media.rules.forEach(function(rule) {
strCss += commentOrRule(rule);
});
strCss += '}\n\n';
log(' @media ' + media.rule);
return strCss;
} | javascript | function(media) {
var strCss = '';
strCss += '@media ' + media.rule + ' {\n\n';
media.rules.forEach(function(rule) {
strCss += commentOrRule(rule);
});
strCss += '}\n\n';
log(' @media ' + media.rule);
return strCss;
} | [
"function",
"(",
"media",
")",
"{",
"var",
"strCss",
"=",
"''",
";",
"strCss",
"+=",
"'@media '",
"+",
"media",
".",
"rule",
"+",
"' {\\n\\n'",
";",
"\\n",
"\\n",
"media",
".",
"rules",
".",
"forEach",
"(",
"function",
"(",
"rule",
")",
"{",
"strCss",
"+=",
"commentOrRule",
"(",
"rule",
")",
";",
"}",
")",
";",
"strCss",
"+=",
"'}\\n\\n'",
";",
"}"
] | Process media queries | [
"Process",
"media",
"queries"
] | fdd106764f19aee522ca3eb2a86217d6462541a4 | https://github.com/konitter/gulp-combine-media-queries/blob/fdd106764f19aee522ca3eb2a86217d6462541a4/index.js#L94-L104 | train |
|
konitter/gulp-combine-media-queries | index.js | function(a, b, isMax) {
var sortValA = a.sortVal,
sortValB = b.sortVal;
isMax = typeof isMax !== 'undefined' ? isMax : false;
// consider print for sorting if sortVals are equal
if (sortValA === sortValB) {
if (a.rule.match(/print/)) {
// a contains print and should be sorted after b
return 1;
}
if (b.rule.match(/print/)) {
// b contains print and should be sorted after a
return -1;
}
}
// return descending sort order for max-(width|height) media queries
if (isMax) {
return sortValB - sortValA;
}
// return ascending sort order
return sortValA - sortValB;
} | javascript | function(a, b, isMax) {
var sortValA = a.sortVal,
sortValB = b.sortVal;
isMax = typeof isMax !== 'undefined' ? isMax : false;
// consider print for sorting if sortVals are equal
if (sortValA === sortValB) {
if (a.rule.match(/print/)) {
// a contains print and should be sorted after b
return 1;
}
if (b.rule.match(/print/)) {
// b contains print and should be sorted after a
return -1;
}
}
// return descending sort order for max-(width|height) media queries
if (isMax) {
return sortValB - sortValA;
}
// return ascending sort order
return sortValA - sortValB;
} | [
"function",
"(",
"a",
",",
"b",
",",
"isMax",
")",
"{",
"var",
"sortValA",
"=",
"a",
".",
"sortVal",
",",
"sortValB",
"=",
"b",
".",
"sortVal",
";",
"isMax",
"=",
"typeof",
"isMax",
"!==",
"'undefined'",
"?",
"isMax",
":",
"false",
";",
"if",
"(",
"sortValA",
"===",
"sortValB",
")",
"{",
"if",
"(",
"a",
".",
"rule",
".",
"match",
"(",
"/",
"print",
"/",
")",
")",
"{",
"return",
"1",
";",
"}",
"if",
"(",
"b",
".",
"rule",
".",
"match",
"(",
"/",
"print",
"/",
")",
")",
"{",
"return",
"-",
"1",
";",
"}",
"}",
"if",
"(",
"isMax",
")",
"{",
"return",
"sortValB",
"-",
"sortValA",
";",
"}",
"return",
"sortValA",
"-",
"sortValB",
";",
"}"
] | Function to determine sort order | [
"Function",
"to",
"determine",
"sort",
"order"
] | fdd106764f19aee522ca3eb2a86217d6462541a4 | https://github.com/konitter/gulp-combine-media-queries/blob/fdd106764f19aee522ca3eb2a86217d6462541a4/index.js#L230-L254 | train |
|
konitter/gulp-combine-media-queries | index.js | function(media) {
if (options.use_external) {
media.forEach(function(item) {
strMediaStyles += processMedia(item);
});
} else {
media.forEach(function(item) {
strStyles += processMedia(item);
});
}
} | javascript | function(media) {
if (options.use_external) {
media.forEach(function(item) {
strMediaStyles += processMedia(item);
});
} else {
media.forEach(function(item) {
strStyles += processMedia(item);
});
}
} | [
"function",
"(",
"media",
")",
"{",
"if",
"(",
"options",
".",
"use_external",
")",
"{",
"media",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"strMediaStyles",
"+=",
"processMedia",
"(",
"item",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"media",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"strStyles",
"+=",
"processMedia",
"(",
"item",
")",
";",
"}",
")",
";",
"}",
"}"
] | Function to output media queries | [
"Function",
"to",
"output",
"media",
"queries"
] | fdd106764f19aee522ca3eb2a86217d6462541a4 | https://github.com/konitter/gulp-combine-media-queries/blob/fdd106764f19aee522ca3eb2a86217d6462541a4/index.js#L296-L307 | train |
|
segmentio/utm-params | lib/index.js | strict | function strict(query) {
return foldl(function(acc, val, key) {
if (has.call(allowedKeys, key)) acc[key] = val;
return acc;
}, {}, utm(query));
} | javascript | function strict(query) {
return foldl(function(acc, val, key) {
if (has.call(allowedKeys, key)) acc[key] = val;
return acc;
}, {}, utm(query));
} | [
"function",
"strict",
"(",
"query",
")",
"{",
"return",
"foldl",
"(",
"function",
"(",
"acc",
",",
"val",
",",
"key",
")",
"{",
"if",
"(",
"has",
".",
"call",
"(",
"allowedKeys",
",",
"key",
")",
")",
"acc",
"[",
"key",
"]",
"=",
"val",
";",
"return",
"acc",
";",
"}",
",",
"{",
"}",
",",
"utm",
"(",
"query",
")",
")",
";",
"}"
] | Get strict utm params - from the given `querystring`
@param {String} query
@return {Object}
@api private | [
"Get",
"strict",
"utm",
"params",
"-",
"from",
"the",
"given",
"querystring"
] | 3cfebf8a57c5df7ed9f8b98f389b35096f7881fb | https://github.com/segmentio/utm-params/blob/3cfebf8a57c5df7ed9f8b98f389b35096f7881fb/lib/index.js#L65-L70 | train |
arabold/serverless-sentry-lib | src/index.js | installTimers | function installTimers(pluginConfig, lambdaContext) {
const timeRemaining = lambdaContext.getRemainingTimeInMillis();
const memoryLimit = lambdaContext.memoryLimitInMB;
function timeoutWarningFunc(cb) {
const Raven = pluginConfig.ravenClient;
ravenInstalled && Raven.captureMessage("Function Execution Time Warning", {
level: "warning",
extra: {
TimeRemainingInMsec: lambdaContext.getRemainingTimeInMillis()
}
}, cb);
}
function timeoutErrorFunc(cb) {
const Raven = pluginConfig.ravenClient;
ravenInstalled && Raven.captureMessage("Function Timed Out", {
level: "error",
extra: {
TimeRemainingInMsec: lambdaContext.getRemainingTimeInMillis()
}
}, cb);
}
function memoryWatchFunc(cb) {
const used = process.memoryUsage().rss / 1048576;
const p = (used / memoryLimit);
if (p >= 0.75) {
const Raven = pluginConfig.ravenClient;
ravenInstalled && Raven.captureMessage("Low Memory Warning", {
level: "warning",
extra: {
MemoryLimitInMB: memoryLimit,
MemoryUsedInMB: Math.floor(used)
}
}, cb);
if (memoryWatch) {
clearTimeout(memoryWatch);
memoryWatch = null;
}
}
else {
memoryWatch = setTimeout(memoryWatchFunc, 500);
}
}
if (pluginConfig.captureTimeoutWarnings) {
// We schedule the warning at half the maximum execution time and
// the error a few milliseconds before the actual timeout happens.
timeoutWarning = setTimeout(timeoutWarningFunc, timeRemaining / 2);
timeoutError = setTimeout(timeoutErrorFunc, Math.max(timeRemaining - 500, 0));
}
if (pluginConfig.captureMemoryWarnings) {
// Schedule memory watch dog interval. Note that we're not using
// setInterval() here as we don't want invokes to be skipped.
memoryWatch = setTimeout(memoryWatchFunc, 500);
}
} | javascript | function installTimers(pluginConfig, lambdaContext) {
const timeRemaining = lambdaContext.getRemainingTimeInMillis();
const memoryLimit = lambdaContext.memoryLimitInMB;
function timeoutWarningFunc(cb) {
const Raven = pluginConfig.ravenClient;
ravenInstalled && Raven.captureMessage("Function Execution Time Warning", {
level: "warning",
extra: {
TimeRemainingInMsec: lambdaContext.getRemainingTimeInMillis()
}
}, cb);
}
function timeoutErrorFunc(cb) {
const Raven = pluginConfig.ravenClient;
ravenInstalled && Raven.captureMessage("Function Timed Out", {
level: "error",
extra: {
TimeRemainingInMsec: lambdaContext.getRemainingTimeInMillis()
}
}, cb);
}
function memoryWatchFunc(cb) {
const used = process.memoryUsage().rss / 1048576;
const p = (used / memoryLimit);
if (p >= 0.75) {
const Raven = pluginConfig.ravenClient;
ravenInstalled && Raven.captureMessage("Low Memory Warning", {
level: "warning",
extra: {
MemoryLimitInMB: memoryLimit,
MemoryUsedInMB: Math.floor(used)
}
}, cb);
if (memoryWatch) {
clearTimeout(memoryWatch);
memoryWatch = null;
}
}
else {
memoryWatch = setTimeout(memoryWatchFunc, 500);
}
}
if (pluginConfig.captureTimeoutWarnings) {
// We schedule the warning at half the maximum execution time and
// the error a few milliseconds before the actual timeout happens.
timeoutWarning = setTimeout(timeoutWarningFunc, timeRemaining / 2);
timeoutError = setTimeout(timeoutErrorFunc, Math.max(timeRemaining - 500, 0));
}
if (pluginConfig.captureMemoryWarnings) {
// Schedule memory watch dog interval. Note that we're not using
// setInterval() here as we don't want invokes to be skipped.
memoryWatch = setTimeout(memoryWatchFunc, 500);
}
} | [
"function",
"installTimers",
"(",
"pluginConfig",
",",
"lambdaContext",
")",
"{",
"const",
"timeRemaining",
"=",
"lambdaContext",
".",
"getRemainingTimeInMillis",
"(",
")",
";",
"const",
"memoryLimit",
"=",
"lambdaContext",
".",
"memoryLimitInMB",
";",
"function",
"timeoutWarningFunc",
"(",
"cb",
")",
"{",
"const",
"Raven",
"=",
"pluginConfig",
".",
"ravenClient",
";",
"ravenInstalled",
"&&",
"Raven",
".",
"captureMessage",
"(",
"\"Function Execution Time Warning\"",
",",
"{",
"level",
":",
"\"warning\"",
",",
"extra",
":",
"{",
"TimeRemainingInMsec",
":",
"lambdaContext",
".",
"getRemainingTimeInMillis",
"(",
")",
"}",
"}",
",",
"cb",
")",
";",
"}",
"function",
"timeoutErrorFunc",
"(",
"cb",
")",
"{",
"const",
"Raven",
"=",
"pluginConfig",
".",
"ravenClient",
";",
"ravenInstalled",
"&&",
"Raven",
".",
"captureMessage",
"(",
"\"Function Timed Out\"",
",",
"{",
"level",
":",
"\"error\"",
",",
"extra",
":",
"{",
"TimeRemainingInMsec",
":",
"lambdaContext",
".",
"getRemainingTimeInMillis",
"(",
")",
"}",
"}",
",",
"cb",
")",
";",
"}",
"function",
"memoryWatchFunc",
"(",
"cb",
")",
"{",
"const",
"used",
"=",
"process",
".",
"memoryUsage",
"(",
")",
".",
"rss",
"/",
"1048576",
";",
"const",
"p",
"=",
"(",
"used",
"/",
"memoryLimit",
")",
";",
"if",
"(",
"p",
">=",
"0.75",
")",
"{",
"const",
"Raven",
"=",
"pluginConfig",
".",
"ravenClient",
";",
"ravenInstalled",
"&&",
"Raven",
".",
"captureMessage",
"(",
"\"Low Memory Warning\"",
",",
"{",
"level",
":",
"\"warning\"",
",",
"extra",
":",
"{",
"MemoryLimitInMB",
":",
"memoryLimit",
",",
"MemoryUsedInMB",
":",
"Math",
".",
"floor",
"(",
"used",
")",
"}",
"}",
",",
"cb",
")",
";",
"if",
"(",
"memoryWatch",
")",
"{",
"clearTimeout",
"(",
"memoryWatch",
")",
";",
"memoryWatch",
"=",
"null",
";",
"}",
"}",
"else",
"{",
"memoryWatch",
"=",
"setTimeout",
"(",
"memoryWatchFunc",
",",
"500",
")",
";",
"}",
"}",
"if",
"(",
"pluginConfig",
".",
"captureTimeoutWarnings",
")",
"{",
"timeoutWarning",
"=",
"setTimeout",
"(",
"timeoutWarningFunc",
",",
"timeRemaining",
"/",
"2",
")",
";",
"timeoutError",
"=",
"setTimeout",
"(",
"timeoutErrorFunc",
",",
"Math",
".",
"max",
"(",
"timeRemaining",
"-",
"500",
",",
"0",
")",
")",
";",
"}",
"if",
"(",
"pluginConfig",
".",
"captureMemoryWarnings",
")",
"{",
"memoryWatch",
"=",
"setTimeout",
"(",
"memoryWatchFunc",
",",
"500",
")",
";",
"}",
"}"
] | Insatll Watchdog timers
@param {Object} pluginConfig
@param {Object} lambdaContext | [
"Insatll",
"Watchdog",
"timers"
] | 479430b9d23127a24fff2c8f54ceeba54851ca80 | https://github.com/arabold/serverless-sentry-lib/blob/479430b9d23127a24fff2c8f54ceeba54851ca80/src/index.js#L135-L194 | train |
arabold/serverless-sentry-lib | src/index.js | clearTimers | function clearTimers() {
if (timeoutWarning) {
clearTimeout(timeoutWarning);
timeoutWarning = null;
}
if (timeoutError) {
clearTimeout(timeoutError);
timeoutError = null;
}
if (memoryWatch) {
clearTimeout(memoryWatch);
memoryWatch = null;
}
} | javascript | function clearTimers() {
if (timeoutWarning) {
clearTimeout(timeoutWarning);
timeoutWarning = null;
}
if (timeoutError) {
clearTimeout(timeoutError);
timeoutError = null;
}
if (memoryWatch) {
clearTimeout(memoryWatch);
memoryWatch = null;
}
} | [
"function",
"clearTimers",
"(",
")",
"{",
"if",
"(",
"timeoutWarning",
")",
"{",
"clearTimeout",
"(",
"timeoutWarning",
")",
";",
"timeoutWarning",
"=",
"null",
";",
"}",
"if",
"(",
"timeoutError",
")",
"{",
"clearTimeout",
"(",
"timeoutError",
")",
";",
"timeoutError",
"=",
"null",
";",
"}",
"if",
"(",
"memoryWatch",
")",
"{",
"clearTimeout",
"(",
"memoryWatch",
")",
";",
"memoryWatch",
"=",
"null",
";",
"}",
"}"
] | Stops and removes all timers | [
"Stops",
"and",
"removes",
"all",
"timers"
] | 479430b9d23127a24fff2c8f54ceeba54851ca80 | https://github.com/arabold/serverless-sentry-lib/blob/479430b9d23127a24fff2c8f54ceeba54851ca80/src/index.js#L199-L212 | train |
arabold/serverless-sentry-lib | src/index.js | wrapCallback | function wrapCallback(pluginConfig, cb) {
return (err, data) => {
// Stop watchdog timers
clearTimers();
// If an error was thrown we'll report it to Sentry
if (err && pluginConfig.captureErrors) {
const Raven = pluginConfig.ravenClient;
ravenInstalled && Raven.captureException(err, {}, () => {
cb(err, data);
});
}
else {
cb(err, data);
}
};
} | javascript | function wrapCallback(pluginConfig, cb) {
return (err, data) => {
// Stop watchdog timers
clearTimers();
// If an error was thrown we'll report it to Sentry
if (err && pluginConfig.captureErrors) {
const Raven = pluginConfig.ravenClient;
ravenInstalled && Raven.captureException(err, {}, () => {
cb(err, data);
});
}
else {
cb(err, data);
}
};
} | [
"function",
"wrapCallback",
"(",
"pluginConfig",
",",
"cb",
")",
"{",
"return",
"(",
"err",
",",
"data",
")",
"=>",
"{",
"clearTimers",
"(",
")",
";",
"if",
"(",
"err",
"&&",
"pluginConfig",
".",
"captureErrors",
")",
"{",
"const",
"Raven",
"=",
"pluginConfig",
".",
"ravenClient",
";",
"ravenInstalled",
"&&",
"Raven",
".",
"captureException",
"(",
"err",
",",
"{",
"}",
",",
"(",
")",
"=>",
"{",
"cb",
"(",
"err",
",",
"data",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"err",
",",
"data",
")",
";",
"}",
"}",
";",
"}"
] | Wraps a given callback function with error logging
@param {Object} pluginConfig
@param {Function} cb - Callback function to wrap
@returns {Function} | [
"Wraps",
"a",
"given",
"callback",
"function",
"with",
"error",
"logging"
] | 479430b9d23127a24fff2c8f54ceeba54851ca80 | https://github.com/arabold/serverless-sentry-lib/blob/479430b9d23127a24fff2c8f54ceeba54851ca80/src/index.js#L221-L237 | train |
benchpressjs/benchpressjs | lib/compiler/tokens.js | first | function first(arr, fn) {
const l = arr.length;
for (let i = 0; i < l; i += 1) {
const res = fn(arr[i], i);
if (res) {
return res;
}
}
return null;
} | javascript | function first(arr, fn) {
const l = arr.length;
for (let i = 0; i < l; i += 1) {
const res = fn(arr[i], i);
if (res) {
return res;
}
}
return null;
} | [
"function",
"first",
"(",
"arr",
",",
"fn",
")",
"{",
"const",
"l",
"=",
"arr",
".",
"length",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"l",
";",
"i",
"+=",
"1",
")",
"{",
"const",
"res",
"=",
"fn",
"(",
"arr",
"[",
"i",
"]",
",",
"i",
")",
";",
"if",
"(",
"res",
")",
"{",
"return",
"res",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Get the first truthy value returned by a mapper function
@param {any[]} arr
@param {function} fn | [
"Get",
"the",
"first",
"truthy",
"value",
"returned",
"by",
"a",
"mapper",
"function"
] | bf1f8b997da86867700c9a7dfc90bd33fb49270f | https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/compiler/tokens.js#L10-L20 | train |
benchpressjs/benchpressjs | lib/compiler/tokens.js | splitArgs | function splitArgs(str) {
const out = [];
let inString = false;
let currentArg = '';
for (let index = 0; index < str.length; index += 1) {
const c = str[index];
if (c === ',' && !inString) {
out.push(currentArg.trim());
currentArg = '';
} else if (currentArg.length === 0 && c === '"' && !inString) {
currentArg += c;
inString = true;
} else if (inString && c === '"' && str[index - 1] !== '\\') {
currentArg += c;
inString = false;
} else if (!(c === ' ' && currentArg.length === 0)) {
currentArg += c;
}
}
out.push(currentArg.trim());
return out;
} | javascript | function splitArgs(str) {
const out = [];
let inString = false;
let currentArg = '';
for (let index = 0; index < str.length; index += 1) {
const c = str[index];
if (c === ',' && !inString) {
out.push(currentArg.trim());
currentArg = '';
} else if (currentArg.length === 0 && c === '"' && !inString) {
currentArg += c;
inString = true;
} else if (inString && c === '"' && str[index - 1] !== '\\') {
currentArg += c;
inString = false;
} else if (!(c === ' ' && currentArg.length === 0)) {
currentArg += c;
}
}
out.push(currentArg.trim());
return out;
} | [
"function",
"splitArgs",
"(",
"str",
")",
"{",
"const",
"out",
"=",
"[",
"]",
";",
"let",
"inString",
"=",
"false",
";",
"let",
"currentArg",
"=",
"''",
";",
"for",
"(",
"let",
"index",
"=",
"0",
";",
"index",
"<",
"str",
".",
"length",
";",
"index",
"+=",
"1",
")",
"{",
"const",
"c",
"=",
"str",
"[",
"index",
"]",
";",
"if",
"(",
"c",
"===",
"','",
"&&",
"!",
"inString",
")",
"{",
"out",
".",
"push",
"(",
"currentArg",
".",
"trim",
"(",
")",
")",
";",
"currentArg",
"=",
"''",
";",
"}",
"else",
"if",
"(",
"currentArg",
".",
"length",
"===",
"0",
"&&",
"c",
"===",
"'\"'",
"&&",
"!",
"inString",
")",
"{",
"currentArg",
"+=",
"c",
";",
"inString",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"inString",
"&&",
"c",
"===",
"'\"'",
"&&",
"str",
"[",
"index",
"-",
"1",
"]",
"!==",
"'\\\\'",
")",
"\\\\",
"else",
"{",
"currentArg",
"+=",
"c",
";",
"inString",
"=",
"false",
";",
"}",
"}",
"if",
"(",
"!",
"(",
"c",
"===",
"' '",
"&&",
"currentArg",
".",
"length",
"===",
"0",
")",
")",
"{",
"currentArg",
"+=",
"c",
";",
"}",
"out",
".",
"push",
"(",
"currentArg",
".",
"trim",
"(",
")",
")",
";",
"}"
] | Split on commas, but ignore commas inside strings
@param {string} str | [
"Split",
"on",
"commas",
"but",
"ignore",
"commas",
"inside",
"strings"
] | bf1f8b997da86867700c9a7dfc90bd33fb49270f | https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/compiler/tokens.js#L40-L64 | train |
benchpressjs/benchpressjs | lib/benchpress.js | load | function load(template) {
return new Promise((resolve, reject) => {
const promise = Benchpress.loader(template, (templateFunction) => {
resolve(templateFunction);
});
if (promise && promise.then) {
promise.then(resolve, reject);
}
});
} | javascript | function load(template) {
return new Promise((resolve, reject) => {
const promise = Benchpress.loader(template, (templateFunction) => {
resolve(templateFunction);
});
if (promise && promise.then) {
promise.then(resolve, reject);
}
});
} | [
"function",
"load",
"(",
"template",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"promise",
"=",
"Benchpress",
".",
"loader",
"(",
"template",
",",
"(",
"templateFunction",
")",
"=>",
"{",
"resolve",
"(",
"templateFunction",
")",
";",
"}",
")",
";",
"if",
"(",
"promise",
"&&",
"promise",
".",
"then",
")",
"{",
"promise",
".",
"then",
"(",
"resolve",
",",
"reject",
")",
";",
"}",
"}",
")",
";",
"}"
] | necessary to support both promises and callbacks can remove when `parse` methods are removed | [
"necessary",
"to",
"support",
"both",
"promises",
"and",
"callbacks",
"can",
"remove",
"when",
"parse",
"methods",
"are",
"removed"
] | bf1f8b997da86867700c9a7dfc90bd33fb49270f | https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/benchpress.js#L90-L100 | train |
benchpressjs/benchpressjs | lib/benchpress.js | render | function render(template, data, block) {
data = Benchpress.addGlobals(data || {});
return Promise.try(() => {
Benchpress.cache[template] = Benchpress.cache[template] || load(template);
return Benchpress.cache[template];
}).then((templateFunction) => {
if (block) {
templateFunction = templateFunction.blocks && templateFunction.blocks[block];
}
if (!templateFunction) {
return '';
}
return runtime(Benchpress.helpers, data, templateFunction);
});
} | javascript | function render(template, data, block) {
data = Benchpress.addGlobals(data || {});
return Promise.try(() => {
Benchpress.cache[template] = Benchpress.cache[template] || load(template);
return Benchpress.cache[template];
}).then((templateFunction) => {
if (block) {
templateFunction = templateFunction.blocks && templateFunction.blocks[block];
}
if (!templateFunction) {
return '';
}
return runtime(Benchpress.helpers, data, templateFunction);
});
} | [
"function",
"render",
"(",
"template",
",",
"data",
",",
"block",
")",
"{",
"data",
"=",
"Benchpress",
".",
"addGlobals",
"(",
"data",
"||",
"{",
"}",
")",
";",
"return",
"Promise",
".",
"try",
"(",
"(",
")",
"=>",
"{",
"Benchpress",
".",
"cache",
"[",
"template",
"]",
"=",
"Benchpress",
".",
"cache",
"[",
"template",
"]",
"||",
"load",
"(",
"template",
")",
";",
"return",
"Benchpress",
".",
"cache",
"[",
"template",
"]",
";",
"}",
")",
".",
"then",
"(",
"(",
"templateFunction",
")",
"=>",
"{",
"if",
"(",
"block",
")",
"{",
"templateFunction",
"=",
"templateFunction",
".",
"blocks",
"&&",
"templateFunction",
".",
"blocks",
"[",
"block",
"]",
";",
"}",
"if",
"(",
"!",
"templateFunction",
")",
"{",
"return",
"''",
";",
"}",
"return",
"runtime",
"(",
"Benchpress",
".",
"helpers",
",",
"data",
",",
"templateFunction",
")",
";",
"}",
")",
";",
"}"
] | Fetch and run the given template
@param {string} template - Name of template to fetch
@param {Object} data - Data with which to run the template
@param {string} [block] - Parse only this block in the template
@returns {Promise<string>} - Rendered output | [
"Fetch",
"and",
"run",
"the",
"given",
"template"
] | bf1f8b997da86867700c9a7dfc90bd33fb49270f | https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/benchpress.js#L109-L125 | train |
benchpressjs/benchpressjs | lib/compile-render.js | compileRender | function compileRender(templateSource, data, block) {
const hash = md5(templateSource);
return Promise.try(() => {
const cached = compileRenderCache.get(hash);
if (cached) {
compileRenderCache.ttl(hash);
return cached;
}
const templateFunction = precompile(templateSource, {})
.then(code => evaluate(code));
compileRenderCache.set(hash, templateFunction);
return templateFunction;
}).then((templateFunction) => {
if (block) {
templateFunction = templateFunction.blocks && templateFunction.blocks[block];
}
if (!templateFunction) {
return '';
}
return runtime(Benchpress.helpers, data, templateFunction);
}).catch((err) => {
err.message = `Render failed for template ${templateSource.slice(0, 20)}:\n ${err.message}`;
err.stack = `Render failed for template ${templateSource.slice(0, 20)}:\n ${err.stack}`;
throw err;
});
} | javascript | function compileRender(templateSource, data, block) {
const hash = md5(templateSource);
return Promise.try(() => {
const cached = compileRenderCache.get(hash);
if (cached) {
compileRenderCache.ttl(hash);
return cached;
}
const templateFunction = precompile(templateSource, {})
.then(code => evaluate(code));
compileRenderCache.set(hash, templateFunction);
return templateFunction;
}).then((templateFunction) => {
if (block) {
templateFunction = templateFunction.blocks && templateFunction.blocks[block];
}
if (!templateFunction) {
return '';
}
return runtime(Benchpress.helpers, data, templateFunction);
}).catch((err) => {
err.message = `Render failed for template ${templateSource.slice(0, 20)}:\n ${err.message}`;
err.stack = `Render failed for template ${templateSource.slice(0, 20)}:\n ${err.stack}`;
throw err;
});
} | [
"function",
"compileRender",
"(",
"templateSource",
",",
"data",
",",
"block",
")",
"{",
"const",
"hash",
"=",
"md5",
"(",
"templateSource",
")",
";",
"return",
"Promise",
".",
"try",
"(",
"(",
")",
"=>",
"{",
"const",
"cached",
"=",
"compileRenderCache",
".",
"get",
"(",
"hash",
")",
";",
"if",
"(",
"cached",
")",
"{",
"compileRenderCache",
".",
"ttl",
"(",
"hash",
")",
";",
"return",
"cached",
";",
"}",
"const",
"templateFunction",
"=",
"precompile",
"(",
"templateSource",
",",
"{",
"}",
")",
".",
"then",
"(",
"code",
"=>",
"evaluate",
"(",
"code",
")",
")",
";",
"compileRenderCache",
".",
"set",
"(",
"hash",
",",
"templateFunction",
")",
";",
"return",
"templateFunction",
";",
"}",
")",
".",
"then",
"(",
"(",
"templateFunction",
")",
"=>",
"{",
"if",
"(",
"block",
")",
"{",
"templateFunction",
"=",
"templateFunction",
".",
"blocks",
"&&",
"templateFunction",
".",
"blocks",
"[",
"block",
"]",
";",
"}",
"if",
"(",
"!",
"templateFunction",
")",
"{",
"return",
"''",
";",
"}",
"return",
"runtime",
"(",
"Benchpress",
".",
"helpers",
",",
"data",
",",
"templateFunction",
")",
";",
"}",
")",
".",
"catch",
"(",
"(",
"err",
")",
"=>",
"{",
"err",
".",
"message",
"=",
"`",
"${",
"templateSource",
".",
"slice",
"(",
"0",
",",
"20",
")",
"}",
"\\n",
"${",
"err",
".",
"message",
"}",
"`",
";",
"err",
".",
"stack",
"=",
"`",
"${",
"templateSource",
".",
"slice",
"(",
"0",
",",
"20",
")",
"}",
"\\n",
"${",
"err",
".",
"stack",
"}",
"`",
";",
"throw",
"err",
";",
"}",
")",
";",
"}"
] | Compile a template and render it
Automatically caches template function based on hash of input template
@param {string} templateSource
@param {any} data
@param {string} [block]
@returns {Promise<string>} - rendered output | [
"Compile",
"a",
"template",
"and",
"render",
"it",
"Automatically",
"caches",
"template",
"function",
"based",
"on",
"hash",
"of",
"input",
"template"
] | bf1f8b997da86867700c9a7dfc90bd33fb49270f | https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/compile-render.js#L24-L54 | train |
benchpressjs/benchpressjs | lib/compiler/parser.js | expressionPaths | function expressionPaths(basePath, expression) {
const expr = Object.assign({}, expression);
if (expr.tokenType === 'SimpleExpression') {
if (expr.path === '@value') {
expr.path = basePath;
} else {
expr.path = paths.resolve(basePath, expr.path);
}
} else if (expr.tokenType === 'HelperExpression') {
expr.args = expr.args.map((arg) => {
if (arg.tokenType === 'StringLiteral') {
return arg;
}
return expressionPaths(basePath, arg);
});
}
return expr;
} | javascript | function expressionPaths(basePath, expression) {
const expr = Object.assign({}, expression);
if (expr.tokenType === 'SimpleExpression') {
if (expr.path === '@value') {
expr.path = basePath;
} else {
expr.path = paths.resolve(basePath, expr.path);
}
} else if (expr.tokenType === 'HelperExpression') {
expr.args = expr.args.map((arg) => {
if (arg.tokenType === 'StringLiteral') {
return arg;
}
return expressionPaths(basePath, arg);
});
}
return expr;
} | [
"function",
"expressionPaths",
"(",
"basePath",
",",
"expression",
")",
"{",
"const",
"expr",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"expression",
")",
";",
"if",
"(",
"expr",
".",
"tokenType",
"===",
"'SimpleExpression'",
")",
"{",
"if",
"(",
"expr",
".",
"path",
"===",
"'@value'",
")",
"{",
"expr",
".",
"path",
"=",
"basePath",
";",
"}",
"else",
"{",
"expr",
".",
"path",
"=",
"paths",
".",
"resolve",
"(",
"basePath",
",",
"expr",
".",
"path",
")",
";",
"}",
"}",
"else",
"if",
"(",
"expr",
".",
"tokenType",
"===",
"'HelperExpression'",
")",
"{",
"expr",
".",
"args",
"=",
"expr",
".",
"args",
".",
"map",
"(",
"(",
"arg",
")",
"=>",
"{",
"if",
"(",
"arg",
".",
"tokenType",
"===",
"'StringLiteral'",
")",
"{",
"return",
"arg",
";",
"}",
"return",
"expressionPaths",
"(",
"basePath",
",",
"arg",
")",
";",
"}",
")",
";",
"}",
"return",
"expr",
";",
"}"
] | Resolve all expression paths relative to the loop
@param {string} basePath
@param {object} expression | [
"Resolve",
"all",
"expression",
"paths",
"relative",
"to",
"the",
"loop"
] | bf1f8b997da86867700c9a7dfc90bd33fb49270f | https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/compiler/parser.js#L11-L30 | train |
benchpressjs/benchpressjs | lib/express.js | __express | function __express(filepath, data, next) {
data = Benchpress.addGlobals(data);
data._locals = null;
if (Benchpress.cache[filepath]) {
render(filepath, data, Benchpress.cache[filepath], next);
return;
}
fs.readFile(filepath, 'utf-8', (err, code) => {
if (err) {
next(err);
return;
}
let template;
try {
template = Benchpress.cache[filepath] = evaluate(code);
} catch (e) {
e.message = `Evaluate failed for template ${filepath}:\n ${e.message}`;
e.stack = `Evaluate failed for template ${filepath}:\n ${e.stack}`;
process.nextTick(next, e);
return;
}
render(filepath, data, template, next);
});
} | javascript | function __express(filepath, data, next) {
data = Benchpress.addGlobals(data);
data._locals = null;
if (Benchpress.cache[filepath]) {
render(filepath, data, Benchpress.cache[filepath], next);
return;
}
fs.readFile(filepath, 'utf-8', (err, code) => {
if (err) {
next(err);
return;
}
let template;
try {
template = Benchpress.cache[filepath] = evaluate(code);
} catch (e) {
e.message = `Evaluate failed for template ${filepath}:\n ${e.message}`;
e.stack = `Evaluate failed for template ${filepath}:\n ${e.stack}`;
process.nextTick(next, e);
return;
}
render(filepath, data, template, next);
});
} | [
"function",
"__express",
"(",
"filepath",
",",
"data",
",",
"next",
")",
"{",
"data",
"=",
"Benchpress",
".",
"addGlobals",
"(",
"data",
")",
";",
"data",
".",
"_locals",
"=",
"null",
";",
"if",
"(",
"Benchpress",
".",
"cache",
"[",
"filepath",
"]",
")",
"{",
"render",
"(",
"filepath",
",",
"data",
",",
"Benchpress",
".",
"cache",
"[",
"filepath",
"]",
",",
"next",
")",
";",
"return",
";",
"}",
"fs",
".",
"readFile",
"(",
"filepath",
",",
"'utf-8'",
",",
"(",
"err",
",",
"code",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"next",
"(",
"err",
")",
";",
"return",
";",
"}",
"let",
"template",
";",
"try",
"{",
"template",
"=",
"Benchpress",
".",
"cache",
"[",
"filepath",
"]",
"=",
"evaluate",
"(",
"code",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"e",
".",
"message",
"=",
"`",
"${",
"filepath",
"}",
"\\n",
"${",
"e",
".",
"message",
"}",
"`",
";",
"e",
".",
"stack",
"=",
"`",
"${",
"filepath",
"}",
"\\n",
"${",
"e",
".",
"stack",
"}",
"`",
";",
"process",
".",
"nextTick",
"(",
"next",
",",
"e",
")",
";",
"return",
";",
"}",
"render",
"(",
"filepath",
",",
"data",
",",
"template",
",",
"next",
")",
";",
"}",
")",
";",
"}"
] | Provide functionality to act as an express engine
@param {string} filepath - Compiled template file path
@param {Object} data - Data with which to parse the template
@param {function} next - (err, output) | [
"Provide",
"functionality",
"to",
"act",
"as",
"an",
"express",
"engine"
] | bf1f8b997da86867700c9a7dfc90bd33fb49270f | https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/express.js#L28-L56 | train |
benchpressjs/benchpressjs | lib/compiler/paths.js | resolve | function resolve(basePath, relPath) {
// already relative, so easy work
if (/^\.\.?\//.test(relPath)) {
return relative(basePath, relPath);
}
// otherwise we have to figure out if this is something like
// BEGIN a.b.c
// `- {a.b.c.d}
// or if it's an absolute path
const base = basePath.split('.');
const rel = relPath.split('.');
// find largest possible match in the base path
// decrease size of slice until a match is found
let found = false;
let relStart;
let baseLen;
for (let l = rel.length; l > 0 && !found; l -= 1) {
// slide through array from end to start until a match is found
for (let j = base.length - l; j >= 0 && !found; j -= 1) {
// check every element from (j) to (j + l) for equality
// if not equal, break right away
for (let i = 0; i < l; i += 1) {
if (base[j + i].replace(/\[\d+]$/, '') === rel[i]) {
found = true;
if (i === l - 1) {
relStart = l;
baseLen = j + l;
}
} else {
found = false;
break;
}
}
}
}
if (found) {
return base.slice(0, baseLen).concat(rel.slice(relStart)).join('.');
}
// assume its an absolute path
return relPath;
} | javascript | function resolve(basePath, relPath) {
// already relative, so easy work
if (/^\.\.?\//.test(relPath)) {
return relative(basePath, relPath);
}
// otherwise we have to figure out if this is something like
// BEGIN a.b.c
// `- {a.b.c.d}
// or if it's an absolute path
const base = basePath.split('.');
const rel = relPath.split('.');
// find largest possible match in the base path
// decrease size of slice until a match is found
let found = false;
let relStart;
let baseLen;
for (let l = rel.length; l > 0 && !found; l -= 1) {
// slide through array from end to start until a match is found
for (let j = base.length - l; j >= 0 && !found; j -= 1) {
// check every element from (j) to (j + l) for equality
// if not equal, break right away
for (let i = 0; i < l; i += 1) {
if (base[j + i].replace(/\[\d+]$/, '') === rel[i]) {
found = true;
if (i === l - 1) {
relStart = l;
baseLen = j + l;
}
} else {
found = false;
break;
}
}
}
}
if (found) {
return base.slice(0, baseLen).concat(rel.slice(relStart)).join('.');
}
// assume its an absolute path
return relPath;
} | [
"function",
"resolve",
"(",
"basePath",
",",
"relPath",
")",
"{",
"if",
"(",
"/",
"^\\.\\.?\\/",
"/",
".",
"test",
"(",
"relPath",
")",
")",
"{",
"return",
"relative",
"(",
"basePath",
",",
"relPath",
")",
";",
"}",
"const",
"base",
"=",
"basePath",
".",
"split",
"(",
"'.'",
")",
";",
"const",
"rel",
"=",
"relPath",
".",
"split",
"(",
"'.'",
")",
";",
"let",
"found",
"=",
"false",
";",
"let",
"relStart",
";",
"let",
"baseLen",
";",
"for",
"(",
"let",
"l",
"=",
"rel",
".",
"length",
";",
"l",
">",
"0",
"&&",
"!",
"found",
";",
"l",
"-=",
"1",
")",
"{",
"for",
"(",
"let",
"j",
"=",
"base",
".",
"length",
"-",
"l",
";",
"j",
">=",
"0",
"&&",
"!",
"found",
";",
"j",
"-=",
"1",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"l",
";",
"i",
"+=",
"1",
")",
"{",
"if",
"(",
"base",
"[",
"j",
"+",
"i",
"]",
".",
"replace",
"(",
"/",
"\\[\\d+]$",
"/",
",",
"''",
")",
"===",
"rel",
"[",
"i",
"]",
")",
"{",
"found",
"=",
"true",
";",
"if",
"(",
"i",
"===",
"l",
"-",
"1",
")",
"{",
"relStart",
"=",
"l",
";",
"baseLen",
"=",
"j",
"+",
"l",
";",
"}",
"}",
"else",
"{",
"found",
"=",
"false",
";",
"break",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"found",
")",
"{",
"return",
"base",
".",
"slice",
"(",
"0",
",",
"baseLen",
")",
".",
"concat",
"(",
"rel",
".",
"slice",
"(",
"relStart",
")",
")",
".",
"join",
"(",
"'.'",
")",
";",
"}",
"return",
"relPath",
";",
"}"
] | Resolve a full path from a base path and relative path
@param {string} basePath
@param {string} relPath | [
"Resolve",
"a",
"full",
"path",
"from",
"a",
"base",
"path",
"and",
"relative",
"path"
] | bf1f8b997da86867700c9a7dfc90bd33fb49270f | https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/compiler/paths.js#L24-L68 | train |
benchpressjs/benchpressjs | lib/runtime.js | guard | function guard(value) {
return value == null || (Array.isArray(value) && value.length === 0) ? '' : value;
} | javascript | function guard(value) {
return value == null || (Array.isArray(value) && value.length === 0) ? '' : value;
} | [
"function",
"guard",
"(",
"value",
")",
"{",
"return",
"value",
"==",
"null",
"||",
"(",
"Array",
".",
"isArray",
"(",
"value",
")",
"&&",
"value",
".",
"length",
"===",
"0",
")",
"?",
"''",
":",
"value",
";",
"}"
] | Convert null and undefined values to empty strings
@param {any} value
@returns {string} | [
"Convert",
"null",
"and",
"undefined",
"values",
"to",
"empty",
"strings"
] | bf1f8b997da86867700c9a7dfc90bd33fb49270f | https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/runtime.js#L8-L10 | train |
benchpressjs/benchpressjs | lib/runtime.js | iter | function iter(obj, each) {
if (!obj || typeof obj !== 'object') { return ''; }
let output = '';
const keys = Object.keys(obj);
const length = keys.length;
for (let i = 0; i < length; i += 1) {
const key = keys[i];
output += each(key, i, length, obj[key]);
}
return output;
} | javascript | function iter(obj, each) {
if (!obj || typeof obj !== 'object') { return ''; }
let output = '';
const keys = Object.keys(obj);
const length = keys.length;
for (let i = 0; i < length; i += 1) {
const key = keys[i];
output += each(key, i, length, obj[key]);
}
return output;
} | [
"function",
"iter",
"(",
"obj",
",",
"each",
")",
"{",
"if",
"(",
"!",
"obj",
"||",
"typeof",
"obj",
"!==",
"'object'",
")",
"{",
"return",
"''",
";",
"}",
"let",
"output",
"=",
"''",
";",
"const",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
";",
"const",
"length",
"=",
"keys",
".",
"length",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"const",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"output",
"+=",
"each",
"(",
"key",
",",
"i",
",",
"length",
",",
"obj",
"[",
"key",
"]",
")",
";",
"}",
"return",
"output",
";",
"}"
] | Iterate over an object or array
@param {string[]} obj - Iteratee object / array
@param {function} each - Callback to execute on each item
@return {string} | [
"Iterate",
"over",
"an",
"object",
"or",
"array"
] | bf1f8b997da86867700c9a7dfc90bd33fb49270f | https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/runtime.js#L18-L31 | train |
benchpressjs/benchpressjs | lib/runtime.js | helper | function helper(context, helpers, helperName, args) {
if (typeof helpers[helperName] !== 'function') {
return '';
}
try {
const out = helpers[helperName].apply(context, args);
return out || '';
} catch (e) {
return '';
}
} | javascript | function helper(context, helpers, helperName, args) {
if (typeof helpers[helperName] !== 'function') {
return '';
}
try {
const out = helpers[helperName].apply(context, args);
return out || '';
} catch (e) {
return '';
}
} | [
"function",
"helper",
"(",
"context",
",",
"helpers",
",",
"helperName",
",",
"args",
")",
"{",
"if",
"(",
"typeof",
"helpers",
"[",
"helperName",
"]",
"!==",
"'function'",
")",
"{",
"return",
"''",
";",
"}",
"try",
"{",
"const",
"out",
"=",
"helpers",
"[",
"helperName",
"]",
".",
"apply",
"(",
"context",
",",
"args",
")",
";",
"return",
"out",
"||",
"''",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"''",
";",
"}",
"}"
] | Execute a helper
@param {object} context - Base data object
@param {object} helpers - Map of helper functions
@param {string} helperName - Name of helper to execute
@param {any[]} args - Array of arguments
@returns {string} | [
"Execute",
"a",
"helper"
] | bf1f8b997da86867700c9a7dfc90bd33fb49270f | https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/runtime.js#L41-L51 | train |
benchpressjs/benchpressjs | lib/runtime.js | runtime | function runtime(helpers, context, templateFunction) {
return guard(templateFunction(helpers, context, guard, iter, helper)).toString();
} | javascript | function runtime(helpers, context, templateFunction) {
return guard(templateFunction(helpers, context, guard, iter, helper)).toString();
} | [
"function",
"runtime",
"(",
"helpers",
",",
"context",
",",
"templateFunction",
")",
"{",
"return",
"guard",
"(",
"templateFunction",
"(",
"helpers",
",",
"context",
",",
"guard",
",",
"iter",
",",
"helper",
")",
")",
".",
"toString",
"(",
")",
";",
"}"
] | Run a compiled template function
@param {object} helpers - Map of helper functions
@param {object} context - Base data object
@param {function} templateFunction - Compiled template function
@returns {string} | [
"Run",
"a",
"compiled",
"template",
"function"
] | bf1f8b997da86867700c9a7dfc90bd33fb49270f | https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/runtime.js#L60-L62 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.