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 |
---|---|---|---|---|---|---|---|---|---|---|---|
pkoretic/pdf417-generator | lib/bcmath.js | bcscale | function bcscale(scale) {
scale = parseInt(scale, 10);
if (isNaN(scale)) {
return false;
}
if (scale < 0) {
return false;
}
libbcmath.scale = scale;
return true;
} | javascript | function bcscale(scale) {
scale = parseInt(scale, 10);
if (isNaN(scale)) {
return false;
}
if (scale < 0) {
return false;
}
libbcmath.scale = scale;
return true;
} | [
"function",
"bcscale",
"(",
"scale",
")",
"{",
"scale",
"=",
"parseInt",
"(",
"scale",
",",
"10",
")",
";",
"if",
"(",
"isNaN",
"(",
"scale",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"scale",
"<",
"0",
")",
"{",
"return",
"false",
";",
"}",
"libbcmath",
".",
"scale",
"=",
"scale",
";",
"return",
"true",
";",
"}"
] | bcscale - Set default scale parameter for all bc math functions
@param int scale The scale factor (0 to infinate)
@return bool | [
"bcscale",
"-",
"Set",
"default",
"scale",
"parameter",
"for",
"all",
"bc",
"math",
"functions"
] | bcb0af69d822446aa4e195019a35d0967626a13b | https://github.com/pkoretic/pdf417-generator/blob/bcb0af69d822446aa4e195019a35d0967626a13b/lib/bcmath.js#L119-L129 | train |
pkoretic/pdf417-generator | lib/bcmath.js | bcdiv | function bcdiv(left_operand, right_operand, scale) {
var first, second, result;
if (typeof(scale) == 'undefined') {
scale = libbcmath.scale;
}
scale = ((scale < 0) ? 0 : scale);
// create objects
first = libbcmath.bc_init_num();
second = libbcmath.bc_init_num();
result = libbcmath.bc_init_num();
first = libbcmath.php_str2num(left_operand.toString());
second = libbcmath.php_str2num(right_operand.toString());
// normalize arguments to same scale.
if (first.n_scale > second.n_scale) second.setScale(first.n_scale);
if (second.n_scale > first.n_scale) first.setScale(second.n_scale);
result = libbcmath.bc_divide(first, second, scale);
if (result === -1) {
// error
throw new Error(11, "(BC) Division by zero");
}
if (result.n_scale > scale) {
result.n_scale = scale;
}
return result.toString();
} | javascript | function bcdiv(left_operand, right_operand, scale) {
var first, second, result;
if (typeof(scale) == 'undefined') {
scale = libbcmath.scale;
}
scale = ((scale < 0) ? 0 : scale);
// create objects
first = libbcmath.bc_init_num();
second = libbcmath.bc_init_num();
result = libbcmath.bc_init_num();
first = libbcmath.php_str2num(left_operand.toString());
second = libbcmath.php_str2num(right_operand.toString());
// normalize arguments to same scale.
if (first.n_scale > second.n_scale) second.setScale(first.n_scale);
if (second.n_scale > first.n_scale) first.setScale(second.n_scale);
result = libbcmath.bc_divide(first, second, scale);
if (result === -1) {
// error
throw new Error(11, "(BC) Division by zero");
}
if (result.n_scale > scale) {
result.n_scale = scale;
}
return result.toString();
} | [
"function",
"bcdiv",
"(",
"left_operand",
",",
"right_operand",
",",
"scale",
")",
"{",
"var",
"first",
",",
"second",
",",
"result",
";",
"if",
"(",
"typeof",
"(",
"scale",
")",
"==",
"'undefined'",
")",
"{",
"scale",
"=",
"libbcmath",
".",
"scale",
";",
"}",
"scale",
"=",
"(",
"(",
"scale",
"<",
"0",
")",
"?",
"0",
":",
"scale",
")",
";",
"first",
"=",
"libbcmath",
".",
"bc_init_num",
"(",
")",
";",
"second",
"=",
"libbcmath",
".",
"bc_init_num",
"(",
")",
";",
"result",
"=",
"libbcmath",
".",
"bc_init_num",
"(",
")",
";",
"first",
"=",
"libbcmath",
".",
"php_str2num",
"(",
"left_operand",
".",
"toString",
"(",
")",
")",
";",
"second",
"=",
"libbcmath",
".",
"php_str2num",
"(",
"right_operand",
".",
"toString",
"(",
")",
")",
";",
"if",
"(",
"first",
".",
"n_scale",
">",
"second",
".",
"n_scale",
")",
"second",
".",
"setScale",
"(",
"first",
".",
"n_scale",
")",
";",
"if",
"(",
"second",
".",
"n_scale",
">",
"first",
".",
"n_scale",
")",
"first",
".",
"setScale",
"(",
"second",
".",
"n_scale",
")",
";",
"result",
"=",
"libbcmath",
".",
"bc_divide",
"(",
"first",
",",
"second",
",",
"scale",
")",
";",
"if",
"(",
"result",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"11",
",",
"\"(BC) Division by zero\"",
")",
";",
"}",
"if",
"(",
"result",
".",
"n_scale",
">",
"scale",
")",
"{",
"result",
".",
"n_scale",
"=",
"scale",
";",
"}",
"return",
"result",
".",
"toString",
"(",
")",
";",
"}"
] | bcdiv - Divide two arbitrary precision numbers
@param string left_operand The left operand, as a string
@param string right_operand The right operand, as a string.
@param int [scale] The optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global scale for all functions by using bcscale()
@return string The result as a string | [
"bcdiv",
"-",
"Divide",
"two",
"arbitrary",
"precision",
"numbers"
] | bcb0af69d822446aa4e195019a35d0967626a13b | https://github.com/pkoretic/pdf417-generator/blob/bcb0af69d822446aa4e195019a35d0967626a13b/lib/bcmath.js#L140-L170 | train |
pkoretic/pdf417-generator | lib/bcmath.js | bcmul | function bcmul(left_operand, right_operand, scale) {
var first, second, result;
if (typeof(scale) == 'undefined') {
scale = libbcmath.scale;
}
scale = ((scale < 0) ? 0 : scale);
// create objects
first = libbcmath.bc_init_num();
second = libbcmath.bc_init_num();
result = libbcmath.bc_init_num();
first = libbcmath.php_str2num(left_operand.toString());
second = libbcmath.php_str2num(right_operand.toString());
// normalize arguments to same scale.
if (first.n_scale > second.n_scale) second.setScale(first.n_scale);
if (second.n_scale > first.n_scale) first.setScale(second.n_scale);
result = libbcmath.bc_multiply(first, second, scale);
if (result.n_scale > scale) {
result.n_scale = scale;
}
return result.toString();
} | javascript | function bcmul(left_operand, right_operand, scale) {
var first, second, result;
if (typeof(scale) == 'undefined') {
scale = libbcmath.scale;
}
scale = ((scale < 0) ? 0 : scale);
// create objects
first = libbcmath.bc_init_num();
second = libbcmath.bc_init_num();
result = libbcmath.bc_init_num();
first = libbcmath.php_str2num(left_operand.toString());
second = libbcmath.php_str2num(right_operand.toString());
// normalize arguments to same scale.
if (first.n_scale > second.n_scale) second.setScale(first.n_scale);
if (second.n_scale > first.n_scale) first.setScale(second.n_scale);
result = libbcmath.bc_multiply(first, second, scale);
if (result.n_scale > scale) {
result.n_scale = scale;
}
return result.toString();
} | [
"function",
"bcmul",
"(",
"left_operand",
",",
"right_operand",
",",
"scale",
")",
"{",
"var",
"first",
",",
"second",
",",
"result",
";",
"if",
"(",
"typeof",
"(",
"scale",
")",
"==",
"'undefined'",
")",
"{",
"scale",
"=",
"libbcmath",
".",
"scale",
";",
"}",
"scale",
"=",
"(",
"(",
"scale",
"<",
"0",
")",
"?",
"0",
":",
"scale",
")",
";",
"first",
"=",
"libbcmath",
".",
"bc_init_num",
"(",
")",
";",
"second",
"=",
"libbcmath",
".",
"bc_init_num",
"(",
")",
";",
"result",
"=",
"libbcmath",
".",
"bc_init_num",
"(",
")",
";",
"first",
"=",
"libbcmath",
".",
"php_str2num",
"(",
"left_operand",
".",
"toString",
"(",
")",
")",
";",
"second",
"=",
"libbcmath",
".",
"php_str2num",
"(",
"right_operand",
".",
"toString",
"(",
")",
")",
";",
"if",
"(",
"first",
".",
"n_scale",
">",
"second",
".",
"n_scale",
")",
"second",
".",
"setScale",
"(",
"first",
".",
"n_scale",
")",
";",
"if",
"(",
"second",
".",
"n_scale",
">",
"first",
".",
"n_scale",
")",
"first",
".",
"setScale",
"(",
"second",
".",
"n_scale",
")",
";",
"result",
"=",
"libbcmath",
".",
"bc_multiply",
"(",
"first",
",",
"second",
",",
"scale",
")",
";",
"if",
"(",
"result",
".",
"n_scale",
">",
"scale",
")",
"{",
"result",
".",
"n_scale",
"=",
"scale",
";",
"}",
"return",
"result",
".",
"toString",
"(",
")",
";",
"}"
] | bcdiv - Multiply two arbitrary precision number
@param string left_operand The left operand, as a string
@param string right_operand The right operand, as a string.
@param int [scale] The optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global scale for all functions by using bcscale()
@return string The result as a string | [
"bcdiv",
"-",
"Multiply",
"two",
"arbitrary",
"precision",
"number"
] | bcb0af69d822446aa4e195019a35d0967626a13b | https://github.com/pkoretic/pdf417-generator/blob/bcb0af69d822446aa4e195019a35d0967626a13b/lib/bcmath.js#L180-L207 | train |
hammerjs/simulator | index.js | ensureAnArray | function ensureAnArray (arr) {
if (Object.prototype.toString.call(arr) === '[object Array]') {
return arr;
} else if (arr === null || arr === void 0) {
return [];
} else {
return [arr];
}
} | javascript | function ensureAnArray (arr) {
if (Object.prototype.toString.call(arr) === '[object Array]') {
return arr;
} else if (arr === null || arr === void 0) {
return [];
} else {
return [arr];
}
} | [
"function",
"ensureAnArray",
"(",
"arr",
")",
"{",
"if",
"(",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"arr",
")",
"===",
"'[object Array]'",
")",
"{",
"return",
"arr",
";",
"}",
"else",
"if",
"(",
"arr",
"===",
"null",
"||",
"arr",
"===",
"void",
"0",
")",
"{",
"return",
"[",
"]",
";",
"}",
"else",
"{",
"return",
"[",
"arr",
"]",
";",
"}",
"}"
] | return unchanged if array passed, otherwise wrap in an array
@param {Object|Array|Null} arr any object
@return {Array} | [
"return",
"unchanged",
"if",
"array",
"passed",
"otherwise",
"wrap",
"in",
"an",
"array"
] | 31a05ccd9314247d4e404e18e310b9e3b4642056 | https://github.com/hammerjs/simulator/blob/31a05ccd9314247d4e404e18e310b9e3b4642056/index.js#L7-L15 | train |
hammerjs/simulator | index.js | renderTouches | function renderTouches(touches, element) {
touches.forEach(function(touch) {
var el = document.createElement('div');
el.style.width = '20px';
el.style.height = '20px';
el.style.background = 'red';
el.style.position = 'fixed';
el.style.top = touch.y +'px';
el.style.left = touch.x +'px';
el.style.borderRadius = '100%';
el.style.border = 'solid 2px #000';
el.style.zIndex = 6000;
element.appendChild(el);
setTimeout(function() {
el && el.parentNode && el.parentNode.removeChild(el);
el = null;
}, 100);
});
} | javascript | function renderTouches(touches, element) {
touches.forEach(function(touch) {
var el = document.createElement('div');
el.style.width = '20px';
el.style.height = '20px';
el.style.background = 'red';
el.style.position = 'fixed';
el.style.top = touch.y +'px';
el.style.left = touch.x +'px';
el.style.borderRadius = '100%';
el.style.border = 'solid 2px #000';
el.style.zIndex = 6000;
element.appendChild(el);
setTimeout(function() {
el && el.parentNode && el.parentNode.removeChild(el);
el = null;
}, 100);
});
} | [
"function",
"renderTouches",
"(",
"touches",
",",
"element",
")",
"{",
"touches",
".",
"forEach",
"(",
"function",
"(",
"touch",
")",
"{",
"var",
"el",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"el",
".",
"style",
".",
"width",
"=",
"'20px'",
";",
"el",
".",
"style",
".",
"height",
"=",
"'20px'",
";",
"el",
".",
"style",
".",
"background",
"=",
"'red'",
";",
"el",
".",
"style",
".",
"position",
"=",
"'fixed'",
";",
"el",
".",
"style",
".",
"top",
"=",
"touch",
".",
"y",
"+",
"'px'",
";",
"el",
".",
"style",
".",
"left",
"=",
"touch",
".",
"x",
"+",
"'px'",
";",
"el",
".",
"style",
".",
"borderRadius",
"=",
"'100%'",
";",
"el",
".",
"style",
".",
"border",
"=",
"'solid 2px #000'",
";",
"el",
".",
"style",
".",
"zIndex",
"=",
"6000",
";",
"element",
".",
"appendChild",
"(",
"el",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"el",
"&&",
"el",
".",
"parentNode",
"&&",
"el",
".",
"parentNode",
".",
"removeChild",
"(",
"el",
")",
";",
"el",
"=",
"null",
";",
"}",
",",
"100",
")",
";",
"}",
")",
";",
"}"
] | render the touches
@param touches
@param element
@param type | [
"render",
"the",
"touches"
] | 31a05ccd9314247d4e404e18e310b9e3b4642056 | https://github.com/hammerjs/simulator/blob/31a05ccd9314247d4e404e18e310b9e3b4642056/index.js#L226-L245 | train |
hammerjs/simulator | index.js | trigger | function trigger(touches, element, type) {
return Simulator.events[Simulator.type].trigger(touches, element, type);
} | javascript | function trigger(touches, element, type) {
return Simulator.events[Simulator.type].trigger(touches, element, type);
} | [
"function",
"trigger",
"(",
"touches",
",",
"element",
",",
"type",
")",
"{",
"return",
"Simulator",
".",
"events",
"[",
"Simulator",
".",
"type",
"]",
".",
"trigger",
"(",
"touches",
",",
"element",
",",
"type",
")",
";",
"}"
] | trigger the touch events
@param touches
@param element
@param type
@returns {*} | [
"trigger",
"the",
"touch",
"events"
] | 31a05ccd9314247d4e404e18e310b9e3b4642056 | https://github.com/hammerjs/simulator/blob/31a05ccd9314247d4e404e18e310b9e3b4642056/index.js#L254-L256 | train |
nathanboktae/mocha-phantomjs-core | mocha-phantomjs-core.js | function(msg, errno) {
if (output && config.file) {
output.close()
}
if (msg) {
stderr.writeLine(msg)
}
return phantom.exit(errno || 1)
} | javascript | function(msg, errno) {
if (output && config.file) {
output.close()
}
if (msg) {
stderr.writeLine(msg)
}
return phantom.exit(errno || 1)
} | [
"function",
"(",
"msg",
",",
"errno",
")",
"{",
"if",
"(",
"output",
"&&",
"config",
".",
"file",
")",
"{",
"output",
".",
"close",
"(",
")",
"}",
"if",
"(",
"msg",
")",
"{",
"stderr",
".",
"writeLine",
"(",
"msg",
")",
"}",
"return",
"phantom",
".",
"exit",
"(",
"errno",
"||",
"1",
")",
"}"
] | Create and configure the client page | [
"Create",
"and",
"configure",
"the",
"client",
"page"
] | 562125f41e4248a9ae19b91ed2e23a95f92262e9 | https://github.com/nathanboktae/mocha-phantomjs-core/blob/562125f41e4248a9ae19b91ed2e23a95f92262e9/mocha-phantomjs-core.js#L39-L47 | train |
|
pkoretic/pdf417-generator | lib/libbcmath.js | function() {
this.n_sign = null; // sign
this.n_len = null; /* (int) The number of digits before the decimal point. */
this.n_scale = null; /* (int) The number of digits after the decimal point. */
//this.n_refs = null; /* (int) The number of pointers to this number. */
//this.n_text = null; /* ?? Linked list for available list. */
this.n_value = null; /* array as value, where 1.23 = [1,2,3] */
this.toString = function() {
var r, tmp;
tmp=this.n_value.join('');
// add minus sign (if applicable) then add the integer part
r = ((this.n_sign == libbcmath.PLUS) ? '' : this.n_sign) + tmp.substr(0, this.n_len);
// if decimal places, add a . and the decimal part
if (this.n_scale > 0) {
r += '.' + tmp.substr(this.n_len, this.n_scale);
}
return r;
};
this.setScale = function(newScale) {
while (this.n_scale < newScale) {
this.n_value.push(0);
this.n_scale++;
}
while (this.n_scale > newScale) {
this.n_value.pop();
this.n_scale--;
}
return this;
}
} | javascript | function() {
this.n_sign = null; // sign
this.n_len = null; /* (int) The number of digits before the decimal point. */
this.n_scale = null; /* (int) The number of digits after the decimal point. */
//this.n_refs = null; /* (int) The number of pointers to this number. */
//this.n_text = null; /* ?? Linked list for available list. */
this.n_value = null; /* array as value, where 1.23 = [1,2,3] */
this.toString = function() {
var r, tmp;
tmp=this.n_value.join('');
// add minus sign (if applicable) then add the integer part
r = ((this.n_sign == libbcmath.PLUS) ? '' : this.n_sign) + tmp.substr(0, this.n_len);
// if decimal places, add a . and the decimal part
if (this.n_scale > 0) {
r += '.' + tmp.substr(this.n_len, this.n_scale);
}
return r;
};
this.setScale = function(newScale) {
while (this.n_scale < newScale) {
this.n_value.push(0);
this.n_scale++;
}
while (this.n_scale > newScale) {
this.n_value.pop();
this.n_scale--;
}
return this;
}
} | [
"function",
"(",
")",
"{",
"this",
".",
"n_sign",
"=",
"null",
";",
"this",
".",
"n_len",
"=",
"null",
";",
"this",
".",
"n_scale",
"=",
"null",
";",
"this",
".",
"n_value",
"=",
"null",
";",
"this",
".",
"toString",
"=",
"function",
"(",
")",
"{",
"var",
"r",
",",
"tmp",
";",
"tmp",
"=",
"this",
".",
"n_value",
".",
"join",
"(",
"''",
")",
";",
"r",
"=",
"(",
"(",
"this",
".",
"n_sign",
"==",
"libbcmath",
".",
"PLUS",
")",
"?",
"''",
":",
"this",
".",
"n_sign",
")",
"+",
"tmp",
".",
"substr",
"(",
"0",
",",
"this",
".",
"n_len",
")",
";",
"if",
"(",
"this",
".",
"n_scale",
">",
"0",
")",
"{",
"r",
"+=",
"'.'",
"+",
"tmp",
".",
"substr",
"(",
"this",
".",
"n_len",
",",
"this",
".",
"n_scale",
")",
";",
"}",
"return",
"r",
";",
"}",
";",
"this",
".",
"setScale",
"=",
"function",
"(",
"newScale",
")",
"{",
"while",
"(",
"this",
".",
"n_scale",
"<",
"newScale",
")",
"{",
"this",
".",
"n_value",
".",
"push",
"(",
"0",
")",
";",
"this",
".",
"n_scale",
"++",
";",
"}",
"while",
"(",
"this",
".",
"n_scale",
">",
"newScale",
")",
"{",
"this",
".",
"n_value",
".",
"pop",
"(",
")",
";",
"this",
".",
"n_scale",
"--",
";",
"}",
"return",
"this",
";",
"}",
"}"
] | default scale
Basic number structure | [
"default",
"scale",
"Basic",
"number",
"structure"
] | bcb0af69d822446aa4e195019a35d0967626a13b | https://github.com/pkoretic/pdf417-generator/blob/bcb0af69d822446aa4e195019a35d0967626a13b/lib/libbcmath.js#L31-L64 | train |
|
pkoretic/pdf417-generator | lib/libbcmath.js | function(str) {
var p;
p = str.indexOf('.');
if (p==-1) {
return libbcmath.bc_str2num(str, 0);
} else {
return libbcmath.bc_str2num(str, (str.length-p));
}
} | javascript | function(str) {
var p;
p = str.indexOf('.');
if (p==-1) {
return libbcmath.bc_str2num(str, 0);
} else {
return libbcmath.bc_str2num(str, (str.length-p));
}
} | [
"function",
"(",
"str",
")",
"{",
"var",
"p",
";",
"p",
"=",
"str",
".",
"indexOf",
"(",
"'.'",
")",
";",
"if",
"(",
"p",
"==",
"-",
"1",
")",
"{",
"return",
"libbcmath",
".",
"bc_str2num",
"(",
"str",
",",
"0",
")",
";",
"}",
"else",
"{",
"return",
"libbcmath",
".",
"bc_str2num",
"(",
"str",
",",
"(",
"str",
".",
"length",
"-",
"p",
")",
")",
";",
"}",
"}"
] | Convert to bc_num detecting scale | [
"Convert",
"to",
"bc_num",
"detecting",
"scale"
] | bcb0af69d822446aa4e195019a35d0967626a13b | https://github.com/pkoretic/pdf417-generator/blob/bcb0af69d822446aa4e195019a35d0967626a13b/lib/libbcmath.js#L105-L114 | train |
|
pkoretic/pdf417-generator | lib/libbcmath.js | function(r, ptr, chr, len) {
var i;
for (i=0;i<len;i++) {
r[ptr+i] = chr;
}
} | javascript | function(r, ptr, chr, len) {
var i;
for (i=0;i<len;i++) {
r[ptr+i] = chr;
}
} | [
"function",
"(",
"r",
",",
"ptr",
",",
"chr",
",",
"len",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"r",
"[",
"ptr",
"+",
"i",
"]",
"=",
"chr",
";",
"}",
"}"
] | replicate c function
@param array return (by reference)
@param string char to fill
@param int length to fill | [
"replicate",
"c",
"function"
] | bcb0af69d822446aa4e195019a35d0967626a13b | https://github.com/pkoretic/pdf417-generator/blob/bcb0af69d822446aa4e195019a35d0967626a13b/lib/libbcmath.js#L256-L261 | train |
|
pkoretic/pdf417-generator | lib/libbcmath.js | function(num) {
var count; // int
var nptr; // int
/* Quick check. */
//if (num == BCG(_zero_)) return TRUE;
/* Initialize */
count = num.n_len + num.n_scale;
nptr = 0; //num->n_value;
/* The check */
while ((count > 0) && (num.n_value[nptr++] === 0)) {
count--;
}
if (count !== 0) {
return false;
} else {
return true;
}
} | javascript | function(num) {
var count; // int
var nptr; // int
/* Quick check. */
//if (num == BCG(_zero_)) return TRUE;
/* Initialize */
count = num.n_len + num.n_scale;
nptr = 0; //num->n_value;
/* The check */
while ((count > 0) && (num.n_value[nptr++] === 0)) {
count--;
}
if (count !== 0) {
return false;
} else {
return true;
}
} | [
"function",
"(",
"num",
")",
"{",
"var",
"count",
";",
"var",
"nptr",
";",
"count",
"=",
"num",
".",
"n_len",
"+",
"num",
".",
"n_scale",
";",
"nptr",
"=",
"0",
";",
"while",
"(",
"(",
"count",
">",
"0",
")",
"&&",
"(",
"num",
".",
"n_value",
"[",
"nptr",
"++",
"]",
"===",
"0",
")",
")",
"{",
"count",
"--",
";",
"}",
"if",
"(",
"count",
"!==",
"0",
")",
"{",
"return",
"false",
";",
"}",
"else",
"{",
"return",
"true",
";",
"}",
"}"
] | Determine if the number specified is zero or not
@param bc_num num number to check
@return boolean true when zero, false when not zero. | [
"Determine",
"if",
"the",
"number",
"specified",
"is",
"zero",
"or",
"not"
] | bcb0af69d822446aa4e195019a35d0967626a13b | https://github.com/pkoretic/pdf417-generator/blob/bcb0af69d822446aa4e195019a35d0967626a13b/lib/libbcmath.js#L282-L303 | train |
|
Suor/pg-bricks | index.js | Conf | function Conf(config, _pg) {
if (typeof config === 'string') config = {connectionString: config};
this._config = config;
this._pg = _pg || pg;
this._pool = this._pg.Pool(config);
} | javascript | function Conf(config, _pg) {
if (typeof config === 'string') config = {connectionString: config};
this._config = config;
this._pg = _pg || pg;
this._pool = this._pg.Pool(config);
} | [
"function",
"Conf",
"(",
"config",
",",
"_pg",
")",
"{",
"if",
"(",
"typeof",
"config",
"===",
"'string'",
")",
"config",
"=",
"{",
"connectionString",
":",
"config",
"}",
";",
"this",
".",
"_config",
"=",
"config",
";",
"this",
".",
"_pg",
"=",
"_pg",
"||",
"pg",
";",
"this",
".",
"_pool",
"=",
"this",
".",
"_pg",
".",
"Pool",
"(",
"config",
")",
";",
"}"
] | A Conf object | [
"A",
"Conf",
"object"
] | 023538ab7ece9c0abba1102db9a437820d1173df | https://github.com/Suor/pg-bricks/blob/023538ab7ece9c0abba1102db9a437820d1173df/index.js#L154-L159 | train |
remy/twitterlib | twitterlib.js | function (tweets, search, includeHighlighted) {
var updated = [], tmp, i = 0;
if (typeof search == 'string') {
search = this.format(search);
}
for (i = 0; i < tweets.length; i++) {
if (this.match(tweets[i], search, includeHighlighted)) {
updated.push(tweets[i]);
}
}
return updated;
} | javascript | function (tweets, search, includeHighlighted) {
var updated = [], tmp, i = 0;
if (typeof search == 'string') {
search = this.format(search);
}
for (i = 0; i < tweets.length; i++) {
if (this.match(tweets[i], search, includeHighlighted)) {
updated.push(tweets[i]);
}
}
return updated;
} | [
"function",
"(",
"tweets",
",",
"search",
",",
"includeHighlighted",
")",
"{",
"var",
"updated",
"=",
"[",
"]",
",",
"tmp",
",",
"i",
"=",
"0",
";",
"if",
"(",
"typeof",
"search",
"==",
"'string'",
")",
"{",
"search",
"=",
"this",
".",
"format",
"(",
"search",
")",
";",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"tweets",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"this",
".",
"match",
"(",
"tweets",
"[",
"i",
"]",
",",
"search",
",",
"includeHighlighted",
")",
")",
"{",
"updated",
".",
"push",
"(",
"tweets",
"[",
"i",
"]",
")",
";",
"}",
"}",
"return",
"updated",
";",
"}"
] | tweets typeof Array | [
"tweets",
"typeof",
"Array"
] | ccfa3c43a44e175d258f9773a7f76196a107e527 | https://github.com/remy/twitterlib/blob/ccfa3c43a44e175d258f9773a7f76196a107e527/twitterlib.js#L350-L364 | train |
|
ahmed-wagdi/angular-joyride | js/joyride.js | function(){
angular.element(document.querySelector('body')).removeClass('jr_active jr_overlay_show');
removeJoyride();
scope.joyride.current = 0;
scope.joyride.transitionStep = true;
if (typeof scope.joyride.config.onFinish === "function") {
scope.joyride.config.onFinish();
}
if (document.querySelector(".jr_target")) {
angular.element(document.querySelector(".jr_target")).removeClass('jr_target');
}
} | javascript | function(){
angular.element(document.querySelector('body')).removeClass('jr_active jr_overlay_show');
removeJoyride();
scope.joyride.current = 0;
scope.joyride.transitionStep = true;
if (typeof scope.joyride.config.onFinish === "function") {
scope.joyride.config.onFinish();
}
if (document.querySelector(".jr_target")) {
angular.element(document.querySelector(".jr_target")).removeClass('jr_target');
}
} | [
"function",
"(",
")",
"{",
"angular",
".",
"element",
"(",
"document",
".",
"querySelector",
"(",
"'body'",
")",
")",
".",
"removeClass",
"(",
"'jr_active jr_overlay_show'",
")",
";",
"removeJoyride",
"(",
")",
";",
"scope",
".",
"joyride",
".",
"current",
"=",
"0",
";",
"scope",
".",
"joyride",
".",
"transitionStep",
"=",
"true",
";",
"if",
"(",
"typeof",
"scope",
".",
"joyride",
".",
"config",
".",
"onFinish",
"===",
"\"function\"",
")",
"{",
"scope",
".",
"joyride",
".",
"config",
".",
"onFinish",
"(",
")",
";",
"}",
"if",
"(",
"document",
".",
"querySelector",
"(",
"\".jr_target\"",
")",
")",
"{",
"angular",
".",
"element",
"(",
"document",
".",
"querySelector",
"(",
"\".jr_target\"",
")",
")",
".",
"removeClass",
"(",
"'jr_target'",
")",
";",
"}",
"}"
] | Reset variables after joyride ends | [
"Reset",
"variables",
"after",
"joyride",
"ends"
] | e2b48d7ceea9d3480ba7c619c7ac71fb5c1fc6f7 | https://github.com/ahmed-wagdi/angular-joyride/blob/e2b48d7ceea9d3480ba7c619c7ac71fb5c1fc6f7/js/joyride.js#L243-L254 | train |
|
dtoubelis/sails-cassandra | lib/adapter.js | function (connection, collections, cb) {
if (!connection.identity) return cb(Errors.IdentityMissing);
if (connections[connection.identity]) return cb(Errors.IdentityDuplicate);
// Store the connection
connections[connection.identity] = {
config: connection,
collections: collections,
client: null
};
// connect to database
new Connection(connection, function (err, client) {
if (err) return cb(err);
connections[connection.identity].client = client;
// Build up a registry of collections
Object.keys(collections).forEach(function (key) {
connections[connection.identity].collections[key] = new Collection(collections[key], client);
});
// execute callback
cb();
});
} | javascript | function (connection, collections, cb) {
if (!connection.identity) return cb(Errors.IdentityMissing);
if (connections[connection.identity]) return cb(Errors.IdentityDuplicate);
// Store the connection
connections[connection.identity] = {
config: connection,
collections: collections,
client: null
};
// connect to database
new Connection(connection, function (err, client) {
if (err) return cb(err);
connections[connection.identity].client = client;
// Build up a registry of collections
Object.keys(collections).forEach(function (key) {
connections[connection.identity].collections[key] = new Collection(collections[key], client);
});
// execute callback
cb();
});
} | [
"function",
"(",
"connection",
",",
"collections",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"connection",
".",
"identity",
")",
"return",
"cb",
"(",
"Errors",
".",
"IdentityMissing",
")",
";",
"if",
"(",
"connections",
"[",
"connection",
".",
"identity",
"]",
")",
"return",
"cb",
"(",
"Errors",
".",
"IdentityDuplicate",
")",
";",
"connections",
"[",
"connection",
".",
"identity",
"]",
"=",
"{",
"config",
":",
"connection",
",",
"collections",
":",
"collections",
",",
"client",
":",
"null",
"}",
";",
"new",
"Connection",
"(",
"connection",
",",
"function",
"(",
"err",
",",
"client",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"connections",
"[",
"connection",
".",
"identity",
"]",
".",
"client",
"=",
"client",
";",
"Object",
".",
"keys",
"(",
"collections",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"connections",
"[",
"connection",
".",
"identity",
"]",
".",
"collections",
"[",
"key",
"]",
"=",
"new",
"Collection",
"(",
"collections",
"[",
"key",
"]",
",",
"client",
")",
";",
"}",
")",
";",
"cb",
"(",
")",
";",
"}",
")",
";",
"}"
] | Register a connection and the collections assigned to it.
@param {Connection} connection
@param {Object} collections
@param {Function} cb | [
"Register",
"a",
"connection",
"and",
"the",
"collections",
"assigned",
"to",
"it",
"."
] | 78c3f5437f92cf0fdc20b7dac819e6c51b56331d | https://github.com/dtoubelis/sails-cassandra/blob/78c3f5437f92cf0fdc20b7dac819e6c51b56331d/lib/adapter.js#L57-L86 | train |
|
dtoubelis/sails-cassandra | lib/adapter.js | function(cb) {
var collection = connectionObject.collections[collectionName];
if (!collection) return cb(Errors.CollectionNotRegistered);
collection.dropTable(function(err) {
// ignore "table does not exist" error
if (err && err.code === 8704) return cb();
if (err) return cb(err);
cb();
});
} | javascript | function(cb) {
var collection = connectionObject.collections[collectionName];
if (!collection) return cb(Errors.CollectionNotRegistered);
collection.dropTable(function(err) {
// ignore "table does not exist" error
if (err && err.code === 8704) return cb();
if (err) return cb(err);
cb();
});
} | [
"function",
"(",
"cb",
")",
"{",
"var",
"collection",
"=",
"connectionObject",
".",
"collections",
"[",
"collectionName",
"]",
";",
"if",
"(",
"!",
"collection",
")",
"return",
"cb",
"(",
"Errors",
".",
"CollectionNotRegistered",
")",
";",
"collection",
".",
"dropTable",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"&&",
"err",
".",
"code",
"===",
"8704",
")",
"return",
"cb",
"(",
")",
";",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"cb",
"(",
")",
";",
"}",
")",
";",
"}"
] | drop the main table | [
"drop",
"the",
"main",
"table"
] | 78c3f5437f92cf0fdc20b7dac819e6c51b56331d | https://github.com/dtoubelis/sails-cassandra/blob/78c3f5437f92cf0fdc20b7dac819e6c51b56331d/lib/adapter.js#L197-L208 | train |
|
Magillem/generator-jhipster-pages | generators/app/files.js | addDropdownToMenu | function addDropdownToMenu(dropdownName, routerName, glyphiconName, enableTranslation, clientFramework) {
let navbarPath;
try {
if (clientFramework === 'angular1') {
navbarPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.html`;
jhipsterUtils.rewriteFile({
file: navbarPath,
needle: 'jhipster-needle-add-element-to-menu',
splicable: [ `<li ng-class="{active: vm.$state.includes('${dropdownName}')}" ng-switch-when="true" uib-dropdown class="dropdown pointer">
<a class="dropdown-toggle" uib-dropdown-toggle href="" id="${dropdownName}-menu">
<span>
<span class="glyphicon glyphicon-${glyphiconName}"></span>
<span class="hidden-sm" data-translate="global.menu.${dropdownName}.main">
${dropdownName}
</span>
<b class="caret"></b>
</span>
</a>
<ul class="dropdown-menu" uib-dropdown-menu>
<li ui-sref-active="active">
<a ui-sref="${routerName}" ng-click="vm.collapseNavbar()">
<span class="glyphicon glyphicon-${glyphiconName}"></span>
<span${enableTranslation ? ` data-translate="global.menu.${routerName}"` : ''}>${_.startCase(routerName)}</span>
</a>
</li>
<!-- jhipster-needle-add-element-to-${dropdownName} - JHipster will add elements to the ${dropdownName} here -->
</ul>
</li>`
]
}, this);
} else {
navbarPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
jhipsterUtils.rewriteFile({
file: navbarPath,
needle: 'jhipster-needle-add-element-to-menu',
splicable: [`<li *ngSwitchCase="true" ngbDropdown class="nav-item dropdown pointer">
<a class="nav-link dropdown-toggle" routerLinkActive="active" ngbDropdownToggle href="javascript:void(0);" id="${dropdownName}-menu">
<span>
<i class="fa fa-${glyphiconName}" aria-hidden="true"></i>
<span>${dropdownName}</span>
</span>
</a>
<ul class="dropdown-menu" ngbDropdownMenu>
<li>
<a class="dropdown-item" routerLink="${routerName}" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }" (click)="collapseNavbar()">
<i class="fa fa-${glyphiconName}" aria-hidden="true"></i>
<span${enableTranslation ? ` jhiTranslate="global.menu.${routerName}"` : ''}>${_.startCase(routerName)}</span>
</a>
</li>
<!-- jhipster-needle-add-element-to-${dropdownName} - JHipster will add elements to the ${dropdownName} here -->
</ul>
</li>`
]
}, this);
}
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + navbarPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + dropdownName} ${chalk.yellow('not added to menu.\n')}`);
this.debug('Error:', e);
this.log('Error:', e);
}
} | javascript | function addDropdownToMenu(dropdownName, routerName, glyphiconName, enableTranslation, clientFramework) {
let navbarPath;
try {
if (clientFramework === 'angular1') {
navbarPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.html`;
jhipsterUtils.rewriteFile({
file: navbarPath,
needle: 'jhipster-needle-add-element-to-menu',
splicable: [ `<li ng-class="{active: vm.$state.includes('${dropdownName}')}" ng-switch-when="true" uib-dropdown class="dropdown pointer">
<a class="dropdown-toggle" uib-dropdown-toggle href="" id="${dropdownName}-menu">
<span>
<span class="glyphicon glyphicon-${glyphiconName}"></span>
<span class="hidden-sm" data-translate="global.menu.${dropdownName}.main">
${dropdownName}
</span>
<b class="caret"></b>
</span>
</a>
<ul class="dropdown-menu" uib-dropdown-menu>
<li ui-sref-active="active">
<a ui-sref="${routerName}" ng-click="vm.collapseNavbar()">
<span class="glyphicon glyphicon-${glyphiconName}"></span>
<span${enableTranslation ? ` data-translate="global.menu.${routerName}"` : ''}>${_.startCase(routerName)}</span>
</a>
</li>
<!-- jhipster-needle-add-element-to-${dropdownName} - JHipster will add elements to the ${dropdownName} here -->
</ul>
</li>`
]
}, this);
} else {
navbarPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
jhipsterUtils.rewriteFile({
file: navbarPath,
needle: 'jhipster-needle-add-element-to-menu',
splicable: [`<li *ngSwitchCase="true" ngbDropdown class="nav-item dropdown pointer">
<a class="nav-link dropdown-toggle" routerLinkActive="active" ngbDropdownToggle href="javascript:void(0);" id="${dropdownName}-menu">
<span>
<i class="fa fa-${glyphiconName}" aria-hidden="true"></i>
<span>${dropdownName}</span>
</span>
</a>
<ul class="dropdown-menu" ngbDropdownMenu>
<li>
<a class="dropdown-item" routerLink="${routerName}" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }" (click)="collapseNavbar()">
<i class="fa fa-${glyphiconName}" aria-hidden="true"></i>
<span${enableTranslation ? ` jhiTranslate="global.menu.${routerName}"` : ''}>${_.startCase(routerName)}</span>
</a>
</li>
<!-- jhipster-needle-add-element-to-${dropdownName} - JHipster will add elements to the ${dropdownName} here -->
</ul>
</li>`
]
}, this);
}
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + navbarPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + dropdownName} ${chalk.yellow('not added to menu.\n')}`);
this.debug('Error:', e);
this.log('Error:', e);
}
} | [
"function",
"addDropdownToMenu",
"(",
"dropdownName",
",",
"routerName",
",",
"glyphiconName",
",",
"enableTranslation",
",",
"clientFramework",
")",
"{",
"let",
"navbarPath",
";",
"try",
"{",
"if",
"(",
"clientFramework",
"===",
"'angular1'",
")",
"{",
"navbarPath",
"=",
"`",
"${",
"CLIENT_MAIN_SRC_DIR",
"}",
"`",
";",
"jhipsterUtils",
".",
"rewriteFile",
"(",
"{",
"file",
":",
"navbarPath",
",",
"needle",
":",
"'jhipster-needle-add-element-to-menu'",
",",
"splicable",
":",
"[",
"`",
"${",
"dropdownName",
"}",
"${",
"dropdownName",
"}",
"${",
"glyphiconName",
"}",
"${",
"dropdownName",
"}",
"${",
"dropdownName",
"}",
"${",
"routerName",
"}",
"${",
"glyphiconName",
"}",
"${",
"enableTranslation",
"?",
"`",
"${",
"routerName",
"}",
"`",
":",
"''",
"}",
"${",
"_",
".",
"startCase",
"(",
"routerName",
")",
"}",
"${",
"dropdownName",
"}",
"${",
"dropdownName",
"}",
"`",
"]",
"}",
",",
"this",
")",
";",
"}",
"else",
"{",
"navbarPath",
"=",
"`",
"${",
"CLIENT_MAIN_SRC_DIR",
"}",
"`",
";",
"jhipsterUtils",
".",
"rewriteFile",
"(",
"{",
"file",
":",
"navbarPath",
",",
"needle",
":",
"'jhipster-needle-add-element-to-menu'",
",",
"splicable",
":",
"[",
"`",
"${",
"dropdownName",
"}",
"${",
"glyphiconName",
"}",
"${",
"dropdownName",
"}",
"${",
"routerName",
"}",
"${",
"glyphiconName",
"}",
"${",
"enableTranslation",
"?",
"`",
"${",
"routerName",
"}",
"`",
":",
"''",
"}",
"${",
"_",
".",
"startCase",
"(",
"routerName",
")",
"}",
"${",
"dropdownName",
"}",
"${",
"dropdownName",
"}",
"`",
"]",
"}",
",",
"this",
")",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"this",
".",
"log",
"(",
"`",
"${",
"chalk",
".",
"yellow",
"(",
"'\\nUnable to find '",
")",
"+",
"\\n",
"+",
"navbarPath",
"+",
"chalk",
".",
"yellow",
"(",
"' or missing required jhipster-needle. Reference to '",
")",
"}",
"dropdownName",
"`",
")",
";",
"${",
"chalk",
".",
"yellow",
"(",
"'not added to menu.\\n'",
")",
"}",
"\\n",
"}",
"}"
] | Add a new dropdown element, at the root of the menu.
@param {string} dropdownName - The name of the AngularJS router that is added to the menu.
@param {string} glyphiconName - The name of the Glyphicon (from Bootstrap) that will be displayed.
@param {boolean} enableTranslation - If translations are enabled or not
@param {string} clientFramework - The name of the client framework | [
"Add",
"a",
"new",
"dropdown",
"element",
"at",
"the",
"root",
"of",
"the",
"menu",
"."
] | 276dc08adc28626705fa251709def03de61a10ac | https://github.com/Magillem/generator-jhipster-pages/blob/276dc08adc28626705fa251709def03de61a10ac/generators/app/files.js#L463-L523 | train |
Magillem/generator-jhipster-pages | generators/app/files.js | addPageSetsModule | function addPageSetsModule(clientFramework) {
let appModulePath;
try {
if (clientFramework !== 'angular1') {
appModulePath = `${CLIENT_MAIN_SRC_DIR}app/app.module.ts`;
const fullPath = path.join(process.cwd(), appModulePath);
let args = {
file: appModulePath
};
args.haystack = this.fs.read(fullPath);
args.needle = `import { ${this.angularXAppName}EntityModule } from './entities/entity.module';`;
args.splicable = [`import { ${this.angularXAppName}PageSetsModule } from './pages/page-sets.module';`]
args.haystack = jhipsterUtils.rewrite(args);
args.needle = `${this.angularXAppName}AccountModule,`;
args.splicable = [`${this.angularXAppName}PageSetsModule,`]
args.haystack = jhipsterUtils.rewrite(args);
this.fs.write(fullPath, args.haystack);
}
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + appModulePath + chalk.yellow('. Reference to PageSets module not added to App module.\n')}`);
this.log('Error:', e);
}
} | javascript | function addPageSetsModule(clientFramework) {
let appModulePath;
try {
if (clientFramework !== 'angular1') {
appModulePath = `${CLIENT_MAIN_SRC_DIR}app/app.module.ts`;
const fullPath = path.join(process.cwd(), appModulePath);
let args = {
file: appModulePath
};
args.haystack = this.fs.read(fullPath);
args.needle = `import { ${this.angularXAppName}EntityModule } from './entities/entity.module';`;
args.splicable = [`import { ${this.angularXAppName}PageSetsModule } from './pages/page-sets.module';`]
args.haystack = jhipsterUtils.rewrite(args);
args.needle = `${this.angularXAppName}AccountModule,`;
args.splicable = [`${this.angularXAppName}PageSetsModule,`]
args.haystack = jhipsterUtils.rewrite(args);
this.fs.write(fullPath, args.haystack);
}
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + appModulePath + chalk.yellow('. Reference to PageSets module not added to App module.\n')}`);
this.log('Error:', e);
}
} | [
"function",
"addPageSetsModule",
"(",
"clientFramework",
")",
"{",
"let",
"appModulePath",
";",
"try",
"{",
"if",
"(",
"clientFramework",
"!==",
"'angular1'",
")",
"{",
"appModulePath",
"=",
"`",
"${",
"CLIENT_MAIN_SRC_DIR",
"}",
"`",
";",
"const",
"fullPath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"appModulePath",
")",
";",
"let",
"args",
"=",
"{",
"file",
":",
"appModulePath",
"}",
";",
"args",
".",
"haystack",
"=",
"this",
".",
"fs",
".",
"read",
"(",
"fullPath",
")",
";",
"args",
".",
"needle",
"=",
"`",
"${",
"this",
".",
"angularXAppName",
"}",
"`",
";",
"args",
".",
"splicable",
"=",
"[",
"`",
"${",
"this",
".",
"angularXAppName",
"}",
"`",
"]",
"args",
".",
"haystack",
"=",
"jhipsterUtils",
".",
"rewrite",
"(",
"args",
")",
";",
"args",
".",
"needle",
"=",
"`",
"${",
"this",
".",
"angularXAppName",
"}",
"`",
";",
"args",
".",
"splicable",
"=",
"[",
"`",
"${",
"this",
".",
"angularXAppName",
"}",
"`",
"]",
"args",
".",
"haystack",
"=",
"jhipsterUtils",
".",
"rewrite",
"(",
"args",
")",
";",
"this",
".",
"fs",
".",
"write",
"(",
"fullPath",
",",
"args",
".",
"haystack",
")",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"this",
".",
"log",
"(",
"`",
"${",
"chalk",
".",
"yellow",
"(",
"'\\nUnable to find '",
")",
"+",
"\\n",
"+",
"appModulePath",
"}",
"`",
")",
";",
"chalk",
".",
"yellow",
"(",
"'. Reference to PageSets module not added to App module.\\n'",
")",
"}",
"}"
] | Add pageSets module to app module.
@param {string} clientFramework - The name of the client framework | [
"Add",
"pageSets",
"module",
"to",
"app",
"module",
"."
] | 276dc08adc28626705fa251709def03de61a10ac | https://github.com/Magillem/generator-jhipster-pages/blob/276dc08adc28626705fa251709def03de61a10ac/generators/app/files.js#L575-L603 | train |
senecajs/seneca-auth | lib/express-auth.js | trigger_service_login | function trigger_service_login (msg, respond) {
var seneca = this
if (!msg.user) {
return respond(null, {ok: false, why: 'no-user'})
}
var user_data = msg.user
var q = {}
if (user_data.identifier) {
q[msg.service + '_id'] = user_data.identifier
user_data[msg.service + '_id'] = user_data.identifier
}
else {
return respond(null, {ok: false, why: 'no-identifier'})
}
seneca.act("role: 'user', get: 'user'", q, function (err, data) {
if (err) return respond(null, {ok: false, why: 'no-identifier'})
if (!data.ok) return respond(null, {ok: false, why: data.why})
var user = data.user
if (!user) {
seneca.act("role:'user',cmd:'register'", user_data, function (err, out) {
if (err) {
return respond(null, {ok: false, why: err})
}
respond(null, out.user)
})
}
else {
seneca.act("role:'user',cmd:'update'", user_data, function (err, out) {
if (err) {
return respond(null, {ok: false, why: err})
}
respond(null, out.user)
})
}
})
} | javascript | function trigger_service_login (msg, respond) {
var seneca = this
if (!msg.user) {
return respond(null, {ok: false, why: 'no-user'})
}
var user_data = msg.user
var q = {}
if (user_data.identifier) {
q[msg.service + '_id'] = user_data.identifier
user_data[msg.service + '_id'] = user_data.identifier
}
else {
return respond(null, {ok: false, why: 'no-identifier'})
}
seneca.act("role: 'user', get: 'user'", q, function (err, data) {
if (err) return respond(null, {ok: false, why: 'no-identifier'})
if (!data.ok) return respond(null, {ok: false, why: data.why})
var user = data.user
if (!user) {
seneca.act("role:'user',cmd:'register'", user_data, function (err, out) {
if (err) {
return respond(null, {ok: false, why: err})
}
respond(null, out.user)
})
}
else {
seneca.act("role:'user',cmd:'update'", user_data, function (err, out) {
if (err) {
return respond(null, {ok: false, why: err})
}
respond(null, out.user)
})
}
})
} | [
"function",
"trigger_service_login",
"(",
"msg",
",",
"respond",
")",
"{",
"var",
"seneca",
"=",
"this",
"if",
"(",
"!",
"msg",
".",
"user",
")",
"{",
"return",
"respond",
"(",
"null",
",",
"{",
"ok",
":",
"false",
",",
"why",
":",
"'no-user'",
"}",
")",
"}",
"var",
"user_data",
"=",
"msg",
".",
"user",
"var",
"q",
"=",
"{",
"}",
"if",
"(",
"user_data",
".",
"identifier",
")",
"{",
"q",
"[",
"msg",
".",
"service",
"+",
"'_id'",
"]",
"=",
"user_data",
".",
"identifier",
"user_data",
"[",
"msg",
".",
"service",
"+",
"'_id'",
"]",
"=",
"user_data",
".",
"identifier",
"}",
"else",
"{",
"return",
"respond",
"(",
"null",
",",
"{",
"ok",
":",
"false",
",",
"why",
":",
"'no-identifier'",
"}",
")",
"}",
"seneca",
".",
"act",
"(",
"\"role: 'user', get: 'user'\"",
",",
"q",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"return",
"respond",
"(",
"null",
",",
"{",
"ok",
":",
"false",
",",
"why",
":",
"'no-identifier'",
"}",
")",
"if",
"(",
"!",
"data",
".",
"ok",
")",
"return",
"respond",
"(",
"null",
",",
"{",
"ok",
":",
"false",
",",
"why",
":",
"data",
".",
"why",
"}",
")",
"var",
"user",
"=",
"data",
".",
"user",
"if",
"(",
"!",
"user",
")",
"{",
"seneca",
".",
"act",
"(",
"\"role:'user',cmd:'register'\"",
",",
"user_data",
",",
"function",
"(",
"err",
",",
"out",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"respond",
"(",
"null",
",",
"{",
"ok",
":",
"false",
",",
"why",
":",
"err",
"}",
")",
"}",
"respond",
"(",
"null",
",",
"out",
".",
"user",
")",
"}",
")",
"}",
"else",
"{",
"seneca",
".",
"act",
"(",
"\"role:'user',cmd:'update'\"",
",",
"user_data",
",",
"function",
"(",
"err",
",",
"out",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"respond",
"(",
"null",
",",
"{",
"ok",
":",
"false",
",",
"why",
":",
"err",
"}",
")",
"}",
"respond",
"(",
"null",
",",
"out",
".",
"user",
")",
"}",
")",
"}",
"}",
")",
"}"
] | LOGOUT END default service login trigger | [
"LOGOUT",
"END",
"default",
"service",
"login",
"trigger"
] | 537716d2a07c9be6e3aa5ae6529929704c97338b | https://github.com/senecajs/seneca-auth/blob/537716d2a07c9be6e3aa5ae6529929704c97338b/lib/express-auth.js#L278-L320 | train |
JedWatson/react-component-gulp-tasks | index.js | readPackageJSON | function readPackageJSON () {
var pkg = JSON.parse(require('fs').readFileSync('./package.json'));
var dependencies = pkg.dependencies ? Object.keys(pkg.dependencies) : [];
var peerDependencies = pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : [];
return {
name: pkg.name,
deps: dependencies.concat(peerDependencies),
aliasify: pkg.aliasify
};
} | javascript | function readPackageJSON () {
var pkg = JSON.parse(require('fs').readFileSync('./package.json'));
var dependencies = pkg.dependencies ? Object.keys(pkg.dependencies) : [];
var peerDependencies = pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : [];
return {
name: pkg.name,
deps: dependencies.concat(peerDependencies),
aliasify: pkg.aliasify
};
} | [
"function",
"readPackageJSON",
"(",
")",
"{",
"var",
"pkg",
"=",
"JSON",
".",
"parse",
"(",
"require",
"(",
"'fs'",
")",
".",
"readFileSync",
"(",
"'./package.json'",
")",
")",
";",
"var",
"dependencies",
"=",
"pkg",
".",
"dependencies",
"?",
"Object",
".",
"keys",
"(",
"pkg",
".",
"dependencies",
")",
":",
"[",
"]",
";",
"var",
"peerDependencies",
"=",
"pkg",
".",
"peerDependencies",
"?",
"Object",
".",
"keys",
"(",
"pkg",
".",
"peerDependencies",
")",
":",
"[",
"]",
";",
"return",
"{",
"name",
":",
"pkg",
".",
"name",
",",
"deps",
":",
"dependencies",
".",
"concat",
"(",
"peerDependencies",
")",
",",
"aliasify",
":",
"pkg",
".",
"aliasify",
"}",
";",
"}"
] | Extract package.json metadata | [
"Extract",
"package",
".",
"json",
"metadata"
] | 8a6d636b72fcb10ecd9d633343193923d7447d8d | https://github.com/JedWatson/react-component-gulp-tasks/blob/8a6d636b72fcb10ecd9d633343193923d7447d8d/index.js#L6-L16 | train |
JedWatson/react-component-gulp-tasks | index.js | initTasks | function initTasks (gulp, config) {
var pkg = readPackageJSON();
var name = capitalize(camelCase(config.component.pkgName || pkg.name));
config = defaults(config, { aliasify: pkg.aliasify });
config.component = defaults(config.component, {
pkgName: pkg.name,
dependencies: pkg.deps,
name: name,
src: 'src',
lib: 'lib',
dist: 'dist',
file: (config.component.name || name) + '.js'
});
if (config.example) {
if (config.example === true) config.example = {};
defaults(config.example, {
src: 'example/src',
dist: 'example/dist',
files: ['index.html'],
scripts: ['example.js'],
less: ['example.less']
});
}
require('./tasks/bump')(gulp, config);
require('./tasks/dev')(gulp, config);
require('./tasks/dist')(gulp, config);
require('./tasks/release')(gulp, config);
var buildTasks = ['build:dist'];
var cleanTasks = ['clean:dist'];
if (config.component.lib) {
require('./tasks/lib')(gulp, config);
buildTasks.push('build:lib');
cleanTasks.push('clean:lib');
}
if (config.example) {
require('./tasks/examples')(gulp, config);
buildTasks.push('build:examples');
cleanTasks.push('clean:examples');
}
gulp.task('build', buildTasks);
gulp.task('clean', cleanTasks);
} | javascript | function initTasks (gulp, config) {
var pkg = readPackageJSON();
var name = capitalize(camelCase(config.component.pkgName || pkg.name));
config = defaults(config, { aliasify: pkg.aliasify });
config.component = defaults(config.component, {
pkgName: pkg.name,
dependencies: pkg.deps,
name: name,
src: 'src',
lib: 'lib',
dist: 'dist',
file: (config.component.name || name) + '.js'
});
if (config.example) {
if (config.example === true) config.example = {};
defaults(config.example, {
src: 'example/src',
dist: 'example/dist',
files: ['index.html'],
scripts: ['example.js'],
less: ['example.less']
});
}
require('./tasks/bump')(gulp, config);
require('./tasks/dev')(gulp, config);
require('./tasks/dist')(gulp, config);
require('./tasks/release')(gulp, config);
var buildTasks = ['build:dist'];
var cleanTasks = ['clean:dist'];
if (config.component.lib) {
require('./tasks/lib')(gulp, config);
buildTasks.push('build:lib');
cleanTasks.push('clean:lib');
}
if (config.example) {
require('./tasks/examples')(gulp, config);
buildTasks.push('build:examples');
cleanTasks.push('clean:examples');
}
gulp.task('build', buildTasks);
gulp.task('clean', cleanTasks);
} | [
"function",
"initTasks",
"(",
"gulp",
",",
"config",
")",
"{",
"var",
"pkg",
"=",
"readPackageJSON",
"(",
")",
";",
"var",
"name",
"=",
"capitalize",
"(",
"camelCase",
"(",
"config",
".",
"component",
".",
"pkgName",
"||",
"pkg",
".",
"name",
")",
")",
";",
"config",
"=",
"defaults",
"(",
"config",
",",
"{",
"aliasify",
":",
"pkg",
".",
"aliasify",
"}",
")",
";",
"config",
".",
"component",
"=",
"defaults",
"(",
"config",
".",
"component",
",",
"{",
"pkgName",
":",
"pkg",
".",
"name",
",",
"dependencies",
":",
"pkg",
".",
"deps",
",",
"name",
":",
"name",
",",
"src",
":",
"'src'",
",",
"lib",
":",
"'lib'",
",",
"dist",
":",
"'dist'",
",",
"file",
":",
"(",
"config",
".",
"component",
".",
"name",
"||",
"name",
")",
"+",
"'.js'",
"}",
")",
";",
"if",
"(",
"config",
".",
"example",
")",
"{",
"if",
"(",
"config",
".",
"example",
"===",
"true",
")",
"config",
".",
"example",
"=",
"{",
"}",
";",
"defaults",
"(",
"config",
".",
"example",
",",
"{",
"src",
":",
"'example/src'",
",",
"dist",
":",
"'example/dist'",
",",
"files",
":",
"[",
"'index.html'",
"]",
",",
"scripts",
":",
"[",
"'example.js'",
"]",
",",
"less",
":",
"[",
"'example.less'",
"]",
"}",
")",
";",
"}",
"require",
"(",
"'./tasks/bump'",
")",
"(",
"gulp",
",",
"config",
")",
";",
"require",
"(",
"'./tasks/dev'",
")",
"(",
"gulp",
",",
"config",
")",
";",
"require",
"(",
"'./tasks/dist'",
")",
"(",
"gulp",
",",
"config",
")",
";",
"require",
"(",
"'./tasks/release'",
")",
"(",
"gulp",
",",
"config",
")",
";",
"var",
"buildTasks",
"=",
"[",
"'build:dist'",
"]",
";",
"var",
"cleanTasks",
"=",
"[",
"'clean:dist'",
"]",
";",
"if",
"(",
"config",
".",
"component",
".",
"lib",
")",
"{",
"require",
"(",
"'./tasks/lib'",
")",
"(",
"gulp",
",",
"config",
")",
";",
"buildTasks",
".",
"push",
"(",
"'build:lib'",
")",
";",
"cleanTasks",
".",
"push",
"(",
"'clean:lib'",
")",
";",
"}",
"if",
"(",
"config",
".",
"example",
")",
"{",
"require",
"(",
"'./tasks/examples'",
")",
"(",
"gulp",
",",
"config",
")",
";",
"buildTasks",
".",
"push",
"(",
"'build:examples'",
")",
";",
"cleanTasks",
".",
"push",
"(",
"'clean:examples'",
")",
";",
"}",
"gulp",
".",
"task",
"(",
"'build'",
",",
"buildTasks",
")",
";",
"gulp",
".",
"task",
"(",
"'clean'",
",",
"cleanTasks",
")",
";",
"}"
] | This package exports a function that binds tasks to a gulp instance
based on the provided config. | [
"This",
"package",
"exports",
"a",
"function",
"that",
"binds",
"tasks",
"to",
"a",
"gulp",
"instance",
"based",
"on",
"the",
"provided",
"config",
"."
] | 8a6d636b72fcb10ecd9d633343193923d7447d8d | https://github.com/JedWatson/react-component-gulp-tasks/blob/8a6d636b72fcb10ecd9d633343193923d7447d8d/index.js#L22-L71 | train |
stdarg/tcp-port-used | index.js | makeOptionsObj | function makeOptionsObj(port, host, inUse, retryTimeMs, timeOutMs) {
var opts = {};
opts.port = port;
opts.host = host;
opts.inUse = inUse;
opts.retryTimeMs = retryTimeMs;
opts.timeOutMs = timeOutMs;
return opts;
} | javascript | function makeOptionsObj(port, host, inUse, retryTimeMs, timeOutMs) {
var opts = {};
opts.port = port;
opts.host = host;
opts.inUse = inUse;
opts.retryTimeMs = retryTimeMs;
opts.timeOutMs = timeOutMs;
return opts;
} | [
"function",
"makeOptionsObj",
"(",
"port",
",",
"host",
",",
"inUse",
",",
"retryTimeMs",
",",
"timeOutMs",
")",
"{",
"var",
"opts",
"=",
"{",
"}",
";",
"opts",
".",
"port",
"=",
"port",
";",
"opts",
".",
"host",
"=",
"host",
";",
"opts",
".",
"inUse",
"=",
"inUse",
";",
"opts",
".",
"retryTimeMs",
"=",
"retryTimeMs",
";",
"opts",
".",
"timeOutMs",
"=",
"timeOutMs",
";",
"return",
"opts",
";",
"}"
] | Creates an options object from all the possible arguments
@private
@param {Number} port a valid TCP port number
@param {String} host The DNS name or IP address.
@param {Boolean} status The desired in use status to wait for: false === not in use, true === in use
@param {Number} retryTimeMs the retry interval in milliseconds - defaultis is 200ms
@param {Number} timeOutMs the amount of time to wait until port is free default is 1000ms
@return {Object} An options object with all the above parameters as properties. | [
"Creates",
"an",
"options",
"object",
"from",
"all",
"the",
"possible",
"arguments"
] | 23356dede7d2bb198cc07f47215d763c225a96c8 | https://github.com/stdarg/tcp-port-used/blob/23356dede7d2bb198cc07f47215d763c225a96c8/index.js#L47-L55 | train |
senecajs/seneca-auth | lib/hapi-auth.js | cmd_logout | function cmd_logout (msg, respond) {
var req = msg.req$
// get token from request
req.seneca.act("role: 'auth', get: 'token'", {tokenkey: options.tokenkey}, function (err, clienttoken) {
if (err) {
return req.seneca.act('role: auth, do: respond', {err: err, action: 'logout', req: req}, respond)
}
if (!clienttoken) {
return req.seneca.act('role: auth, do: respond', {err: err, action: 'logout', req: req}, respond)
}
clienttoken = clienttoken.token
// delete token
req.seneca.act("role: 'auth', set: 'token'", {tokenkey: options.tokenkey}, function (err) {
if (err) {
return req.seneca.act('role: auth, do: respond', {err: err, action: 'logout', req: req}, respond)
}
req.seneca.act("role:'user',cmd:'logout'", {token: clienttoken}, function (err) {
if (err) {
req.seneca.log('error ', err)
}
req.cookieAuth.clear()
delete req.seneca.user
delete req.seneca.login
return req.seneca.act('role: auth, do: respond', {err: err, action: 'logout', req: req}, respond)
})
})
})
} | javascript | function cmd_logout (msg, respond) {
var req = msg.req$
// get token from request
req.seneca.act("role: 'auth', get: 'token'", {tokenkey: options.tokenkey}, function (err, clienttoken) {
if (err) {
return req.seneca.act('role: auth, do: respond', {err: err, action: 'logout', req: req}, respond)
}
if (!clienttoken) {
return req.seneca.act('role: auth, do: respond', {err: err, action: 'logout', req: req}, respond)
}
clienttoken = clienttoken.token
// delete token
req.seneca.act("role: 'auth', set: 'token'", {tokenkey: options.tokenkey}, function (err) {
if (err) {
return req.seneca.act('role: auth, do: respond', {err: err, action: 'logout', req: req}, respond)
}
req.seneca.act("role:'user',cmd:'logout'", {token: clienttoken}, function (err) {
if (err) {
req.seneca.log('error ', err)
}
req.cookieAuth.clear()
delete req.seneca.user
delete req.seneca.login
return req.seneca.act('role: auth, do: respond', {err: err, action: 'logout', req: req}, respond)
})
})
})
} | [
"function",
"cmd_logout",
"(",
"msg",
",",
"respond",
")",
"{",
"var",
"req",
"=",
"msg",
".",
"req$",
"req",
".",
"seneca",
".",
"act",
"(",
"\"role: 'auth', get: 'token'\"",
",",
"{",
"tokenkey",
":",
"options",
".",
"tokenkey",
"}",
",",
"function",
"(",
"err",
",",
"clienttoken",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"req",
".",
"seneca",
".",
"act",
"(",
"'role: auth, do: respond'",
",",
"{",
"err",
":",
"err",
",",
"action",
":",
"'logout'",
",",
"req",
":",
"req",
"}",
",",
"respond",
")",
"}",
"if",
"(",
"!",
"clienttoken",
")",
"{",
"return",
"req",
".",
"seneca",
".",
"act",
"(",
"'role: auth, do: respond'",
",",
"{",
"err",
":",
"err",
",",
"action",
":",
"'logout'",
",",
"req",
":",
"req",
"}",
",",
"respond",
")",
"}",
"clienttoken",
"=",
"clienttoken",
".",
"token",
"req",
".",
"seneca",
".",
"act",
"(",
"\"role: 'auth', set: 'token'\"",
",",
"{",
"tokenkey",
":",
"options",
".",
"tokenkey",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"req",
".",
"seneca",
".",
"act",
"(",
"'role: auth, do: respond'",
",",
"{",
"err",
":",
"err",
",",
"action",
":",
"'logout'",
",",
"req",
":",
"req",
"}",
",",
"respond",
")",
"}",
"req",
".",
"seneca",
".",
"act",
"(",
"\"role:'user',cmd:'logout'\"",
",",
"{",
"token",
":",
"clienttoken",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"req",
".",
"seneca",
".",
"log",
"(",
"'error '",
",",
"err",
")",
"}",
"req",
".",
"cookieAuth",
".",
"clear",
"(",
")",
"delete",
"req",
".",
"seneca",
".",
"user",
"delete",
"req",
".",
"seneca",
".",
"login",
"return",
"req",
".",
"seneca",
".",
"act",
"(",
"'role: auth, do: respond'",
",",
"{",
"err",
":",
"err",
",",
"action",
":",
"'logout'",
",",
"req",
":",
"req",
"}",
",",
"respond",
")",
"}",
")",
"}",
")",
"}",
")",
"}"
] | LOGIN END LOGOUT START | [
"LOGIN",
"END",
"LOGOUT",
"START"
] | 537716d2a07c9be6e3aa5ae6529929704c97338b | https://github.com/senecajs/seneca-auth/blob/537716d2a07c9be6e3aa5ae6529929704c97338b/lib/hapi-auth.js#L146-L177 | train |
jonschlinkert/extract-comments | index.js | extract | function extract(str, options, tranformFn) {
let extractor = new Extractor(options, tranformFn);
return extractor.extract(str);
} | javascript | function extract(str, options, tranformFn) {
let extractor = new Extractor(options, tranformFn);
return extractor.extract(str);
} | [
"function",
"extract",
"(",
"str",
",",
"options",
",",
"tranformFn",
")",
"{",
"let",
"extractor",
"=",
"new",
"Extractor",
"(",
"options",
",",
"tranformFn",
")",
";",
"return",
"extractor",
".",
"extract",
"(",
"str",
")",
";",
"}"
] | Extract comments from the given `string`.
```js
const extract = require('extract-comments');
console.log(extract(string, options));
```
@param {String} `string`
@param {Object} `options` Pass `first: true` to return after the first comment is found.
@param {Function} `tranformFn` (optional) Tranform function to modify each comment
@return {Array} Returns an array of comment objects
@api public | [
"Extract",
"comments",
"from",
"the",
"given",
"string",
"."
] | cc42e9f52a2502c6654d435e91e41ebebfbef4b2 | https://github.com/jonschlinkert/extract-comments/blob/cc42e9f52a2502c6654d435e91e41ebebfbef4b2/index.js#L26-L29 | train |
stefanjudis/grunt-photobox | tasks/lib/photobox.js | function( grunt, options, callback ) {
this.callback = callback;
this.diffCount = 0;
this.grunt = grunt;
this.options = options;
this.options.indexPath = this.getIndexPath();
this.pictureCount = 0;
if ( typeof options.template === 'string' ) {
this.template = options.template;
} else if ( typeof options.template === 'object' ) {
this.template = options.template.name;
}
this.movePictures();
this.pictures = this.getPreparedPictures();
} | javascript | function( grunt, options, callback ) {
this.callback = callback;
this.diffCount = 0;
this.grunt = grunt;
this.options = options;
this.options.indexPath = this.getIndexPath();
this.pictureCount = 0;
if ( typeof options.template === 'string' ) {
this.template = options.template;
} else if ( typeof options.template === 'object' ) {
this.template = options.template.name;
}
this.movePictures();
this.pictures = this.getPreparedPictures();
} | [
"function",
"(",
"grunt",
",",
"options",
",",
"callback",
")",
"{",
"this",
".",
"callback",
"=",
"callback",
";",
"this",
".",
"diffCount",
"=",
"0",
";",
"this",
".",
"grunt",
"=",
"grunt",
";",
"this",
".",
"options",
"=",
"options",
";",
"this",
".",
"options",
".",
"indexPath",
"=",
"this",
".",
"getIndexPath",
"(",
")",
";",
"this",
".",
"pictureCount",
"=",
"0",
";",
"if",
"(",
"typeof",
"options",
".",
"template",
"===",
"'string'",
")",
"{",
"this",
".",
"template",
"=",
"options",
".",
"template",
";",
"}",
"else",
"if",
"(",
"typeof",
"options",
".",
"template",
"===",
"'object'",
")",
"{",
"this",
".",
"template",
"=",
"options",
".",
"template",
".",
"name",
";",
"}",
"this",
".",
"movePictures",
"(",
")",
";",
"this",
".",
"pictures",
"=",
"this",
".",
"getPreparedPictures",
"(",
")",
";",
"}"
] | Constructor for PhotoBox
@param {Object} grunt grunt
@param {Object} options plugin options
@param {Function} callback callback
@tested | [
"Constructor",
"for",
"PhotoBox"
] | 9d91025d554a997953deb655de808b40399bc805 | https://github.com/stefanjudis/grunt-photobox/blob/9d91025d554a997953deb655de808b40399bc805/tasks/lib/photobox.js#L26-L42 | train |
|
asakusuma/ember-spaniel | index.js | function(treeType) {
if (treeType === 'vendor') {
// The treeForVendor returns a different value based on whether or not
// this addon is a nested dependency
return caclculateCacheKeyForTree(treeType, this, [!this.parent.parent]);
} else {
return this._super.cacheKeyForTree.call(this, treeType);
}
} | javascript | function(treeType) {
if (treeType === 'vendor') {
// The treeForVendor returns a different value based on whether or not
// this addon is a nested dependency
return caclculateCacheKeyForTree(treeType, this, [!this.parent.parent]);
} else {
return this._super.cacheKeyForTree.call(this, treeType);
}
} | [
"function",
"(",
"treeType",
")",
"{",
"if",
"(",
"treeType",
"===",
"'vendor'",
")",
"{",
"return",
"caclculateCacheKeyForTree",
"(",
"treeType",
",",
"this",
",",
"[",
"!",
"this",
".",
"parent",
".",
"parent",
"]",
")",
";",
"}",
"else",
"{",
"return",
"this",
".",
"_super",
".",
"cacheKeyForTree",
".",
"call",
"(",
"this",
",",
"treeType",
")",
";",
"}",
"}"
] | ember-rollup implements a custom treeForVendor hook, we restore the caching for that hook here | [
"ember",
"-",
"rollup",
"implements",
"a",
"custom",
"treeForVendor",
"hook",
"we",
"restore",
"the",
"caching",
"for",
"that",
"hook",
"here"
] | 26bb0917eebf710e662199cc1c2cc5c4eb37c42e | https://github.com/asakusuma/ember-spaniel/blob/26bb0917eebf710e662199cc1c2cc5c4eb37c42e/index.js#L15-L23 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function(elem) {
this.getOffset._offset = $(elem).offset();
if (Garnish.$scrollContainer[0] !== Garnish.$win[0]) {
this.getOffset._offset.top += Garnish.$scrollContainer.scrollTop();
this.getOffset._offset.left += Garnish.$scrollContainer.scrollLeft();
}
return this.getOffset._offset;
} | javascript | function(elem) {
this.getOffset._offset = $(elem).offset();
if (Garnish.$scrollContainer[0] !== Garnish.$win[0]) {
this.getOffset._offset.top += Garnish.$scrollContainer.scrollTop();
this.getOffset._offset.left += Garnish.$scrollContainer.scrollLeft();
}
return this.getOffset._offset;
} | [
"function",
"(",
"elem",
")",
"{",
"this",
".",
"getOffset",
".",
"_offset",
"=",
"$",
"(",
"elem",
")",
".",
"offset",
"(",
")",
";",
"if",
"(",
"Garnish",
".",
"$scrollContainer",
"[",
"0",
"]",
"!==",
"Garnish",
".",
"$win",
"[",
"0",
"]",
")",
"{",
"this",
".",
"getOffset",
".",
"_offset",
".",
"top",
"+=",
"Garnish",
".",
"$scrollContainer",
".",
"scrollTop",
"(",
")",
";",
"this",
".",
"getOffset",
".",
"_offset",
".",
"left",
"+=",
"Garnish",
".",
"$scrollContainer",
".",
"scrollLeft",
"(",
")",
";",
"}",
"return",
"this",
".",
"getOffset",
".",
"_offset",
";",
"}"
] | Returns the offset of an element within the scroll container, whether that's the window or something else | [
"Returns",
"the",
"offset",
"of",
"an",
"element",
"within",
"the",
"scroll",
"container",
"whether",
"that",
"s",
"the",
"window",
"or",
"something",
"else"
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L300-L309 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function(source, target) {
var $source = $(source),
$target = $(target);
$target.css({
fontFamily: $source.css('fontFamily'),
fontSize: $source.css('fontSize'),
fontWeight: $source.css('fontWeight'),
letterSpacing: $source.css('letterSpacing'),
lineHeight: $source.css('lineHeight'),
textAlign: $source.css('textAlign'),
textIndent: $source.css('textIndent'),
whiteSpace: $source.css('whiteSpace'),
wordSpacing: $source.css('wordSpacing'),
wordWrap: $source.css('wordWrap')
});
} | javascript | function(source, target) {
var $source = $(source),
$target = $(target);
$target.css({
fontFamily: $source.css('fontFamily'),
fontSize: $source.css('fontSize'),
fontWeight: $source.css('fontWeight'),
letterSpacing: $source.css('letterSpacing'),
lineHeight: $source.css('lineHeight'),
textAlign: $source.css('textAlign'),
textIndent: $source.css('textIndent'),
whiteSpace: $source.css('whiteSpace'),
wordSpacing: $source.css('wordSpacing'),
wordWrap: $source.css('wordWrap')
});
} | [
"function",
"(",
"source",
",",
"target",
")",
"{",
"var",
"$source",
"=",
"$",
"(",
"source",
")",
",",
"$target",
"=",
"$",
"(",
"target",
")",
";",
"$target",
".",
"css",
"(",
"{",
"fontFamily",
":",
"$source",
".",
"css",
"(",
"'fontFamily'",
")",
",",
"fontSize",
":",
"$source",
".",
"css",
"(",
"'fontSize'",
")",
",",
"fontWeight",
":",
"$source",
".",
"css",
"(",
"'fontWeight'",
")",
",",
"letterSpacing",
":",
"$source",
".",
"css",
"(",
"'letterSpacing'",
")",
",",
"lineHeight",
":",
"$source",
".",
"css",
"(",
"'lineHeight'",
")",
",",
"textAlign",
":",
"$source",
".",
"css",
"(",
"'textAlign'",
")",
",",
"textIndent",
":",
"$source",
".",
"css",
"(",
"'textIndent'",
")",
",",
"whiteSpace",
":",
"$source",
".",
"css",
"(",
"'whiteSpace'",
")",
",",
"wordSpacing",
":",
"$source",
".",
"css",
"(",
"'wordSpacing'",
")",
",",
"wordWrap",
":",
"$source",
".",
"css",
"(",
"'wordWrap'",
")",
"}",
")",
";",
"}"
] | Copies text styles from one element to another.
@param {object} source The source element. Can be either an actual element or a jQuery collection.
@param {object} target The target element. Can be either an actual element or a jQuery collection. | [
"Copies",
"text",
"styles",
"from",
"one",
"element",
"to",
"another",
"."
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L360-L376 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function() {
Garnish.getBodyScrollTop._scrollTop = document.body.scrollTop;
if (Garnish.getBodyScrollTop._scrollTop < 0) {
Garnish.getBodyScrollTop._scrollTop = 0;
}
else {
Garnish.getBodyScrollTop._maxScrollTop = Garnish.$bod.outerHeight() - Garnish.$win.height();
if (Garnish.getBodyScrollTop._scrollTop > Garnish.getBodyScrollTop._maxScrollTop) {
Garnish.getBodyScrollTop._scrollTop = Garnish.getBodyScrollTop._maxScrollTop;
}
}
return Garnish.getBodyScrollTop._scrollTop;
} | javascript | function() {
Garnish.getBodyScrollTop._scrollTop = document.body.scrollTop;
if (Garnish.getBodyScrollTop._scrollTop < 0) {
Garnish.getBodyScrollTop._scrollTop = 0;
}
else {
Garnish.getBodyScrollTop._maxScrollTop = Garnish.$bod.outerHeight() - Garnish.$win.height();
if (Garnish.getBodyScrollTop._scrollTop > Garnish.getBodyScrollTop._maxScrollTop) {
Garnish.getBodyScrollTop._scrollTop = Garnish.getBodyScrollTop._maxScrollTop;
}
}
return Garnish.getBodyScrollTop._scrollTop;
} | [
"function",
"(",
")",
"{",
"Garnish",
".",
"getBodyScrollTop",
".",
"_scrollTop",
"=",
"document",
".",
"body",
".",
"scrollTop",
";",
"if",
"(",
"Garnish",
".",
"getBodyScrollTop",
".",
"_scrollTop",
"<",
"0",
")",
"{",
"Garnish",
".",
"getBodyScrollTop",
".",
"_scrollTop",
"=",
"0",
";",
"}",
"else",
"{",
"Garnish",
".",
"getBodyScrollTop",
".",
"_maxScrollTop",
"=",
"Garnish",
".",
"$bod",
".",
"outerHeight",
"(",
")",
"-",
"Garnish",
".",
"$win",
".",
"height",
"(",
")",
";",
"if",
"(",
"Garnish",
".",
"getBodyScrollTop",
".",
"_scrollTop",
">",
"Garnish",
".",
"getBodyScrollTop",
".",
"_maxScrollTop",
")",
"{",
"Garnish",
".",
"getBodyScrollTop",
".",
"_scrollTop",
"=",
"Garnish",
".",
"getBodyScrollTop",
".",
"_maxScrollTop",
";",
"}",
"}",
"return",
"Garnish",
".",
"getBodyScrollTop",
".",
"_scrollTop",
";",
"}"
] | Returns the body's real scrollTop, discarding any window banding in Safari.
@return {number} | [
"Returns",
"the",
"body",
"s",
"real",
"scrollTop",
"discarding",
"any",
"window",
"banding",
"in",
"Safari",
"."
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L383-L398 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function(container, elem) {
var $elem;
if (typeof elem === 'undefined') {
$elem = $(container);
$container = $elem.scrollParent();
}
else {
var $container = $(container);
$elem = $(elem);
}
if ($container.prop('nodeName') === 'HTML' || $container[0] === Garnish.$doc[0]) {
$container = Garnish.$win;
}
var scrollTop = $container.scrollTop(),
elemOffset = $elem.offset().top;
var elemScrollOffset;
if ($container[0] === window) {
elemScrollOffset = elemOffset - scrollTop;
}
else {
elemScrollOffset = elemOffset - $container.offset().top;
}
var targetScrollTop = false;
// Is the element above the fold?
if (elemScrollOffset < 0) {
targetScrollTop = scrollTop + elemScrollOffset - 10;
}
else {
var elemHeight = $elem.outerHeight(),
containerHeight = ($container[0] === window ? window.innerHeight : $container[0].clientHeight);
// Is it below the fold?
if (elemScrollOffset + elemHeight > containerHeight) {
targetScrollTop = scrollTop + (elemScrollOffset - (containerHeight - elemHeight)) + 10;
}
}
if (targetScrollTop !== false) {
// Velocity only allows you to scroll to an arbitrary position if you're scrolling the main window
if ($container[0] === window) {
$('html').velocity('scroll', {
offset: targetScrollTop + 'px',
mobileHA: false
});
}
else {
$container.scrollTop(targetScrollTop);
}
}
} | javascript | function(container, elem) {
var $elem;
if (typeof elem === 'undefined') {
$elem = $(container);
$container = $elem.scrollParent();
}
else {
var $container = $(container);
$elem = $(elem);
}
if ($container.prop('nodeName') === 'HTML' || $container[0] === Garnish.$doc[0]) {
$container = Garnish.$win;
}
var scrollTop = $container.scrollTop(),
elemOffset = $elem.offset().top;
var elemScrollOffset;
if ($container[0] === window) {
elemScrollOffset = elemOffset - scrollTop;
}
else {
elemScrollOffset = elemOffset - $container.offset().top;
}
var targetScrollTop = false;
// Is the element above the fold?
if (elemScrollOffset < 0) {
targetScrollTop = scrollTop + elemScrollOffset - 10;
}
else {
var elemHeight = $elem.outerHeight(),
containerHeight = ($container[0] === window ? window.innerHeight : $container[0].clientHeight);
// Is it below the fold?
if (elemScrollOffset + elemHeight > containerHeight) {
targetScrollTop = scrollTop + (elemScrollOffset - (containerHeight - elemHeight)) + 10;
}
}
if (targetScrollTop !== false) {
// Velocity only allows you to scroll to an arbitrary position if you're scrolling the main window
if ($container[0] === window) {
$('html').velocity('scroll', {
offset: targetScrollTop + 'px',
mobileHA: false
});
}
else {
$container.scrollTop(targetScrollTop);
}
}
} | [
"function",
"(",
"container",
",",
"elem",
")",
"{",
"var",
"$elem",
";",
"if",
"(",
"typeof",
"elem",
"===",
"'undefined'",
")",
"{",
"$elem",
"=",
"$",
"(",
"container",
")",
";",
"$container",
"=",
"$elem",
".",
"scrollParent",
"(",
")",
";",
"}",
"else",
"{",
"var",
"$container",
"=",
"$",
"(",
"container",
")",
";",
"$elem",
"=",
"$",
"(",
"elem",
")",
";",
"}",
"if",
"(",
"$container",
".",
"prop",
"(",
"'nodeName'",
")",
"===",
"'HTML'",
"||",
"$container",
"[",
"0",
"]",
"===",
"Garnish",
".",
"$doc",
"[",
"0",
"]",
")",
"{",
"$container",
"=",
"Garnish",
".",
"$win",
";",
"}",
"var",
"scrollTop",
"=",
"$container",
".",
"scrollTop",
"(",
")",
",",
"elemOffset",
"=",
"$elem",
".",
"offset",
"(",
")",
".",
"top",
";",
"var",
"elemScrollOffset",
";",
"if",
"(",
"$container",
"[",
"0",
"]",
"===",
"window",
")",
"{",
"elemScrollOffset",
"=",
"elemOffset",
"-",
"scrollTop",
";",
"}",
"else",
"{",
"elemScrollOffset",
"=",
"elemOffset",
"-",
"$container",
".",
"offset",
"(",
")",
".",
"top",
";",
"}",
"var",
"targetScrollTop",
"=",
"false",
";",
"if",
"(",
"elemScrollOffset",
"<",
"0",
")",
"{",
"targetScrollTop",
"=",
"scrollTop",
"+",
"elemScrollOffset",
"-",
"10",
";",
"}",
"else",
"{",
"var",
"elemHeight",
"=",
"$elem",
".",
"outerHeight",
"(",
")",
",",
"containerHeight",
"=",
"(",
"$container",
"[",
"0",
"]",
"===",
"window",
"?",
"window",
".",
"innerHeight",
":",
"$container",
"[",
"0",
"]",
".",
"clientHeight",
")",
";",
"if",
"(",
"elemScrollOffset",
"+",
"elemHeight",
">",
"containerHeight",
")",
"{",
"targetScrollTop",
"=",
"scrollTop",
"+",
"(",
"elemScrollOffset",
"-",
"(",
"containerHeight",
"-",
"elemHeight",
")",
")",
"+",
"10",
";",
"}",
"}",
"if",
"(",
"targetScrollTop",
"!==",
"false",
")",
"{",
"if",
"(",
"$container",
"[",
"0",
"]",
"===",
"window",
")",
"{",
"$",
"(",
"'html'",
")",
".",
"velocity",
"(",
"'scroll'",
",",
"{",
"offset",
":",
"targetScrollTop",
"+",
"'px'",
",",
"mobileHA",
":",
"false",
"}",
")",
";",
"}",
"else",
"{",
"$container",
".",
"scrollTop",
"(",
"targetScrollTop",
")",
";",
"}",
"}",
"}"
] | Scrolls a container element to an element within it.
@param {object} container Either an actual element or a jQuery collection.
@param {object} elem Either an actual element or a jQuery collection. | [
"Scrolls",
"a",
"container",
"element",
"to",
"an",
"element",
"within",
"it",
"."
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L434-L490 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function(elem, prop) {
var $elem = $(elem);
if (!prop) {
prop = 'margin-left';
}
var startingPoint = parseInt($elem.css(prop));
if (isNaN(startingPoint)) {
startingPoint = 0;
}
for (var i = 0; i <= Garnish.SHAKE_STEPS; i++) {
(function(i) {
setTimeout(function() {
Garnish.shake._properties = {};
Garnish.shake._properties[prop] = startingPoint + (i % 2 ? -1 : 1) * (10 - i);
$elem.velocity(Garnish.shake._properties, Garnish.SHAKE_STEP_DURATION);
}, (Garnish.SHAKE_STEP_DURATION * i));
})(i);
}
} | javascript | function(elem, prop) {
var $elem = $(elem);
if (!prop) {
prop = 'margin-left';
}
var startingPoint = parseInt($elem.css(prop));
if (isNaN(startingPoint)) {
startingPoint = 0;
}
for (var i = 0; i <= Garnish.SHAKE_STEPS; i++) {
(function(i) {
setTimeout(function() {
Garnish.shake._properties = {};
Garnish.shake._properties[prop] = startingPoint + (i % 2 ? -1 : 1) * (10 - i);
$elem.velocity(Garnish.shake._properties, Garnish.SHAKE_STEP_DURATION);
}, (Garnish.SHAKE_STEP_DURATION * i));
})(i);
}
} | [
"function",
"(",
"elem",
",",
"prop",
")",
"{",
"var",
"$elem",
"=",
"$",
"(",
"elem",
")",
";",
"if",
"(",
"!",
"prop",
")",
"{",
"prop",
"=",
"'margin-left'",
";",
"}",
"var",
"startingPoint",
"=",
"parseInt",
"(",
"$elem",
".",
"css",
"(",
"prop",
")",
")",
";",
"if",
"(",
"isNaN",
"(",
"startingPoint",
")",
")",
"{",
"startingPoint",
"=",
"0",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<=",
"Garnish",
".",
"SHAKE_STEPS",
";",
"i",
"++",
")",
"{",
"(",
"function",
"(",
"i",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"Garnish",
".",
"shake",
".",
"_properties",
"=",
"{",
"}",
";",
"Garnish",
".",
"shake",
".",
"_properties",
"[",
"prop",
"]",
"=",
"startingPoint",
"+",
"(",
"i",
"%",
"2",
"?",
"-",
"1",
":",
"1",
")",
"*",
"(",
"10",
"-",
"i",
")",
";",
"$elem",
".",
"velocity",
"(",
"Garnish",
".",
"shake",
".",
"_properties",
",",
"Garnish",
".",
"SHAKE_STEP_DURATION",
")",
";",
"}",
",",
"(",
"Garnish",
".",
"SHAKE_STEP_DURATION",
"*",
"i",
")",
")",
";",
"}",
")",
"(",
"i",
")",
";",
"}",
"}"
] | Shakes an element.
@param {object} elem Either an actual element or a jQuery collection.
@param {string} prop The property that should be adjusted (default is 'margin-left'). | [
"Shakes",
"an",
"element",
"."
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L501-L522 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function(container) {
var postData = {},
arrayInputCounters = {},
$inputs = Garnish.findInputs(container);
var inputName;
for (var i = 0; i < $inputs.length; i++) {
var $input = $inputs.eq(i);
if ($input.prop('disabled')) {
continue;
}
inputName = $input.attr('name');
if (!inputName) {
continue;
}
var inputVal = Garnish.getInputPostVal($input);
if (inputVal === null) {
continue;
}
var isArrayInput = (inputName.substr(-2) === '[]');
if (isArrayInput) {
// Get the cropped input name
var croppedName = inputName.substring(0, inputName.length - 2);
// Prep the input counter
if (typeof arrayInputCounters[croppedName] === 'undefined') {
arrayInputCounters[croppedName] = 0;
}
}
if (!Garnish.isArray(inputVal)) {
inputVal = [inputVal];
}
for (var j = 0; j < inputVal.length; j++) {
if (isArrayInput) {
inputName = croppedName + '[' + arrayInputCounters[croppedName] + ']';
arrayInputCounters[croppedName]++;
}
postData[inputName] = inputVal[j];
}
}
return postData;
} | javascript | function(container) {
var postData = {},
arrayInputCounters = {},
$inputs = Garnish.findInputs(container);
var inputName;
for (var i = 0; i < $inputs.length; i++) {
var $input = $inputs.eq(i);
if ($input.prop('disabled')) {
continue;
}
inputName = $input.attr('name');
if (!inputName) {
continue;
}
var inputVal = Garnish.getInputPostVal($input);
if (inputVal === null) {
continue;
}
var isArrayInput = (inputName.substr(-2) === '[]');
if (isArrayInput) {
// Get the cropped input name
var croppedName = inputName.substring(0, inputName.length - 2);
// Prep the input counter
if (typeof arrayInputCounters[croppedName] === 'undefined') {
arrayInputCounters[croppedName] = 0;
}
}
if (!Garnish.isArray(inputVal)) {
inputVal = [inputVal];
}
for (var j = 0; j < inputVal.length; j++) {
if (isArrayInput) {
inputName = croppedName + '[' + arrayInputCounters[croppedName] + ']';
arrayInputCounters[croppedName]++;
}
postData[inputName] = inputVal[j];
}
}
return postData;
} | [
"function",
"(",
"container",
")",
"{",
"var",
"postData",
"=",
"{",
"}",
",",
"arrayInputCounters",
"=",
"{",
"}",
",",
"$inputs",
"=",
"Garnish",
".",
"findInputs",
"(",
"container",
")",
";",
"var",
"inputName",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"$inputs",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"$input",
"=",
"$inputs",
".",
"eq",
"(",
"i",
")",
";",
"if",
"(",
"$input",
".",
"prop",
"(",
"'disabled'",
")",
")",
"{",
"continue",
";",
"}",
"inputName",
"=",
"$input",
".",
"attr",
"(",
"'name'",
")",
";",
"if",
"(",
"!",
"inputName",
")",
"{",
"continue",
";",
"}",
"var",
"inputVal",
"=",
"Garnish",
".",
"getInputPostVal",
"(",
"$input",
")",
";",
"if",
"(",
"inputVal",
"===",
"null",
")",
"{",
"continue",
";",
"}",
"var",
"isArrayInput",
"=",
"(",
"inputName",
".",
"substr",
"(",
"-",
"2",
")",
"===",
"'[]'",
")",
";",
"if",
"(",
"isArrayInput",
")",
"{",
"var",
"croppedName",
"=",
"inputName",
".",
"substring",
"(",
"0",
",",
"inputName",
".",
"length",
"-",
"2",
")",
";",
"if",
"(",
"typeof",
"arrayInputCounters",
"[",
"croppedName",
"]",
"===",
"'undefined'",
")",
"{",
"arrayInputCounters",
"[",
"croppedName",
"]",
"=",
"0",
";",
"}",
"}",
"if",
"(",
"!",
"Garnish",
".",
"isArray",
"(",
"inputVal",
")",
")",
"{",
"inputVal",
"=",
"[",
"inputVal",
"]",
";",
"}",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"inputVal",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"isArrayInput",
")",
"{",
"inputName",
"=",
"croppedName",
"+",
"'['",
"+",
"arrayInputCounters",
"[",
"croppedName",
"]",
"+",
"']'",
";",
"arrayInputCounters",
"[",
"croppedName",
"]",
"++",
";",
"}",
"postData",
"[",
"inputName",
"]",
"=",
"inputVal",
"[",
"j",
"]",
";",
"}",
"}",
"return",
"postData",
";",
"}"
] | Returns the post data within a container.
@param {object} container
@return {array} | [
"Returns",
"the",
"post",
"data",
"within",
"a",
"container",
"."
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L606-L657 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function(ev) {
ev.preventDefault();
this.realMouseX = ev.pageX;
this.realMouseY = ev.pageY;
if (this.settings.axis !== Garnish.Y_AXIS) {
this.mouseX = ev.pageX;
}
if (this.settings.axis !== Garnish.X_AXIS) {
this.mouseY = ev.pageY;
}
this.mouseDistX = this.mouseX - this.mousedownX;
this.mouseDistY = this.mouseY - this.mousedownY;
if (!this.dragging) {
// Has the mouse moved far enough to initiate dragging yet?
this._handleMouseMove._mouseDist = Garnish.getDist(this.mousedownX, this.mousedownY, this.realMouseX, this.realMouseY);
if (this._handleMouseMove._mouseDist >= Garnish.BaseDrag.minMouseDist) {
this.startDragging();
}
}
if (this.dragging) {
this.drag(true);
}
} | javascript | function(ev) {
ev.preventDefault();
this.realMouseX = ev.pageX;
this.realMouseY = ev.pageY;
if (this.settings.axis !== Garnish.Y_AXIS) {
this.mouseX = ev.pageX;
}
if (this.settings.axis !== Garnish.X_AXIS) {
this.mouseY = ev.pageY;
}
this.mouseDistX = this.mouseX - this.mousedownX;
this.mouseDistY = this.mouseY - this.mousedownY;
if (!this.dragging) {
// Has the mouse moved far enough to initiate dragging yet?
this._handleMouseMove._mouseDist = Garnish.getDist(this.mousedownX, this.mousedownY, this.realMouseX, this.realMouseY);
if (this._handleMouseMove._mouseDist >= Garnish.BaseDrag.minMouseDist) {
this.startDragging();
}
}
if (this.dragging) {
this.drag(true);
}
} | [
"function",
"(",
"ev",
")",
"{",
"ev",
".",
"preventDefault",
"(",
")",
";",
"this",
".",
"realMouseX",
"=",
"ev",
".",
"pageX",
";",
"this",
".",
"realMouseY",
"=",
"ev",
".",
"pageY",
";",
"if",
"(",
"this",
".",
"settings",
".",
"axis",
"!==",
"Garnish",
".",
"Y_AXIS",
")",
"{",
"this",
".",
"mouseX",
"=",
"ev",
".",
"pageX",
";",
"}",
"if",
"(",
"this",
".",
"settings",
".",
"axis",
"!==",
"Garnish",
".",
"X_AXIS",
")",
"{",
"this",
".",
"mouseY",
"=",
"ev",
".",
"pageY",
";",
"}",
"this",
".",
"mouseDistX",
"=",
"this",
".",
"mouseX",
"-",
"this",
".",
"mousedownX",
";",
"this",
".",
"mouseDistY",
"=",
"this",
".",
"mouseY",
"-",
"this",
".",
"mousedownY",
";",
"if",
"(",
"!",
"this",
".",
"dragging",
")",
"{",
"this",
".",
"_handleMouseMove",
".",
"_mouseDist",
"=",
"Garnish",
".",
"getDist",
"(",
"this",
".",
"mousedownX",
",",
"this",
".",
"mousedownY",
",",
"this",
".",
"realMouseX",
",",
"this",
".",
"realMouseY",
")",
";",
"if",
"(",
"this",
".",
"_handleMouseMove",
".",
"_mouseDist",
">=",
"Garnish",
".",
"BaseDrag",
".",
"minMouseDist",
")",
"{",
"this",
".",
"startDragging",
"(",
")",
";",
"}",
"}",
"if",
"(",
"this",
".",
"dragging",
")",
"{",
"this",
".",
"drag",
"(",
"true",
")",
";",
"}",
"}"
] | Handle Mouse Move | [
"Handle",
"Mouse",
"Move"
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L1407-L1436 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function($newDraggee) {
if (!$newDraggee.length) {
return;
}
if (!this.settings.collapseDraggees) {
var oldLength = this.$draggee.length;
}
this.$draggee = $(this.$draggee.toArray().concat($newDraggee.toArray()));
// Create new helpers?
if (!this.settings.collapseDraggees) {
var newLength = this.$draggee.length;
for (var i = oldLength; i < newLength; i++) {
this._createHelper(i);
}
}
if (this.settings.removeDraggee || this.settings.collapseDraggees) {
$newDraggee.hide();
}
else {
$newDraggee.css('visibility', 'hidden');
}
} | javascript | function($newDraggee) {
if (!$newDraggee.length) {
return;
}
if (!this.settings.collapseDraggees) {
var oldLength = this.$draggee.length;
}
this.$draggee = $(this.$draggee.toArray().concat($newDraggee.toArray()));
// Create new helpers?
if (!this.settings.collapseDraggees) {
var newLength = this.$draggee.length;
for (var i = oldLength; i < newLength; i++) {
this._createHelper(i);
}
}
if (this.settings.removeDraggee || this.settings.collapseDraggees) {
$newDraggee.hide();
}
else {
$newDraggee.css('visibility', 'hidden');
}
} | [
"function",
"(",
"$newDraggee",
")",
"{",
"if",
"(",
"!",
"$newDraggee",
".",
"length",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"this",
".",
"settings",
".",
"collapseDraggees",
")",
"{",
"var",
"oldLength",
"=",
"this",
".",
"$draggee",
".",
"length",
";",
"}",
"this",
".",
"$draggee",
"=",
"$",
"(",
"this",
".",
"$draggee",
".",
"toArray",
"(",
")",
".",
"concat",
"(",
"$newDraggee",
".",
"toArray",
"(",
")",
")",
")",
";",
"if",
"(",
"!",
"this",
".",
"settings",
".",
"collapseDraggees",
")",
"{",
"var",
"newLength",
"=",
"this",
".",
"$draggee",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"oldLength",
";",
"i",
"<",
"newLength",
";",
"i",
"++",
")",
"{",
"this",
".",
"_createHelper",
"(",
"i",
")",
";",
"}",
"}",
"if",
"(",
"this",
".",
"settings",
".",
"removeDraggee",
"||",
"this",
".",
"settings",
".",
"collapseDraggees",
")",
"{",
"$newDraggee",
".",
"hide",
"(",
")",
";",
"}",
"else",
"{",
"$newDraggee",
".",
"css",
"(",
"'visibility'",
",",
"'hidden'",
")",
";",
"}",
"}"
] | Appends additional items to the draggee. | [
"Appends",
"additional",
"items",
"to",
"the",
"draggee",
"."
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L1836-L1862 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function() {
this._returningHelpersToDraggees = true;
for (var i = 0; i < this.helpers.length; i++) {
var $draggee = this.$draggee.eq(i),
$helper = this.helpers[i];
$draggee.css({
display: this.draggeeDisplay,
visibility: 'hidden'
});
var draggeeOffset = $draggee.offset();
var callback;
if (i === 0) {
callback = $.proxy(this, '_showDraggee');
}
else {
callback = null;
}
$helper.velocity({left: draggeeOffset.left, top: draggeeOffset.top}, Garnish.FX_DURATION, callback);
}
} | javascript | function() {
this._returningHelpersToDraggees = true;
for (var i = 0; i < this.helpers.length; i++) {
var $draggee = this.$draggee.eq(i),
$helper = this.helpers[i];
$draggee.css({
display: this.draggeeDisplay,
visibility: 'hidden'
});
var draggeeOffset = $draggee.offset();
var callback;
if (i === 0) {
callback = $.proxy(this, '_showDraggee');
}
else {
callback = null;
}
$helper.velocity({left: draggeeOffset.left, top: draggeeOffset.top}, Garnish.FX_DURATION, callback);
}
} | [
"function",
"(",
")",
"{",
"this",
".",
"_returningHelpersToDraggees",
"=",
"true",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"helpers",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"$draggee",
"=",
"this",
".",
"$draggee",
".",
"eq",
"(",
"i",
")",
",",
"$helper",
"=",
"this",
".",
"helpers",
"[",
"i",
"]",
";",
"$draggee",
".",
"css",
"(",
"{",
"display",
":",
"this",
".",
"draggeeDisplay",
",",
"visibility",
":",
"'hidden'",
"}",
")",
";",
"var",
"draggeeOffset",
"=",
"$draggee",
".",
"offset",
"(",
")",
";",
"var",
"callback",
";",
"if",
"(",
"i",
"===",
"0",
")",
"{",
"callback",
"=",
"$",
".",
"proxy",
"(",
"this",
",",
"'_showDraggee'",
")",
";",
"}",
"else",
"{",
"callback",
"=",
"null",
";",
"}",
"$helper",
".",
"velocity",
"(",
"{",
"left",
":",
"draggeeOffset",
".",
"left",
",",
"top",
":",
"draggeeOffset",
".",
"top",
"}",
",",
"Garnish",
".",
"FX_DURATION",
",",
"callback",
")",
";",
"}",
"}"
] | Return Helpers to Draggees | [
"Return",
"Helpers",
"to",
"Draggees"
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L1921-L1945 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function() {
// Has the mouse moved?
if (this.mouseX !== this.lastMouseX || this.mouseY !== this.lastMouseY) {
// Get the new target helper positions
for (this._updateHelperPos._i = 0; this._updateHelperPos._i < this.helpers.length; this._updateHelperPos._i++) {
this.helperTargets[this._updateHelperPos._i] = this._getHelperTarget(this._updateHelperPos._i);
}
this.lastMouseX = this.mouseX;
this.lastMouseY = this.mouseY;
}
// Gravitate helpers toward their target positions
for (this._updateHelperPos._j = 0; this._updateHelperPos._j < this.helpers.length; this._updateHelperPos._j++) {
this._updateHelperPos._lag = this.settings.helperLagBase + (this.helperLagIncrement * this._updateHelperPos._j);
this.helperPositions[this._updateHelperPos._j] = {
left: this.helperPositions[this._updateHelperPos._j].left + ((this.helperTargets[this._updateHelperPos._j].left - this.helperPositions[this._updateHelperPos._j].left) / this._updateHelperPos._lag),
top: this.helperPositions[this._updateHelperPos._j].top + ((this.helperTargets[this._updateHelperPos._j].top - this.helperPositions[this._updateHelperPos._j].top) / this._updateHelperPos._lag)
};
this.helpers[this._updateHelperPos._j].css(this.helperPositions[this._updateHelperPos._j]);
}
// Let's do this again on the next frame!
this.updateHelperPosFrame = Garnish.requestAnimationFrame(this.updateHelperPosProxy);
} | javascript | function() {
// Has the mouse moved?
if (this.mouseX !== this.lastMouseX || this.mouseY !== this.lastMouseY) {
// Get the new target helper positions
for (this._updateHelperPos._i = 0; this._updateHelperPos._i < this.helpers.length; this._updateHelperPos._i++) {
this.helperTargets[this._updateHelperPos._i] = this._getHelperTarget(this._updateHelperPos._i);
}
this.lastMouseX = this.mouseX;
this.lastMouseY = this.mouseY;
}
// Gravitate helpers toward their target positions
for (this._updateHelperPos._j = 0; this._updateHelperPos._j < this.helpers.length; this._updateHelperPos._j++) {
this._updateHelperPos._lag = this.settings.helperLagBase + (this.helperLagIncrement * this._updateHelperPos._j);
this.helperPositions[this._updateHelperPos._j] = {
left: this.helperPositions[this._updateHelperPos._j].left + ((this.helperTargets[this._updateHelperPos._j].left - this.helperPositions[this._updateHelperPos._j].left) / this._updateHelperPos._lag),
top: this.helperPositions[this._updateHelperPos._j].top + ((this.helperTargets[this._updateHelperPos._j].top - this.helperPositions[this._updateHelperPos._j].top) / this._updateHelperPos._lag)
};
this.helpers[this._updateHelperPos._j].css(this.helperPositions[this._updateHelperPos._j]);
}
// Let's do this again on the next frame!
this.updateHelperPosFrame = Garnish.requestAnimationFrame(this.updateHelperPosProxy);
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"mouseX",
"!==",
"this",
".",
"lastMouseX",
"||",
"this",
".",
"mouseY",
"!==",
"this",
".",
"lastMouseY",
")",
"{",
"for",
"(",
"this",
".",
"_updateHelperPos",
".",
"_i",
"=",
"0",
";",
"this",
".",
"_updateHelperPos",
".",
"_i",
"<",
"this",
".",
"helpers",
".",
"length",
";",
"this",
".",
"_updateHelperPos",
".",
"_i",
"++",
")",
"{",
"this",
".",
"helperTargets",
"[",
"this",
".",
"_updateHelperPos",
".",
"_i",
"]",
"=",
"this",
".",
"_getHelperTarget",
"(",
"this",
".",
"_updateHelperPos",
".",
"_i",
")",
";",
"}",
"this",
".",
"lastMouseX",
"=",
"this",
".",
"mouseX",
";",
"this",
".",
"lastMouseY",
"=",
"this",
".",
"mouseY",
";",
"}",
"for",
"(",
"this",
".",
"_updateHelperPos",
".",
"_j",
"=",
"0",
";",
"this",
".",
"_updateHelperPos",
".",
"_j",
"<",
"this",
".",
"helpers",
".",
"length",
";",
"this",
".",
"_updateHelperPos",
".",
"_j",
"++",
")",
"{",
"this",
".",
"_updateHelperPos",
".",
"_lag",
"=",
"this",
".",
"settings",
".",
"helperLagBase",
"+",
"(",
"this",
".",
"helperLagIncrement",
"*",
"this",
".",
"_updateHelperPos",
".",
"_j",
")",
";",
"this",
".",
"helperPositions",
"[",
"this",
".",
"_updateHelperPos",
".",
"_j",
"]",
"=",
"{",
"left",
":",
"this",
".",
"helperPositions",
"[",
"this",
".",
"_updateHelperPos",
".",
"_j",
"]",
".",
"left",
"+",
"(",
"(",
"this",
".",
"helperTargets",
"[",
"this",
".",
"_updateHelperPos",
".",
"_j",
"]",
".",
"left",
"-",
"this",
".",
"helperPositions",
"[",
"this",
".",
"_updateHelperPos",
".",
"_j",
"]",
".",
"left",
")",
"/",
"this",
".",
"_updateHelperPos",
".",
"_lag",
")",
",",
"top",
":",
"this",
".",
"helperPositions",
"[",
"this",
".",
"_updateHelperPos",
".",
"_j",
"]",
".",
"top",
"+",
"(",
"(",
"this",
".",
"helperTargets",
"[",
"this",
".",
"_updateHelperPos",
".",
"_j",
"]",
".",
"top",
"-",
"this",
".",
"helperPositions",
"[",
"this",
".",
"_updateHelperPos",
".",
"_j",
"]",
".",
"top",
")",
"/",
"this",
".",
"_updateHelperPos",
".",
"_lag",
")",
"}",
";",
"this",
".",
"helpers",
"[",
"this",
".",
"_updateHelperPos",
".",
"_j",
"]",
".",
"css",
"(",
"this",
".",
"helperPositions",
"[",
"this",
".",
"_updateHelperPos",
".",
"_j",
"]",
")",
";",
"}",
"this",
".",
"updateHelperPosFrame",
"=",
"Garnish",
".",
"requestAnimationFrame",
"(",
"this",
".",
"updateHelperPosProxy",
")",
";",
"}"
] | Update Helper Position | [
"Update",
"Helper",
"Position"
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L2012-L2038 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function(i) {
return {
left: this.getHelperTargetX() + (this.settings.helperSpacingX * i),
top: this.getHelperTargetY() + (this.settings.helperSpacingY * i)
};
} | javascript | function(i) {
return {
left: this.getHelperTargetX() + (this.settings.helperSpacingX * i),
top: this.getHelperTargetY() + (this.settings.helperSpacingY * i)
};
} | [
"function",
"(",
"i",
")",
"{",
"return",
"{",
"left",
":",
"this",
".",
"getHelperTargetX",
"(",
")",
"+",
"(",
"this",
".",
"settings",
".",
"helperSpacingX",
"*",
"i",
")",
",",
"top",
":",
"this",
".",
"getHelperTargetY",
"(",
")",
"+",
"(",
"this",
".",
"settings",
".",
"helperSpacingY",
"*",
"i",
")",
"}",
";",
"}"
] | Get the helper position for a draggee helper | [
"Get",
"the",
"helper",
"position",
"for",
"a",
"draggee",
"helper"
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L2043-L2048 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function() {
for (var i = 0; i < this.helpers.length; i++) {
(function($draggeeHelper) {
$draggeeHelper.velocity('fadeOut', {
duration: Garnish.FX_DURATION,
complete: function() {
$draggeeHelper.remove();
}
});
})(this.helpers[i]);
}
} | javascript | function() {
for (var i = 0; i < this.helpers.length; i++) {
(function($draggeeHelper) {
$draggeeHelper.velocity('fadeOut', {
duration: Garnish.FX_DURATION,
complete: function() {
$draggeeHelper.remove();
}
});
})(this.helpers[i]);
}
} | [
"function",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"helpers",
".",
"length",
";",
"i",
"++",
")",
"{",
"(",
"function",
"(",
"$draggeeHelper",
")",
"{",
"$draggeeHelper",
".",
"velocity",
"(",
"'fadeOut'",
",",
"{",
"duration",
":",
"Garnish",
".",
"FX_DURATION",
",",
"complete",
":",
"function",
"(",
")",
"{",
"$draggeeHelper",
".",
"remove",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
")",
"(",
"this",
".",
"helpers",
"[",
"i",
"]",
")",
";",
"}",
"}"
] | Fade Out Helpers | [
"Fade",
"Out",
"Helpers"
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L2185-L2196 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function(bodyContents) {
// Cleanup
this.$main.html('');
if (this.$header) {
this.$hud.removeClass('has-header');
this.$header.remove();
this.$header = null;
}
if (this.$footer) {
this.$hud.removeClass('has-footer');
this.$footer.remove();
this.$footer = null;
}
// Append the new body contents
this.$main.append(bodyContents);
// Look for a header and footer
var $header = this.$main.find('.' + this.settings.headerClass + ':first'),
$footer = this.$main.find('.' + this.settings.footerClass + ':first');
if ($header.length) {
this.$header = $header.insertBefore(this.$mainContainer);
this.$hud.addClass('has-header');
}
if ($footer.length) {
this.$footer = $footer.insertAfter(this.$mainContainer);
this.$hud.addClass('has-footer');
}
} | javascript | function(bodyContents) {
// Cleanup
this.$main.html('');
if (this.$header) {
this.$hud.removeClass('has-header');
this.$header.remove();
this.$header = null;
}
if (this.$footer) {
this.$hud.removeClass('has-footer');
this.$footer.remove();
this.$footer = null;
}
// Append the new body contents
this.$main.append(bodyContents);
// Look for a header and footer
var $header = this.$main.find('.' + this.settings.headerClass + ':first'),
$footer = this.$main.find('.' + this.settings.footerClass + ':first');
if ($header.length) {
this.$header = $header.insertBefore(this.$mainContainer);
this.$hud.addClass('has-header');
}
if ($footer.length) {
this.$footer = $footer.insertAfter(this.$mainContainer);
this.$hud.addClass('has-footer');
}
} | [
"function",
"(",
"bodyContents",
")",
"{",
"this",
".",
"$main",
".",
"html",
"(",
"''",
")",
";",
"if",
"(",
"this",
".",
"$header",
")",
"{",
"this",
".",
"$hud",
".",
"removeClass",
"(",
"'has-header'",
")",
";",
"this",
".",
"$header",
".",
"remove",
"(",
")",
";",
"this",
".",
"$header",
"=",
"null",
";",
"}",
"if",
"(",
"this",
".",
"$footer",
")",
"{",
"this",
".",
"$hud",
".",
"removeClass",
"(",
"'has-footer'",
")",
";",
"this",
".",
"$footer",
".",
"remove",
"(",
")",
";",
"this",
".",
"$footer",
"=",
"null",
";",
"}",
"this",
".",
"$main",
".",
"append",
"(",
"bodyContents",
")",
";",
"var",
"$header",
"=",
"this",
".",
"$main",
".",
"find",
"(",
"'.'",
"+",
"this",
".",
"settings",
".",
"headerClass",
"+",
"':first'",
")",
",",
"$footer",
"=",
"this",
".",
"$main",
".",
"find",
"(",
"'.'",
"+",
"this",
".",
"settings",
".",
"footerClass",
"+",
"':first'",
")",
";",
"if",
"(",
"$header",
".",
"length",
")",
"{",
"this",
".",
"$header",
"=",
"$header",
".",
"insertBefore",
"(",
"this",
".",
"$mainContainer",
")",
";",
"this",
".",
"$hud",
".",
"addClass",
"(",
"'has-header'",
")",
";",
"}",
"if",
"(",
"$footer",
".",
"length",
")",
"{",
"this",
".",
"$footer",
"=",
"$footer",
".",
"insertAfter",
"(",
"this",
".",
"$mainContainer",
")",
";",
"this",
".",
"$hud",
".",
"addClass",
"(",
"'has-footer'",
")",
";",
"}",
"}"
] | Update the body contents | [
"Update",
"the",
"body",
"contents"
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L2850-L2882 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function($item, preventScroll) {
if (preventScroll) {
var scrollLeft = Garnish.$doc.scrollLeft(),
scrollTop = Garnish.$doc.scrollTop();
$item.focus();
window.scrollTo(scrollLeft, scrollTop);
}
else {
$item.focus();
}
this.$focusedItem = $item;
this.trigger('focusItem', {item: $item});
} | javascript | function($item, preventScroll) {
if (preventScroll) {
var scrollLeft = Garnish.$doc.scrollLeft(),
scrollTop = Garnish.$doc.scrollTop();
$item.focus();
window.scrollTo(scrollLeft, scrollTop);
}
else {
$item.focus();
}
this.$focusedItem = $item;
this.trigger('focusItem', {item: $item});
} | [
"function",
"(",
"$item",
",",
"preventScroll",
")",
"{",
"if",
"(",
"preventScroll",
")",
"{",
"var",
"scrollLeft",
"=",
"Garnish",
".",
"$doc",
".",
"scrollLeft",
"(",
")",
",",
"scrollTop",
"=",
"Garnish",
".",
"$doc",
".",
"scrollTop",
"(",
")",
";",
"$item",
".",
"focus",
"(",
")",
";",
"window",
".",
"scrollTo",
"(",
"scrollLeft",
",",
"scrollTop",
")",
";",
"}",
"else",
"{",
"$item",
".",
"focus",
"(",
")",
";",
"}",
"this",
".",
"$focusedItem",
"=",
"$item",
";",
"this",
".",
"trigger",
"(",
"'focusItem'",
",",
"{",
"item",
":",
"$item",
"}",
")",
";",
"}"
] | Sets the focus on an item. | [
"Sets",
"the",
"focus",
"on",
"an",
"item",
"."
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L5390-L5403 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function(ev) {
// ignore right clicks
if (ev.which !== Garnish.PRIMARY_CLICK) {
return;
}
// Enfore the filter
if (this.settings.filter && !$(ev.target).is(this.settings.filter)) {
return;
}
var $item = $($.data(ev.currentTarget, 'select-item'));
// was this a click?
if (
!this._actAsCheckbox(ev) && !ev.shiftKey &&
ev.currentTarget === this.mousedownTarget
) {
// If this is already selected, wait a moment to see if this is a double click before making any rash decisions
if (this.isSelected($item)) {
this.clearMouseUpTimeout();
this.mouseUpTimeout = setTimeout($.proxy(function() {
this.deselectOthers($item);
}, this), 300);
}
else {
this.deselectAll();
this.selectItem($item, true, true);
}
}
} | javascript | function(ev) {
// ignore right clicks
if (ev.which !== Garnish.PRIMARY_CLICK) {
return;
}
// Enfore the filter
if (this.settings.filter && !$(ev.target).is(this.settings.filter)) {
return;
}
var $item = $($.data(ev.currentTarget, 'select-item'));
// was this a click?
if (
!this._actAsCheckbox(ev) && !ev.shiftKey &&
ev.currentTarget === this.mousedownTarget
) {
// If this is already selected, wait a moment to see if this is a double click before making any rash decisions
if (this.isSelected($item)) {
this.clearMouseUpTimeout();
this.mouseUpTimeout = setTimeout($.proxy(function() {
this.deselectOthers($item);
}, this), 300);
}
else {
this.deselectAll();
this.selectItem($item, true, true);
}
}
} | [
"function",
"(",
"ev",
")",
"{",
"if",
"(",
"ev",
".",
"which",
"!==",
"Garnish",
".",
"PRIMARY_CLICK",
")",
"{",
"return",
";",
"}",
"if",
"(",
"this",
".",
"settings",
".",
"filter",
"&&",
"!",
"$",
"(",
"ev",
".",
"target",
")",
".",
"is",
"(",
"this",
".",
"settings",
".",
"filter",
")",
")",
"{",
"return",
";",
"}",
"var",
"$item",
"=",
"$",
"(",
"$",
".",
"data",
"(",
"ev",
".",
"currentTarget",
",",
"'select-item'",
")",
")",
";",
"if",
"(",
"!",
"this",
".",
"_actAsCheckbox",
"(",
"ev",
")",
"&&",
"!",
"ev",
".",
"shiftKey",
"&&",
"ev",
".",
"currentTarget",
"===",
"this",
".",
"mousedownTarget",
")",
"{",
"if",
"(",
"this",
".",
"isSelected",
"(",
"$item",
")",
")",
"{",
"this",
".",
"clearMouseUpTimeout",
"(",
")",
";",
"this",
".",
"mouseUpTimeout",
"=",
"setTimeout",
"(",
"$",
".",
"proxy",
"(",
"function",
"(",
")",
"{",
"this",
".",
"deselectOthers",
"(",
"$item",
")",
";",
"}",
",",
"this",
")",
",",
"300",
")",
";",
"}",
"else",
"{",
"this",
".",
"deselectAll",
"(",
")",
";",
"this",
".",
"selectItem",
"(",
"$item",
",",
"true",
",",
"true",
")",
";",
"}",
"}",
"}"
] | On Mouse Up | [
"On",
"Mouse",
"Up"
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L5454-L5485 | train |
|
pixelandtonic/garnishjs | dist/garnish.js | function(item) {
var $handle = $.data(item, 'select-handle');
if ($handle) {
$handle.removeData('select-item');
this.removeAllListeners($handle);
}
$.removeData(item, 'select');
$.removeData(item, 'select-handle');
if (this.$focusedItem && this.$focusedItem[0] === item) {
this.$focusedItem = null;
}
} | javascript | function(item) {
var $handle = $.data(item, 'select-handle');
if ($handle) {
$handle.removeData('select-item');
this.removeAllListeners($handle);
}
$.removeData(item, 'select');
$.removeData(item, 'select-handle');
if (this.$focusedItem && this.$focusedItem[0] === item) {
this.$focusedItem = null;
}
} | [
"function",
"(",
"item",
")",
"{",
"var",
"$handle",
"=",
"$",
".",
"data",
"(",
"item",
",",
"'select-handle'",
")",
";",
"if",
"(",
"$handle",
")",
"{",
"$handle",
".",
"removeData",
"(",
"'select-item'",
")",
";",
"this",
".",
"removeAllListeners",
"(",
"$handle",
")",
";",
"}",
"$",
".",
"removeData",
"(",
"item",
",",
"'select'",
")",
";",
"$",
".",
"removeData",
"(",
"item",
",",
"'select-handle'",
")",
";",
"if",
"(",
"this",
".",
"$focusedItem",
"&&",
"this",
".",
"$focusedItem",
"[",
"0",
"]",
"===",
"item",
")",
"{",
"this",
".",
"$focusedItem",
"=",
"null",
";",
"}",
"}"
] | Deinitialize an item. | [
"Deinitialize",
"an",
"item",
"."
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/dist/garnish.js#L5716-L5730 | train |
|
contentful/contentful-extension-cli | lib/command/update.js | loadCurrentVersion | function loadCurrentVersion (options, context) {
return new Extension(options, context).read()
.then(function (response) {
let version = response.sys.version;
options.version = version;
return options;
});
} | javascript | function loadCurrentVersion (options, context) {
return new Extension(options, context).read()
.then(function (response) {
let version = response.sys.version;
options.version = version;
return options;
});
} | [
"function",
"loadCurrentVersion",
"(",
"options",
",",
"context",
")",
"{",
"return",
"new",
"Extension",
"(",
"options",
",",
"context",
")",
".",
"read",
"(",
")",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"let",
"version",
"=",
"response",
".",
"sys",
".",
"version",
";",
"options",
".",
"version",
"=",
"version",
";",
"return",
"options",
";",
"}",
")",
";",
"}"
] | GETs the extension from the server and extends `options` with the
current version. | [
"GETs",
"the",
"extension",
"from",
"the",
"server",
"and",
"extends",
"options",
"with",
"the",
"current",
"version",
"."
] | 5405485695a0e920eb30a99a43d80bdc8778b5bd | https://github.com/contentful/contentful-extension-cli/blob/5405485695a0e920eb30a99a43d80bdc8778b5bd/lib/command/update.js#L58-L66 | train |
pixelandtonic/garnishjs | gulpfile.js | function(err) {
notify.onError({
title: "Garnish",
message: "Error: <%= error.message %>",
sound: "Beep"
})(err);
console.log( 'plumber error!' );
this.emit('end');
} | javascript | function(err) {
notify.onError({
title: "Garnish",
message: "Error: <%= error.message %>",
sound: "Beep"
})(err);
console.log( 'plumber error!' );
this.emit('end');
} | [
"function",
"(",
"err",
")",
"{",
"notify",
".",
"onError",
"(",
"{",
"title",
":",
"\"Garnish\"",
",",
"message",
":",
"\"Error: <%= error.message %>\"",
",",
"sound",
":",
"\"Beep\"",
"}",
")",
"(",
"err",
")",
";",
"console",
".",
"log",
"(",
"'plumber error!'",
")",
";",
"this",
".",
"emit",
"(",
"'end'",
")",
";",
"}"
] | error notification settings for plumber | [
"error",
"notification",
"settings",
"for",
"plumber"
] | 3e57331081c277eeac9a022feeadac5da3f4a2f9 | https://github.com/pixelandtonic/garnishjs/blob/3e57331081c277eeac9a022feeadac5da3f4a2f9/gulpfile.js#L28-L39 | train |
|
dylang/random-puppy | index.js | all | function all(subreddit) {
const eventEmitter = new EventEmitter();
function emitRandomImage(subreddit) {
randomPuppy(subreddit).then(imageUrl => {
eventEmitter.emit('data', imageUrl + '#' + subreddit);
if (eventEmitter.listeners('data').length) {
setTimeout(() => emitRandomImage(subreddit), 200);
}
});
}
emitRandomImage(subreddit);
return eventEmitter;
} | javascript | function all(subreddit) {
const eventEmitter = new EventEmitter();
function emitRandomImage(subreddit) {
randomPuppy(subreddit).then(imageUrl => {
eventEmitter.emit('data', imageUrl + '#' + subreddit);
if (eventEmitter.listeners('data').length) {
setTimeout(() => emitRandomImage(subreddit), 200);
}
});
}
emitRandomImage(subreddit);
return eventEmitter;
} | [
"function",
"all",
"(",
"subreddit",
")",
"{",
"const",
"eventEmitter",
"=",
"new",
"EventEmitter",
"(",
")",
";",
"function",
"emitRandomImage",
"(",
"subreddit",
")",
"{",
"randomPuppy",
"(",
"subreddit",
")",
".",
"then",
"(",
"imageUrl",
"=>",
"{",
"eventEmitter",
".",
"emit",
"(",
"'data'",
",",
"imageUrl",
"+",
"'#'",
"+",
"subreddit",
")",
";",
"if",
"(",
"eventEmitter",
".",
"listeners",
"(",
"'data'",
")",
".",
"length",
")",
"{",
"setTimeout",
"(",
"(",
")",
"=>",
"emitRandomImage",
"(",
"subreddit",
")",
",",
"200",
")",
";",
"}",
"}",
")",
";",
"}",
"emitRandomImage",
"(",
"subreddit",
")",
";",
"return",
"eventEmitter",
";",
"}"
] | silly feature to play with observables | [
"silly",
"feature",
"to",
"play",
"with",
"observables"
] | cf003bea00816ae03fd368bbeb7d3fbab6f2002b | https://github.com/dylang/random-puppy/blob/cf003bea00816ae03fd368bbeb7d3fbab6f2002b/index.js#L37-L51 | train |
punkave/mongo-dump-stream | index.js | function(dbOrUri, stream, callback) {
if (arguments.length === 2) {
callback = stream;
stream = undefined;
}
if (!stream) {
stream = process.stdout;
}
var db;
var out = stream;
var endOfCollection = crypto.pseudoRandomBytes(8).toString('base64');
write({
type: 'mongo-dump-stream',
version: '2',
endOfCollection: endOfCollection
});
return async.series({
connect: function(callback) {
if (typeof(dbOrUri) !== 'string') {
// Already a mongodb connection
db = dbOrUri;
return setImmediate(callback);
}
return mongodb.MongoClient.connect(dbOrUri, function(err, _db) {
if (err) {
return callback(err);
}
db = _db;
return callback(null);
});
},
getCollections: function(callback) {
return db.collections(function(err, _collections) {
if (err) {
return callback(err);
}
collections = _collections;
return callback(null);
});
},
dumpCollections: function(callback) {
return async.eachSeries(collections, function(collection, callback) {
if (collection.collectionName.match(/^system\./)) {
return setImmediate(callback);
}
return async.series({
getIndexes: function(callback) {
return collection.indexInformation({ full: true }, function(err, info) {
if (err) {
return callback(err);
}
write({
type: 'collection',
name: collection.collectionName,
indexes: info
});
return callback(null);
});
},
getDocuments: function(callback) {
var cursor = collection.find({}, { raw: true });
iterate();
function iterate() {
return cursor.nextObject(function(err, item) {
if (err) {
return callback(err);
}
if (!item) {
write({
// Ensures we don't confuse this with
// a legitimate database object
endOfCollection: endOfCollection
});
return callback(null);
}
// v2: just a series of actual data documents
out.write(item);
// If we didn't have the raw BSON document,
// we could do this instead, but it would be very slow
// write({
// type: 'document',
// document: item
// });
return setImmediate(iterate);
});
}
},
}, callback);
}, callback);
},
endDatabase: function(callback) {
write({
type: 'endDatabase'
}, callback);
}
}, function(err) {
if (err) {
return callback(err);
}
return callback(null);
});
function write(o, callback) {
out.write(BSON.serialize(o, false, true, false), callback);
}
} | javascript | function(dbOrUri, stream, callback) {
if (arguments.length === 2) {
callback = stream;
stream = undefined;
}
if (!stream) {
stream = process.stdout;
}
var db;
var out = stream;
var endOfCollection = crypto.pseudoRandomBytes(8).toString('base64');
write({
type: 'mongo-dump-stream',
version: '2',
endOfCollection: endOfCollection
});
return async.series({
connect: function(callback) {
if (typeof(dbOrUri) !== 'string') {
// Already a mongodb connection
db = dbOrUri;
return setImmediate(callback);
}
return mongodb.MongoClient.connect(dbOrUri, function(err, _db) {
if (err) {
return callback(err);
}
db = _db;
return callback(null);
});
},
getCollections: function(callback) {
return db.collections(function(err, _collections) {
if (err) {
return callback(err);
}
collections = _collections;
return callback(null);
});
},
dumpCollections: function(callback) {
return async.eachSeries(collections, function(collection, callback) {
if (collection.collectionName.match(/^system\./)) {
return setImmediate(callback);
}
return async.series({
getIndexes: function(callback) {
return collection.indexInformation({ full: true }, function(err, info) {
if (err) {
return callback(err);
}
write({
type: 'collection',
name: collection.collectionName,
indexes: info
});
return callback(null);
});
},
getDocuments: function(callback) {
var cursor = collection.find({}, { raw: true });
iterate();
function iterate() {
return cursor.nextObject(function(err, item) {
if (err) {
return callback(err);
}
if (!item) {
write({
// Ensures we don't confuse this with
// a legitimate database object
endOfCollection: endOfCollection
});
return callback(null);
}
// v2: just a series of actual data documents
out.write(item);
// If we didn't have the raw BSON document,
// we could do this instead, but it would be very slow
// write({
// type: 'document',
// document: item
// });
return setImmediate(iterate);
});
}
},
}, callback);
}, callback);
},
endDatabase: function(callback) {
write({
type: 'endDatabase'
}, callback);
}
}, function(err) {
if (err) {
return callback(err);
}
return callback(null);
});
function write(o, callback) {
out.write(BSON.serialize(o, false, true, false), callback);
}
} | [
"function",
"(",
"dbOrUri",
",",
"stream",
",",
"callback",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"2",
")",
"{",
"callback",
"=",
"stream",
";",
"stream",
"=",
"undefined",
";",
"}",
"if",
"(",
"!",
"stream",
")",
"{",
"stream",
"=",
"process",
".",
"stdout",
";",
"}",
"var",
"db",
";",
"var",
"out",
"=",
"stream",
";",
"var",
"endOfCollection",
"=",
"crypto",
".",
"pseudoRandomBytes",
"(",
"8",
")",
".",
"toString",
"(",
"'base64'",
")",
";",
"write",
"(",
"{",
"type",
":",
"'mongo-dump-stream'",
",",
"version",
":",
"'2'",
",",
"endOfCollection",
":",
"endOfCollection",
"}",
")",
";",
"return",
"async",
".",
"series",
"(",
"{",
"connect",
":",
"function",
"(",
"callback",
")",
"{",
"if",
"(",
"typeof",
"(",
"dbOrUri",
")",
"!==",
"'string'",
")",
"{",
"db",
"=",
"dbOrUri",
";",
"return",
"setImmediate",
"(",
"callback",
")",
";",
"}",
"return",
"mongodb",
".",
"MongoClient",
".",
"connect",
"(",
"dbOrUri",
",",
"function",
"(",
"err",
",",
"_db",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"db",
"=",
"_db",
";",
"return",
"callback",
"(",
"null",
")",
";",
"}",
")",
";",
"}",
",",
"getCollections",
":",
"function",
"(",
"callback",
")",
"{",
"return",
"db",
".",
"collections",
"(",
"function",
"(",
"err",
",",
"_collections",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"collections",
"=",
"_collections",
";",
"return",
"callback",
"(",
"null",
")",
";",
"}",
")",
";",
"}",
",",
"dumpCollections",
":",
"function",
"(",
"callback",
")",
"{",
"return",
"async",
".",
"eachSeries",
"(",
"collections",
",",
"function",
"(",
"collection",
",",
"callback",
")",
"{",
"if",
"(",
"collection",
".",
"collectionName",
".",
"match",
"(",
"/",
"^system\\.",
"/",
")",
")",
"{",
"return",
"setImmediate",
"(",
"callback",
")",
";",
"}",
"return",
"async",
".",
"series",
"(",
"{",
"getIndexes",
":",
"function",
"(",
"callback",
")",
"{",
"return",
"collection",
".",
"indexInformation",
"(",
"{",
"full",
":",
"true",
"}",
",",
"function",
"(",
"err",
",",
"info",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"write",
"(",
"{",
"type",
":",
"'collection'",
",",
"name",
":",
"collection",
".",
"collectionName",
",",
"indexes",
":",
"info",
"}",
")",
";",
"return",
"callback",
"(",
"null",
")",
";",
"}",
")",
";",
"}",
",",
"getDocuments",
":",
"function",
"(",
"callback",
")",
"{",
"var",
"cursor",
"=",
"collection",
".",
"find",
"(",
"{",
"}",
",",
"{",
"raw",
":",
"true",
"}",
")",
";",
"iterate",
"(",
")",
";",
"function",
"iterate",
"(",
")",
"{",
"return",
"cursor",
".",
"nextObject",
"(",
"function",
"(",
"err",
",",
"item",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"if",
"(",
"!",
"item",
")",
"{",
"write",
"(",
"{",
"endOfCollection",
":",
"endOfCollection",
"}",
")",
";",
"return",
"callback",
"(",
"null",
")",
";",
"}",
"out",
".",
"write",
"(",
"item",
")",
";",
"return",
"setImmediate",
"(",
"iterate",
")",
";",
"}",
")",
";",
"}",
"}",
",",
"}",
",",
"callback",
")",
";",
"}",
",",
"callback",
")",
";",
"}",
",",
"endDatabase",
":",
"function",
"(",
"callback",
")",
"{",
"write",
"(",
"{",
"type",
":",
"'endDatabase'",
"}",
",",
"callback",
")",
";",
"}",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"return",
"callback",
"(",
"null",
")",
";",
"}",
")",
";",
"function",
"write",
"(",
"o",
",",
"callback",
")",
"{",
"out",
".",
"write",
"(",
"BSON",
".",
"serialize",
"(",
"o",
",",
"false",
",",
"true",
",",
"false",
")",
",",
"callback",
")",
";",
"}",
"}"
] | If you leave out "stream" it'll be stdout | [
"If",
"you",
"leave",
"out",
"stream",
"it",
"ll",
"be",
"stdout"
] | ef0edec544ebd727b5376c8bac06f0f967a6d1c7 | https://github.com/punkave/mongo-dump-stream/blob/ef0edec544ebd727b5376c8bac06f0f967a6d1c7/index.js#L16-L122 | train |
|
wooorm/markdown-escapes | index.js | escapes | function escapes(options) {
var settings = options || {}
if (settings.commonmark) {
return commonmark
}
return settings.gfm ? gfm : defaults
} | javascript | function escapes(options) {
var settings = options || {}
if (settings.commonmark) {
return commonmark
}
return settings.gfm ? gfm : defaults
} | [
"function",
"escapes",
"(",
"options",
")",
"{",
"var",
"settings",
"=",
"options",
"||",
"{",
"}",
"if",
"(",
"settings",
".",
"commonmark",
")",
"{",
"return",
"commonmark",
"}",
"return",
"settings",
".",
"gfm",
"?",
"gfm",
":",
"defaults",
"}"
] | Get markdown escapes. | [
"Get",
"markdown",
"escapes",
"."
] | 129e65017ee4ac1eb1ed7bc2e0160ed3bbc473d8 | https://github.com/wooorm/markdown-escapes/blob/129e65017ee4ac1eb1ed7bc2e0160ed3bbc473d8/index.js#L49-L57 | train |
agirorn/node-hid-stream | lib/keyboard-parser.js | parseModifiers | function parseModifiers(packet, bits) {
/* eslint-disable no-bitwise */
/* eslint-disable no-param-reassign */
packet.modifiers.l_control = ((bits & 1) !== 0);
packet.modifiers.l_shift = ((bits & 2) !== 0);
packet.modifiers.l_alt = ((bits & 4) !== 0);
packet.modifiers.l_meta = ((bits & 8) !== 0);
packet.modifiers.r_control = ((bits & 16) !== 0);
packet.modifiers.r_shift = ((bits & 32) !== 0);
packet.modifiers.r_alt = ((bits & 64) !== 0);
packet.modifiers.r_meta = ((bits & 128) !== 0);
/* eslint-enable no-bitwise */
/* eslint-enable no-param-reassign */
} | javascript | function parseModifiers(packet, bits) {
/* eslint-disable no-bitwise */
/* eslint-disable no-param-reassign */
packet.modifiers.l_control = ((bits & 1) !== 0);
packet.modifiers.l_shift = ((bits & 2) !== 0);
packet.modifiers.l_alt = ((bits & 4) !== 0);
packet.modifiers.l_meta = ((bits & 8) !== 0);
packet.modifiers.r_control = ((bits & 16) !== 0);
packet.modifiers.r_shift = ((bits & 32) !== 0);
packet.modifiers.r_alt = ((bits & 64) !== 0);
packet.modifiers.r_meta = ((bits & 128) !== 0);
/* eslint-enable no-bitwise */
/* eslint-enable no-param-reassign */
} | [
"function",
"parseModifiers",
"(",
"packet",
",",
"bits",
")",
"{",
"packet",
".",
"modifiers",
".",
"l_control",
"=",
"(",
"(",
"bits",
"&",
"1",
")",
"!==",
"0",
")",
";",
"packet",
".",
"modifiers",
".",
"l_shift",
"=",
"(",
"(",
"bits",
"&",
"2",
")",
"!==",
"0",
")",
";",
"packet",
".",
"modifiers",
".",
"l_alt",
"=",
"(",
"(",
"bits",
"&",
"4",
")",
"!==",
"0",
")",
";",
"packet",
".",
"modifiers",
".",
"l_meta",
"=",
"(",
"(",
"bits",
"&",
"8",
")",
"!==",
"0",
")",
";",
"packet",
".",
"modifiers",
".",
"r_control",
"=",
"(",
"(",
"bits",
"&",
"16",
")",
"!==",
"0",
")",
";",
"packet",
".",
"modifiers",
".",
"r_shift",
"=",
"(",
"(",
"bits",
"&",
"32",
")",
"!==",
"0",
")",
";",
"packet",
".",
"modifiers",
".",
"r_alt",
"=",
"(",
"(",
"bits",
"&",
"64",
")",
"!==",
"0",
")",
";",
"packet",
".",
"modifiers",
".",
"r_meta",
"=",
"(",
"(",
"bits",
"&",
"128",
")",
"!==",
"0",
")",
";",
"}"
] | Convert modifier key bits into
array of human-readable identifiers | [
"Convert",
"modifier",
"key",
"bits",
"into",
"array",
"of",
"human",
"-",
"readable",
"identifiers"
] | 3cbb1e0f85fc920f83618cd6c929d811df9b230c | https://github.com/agirorn/node-hid-stream/blob/3cbb1e0f85fc920f83618cd6c929d811df9b230c/lib/keyboard-parser.js#L22-L35 | train |
agirorn/node-hid-stream | lib/keyboard-parser.js | parseKeyCodes | function parseKeyCodes(arr, keys) {
if (typeof keys !== 'object') { return false; }
keys.forEach((key) => {
if (key > 3) { arr.keyCodes.push(key); }
});
return true;
} | javascript | function parseKeyCodes(arr, keys) {
if (typeof keys !== 'object') { return false; }
keys.forEach((key) => {
if (key > 3) { arr.keyCodes.push(key); }
});
return true;
} | [
"function",
"parseKeyCodes",
"(",
"arr",
",",
"keys",
")",
"{",
"if",
"(",
"typeof",
"keys",
"!==",
"'object'",
")",
"{",
"return",
"false",
";",
"}",
"keys",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"{",
"if",
"(",
"key",
">",
"3",
")",
"{",
"arr",
".",
"keyCodes",
".",
"push",
"(",
"key",
")",
";",
"}",
"}",
")",
";",
"return",
"true",
";",
"}"
] | Slice HID keycodes into separate array | [
"Slice",
"HID",
"keycodes",
"into",
"separate",
"array"
] | 3cbb1e0f85fc920f83618cd6c929d811df9b230c | https://github.com/agirorn/node-hid-stream/blob/3cbb1e0f85fc920f83618cd6c929d811df9b230c/lib/keyboard-parser.js#L41-L49 | train |
agirorn/node-hid-stream | lib/keyboard-parser.js | parseErrorState | function parseErrorState(packet, state) {
let states = 0;
state.forEach((s) => {
if (s === 1) {
states += 1;
}
});
if (states >= 6) {
packet.errorStatus = true; // eslint-disable-line no-param-reassign
}
} | javascript | function parseErrorState(packet, state) {
let states = 0;
state.forEach((s) => {
if (s === 1) {
states += 1;
}
});
if (states >= 6) {
packet.errorStatus = true; // eslint-disable-line no-param-reassign
}
} | [
"function",
"parseErrorState",
"(",
"packet",
",",
"state",
")",
"{",
"let",
"states",
"=",
"0",
";",
"state",
".",
"forEach",
"(",
"(",
"s",
")",
"=>",
"{",
"if",
"(",
"s",
"===",
"1",
")",
"{",
"states",
"+=",
"1",
";",
"}",
"}",
")",
";",
"if",
"(",
"states",
">=",
"6",
")",
"{",
"packet",
".",
"errorStatus",
"=",
"true",
";",
"}",
"}"
] | Detect keyboard rollover error
This occurs when the user has pressed too many keys for the
particular device to handle | [
"Detect",
"keyboard",
"rollover",
"error",
"This",
"occurs",
"when",
"the",
"user",
"has",
"pressed",
"too",
"many",
"keys",
"for",
"the",
"particular",
"device",
"to",
"handle"
] | 3cbb1e0f85fc920f83618cd6c929d811df9b230c | https://github.com/agirorn/node-hid-stream/blob/3cbb1e0f85fc920f83618cd6c929d811df9b230c/lib/keyboard-parser.js#L222-L234 | train |
seanmonstar/intel | lib/record.js | stack | function stack(e) {
return {
toString: function() {
// first line is err.message, which we already show, so start from
// second line
return e.stack.substr(e.stack.indexOf('\n'));
},
toJSON: function() {
return stacktrace.parse(e);
}
};
} | javascript | function stack(e) {
return {
toString: function() {
// first line is err.message, which we already show, so start from
// second line
return e.stack.substr(e.stack.indexOf('\n'));
},
toJSON: function() {
return stacktrace.parse(e);
}
};
} | [
"function",
"stack",
"(",
"e",
")",
"{",
"return",
"{",
"toString",
":",
"function",
"(",
")",
"{",
"return",
"e",
".",
"stack",
".",
"substr",
"(",
"e",
".",
"stack",
".",
"indexOf",
"(",
"'\\n'",
")",
")",
";",
"}",
",",
"\\n",
"}",
";",
"}"
] | stack formatter helper | [
"stack",
"formatter",
"helper"
] | 65e77bc379924fef0dda1f75adc611325028381d | https://github.com/seanmonstar/intel/blob/65e77bc379924fef0dda1f75adc611325028381d/lib/record.js#L20-L31 | train |
watson/original-url | index.js | getFirstHeader | function getFirstHeader (req, header) {
const value = req.headers[header]
return (Array.isArray(value) ? value[0] : value).split(', ')[0]
} | javascript | function getFirstHeader (req, header) {
const value = req.headers[header]
return (Array.isArray(value) ? value[0] : value).split(', ')[0]
} | [
"function",
"getFirstHeader",
"(",
"req",
",",
"header",
")",
"{",
"const",
"value",
"=",
"req",
".",
"headers",
"[",
"header",
"]",
"return",
"(",
"Array",
".",
"isArray",
"(",
"value",
")",
"?",
"value",
"[",
"0",
"]",
":",
"value",
")",
".",
"split",
"(",
"', '",
")",
"[",
"0",
"]",
"}"
] | In case there's more than one header of a given name, we want the first one as it should be the one that was added by the first proxy in the chain | [
"In",
"case",
"there",
"s",
"more",
"than",
"one",
"header",
"of",
"a",
"given",
"name",
"we",
"want",
"the",
"first",
"one",
"as",
"it",
"should",
"be",
"the",
"one",
"that",
"was",
"added",
"by",
"the",
"first",
"proxy",
"in",
"the",
"chain"
] | 4447ad715030695b5a9627765e211e018e99c38c | https://github.com/watson/original-url/blob/4447ad715030695b5a9627765e211e018e99c38c/index.js#L88-L91 | train |
brunschgi/terrificjs | src/Application.js | Application | function Application(ctx, config) {
// validate params
if (!ctx && !config) {
// both empty
ctx = document;
config = {};
}
else if (Utils.isNode(config)) {
// reverse order of arguments
var tmpConfig = config;
config = ctx;
ctx = tmpConfig;
}
else if (!Utils.isNode(ctx) && !config) {
// only config is given
config = ctx;
ctx = document;
}
else if (Utils.isNode(ctx) && !config) {
// only ctx is given
config = {};
}
var defaults = {
namespace: Module
};
config = Utils.extend(defaults, config);
/**
* The context node.
*
* @property _ctx
* @type Node
*/
this._ctx = Utils.getElement(ctx);
/**
* The configuration.
*
* @property config
* @type Object
*/
this._config = config;
/**
* The sandbox to get the resources from.
* The singleton is shared between all modules.
*
* @property _sandbox
* @type Sandbox
*/
this._sandbox = new Sandbox(this);
/**
* Contains references to all modules on the page.
*
* @property _modules
* @type Object
*/
this._modules = {};
/**
* The next unique module id to use.
*
* @property id
* @type Number
*/
this._id = 1;
} | javascript | function Application(ctx, config) {
// validate params
if (!ctx && !config) {
// both empty
ctx = document;
config = {};
}
else if (Utils.isNode(config)) {
// reverse order of arguments
var tmpConfig = config;
config = ctx;
ctx = tmpConfig;
}
else if (!Utils.isNode(ctx) && !config) {
// only config is given
config = ctx;
ctx = document;
}
else if (Utils.isNode(ctx) && !config) {
// only ctx is given
config = {};
}
var defaults = {
namespace: Module
};
config = Utils.extend(defaults, config);
/**
* The context node.
*
* @property _ctx
* @type Node
*/
this._ctx = Utils.getElement(ctx);
/**
* The configuration.
*
* @property config
* @type Object
*/
this._config = config;
/**
* The sandbox to get the resources from.
* The singleton is shared between all modules.
*
* @property _sandbox
* @type Sandbox
*/
this._sandbox = new Sandbox(this);
/**
* Contains references to all modules on the page.
*
* @property _modules
* @type Object
*/
this._modules = {};
/**
* The next unique module id to use.
*
* @property id
* @type Number
*/
this._id = 1;
} | [
"function",
"Application",
"(",
"ctx",
",",
"config",
")",
"{",
"if",
"(",
"!",
"ctx",
"&&",
"!",
"config",
")",
"{",
"ctx",
"=",
"document",
";",
"config",
"=",
"{",
"}",
";",
"}",
"else",
"if",
"(",
"Utils",
".",
"isNode",
"(",
"config",
")",
")",
"{",
"var",
"tmpConfig",
"=",
"config",
";",
"config",
"=",
"ctx",
";",
"ctx",
"=",
"tmpConfig",
";",
"}",
"else",
"if",
"(",
"!",
"Utils",
".",
"isNode",
"(",
"ctx",
")",
"&&",
"!",
"config",
")",
"{",
"config",
"=",
"ctx",
";",
"ctx",
"=",
"document",
";",
"}",
"else",
"if",
"(",
"Utils",
".",
"isNode",
"(",
"ctx",
")",
"&&",
"!",
"config",
")",
"{",
"config",
"=",
"{",
"}",
";",
"}",
"var",
"defaults",
"=",
"{",
"namespace",
":",
"Module",
"}",
";",
"config",
"=",
"Utils",
".",
"extend",
"(",
"defaults",
",",
"config",
")",
";",
"this",
".",
"_ctx",
"=",
"Utils",
".",
"getElement",
"(",
"ctx",
")",
";",
"this",
".",
"_config",
"=",
"config",
";",
"this",
".",
"_sandbox",
"=",
"new",
"Sandbox",
"(",
"this",
")",
";",
"this",
".",
"_modules",
"=",
"{",
"}",
";",
"this",
".",
"_id",
"=",
"1",
";",
"}"
] | Responsible for application-wide issues such as the creation of modules.
@author Remo Brunschwiler
@namespace T
@class Application
@constructor
@param {Node} ctx
The context node
@param {Object} config
The configuration
/* global Sandbox, Utils, Module | [
"Responsible",
"for",
"application",
"-",
"wide",
"issues",
"such",
"as",
"the",
"creation",
"of",
"modules",
"."
] | 4e9055ffb99bec24b2014c9389c20682a23a209f | https://github.com/brunschgi/terrificjs/blob/4e9055ffb99bec24b2014c9389c20682a23a209f/src/Application.js#L28-L97 | train |
Zimbra-Community/js-zimbra | lib/utils/preauth.js | function (options, callback) {
LOG.debug('preauth#createPreauth called');
LOG.debug('Validating options');
try {
options = new preauthOptions.CreatePreauth().validate(options);
} catch (err) {
if (err.name === 'InvalidOption') {
LOG.error('Invalid options specified: %s', err.message);
callback(
commonErrors.InvalidOption(
undefined,
{
message: err.message
}
)
);
} else {
LOG.error('System error: %s', err.message);
callback(
commonErrors.SystemError(
undefined,
{
message: err.message
}
)
);
}
return;
}
var timestamp = options.timestamp;
if (!timestamp) {
timestamp = new Date().getTime();
}
LOG.debug('Generating preauth key');
var pakCreator = crypto.createHmac('sha1', options.key)
.setEncoding('hex');
pakCreator.write(
util.format(
'%s|%s|%s|%s',
options.byValue,
options.by,
options.expires,
timestamp
)
);
pakCreator.end();
var pak = pakCreator.read();
LOG.debug('Returning preauth key %s', pak);
callback(null, pak);
} | javascript | function (options, callback) {
LOG.debug('preauth#createPreauth called');
LOG.debug('Validating options');
try {
options = new preauthOptions.CreatePreauth().validate(options);
} catch (err) {
if (err.name === 'InvalidOption') {
LOG.error('Invalid options specified: %s', err.message);
callback(
commonErrors.InvalidOption(
undefined,
{
message: err.message
}
)
);
} else {
LOG.error('System error: %s', err.message);
callback(
commonErrors.SystemError(
undefined,
{
message: err.message
}
)
);
}
return;
}
var timestamp = options.timestamp;
if (!timestamp) {
timestamp = new Date().getTime();
}
LOG.debug('Generating preauth key');
var pakCreator = crypto.createHmac('sha1', options.key)
.setEncoding('hex');
pakCreator.write(
util.format(
'%s|%s|%s|%s',
options.byValue,
options.by,
options.expires,
timestamp
)
);
pakCreator.end();
var pak = pakCreator.read();
LOG.debug('Returning preauth key %s', pak);
callback(null, pak);
} | [
"function",
"(",
"options",
",",
"callback",
")",
"{",
"LOG",
".",
"debug",
"(",
"'preauth#createPreauth called'",
")",
";",
"LOG",
".",
"debug",
"(",
"'Validating options'",
")",
";",
"try",
"{",
"options",
"=",
"new",
"preauthOptions",
".",
"CreatePreauth",
"(",
")",
".",
"validate",
"(",
"options",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"name",
"===",
"'InvalidOption'",
")",
"{",
"LOG",
".",
"error",
"(",
"'Invalid options specified: %s'",
",",
"err",
".",
"message",
")",
";",
"callback",
"(",
"commonErrors",
".",
"InvalidOption",
"(",
"undefined",
",",
"{",
"message",
":",
"err",
".",
"message",
"}",
")",
")",
";",
"}",
"else",
"{",
"LOG",
".",
"error",
"(",
"'System error: %s'",
",",
"err",
".",
"message",
")",
";",
"callback",
"(",
"commonErrors",
".",
"SystemError",
"(",
"undefined",
",",
"{",
"message",
":",
"err",
".",
"message",
"}",
")",
")",
";",
"}",
"return",
";",
"}",
"var",
"timestamp",
"=",
"options",
".",
"timestamp",
";",
"if",
"(",
"!",
"timestamp",
")",
"{",
"timestamp",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"}",
"LOG",
".",
"debug",
"(",
"'Generating preauth key'",
")",
";",
"var",
"pakCreator",
"=",
"crypto",
".",
"createHmac",
"(",
"'sha1'",
",",
"options",
".",
"key",
")",
".",
"setEncoding",
"(",
"'hex'",
")",
";",
"pakCreator",
".",
"write",
"(",
"util",
".",
"format",
"(",
"'%s|%s|%s|%s'",
",",
"options",
".",
"byValue",
",",
"options",
".",
"by",
",",
"options",
".",
"expires",
",",
"timestamp",
")",
")",
";",
"pakCreator",
".",
"end",
"(",
")",
";",
"var",
"pak",
"=",
"pakCreator",
".",
"read",
"(",
")",
";",
"LOG",
".",
"debug",
"(",
"'Returning preauth key %s'",
",",
"pak",
")",
";",
"callback",
"(",
"null",
",",
"pak",
")",
";",
"}"
] | Create a preauth value
@param {CreatePreauthOptions} options options for createPreauth
@param {callback} callback run with optional error (see throws) and
preauth key
@throws {InvalidOptionError}
@throws {SystemError} | [
"Create",
"a",
"preauth",
"value"
] | dc073847a04da093b848463942731d15d256f00d | https://github.com/Zimbra-Community/js-zimbra/blob/dc073847a04da093b848463942731d15d256f00d/lib/utils/preauth.js#L25-L97 | train |
|
NathanaelA/nativescript-liveedit | liveedit.ios.js | loadCss | function loadCss() {
var cssFileName = fs.path.join(fs.knownFolders.currentApp().path, application.cssFile);
var applicationCss;
if (FSA.fileExists(cssFileName)) {
FSA.readText(cssFileName, function (r) { applicationCss = r; });
//noinspection JSUnusedAssignment
application.cssSelectorsCache = styleScope.StyleScope.createSelectorsFromCss(applicationCss, cssFileName);
// Add New CSS to Current Page
var f = frameCommon.topmost();
if (f && f.currentPage) {
f.currentPage._resetCssValues();
f.currentPage._styleScope = new styleScope.StyleScope();
//noinspection JSUnusedAssignment
f.currentPage._addCssInternal(applicationCss, cssFileName);
f.currentPage._refreshCss();
}
}
} | javascript | function loadCss() {
var cssFileName = fs.path.join(fs.knownFolders.currentApp().path, application.cssFile);
var applicationCss;
if (FSA.fileExists(cssFileName)) {
FSA.readText(cssFileName, function (r) { applicationCss = r; });
//noinspection JSUnusedAssignment
application.cssSelectorsCache = styleScope.StyleScope.createSelectorsFromCss(applicationCss, cssFileName);
// Add New CSS to Current Page
var f = frameCommon.topmost();
if (f && f.currentPage) {
f.currentPage._resetCssValues();
f.currentPage._styleScope = new styleScope.StyleScope();
//noinspection JSUnusedAssignment
f.currentPage._addCssInternal(applicationCss, cssFileName);
f.currentPage._refreshCss();
}
}
} | [
"function",
"loadCss",
"(",
")",
"{",
"var",
"cssFileName",
"=",
"fs",
".",
"path",
".",
"join",
"(",
"fs",
".",
"knownFolders",
".",
"currentApp",
"(",
")",
".",
"path",
",",
"application",
".",
"cssFile",
")",
";",
"var",
"applicationCss",
";",
"if",
"(",
"FSA",
".",
"fileExists",
"(",
"cssFileName",
")",
")",
"{",
"FSA",
".",
"readText",
"(",
"cssFileName",
",",
"function",
"(",
"r",
")",
"{",
"applicationCss",
"=",
"r",
";",
"}",
")",
";",
"application",
".",
"cssSelectorsCache",
"=",
"styleScope",
".",
"StyleScope",
".",
"createSelectorsFromCss",
"(",
"applicationCss",
",",
"cssFileName",
")",
";",
"var",
"f",
"=",
"frameCommon",
".",
"topmost",
"(",
")",
";",
"if",
"(",
"f",
"&&",
"f",
".",
"currentPage",
")",
"{",
"f",
".",
"currentPage",
".",
"_resetCssValues",
"(",
")",
";",
"f",
".",
"currentPage",
".",
"_styleScope",
"=",
"new",
"styleScope",
".",
"StyleScope",
"(",
")",
";",
"f",
".",
"currentPage",
".",
"_addCssInternal",
"(",
"applicationCss",
",",
"cssFileName",
")",
";",
"f",
".",
"currentPage",
".",
"_refreshCss",
"(",
")",
";",
"}",
"}",
"}"
] | This is the loadCss helper function to replace the one on Application | [
"This",
"is",
"the",
"loadCss",
"helper",
"function",
"to",
"replace",
"the",
"one",
"on",
"Application"
] | 40fc852012d36f08d10669d4a79fc7a260a1618d | https://github.com/NathanaelA/nativescript-liveedit/blob/40fc852012d36f08d10669d4a79fc7a260a1618d/liveedit.ios.js#L354-L373 | train |
NathanaelA/nativescript-liveedit | liveedit.ios.js | loadPageCss | function loadPageCss(cssFile) {
var cssFileName;
// Eliminate the ./ on the file if present so that we can add the full path
if (cssFile.startsWith("./")) {
cssFile = cssFile.substring(2);
}
if (cssFile.startsWith(UpdaterSingleton.currentAppPath())) {
cssFileName = cssFile;
} else {
cssFileName = fs.path.join(UpdaterSingleton.currentAppPath(), cssFile);
}
var applicationCss;
if (FSA.fileExists(cssFileName)) {
FSA.readText(cssFileName, function (r) { applicationCss = r; });
// Add New CSS to Current Page
var f = frameCommon.topmost();
if (f && f.currentPage) {
f.currentPage._resetCssValues();
f.currentPage._styleScope = new styleScope.StyleScope();
//noinspection JSUnusedAssignment
f.currentPage._addCssInternal(applicationCss, cssFileName);
f.currentPage._refreshCss();
}
}
} | javascript | function loadPageCss(cssFile) {
var cssFileName;
// Eliminate the ./ on the file if present so that we can add the full path
if (cssFile.startsWith("./")) {
cssFile = cssFile.substring(2);
}
if (cssFile.startsWith(UpdaterSingleton.currentAppPath())) {
cssFileName = cssFile;
} else {
cssFileName = fs.path.join(UpdaterSingleton.currentAppPath(), cssFile);
}
var applicationCss;
if (FSA.fileExists(cssFileName)) {
FSA.readText(cssFileName, function (r) { applicationCss = r; });
// Add New CSS to Current Page
var f = frameCommon.topmost();
if (f && f.currentPage) {
f.currentPage._resetCssValues();
f.currentPage._styleScope = new styleScope.StyleScope();
//noinspection JSUnusedAssignment
f.currentPage._addCssInternal(applicationCss, cssFileName);
f.currentPage._refreshCss();
}
}
} | [
"function",
"loadPageCss",
"(",
"cssFile",
")",
"{",
"var",
"cssFileName",
";",
"if",
"(",
"cssFile",
".",
"startsWith",
"(",
"\"./\"",
")",
")",
"{",
"cssFile",
"=",
"cssFile",
".",
"substring",
"(",
"2",
")",
";",
"}",
"if",
"(",
"cssFile",
".",
"startsWith",
"(",
"UpdaterSingleton",
".",
"currentAppPath",
"(",
")",
")",
")",
"{",
"cssFileName",
"=",
"cssFile",
";",
"}",
"else",
"{",
"cssFileName",
"=",
"fs",
".",
"path",
".",
"join",
"(",
"UpdaterSingleton",
".",
"currentAppPath",
"(",
")",
",",
"cssFile",
")",
";",
"}",
"var",
"applicationCss",
";",
"if",
"(",
"FSA",
".",
"fileExists",
"(",
"cssFileName",
")",
")",
"{",
"FSA",
".",
"readText",
"(",
"cssFileName",
",",
"function",
"(",
"r",
")",
"{",
"applicationCss",
"=",
"r",
";",
"}",
")",
";",
"var",
"f",
"=",
"frameCommon",
".",
"topmost",
"(",
")",
";",
"if",
"(",
"f",
"&&",
"f",
".",
"currentPage",
")",
"{",
"f",
".",
"currentPage",
".",
"_resetCssValues",
"(",
")",
";",
"f",
".",
"currentPage",
".",
"_styleScope",
"=",
"new",
"styleScope",
".",
"StyleScope",
"(",
")",
";",
"f",
".",
"currentPage",
".",
"_addCssInternal",
"(",
"applicationCss",
",",
"cssFileName",
")",
";",
"f",
".",
"currentPage",
".",
"_refreshCss",
"(",
")",
";",
"}",
"}",
"}"
] | Override a single page's css
@param cssFile | [
"Override",
"a",
"single",
"page",
"s",
"css"
] | 40fc852012d36f08d10669d4a79fc7a260a1618d | https://github.com/NathanaelA/nativescript-liveedit/blob/40fc852012d36f08d10669d4a79fc7a260a1618d/liveedit.ios.js#L379-L407 | train |
Zimbra-Community/js-zimbra | lib/api/response.js | ResponseApi | function ResponseApi(constructorOptions) {
LOG.debug('Instantiating new response object');
LOG.debug('Validating options');
try {
this.options =
new responseOptions.Constructor().validate(constructorOptions);
} catch (err) {
LOG.error('Received error: %s', err);
throw(err);
}
this.response = {};
this.isBatch = false;
this._createResponseView();
} | javascript | function ResponseApi(constructorOptions) {
LOG.debug('Instantiating new response object');
LOG.debug('Validating options');
try {
this.options =
new responseOptions.Constructor().validate(constructorOptions);
} catch (err) {
LOG.error('Received error: %s', err);
throw(err);
}
this.response = {};
this.isBatch = false;
this._createResponseView();
} | [
"function",
"ResponseApi",
"(",
"constructorOptions",
")",
"{",
"LOG",
".",
"debug",
"(",
"'Instantiating new response object'",
")",
";",
"LOG",
".",
"debug",
"(",
"'Validating options'",
")",
";",
"try",
"{",
"this",
".",
"options",
"=",
"new",
"responseOptions",
".",
"Constructor",
"(",
")",
".",
"validate",
"(",
"constructorOptions",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"LOG",
".",
"error",
"(",
"'Received error: %s'",
",",
"err",
")",
";",
"throw",
"(",
"err",
")",
";",
"}",
"this",
".",
"response",
"=",
"{",
"}",
";",
"this",
".",
"isBatch",
"=",
"false",
";",
"this",
".",
"_createResponseView",
"(",
")",
";",
"}"
] | Response-handling API
@param {ResponseConstructorOptions} constructorOptions
Options for the constructor
@constructor
@throws {NoBatchResponse}
@throws {InvalidOptionError} | [
"Response",
"-",
"handling",
"API"
] | dc073847a04da093b848463942731d15d256f00d | https://github.com/Zimbra-Community/js-zimbra/blob/dc073847a04da093b848463942731d15d256f00d/lib/api/response.js#L22-L45 | train |
lirown/graphql-custom-directive | src/index.js | wrapFieldsWithMiddleware | function wrapFieldsWithMiddleware(type, deepWrap = true, typeMet = {}) {
if (!type) {
return;
}
let fields = type._fields;
typeMet[type.name] = true;
for (let label in fields) {
let field = fields[label];
if (field && !typeMet[field.type.name]) {
if (!!field && typeof field == 'object') {
field.resolve = resolveMiddlewareWrapper(
field.resolve,
field.directives,
);
if (field.type._fields && deepWrap) {
wrapFieldsWithMiddleware(field.type, deepWrap, typeMet);
} else if (field.type.ofType && field.type.ofType._fields && deepWrap) {
let child = field.type;
while (child.ofType) {
child = child.ofType;
}
if (child._fields) {
wrapFieldsWithMiddleware(child._fields);
}
}
}
}
}
} | javascript | function wrapFieldsWithMiddleware(type, deepWrap = true, typeMet = {}) {
if (!type) {
return;
}
let fields = type._fields;
typeMet[type.name] = true;
for (let label in fields) {
let field = fields[label];
if (field && !typeMet[field.type.name]) {
if (!!field && typeof field == 'object') {
field.resolve = resolveMiddlewareWrapper(
field.resolve,
field.directives,
);
if (field.type._fields && deepWrap) {
wrapFieldsWithMiddleware(field.type, deepWrap, typeMet);
} else if (field.type.ofType && field.type.ofType._fields && deepWrap) {
let child = field.type;
while (child.ofType) {
child = child.ofType;
}
if (child._fields) {
wrapFieldsWithMiddleware(child._fields);
}
}
}
}
}
} | [
"function",
"wrapFieldsWithMiddleware",
"(",
"type",
",",
"deepWrap",
"=",
"true",
",",
"typeMet",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"!",
"type",
")",
"{",
"return",
";",
"}",
"let",
"fields",
"=",
"type",
".",
"_fields",
";",
"typeMet",
"[",
"type",
".",
"name",
"]",
"=",
"true",
";",
"for",
"(",
"let",
"label",
"in",
"fields",
")",
"{",
"let",
"field",
"=",
"fields",
"[",
"label",
"]",
";",
"if",
"(",
"field",
"&&",
"!",
"typeMet",
"[",
"field",
".",
"type",
".",
"name",
"]",
")",
"{",
"if",
"(",
"!",
"!",
"field",
"&&",
"typeof",
"field",
"==",
"'object'",
")",
"{",
"field",
".",
"resolve",
"=",
"resolveMiddlewareWrapper",
"(",
"field",
".",
"resolve",
",",
"field",
".",
"directives",
",",
")",
";",
"if",
"(",
"field",
".",
"type",
".",
"_fields",
"&&",
"deepWrap",
")",
"{",
"wrapFieldsWithMiddleware",
"(",
"field",
".",
"type",
",",
"deepWrap",
",",
"typeMet",
")",
";",
"}",
"else",
"if",
"(",
"field",
".",
"type",
".",
"ofType",
"&&",
"field",
".",
"type",
".",
"ofType",
".",
"_fields",
"&&",
"deepWrap",
")",
"{",
"let",
"child",
"=",
"field",
".",
"type",
";",
"while",
"(",
"child",
".",
"ofType",
")",
"{",
"child",
"=",
"child",
".",
"ofType",
";",
"}",
"if",
"(",
"child",
".",
"_fields",
")",
"{",
"wrapFieldsWithMiddleware",
"(",
"child",
".",
"_fields",
")",
";",
"}",
"}",
"}",
"}",
"}",
"}"
] | Scanning the shema and wrapping the resolve of each field with the support
of the graphql custom directives resolve execution | [
"Scanning",
"the",
"shema",
"and",
"wrapping",
"the",
"resolve",
"of",
"each",
"field",
"with",
"the",
"support",
"of",
"the",
"graphql",
"custom",
"directives",
"resolve",
"execution"
] | 90b5a3641fda77cd484936a1e79909938955ee09 | https://github.com/lirown/graphql-custom-directive/blob/90b5a3641fda77cd484936a1e79909938955ee09/src/index.js#L144-L173 | train |
NathanaelA/nativescript-liveedit | liveedit.android.js | reloadPage | function reloadPage(page, isModal) {
if (!LiveEditSingleton.enabled()) {
return;
}
var t = frameCommon.topmost();
if (!t) {
return;
}
if (!page) {
if (!t.currentEntry || !t.currentEntry.entry) {
return;
}
page = t.currentEntry.entry.moduleName;
if (!page) {
return;
}
}
if (LiveEditSingleton.isSuspended()) {
LiveEditSingleton._suspendedNavigate(page, isModal);
return;
}
if (isModal) {
reloadModal(page);
return;
}
var ext = "";
if (!page.endsWith(".js") && !page.endsWith(".xml")) {
ext = ".js";
}
var nextPage;
if (t._currentEntry && t._currentEntry.entry) {
nextPage = t._currentEntry.entry;
nextPage.animated = false;
} else {
nextPage = {moduleName: page, animated: false};
}
if (!nextPage.context) {
nextPage.context = {};
}
if (t._currentEntry && t._currentEntry.create) {
nextPage.create = t._currentEntry.create;
}
nextPage.context.liveSync = true;
nextPage.context.liveEdit = true;
// Disable it in the backstack
//nextPage.backstackVisible = false;
// Attempt to Go back, so that this is the one left in the queue
if (t.canGoBack()) {
//t._popFromFrameStack();
t.goBack();
} else {
nextPage.clearHistory = true;
}
// This should be before we navigate so that it is removed from the cache just before
// In case the goBack goes to the same page; we want it to return to the prior version in the cache; then
// we clear it so that we go to a new version.
__clearRequireCachedItem(LiveEditSingleton.currentAppPath() + page + ext);
__clearRequireCachedItem(LiveEditSingleton.currentAppPath() + "*" + LiveEditSingleton.currentAppPath() + page);
if (fileResolver.clearCache) {
fileResolver.clearCache();
}
// Navigate back to this page
try {
t.navigate(nextPage);
}
catch (err) {
console.log(err);
}
} | javascript | function reloadPage(page, isModal) {
if (!LiveEditSingleton.enabled()) {
return;
}
var t = frameCommon.topmost();
if (!t) {
return;
}
if (!page) {
if (!t.currentEntry || !t.currentEntry.entry) {
return;
}
page = t.currentEntry.entry.moduleName;
if (!page) {
return;
}
}
if (LiveEditSingleton.isSuspended()) {
LiveEditSingleton._suspendedNavigate(page, isModal);
return;
}
if (isModal) {
reloadModal(page);
return;
}
var ext = "";
if (!page.endsWith(".js") && !page.endsWith(".xml")) {
ext = ".js";
}
var nextPage;
if (t._currentEntry && t._currentEntry.entry) {
nextPage = t._currentEntry.entry;
nextPage.animated = false;
} else {
nextPage = {moduleName: page, animated: false};
}
if (!nextPage.context) {
nextPage.context = {};
}
if (t._currentEntry && t._currentEntry.create) {
nextPage.create = t._currentEntry.create;
}
nextPage.context.liveSync = true;
nextPage.context.liveEdit = true;
// Disable it in the backstack
//nextPage.backstackVisible = false;
// Attempt to Go back, so that this is the one left in the queue
if (t.canGoBack()) {
//t._popFromFrameStack();
t.goBack();
} else {
nextPage.clearHistory = true;
}
// This should be before we navigate so that it is removed from the cache just before
// In case the goBack goes to the same page; we want it to return to the prior version in the cache; then
// we clear it so that we go to a new version.
__clearRequireCachedItem(LiveEditSingleton.currentAppPath() + page + ext);
__clearRequireCachedItem(LiveEditSingleton.currentAppPath() + "*" + LiveEditSingleton.currentAppPath() + page);
if (fileResolver.clearCache) {
fileResolver.clearCache();
}
// Navigate back to this page
try {
t.navigate(nextPage);
}
catch (err) {
console.log(err);
}
} | [
"function",
"reloadPage",
"(",
"page",
",",
"isModal",
")",
"{",
"if",
"(",
"!",
"LiveEditSingleton",
".",
"enabled",
"(",
")",
")",
"{",
"return",
";",
"}",
"var",
"t",
"=",
"frameCommon",
".",
"topmost",
"(",
")",
";",
"if",
"(",
"!",
"t",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"page",
")",
"{",
"if",
"(",
"!",
"t",
".",
"currentEntry",
"||",
"!",
"t",
".",
"currentEntry",
".",
"entry",
")",
"{",
"return",
";",
"}",
"page",
"=",
"t",
".",
"currentEntry",
".",
"entry",
".",
"moduleName",
";",
"if",
"(",
"!",
"page",
")",
"{",
"return",
";",
"}",
"}",
"if",
"(",
"LiveEditSingleton",
".",
"isSuspended",
"(",
")",
")",
"{",
"LiveEditSingleton",
".",
"_suspendedNavigate",
"(",
"page",
",",
"isModal",
")",
";",
"return",
";",
"}",
"if",
"(",
"isModal",
")",
"{",
"reloadModal",
"(",
"page",
")",
";",
"return",
";",
"}",
"var",
"ext",
"=",
"\"\"",
";",
"if",
"(",
"!",
"page",
".",
"endsWith",
"(",
"\".js\"",
")",
"&&",
"!",
"page",
".",
"endsWith",
"(",
"\".xml\"",
")",
")",
"{",
"ext",
"=",
"\".js\"",
";",
"}",
"var",
"nextPage",
";",
"if",
"(",
"t",
".",
"_currentEntry",
"&&",
"t",
".",
"_currentEntry",
".",
"entry",
")",
"{",
"nextPage",
"=",
"t",
".",
"_currentEntry",
".",
"entry",
";",
"nextPage",
".",
"animated",
"=",
"false",
";",
"}",
"else",
"{",
"nextPage",
"=",
"{",
"moduleName",
":",
"page",
",",
"animated",
":",
"false",
"}",
";",
"}",
"if",
"(",
"!",
"nextPage",
".",
"context",
")",
"{",
"nextPage",
".",
"context",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"t",
".",
"_currentEntry",
"&&",
"t",
".",
"_currentEntry",
".",
"create",
")",
"{",
"nextPage",
".",
"create",
"=",
"t",
".",
"_currentEntry",
".",
"create",
";",
"}",
"nextPage",
".",
"context",
".",
"liveSync",
"=",
"true",
";",
"nextPage",
".",
"context",
".",
"liveEdit",
"=",
"true",
";",
"if",
"(",
"t",
".",
"canGoBack",
"(",
")",
")",
"{",
"t",
".",
"goBack",
"(",
")",
";",
"}",
"else",
"{",
"nextPage",
".",
"clearHistory",
"=",
"true",
";",
"}",
"__clearRequireCachedItem",
"(",
"LiveEditSingleton",
".",
"currentAppPath",
"(",
")",
"+",
"page",
"+",
"ext",
")",
";",
"__clearRequireCachedItem",
"(",
"LiveEditSingleton",
".",
"currentAppPath",
"(",
")",
"+",
"\"*\"",
"+",
"LiveEditSingleton",
".",
"currentAppPath",
"(",
")",
"+",
"page",
")",
";",
"if",
"(",
"fileResolver",
".",
"clearCache",
")",
"{",
"fileResolver",
".",
"clearCache",
"(",
")",
";",
"}",
"try",
"{",
"t",
".",
"navigate",
"(",
"nextPage",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"err",
")",
";",
"}",
"}"
] | This is a helper function to reload the current page
@param page | [
"This",
"is",
"a",
"helper",
"function",
"to",
"reload",
"the",
"current",
"page"
] | 40fc852012d36f08d10669d4a79fc7a260a1618d | https://github.com/NathanaelA/nativescript-liveedit/blob/40fc852012d36f08d10669d4a79fc7a260a1618d/liveedit.android.js#L789-L873 | train |
NathanaelA/nativescript-liveedit | support/watcher.js | isWatching | function isWatching(fileName) {
for (var i=0;i<watching.length;i++) {
if (fileName.endsWith(watching[i])) {
return true;
}
}
//noinspection RedundantIfStatementJS
if (fileName.toLowerCase().lastIndexOf("restart.livesync") === (fileName.length - 16)) {
return true;
}
//noinspection RedundantIfStatementJS
if (fileName.toLowerCase().lastIndexOf("restart.liveedit") === (fileName.length - 16)) {
return true;
}
return false;
} | javascript | function isWatching(fileName) {
for (var i=0;i<watching.length;i++) {
if (fileName.endsWith(watching[i])) {
return true;
}
}
//noinspection RedundantIfStatementJS
if (fileName.toLowerCase().lastIndexOf("restart.livesync") === (fileName.length - 16)) {
return true;
}
//noinspection RedundantIfStatementJS
if (fileName.toLowerCase().lastIndexOf("restart.liveedit") === (fileName.length - 16)) {
return true;
}
return false;
} | [
"function",
"isWatching",
"(",
"fileName",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"watching",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"fileName",
".",
"endsWith",
"(",
"watching",
"[",
"i",
"]",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"if",
"(",
"fileName",
".",
"toLowerCase",
"(",
")",
".",
"lastIndexOf",
"(",
"\"restart.livesync\"",
")",
"===",
"(",
"fileName",
".",
"length",
"-",
"16",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"fileName",
".",
"toLowerCase",
"(",
")",
".",
"lastIndexOf",
"(",
"\"restart.liveedit\"",
")",
"===",
"(",
"fileName",
".",
"length",
"-",
"16",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | isWatching - will respond true if watching this file type.
@param fileName
@returns {boolean} | [
"isWatching",
"-",
"will",
"respond",
"true",
"if",
"watching",
"this",
"file",
"type",
"."
] | 40fc852012d36f08d10669d4a79fc7a260a1618d | https://github.com/NathanaelA/nativescript-liveedit/blob/40fc852012d36f08d10669d4a79fc7a260a1618d/support/watcher.js#L206-L221 | train |
NathanaelA/nativescript-liveedit | support/watcher.js | normalPushADB | function normalPushADB(fileName, options, callback) {
if (typeof options === "function") {
callback = options;
options = null;
}
var srcFile = fileName;
if (options && typeof options.srcFile === "string") {
srcFile = options.srcFile;
}
var check = false;
if (options && options.check) {
check = true;
}
var quiet = false;
if (options && options.quiet) {
quiet = true;
}
var path = "/data/data/" + projectData.nativescript.id + "/files/" + fileName;
cp.exec('adb push "'+srcFile+'" "' + path + '"', {timeout: 10000}, function(err, sout, serr) {
if (err) {
if (sout.indexOf('Permission denied') > 0) { pushADB = backupPushADB; console.log("Using backup method for updates!"); }
if (serr.indexOf('Permission denied') > 0) { pushADB = backupPushADB; console.log("Using backup method for updates!"); }
if (check !== true) {
console.log("Failed to Push to Device: ", fileName);
console.log(err);
//console.log(sout);
//console.log(serr);
}
} else if (check !== true && quiet === false ) {
console.log("Pushed to Device: ", fileName);
}
if (callback) {
callback(err);
}
});
} | javascript | function normalPushADB(fileName, options, callback) {
if (typeof options === "function") {
callback = options;
options = null;
}
var srcFile = fileName;
if (options && typeof options.srcFile === "string") {
srcFile = options.srcFile;
}
var check = false;
if (options && options.check) {
check = true;
}
var quiet = false;
if (options && options.quiet) {
quiet = true;
}
var path = "/data/data/" + projectData.nativescript.id + "/files/" + fileName;
cp.exec('adb push "'+srcFile+'" "' + path + '"', {timeout: 10000}, function(err, sout, serr) {
if (err) {
if (sout.indexOf('Permission denied') > 0) { pushADB = backupPushADB; console.log("Using backup method for updates!"); }
if (serr.indexOf('Permission denied') > 0) { pushADB = backupPushADB; console.log("Using backup method for updates!"); }
if (check !== true) {
console.log("Failed to Push to Device: ", fileName);
console.log(err);
//console.log(sout);
//console.log(serr);
}
} else if (check !== true && quiet === false ) {
console.log("Pushed to Device: ", fileName);
}
if (callback) {
callback(err);
}
});
} | [
"function",
"normalPushADB",
"(",
"fileName",
",",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"options",
"===",
"\"function\"",
")",
"{",
"callback",
"=",
"options",
";",
"options",
"=",
"null",
";",
"}",
"var",
"srcFile",
"=",
"fileName",
";",
"if",
"(",
"options",
"&&",
"typeof",
"options",
".",
"srcFile",
"===",
"\"string\"",
")",
"{",
"srcFile",
"=",
"options",
".",
"srcFile",
";",
"}",
"var",
"check",
"=",
"false",
";",
"if",
"(",
"options",
"&&",
"options",
".",
"check",
")",
"{",
"check",
"=",
"true",
";",
"}",
"var",
"quiet",
"=",
"false",
";",
"if",
"(",
"options",
"&&",
"options",
".",
"quiet",
")",
"{",
"quiet",
"=",
"true",
";",
"}",
"var",
"path",
"=",
"\"/data/data/\"",
"+",
"projectData",
".",
"nativescript",
".",
"id",
"+",
"\"/files/\"",
"+",
"fileName",
";",
"cp",
".",
"exec",
"(",
"'adb push \"'",
"+",
"srcFile",
"+",
"'\" \"'",
"+",
"path",
"+",
"'\"'",
",",
"{",
"timeout",
":",
"10000",
"}",
",",
"function",
"(",
"err",
",",
"sout",
",",
"serr",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"sout",
".",
"indexOf",
"(",
"'Permission denied'",
")",
">",
"0",
")",
"{",
"pushADB",
"=",
"backupPushADB",
";",
"console",
".",
"log",
"(",
"\"Using backup method for updates!\"",
")",
";",
"}",
"if",
"(",
"serr",
".",
"indexOf",
"(",
"'Permission denied'",
")",
">",
"0",
")",
"{",
"pushADB",
"=",
"backupPushADB",
";",
"console",
".",
"log",
"(",
"\"Using backup method for updates!\"",
")",
";",
"}",
"if",
"(",
"check",
"!==",
"true",
")",
"{",
"console",
".",
"log",
"(",
"\"Failed to Push to Device: \"",
",",
"fileName",
")",
";",
"console",
".",
"log",
"(",
"err",
")",
";",
"}",
"}",
"else",
"if",
"(",
"check",
"!==",
"true",
"&&",
"quiet",
"===",
"false",
")",
"{",
"console",
".",
"log",
"(",
"\"Pushed to Device: \"",
",",
"fileName",
")",
";",
"}",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}"
] | This runs the adb command so that we can push the file up to the emulator or device
@param fileName
@param options
@param callback | [
"This",
"runs",
"the",
"adb",
"command",
"so",
"that",
"we",
"can",
"push",
"the",
"file",
"up",
"to",
"the",
"emulator",
"or",
"device"
] | 40fc852012d36f08d10669d4a79fc7a260a1618d | https://github.com/NathanaelA/nativescript-liveedit/blob/40fc852012d36f08d10669d4a79fc7a260a1618d/support/watcher.js#L329-L367 | train |
NathanaelA/nativescript-liveedit | support/watcher.js | getWatcher | function getWatcher(dir) {
return function (event, fileName) {
if (event === "rename") {
verifyWatches();
if (fileName) {
if (!fs.existsSync(dir + fileName)) { return; }
var dirStat;
try {
dirStat = fs.statSync(dir + fileName);
} catch (err) {
// This means the File disappeared out from under me...
return;
}
if (dirStat.isDirectory()) {
if (!watchingFolders[dir + fileName]) {
console.log("Adding new directory to watch: ", dir + fileName);
setupWatchers(dir + fileName);
}
return;
}
} else {
checkForChangedFolders(dir);
}
return;
}
if (!fileName) {
fileName = checkForChangedFiles(dir);
if (fileName) {
checkCache(fileName);
}
}
else {
if (isWatching(fileName)) {
if (!fs.existsSync(dir + fileName)) {
return;
}
var stat;
try {
stat = fs.statSync(dir + fileName);
}
catch (e) {
// This means the file disappeared between exists and stat...
return;
}
if (stat.size === 0) { return; }
if (timeStamps[dir + fileName] === undefined || timeStamps[dir + fileName] !== stat.mtime.getTime()) {
//console.log("Found 2: ", event, dir+fileName, stat.mtime.getTime(), stat.mtime, stat.ctime.getTime(), stat.size);
timeStamps[dir + fileName] = stat.mtime.getTime();
checkCache(dir + fileName);
}
}
}
};
} | javascript | function getWatcher(dir) {
return function (event, fileName) {
if (event === "rename") {
verifyWatches();
if (fileName) {
if (!fs.existsSync(dir + fileName)) { return; }
var dirStat;
try {
dirStat = fs.statSync(dir + fileName);
} catch (err) {
// This means the File disappeared out from under me...
return;
}
if (dirStat.isDirectory()) {
if (!watchingFolders[dir + fileName]) {
console.log("Adding new directory to watch: ", dir + fileName);
setupWatchers(dir + fileName);
}
return;
}
} else {
checkForChangedFolders(dir);
}
return;
}
if (!fileName) {
fileName = checkForChangedFiles(dir);
if (fileName) {
checkCache(fileName);
}
}
else {
if (isWatching(fileName)) {
if (!fs.existsSync(dir + fileName)) {
return;
}
var stat;
try {
stat = fs.statSync(dir + fileName);
}
catch (e) {
// This means the file disappeared between exists and stat...
return;
}
if (stat.size === 0) { return; }
if (timeStamps[dir + fileName] === undefined || timeStamps[dir + fileName] !== stat.mtime.getTime()) {
//console.log("Found 2: ", event, dir+fileName, stat.mtime.getTime(), stat.mtime, stat.ctime.getTime(), stat.size);
timeStamps[dir + fileName] = stat.mtime.getTime();
checkCache(dir + fileName);
}
}
}
};
} | [
"function",
"getWatcher",
"(",
"dir",
")",
"{",
"return",
"function",
"(",
"event",
",",
"fileName",
")",
"{",
"if",
"(",
"event",
"===",
"\"rename\"",
")",
"{",
"verifyWatches",
"(",
")",
";",
"if",
"(",
"fileName",
")",
"{",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"dir",
"+",
"fileName",
")",
")",
"{",
"return",
";",
"}",
"var",
"dirStat",
";",
"try",
"{",
"dirStat",
"=",
"fs",
".",
"statSync",
"(",
"dir",
"+",
"fileName",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
";",
"}",
"if",
"(",
"dirStat",
".",
"isDirectory",
"(",
")",
")",
"{",
"if",
"(",
"!",
"watchingFolders",
"[",
"dir",
"+",
"fileName",
"]",
")",
"{",
"console",
".",
"log",
"(",
"\"Adding new directory to watch: \"",
",",
"dir",
"+",
"fileName",
")",
";",
"setupWatchers",
"(",
"dir",
"+",
"fileName",
")",
";",
"}",
"return",
";",
"}",
"}",
"else",
"{",
"checkForChangedFolders",
"(",
"dir",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"!",
"fileName",
")",
"{",
"fileName",
"=",
"checkForChangedFiles",
"(",
"dir",
")",
";",
"if",
"(",
"fileName",
")",
"{",
"checkCache",
"(",
"fileName",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"isWatching",
"(",
"fileName",
")",
")",
"{",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"dir",
"+",
"fileName",
")",
")",
"{",
"return",
";",
"}",
"var",
"stat",
";",
"try",
"{",
"stat",
"=",
"fs",
".",
"statSync",
"(",
"dir",
"+",
"fileName",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
";",
"}",
"if",
"(",
"stat",
".",
"size",
"===",
"0",
")",
"{",
"return",
";",
"}",
"if",
"(",
"timeStamps",
"[",
"dir",
"+",
"fileName",
"]",
"===",
"undefined",
"||",
"timeStamps",
"[",
"dir",
"+",
"fileName",
"]",
"!==",
"stat",
".",
"mtime",
".",
"getTime",
"(",
")",
")",
"{",
"timeStamps",
"[",
"dir",
"+",
"fileName",
"]",
"=",
"stat",
".",
"mtime",
".",
"getTime",
"(",
")",
";",
"checkCache",
"(",
"dir",
"+",
"fileName",
")",
";",
"}",
"}",
"}",
"}",
";",
"}"
] | This is the watcher callback to verify the file actually changed
@param dir
@returns {Function} | [
"This",
"is",
"the",
"watcher",
"callback",
"to",
"verify",
"the",
"file",
"actually",
"changed"
] | 40fc852012d36f08d10669d4a79fc7a260a1618d | https://github.com/NathanaelA/nativescript-liveedit/blob/40fc852012d36f08d10669d4a79fc7a260a1618d/support/watcher.js#L616-L673 | train |
NathanaelA/nativescript-liveedit | support/watcher.js | setupWatchers | function setupWatchers(path) {
// We want to track the watchers now and return if we are already watching this folder
if (watchingFolders[path]) { return; }
watchingFolders[path] = fs.watch(path, getWatcher(path + "/"));
watchingFolders[path].on('error', function() { verifyWatches(); });
var fileList = fs.readdirSync(path);
var stats;
for (var i = 0; i < fileList.length; i++) {
try {
stats = fs.statSync(path + "/" + fileList[i]);
}
catch (e) {
continue;
}
if (isWatching(fileList[i])) {
timeStamps[path + "/" + fileList[i]] = stats.mtime.getTime();
} else {
if (stats.isDirectory()) {
if (fileList[i] === "node_modules") {
watchingFolders[path + "/" + fileList[i]] = true;
continue;
}
if (fileList[i] === "tns_modules") {
watchingFolders[path + "/" + fileList[i]] = true;
continue;
}
if (fileList[i] === "App_Resources") {
watchingFolders[path + "/" + fileList[i]] = true;
continue;
}
setupWatchers(path + "/" + fileList[i]);
}
}
}
} | javascript | function setupWatchers(path) {
// We want to track the watchers now and return if we are already watching this folder
if (watchingFolders[path]) { return; }
watchingFolders[path] = fs.watch(path, getWatcher(path + "/"));
watchingFolders[path].on('error', function() { verifyWatches(); });
var fileList = fs.readdirSync(path);
var stats;
for (var i = 0; i < fileList.length; i++) {
try {
stats = fs.statSync(path + "/" + fileList[i]);
}
catch (e) {
continue;
}
if (isWatching(fileList[i])) {
timeStamps[path + "/" + fileList[i]] = stats.mtime.getTime();
} else {
if (stats.isDirectory()) {
if (fileList[i] === "node_modules") {
watchingFolders[path + "/" + fileList[i]] = true;
continue;
}
if (fileList[i] === "tns_modules") {
watchingFolders[path + "/" + fileList[i]] = true;
continue;
}
if (fileList[i] === "App_Resources") {
watchingFolders[path + "/" + fileList[i]] = true;
continue;
}
setupWatchers(path + "/" + fileList[i]);
}
}
}
} | [
"function",
"setupWatchers",
"(",
"path",
")",
"{",
"if",
"(",
"watchingFolders",
"[",
"path",
"]",
")",
"{",
"return",
";",
"}",
"watchingFolders",
"[",
"path",
"]",
"=",
"fs",
".",
"watch",
"(",
"path",
",",
"getWatcher",
"(",
"path",
"+",
"\"/\"",
")",
")",
";",
"watchingFolders",
"[",
"path",
"]",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
")",
"{",
"verifyWatches",
"(",
")",
";",
"}",
")",
";",
"var",
"fileList",
"=",
"fs",
".",
"readdirSync",
"(",
"path",
")",
";",
"var",
"stats",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"fileList",
".",
"length",
";",
"i",
"++",
")",
"{",
"try",
"{",
"stats",
"=",
"fs",
".",
"statSync",
"(",
"path",
"+",
"\"/\"",
"+",
"fileList",
"[",
"i",
"]",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"isWatching",
"(",
"fileList",
"[",
"i",
"]",
")",
")",
"{",
"timeStamps",
"[",
"path",
"+",
"\"/\"",
"+",
"fileList",
"[",
"i",
"]",
"]",
"=",
"stats",
".",
"mtime",
".",
"getTime",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"if",
"(",
"fileList",
"[",
"i",
"]",
"===",
"\"node_modules\"",
")",
"{",
"watchingFolders",
"[",
"path",
"+",
"\"/\"",
"+",
"fileList",
"[",
"i",
"]",
"]",
"=",
"true",
";",
"continue",
";",
"}",
"if",
"(",
"fileList",
"[",
"i",
"]",
"===",
"\"tns_modules\"",
")",
"{",
"watchingFolders",
"[",
"path",
"+",
"\"/\"",
"+",
"fileList",
"[",
"i",
"]",
"]",
"=",
"true",
";",
"continue",
";",
"}",
"if",
"(",
"fileList",
"[",
"i",
"]",
"===",
"\"App_Resources\"",
")",
"{",
"watchingFolders",
"[",
"path",
"+",
"\"/\"",
"+",
"fileList",
"[",
"i",
"]",
"]",
"=",
"true",
";",
"continue",
";",
"}",
"setupWatchers",
"(",
"path",
"+",
"\"/\"",
"+",
"fileList",
"[",
"i",
"]",
")",
";",
"}",
"}",
"}",
"}"
] | This setups a watcher on a directory
@param path | [
"This",
"setups",
"a",
"watcher",
"on",
"a",
"directory"
] | 40fc852012d36f08d10669d4a79fc7a260a1618d | https://github.com/NathanaelA/nativescript-liveedit/blob/40fc852012d36f08d10669d4a79fc7a260a1618d/support/watcher.js#L679-L714 | train |
Zimbra-Community/js-zimbra | lib/api/communication.js | CommunicationApi | function CommunicationApi(constructorOptions) {
LOG.debug('Instantiating communication API');
LOG.debug('Validating constructor options');
// Sanitize option eventually throwing an InvalidOption
try {
this.options =
new communicationOptions.Constructor().validate(constructorOptions);
} catch (err) {
throw(
err
);
}
if (this.options.token !== '') {
LOG.debug('Setting predefined token');
this.token = this.options.token;
} else {
this.token = null;
}
} | javascript | function CommunicationApi(constructorOptions) {
LOG.debug('Instantiating communication API');
LOG.debug('Validating constructor options');
// Sanitize option eventually throwing an InvalidOption
try {
this.options =
new communicationOptions.Constructor().validate(constructorOptions);
} catch (err) {
throw(
err
);
}
if (this.options.token !== '') {
LOG.debug('Setting predefined token');
this.token = this.options.token;
} else {
this.token = null;
}
} | [
"function",
"CommunicationApi",
"(",
"constructorOptions",
")",
"{",
"LOG",
".",
"debug",
"(",
"'Instantiating communication API'",
")",
";",
"LOG",
".",
"debug",
"(",
"'Validating constructor options'",
")",
";",
"try",
"{",
"this",
".",
"options",
"=",
"new",
"communicationOptions",
".",
"Constructor",
"(",
")",
".",
"validate",
"(",
"constructorOptions",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"throw",
"(",
"err",
")",
";",
"}",
"if",
"(",
"this",
".",
"options",
".",
"token",
"!==",
"''",
")",
"{",
"LOG",
".",
"debug",
"(",
"'Setting predefined token'",
")",
";",
"this",
".",
"token",
"=",
"this",
".",
"options",
".",
"token",
";",
"}",
"else",
"{",
"this",
".",
"token",
"=",
"null",
";",
"}",
"}"
] | Communications-Handling API
@param {CommunicationConstructorOptions} constructorOptions
Options for constructor
@constructor
@throws {InvalidOptionError} | [
"Communications",
"-",
"Handling",
"API"
] | dc073847a04da093b848463942731d15d256f00d | https://github.com/Zimbra-Community/js-zimbra/blob/dc073847a04da093b848463942731d15d256f00d/lib/api/communication.js#L27-L59 | train |
Zimbra-Community/js-zimbra | lib/api/request.js | RequestApi | function RequestApi(constructorOptions) {
LOG.debug('Instantiating new Request object');
LOG.debug('Validating options');
try {
this.options =
new requestOptions.Constructor().validate(constructorOptions);
} catch (err) {
LOG.error('Received error: %s', err);
throw(
err
);
}
this.requests = [];
this.batchId = 1;
} | javascript | function RequestApi(constructorOptions) {
LOG.debug('Instantiating new Request object');
LOG.debug('Validating options');
try {
this.options =
new requestOptions.Constructor().validate(constructorOptions);
} catch (err) {
LOG.error('Received error: %s', err);
throw(
err
);
}
this.requests = [];
this.batchId = 1;
} | [
"function",
"RequestApi",
"(",
"constructorOptions",
")",
"{",
"LOG",
".",
"debug",
"(",
"'Instantiating new Request object'",
")",
";",
"LOG",
".",
"debug",
"(",
"'Validating options'",
")",
";",
"try",
"{",
"this",
".",
"options",
"=",
"new",
"requestOptions",
".",
"Constructor",
"(",
")",
".",
"validate",
"(",
"constructorOptions",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"LOG",
".",
"error",
"(",
"'Received error: %s'",
",",
"err",
")",
";",
"throw",
"(",
"err",
")",
";",
"}",
"this",
".",
"requests",
"=",
"[",
"]",
";",
"this",
".",
"batchId",
"=",
"1",
";",
"}"
] | Request-handling API
@param {ResponseConstructorOptions} Options for the
constructor
@constructor
@throws {InvalidOptionError} | [
"Request",
"-",
"handling",
"API"
] | dc073847a04da093b848463942731d15d256f00d | https://github.com/Zimbra-Community/js-zimbra/blob/dc073847a04da093b848463942731d15d256f00d/lib/api/request.js#L23-L46 | train |
fent/node-torrent | lib/hasher.js | round | function round(num, dec) {
var pow = Math.pow(10, dec);
return Math.round(num * pow) / pow;
} | javascript | function round(num, dec) {
var pow = Math.pow(10, dec);
return Math.round(num * pow) / pow;
} | [
"function",
"round",
"(",
"num",
",",
"dec",
")",
"{",
"var",
"pow",
"=",
"Math",
".",
"pow",
"(",
"10",
",",
"dec",
")",
";",
"return",
"Math",
".",
"round",
"(",
"num",
"*",
"pow",
")",
"/",
"pow",
";",
"}"
] | Rounds a number to given decimal place.
@param {Number} num
@param {Number} dec
@return {Number} | [
"Rounds",
"a",
"number",
"to",
"given",
"decimal",
"place",
"."
] | a6784b78867d3f026a54c0445abf2e18dc82323c | https://github.com/fent/node-torrent/blob/a6784b78867d3f026a54c0445abf2e18dc82323c/lib/hasher.js#L38-L41 | train |
c9/vfs-http-adapter | restful.js | jsonEncoder | function jsonEncoder(input, path) {
var output = new Stream();
output.readable = true;
var first = true;
input.on("data", function (entry) {
if (path) {
entry.href = path + entry.name;
var mime = entry.linkStat ? entry.linkStat.mime : entry.mime;
if (mime && mime.match(/(directory|folder)$/)) {
entry.href += "/";
}
}
if (first) {
output.emit("data", "[\n " + JSON.stringify(entry));
first = false;
} else {
output.emit("data", ",\n " + JSON.stringify(entry));
}
});
input.on("end", function () {
if (first) output.emit("data", "[]");
else output.emit("data", "\n]");
output.emit("end");
});
if (input.pause) {
output.pause = function () {
input.pause();
};
}
if (input.resume) {
output.resume = function () {
input.resume();
};
}
return output;
} | javascript | function jsonEncoder(input, path) {
var output = new Stream();
output.readable = true;
var first = true;
input.on("data", function (entry) {
if (path) {
entry.href = path + entry.name;
var mime = entry.linkStat ? entry.linkStat.mime : entry.mime;
if (mime && mime.match(/(directory|folder)$/)) {
entry.href += "/";
}
}
if (first) {
output.emit("data", "[\n " + JSON.stringify(entry));
first = false;
} else {
output.emit("data", ",\n " + JSON.stringify(entry));
}
});
input.on("end", function () {
if (first) output.emit("data", "[]");
else output.emit("data", "\n]");
output.emit("end");
});
if (input.pause) {
output.pause = function () {
input.pause();
};
}
if (input.resume) {
output.resume = function () {
input.resume();
};
}
return output;
} | [
"function",
"jsonEncoder",
"(",
"input",
",",
"path",
")",
"{",
"var",
"output",
"=",
"new",
"Stream",
"(",
")",
";",
"output",
".",
"readable",
"=",
"true",
";",
"var",
"first",
"=",
"true",
";",
"input",
".",
"on",
"(",
"\"data\"",
",",
"function",
"(",
"entry",
")",
"{",
"if",
"(",
"path",
")",
"{",
"entry",
".",
"href",
"=",
"path",
"+",
"entry",
".",
"name",
";",
"var",
"mime",
"=",
"entry",
".",
"linkStat",
"?",
"entry",
".",
"linkStat",
".",
"mime",
":",
"entry",
".",
"mime",
";",
"if",
"(",
"mime",
"&&",
"mime",
".",
"match",
"(",
"/",
"(directory|folder)$",
"/",
")",
")",
"{",
"entry",
".",
"href",
"+=",
"\"/\"",
";",
"}",
"}",
"if",
"(",
"first",
")",
"{",
"output",
".",
"emit",
"(",
"\"data\"",
",",
"\"[\\n \"",
"+",
"\\n",
")",
";",
"JSON",
".",
"stringify",
"(",
"entry",
")",
"}",
"else",
"first",
"=",
"false",
";",
"}",
")",
";",
"{",
"output",
".",
"emit",
"(",
"\"data\"",
",",
"\",\\n \"",
"+",
"\\n",
")",
";",
"}",
"JSON",
".",
"stringify",
"(",
"entry",
")",
"input",
".",
"on",
"(",
"\"end\"",
",",
"function",
"(",
")",
"{",
"if",
"(",
"first",
")",
"output",
".",
"emit",
"(",
"\"data\"",
",",
"\"[]\"",
")",
";",
"else",
"output",
".",
"emit",
"(",
"\"data\"",
",",
"\"\\n]\"",
")",
";",
"\\n",
"}",
")",
";",
"output",
".",
"emit",
"(",
"\"end\"",
")",
";",
"}"
] | Returns a json stream that wraps input object stream | [
"Returns",
"a",
"json",
"stream",
"that",
"wraps",
"input",
"object",
"stream"
] | 89b1253e0f10c0a2edacd9a69d99cb20f95bfa73 | https://github.com/c9/vfs-http-adapter/blob/89b1253e0f10c0a2edacd9a69d99cb20f95bfa73/restful.js#L26-L61 | train |
TheRusskiy/pusher-redux | lib/pusher-redux.js | function (options) {
var result = {
type: options.actionType
};
if (options.channelName) {
result.channel = options.channelName
}
if (options.eventName) {
result.event = options.eventName
}
if (options.data) {
result.data = options.data
}
if (options.additionalParams) {
result.additionalParams = options.additionalParams
}
return result;
} | javascript | function (options) {
var result = {
type: options.actionType
};
if (options.channelName) {
result.channel = options.channelName
}
if (options.eventName) {
result.event = options.eventName
}
if (options.data) {
result.data = options.data
}
if (options.additionalParams) {
result.additionalParams = options.additionalParams
}
return result;
} | [
"function",
"(",
"options",
")",
"{",
"var",
"result",
"=",
"{",
"type",
":",
"options",
".",
"actionType",
"}",
";",
"if",
"(",
"options",
".",
"channelName",
")",
"{",
"result",
".",
"channel",
"=",
"options",
".",
"channelName",
"}",
"if",
"(",
"options",
".",
"eventName",
")",
"{",
"result",
".",
"event",
"=",
"options",
".",
"eventName",
"}",
"if",
"(",
"options",
".",
"data",
")",
"{",
"result",
".",
"data",
"=",
"options",
".",
"data",
"}",
"if",
"(",
"options",
".",
"additionalParams",
")",
"{",
"result",
".",
"additionalParams",
"=",
"options",
".",
"additionalParams",
"}",
"return",
"result",
";",
"}"
] | create redux action | [
"create",
"redux",
"action"
] | 683a9c3cbdea0d8f0b29f547250c4ab6468bddd6 | https://github.com/TheRusskiy/pusher-redux/blob/683a9c3cbdea0d8f0b29f547250c4ab6468bddd6/lib/pusher-redux.js#L23-L40 | train |
|
cozy/cozy-emails | client/plugins/keyboard/js/mousetrap.js | _characterFromEvent | function _characterFromEvent(e) {
// for keypress events we should return the character as is
if (e.type == 'keypress') {
var character = String.fromCharCode(e.which);
// if the shift key is not pressed then it is safe to assume
// that we want the character to be lowercase. this means if
// you accidentally have caps lock on then your key bindings
// will continue to work
//
// the only side effect that might not be desired is if you
// bind something like 'A' cause you want to trigger an
// event when capital A is pressed caps lock will no longer
// trigger the event. shift+a will though.
if (!e.shiftKey) {
character = character.toLowerCase();
}
return character;
}
// for non keypress events the special maps are needed
if (_MAP[e.which]) {
return _MAP[e.which];
}
if (_KEYCODE_MAP[e.which]) {
return _KEYCODE_MAP[e.which];
}
// if it is not in the special map
// with keydown and keyup events the character seems to always
// come in as an uppercase character whether you are pressing shift
// or not. we should make sure it is always lowercase for comparisons
return String.fromCharCode(e.which).toLowerCase();
} | javascript | function _characterFromEvent(e) {
// for keypress events we should return the character as is
if (e.type == 'keypress') {
var character = String.fromCharCode(e.which);
// if the shift key is not pressed then it is safe to assume
// that we want the character to be lowercase. this means if
// you accidentally have caps lock on then your key bindings
// will continue to work
//
// the only side effect that might not be desired is if you
// bind something like 'A' cause you want to trigger an
// event when capital A is pressed caps lock will no longer
// trigger the event. shift+a will though.
if (!e.shiftKey) {
character = character.toLowerCase();
}
return character;
}
// for non keypress events the special maps are needed
if (_MAP[e.which]) {
return _MAP[e.which];
}
if (_KEYCODE_MAP[e.which]) {
return _KEYCODE_MAP[e.which];
}
// if it is not in the special map
// with keydown and keyup events the character seems to always
// come in as an uppercase character whether you are pressing shift
// or not. we should make sure it is always lowercase for comparisons
return String.fromCharCode(e.which).toLowerCase();
} | [
"function",
"_characterFromEvent",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"type",
"==",
"'keypress'",
")",
"{",
"var",
"character",
"=",
"String",
".",
"fromCharCode",
"(",
"e",
".",
"which",
")",
";",
"if",
"(",
"!",
"e",
".",
"shiftKey",
")",
"{",
"character",
"=",
"character",
".",
"toLowerCase",
"(",
")",
";",
"}",
"return",
"character",
";",
"}",
"if",
"(",
"_MAP",
"[",
"e",
".",
"which",
"]",
")",
"{",
"return",
"_MAP",
"[",
"e",
".",
"which",
"]",
";",
"}",
"if",
"(",
"_KEYCODE_MAP",
"[",
"e",
".",
"which",
"]",
")",
"{",
"return",
"_KEYCODE_MAP",
"[",
"e",
".",
"which",
"]",
";",
"}",
"return",
"String",
".",
"fromCharCode",
"(",
"e",
".",
"which",
")",
".",
"toLowerCase",
"(",
")",
";",
"}"
] | takes the event and returns the key character
@param {Event} e
@return {string} | [
"takes",
"the",
"event",
"and",
"returns",
"the",
"key",
"character"
] | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/plugins/keyboard/js/mousetrap.js#L180-L217 | train |
cozy/cozy-emails | client/plugins/keyboard/js/mousetrap.js | _eventModifiers | function _eventModifiers(e) {
var modifiers = [];
if (e.shiftKey) {
modifiers.push('shift');
}
if (e.altKey) {
modifiers.push('alt');
}
if (e.ctrlKey) {
modifiers.push('ctrl');
}
if (e.metaKey) {
modifiers.push('meta');
}
return modifiers;
} | javascript | function _eventModifiers(e) {
var modifiers = [];
if (e.shiftKey) {
modifiers.push('shift');
}
if (e.altKey) {
modifiers.push('alt');
}
if (e.ctrlKey) {
modifiers.push('ctrl');
}
if (e.metaKey) {
modifiers.push('meta');
}
return modifiers;
} | [
"function",
"_eventModifiers",
"(",
"e",
")",
"{",
"var",
"modifiers",
"=",
"[",
"]",
";",
"if",
"(",
"e",
".",
"shiftKey",
")",
"{",
"modifiers",
".",
"push",
"(",
"'shift'",
")",
";",
"}",
"if",
"(",
"e",
".",
"altKey",
")",
"{",
"modifiers",
".",
"push",
"(",
"'alt'",
")",
";",
"}",
"if",
"(",
"e",
".",
"ctrlKey",
")",
"{",
"modifiers",
".",
"push",
"(",
"'ctrl'",
")",
";",
"}",
"if",
"(",
"e",
".",
"metaKey",
")",
"{",
"modifiers",
".",
"push",
"(",
"'meta'",
")",
";",
"}",
"return",
"modifiers",
";",
"}"
] | takes a key event and figures out what the modifiers are
@param {Event} e
@returns {Array} | [
"takes",
"a",
"key",
"event",
"and",
"figures",
"out",
"what",
"the",
"modifiers",
"are"
] | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/plugins/keyboard/js/mousetrap.js#L236-L256 | train |
cozy/cozy-emails | client/plugins/keyboard/js/mousetrap.js | _pickBestAction | function _pickBestAction(key, modifiers, action) {
// if no action was picked in we should try to pick the one
// that we think would work best for this key
if (!action) {
action = _getReverseMap()[key] ? 'keydown' : 'keypress';
}
// modifier keys don't work as expected with keypress,
// switch to keydown
if (action == 'keypress' && modifiers.length) {
action = 'keydown';
}
return action;
} | javascript | function _pickBestAction(key, modifiers, action) {
// if no action was picked in we should try to pick the one
// that we think would work best for this key
if (!action) {
action = _getReverseMap()[key] ? 'keydown' : 'keypress';
}
// modifier keys don't work as expected with keypress,
// switch to keydown
if (action == 'keypress' && modifiers.length) {
action = 'keydown';
}
return action;
} | [
"function",
"_pickBestAction",
"(",
"key",
",",
"modifiers",
",",
"action",
")",
"{",
"if",
"(",
"!",
"action",
")",
"{",
"action",
"=",
"_getReverseMap",
"(",
")",
"[",
"key",
"]",
"?",
"'keydown'",
":",
"'keypress'",
";",
"}",
"if",
"(",
"action",
"==",
"'keypress'",
"&&",
"modifiers",
".",
"length",
")",
"{",
"action",
"=",
"'keydown'",
";",
"}",
"return",
"action",
";",
"}"
] | picks the best action based on the key combination
@param {string} key - character for key
@param {Array} modifiers
@param {string=} action passed in | [
"picks",
"the",
"best",
"action",
"based",
"on",
"the",
"key",
"combination"
] | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/plugins/keyboard/js/mousetrap.js#L330-L345 | train |
cozy/cozy-emails | client/plugins/keyboard/js/mousetrap.js | _resetSequences | function _resetSequences(doNotReset) {
doNotReset = doNotReset || {};
var activeSequences = false,
key;
for (key in _sequenceLevels) {
if (doNotReset[key]) {
activeSequences = true;
continue;
}
_sequenceLevels[key] = 0;
}
if (!activeSequences) {
_nextExpectedAction = false;
}
} | javascript | function _resetSequences(doNotReset) {
doNotReset = doNotReset || {};
var activeSequences = false,
key;
for (key in _sequenceLevels) {
if (doNotReset[key]) {
activeSequences = true;
continue;
}
_sequenceLevels[key] = 0;
}
if (!activeSequences) {
_nextExpectedAction = false;
}
} | [
"function",
"_resetSequences",
"(",
"doNotReset",
")",
"{",
"doNotReset",
"=",
"doNotReset",
"||",
"{",
"}",
";",
"var",
"activeSequences",
"=",
"false",
",",
"key",
";",
"for",
"(",
"key",
"in",
"_sequenceLevels",
")",
"{",
"if",
"(",
"doNotReset",
"[",
"key",
"]",
")",
"{",
"activeSequences",
"=",
"true",
";",
"continue",
";",
"}",
"_sequenceLevels",
"[",
"key",
"]",
"=",
"0",
";",
"}",
"if",
"(",
"!",
"activeSequences",
")",
"{",
"_nextExpectedAction",
"=",
"false",
";",
"}",
"}"
] | resets all sequence counters except for the ones passed in
@param {Object} doNotReset
@returns void | [
"resets",
"all",
"sequence",
"counters",
"except",
"for",
"the",
"ones",
"passed",
"in"
] | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/plugins/keyboard/js/mousetrap.js#L497-L514 | train |
cozy/cozy-emails | client/plugins/keyboard/js/mousetrap.js | _handleKeyEvent | function _handleKeyEvent(e) {
// normalize e.which for key events
// @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
if (typeof e.which !== 'number') {
e.which = e.keyCode;
}
var character = _characterFromEvent(e);
// no character found then stop
if (!character) {
return;
}
// need to use === for the character check because the character can be 0
if (e.type == 'keyup' && _ignoreNextKeyup === character) {
_ignoreNextKeyup = false;
return;
}
self.handleKey(character, _eventModifiers(e), e);
} | javascript | function _handleKeyEvent(e) {
// normalize e.which for key events
// @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
if (typeof e.which !== 'number') {
e.which = e.keyCode;
}
var character = _characterFromEvent(e);
// no character found then stop
if (!character) {
return;
}
// need to use === for the character check because the character can be 0
if (e.type == 'keyup' && _ignoreNextKeyup === character) {
_ignoreNextKeyup = false;
return;
}
self.handleKey(character, _eventModifiers(e), e);
} | [
"function",
"_handleKeyEvent",
"(",
"e",
")",
"{",
"if",
"(",
"typeof",
"e",
".",
"which",
"!==",
"'number'",
")",
"{",
"e",
".",
"which",
"=",
"e",
".",
"keyCode",
";",
"}",
"var",
"character",
"=",
"_characterFromEvent",
"(",
"e",
")",
";",
"if",
"(",
"!",
"character",
")",
"{",
"return",
";",
"}",
"if",
"(",
"e",
".",
"type",
"==",
"'keyup'",
"&&",
"_ignoreNextKeyup",
"===",
"character",
")",
"{",
"_ignoreNextKeyup",
"=",
"false",
";",
"return",
";",
"}",
"self",
".",
"handleKey",
"(",
"character",
",",
"_eventModifiers",
"(",
"e",
")",
",",
"e",
")",
";",
"}"
] | handles a keydown event
@param {Event} e
@returns void | [
"handles",
"a",
"keydown",
"event"
] | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/plugins/keyboard/js/mousetrap.js#L705-L727 | train |
cozy/cozy-emails | client/plugins/keyboard/js/mousetrap.js | _bindSingle | function _bindSingle(combination, callback, action, sequenceName, level) {
// store a direct mapped reference for use with Mousetrap.trigger
self._directMap[combination + ':' + action] = callback;
// make sure multiple spaces in a row become a single space
combination = combination.replace(/\s+/g, ' ');
var sequence = combination.split(' ');
var info;
// if this pattern is a sequence of keys then run through this method
// to reprocess each pattern one key at a time
if (sequence.length > 1) {
_bindSequence(combination, sequence, callback, action);
return;
}
info = _getKeyInfo(combination, action);
// make sure to initialize array if this is the first time
// a callback is added for this key
self._callbacks[info.key] = self._callbacks[info.key] || [];
// remove an existing match if there is one
_getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level);
// add this call back to the array
// if it is a sequence put it at the beginning
// if not put it at the end
//
// this is important because the way these are processed expects
// the sequence ones to come first
self._callbacks[info.key][sequenceName ? 'unshift' : 'push']({
callback: callback,
modifiers: info.modifiers,
action: info.action,
seq: sequenceName,
level: level,
combo: combination
});
} | javascript | function _bindSingle(combination, callback, action, sequenceName, level) {
// store a direct mapped reference for use with Mousetrap.trigger
self._directMap[combination + ':' + action] = callback;
// make sure multiple spaces in a row become a single space
combination = combination.replace(/\s+/g, ' ');
var sequence = combination.split(' ');
var info;
// if this pattern is a sequence of keys then run through this method
// to reprocess each pattern one key at a time
if (sequence.length > 1) {
_bindSequence(combination, sequence, callback, action);
return;
}
info = _getKeyInfo(combination, action);
// make sure to initialize array if this is the first time
// a callback is added for this key
self._callbacks[info.key] = self._callbacks[info.key] || [];
// remove an existing match if there is one
_getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level);
// add this call back to the array
// if it is a sequence put it at the beginning
// if not put it at the end
//
// this is important because the way these are processed expects
// the sequence ones to come first
self._callbacks[info.key][sequenceName ? 'unshift' : 'push']({
callback: callback,
modifiers: info.modifiers,
action: info.action,
seq: sequenceName,
level: level,
combo: combination
});
} | [
"function",
"_bindSingle",
"(",
"combination",
",",
"callback",
",",
"action",
",",
"sequenceName",
",",
"level",
")",
"{",
"self",
".",
"_directMap",
"[",
"combination",
"+",
"':'",
"+",
"action",
"]",
"=",
"callback",
";",
"combination",
"=",
"combination",
".",
"replace",
"(",
"/",
"\\s+",
"/",
"g",
",",
"' '",
")",
";",
"var",
"sequence",
"=",
"combination",
".",
"split",
"(",
"' '",
")",
";",
"var",
"info",
";",
"if",
"(",
"sequence",
".",
"length",
">",
"1",
")",
"{",
"_bindSequence",
"(",
"combination",
",",
"sequence",
",",
"callback",
",",
"action",
")",
";",
"return",
";",
"}",
"info",
"=",
"_getKeyInfo",
"(",
"combination",
",",
"action",
")",
";",
"self",
".",
"_callbacks",
"[",
"info",
".",
"key",
"]",
"=",
"self",
".",
"_callbacks",
"[",
"info",
".",
"key",
"]",
"||",
"[",
"]",
";",
"_getMatches",
"(",
"info",
".",
"key",
",",
"info",
".",
"modifiers",
",",
"{",
"type",
":",
"info",
".",
"action",
"}",
",",
"sequenceName",
",",
"combination",
",",
"level",
")",
";",
"self",
".",
"_callbacks",
"[",
"info",
".",
"key",
"]",
"[",
"sequenceName",
"?",
"'unshift'",
":",
"'push'",
"]",
"(",
"{",
"callback",
":",
"callback",
",",
"modifiers",
":",
"info",
".",
"modifiers",
",",
"action",
":",
"info",
".",
"action",
",",
"seq",
":",
"sequenceName",
",",
"level",
":",
"level",
",",
"combo",
":",
"combination",
"}",
")",
";",
"}"
] | binds a single keyboard combination
@param {string} combination
@param {Function} callback
@param {string=} action
@param {string=} sequenceName - name of sequence if part of sequence
@param {number=} level - what part of the sequence the command is
@returns void | [
"binds",
"a",
"single",
"keyboard",
"combination"
] | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/plugins/keyboard/js/mousetrap.js#L820-L861 | train |
cozy/cozy-emails | client/vendor/talkerjs-1.0.1.js | function(remoteWindow, remoteOrigin) {
this.remoteWindow = remoteWindow;
this.remoteOrigin = remoteOrigin;
this.timeout = 3000;
this.handshaken = false;
this.handshake = pinkySwearPromise();
this._id = 0;
this._queue = [];
this._sent = {};
var _this = this;
window.addEventListener('message', function(messageEvent) { _this._receiveMessage(messageEvent) }, false);
this._sendHandshake();
return this;
} | javascript | function(remoteWindow, remoteOrigin) {
this.remoteWindow = remoteWindow;
this.remoteOrigin = remoteOrigin;
this.timeout = 3000;
this.handshaken = false;
this.handshake = pinkySwearPromise();
this._id = 0;
this._queue = [];
this._sent = {};
var _this = this;
window.addEventListener('message', function(messageEvent) { _this._receiveMessage(messageEvent) }, false);
this._sendHandshake();
return this;
} | [
"function",
"(",
"remoteWindow",
",",
"remoteOrigin",
")",
"{",
"this",
".",
"remoteWindow",
"=",
"remoteWindow",
";",
"this",
".",
"remoteOrigin",
"=",
"remoteOrigin",
";",
"this",
".",
"timeout",
"=",
"3000",
";",
"this",
".",
"handshaken",
"=",
"false",
";",
"this",
".",
"handshake",
"=",
"pinkySwearPromise",
"(",
")",
";",
"this",
".",
"_id",
"=",
"0",
";",
"this",
".",
"_queue",
"=",
"[",
"]",
";",
"this",
".",
"_sent",
"=",
"{",
"}",
";",
"var",
"_this",
"=",
"this",
";",
"window",
".",
"addEventListener",
"(",
"'message'",
",",
"function",
"(",
"messageEvent",
")",
"{",
"_this",
".",
"_receiveMessage",
"(",
"messageEvent",
")",
"}",
",",
"false",
")",
";",
"this",
".",
"_sendHandshake",
"(",
")",
";",
"return",
"this",
";",
"}"
] | region Public Methods
Talker
Used to open a communication line between this window and a remote window via postMessage.
@param remoteWindow - The remote `window` object to post/receive messages to/from.
@property {Window} remoteWindow - The remote window object this Talker is communicating with
@property {string} remoteOrigin - The protocol, host, and port you expect the remote to be
@property {number} timeout - The number of milliseconds to wait before assuming no response will be received.
@property {boolean} handshaken - Whether we've received a handshake from the remote window
@property {function(Talker.Message)} onMessage - Will be called with every non-handshake, non-response message from the remote window
@property {Promise} handshake - Will be resolved when a handshake is newly established with the remote window.
@returns {Talker}
@constructor | [
"region",
"Public",
"Methods",
"Talker",
"Used",
"to",
"open",
"a",
"communication",
"line",
"between",
"this",
"window",
"and",
"a",
"remote",
"window",
"via",
"postMessage",
"."
] | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/vendor/talkerjs-1.0.1.js#L127-L143 | train |
|
natefaubion/adt.js | adt.js | function () {
var args = arguments;
var len = names.length;
if (this instanceof ctr) {
if (args.length !== len) {
throw new Error(
'Unexpected number of arguments for ' + ctr.className + ': ' +
'got ' + args.length + ', but need ' + len + '.'
);
}
var i = 0, n;
for (; n = names[i]; i++) {
this[n] = constraints[n](args[i], n, ctr);
}
} else {
return args.length < len
? partial(ctr, toArray(args))
: ctrApply(ctr, args);
}
} | javascript | function () {
var args = arguments;
var len = names.length;
if (this instanceof ctr) {
if (args.length !== len) {
throw new Error(
'Unexpected number of arguments for ' + ctr.className + ': ' +
'got ' + args.length + ', but need ' + len + '.'
);
}
var i = 0, n;
for (; n = names[i]; i++) {
this[n] = constraints[n](args[i], n, ctr);
}
} else {
return args.length < len
? partial(ctr, toArray(args))
: ctrApply(ctr, args);
}
} | [
"function",
"(",
")",
"{",
"var",
"args",
"=",
"arguments",
";",
"var",
"len",
"=",
"names",
".",
"length",
";",
"if",
"(",
"this",
"instanceof",
"ctr",
")",
"{",
"if",
"(",
"args",
".",
"length",
"!==",
"len",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unexpected number of arguments for '",
"+",
"ctr",
".",
"className",
"+",
"': '",
"+",
"'got '",
"+",
"args",
".",
"length",
"+",
"', but need '",
"+",
"len",
"+",
"'.'",
")",
";",
"}",
"var",
"i",
"=",
"0",
",",
"n",
";",
"for",
"(",
";",
"n",
"=",
"names",
"[",
"i",
"]",
";",
"i",
"++",
")",
"{",
"this",
"[",
"n",
"]",
"=",
"constraints",
"[",
"n",
"]",
"(",
"args",
"[",
"i",
"]",
",",
"n",
",",
"ctr",
")",
";",
"}",
"}",
"else",
"{",
"return",
"args",
".",
"length",
"<",
"len",
"?",
"partial",
"(",
"ctr",
",",
"toArray",
"(",
"args",
")",
")",
":",
"ctrApply",
"(",
"ctr",
",",
"args",
")",
";",
"}",
"}"
] | A record's constructor can be called without `new` and will also throw an error if called with the wrong number of arguments. Its arguments can be curried as long as it isn't called with the `new` keyword. | [
"A",
"record",
"s",
"constructor",
"can",
"be",
"called",
"without",
"new",
"and",
"will",
"also",
"throw",
"an",
"error",
"if",
"called",
"with",
"the",
"wrong",
"number",
"of",
"arguments",
".",
"Its",
"arguments",
"can",
"be",
"curried",
"as",
"long",
"as",
"it",
"isn",
"t",
"called",
"with",
"the",
"new",
"keyword",
"."
] | 0163b8ea3b3f8f3f8c6ea53c672f3a670c4ce9d6 | https://github.com/natefaubion/adt.js/blob/0163b8ea3b3f8f3f8c6ea53c672f3a670c4ce9d6/adt.js#L194-L213 | train |
|
natefaubion/adt.js | adt.js | function () {
var ctr = this.constructor;
var names = ctr.__names__;
var args = [], i = 0, n, val;
for (; n = names[i]; i++) {
val = this[n];
args[i] = val instanceof adt.__Base__
? val.clone()
: adt.nativeClone(val);
}
return ctr.apply(null, args);
} | javascript | function () {
var ctr = this.constructor;
var names = ctr.__names__;
var args = [], i = 0, n, val;
for (; n = names[i]; i++) {
val = this[n];
args[i] = val instanceof adt.__Base__
? val.clone()
: adt.nativeClone(val);
}
return ctr.apply(null, args);
} | [
"function",
"(",
")",
"{",
"var",
"ctr",
"=",
"this",
".",
"constructor",
";",
"var",
"names",
"=",
"ctr",
".",
"__names__",
";",
"var",
"args",
"=",
"[",
"]",
",",
"i",
"=",
"0",
",",
"n",
",",
"val",
";",
"for",
"(",
";",
"n",
"=",
"names",
"[",
"i",
"]",
";",
"i",
"++",
")",
"{",
"val",
"=",
"this",
"[",
"n",
"]",
";",
"args",
"[",
"i",
"]",
"=",
"val",
"instanceof",
"adt",
".",
"__Base__",
"?",
"val",
".",
"clone",
"(",
")",
":",
"adt",
".",
"nativeClone",
"(",
"val",
")",
";",
"}",
"return",
"ctr",
".",
"apply",
"(",
"null",
",",
"args",
")",
";",
"}"
] | Clones any value that is an adt.js type, delegating other JS values to `adt.nativeClone`. | [
"Clones",
"any",
"value",
"that",
"is",
"an",
"adt",
".",
"js",
"type",
"delegating",
"other",
"JS",
"values",
"to",
"adt",
".",
"nativeClone",
"."
] | 0163b8ea3b3f8f3f8c6ea53c672f3a670c4ce9d6 | https://github.com/natefaubion/adt.js/blob/0163b8ea3b3f8f3f8c6ea53c672f3a670c4ce9d6/adt.js#L268-L279 | train |
|
natefaubion/adt.js | adt.js | function (that) {
var ctr = this.constructor;
if (this === that) return true;
if (!(that instanceof ctr)) return false;
var names = ctr.__names__;
var i = 0, len = names.length;
var vala, valb, n;
for (; i < len; i++) {
n = names[i], vala = this[n], valb = that[n];
if (vala instanceof adt.__Base__) {
if (!vala.equals(valb)) return false;
} else if (!adt.nativeEquals(vala, valb)) return false;
}
return true;
} | javascript | function (that) {
var ctr = this.constructor;
if (this === that) return true;
if (!(that instanceof ctr)) return false;
var names = ctr.__names__;
var i = 0, len = names.length;
var vala, valb, n;
for (; i < len; i++) {
n = names[i], vala = this[n], valb = that[n];
if (vala instanceof adt.__Base__) {
if (!vala.equals(valb)) return false;
} else if (!adt.nativeEquals(vala, valb)) return false;
}
return true;
} | [
"function",
"(",
"that",
")",
"{",
"var",
"ctr",
"=",
"this",
".",
"constructor",
";",
"if",
"(",
"this",
"===",
"that",
")",
"return",
"true",
";",
"if",
"(",
"!",
"(",
"that",
"instanceof",
"ctr",
")",
")",
"return",
"false",
";",
"var",
"names",
"=",
"ctr",
".",
"__names__",
";",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"names",
".",
"length",
";",
"var",
"vala",
",",
"valb",
",",
"n",
";",
"for",
"(",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"n",
"=",
"names",
"[",
"i",
"]",
",",
"vala",
"=",
"this",
"[",
"n",
"]",
",",
"valb",
"=",
"that",
"[",
"n",
"]",
";",
"if",
"(",
"vala",
"instanceof",
"adt",
".",
"__Base__",
")",
"{",
"if",
"(",
"!",
"vala",
".",
"equals",
"(",
"valb",
")",
")",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"!",
"adt",
".",
"nativeEquals",
"(",
"vala",
",",
"valb",
")",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Recursively compares all adt.js types, delegating other JS values to `adt.nativeEquals`. | [
"Recursively",
"compares",
"all",
"adt",
".",
"js",
"types",
"delegating",
"other",
"JS",
"values",
"to",
"adt",
".",
"nativeEquals",
"."
] | 0163b8ea3b3f8f3f8c6ea53c672f3a670c4ce9d6 | https://github.com/natefaubion/adt.js/blob/0163b8ea3b3f8f3f8c6ea53c672f3a670c4ce9d6/adt.js#L283-L297 | train |
|
natefaubion/adt.js | adt.js | function (field) {
var ctr = this.constructor;
var names = ctr.__names__;
var constraints = ctr.__constraints__;
if (typeof field === 'number') {
if (field < 0 || field > names.length - 1) {
throw new Error('Field index out of range: ' + field);
}
field = names[field];
} else {
if (!constraints.hasOwnProperty(field)) {
throw new Error('Field name does not exist: ' + field);
}
}
return this[field];
} | javascript | function (field) {
var ctr = this.constructor;
var names = ctr.__names__;
var constraints = ctr.__constraints__;
if (typeof field === 'number') {
if (field < 0 || field > names.length - 1) {
throw new Error('Field index out of range: ' + field);
}
field = names[field];
} else {
if (!constraints.hasOwnProperty(field)) {
throw new Error('Field name does not exist: ' + field);
}
}
return this[field];
} | [
"function",
"(",
"field",
")",
"{",
"var",
"ctr",
"=",
"this",
".",
"constructor",
";",
"var",
"names",
"=",
"ctr",
".",
"__names__",
";",
"var",
"constraints",
"=",
"ctr",
".",
"__constraints__",
";",
"if",
"(",
"typeof",
"field",
"===",
"'number'",
")",
"{",
"if",
"(",
"field",
"<",
"0",
"||",
"field",
">",
"names",
".",
"length",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Field index out of range: '",
"+",
"field",
")",
";",
"}",
"field",
"=",
"names",
"[",
"field",
"]",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"constraints",
".",
"hasOwnProperty",
"(",
"field",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Field name does not exist: '",
"+",
"field",
")",
";",
"}",
"}",
"return",
"this",
"[",
"field",
"]",
";",
"}"
] | Overloaded to take either strings or numbers. Throws an error if the key can't be found. | [
"Overloaded",
"to",
"take",
"either",
"strings",
"or",
"numbers",
".",
"Throws",
"an",
"error",
"if",
"the",
"key",
"can",
"t",
"be",
"found",
"."
] | 0163b8ea3b3f8f3f8c6ea53c672f3a670c4ce9d6 | https://github.com/natefaubion/adt.js/blob/0163b8ea3b3f8f3f8c6ea53c672f3a670c4ce9d6/adt.js#L301-L316 | train |
|
natefaubion/adt.js | adt.js | addOrder | function addOrder (that) {
if (that.constructor) that = that.constructor;
that.__order__ = order++;
return that;
} | javascript | function addOrder (that) {
if (that.constructor) that = that.constructor;
that.__order__ = order++;
return that;
} | [
"function",
"addOrder",
"(",
"that",
")",
"{",
"if",
"(",
"that",
".",
"constructor",
")",
"that",
"=",
"that",
".",
"constructor",
";",
"that",
".",
"__order__",
"=",
"order",
"++",
";",
"return",
"that",
";",
"}"
] | Helper to add the order meta attribute to a type. | [
"Helper",
"to",
"add",
"the",
"order",
"meta",
"attribute",
"to",
"a",
"type",
"."
] | 0163b8ea3b3f8f3f8c6ea53c672f3a670c4ce9d6 | https://github.com/natefaubion/adt.js/blob/0163b8ea3b3f8f3f8c6ea53c672f3a670c4ce9d6/adt.js#L378-L382 | train |
wachunga/omega | r.js | makeRequire | function makeRequire(relModuleMap, enableBuildCallback, altRequire) {
var modRequire = makeContextModuleFunc(altRequire || context.require, relModuleMap, enableBuildCallback);
mixin(modRequire, {
nameToUrl: makeContextModuleFunc(context.nameToUrl, relModuleMap),
toUrl: makeContextModuleFunc(context.toUrl, relModuleMap),
defined: makeContextModuleFunc(context.requireDefined, relModuleMap),
specified: makeContextModuleFunc(context.requireSpecified, relModuleMap),
isBrowser: req.isBrowser
});
return modRequire;
} | javascript | function makeRequire(relModuleMap, enableBuildCallback, altRequire) {
var modRequire = makeContextModuleFunc(altRequire || context.require, relModuleMap, enableBuildCallback);
mixin(modRequire, {
nameToUrl: makeContextModuleFunc(context.nameToUrl, relModuleMap),
toUrl: makeContextModuleFunc(context.toUrl, relModuleMap),
defined: makeContextModuleFunc(context.requireDefined, relModuleMap),
specified: makeContextModuleFunc(context.requireSpecified, relModuleMap),
isBrowser: req.isBrowser
});
return modRequire;
} | [
"function",
"makeRequire",
"(",
"relModuleMap",
",",
"enableBuildCallback",
",",
"altRequire",
")",
"{",
"var",
"modRequire",
"=",
"makeContextModuleFunc",
"(",
"altRequire",
"||",
"context",
".",
"require",
",",
"relModuleMap",
",",
"enableBuildCallback",
")",
";",
"mixin",
"(",
"modRequire",
",",
"{",
"nameToUrl",
":",
"makeContextModuleFunc",
"(",
"context",
".",
"nameToUrl",
",",
"relModuleMap",
")",
",",
"toUrl",
":",
"makeContextModuleFunc",
"(",
"context",
".",
"toUrl",
",",
"relModuleMap",
")",
",",
"defined",
":",
"makeContextModuleFunc",
"(",
"context",
".",
"requireDefined",
",",
"relModuleMap",
")",
",",
"specified",
":",
"makeContextModuleFunc",
"(",
"context",
".",
"requireSpecified",
",",
"relModuleMap",
")",
",",
"isBrowser",
":",
"req",
".",
"isBrowser",
"}",
")",
";",
"return",
"modRequire",
";",
"}"
] | Helper function that creates a require function object to give to
modules that ask for it as a dependency. It needs to be specific
per module because of the implication of path mappings that may
need to be relative to the module name. | [
"Helper",
"function",
"that",
"creates",
"a",
"require",
"function",
"object",
"to",
"give",
"to",
"modules",
"that",
"ask",
"for",
"it",
"as",
"a",
"dependency",
".",
"It",
"needs",
"to",
"be",
"specific",
"per",
"module",
"because",
"of",
"the",
"implication",
"of",
"path",
"mappings",
"that",
"may",
"need",
"to",
"be",
"relative",
"to",
"the",
"module",
"name",
"."
] | c5ecf4ed058d2198065f17c3313b0884e8efa6a9 | https://github.com/wachunga/omega/blob/c5ecf4ed058d2198065f17c3313b0884e8efa6a9/r.js#L500-L511 | train |
wachunga/omega | r.js | makeArgCallback | function makeArgCallback(manager, i) {
return function (value) {
//Only do the work if it has not been done
//already for a dependency. Cycle breaking
//logic in forceExec could mean this function
//is called more than once for a given dependency.
if (!manager.depDone[i]) {
manager.depDone[i] = true;
manager.deps[i] = value;
manager.depCount -= 1;
if (!manager.depCount) {
//All done, execute!
execManager(manager);
}
}
};
} | javascript | function makeArgCallback(manager, i) {
return function (value) {
//Only do the work if it has not been done
//already for a dependency. Cycle breaking
//logic in forceExec could mean this function
//is called more than once for a given dependency.
if (!manager.depDone[i]) {
manager.depDone[i] = true;
manager.deps[i] = value;
manager.depCount -= 1;
if (!manager.depCount) {
//All done, execute!
execManager(manager);
}
}
};
} | [
"function",
"makeArgCallback",
"(",
"manager",
",",
"i",
")",
"{",
"return",
"function",
"(",
"value",
")",
"{",
"if",
"(",
"!",
"manager",
".",
"depDone",
"[",
"i",
"]",
")",
"{",
"manager",
".",
"depDone",
"[",
"i",
"]",
"=",
"true",
";",
"manager",
".",
"deps",
"[",
"i",
"]",
"=",
"value",
";",
"manager",
".",
"depCount",
"-=",
"1",
";",
"if",
"(",
"!",
"manager",
".",
"depCount",
")",
"{",
"execManager",
"(",
"manager",
")",
";",
"}",
"}",
"}",
";",
"}"
] | Helper that creates a callack function that is called when a dependency
is ready, and sets the i-th dependency for the manager as the
value passed to the callback generated by this function. | [
"Helper",
"that",
"creates",
"a",
"callack",
"function",
"that",
"is",
"called",
"when",
"a",
"dependency",
"is",
"ready",
"and",
"sets",
"the",
"i",
"-",
"th",
"dependency",
"for",
"the",
"manager",
"as",
"the",
"value",
"passed",
"to",
"the",
"callback",
"generated",
"by",
"this",
"function",
"."
] | c5ecf4ed058d2198065f17c3313b0884e8efa6a9 | https://github.com/wachunga/omega/blob/c5ecf4ed058d2198065f17c3313b0884e8efa6a9/r.js#L629-L645 | train |
wachunga/omega | r.js | addWait | function addWait(manager) {
if (!waiting[manager.id]) {
waiting[manager.id] = manager;
waitAry.push(manager);
context.waitCount += 1;
}
} | javascript | function addWait(manager) {
if (!waiting[manager.id]) {
waiting[manager.id] = manager;
waitAry.push(manager);
context.waitCount += 1;
}
} | [
"function",
"addWait",
"(",
"manager",
")",
"{",
"if",
"(",
"!",
"waiting",
"[",
"manager",
".",
"id",
"]",
")",
"{",
"waiting",
"[",
"manager",
".",
"id",
"]",
"=",
"manager",
";",
"waitAry",
".",
"push",
"(",
"manager",
")",
";",
"context",
".",
"waitCount",
"+=",
"1",
";",
"}",
"}"
] | Adds the manager to the waiting queue. Only fully
resolved items should be in the waiting queue. | [
"Adds",
"the",
"manager",
"to",
"the",
"waiting",
"queue",
".",
"Only",
"fully",
"resolved",
"items",
"should",
"be",
"in",
"the",
"waiting",
"queue",
"."
] | c5ecf4ed058d2198065f17c3313b0884e8efa6a9 | https://github.com/wachunga/omega/blob/c5ecf4ed058d2198065f17c3313b0884e8efa6a9/r.js#L739-L745 | train |
wachunga/omega | r.js | toAstArray | function toAstArray(ary) {
var output = [
'array',
[]
],
i, item;
for (i = 0; (item = ary[i]); i++) {
output[1].push([
'string',
item
]);
}
return output;
} | javascript | function toAstArray(ary) {
var output = [
'array',
[]
],
i, item;
for (i = 0; (item = ary[i]); i++) {
output[1].push([
'string',
item
]);
}
return output;
} | [
"function",
"toAstArray",
"(",
"ary",
")",
"{",
"var",
"output",
"=",
"[",
"'array'",
",",
"[",
"]",
"]",
",",
"i",
",",
"item",
";",
"for",
"(",
"i",
"=",
"0",
";",
"(",
"item",
"=",
"ary",
"[",
"i",
"]",
")",
";",
"i",
"++",
")",
"{",
"output",
"[",
"1",
"]",
".",
"push",
"(",
"[",
"'string'",
",",
"item",
"]",
")",
";",
"}",
"return",
"output",
";",
"}"
] | Converts a regular JS array of strings to an AST node that
represents that array.
@param {Array} ary
@param {Node} an AST node that represents an array of strings. | [
"Converts",
"a",
"regular",
"JS",
"array",
"of",
"strings",
"to",
"an",
"AST",
"node",
"that",
"represents",
"that",
"array",
"."
] | c5ecf4ed058d2198065f17c3313b0884e8efa6a9 | https://github.com/wachunga/omega/blob/c5ecf4ed058d2198065f17c3313b0884e8efa6a9/r.js#L6614-L6629 | train |
wachunga/omega | r.js | function (fileContents, fileName) {
//Uglify's ast generation removes comments, so just convert to ast,
//then back to source code to get rid of comments.
return uglify.uglify.gen_code(uglify.parser.parse(fileContents), true);
} | javascript | function (fileContents, fileName) {
//Uglify's ast generation removes comments, so just convert to ast,
//then back to source code to get rid of comments.
return uglify.uglify.gen_code(uglify.parser.parse(fileContents), true);
} | [
"function",
"(",
"fileContents",
",",
"fileName",
")",
"{",
"return",
"uglify",
".",
"uglify",
".",
"gen_code",
"(",
"uglify",
".",
"parser",
".",
"parse",
"(",
"fileContents",
")",
",",
"true",
")",
";",
"}"
] | Removes the comments from a string.
@param {String} fileContents
@param {String} fileName mostly used for informative reasons if an error.
@returns {String} a string of JS with comments removed. | [
"Removes",
"the",
"comments",
"from",
"a",
"string",
"."
] | c5ecf4ed058d2198065f17c3313b0884e8efa6a9 | https://github.com/wachunga/omega/blob/c5ecf4ed058d2198065f17c3313b0884e8efa6a9/r.js#L8262-L8266 | train |
|
wachunga/omega | r.js | makeWriteFile | function makeWriteFile(anonDefRegExp, namespaceWithDot, layer) {
function writeFile(name, contents) {
logger.trace('Saving plugin-optimized file: ' + name);
file.saveUtf8File(name, contents);
}
writeFile.asModule = function (moduleName, fileName, contents) {
writeFile(fileName,
build.toTransport(anonDefRegExp, namespaceWithDot, moduleName, fileName, contents, layer));
};
return writeFile;
} | javascript | function makeWriteFile(anonDefRegExp, namespaceWithDot, layer) {
function writeFile(name, contents) {
logger.trace('Saving plugin-optimized file: ' + name);
file.saveUtf8File(name, contents);
}
writeFile.asModule = function (moduleName, fileName, contents) {
writeFile(fileName,
build.toTransport(anonDefRegExp, namespaceWithDot, moduleName, fileName, contents, layer));
};
return writeFile;
} | [
"function",
"makeWriteFile",
"(",
"anonDefRegExp",
",",
"namespaceWithDot",
",",
"layer",
")",
"{",
"function",
"writeFile",
"(",
"name",
",",
"contents",
")",
"{",
"logger",
".",
"trace",
"(",
"'Saving plugin-optimized file: '",
"+",
"name",
")",
";",
"file",
".",
"saveUtf8File",
"(",
"name",
",",
"contents",
")",
";",
"}",
"writeFile",
".",
"asModule",
"=",
"function",
"(",
"moduleName",
",",
"fileName",
",",
"contents",
")",
"{",
"writeFile",
"(",
"fileName",
",",
"build",
".",
"toTransport",
"(",
"anonDefRegExp",
",",
"namespaceWithDot",
",",
"moduleName",
",",
"fileName",
",",
"contents",
",",
"layer",
")",
")",
";",
"}",
";",
"return",
"writeFile",
";",
"}"
] | Method used by plugin writeFile calls, defined up here to avoid jslint warning about "making a function in a loop". | [
"Method",
"used",
"by",
"plugin",
"writeFile",
"calls",
"defined",
"up",
"here",
"to",
"avoid",
"jslint",
"warning",
"about",
"making",
"a",
"function",
"in",
"a",
"loop",
"."
] | c5ecf4ed058d2198065f17c3313b0884e8efa6a9 | https://github.com/wachunga/omega/blob/c5ecf4ed058d2198065f17c3313b0884e8efa6a9/r.js#L8410-L8422 | train |
wachunga/omega | r.js | setBaseUrl | function setBaseUrl(fileName) {
//Use the file name's directory as the baseUrl if available.
dir = fileName.replace(/\\/g, '/');
if (dir.indexOf('/') !== -1) {
dir = dir.split('/');
dir.pop();
dir = dir.join('/');
exec("require({baseUrl: '" + dir + "'});");
}
} | javascript | function setBaseUrl(fileName) {
//Use the file name's directory as the baseUrl if available.
dir = fileName.replace(/\\/g, '/');
if (dir.indexOf('/') !== -1) {
dir = dir.split('/');
dir.pop();
dir = dir.join('/');
exec("require({baseUrl: '" + dir + "'});");
}
} | [
"function",
"setBaseUrl",
"(",
"fileName",
")",
"{",
"dir",
"=",
"fileName",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'/'",
")",
";",
"if",
"(",
"dir",
".",
"indexOf",
"(",
"'/'",
")",
"!==",
"-",
"1",
")",
"{",
"dir",
"=",
"dir",
".",
"split",
"(",
"'/'",
")",
";",
"dir",
".",
"pop",
"(",
")",
";",
"dir",
"=",
"dir",
".",
"join",
"(",
"'/'",
")",
";",
"exec",
"(",
"\"require({baseUrl: '\"",
"+",
"dir",
"+",
"\"'});\"",
")",
";",
"}",
"}"
] | Sets the default baseUrl for requirejs to be directory of top level
script. | [
"Sets",
"the",
"default",
"baseUrl",
"for",
"requirejs",
"to",
"be",
"directory",
"of",
"top",
"level",
"script",
"."
] | c5ecf4ed058d2198065f17c3313b0884e8efa6a9 | https://github.com/wachunga/omega/blob/c5ecf4ed058d2198065f17c3313b0884e8efa6a9/r.js#L9406-L9415 | train |
cozy/cozy-emails | client/plugins/vcard/js/vcardjs-0.3.js | validateCompoundWithType | function validateCompoundWithType(attribute, values) {
for(var i in values) {
var value = values[i];
if(typeof(value) !== 'object') {
errors.push([attribute + '-' + i, "not-an-object"]);
} else if(! value.type) {
errors.push([attribute + '-' + i, "missing-type"]);
} else if(! value.value) { // empty values are not allowed.
errors.push([attribute + '-' + i, "missing-value"]);
}
}
} | javascript | function validateCompoundWithType(attribute, values) {
for(var i in values) {
var value = values[i];
if(typeof(value) !== 'object') {
errors.push([attribute + '-' + i, "not-an-object"]);
} else if(! value.type) {
errors.push([attribute + '-' + i, "missing-type"]);
} else if(! value.value) { // empty values are not allowed.
errors.push([attribute + '-' + i, "missing-value"]);
}
}
} | [
"function",
"validateCompoundWithType",
"(",
"attribute",
",",
"values",
")",
"{",
"for",
"(",
"var",
"i",
"in",
"values",
")",
"{",
"var",
"value",
"=",
"values",
"[",
"i",
"]",
";",
"if",
"(",
"typeof",
"(",
"value",
")",
"!==",
"'object'",
")",
"{",
"errors",
".",
"push",
"(",
"[",
"attribute",
"+",
"'-'",
"+",
"i",
",",
"\"not-an-object\"",
"]",
")",
";",
"}",
"else",
"if",
"(",
"!",
"value",
".",
"type",
")",
"{",
"errors",
".",
"push",
"(",
"[",
"attribute",
"+",
"'-'",
"+",
"i",
",",
"\"missing-type\"",
"]",
")",
";",
"}",
"else",
"if",
"(",
"!",
"value",
".",
"value",
")",
"{",
"errors",
".",
"push",
"(",
"[",
"attribute",
"+",
"'-'",
"+",
"i",
",",
"\"missing-value\"",
"]",
")",
";",
"}",
"}",
"}"
] | make sure compound fields have their type & value set (to prevent mistakes such as vcard.addAttribute('email', '[email protected]') | [
"make",
"sure",
"compound",
"fields",
"have",
"their",
"type",
"&",
"value",
"set",
"(",
"to",
"prevent",
"mistakes",
"such",
"as",
"vcard",
".",
"addAttribute",
"(",
"email",
"foo"
] | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/plugins/vcard/js/vcardjs-0.3.js#L150-L161 | train |
cozy/cozy-emails | client/plugins/vcard/js/vcardjs-0.3.js | function(key, value) {
console.log('add attribute', key, value);
if(! value) {
return;
}
if(VCard.multivaluedKeys[key]) {
if(this[key]) {
console.log('multivalued push');
this[key].push(value)
} else {
console.log('multivalued set');
this.setAttribute(key, [value]);
}
} else {
this.setAttribute(key, value);
}
} | javascript | function(key, value) {
console.log('add attribute', key, value);
if(! value) {
return;
}
if(VCard.multivaluedKeys[key]) {
if(this[key]) {
console.log('multivalued push');
this[key].push(value)
} else {
console.log('multivalued set');
this.setAttribute(key, [value]);
}
} else {
this.setAttribute(key, value);
}
} | [
"function",
"(",
"key",
",",
"value",
")",
"{",
"console",
".",
"log",
"(",
"'add attribute'",
",",
"key",
",",
"value",
")",
";",
"if",
"(",
"!",
"value",
")",
"{",
"return",
";",
"}",
"if",
"(",
"VCard",
".",
"multivaluedKeys",
"[",
"key",
"]",
")",
"{",
"if",
"(",
"this",
"[",
"key",
"]",
")",
"{",
"console",
".",
"log",
"(",
"'multivalued push'",
")",
";",
"this",
"[",
"key",
"]",
".",
"push",
"(",
"value",
")",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'multivalued set'",
")",
";",
"this",
".",
"setAttribute",
"(",
"key",
",",
"[",
"value",
"]",
")",
";",
"}",
"}",
"else",
"{",
"this",
".",
"setAttribute",
"(",
"key",
",",
"value",
")",
";",
"}",
"}"
] | Set the given attribute to the given value. If the given attribute's key has cardinality > 1, instead of overwriting the current value, an additional value is appended. | [
"Set",
"the",
"given",
"attribute",
"to",
"the",
"given",
"value",
".",
"If",
"the",
"given",
"attribute",
"s",
"key",
"has",
"cardinality",
">",
"1",
"instead",
"of",
"overwriting",
"the",
"current",
"value",
"an",
"additional",
"value",
"is",
"appended",
"."
] | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/plugins/vcard/js/vcardjs-0.3.js#L206-L222 | train |
|
cozy/cozy-emails | client/plugins/vcard/js/vcardjs-0.3.js | function(aDate, bDate, addSub) {
if(typeof(addSub) == 'undefined') { addSub = true };
if(! aDate) { return bDate; }
if(! bDate) { return aDate; }
var a = Number(aDate);
var b = Number(bDate);
var c = addSub ? a + b : a - b;
return new Date(c);
} | javascript | function(aDate, bDate, addSub) {
if(typeof(addSub) == 'undefined') { addSub = true };
if(! aDate) { return bDate; }
if(! bDate) { return aDate; }
var a = Number(aDate);
var b = Number(bDate);
var c = addSub ? a + b : a - b;
return new Date(c);
} | [
"function",
"(",
"aDate",
",",
"bDate",
",",
"addSub",
")",
"{",
"if",
"(",
"typeof",
"(",
"addSub",
")",
"==",
"'undefined'",
")",
"{",
"addSub",
"=",
"true",
"}",
";",
"if",
"(",
"!",
"aDate",
")",
"{",
"return",
"bDate",
";",
"}",
"if",
"(",
"!",
"bDate",
")",
"{",
"return",
"aDate",
";",
"}",
"var",
"a",
"=",
"Number",
"(",
"aDate",
")",
";",
"var",
"b",
"=",
"Number",
"(",
"bDate",
")",
";",
"var",
"c",
"=",
"addSub",
"?",
"a",
"+",
"b",
":",
"a",
"-",
"b",
";",
"return",
"new",
"Date",
"(",
"c",
")",
";",
"}"
] | add two dates. if addSub is false, substract instead of add. | [
"add",
"two",
"dates",
".",
"if",
"addSub",
"is",
"false",
"substract",
"instead",
"of",
"add",
"."
] | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/plugins/vcard/js/vcardjs-0.3.js#L629-L637 | train |
|
cozy/cozy-emails | client/plugins/vcard/js/vcardjs-0.3.js | function(str){
str = (str || "").toString();
str = str.replace(/\=(?:\r?\n|$)/g, "");
var str2 = "";
for(var i=0, len = str.length; i<len; i++){
chr = str.charAt(i);
if(chr == "=" && (hex = str.substr(i+1, 2)) && /[\da-fA-F]{2}/.test(hex)){
str2 += String.fromCharCode(parseInt(hex,16));
i+=2;
continue;
}
str2 += chr;
}
return str2;
} | javascript | function(str){
str = (str || "").toString();
str = str.replace(/\=(?:\r?\n|$)/g, "");
var str2 = "";
for(var i=0, len = str.length; i<len; i++){
chr = str.charAt(i);
if(chr == "=" && (hex = str.substr(i+1, 2)) && /[\da-fA-F]{2}/.test(hex)){
str2 += String.fromCharCode(parseInt(hex,16));
i+=2;
continue;
}
str2 += chr;
}
return str2;
} | [
"function",
"(",
"str",
")",
"{",
"str",
"=",
"(",
"str",
"||",
"\"\"",
")",
".",
"toString",
"(",
")",
";",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"\\=(?:\\r?\\n|$)",
"/",
"g",
",",
"\"\"",
")",
";",
"var",
"str2",
"=",
"\"\"",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"str",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"chr",
"=",
"str",
".",
"charAt",
"(",
"i",
")",
";",
"if",
"(",
"chr",
"==",
"\"=\"",
"&&",
"(",
"hex",
"=",
"str",
".",
"substr",
"(",
"i",
"+",
"1",
",",
"2",
")",
")",
"&&",
"/",
"[\\da-fA-F]{2}",
"/",
".",
"test",
"(",
"hex",
")",
")",
"{",
"str2",
"+=",
"String",
".",
"fromCharCode",
"(",
"parseInt",
"(",
"hex",
",",
"16",
")",
")",
";",
"i",
"+=",
"2",
";",
"continue",
";",
"}",
"str2",
"+=",
"chr",
";",
"}",
"return",
"str2",
";",
"}"
] | Quoted Printable Parser
Parses quoted-printable strings, which sometimes appear in
vCard 2.1 files (usually the address field)
Code adapted from:
https://github.com/andris9/mimelib | [
"Quoted",
"Printable",
"Parser"
] | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/plugins/vcard/js/vcardjs-0.3.js#L793-L807 | train |
|
mangalam-research/wed | lib/wed/polyfills/firstElementChild_etc.js | addParentNodeInterfaceToPrototype | function addParentNodeInterfaceToPrototype(p) {
Object.defineProperty(p, "firstElementChild", {
get: function firstElementChild() {
var el = this.firstChild;
while (el && el.nodeType !== 1) {
el = el.nextSibling;
}
return el;
},
});
Object.defineProperty(p, "lastElementChild", {
get: function lastElementChild() {
var el = this.lastChild;
while (el && el.nodeType !== 1) {
el = el.previousSibling;
}
return el;
},
});
Object.defineProperty(p, "childElementCount", {
get: function childElementCount() {
var el = this.firstElementChild;
var count = 0;
while (el) {
count++;
el = el.nextElementSibling;
}
return count;
},
});
} | javascript | function addParentNodeInterfaceToPrototype(p) {
Object.defineProperty(p, "firstElementChild", {
get: function firstElementChild() {
var el = this.firstChild;
while (el && el.nodeType !== 1) {
el = el.nextSibling;
}
return el;
},
});
Object.defineProperty(p, "lastElementChild", {
get: function lastElementChild() {
var el = this.lastChild;
while (el && el.nodeType !== 1) {
el = el.previousSibling;
}
return el;
},
});
Object.defineProperty(p, "childElementCount", {
get: function childElementCount() {
var el = this.firstElementChild;
var count = 0;
while (el) {
count++;
el = el.nextElementSibling;
}
return count;
},
});
} | [
"function",
"addParentNodeInterfaceToPrototype",
"(",
"p",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"p",
",",
"\"firstElementChild\"",
",",
"{",
"get",
":",
"function",
"firstElementChild",
"(",
")",
"{",
"var",
"el",
"=",
"this",
".",
"firstChild",
";",
"while",
"(",
"el",
"&&",
"el",
".",
"nodeType",
"!==",
"1",
")",
"{",
"el",
"=",
"el",
".",
"nextSibling",
";",
"}",
"return",
"el",
";",
"}",
",",
"}",
")",
";",
"Object",
".",
"defineProperty",
"(",
"p",
",",
"\"lastElementChild\"",
",",
"{",
"get",
":",
"function",
"lastElementChild",
"(",
")",
"{",
"var",
"el",
"=",
"this",
".",
"lastChild",
";",
"while",
"(",
"el",
"&&",
"el",
".",
"nodeType",
"!==",
"1",
")",
"{",
"el",
"=",
"el",
".",
"previousSibling",
";",
"}",
"return",
"el",
";",
"}",
",",
"}",
")",
";",
"Object",
".",
"defineProperty",
"(",
"p",
",",
"\"childElementCount\"",
",",
"{",
"get",
":",
"function",
"childElementCount",
"(",
")",
"{",
"var",
"el",
"=",
"this",
".",
"firstElementChild",
";",
"var",
"count",
"=",
"0",
";",
"while",
"(",
"el",
")",
"{",
"count",
"++",
";",
"el",
"=",
"el",
".",
"nextElementSibling",
";",
"}",
"return",
"count",
";",
"}",
",",
"}",
")",
";",
"}"
] | This polyfill has been tested with IE 11 and 10. It has not been tested with older versions of IE because we do not support them. | [
"This",
"polyfill",
"has",
"been",
"tested",
"with",
"IE",
"11",
"and",
"10",
".",
"It",
"has",
"not",
"been",
"tested",
"with",
"older",
"versions",
"of",
"IE",
"because",
"we",
"do",
"not",
"support",
"them",
"."
] | f0c6d23492ac97afa730098df46e18fdeb647ef5 | https://github.com/mangalam-research/wed/blob/f0c6d23492ac97afa730098df46e18fdeb647ef5/lib/wed/polyfills/firstElementChild_etc.js#L28-L60 | train |
mangalam-research/wed | lib/wed/polyfills/firstElementChild_etc.js | addChildrenToPrototype | function addChildrenToPrototype(p) {
// Unfortunately, it is not possible to emulate the liveness of the
// HTMLCollection this property *should* provide.
Object.defineProperty(p, "children", {
get: function children() {
var ret = [];
var el = this.firstElementChild;
while (el) {
ret.push(el);
el = el.nextElementSibling;
}
return ret;
},
});
} | javascript | function addChildrenToPrototype(p) {
// Unfortunately, it is not possible to emulate the liveness of the
// HTMLCollection this property *should* provide.
Object.defineProperty(p, "children", {
get: function children() {
var ret = [];
var el = this.firstElementChild;
while (el) {
ret.push(el);
el = el.nextElementSibling;
}
return ret;
},
});
} | [
"function",
"addChildrenToPrototype",
"(",
"p",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"p",
",",
"\"children\"",
",",
"{",
"get",
":",
"function",
"children",
"(",
")",
"{",
"var",
"ret",
"=",
"[",
"]",
";",
"var",
"el",
"=",
"this",
".",
"firstElementChild",
";",
"while",
"(",
"el",
")",
"{",
"ret",
".",
"push",
"(",
"el",
")",
";",
"el",
"=",
"el",
".",
"nextElementSibling",
";",
"}",
"return",
"ret",
";",
"}",
",",
"}",
")",
";",
"}"
] | We separate children from the rest because it is possible to have firstElementChild, etc defined and yet not have children defined. Go figure... | [
"We",
"separate",
"children",
"from",
"the",
"rest",
"because",
"it",
"is",
"possible",
"to",
"have",
"firstElementChild",
"etc",
"defined",
"and",
"yet",
"not",
"have",
"children",
"defined",
".",
"Go",
"figure",
"..."
] | f0c6d23492ac97afa730098df46e18fdeb647ef5 | https://github.com/mangalam-research/wed/blob/f0c6d23492ac97afa730098df46e18fdeb647ef5/lib/wed/polyfills/firstElementChild_etc.js#L65-L80 | train |
mangalam-research/wed | misc/util.js | captureConfigObject | function captureConfigObject(config) {
let captured;
const require = {};
require.config = function _config(conf) {
captured = conf;
};
let wedConfig;
// eslint-disable-next-line no-unused-vars
function define(name, obj) {
if (wedConfig !== undefined) {
throw new Error("more than one define");
}
switch (arguments.length) {
case 0:
throw new Error("no arguments to the define!");
case 1:
if (typeof name !== "object") {
throw new Error("if define has only one argument, it must be an " +
"object");
}
wedConfig = name;
break;
default:
throw new Error("captureConfigObject is designed to capture a " +
"maximum of two arguments.");
}
}
eval(config); // eslint-disable-line no-eval
return {
requireConfig: captured,
wedConfig,
};
} | javascript | function captureConfigObject(config) {
let captured;
const require = {};
require.config = function _config(conf) {
captured = conf;
};
let wedConfig;
// eslint-disable-next-line no-unused-vars
function define(name, obj) {
if (wedConfig !== undefined) {
throw new Error("more than one define");
}
switch (arguments.length) {
case 0:
throw new Error("no arguments to the define!");
case 1:
if (typeof name !== "object") {
throw new Error("if define has only one argument, it must be an " +
"object");
}
wedConfig = name;
break;
default:
throw new Error("captureConfigObject is designed to capture a " +
"maximum of two arguments.");
}
}
eval(config); // eslint-disable-line no-eval
return {
requireConfig: captured,
wedConfig,
};
} | [
"function",
"captureConfigObject",
"(",
"config",
")",
"{",
"let",
"captured",
";",
"const",
"require",
"=",
"{",
"}",
";",
"require",
".",
"config",
"=",
"function",
"_config",
"(",
"conf",
")",
"{",
"captured",
"=",
"conf",
";",
"}",
";",
"let",
"wedConfig",
";",
"function",
"define",
"(",
"name",
",",
"obj",
")",
"{",
"if",
"(",
"wedConfig",
"!==",
"undefined",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"more than one define\"",
")",
";",
"}",
"switch",
"(",
"arguments",
".",
"length",
")",
"{",
"case",
"0",
":",
"throw",
"new",
"Error",
"(",
"\"no arguments to the define!\"",
")",
";",
"case",
"1",
":",
"if",
"(",
"typeof",
"name",
"!==",
"\"object\"",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"if define has only one argument, it must be an \"",
"+",
"\"object\"",
")",
";",
"}",
"wedConfig",
"=",
"name",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"\"captureConfigObject is designed to capture a \"",
"+",
"\"maximum of two arguments.\"",
")",
";",
"}",
"}",
"eval",
"(",
"config",
")",
";",
"return",
"{",
"requireConfig",
":",
"captured",
",",
"wedConfig",
",",
"}",
";",
"}"
] | This function defines ``require.config`` so that evaluating our
configuration file will capture the configuration passed to
``require.config``.
@param {String} config The text of the configuration file.
@returns {Object} The configuration object. | [
"This",
"function",
"defines",
"require",
".",
"config",
"so",
"that",
"evaluating",
"our",
"configuration",
"file",
"will",
"capture",
"the",
"configuration",
"passed",
"to",
"require",
".",
"config",
"."
] | f0c6d23492ac97afa730098df46e18fdeb647ef5 | https://github.com/mangalam-research/wed/blob/f0c6d23492ac97afa730098df46e18fdeb647ef5/misc/util.js#L14-L50 | train |
mangalam-research/wed | lib/wed/onerror.js | _reset | function _reset() {
terminating = false;
if (termination_timeout) {
termination_window.clearTimeout(termination_timeout);
termination_timeout = undefined;
}
$modal.off();
$modal.modal("hide");
$modal.remove();
} | javascript | function _reset() {
terminating = false;
if (termination_timeout) {
termination_window.clearTimeout(termination_timeout);
termination_timeout = undefined;
}
$modal.off();
$modal.modal("hide");
$modal.remove();
} | [
"function",
"_reset",
"(",
")",
"{",
"terminating",
"=",
"false",
";",
"if",
"(",
"termination_timeout",
")",
"{",
"termination_window",
".",
"clearTimeout",
"(",
"termination_timeout",
")",
";",
"termination_timeout",
"=",
"undefined",
";",
"}",
"$modal",
".",
"off",
"(",
")",
";",
"$modal",
".",
"modal",
"(",
"\"hide\"",
")",
";",
"$modal",
".",
"remove",
"(",
")",
";",
"}"
] | Normally onerror will be reset by reloading but when testing with mocha we don't want reloading, so we export this function. | [
"Normally",
"onerror",
"will",
"be",
"reset",
"by",
"reloading",
"but",
"when",
"testing",
"with",
"mocha",
"we",
"don",
"t",
"want",
"reloading",
"so",
"we",
"export",
"this",
"function",
"."
] | f0c6d23492ac97afa730098df46e18fdeb647ef5 | https://github.com/mangalam-research/wed/blob/f0c6d23492ac97afa730098df46e18fdeb647ef5/lib/wed/onerror.js#L44-L53 | train |
mangalam-research/wed | lib/wed/onerror.js | showModal | function showModal(saveMessages, errorMessage) {
$(document.body).append($modal);
$modal.find(".save-messages")[0].innerHTML = saveMessages;
$modal.find(".error-message")[0].textContent = errorMessage;
$modal.on("hide.bs.modal.modal", function hidden() {
$modal.remove();
window.location.reload();
});
$modal.modal();
} | javascript | function showModal(saveMessages, errorMessage) {
$(document.body).append($modal);
$modal.find(".save-messages")[0].innerHTML = saveMessages;
$modal.find(".error-message")[0].textContent = errorMessage;
$modal.on("hide.bs.modal.modal", function hidden() {
$modal.remove();
window.location.reload();
});
$modal.modal();
} | [
"function",
"showModal",
"(",
"saveMessages",
",",
"errorMessage",
")",
"{",
"$",
"(",
"document",
".",
"body",
")",
".",
"append",
"(",
"$modal",
")",
";",
"$modal",
".",
"find",
"(",
"\".save-messages\"",
")",
"[",
"0",
"]",
".",
"innerHTML",
"=",
"saveMessages",
";",
"$modal",
".",
"find",
"(",
"\".error-message\"",
")",
"[",
"0",
"]",
".",
"textContent",
"=",
"errorMessage",
";",
"$modal",
".",
"on",
"(",
"\"hide.bs.modal.modal\"",
",",
"function",
"hidden",
"(",
")",
"{",
"$modal",
".",
"remove",
"(",
")",
";",
"window",
".",
"location",
".",
"reload",
"(",
")",
";",
"}",
")",
";",
"$modal",
".",
"modal",
"(",
")",
";",
"}"
] | So that we can issue clearTimeout elsewhere. | [
"So",
"that",
"we",
"can",
"issue",
"clearTimeout",
"elsewhere",
"."
] | f0c6d23492ac97afa730098df46e18fdeb647ef5 | https://github.com/mangalam-research/wed/blob/f0c6d23492ac97afa730098df46e18fdeb647ef5/lib/wed/onerror.js#L78-L87 | train |
jonschlinkert/lazy-cache | index.js | lazyCache | function lazyCache(requireFn) {
var cache = {};
return function proxy(name, alias) {
var key = alias;
// camel-case the module `name` if `alias` is not defined
if (typeof key !== 'string') {
key = camelcase(name);
}
// create a getter to lazily invoke the module the first time it's called
function getter() {
return cache[key] || (cache[key] = requireFn(name));
}
// trip the getter if `process.env.UNLAZY` is defined
if (unlazy(process.env)) {
getter();
}
set(proxy, key, getter);
return getter;
};
} | javascript | function lazyCache(requireFn) {
var cache = {};
return function proxy(name, alias) {
var key = alias;
// camel-case the module `name` if `alias` is not defined
if (typeof key !== 'string') {
key = camelcase(name);
}
// create a getter to lazily invoke the module the first time it's called
function getter() {
return cache[key] || (cache[key] = requireFn(name));
}
// trip the getter if `process.env.UNLAZY` is defined
if (unlazy(process.env)) {
getter();
}
set(proxy, key, getter);
return getter;
};
} | [
"function",
"lazyCache",
"(",
"requireFn",
")",
"{",
"var",
"cache",
"=",
"{",
"}",
";",
"return",
"function",
"proxy",
"(",
"name",
",",
"alias",
")",
"{",
"var",
"key",
"=",
"alias",
";",
"if",
"(",
"typeof",
"key",
"!==",
"'string'",
")",
"{",
"key",
"=",
"camelcase",
"(",
"name",
")",
";",
"}",
"function",
"getter",
"(",
")",
"{",
"return",
"cache",
"[",
"key",
"]",
"||",
"(",
"cache",
"[",
"key",
"]",
"=",
"requireFn",
"(",
"name",
")",
")",
";",
"}",
"if",
"(",
"unlazy",
"(",
"process",
".",
"env",
")",
")",
"{",
"getter",
"(",
")",
";",
"}",
"set",
"(",
"proxy",
",",
"key",
",",
"getter",
")",
";",
"return",
"getter",
";",
"}",
";",
"}"
] | Cache results of the first function call to ensure only calling once.
```js
var utils = require('lazy-cache')(require);
// cache the call to `require('ansi-yellow')`
utils('ansi-yellow', 'yellow');
// use `ansi-yellow`
console.log(utils.yellow('this is yellow'));
```
@param {Function} `fn` Function that will be called only once.
@return {Function} Function that can be called to get the cached function
@api public | [
"Cache",
"results",
"of",
"the",
"first",
"function",
"call",
"to",
"ensure",
"only",
"calling",
"once",
"."
] | 2f15129f05f2d69cbc2cb7ba52e383fc31b9fc2c | https://github.com/jonschlinkert/lazy-cache/blob/2f15129f05f2d69cbc2cb7ba52e383fc31b9fc2c/index.js#L21-L45 | train |
temando/remark-mermaid | src/utils.js | getDestinationDir | function getDestinationDir(vFile) {
if (vFile.data.destinationDir) {
return vFile.data.destinationDir;
}
return vFile.dirname;
} | javascript | function getDestinationDir(vFile) {
if (vFile.data.destinationDir) {
return vFile.data.destinationDir;
}
return vFile.dirname;
} | [
"function",
"getDestinationDir",
"(",
"vFile",
")",
"{",
"if",
"(",
"vFile",
".",
"data",
".",
"destinationDir",
")",
"{",
"return",
"vFile",
".",
"data",
".",
"destinationDir",
";",
"}",
"return",
"vFile",
".",
"dirname",
";",
"}"
] | Returns the destination for the SVG to be rendered at, explicity defined
using `vFile.data.destinationDir`, or falling back to the file's current
directory.
@param {vFile} vFile
@return {string} | [
"Returns",
"the",
"destination",
"for",
"the",
"SVG",
"to",
"be",
"rendered",
"at",
"explicity",
"defined",
"using",
"vFile",
".",
"data",
".",
"destinationDir",
"or",
"falling",
"back",
"to",
"the",
"file",
"s",
"current",
"directory",
"."
] | 3c0aaa8e90ff8ca0d043a9648c651683c0867ae3 | https://github.com/temando/remark-mermaid/blob/3c0aaa8e90ff8ca0d043a9648c651683c0867ae3/src/utils.js#L64-L70 | train |
IonicaBizau/parse-url | lib/index.js | parseUrl | function parseUrl(url, normalize = false) {
if (typeof url !== "string" || !url.trim()) {
throw new Error("Invalid url.")
}
if (normalize) {
if (typeof normalize !== "object") {
normalize = {
stripFragment: false
}
}
url = normalizeUrl(url, normalize)
}
const parsed = parsePath(url)
return parsed;
} | javascript | function parseUrl(url, normalize = false) {
if (typeof url !== "string" || !url.trim()) {
throw new Error("Invalid url.")
}
if (normalize) {
if (typeof normalize !== "object") {
normalize = {
stripFragment: false
}
}
url = normalizeUrl(url, normalize)
}
const parsed = parsePath(url)
return parsed;
} | [
"function",
"parseUrl",
"(",
"url",
",",
"normalize",
"=",
"false",
")",
"{",
"if",
"(",
"typeof",
"url",
"!==",
"\"string\"",
"||",
"!",
"url",
".",
"trim",
"(",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Invalid url.\"",
")",
"}",
"if",
"(",
"normalize",
")",
"{",
"if",
"(",
"typeof",
"normalize",
"!==",
"\"object\"",
")",
"{",
"normalize",
"=",
"{",
"stripFragment",
":",
"false",
"}",
"}",
"url",
"=",
"normalizeUrl",
"(",
"url",
",",
"normalize",
")",
"}",
"const",
"parsed",
"=",
"parsePath",
"(",
"url",
")",
"return",
"parsed",
";",
"}"
] | parseUrl
Parses the input url.
**Note**: This *throws* if invalid urls are provided.
@name parseUrl
@function
@param {String} url The input url.
@param {Boolean|Object} normalize Wheter to normalize the url or not.
Default is `false`. If `true`, the url will
be normalized. If an object, it will be the
options object sent to [`normalize-url`](https://github.com/sindresorhus/normalize-url).
For SSH urls, normalize won't work.
@return {Object} An object containing the following fields:
- `protocols` (Array): An array with the url protocols (usually it has one element).
- `protocol` (String): The first protocol, `"ssh"` (if the url is a ssh url) or `"file"`.
- `port` (null|Number): The domain port.
- `resource` (String): The url domain (including subdomains).
- `user` (String): The authentication user (usually for ssh urls).
- `pathname` (String): The url pathname.
- `hash` (String): The url hash.
- `search` (String): The url querystring value.
- `href` (String): The input url.
- `query` (Object): The url querystring, parsed as object. | [
"parseUrl",
"Parses",
"the",
"input",
"url",
"."
] | 0be4cd98d7ad1b82a006e1edd7dbb3bde56a7537 | https://github.com/IonicaBizau/parse-url/blob/0be4cd98d7ad1b82a006e1edd7dbb3bde56a7537/lib/index.js#L35-L49 | train |
Pamblam/jSQL | jSQL.js | function(query, data, successCallback, failureCallback) {
if(typeof successCallback != "function") successCallback = function(){};
if(typeof failureCallback != "function") failureCallback = function(){ return _throw(new jSQL_Error("0054")); };
var i, l, remaining;
if(!Array.isArray(data[0])) data = [data];
remaining = data.length;
var innerSuccessCallback = function(tx, rs) {
var i, l, output = [];
remaining = remaining - 1;
if (!remaining) {
for (i = 0, l = rs.rows.length; i < l; i = i + 1){
var j = rs.rows.item(i).json;
//j = JSON.parse(j);
output.push(j);
}
successCallback(output);
}
};
self.db.transaction(function (tx) {
for (i = 0, l = data.length; i < l; i = i + 1) {
tx.executeSql(query, data[i], innerSuccessCallback, failureCallback);
}
});
} | javascript | function(query, data, successCallback, failureCallback) {
if(typeof successCallback != "function") successCallback = function(){};
if(typeof failureCallback != "function") failureCallback = function(){ return _throw(new jSQL_Error("0054")); };
var i, l, remaining;
if(!Array.isArray(data[0])) data = [data];
remaining = data.length;
var innerSuccessCallback = function(tx, rs) {
var i, l, output = [];
remaining = remaining - 1;
if (!remaining) {
for (i = 0, l = rs.rows.length; i < l; i = i + 1){
var j = rs.rows.item(i).json;
//j = JSON.parse(j);
output.push(j);
}
successCallback(output);
}
};
self.db.transaction(function (tx) {
for (i = 0, l = data.length; i < l; i = i + 1) {
tx.executeSql(query, data[i], innerSuccessCallback, failureCallback);
}
});
} | [
"function",
"(",
"query",
",",
"data",
",",
"successCallback",
",",
"failureCallback",
")",
"{",
"if",
"(",
"typeof",
"successCallback",
"!=",
"\"function\"",
")",
"successCallback",
"=",
"function",
"(",
")",
"{",
"}",
";",
"if",
"(",
"typeof",
"failureCallback",
"!=",
"\"function\"",
")",
"failureCallback",
"=",
"function",
"(",
")",
"{",
"return",
"_throw",
"(",
"new",
"jSQL_Error",
"(",
"\"0054\"",
")",
")",
";",
"}",
";",
"var",
"i",
",",
"l",
",",
"remaining",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"data",
"[",
"0",
"]",
")",
")",
"data",
"=",
"[",
"data",
"]",
";",
"remaining",
"=",
"data",
".",
"length",
";",
"var",
"innerSuccessCallback",
"=",
"function",
"(",
"tx",
",",
"rs",
")",
"{",
"var",
"i",
",",
"l",
",",
"output",
"=",
"[",
"]",
";",
"remaining",
"=",
"remaining",
"-",
"1",
";",
"if",
"(",
"!",
"remaining",
")",
"{",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"rs",
".",
"rows",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"=",
"i",
"+",
"1",
")",
"{",
"var",
"j",
"=",
"rs",
".",
"rows",
".",
"item",
"(",
"i",
")",
".",
"json",
";",
"output",
".",
"push",
"(",
"j",
")",
";",
"}",
"successCallback",
"(",
"output",
")",
";",
"}",
"}",
";",
"self",
".",
"db",
".",
"transaction",
"(",
"function",
"(",
"tx",
")",
"{",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"data",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"=",
"i",
"+",
"1",
")",
"{",
"tx",
".",
"executeSql",
"(",
"query",
",",
"data",
"[",
"i",
"]",
",",
"innerSuccessCallback",
",",
"failureCallback",
")",
";",
"}",
"}",
")",
";",
"}"
] | private function to execute a query | [
"private",
"function",
"to",
"execute",
"a",
"query"
] | 507ef210e339fdb8f820b26412e2173aa8c19d82 | https://github.com/Pamblam/jSQL/blob/507ef210e339fdb8f820b26412e2173aa8c19d82/jSQL.js#L2370-L2395 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.