id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
500 | SeleniumHQ/selenium | javascript/selenium-core/scripts/htmlutils.js | eval_css | function eval_css(locator, inDocument) {
var results = [];
try {
window.Sizzle(locator, inDocument, results);
} catch (ignored) {
// Presumably poor formatting
}
return results;
} | javascript | function eval_css(locator, inDocument) {
var results = [];
try {
window.Sizzle(locator, inDocument, results);
} catch (ignored) {
// Presumably poor formatting
}
return results;
} | [
"function",
"eval_css",
"(",
"locator",
",",
"inDocument",
")",
"{",
"var",
"results",
"=",
"[",
"]",
";",
"try",
"{",
"window",
".",
"Sizzle",
"(",
"locator",
",",
"inDocument",
",",
"results",
")",
";",
"}",
"catch",
"(",
"ignored",
")",
"{",
"// Presumably poor formatting",
"}",
"return",
"results",
";",
"}"
] | Returns the full resultset of a CSS selector evaluation. | [
"Returns",
"the",
"full",
"resultset",
"of",
"a",
"CSS",
"selector",
"evaluation",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/selenium-core/scripts/htmlutils.js#L2186-L2194 |
501 | SeleniumHQ/selenium | javascript/selenium-core/scripts/htmlutils.js | are_equal | function are_equal(a1, a2)
{
if (typeof(a1) != typeof(a2))
return false;
switch(typeof(a1)) {
case 'object':
// arrays
if (a1.length) {
if (a1.length != a2.length)
return false;
for (var i = 0; i < a1.length; ++i) {
if (!are_equal(a1[i], a2[i]))
return false
}
}
// associative arrays
else {
var keys = {};
for (var key in a1) {
keys[key] = true;
}
for (var key in a2) {
keys[key] = true;
}
for (var key in keys) {
if (!are_equal(a1[key], a2[key]))
return false;
}
}
return true;
default:
return a1 == a2;
}
} | javascript | function are_equal(a1, a2)
{
if (typeof(a1) != typeof(a2))
return false;
switch(typeof(a1)) {
case 'object':
// arrays
if (a1.length) {
if (a1.length != a2.length)
return false;
for (var i = 0; i < a1.length; ++i) {
if (!are_equal(a1[i], a2[i]))
return false
}
}
// associative arrays
else {
var keys = {};
for (var key in a1) {
keys[key] = true;
}
for (var key in a2) {
keys[key] = true;
}
for (var key in keys) {
if (!are_equal(a1[key], a2[key]))
return false;
}
}
return true;
default:
return a1 == a2;
}
} | [
"function",
"are_equal",
"(",
"a1",
",",
"a2",
")",
"{",
"if",
"(",
"typeof",
"(",
"a1",
")",
"!=",
"typeof",
"(",
"a2",
")",
")",
"return",
"false",
";",
"switch",
"(",
"typeof",
"(",
"a1",
")",
")",
"{",
"case",
"'object'",
":",
"// arrays",
"if",
"(",
"a1",
".",
"length",
")",
"{",
"if",
"(",
"a1",
".",
"length",
"!=",
"a2",
".",
"length",
")",
"return",
"false",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"a1",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"!",
"are_equal",
"(",
"a1",
"[",
"i",
"]",
",",
"a2",
"[",
"i",
"]",
")",
")",
"return",
"false",
"}",
"}",
"// associative arrays",
"else",
"{",
"var",
"keys",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"a1",
")",
"{",
"keys",
"[",
"key",
"]",
"=",
"true",
";",
"}",
"for",
"(",
"var",
"key",
"in",
"a2",
")",
"{",
"keys",
"[",
"key",
"]",
"=",
"true",
";",
"}",
"for",
"(",
"var",
"key",
"in",
"keys",
")",
"{",
"if",
"(",
"!",
"are_equal",
"(",
"a1",
"[",
"key",
"]",
",",
"a2",
"[",
"key",
"]",
")",
")",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"default",
":",
"return",
"a1",
"==",
"a2",
";",
"}",
"}"
] | Returns true if two arrays are identical, and false otherwise.
@param a1 the first array, may only contain simple values (strings or
numbers)
@param a2 the second array, same restricts on data as for a1
@return true if the arrays are equivalent, false otherwise. | [
"Returns",
"true",
"if",
"two",
"arrays",
"are",
"identical",
"and",
"false",
"otherwise",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/selenium-core/scripts/htmlutils.js#L2292-L2327 |
502 | SeleniumHQ/selenium | javascript/selenium-core/scripts/htmlutils.js | clone | function clone(orig) {
var copy;
switch(typeof(orig)) {
case 'object':
copy = (orig.length) ? [] : {};
for (var attr in orig) {
copy[attr] = clone(orig[attr]);
}
break;
default:
copy = orig;
break;
}
return copy;
} | javascript | function clone(orig) {
var copy;
switch(typeof(orig)) {
case 'object':
copy = (orig.length) ? [] : {};
for (var attr in orig) {
copy[attr] = clone(orig[attr]);
}
break;
default:
copy = orig;
break;
}
return copy;
} | [
"function",
"clone",
"(",
"orig",
")",
"{",
"var",
"copy",
";",
"switch",
"(",
"typeof",
"(",
"orig",
")",
")",
"{",
"case",
"'object'",
":",
"copy",
"=",
"(",
"orig",
".",
"length",
")",
"?",
"[",
"]",
":",
"{",
"}",
";",
"for",
"(",
"var",
"attr",
"in",
"orig",
")",
"{",
"copy",
"[",
"attr",
"]",
"=",
"clone",
"(",
"orig",
"[",
"attr",
"]",
")",
";",
"}",
"break",
";",
"default",
":",
"copy",
"=",
"orig",
";",
"break",
";",
"}",
"return",
"copy",
";",
"}"
] | Create a clone of an object and return it. This is a deep copy of everything
but functions, whose references are copied. You shouldn't expect a deep copy
of functions anyway.
@param orig the original object to copy
@return a deep copy of the original object. Any functions attached,
however, will have their references copied only. | [
"Create",
"a",
"clone",
"of",
"an",
"object",
"and",
"return",
"it",
".",
"This",
"is",
"a",
"deep",
"copy",
"of",
"everything",
"but",
"functions",
"whose",
"references",
"are",
"copied",
".",
"You",
"shouldn",
"t",
"expect",
"a",
"deep",
"copy",
"of",
"functions",
"anyway",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/selenium-core/scripts/htmlutils.js#L2339-L2353 |
503 | SeleniumHQ/selenium | javascript/selenium-core/scripts/htmlutils.js | parse_kwargs | function parse_kwargs(kwargs)
{
var args = new Object();
var pairs = kwargs.split(/,/);
for (var i = 0; i < pairs.length;) {
if (i > 0 && pairs[i].indexOf('=') == -1) {
// the value string contained a comma. Glue the parts back together.
pairs[i-1] += ',' + pairs.splice(i, 1)[0];
}
else {
++i;
}
}
for (var i = 0; i < pairs.length; ++i) {
var splits = pairs[i].split(/=/);
if (splits.length == 1) {
continue;
}
var key = splits.shift();
var value = splits.join('=');
args[key.trim()] = value.trim();
}
return args;
} | javascript | function parse_kwargs(kwargs)
{
var args = new Object();
var pairs = kwargs.split(/,/);
for (var i = 0; i < pairs.length;) {
if (i > 0 && pairs[i].indexOf('=') == -1) {
// the value string contained a comma. Glue the parts back together.
pairs[i-1] += ',' + pairs.splice(i, 1)[0];
}
else {
++i;
}
}
for (var i = 0; i < pairs.length; ++i) {
var splits = pairs[i].split(/=/);
if (splits.length == 1) {
continue;
}
var key = splits.shift();
var value = splits.join('=');
args[key.trim()] = value.trim();
}
return args;
} | [
"function",
"parse_kwargs",
"(",
"kwargs",
")",
"{",
"var",
"args",
"=",
"new",
"Object",
"(",
")",
";",
"var",
"pairs",
"=",
"kwargs",
".",
"split",
"(",
"/",
",",
"/",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"pairs",
".",
"length",
";",
")",
"{",
"if",
"(",
"i",
">",
"0",
"&&",
"pairs",
"[",
"i",
"]",
".",
"indexOf",
"(",
"'='",
")",
"==",
"-",
"1",
")",
"{",
"// the value string contained a comma. Glue the parts back together.",
"pairs",
"[",
"i",
"-",
"1",
"]",
"+=",
"','",
"+",
"pairs",
".",
"splice",
"(",
"i",
",",
"1",
")",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"++",
"i",
";",
"}",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"pairs",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"splits",
"=",
"pairs",
"[",
"i",
"]",
".",
"split",
"(",
"/",
"=",
"/",
")",
";",
"if",
"(",
"splits",
".",
"length",
"==",
"1",
")",
"{",
"continue",
";",
"}",
"var",
"key",
"=",
"splits",
".",
"shift",
"(",
")",
";",
"var",
"value",
"=",
"splits",
".",
"join",
"(",
"'='",
")",
";",
"args",
"[",
"key",
".",
"trim",
"(",
")",
"]",
"=",
"value",
".",
"trim",
"(",
")",
";",
"}",
"return",
"args",
";",
"}"
] | Parses a python-style keyword arguments string and returns the pairs in a
new object.
@param kwargs a string representing a set of keyword arguments. It should
look like <tt>keyword1=value1, keyword2=value2, ...</tt>
@return an object mapping strings to strings | [
"Parses",
"a",
"python",
"-",
"style",
"keyword",
"arguments",
"string",
"and",
"returns",
"the",
"pairs",
"in",
"a",
"new",
"object",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/selenium-core/scripts/htmlutils.js#L2482-L2505 |
504 | SeleniumHQ/selenium | javascript/selenium-core/scripts/htmlutils.js | to_kwargs | function to_kwargs(args, sortedKeys)
{
var s = '';
if (!sortedKeys) {
var sortedKeys = keys(args).sort();
}
for (var i = 0; i < sortedKeys.length; ++i) {
var k = sortedKeys[i];
if (args[k] != undefined) {
if (s) {
s += ', ';
}
s += k + '=' + args[k];
}
}
return s;
} | javascript | function to_kwargs(args, sortedKeys)
{
var s = '';
if (!sortedKeys) {
var sortedKeys = keys(args).sort();
}
for (var i = 0; i < sortedKeys.length; ++i) {
var k = sortedKeys[i];
if (args[k] != undefined) {
if (s) {
s += ', ';
}
s += k + '=' + args[k];
}
}
return s;
} | [
"function",
"to_kwargs",
"(",
"args",
",",
"sortedKeys",
")",
"{",
"var",
"s",
"=",
"''",
";",
"if",
"(",
"!",
"sortedKeys",
")",
"{",
"var",
"sortedKeys",
"=",
"keys",
"(",
"args",
")",
".",
"sort",
"(",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"sortedKeys",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"k",
"=",
"sortedKeys",
"[",
"i",
"]",
";",
"if",
"(",
"args",
"[",
"k",
"]",
"!=",
"undefined",
")",
"{",
"if",
"(",
"s",
")",
"{",
"s",
"+=",
"', '",
";",
"}",
"s",
"+=",
"k",
"+",
"'='",
"+",
"args",
"[",
"k",
"]",
";",
"}",
"}",
"return",
"s",
";",
"}"
] | Creates a python-style keyword arguments string from an object.
@param args an associative array mapping strings to strings
@param sortedKeys (optional) a list of keys of the args parameter that
specifies the order in which the arguments will appear in
the returned kwargs string
@return a kwarg string representation of args | [
"Creates",
"a",
"python",
"-",
"style",
"keyword",
"arguments",
"string",
"from",
"an",
"object",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/selenium-core/scripts/htmlutils.js#L2517-L2533 |
505 | SeleniumHQ/selenium | javascript/selenium-core/scripts/htmlutils.js | is_ancestor | function is_ancestor(node, target)
{
while (target.parentNode) {
target = target.parentNode;
if (node == target)
return true;
}
return false;
} | javascript | function is_ancestor(node, target)
{
while (target.parentNode) {
target = target.parentNode;
if (node == target)
return true;
}
return false;
} | [
"function",
"is_ancestor",
"(",
"node",
",",
"target",
")",
"{",
"while",
"(",
"target",
".",
"parentNode",
")",
"{",
"target",
"=",
"target",
".",
"parentNode",
";",
"if",
"(",
"node",
"==",
"target",
")",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Returns true if a node is an ancestor node of a target node, and false
otherwise.
@param node the node being compared to the target node
@param target the target node
@return true if node is an ancestor node of target, false otherwise. | [
"Returns",
"true",
"if",
"a",
"node",
"is",
"an",
"ancestor",
"node",
"of",
"a",
"target",
"node",
"and",
"false",
"otherwise",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/selenium-core/scripts/htmlutils.js#L2543-L2551 |
506 | SeleniumHQ/selenium | javascript/selenium-core/scripts/htmlutils.js | function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
// Set display property to block for height/width animations
if ( ( this.prop === "height" || this.prop === "width" ) && this.elem.style ) {
this.elem.style.display = "block";
}
} | javascript | function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
// Set display property to block for height/width animations
if ( ( this.prop === "height" || this.prop === "width" ) && this.elem.style ) {
this.elem.style.display = "block";
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"options",
".",
"step",
")",
"{",
"this",
".",
"options",
".",
"step",
".",
"call",
"(",
"this",
".",
"elem",
",",
"this",
".",
"now",
",",
"this",
")",
";",
"}",
"(",
"jQuery",
".",
"fx",
".",
"step",
"[",
"this",
".",
"prop",
"]",
"||",
"jQuery",
".",
"fx",
".",
"step",
".",
"_default",
")",
"(",
"this",
")",
";",
"// Set display property to block for height/width animations",
"if",
"(",
"(",
"this",
".",
"prop",
"===",
"\"height\"",
"||",
"this",
".",
"prop",
"===",
"\"width\"",
")",
"&&",
"this",
".",
"elem",
".",
"style",
")",
"{",
"this",
".",
"elem",
".",
"style",
".",
"display",
"=",
"\"block\"",
";",
"}",
"}"
] | Simple function for setting a style value | [
"Simple",
"function",
"for",
"setting",
"a",
"style",
"value"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/selenium-core/scripts/htmlutils.js#L8168-L8179 |
|
507 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/toolbars.js | locationBar_clear | function locationBar_clear() {
this.focus({type: "shortcut"});
this._controller.keypress(this.urlbar, "VK_DELETE", {});
this._controller.waitForEval("subject.value == ''",
TIMEOUT, 100, this.urlbar.getNode());
} | javascript | function locationBar_clear() {
this.focus({type: "shortcut"});
this._controller.keypress(this.urlbar, "VK_DELETE", {});
this._controller.waitForEval("subject.value == ''",
TIMEOUT, 100, this.urlbar.getNode());
} | [
"function",
"locationBar_clear",
"(",
")",
"{",
"this",
".",
"focus",
"(",
"{",
"type",
":",
"\"shortcut\"",
"}",
")",
";",
"this",
".",
"_controller",
".",
"keypress",
"(",
"this",
".",
"urlbar",
",",
"\"VK_DELETE\"",
",",
"{",
"}",
")",
";",
"this",
".",
"_controller",
".",
"waitForEval",
"(",
"\"subject.value == ''\"",
",",
"TIMEOUT",
",",
"100",
",",
"this",
".",
"urlbar",
".",
"getNode",
"(",
")",
")",
";",
"}"
] | Clear the location bar | [
"Clear",
"the",
"location",
"bar"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/toolbars.js#L301-L306 |
508 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/toolbars.js | locationBar_focus | function locationBar_focus(event) {
switch (event.type) {
case "click":
this._controller.click(this.urlbar);
break;
case "shortcut":
var cmdKey = utils.getEntity(this.getDtds(), "openCmd.commandkey");
this._controller.keypress(null, cmdKey, {accelKey: true});
break;
default:
throw new Error(arguments.callee.name + ": Unkown event type - " + event.type);
}
// Wait until the location bar has been focused
this._controller.waitForEval("subject.getAttribute('focused') == 'true'",
TIMEOUT, 100, this.urlbar.getNode());
} | javascript | function locationBar_focus(event) {
switch (event.type) {
case "click":
this._controller.click(this.urlbar);
break;
case "shortcut":
var cmdKey = utils.getEntity(this.getDtds(), "openCmd.commandkey");
this._controller.keypress(null, cmdKey, {accelKey: true});
break;
default:
throw new Error(arguments.callee.name + ": Unkown event type - " + event.type);
}
// Wait until the location bar has been focused
this._controller.waitForEval("subject.getAttribute('focused') == 'true'",
TIMEOUT, 100, this.urlbar.getNode());
} | [
"function",
"locationBar_focus",
"(",
"event",
")",
"{",
"switch",
"(",
"event",
".",
"type",
")",
"{",
"case",
"\"click\"",
":",
"this",
".",
"_controller",
".",
"click",
"(",
"this",
".",
"urlbar",
")",
";",
"break",
";",
"case",
"\"shortcut\"",
":",
"var",
"cmdKey",
"=",
"utils",
".",
"getEntity",
"(",
"this",
".",
"getDtds",
"(",
")",
",",
"\"openCmd.commandkey\"",
")",
";",
"this",
".",
"_controller",
".",
"keypress",
"(",
"null",
",",
"cmdKey",
",",
"{",
"accelKey",
":",
"true",
"}",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"arguments",
".",
"callee",
".",
"name",
"+",
"\": Unkown event type - \"",
"+",
"event",
".",
"type",
")",
";",
"}",
"// Wait until the location bar has been focused",
"this",
".",
"_controller",
".",
"waitForEval",
"(",
"\"subject.getAttribute('focused') == 'true'\"",
",",
"TIMEOUT",
",",
"100",
",",
"this",
".",
"urlbar",
".",
"getNode",
"(",
")",
")",
";",
"}"
] | Focus the location bar
@param {object} event
Focus the location bar with the given event (click or shortcut) | [
"Focus",
"the",
"location",
"bar"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/toolbars.js#L332-L348 |
509 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/toolbars.js | locationBar_getNotificationElement | function locationBar_getNotificationElement(aType, aLookupString)
{
var lookup = '/id("' + aType + '")';
lookup = aLookupString ? lookup + aLookupString : lookup;
// Get the notification and fetch the child element if wanted
return this.getElement({type: "notification_element", subtype: lookup});
} | javascript | function locationBar_getNotificationElement(aType, aLookupString)
{
var lookup = '/id("' + aType + '")';
lookup = aLookupString ? lookup + aLookupString : lookup;
// Get the notification and fetch the child element if wanted
return this.getElement({type: "notification_element", subtype: lookup});
} | [
"function",
"locationBar_getNotificationElement",
"(",
"aType",
",",
"aLookupString",
")",
"{",
"var",
"lookup",
"=",
"'/id(\"'",
"+",
"aType",
"+",
"'\")'",
";",
"lookup",
"=",
"aLookupString",
"?",
"lookup",
"+",
"aLookupString",
":",
"lookup",
";",
"// Get the notification and fetch the child element if wanted",
"return",
"this",
".",
"getElement",
"(",
"{",
"type",
":",
"\"notification_element\"",
",",
"subtype",
":",
"lookup",
"}",
")",
";",
"}"
] | Retrieves the specified element of the door hanger notification bar
@param {string} aType
Type of the notification bar to look for
@param {string} aLookupString
Lookup string of the notification bar's child element
[optional - default: ""]
@return The created element
@type {ElemBase} | [
"Retrieves",
"the",
"specified",
"element",
"of",
"the",
"door",
"hanger",
"notification",
"bar"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/toolbars.js#L450-L457 |
510 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/toolbars.js | locationBar_toggleAutocompletePopup | function locationBar_toggleAutocompletePopup() {
var dropdown = this.getElement({type: "historyDropMarker"});
var stateOpen = this.autoCompleteResults.isOpened;
this._controller.click(dropdown);
this._controller.waitForEval("subject.isOpened == " + stateOpen,
TIMEOUT, 100, this.autoCompleteResults);
} | javascript | function locationBar_toggleAutocompletePopup() {
var dropdown = this.getElement({type: "historyDropMarker"});
var stateOpen = this.autoCompleteResults.isOpened;
this._controller.click(dropdown);
this._controller.waitForEval("subject.isOpened == " + stateOpen,
TIMEOUT, 100, this.autoCompleteResults);
} | [
"function",
"locationBar_toggleAutocompletePopup",
"(",
")",
"{",
"var",
"dropdown",
"=",
"this",
".",
"getElement",
"(",
"{",
"type",
":",
"\"historyDropMarker\"",
"}",
")",
";",
"var",
"stateOpen",
"=",
"this",
".",
"autoCompleteResults",
".",
"isOpened",
";",
"this",
".",
"_controller",
".",
"click",
"(",
"dropdown",
")",
";",
"this",
".",
"_controller",
".",
"waitForEval",
"(",
"\"subject.isOpened == \"",
"+",
"stateOpen",
",",
"TIMEOUT",
",",
"100",
",",
"this",
".",
"autoCompleteResults",
")",
";",
"}"
] | Toggles between the open and closed state of the auto-complete popup | [
"Toggles",
"between",
"the",
"open",
"and",
"closed",
"state",
"of",
"the",
"auto",
"-",
"complete",
"popup"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/toolbars.js#L474-L481 |
511 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/prefs.js | preferencesDialog_close | function preferencesDialog_close(saveChanges) {
saveChanges = (saveChanges == undefined) ? false : saveChanges;
if (mozmill.isWindows) {
var button = this.getElement({type: "button", subtype: (saveChanges ? "accept" : "cancel")});
this._controller.click(button);
} else {
this._controller.keypress(null, 'w', {accelKey: true});
}
} | javascript | function preferencesDialog_close(saveChanges) {
saveChanges = (saveChanges == undefined) ? false : saveChanges;
if (mozmill.isWindows) {
var button = this.getElement({type: "button", subtype: (saveChanges ? "accept" : "cancel")});
this._controller.click(button);
} else {
this._controller.keypress(null, 'w', {accelKey: true});
}
} | [
"function",
"preferencesDialog_close",
"(",
"saveChanges",
")",
"{",
"saveChanges",
"=",
"(",
"saveChanges",
"==",
"undefined",
")",
"?",
"false",
":",
"saveChanges",
";",
"if",
"(",
"mozmill",
".",
"isWindows",
")",
"{",
"var",
"button",
"=",
"this",
".",
"getElement",
"(",
"{",
"type",
":",
"\"button\"",
",",
"subtype",
":",
"(",
"saveChanges",
"?",
"\"accept\"",
":",
"\"cancel\"",
")",
"}",
")",
";",
"this",
".",
"_controller",
".",
"click",
"(",
"button",
")",
";",
"}",
"else",
"{",
"this",
".",
"_controller",
".",
"keypress",
"(",
"null",
",",
"'w'",
",",
"{",
"accelKey",
":",
"true",
"}",
")",
";",
"}",
"}"
] | Close the preferences dialog
@param {MozMillController} controller
MozMillController of the window to operate on
@param {boolean} saveChanges
(Optional) If true the OK button is clicked on Windows which saves
the changes. On OS X and Linux changes are applied immediately | [
"Close",
"the",
"preferences",
"dialog"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/prefs.js#L131-L140 |
512 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/prefs.js | preferences_getPref | function preferences_getPref(prefName, defaultValue, defaultBranch,
interfaceType) {
try {
branch = defaultBranch ? this.defaultPrefBranch : this.prefBranch;
// If interfaceType has been set, handle it differently
if (interfaceType != undefined) {
return branch.getComplexValue(prefName, interfaceType);
}
switch (typeof defaultValue) {
case ('boolean'):
return branch.getBoolPref(prefName);
case ('string'):
return branch.getCharPref(prefName);
case ('number'):
return branch.getIntPref(prefName);
default:
return undefined;
}
} catch(e) {
return defaultValue;
}
} | javascript | function preferences_getPref(prefName, defaultValue, defaultBranch,
interfaceType) {
try {
branch = defaultBranch ? this.defaultPrefBranch : this.prefBranch;
// If interfaceType has been set, handle it differently
if (interfaceType != undefined) {
return branch.getComplexValue(prefName, interfaceType);
}
switch (typeof defaultValue) {
case ('boolean'):
return branch.getBoolPref(prefName);
case ('string'):
return branch.getCharPref(prefName);
case ('number'):
return branch.getIntPref(prefName);
default:
return undefined;
}
} catch(e) {
return defaultValue;
}
} | [
"function",
"preferences_getPref",
"(",
"prefName",
",",
"defaultValue",
",",
"defaultBranch",
",",
"interfaceType",
")",
"{",
"try",
"{",
"branch",
"=",
"defaultBranch",
"?",
"this",
".",
"defaultPrefBranch",
":",
"this",
".",
"prefBranch",
";",
"// If interfaceType has been set, handle it differently",
"if",
"(",
"interfaceType",
"!=",
"undefined",
")",
"{",
"return",
"branch",
".",
"getComplexValue",
"(",
"prefName",
",",
"interfaceType",
")",
";",
"}",
"switch",
"(",
"typeof",
"defaultValue",
")",
"{",
"case",
"(",
"'boolean'",
")",
":",
"return",
"branch",
".",
"getBoolPref",
"(",
"prefName",
")",
";",
"case",
"(",
"'string'",
")",
":",
"return",
"branch",
".",
"getCharPref",
"(",
"prefName",
")",
";",
"case",
"(",
"'number'",
")",
":",
"return",
"branch",
".",
"getIntPref",
"(",
"prefName",
")",
";",
"default",
":",
"return",
"undefined",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"defaultValue",
";",
"}",
"}"
] | Retrieve the value of an individual preference.
@param {string} prefName
The preference to get the value of.
@param {boolean/number/string} defaultValue
The default value if preference cannot be found.
@param {boolean/number/string} defaultBranch
If true the value will be read from the default branch (optional)
@param {string} interfaceType
Interface to use for the complex value (optional)
(nsILocalFile, nsISupportsString, nsIPrefLocalizedString)
@return The value of the requested preference
@type boolean/int/string/complex | [
"Retrieve",
"the",
"value",
"of",
"an",
"individual",
"preference",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/prefs.js#L269-L292 |
513 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/prefs.js | preferences_setPref | function preferences_setPref(prefName, value, interfaceType) {
try {
switch (typeof value) {
case ('boolean'):
this.prefBranch.setBoolPref(prefName, value);
break;
case ('string'):
this.prefBranch.setCharPref(prefName, value);
break;
case ('number'):
this.prefBranch.setIntPref(prefName, value);
break;
default:
this.prefBranch.setComplexValue(prefName, interfaceType, value);
}
} catch(e) {
return false;
}
return true;
} | javascript | function preferences_setPref(prefName, value, interfaceType) {
try {
switch (typeof value) {
case ('boolean'):
this.prefBranch.setBoolPref(prefName, value);
break;
case ('string'):
this.prefBranch.setCharPref(prefName, value);
break;
case ('number'):
this.prefBranch.setIntPref(prefName, value);
break;
default:
this.prefBranch.setComplexValue(prefName, interfaceType, value);
}
} catch(e) {
return false;
}
return true;
} | [
"function",
"preferences_setPref",
"(",
"prefName",
",",
"value",
",",
"interfaceType",
")",
"{",
"try",
"{",
"switch",
"(",
"typeof",
"value",
")",
"{",
"case",
"(",
"'boolean'",
")",
":",
"this",
".",
"prefBranch",
".",
"setBoolPref",
"(",
"prefName",
",",
"value",
")",
";",
"break",
";",
"case",
"(",
"'string'",
")",
":",
"this",
".",
"prefBranch",
".",
"setCharPref",
"(",
"prefName",
",",
"value",
")",
";",
"break",
";",
"case",
"(",
"'number'",
")",
":",
"this",
".",
"prefBranch",
".",
"setIntPref",
"(",
"prefName",
",",
"value",
")",
";",
"break",
";",
"default",
":",
"this",
".",
"prefBranch",
".",
"setComplexValue",
"(",
"prefName",
",",
"interfaceType",
",",
"value",
")",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Set the value of an individual preference.
@param {string} prefName
The preference to set the value of.
@param {boolean/number/string/complex} value
The value to set the preference to.
@param {string} interfaceType
Interface to use for the complex value
(nsILocalFile, nsISupportsString, nsIPrefLocalizedString)
@return Returns if the value was successfully set.
@type boolean | [
"Set",
"the",
"value",
"of",
"an",
"individual",
"preference",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/prefs.js#L308-L328 |
514 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/prefs.js | openPreferencesDialog | function openPreferencesDialog(controller, callback, launcher) {
if(!controller)
throw new Error("No controller given for Preferences Dialog");
if(typeof callback != "function")
throw new Error("No callback given for Preferences Dialog");
if (mozmill.isWindows) {
// Preference dialog is modal on windows, set up our callback
var prefModal = new modalDialog.modalDialog(controller.window);
prefModal.start(callback);
}
// Launch the preference dialog
if (launcher) {
launcher();
} else {
mozmill.getPreferencesController();
}
if (mozmill.isWindows) {
prefModal.waitForDialog();
} else {
// Get the window type of the preferences window depending on the application
var prefWindowType = null;
switch (mozmill.Application) {
case "Thunderbird":
prefWindowType = "Mail:Preferences";
break;
default:
prefWindowType = "Browser:Preferences";
}
utils.handleWindow("type", prefWindowType, callback);
}
} | javascript | function openPreferencesDialog(controller, callback, launcher) {
if(!controller)
throw new Error("No controller given for Preferences Dialog");
if(typeof callback != "function")
throw new Error("No callback given for Preferences Dialog");
if (mozmill.isWindows) {
// Preference dialog is modal on windows, set up our callback
var prefModal = new modalDialog.modalDialog(controller.window);
prefModal.start(callback);
}
// Launch the preference dialog
if (launcher) {
launcher();
} else {
mozmill.getPreferencesController();
}
if (mozmill.isWindows) {
prefModal.waitForDialog();
} else {
// Get the window type of the preferences window depending on the application
var prefWindowType = null;
switch (mozmill.Application) {
case "Thunderbird":
prefWindowType = "Mail:Preferences";
break;
default:
prefWindowType = "Browser:Preferences";
}
utils.handleWindow("type", prefWindowType, callback);
}
} | [
"function",
"openPreferencesDialog",
"(",
"controller",
",",
"callback",
",",
"launcher",
")",
"{",
"if",
"(",
"!",
"controller",
")",
"throw",
"new",
"Error",
"(",
"\"No controller given for Preferences Dialog\"",
")",
";",
"if",
"(",
"typeof",
"callback",
"!=",
"\"function\"",
")",
"throw",
"new",
"Error",
"(",
"\"No callback given for Preferences Dialog\"",
")",
";",
"if",
"(",
"mozmill",
".",
"isWindows",
")",
"{",
"// Preference dialog is modal on windows, set up our callback",
"var",
"prefModal",
"=",
"new",
"modalDialog",
".",
"modalDialog",
"(",
"controller",
".",
"window",
")",
";",
"prefModal",
".",
"start",
"(",
"callback",
")",
";",
"}",
"// Launch the preference dialog",
"if",
"(",
"launcher",
")",
"{",
"launcher",
"(",
")",
";",
"}",
"else",
"{",
"mozmill",
".",
"getPreferencesController",
"(",
")",
";",
"}",
"if",
"(",
"mozmill",
".",
"isWindows",
")",
"{",
"prefModal",
".",
"waitForDialog",
"(",
")",
";",
"}",
"else",
"{",
"// Get the window type of the preferences window depending on the application",
"var",
"prefWindowType",
"=",
"null",
";",
"switch",
"(",
"mozmill",
".",
"Application",
")",
"{",
"case",
"\"Thunderbird\"",
":",
"prefWindowType",
"=",
"\"Mail:Preferences\"",
";",
"break",
";",
"default",
":",
"prefWindowType",
"=",
"\"Browser:Preferences\"",
";",
"}",
"utils",
".",
"handleWindow",
"(",
"\"type\"",
",",
"prefWindowType",
",",
"callback",
")",
";",
"}",
"}"
] | Open the preferences dialog and call the given handler
@param {MozMillController} controller
MozMillController which is the opener of the preferences dialog
@param {function} callback
The callback handler to use to interact with the preference dialog
@param {function} launcher
(Optional) A callback handler to launch the preference dialog | [
"Open",
"the",
"preferences",
"dialog",
"and",
"call",
"the",
"given",
"handler"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/prefs.js#L341-L375 |
515 | SeleniumHQ/selenium | javascript/node/selenium-webdriver/lib/promise.js | map | async function map(array, fn, self = undefined) {
const v = await Promise.resolve(array);
if (!Array.isArray(v)) {
throw TypeError('not an array');
}
const arr = /** @type {!Array} */(v);
const n = arr.length;
const values = new Array(n);
for (let i = 0; i < n; i++) {
if (i in arr) {
values[i] = await Promise.resolve(fn.call(self, arr[i], i, arr));
}
}
return values;
} | javascript | async function map(array, fn, self = undefined) {
const v = await Promise.resolve(array);
if (!Array.isArray(v)) {
throw TypeError('not an array');
}
const arr = /** @type {!Array} */(v);
const n = arr.length;
const values = new Array(n);
for (let i = 0; i < n; i++) {
if (i in arr) {
values[i] = await Promise.resolve(fn.call(self, arr[i], i, arr));
}
}
return values;
} | [
"async",
"function",
"map",
"(",
"array",
",",
"fn",
",",
"self",
"=",
"undefined",
")",
"{",
"const",
"v",
"=",
"await",
"Promise",
".",
"resolve",
"(",
"array",
")",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"v",
")",
")",
"{",
"throw",
"TypeError",
"(",
"'not an array'",
")",
";",
"}",
"const",
"arr",
"=",
"/** @type {!Array} */",
"(",
"v",
")",
";",
"const",
"n",
"=",
"arr",
".",
"length",
";",
"const",
"values",
"=",
"new",
"Array",
"(",
"n",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
"in",
"arr",
")",
"{",
"values",
"[",
"i",
"]",
"=",
"await",
"Promise",
".",
"resolve",
"(",
"fn",
".",
"call",
"(",
"self",
",",
"arr",
"[",
"i",
"]",
",",
"i",
",",
"arr",
")",
")",
";",
"}",
"}",
"return",
"values",
";",
"}"
] | Calls a function for each element in an array and inserts the result into a
new array, which is used as the fulfillment value of the promise returned
by this function.
If the return value of the mapping function is a promise, this function
will wait for it to be fulfilled before inserting it into the new array.
If the mapping function throws or returns a rejected promise, the
promise returned by this function will be rejected with the same reason.
Only the first failure will be reported; all subsequent errors will be
silently ignored.
@param {!(Array<TYPE>|IThenable<!Array<TYPE>>)} array The array to iterate
over, or a promise that will resolve to said array.
@param {function(this: SELF, TYPE, number, !Array<TYPE>): ?} fn The
function to call for each element in the array. This function should
expect three arguments (the element, the index, and the array itself.
@param {SELF=} self The object to be used as the value of 'this' within `fn`.
@template TYPE, SELF | [
"Calls",
"a",
"function",
"for",
"each",
"element",
"in",
"an",
"array",
"and",
"inserts",
"the",
"result",
"into",
"a",
"new",
"array",
"which",
"is",
"used",
"as",
"the",
"fulfillment",
"value",
"of",
"the",
"promise",
"returned",
"by",
"this",
"function",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/node/selenium-webdriver/lib/promise.js#L153-L169 |
516 | SeleniumHQ/selenium | javascript/node/selenium-webdriver/lib/promise.js | filter | async function filter(array, fn, self = undefined) {
const v = await Promise.resolve(array);
if (!Array.isArray(v)) {
throw TypeError('not an array');
}
const arr = /** @type {!Array} */(v);
const n = arr.length;
const values = [];
let valuesLength = 0;
for (let i = 0; i < n; i++) {
if (i in arr) {
let value = arr[i];
let include = await fn.call(self, value, i, arr);
if (include) {
values[valuesLength++] = value;
}
}
}
return values;
} | javascript | async function filter(array, fn, self = undefined) {
const v = await Promise.resolve(array);
if (!Array.isArray(v)) {
throw TypeError('not an array');
}
const arr = /** @type {!Array} */(v);
const n = arr.length;
const values = [];
let valuesLength = 0;
for (let i = 0; i < n; i++) {
if (i in arr) {
let value = arr[i];
let include = await fn.call(self, value, i, arr);
if (include) {
values[valuesLength++] = value;
}
}
}
return values;
} | [
"async",
"function",
"filter",
"(",
"array",
",",
"fn",
",",
"self",
"=",
"undefined",
")",
"{",
"const",
"v",
"=",
"await",
"Promise",
".",
"resolve",
"(",
"array",
")",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"v",
")",
")",
"{",
"throw",
"TypeError",
"(",
"'not an array'",
")",
";",
"}",
"const",
"arr",
"=",
"/** @type {!Array} */",
"(",
"v",
")",
";",
"const",
"n",
"=",
"arr",
".",
"length",
";",
"const",
"values",
"=",
"[",
"]",
";",
"let",
"valuesLength",
"=",
"0",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
"in",
"arr",
")",
"{",
"let",
"value",
"=",
"arr",
"[",
"i",
"]",
";",
"let",
"include",
"=",
"await",
"fn",
".",
"call",
"(",
"self",
",",
"value",
",",
"i",
",",
"arr",
")",
";",
"if",
"(",
"include",
")",
"{",
"values",
"[",
"valuesLength",
"++",
"]",
"=",
"value",
";",
"}",
"}",
"}",
"return",
"values",
";",
"}"
] | Calls a function for each element in an array, and if the function returns
true adds the element to a new array.
If the return value of the filter function is a promise, this function
will wait for it to be fulfilled before determining whether to insert the
element into the new array.
If the filter function throws or returns a rejected promise, the promise
returned by this function will be rejected with the same reason. Only the
first failure will be reported; all subsequent errors will be silently
ignored.
@param {!(Array<TYPE>|IThenable<!Array<TYPE>>)} array The array to iterate
over, or a promise that will resolve to said array.
@param {function(this: SELF, TYPE, number, !Array<TYPE>): (
boolean|IThenable<boolean>)} fn The function
to call for each element in the array.
@param {SELF=} self The object to be used as the value of 'this' within `fn`.
@template TYPE, SELF | [
"Calls",
"a",
"function",
"for",
"each",
"element",
"in",
"an",
"array",
"and",
"if",
"the",
"function",
"returns",
"true",
"adds",
"the",
"element",
"to",
"a",
"new",
"array",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/node/selenium-webdriver/lib/promise.js#L193-L214 |
517 | SeleniumHQ/selenium | javascript/jsunit/app/xbDebug.js | xbDebugApplyFunction | function xbDebugApplyFunction(funcname, funcref, thisref, argumentsref)
{
var rv;
if (!funcref)
{
alert('xbDebugApplyFunction: funcref is null');
}
if (typeof(funcref.apply) != 'undefined')
return funcref.apply(thisref, argumentsref);
var applyexpr = 'thisref.xbDebug_orig_' + funcname + '(';
var i;
for (i = 0; i < argumentsref.length; i++)
{
applyexpr += 'argumentsref[' + i + '],';
}
if (argumentsref.length > 0)
{
applyexpr = applyexpr.substring(0, applyexpr.length - 1);
}
applyexpr += ')';
return eval(applyexpr);
} | javascript | function xbDebugApplyFunction(funcname, funcref, thisref, argumentsref)
{
var rv;
if (!funcref)
{
alert('xbDebugApplyFunction: funcref is null');
}
if (typeof(funcref.apply) != 'undefined')
return funcref.apply(thisref, argumentsref);
var applyexpr = 'thisref.xbDebug_orig_' + funcname + '(';
var i;
for (i = 0; i < argumentsref.length; i++)
{
applyexpr += 'argumentsref[' + i + '],';
}
if (argumentsref.length > 0)
{
applyexpr = applyexpr.substring(0, applyexpr.length - 1);
}
applyexpr += ')';
return eval(applyexpr);
} | [
"function",
"xbDebugApplyFunction",
"(",
"funcname",
",",
"funcref",
",",
"thisref",
",",
"argumentsref",
")",
"{",
"var",
"rv",
";",
"if",
"(",
"!",
"funcref",
")",
"{",
"alert",
"(",
"'xbDebugApplyFunction: funcref is null'",
")",
";",
"}",
"if",
"(",
"typeof",
"(",
"funcref",
".",
"apply",
")",
"!=",
"'undefined'",
")",
"return",
"funcref",
".",
"apply",
"(",
"thisref",
",",
"argumentsref",
")",
";",
"var",
"applyexpr",
"=",
"'thisref.xbDebug_orig_'",
"+",
"funcname",
"+",
"'('",
";",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"argumentsref",
".",
"length",
";",
"i",
"++",
")",
"{",
"applyexpr",
"+=",
"'argumentsref['",
"+",
"i",
"+",
"'],'",
";",
"}",
"if",
"(",
"argumentsref",
".",
"length",
">",
"0",
")",
"{",
"applyexpr",
"=",
"applyexpr",
".",
"substring",
"(",
"0",
",",
"applyexpr",
".",
"length",
"-",
"1",
")",
";",
"}",
"applyexpr",
"+=",
"')'",
";",
"return",
"eval",
"(",
"applyexpr",
")",
";",
"}"
] | emulate functionref.apply for IE mac and IE win < 5.5 | [
"emulate",
"functionref",
".",
"apply",
"for",
"IE",
"mac",
"and",
"IE",
"win",
"<",
"5",
".",
"5"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/jsunit/app/xbDebug.js#L118-L146 |
518 | SeleniumHQ/selenium | javascript/selenium-core/xpath/xpath.js | xpathCollectDescendants | function xpathCollectDescendants(nodelist, node, opt_tagName) {
if (opt_tagName && node.getElementsByTagName) {
copyArray(nodelist, node.getElementsByTagName(opt_tagName));
return;
}
for (var n = node.firstChild; n; n = n.nextSibling) {
nodelist.push(n);
xpathCollectDescendants(nodelist, n);
}
} | javascript | function xpathCollectDescendants(nodelist, node, opt_tagName) {
if (opt_tagName && node.getElementsByTagName) {
copyArray(nodelist, node.getElementsByTagName(opt_tagName));
return;
}
for (var n = node.firstChild; n; n = n.nextSibling) {
nodelist.push(n);
xpathCollectDescendants(nodelist, n);
}
} | [
"function",
"xpathCollectDescendants",
"(",
"nodelist",
",",
"node",
",",
"opt_tagName",
")",
"{",
"if",
"(",
"opt_tagName",
"&&",
"node",
".",
"getElementsByTagName",
")",
"{",
"copyArray",
"(",
"nodelist",
",",
"node",
".",
"getElementsByTagName",
"(",
"opt_tagName",
")",
")",
";",
"return",
";",
"}",
"for",
"(",
"var",
"n",
"=",
"node",
".",
"firstChild",
";",
"n",
";",
"n",
"=",
"n",
".",
"nextSibling",
")",
"{",
"nodelist",
".",
"push",
"(",
"n",
")",
";",
"xpathCollectDescendants",
"(",
"nodelist",
",",
"n",
")",
";",
"}",
"}"
] | Local utility functions that are used by the lexer or parser. | [
"Local",
"utility",
"functions",
"that",
"are",
"used",
"by",
"the",
"lexer",
"or",
"parser",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/selenium-core/xpath/xpath.js#L2362-L2371 |
519 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/private-browsing.js | privateBrowsing | function privateBrowsing(controller) {
this._controller = controller;
this._handler = null;
/**
* Menu item in the main menu to enter/leave Private Browsing mode
* @private
*/
this._pbMenuItem = new elementslib.Elem(this._controller.menus['tools-menu'].privateBrowsingItem);
this._pbTransitionItem = new elementslib.ID(this._controller.window.document, "Tools:PrivateBrowsing");
this.__defineGetter__('_pbs', function() {
delete this._pbs;
return this._pbs = Cc["@mozilla.org/privatebrowsing;1"].
getService(Ci.nsIPrivateBrowsingService);
});
} | javascript | function privateBrowsing(controller) {
this._controller = controller;
this._handler = null;
/**
* Menu item in the main menu to enter/leave Private Browsing mode
* @private
*/
this._pbMenuItem = new elementslib.Elem(this._controller.menus['tools-menu'].privateBrowsingItem);
this._pbTransitionItem = new elementslib.ID(this._controller.window.document, "Tools:PrivateBrowsing");
this.__defineGetter__('_pbs', function() {
delete this._pbs;
return this._pbs = Cc["@mozilla.org/privatebrowsing;1"].
getService(Ci.nsIPrivateBrowsingService);
});
} | [
"function",
"privateBrowsing",
"(",
"controller",
")",
"{",
"this",
".",
"_controller",
"=",
"controller",
";",
"this",
".",
"_handler",
"=",
"null",
";",
"/**\n * Menu item in the main menu to enter/leave Private Browsing mode\n * @private\n */",
"this",
".",
"_pbMenuItem",
"=",
"new",
"elementslib",
".",
"Elem",
"(",
"this",
".",
"_controller",
".",
"menus",
"[",
"'tools-menu'",
"]",
".",
"privateBrowsingItem",
")",
";",
"this",
".",
"_pbTransitionItem",
"=",
"new",
"elementslib",
".",
"ID",
"(",
"this",
".",
"_controller",
".",
"window",
".",
"document",
",",
"\"Tools:PrivateBrowsing\"",
")",
";",
"this",
".",
"__defineGetter__",
"(",
"'_pbs'",
",",
"function",
"(",
")",
"{",
"delete",
"this",
".",
"_pbs",
";",
"return",
"this",
".",
"_pbs",
"=",
"Cc",
"[",
"\"@mozilla.org/privatebrowsing;1\"",
"]",
".",
"getService",
"(",
"Ci",
".",
"nsIPrivateBrowsingService",
")",
";",
"}",
")",
";",
"}"
] | Create a new privateBrowsing instance.
@class This class adds support for the Private Browsing mode
@param {MozMillController} controller
MozMillController to use for the modal entry dialog | [
"Create",
"a",
"new",
"privateBrowsing",
"instance",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/private-browsing.js#L61-L77 |
520 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/private-browsing.js | privateBrowsing_start | function privateBrowsing_start(useShortcut) {
var dialog = null;
if (this.enabled)
return;
if (this.showPrompt) {
dialog = new modalDialog.modalDialog(this._controller.window);
dialog.start(this._handler);
}
if (useShortcut) {
var cmdKey = utils.getEntity(this.getDtds(), "privateBrowsingCmd.commandkey");
this._controller.keypress(null, cmdKey, {accelKey: true, shiftKey: true});
} else {
this._controller.click(this._pbMenuItem);
}
if (dialog) {
dialog.waitForDialog();
}
this.waitForTransistionComplete(true);
} | javascript | function privateBrowsing_start(useShortcut) {
var dialog = null;
if (this.enabled)
return;
if (this.showPrompt) {
dialog = new modalDialog.modalDialog(this._controller.window);
dialog.start(this._handler);
}
if (useShortcut) {
var cmdKey = utils.getEntity(this.getDtds(), "privateBrowsingCmd.commandkey");
this._controller.keypress(null, cmdKey, {accelKey: true, shiftKey: true});
} else {
this._controller.click(this._pbMenuItem);
}
if (dialog) {
dialog.waitForDialog();
}
this.waitForTransistionComplete(true);
} | [
"function",
"privateBrowsing_start",
"(",
"useShortcut",
")",
"{",
"var",
"dialog",
"=",
"null",
";",
"if",
"(",
"this",
".",
"enabled",
")",
"return",
";",
"if",
"(",
"this",
".",
"showPrompt",
")",
"{",
"dialog",
"=",
"new",
"modalDialog",
".",
"modalDialog",
"(",
"this",
".",
"_controller",
".",
"window",
")",
";",
"dialog",
".",
"start",
"(",
"this",
".",
"_handler",
")",
";",
"}",
"if",
"(",
"useShortcut",
")",
"{",
"var",
"cmdKey",
"=",
"utils",
".",
"getEntity",
"(",
"this",
".",
"getDtds",
"(",
")",
",",
"\"privateBrowsingCmd.commandkey\"",
")",
";",
"this",
".",
"_controller",
".",
"keypress",
"(",
"null",
",",
"cmdKey",
",",
"{",
"accelKey",
":",
"true",
",",
"shiftKey",
":",
"true",
"}",
")",
";",
"}",
"else",
"{",
"this",
".",
"_controller",
".",
"click",
"(",
"this",
".",
"_pbMenuItem",
")",
";",
"}",
"if",
"(",
"dialog",
")",
"{",
"dialog",
".",
"waitForDialog",
"(",
")",
";",
"}",
"this",
".",
"waitForTransistionComplete",
"(",
"true",
")",
";",
"}"
] | Start the Private Browsing mode
@param {boolean} useShortcut
Use the keyboard shortcut if true otherwise the menu entry is used | [
"Start",
"the",
"Private",
"Browsing",
"mode"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/private-browsing.js#L176-L198 |
521 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/private-browsing.js | privateBrowsing_stop | function privateBrowsing_stop(useShortcut)
{
if (!this.enabled)
return;
if (useShortcut) {
var privateBrowsingCmdKey = utils.getEntity(this.getDtds(), "privateBrowsingCmd.commandkey");
this._controller.keypress(null, privateBrowsingCmdKey, {accelKey: true, shiftKey: true});
} else {
this._controller.click(this._pbMenuItem);
}
this.waitForTransistionComplete(false);
} | javascript | function privateBrowsing_stop(useShortcut)
{
if (!this.enabled)
return;
if (useShortcut) {
var privateBrowsingCmdKey = utils.getEntity(this.getDtds(), "privateBrowsingCmd.commandkey");
this._controller.keypress(null, privateBrowsingCmdKey, {accelKey: true, shiftKey: true});
} else {
this._controller.click(this._pbMenuItem);
}
this.waitForTransistionComplete(false);
} | [
"function",
"privateBrowsing_stop",
"(",
"useShortcut",
")",
"{",
"if",
"(",
"!",
"this",
".",
"enabled",
")",
"return",
";",
"if",
"(",
"useShortcut",
")",
"{",
"var",
"privateBrowsingCmdKey",
"=",
"utils",
".",
"getEntity",
"(",
"this",
".",
"getDtds",
"(",
")",
",",
"\"privateBrowsingCmd.commandkey\"",
")",
";",
"this",
".",
"_controller",
".",
"keypress",
"(",
"null",
",",
"privateBrowsingCmdKey",
",",
"{",
"accelKey",
":",
"true",
",",
"shiftKey",
":",
"true",
"}",
")",
";",
"}",
"else",
"{",
"this",
".",
"_controller",
".",
"click",
"(",
"this",
".",
"_pbMenuItem",
")",
";",
"}",
"this",
".",
"waitForTransistionComplete",
"(",
"false",
")",
";",
"}"
] | Stop the Private Browsing mode
@param {boolean} useShortcut
Use the keyboard shortcut if true otherwise the menu entry is used | [
"Stop",
"the",
"Private",
"Browsing",
"mode"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/private-browsing.js#L206-L219 |
522 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/private-browsing.js | privateBrowsing_waitForTransitionComplete | function privateBrowsing_waitForTransitionComplete(state) {
// We have to wait until the transition has been finished
this._controller.waitForEval("subject.hasAttribute('disabled') == false", gTimeout, 100,
this._pbTransitionItem.getNode());
this._controller.waitForEval("subject.privateBrowsing.enabled == subject.state", gTimeout, 100,
{privateBrowsing: this, state: state});
} | javascript | function privateBrowsing_waitForTransitionComplete(state) {
// We have to wait until the transition has been finished
this._controller.waitForEval("subject.hasAttribute('disabled') == false", gTimeout, 100,
this._pbTransitionItem.getNode());
this._controller.waitForEval("subject.privateBrowsing.enabled == subject.state", gTimeout, 100,
{privateBrowsing: this, state: state});
} | [
"function",
"privateBrowsing_waitForTransitionComplete",
"(",
"state",
")",
"{",
"// We have to wait until the transition has been finished",
"this",
".",
"_controller",
".",
"waitForEval",
"(",
"\"subject.hasAttribute('disabled') == false\"",
",",
"gTimeout",
",",
"100",
",",
"this",
".",
"_pbTransitionItem",
".",
"getNode",
"(",
")",
")",
";",
"this",
".",
"_controller",
".",
"waitForEval",
"(",
"\"subject.privateBrowsing.enabled == subject.state\"",
",",
"gTimeout",
",",
"100",
",",
"{",
"privateBrowsing",
":",
"this",
",",
"state",
":",
"state",
"}",
")",
";",
"}"
] | Waits until the transistion into or out of the Private Browsing mode happened
@param {boolean} state
Expected target state of the Private Browsing mode | [
"Waits",
"until",
"the",
"transistion",
"into",
"or",
"out",
"of",
"the",
"Private",
"Browsing",
"mode",
"happened"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/private-browsing.js#L227-L233 |
523 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/screenshot.js | create | function create(controller, boxes) {
var doc = controller.window.document;
var maxWidth = doc.documentElement.boxObject.width;
var maxHeight = doc.documentElement.boxObject.height;
var rect = [];
for (var i = 0, j = boxes.length; i < j; ++i) {
rect = boxes[i];
if (rect[0] + rect[2] > maxWidth) maxWidth = rect[0] + rect[2];
if (rect[1] + rect[3] > maxHeight) maxHeight = rect[1] + rect[3];
}
var canvas = doc.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
var width = doc.documentElement.boxObject.width;
var height = doc.documentElement.boxObject.height;
canvas.width = maxWidth;
canvas.height = maxHeight;
var ctx = canvas.getContext("2d");
ctx.clearRect(0,0, canvas.width, canvas.height);
ctx.save();
ctx.drawWindow(controller.window, 0, 0, width, height, "rgb(0,0,0)");
ctx.restore();
ctx.save();
ctx.fillStyle = "rgba(255,0,0,0.4)";
for (var i = 0, j = boxes.length; i < j; ++i) {
rect = boxes[i];
ctx.fillRect(rect[0], rect[1], rect[2], rect[3]);
}
ctx.restore();
_saveCanvas(canvas);
} | javascript | function create(controller, boxes) {
var doc = controller.window.document;
var maxWidth = doc.documentElement.boxObject.width;
var maxHeight = doc.documentElement.boxObject.height;
var rect = [];
for (var i = 0, j = boxes.length; i < j; ++i) {
rect = boxes[i];
if (rect[0] + rect[2] > maxWidth) maxWidth = rect[0] + rect[2];
if (rect[1] + rect[3] > maxHeight) maxHeight = rect[1] + rect[3];
}
var canvas = doc.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
var width = doc.documentElement.boxObject.width;
var height = doc.documentElement.boxObject.height;
canvas.width = maxWidth;
canvas.height = maxHeight;
var ctx = canvas.getContext("2d");
ctx.clearRect(0,0, canvas.width, canvas.height);
ctx.save();
ctx.drawWindow(controller.window, 0, 0, width, height, "rgb(0,0,0)");
ctx.restore();
ctx.save();
ctx.fillStyle = "rgba(255,0,0,0.4)";
for (var i = 0, j = boxes.length; i < j; ++i) {
rect = boxes[i];
ctx.fillRect(rect[0], rect[1], rect[2], rect[3]);
}
ctx.restore();
_saveCanvas(canvas);
} | [
"function",
"create",
"(",
"controller",
",",
"boxes",
")",
"{",
"var",
"doc",
"=",
"controller",
".",
"window",
".",
"document",
";",
"var",
"maxWidth",
"=",
"doc",
".",
"documentElement",
".",
"boxObject",
".",
"width",
";",
"var",
"maxHeight",
"=",
"doc",
".",
"documentElement",
".",
"boxObject",
".",
"height",
";",
"var",
"rect",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"j",
"=",
"boxes",
".",
"length",
";",
"i",
"<",
"j",
";",
"++",
"i",
")",
"{",
"rect",
"=",
"boxes",
"[",
"i",
"]",
";",
"if",
"(",
"rect",
"[",
"0",
"]",
"+",
"rect",
"[",
"2",
"]",
">",
"maxWidth",
")",
"maxWidth",
"=",
"rect",
"[",
"0",
"]",
"+",
"rect",
"[",
"2",
"]",
";",
"if",
"(",
"rect",
"[",
"1",
"]",
"+",
"rect",
"[",
"3",
"]",
">",
"maxHeight",
")",
"maxHeight",
"=",
"rect",
"[",
"1",
"]",
"+",
"rect",
"[",
"3",
"]",
";",
"}",
"var",
"canvas",
"=",
"doc",
".",
"createElementNS",
"(",
"\"http://www.w3.org/1999/xhtml\"",
",",
"\"canvas\"",
")",
";",
"var",
"width",
"=",
"doc",
".",
"documentElement",
".",
"boxObject",
".",
"width",
";",
"var",
"height",
"=",
"doc",
".",
"documentElement",
".",
"boxObject",
".",
"height",
";",
"canvas",
".",
"width",
"=",
"maxWidth",
";",
"canvas",
".",
"height",
"=",
"maxHeight",
";",
"var",
"ctx",
"=",
"canvas",
".",
"getContext",
"(",
"\"2d\"",
")",
";",
"ctx",
".",
"clearRect",
"(",
"0",
",",
"0",
",",
"canvas",
".",
"width",
",",
"canvas",
".",
"height",
")",
";",
"ctx",
".",
"save",
"(",
")",
";",
"ctx",
".",
"drawWindow",
"(",
"controller",
".",
"window",
",",
"0",
",",
"0",
",",
"width",
",",
"height",
",",
"\"rgb(0,0,0)\"",
")",
";",
"ctx",
".",
"restore",
"(",
")",
";",
"ctx",
".",
"save",
"(",
")",
";",
"ctx",
".",
"fillStyle",
"=",
"\"rgba(255,0,0,0.4)\"",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"j",
"=",
"boxes",
".",
"length",
";",
"i",
"<",
"j",
";",
"++",
"i",
")",
"{",
"rect",
"=",
"boxes",
"[",
"i",
"]",
";",
"ctx",
".",
"fillRect",
"(",
"rect",
"[",
"0",
"]",
",",
"rect",
"[",
"1",
"]",
",",
"rect",
"[",
"2",
"]",
",",
"rect",
"[",
"3",
"]",
")",
";",
"}",
"ctx",
".",
"restore",
"(",
")",
";",
"_saveCanvas",
"(",
"canvas",
")",
";",
"}"
] | This function creates a screenshot of the window provided in the given
controller and highlights elements from the coordinates provided in the
given boxes-array.
@param {array of array of int} boxes
@param {MozmillController} controller | [
"This",
"function",
"creates",
"a",
"screenshot",
"of",
"the",
"window",
"provided",
"in",
"the",
"given",
"controller",
"and",
"highlights",
"elements",
"from",
"the",
"coordinates",
"provided",
"in",
"the",
"given",
"boxes",
"-",
"array",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/screenshot.js#L50-L79 |
524 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/screenshot.js | _saveCanvas | function _saveCanvas(canvas) {
// Use the path given on the command line and saved under
// persisted.screenshotPath, if available. If not, use the path to the
// temporary folder as a fallback.
var file = null;
if ("screenshotPath" in persisted) {
file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
file.initWithPath(persisted.screenshotPath);
}
else {
file = Cc["@mozilla.org/file/directory_service;1"].
getService(Ci.nsIProperties).
get("TmpD", Ci.nsIFile);
}
var fileName = utils.appInfo.name + "-" +
utils.appInfo.locale + "." +
utils.appInfo.version + "." +
utils.appInfo.buildID + "." +
utils.appInfo.os + ".png";
file.append(fileName);
// if a file already exists, don't overwrite it and create a new name
file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, parseInt("0666", 8));
// create a data url from the canvas and then create URIs of the source
// and targets
var io = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
var source = io.newURI(canvas.toDataURL("image/png", ""), "UTF8", null);
var target = io.newFileURI(file)
// prepare to save the canvas data
var wbPersist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].
createInstance(Ci.nsIWebBrowserPersist);
wbPersist.persistFlags = Ci.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
wbPersist.persistFlags |= Ci.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
// save the canvas data to the file
wbPersist.saveURI(source, null, null, null, null, file);
} | javascript | function _saveCanvas(canvas) {
// Use the path given on the command line and saved under
// persisted.screenshotPath, if available. If not, use the path to the
// temporary folder as a fallback.
var file = null;
if ("screenshotPath" in persisted) {
file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
file.initWithPath(persisted.screenshotPath);
}
else {
file = Cc["@mozilla.org/file/directory_service;1"].
getService(Ci.nsIProperties).
get("TmpD", Ci.nsIFile);
}
var fileName = utils.appInfo.name + "-" +
utils.appInfo.locale + "." +
utils.appInfo.version + "." +
utils.appInfo.buildID + "." +
utils.appInfo.os + ".png";
file.append(fileName);
// if a file already exists, don't overwrite it and create a new name
file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, parseInt("0666", 8));
// create a data url from the canvas and then create URIs of the source
// and targets
var io = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
var source = io.newURI(canvas.toDataURL("image/png", ""), "UTF8", null);
var target = io.newFileURI(file)
// prepare to save the canvas data
var wbPersist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].
createInstance(Ci.nsIWebBrowserPersist);
wbPersist.persistFlags = Ci.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
wbPersist.persistFlags |= Ci.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
// save the canvas data to the file
wbPersist.saveURI(source, null, null, null, null, file);
} | [
"function",
"_saveCanvas",
"(",
"canvas",
")",
"{",
"// Use the path given on the command line and saved under",
"// persisted.screenshotPath, if available. If not, use the path to the",
"// temporary folder as a fallback.",
"var",
"file",
"=",
"null",
";",
"if",
"(",
"\"screenshotPath\"",
"in",
"persisted",
")",
"{",
"file",
"=",
"Cc",
"[",
"\"@mozilla.org/file/local;1\"",
"]",
".",
"createInstance",
"(",
"Ci",
".",
"nsILocalFile",
")",
";",
"file",
".",
"initWithPath",
"(",
"persisted",
".",
"screenshotPath",
")",
";",
"}",
"else",
"{",
"file",
"=",
"Cc",
"[",
"\"@mozilla.org/file/directory_service;1\"",
"]",
".",
"getService",
"(",
"Ci",
".",
"nsIProperties",
")",
".",
"get",
"(",
"\"TmpD\"",
",",
"Ci",
".",
"nsIFile",
")",
";",
"}",
"var",
"fileName",
"=",
"utils",
".",
"appInfo",
".",
"name",
"+",
"\"-\"",
"+",
"utils",
".",
"appInfo",
".",
"locale",
"+",
"\".\"",
"+",
"utils",
".",
"appInfo",
".",
"version",
"+",
"\".\"",
"+",
"utils",
".",
"appInfo",
".",
"buildID",
"+",
"\".\"",
"+",
"utils",
".",
"appInfo",
".",
"os",
"+",
"\".png\"",
";",
"file",
".",
"append",
"(",
"fileName",
")",
";",
"// if a file already exists, don't overwrite it and create a new name",
"file",
".",
"createUnique",
"(",
"Ci",
".",
"nsIFile",
".",
"NORMAL_FILE_TYPE",
",",
"parseInt",
"(",
"\"0666\"",
",",
"8",
")",
")",
";",
"// create a data url from the canvas and then create URIs of the source",
"// and targets",
"var",
"io",
"=",
"Cc",
"[",
"\"@mozilla.org/network/io-service;1\"",
"]",
".",
"getService",
"(",
"Ci",
".",
"nsIIOService",
")",
";",
"var",
"source",
"=",
"io",
".",
"newURI",
"(",
"canvas",
".",
"toDataURL",
"(",
"\"image/png\"",
",",
"\"\"",
")",
",",
"\"UTF8\"",
",",
"null",
")",
";",
"var",
"target",
"=",
"io",
".",
"newFileURI",
"(",
"file",
")",
"// prepare to save the canvas data",
"var",
"wbPersist",
"=",
"Cc",
"[",
"\"@mozilla.org/embedding/browser/nsWebBrowserPersist;1\"",
"]",
".",
"createInstance",
"(",
"Ci",
".",
"nsIWebBrowserPersist",
")",
";",
"wbPersist",
".",
"persistFlags",
"=",
"Ci",
".",
"nsIWebBrowserPersist",
".",
"PERSIST_FLAGS_REPLACE_EXISTING_FILES",
";",
"wbPersist",
".",
"persistFlags",
"|=",
"Ci",
".",
"nsIWebBrowserPersist",
".",
"PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION",
";",
"// save the canvas data to the file",
"wbPersist",
".",
"saveURI",
"(",
"source",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"file",
")",
";",
"}"
] | Saves a given Canvas object to a file.
The path to save the file under should be given on the command line. If not,
it will be saved in the temporary folder of the system.
@param {canvas} canvas | [
"Saves",
"a",
"given",
"Canvas",
"object",
"to",
"a",
"file",
".",
"The",
"path",
"to",
"save",
"the",
"file",
"under",
"should",
"be",
"given",
"on",
"the",
"command",
"line",
".",
"If",
"not",
"it",
"will",
"be",
"saved",
"in",
"the",
"temporary",
"folder",
"of",
"the",
"system",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/screenshot.js#L88-L128 |
525 | SeleniumHQ/selenium | third_party/closure/goog/module/modulemanager.js | function(requestedId) {
var requestedDeps =
this.getNotYetLoadedTransitiveDepIds_(requestedId);
return goog.array.some(failedIds, function(id) {
return goog.array.contains(requestedDeps, id);
});
} | javascript | function(requestedId) {
var requestedDeps =
this.getNotYetLoadedTransitiveDepIds_(requestedId);
return goog.array.some(failedIds, function(id) {
return goog.array.contains(requestedDeps, id);
});
} | [
"function",
"(",
"requestedId",
")",
"{",
"var",
"requestedDeps",
"=",
"this",
".",
"getNotYetLoadedTransitiveDepIds_",
"(",
"requestedId",
")",
";",
"return",
"goog",
".",
"array",
".",
"some",
"(",
"failedIds",
",",
"function",
"(",
"id",
")",
"{",
"return",
"goog",
".",
"array",
".",
"contains",
"(",
"requestedDeps",
",",
"id",
")",
";",
"}",
")",
";",
"}"
] | Returns true if the requestedId has dependencies on the modules that
just failed to load.
@param {string} requestedId The module to check for dependencies.
@return {boolean} True if the module depends on failed modules. | [
"Returns",
"true",
"if",
"the",
"requestedId",
"has",
"dependencies",
"on",
"the",
"modules",
"that",
"just",
"failed",
"to",
"load",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/closure/goog/module/modulemanager.js#L1220-L1226 |
|
526 | SeleniumHQ/selenium | javascript/selenium-core/lib/scriptaculous/dragdrop.js | function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.tag);
} | javascript | function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.tag);
} | [
"function",
"(",
"element",
",",
"options",
")",
"{",
"return",
"Element",
".",
"findChildren",
"(",
"element",
",",
"options",
".",
"only",
",",
"options",
".",
"tree",
"?",
"true",
":",
"false",
",",
"options",
".",
"tag",
")",
";",
"}"
] | return all suitable-for-sortable elements in a guaranteed order | [
"return",
"all",
"suitable",
"-",
"for",
"-",
"sortable",
"elements",
"in",
"a",
"guaranteed",
"order"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/selenium-core/lib/scriptaculous/dragdrop.js#L665-L668 |
|
527 | SeleniumHQ/selenium | javascript/atoms/dom.js | positiveSize | function positiveSize(e) {
var rect = bot.dom.getClientRect(e);
if (rect.height > 0 && rect.width > 0) {
return true;
}
// A vertical or horizontal SVG Path element will report zero width or
// height but is "shown" if it has a positive stroke-width.
if (bot.dom.isElement(e, 'PATH') && (rect.height > 0 || rect.width > 0)) {
var strokeWidth = bot.dom.getEffectiveStyle(e, 'stroke-width');
return !!strokeWidth && (parseInt(strokeWidth, 10) > 0);
}
// Zero-sized elements should still be considered to have positive size
// if they have a child element or text node with positive size, unless
// the element has an 'overflow' style of 'hidden'.
return bot.dom.getEffectiveStyle(e, 'overflow') != 'hidden' &&
goog.array.some(e.childNodes, function(n) {
return n.nodeType == goog.dom.NodeType.TEXT ||
(bot.dom.isElement(n) && positiveSize(n));
});
} | javascript | function positiveSize(e) {
var rect = bot.dom.getClientRect(e);
if (rect.height > 0 && rect.width > 0) {
return true;
}
// A vertical or horizontal SVG Path element will report zero width or
// height but is "shown" if it has a positive stroke-width.
if (bot.dom.isElement(e, 'PATH') && (rect.height > 0 || rect.width > 0)) {
var strokeWidth = bot.dom.getEffectiveStyle(e, 'stroke-width');
return !!strokeWidth && (parseInt(strokeWidth, 10) > 0);
}
// Zero-sized elements should still be considered to have positive size
// if they have a child element or text node with positive size, unless
// the element has an 'overflow' style of 'hidden'.
return bot.dom.getEffectiveStyle(e, 'overflow') != 'hidden' &&
goog.array.some(e.childNodes, function(n) {
return n.nodeType == goog.dom.NodeType.TEXT ||
(bot.dom.isElement(n) && positiveSize(n));
});
} | [
"function",
"positiveSize",
"(",
"e",
")",
"{",
"var",
"rect",
"=",
"bot",
".",
"dom",
".",
"getClientRect",
"(",
"e",
")",
";",
"if",
"(",
"rect",
".",
"height",
">",
"0",
"&&",
"rect",
".",
"width",
">",
"0",
")",
"{",
"return",
"true",
";",
"}",
"// A vertical or horizontal SVG Path element will report zero width or",
"// height but is \"shown\" if it has a positive stroke-width.",
"if",
"(",
"bot",
".",
"dom",
".",
"isElement",
"(",
"e",
",",
"'PATH'",
")",
"&&",
"(",
"rect",
".",
"height",
">",
"0",
"||",
"rect",
".",
"width",
">",
"0",
")",
")",
"{",
"var",
"strokeWidth",
"=",
"bot",
".",
"dom",
".",
"getEffectiveStyle",
"(",
"e",
",",
"'stroke-width'",
")",
";",
"return",
"!",
"!",
"strokeWidth",
"&&",
"(",
"parseInt",
"(",
"strokeWidth",
",",
"10",
")",
">",
"0",
")",
";",
"}",
"// Zero-sized elements should still be considered to have positive size",
"// if they have a child element or text node with positive size, unless",
"// the element has an 'overflow' style of 'hidden'.",
"return",
"bot",
".",
"dom",
".",
"getEffectiveStyle",
"(",
"e",
",",
"'overflow'",
")",
"!=",
"'hidden'",
"&&",
"goog",
".",
"array",
".",
"some",
"(",
"e",
".",
"childNodes",
",",
"function",
"(",
"n",
")",
"{",
"return",
"n",
".",
"nodeType",
"==",
"goog",
".",
"dom",
".",
"NodeType",
".",
"TEXT",
"||",
"(",
"bot",
".",
"dom",
".",
"isElement",
"(",
"n",
")",
"&&",
"positiveSize",
"(",
"n",
")",
")",
";",
"}",
")",
";",
"}"
] | Any element without positive size dimensions is not shown. | [
"Any",
"element",
"without",
"positive",
"size",
"dimensions",
"is",
"not",
"shown",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/atoms/dom.js#L527-L546 |
528 | SeleniumHQ/selenium | javascript/atoms/dom.js | hiddenByOverflow | function hiddenByOverflow(e) {
return bot.dom.getOverflowState(e) == bot.dom.OverflowState.HIDDEN &&
goog.array.every(e.childNodes, function(n) {
return !bot.dom.isElement(n) || hiddenByOverflow(n) ||
!positiveSize(n);
});
} | javascript | function hiddenByOverflow(e) {
return bot.dom.getOverflowState(e) == bot.dom.OverflowState.HIDDEN &&
goog.array.every(e.childNodes, function(n) {
return !bot.dom.isElement(n) || hiddenByOverflow(n) ||
!positiveSize(n);
});
} | [
"function",
"hiddenByOverflow",
"(",
"e",
")",
"{",
"return",
"bot",
".",
"dom",
".",
"getOverflowState",
"(",
"e",
")",
"==",
"bot",
".",
"dom",
".",
"OverflowState",
".",
"HIDDEN",
"&&",
"goog",
".",
"array",
".",
"every",
"(",
"e",
".",
"childNodes",
",",
"function",
"(",
"n",
")",
"{",
"return",
"!",
"bot",
".",
"dom",
".",
"isElement",
"(",
"n",
")",
"||",
"hiddenByOverflow",
"(",
"n",
")",
"||",
"!",
"positiveSize",
"(",
"n",
")",
";",
"}",
")",
";",
"}"
] | Elements that are hidden by overflow are not shown. | [
"Elements",
"that",
"are",
"hidden",
"by",
"overflow",
"are",
"not",
"shown",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/atoms/dom.js#L552-L558 |
529 | SeleniumHQ/selenium | javascript/atoms/dom.js | getOverflowParent | function getOverflowParent(e) {
var position = bot.dom.getEffectiveStyle(e, 'position');
if (position == 'fixed') {
treatAsFixedPosition = true;
// Fixed-position element may only overflow the viewport.
return e == htmlElem ? null : htmlElem;
} else {
var parent = bot.dom.getParentElement(e);
while (parent && !canBeOverflowed(parent)) {
parent = bot.dom.getParentElement(parent);
}
return parent;
}
function canBeOverflowed(container) {
// The HTML element can always be overflowed.
if (container == htmlElem) {
return true;
}
// An element cannot overflow an element with an inline or contents display style.
var containerDisplay = /** @type {string} */ (
bot.dom.getEffectiveStyle(container, 'display'));
if (goog.string.startsWith(containerDisplay, 'inline') ||
(containerDisplay == 'contents')) {
return false;
}
// An absolute-positioned element cannot overflow a static-positioned one.
if (position == 'absolute' &&
bot.dom.getEffectiveStyle(container, 'position') == 'static') {
return false;
}
return true;
}
} | javascript | function getOverflowParent(e) {
var position = bot.dom.getEffectiveStyle(e, 'position');
if (position == 'fixed') {
treatAsFixedPosition = true;
// Fixed-position element may only overflow the viewport.
return e == htmlElem ? null : htmlElem;
} else {
var parent = bot.dom.getParentElement(e);
while (parent && !canBeOverflowed(parent)) {
parent = bot.dom.getParentElement(parent);
}
return parent;
}
function canBeOverflowed(container) {
// The HTML element can always be overflowed.
if (container == htmlElem) {
return true;
}
// An element cannot overflow an element with an inline or contents display style.
var containerDisplay = /** @type {string} */ (
bot.dom.getEffectiveStyle(container, 'display'));
if (goog.string.startsWith(containerDisplay, 'inline') ||
(containerDisplay == 'contents')) {
return false;
}
// An absolute-positioned element cannot overflow a static-positioned one.
if (position == 'absolute' &&
bot.dom.getEffectiveStyle(container, 'position') == 'static') {
return false;
}
return true;
}
} | [
"function",
"getOverflowParent",
"(",
"e",
")",
"{",
"var",
"position",
"=",
"bot",
".",
"dom",
".",
"getEffectiveStyle",
"(",
"e",
",",
"'position'",
")",
";",
"if",
"(",
"position",
"==",
"'fixed'",
")",
"{",
"treatAsFixedPosition",
"=",
"true",
";",
"// Fixed-position element may only overflow the viewport.",
"return",
"e",
"==",
"htmlElem",
"?",
"null",
":",
"htmlElem",
";",
"}",
"else",
"{",
"var",
"parent",
"=",
"bot",
".",
"dom",
".",
"getParentElement",
"(",
"e",
")",
";",
"while",
"(",
"parent",
"&&",
"!",
"canBeOverflowed",
"(",
"parent",
")",
")",
"{",
"parent",
"=",
"bot",
".",
"dom",
".",
"getParentElement",
"(",
"parent",
")",
";",
"}",
"return",
"parent",
";",
"}",
"function",
"canBeOverflowed",
"(",
"container",
")",
"{",
"// The HTML element can always be overflowed.",
"if",
"(",
"container",
"==",
"htmlElem",
")",
"{",
"return",
"true",
";",
"}",
"// An element cannot overflow an element with an inline or contents display style.",
"var",
"containerDisplay",
"=",
"/** @type {string} */",
"(",
"bot",
".",
"dom",
".",
"getEffectiveStyle",
"(",
"container",
",",
"'display'",
")",
")",
";",
"if",
"(",
"goog",
".",
"string",
".",
"startsWith",
"(",
"containerDisplay",
",",
"'inline'",
")",
"||",
"(",
"containerDisplay",
"==",
"'contents'",
")",
")",
"{",
"return",
"false",
";",
"}",
"// An absolute-positioned element cannot overflow a static-positioned one.",
"if",
"(",
"position",
"==",
"'absolute'",
"&&",
"bot",
".",
"dom",
".",
"getEffectiveStyle",
"(",
"container",
",",
"'position'",
")",
"==",
"'static'",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}",
"}"
] | Return the closest ancestor that the given element may overflow. | [
"Return",
"the",
"closest",
"ancestor",
"that",
"the",
"given",
"element",
"may",
"overflow",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/atoms/dom.js#L655-L688 |
530 | SeleniumHQ/selenium | javascript/atoms/dom.js | getOverflowStyles | function getOverflowStyles(e) {
// When the <html> element has an overflow style of 'visible', it assumes
// the overflow style of the body, and the body is really overflow:visible.
var overflowElem = e;
if (htmlOverflowStyle == 'visible') {
// Note: bodyElem will be null/undefined in SVG documents.
if (e == htmlElem && bodyElem) {
overflowElem = bodyElem;
} else if (e == bodyElem) {
return {x: 'visible', y: 'visible'};
}
}
var overflow = {
x: bot.dom.getEffectiveStyle(overflowElem, 'overflow-x'),
y: bot.dom.getEffectiveStyle(overflowElem, 'overflow-y')
};
// The <html> element cannot have a genuine 'visible' overflow style,
// because the viewport can't expand; 'visible' is really 'auto'.
if (e == htmlElem) {
overflow.x = overflow.x == 'visible' ? 'auto' : overflow.x;
overflow.y = overflow.y == 'visible' ? 'auto' : overflow.y;
}
return overflow;
} | javascript | function getOverflowStyles(e) {
// When the <html> element has an overflow style of 'visible', it assumes
// the overflow style of the body, and the body is really overflow:visible.
var overflowElem = e;
if (htmlOverflowStyle == 'visible') {
// Note: bodyElem will be null/undefined in SVG documents.
if (e == htmlElem && bodyElem) {
overflowElem = bodyElem;
} else if (e == bodyElem) {
return {x: 'visible', y: 'visible'};
}
}
var overflow = {
x: bot.dom.getEffectiveStyle(overflowElem, 'overflow-x'),
y: bot.dom.getEffectiveStyle(overflowElem, 'overflow-y')
};
// The <html> element cannot have a genuine 'visible' overflow style,
// because the viewport can't expand; 'visible' is really 'auto'.
if (e == htmlElem) {
overflow.x = overflow.x == 'visible' ? 'auto' : overflow.x;
overflow.y = overflow.y == 'visible' ? 'auto' : overflow.y;
}
return overflow;
} | [
"function",
"getOverflowStyles",
"(",
"e",
")",
"{",
"// When the <html> element has an overflow style of 'visible', it assumes",
"// the overflow style of the body, and the body is really overflow:visible.",
"var",
"overflowElem",
"=",
"e",
";",
"if",
"(",
"htmlOverflowStyle",
"==",
"'visible'",
")",
"{",
"// Note: bodyElem will be null/undefined in SVG documents.",
"if",
"(",
"e",
"==",
"htmlElem",
"&&",
"bodyElem",
")",
"{",
"overflowElem",
"=",
"bodyElem",
";",
"}",
"else",
"if",
"(",
"e",
"==",
"bodyElem",
")",
"{",
"return",
"{",
"x",
":",
"'visible'",
",",
"y",
":",
"'visible'",
"}",
";",
"}",
"}",
"var",
"overflow",
"=",
"{",
"x",
":",
"bot",
".",
"dom",
".",
"getEffectiveStyle",
"(",
"overflowElem",
",",
"'overflow-x'",
")",
",",
"y",
":",
"bot",
".",
"dom",
".",
"getEffectiveStyle",
"(",
"overflowElem",
",",
"'overflow-y'",
")",
"}",
";",
"// The <html> element cannot have a genuine 'visible' overflow style,",
"// because the viewport can't expand; 'visible' is really 'auto'.",
"if",
"(",
"e",
"==",
"htmlElem",
")",
"{",
"overflow",
".",
"x",
"=",
"overflow",
".",
"x",
"==",
"'visible'",
"?",
"'auto'",
":",
"overflow",
".",
"x",
";",
"overflow",
".",
"y",
"=",
"overflow",
".",
"y",
"==",
"'visible'",
"?",
"'auto'",
":",
"overflow",
".",
"y",
";",
"}",
"return",
"overflow",
";",
"}"
] | Return the x and y overflow styles for the given element. | [
"Return",
"the",
"x",
"and",
"y",
"overflow",
"styles",
"for",
"the",
"given",
"element",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/atoms/dom.js#L691-L714 |
531 | SeleniumHQ/selenium | javascript/atoms/dom.js | getScroll | function getScroll(e) {
if (e == htmlElem) {
return new goog.dom.DomHelper(ownerDoc).getDocumentScroll();
} else {
return new goog.math.Coordinate(e.scrollLeft, e.scrollTop);
}
} | javascript | function getScroll(e) {
if (e == htmlElem) {
return new goog.dom.DomHelper(ownerDoc).getDocumentScroll();
} else {
return new goog.math.Coordinate(e.scrollLeft, e.scrollTop);
}
} | [
"function",
"getScroll",
"(",
"e",
")",
"{",
"if",
"(",
"e",
"==",
"htmlElem",
")",
"{",
"return",
"new",
"goog",
".",
"dom",
".",
"DomHelper",
"(",
"ownerDoc",
")",
".",
"getDocumentScroll",
"(",
")",
";",
"}",
"else",
"{",
"return",
"new",
"goog",
".",
"math",
".",
"Coordinate",
"(",
"e",
".",
"scrollLeft",
",",
"e",
".",
"scrollTop",
")",
";",
"}",
"}"
] | Returns the scroll offset of the given element. | [
"Returns",
"the",
"scroll",
"offset",
"of",
"the",
"given",
"element",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/atoms/dom.js#L717-L723 |
532 | SeleniumHQ/selenium | javascript/webdriver/logging.js | function() {
var obj = {};
for (var type in this.prefs_) {
if (this.prefs_.hasOwnProperty(type)) {
obj[type] = this.prefs_[type].name;
}
}
return obj;
} | javascript | function() {
var obj = {};
for (var type in this.prefs_) {
if (this.prefs_.hasOwnProperty(type)) {
obj[type] = this.prefs_[type].name;
}
}
return obj;
} | [
"function",
"(",
")",
"{",
"var",
"obj",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"type",
"in",
"this",
".",
"prefs_",
")",
"{",
"if",
"(",
"this",
".",
"prefs_",
".",
"hasOwnProperty",
"(",
"type",
")",
")",
"{",
"obj",
"[",
"type",
"]",
"=",
"this",
".",
"prefs_",
"[",
"type",
"]",
".",
"name",
";",
"}",
"}",
"return",
"obj",
";",
"}"
] | Converts this instance to its JSON representation.
@return {!Object.<string, string>} The JSON representation of this set of
preferences. | [
"Converts",
"this",
"instance",
"to",
"its",
"JSON",
"representation",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/javascript/webdriver/logging.js#L274-L282 |
|
533 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/dom-utils.js | unwrapNode | function unwrapNode(aNode) {
var node = aNode;
if (node) {
// unwrap is not available on older branches (3.5 and 3.6) - Bug 533596
if ("unwrap" in XPCNativeWrapper) {
node = XPCNativeWrapper.unwrap(node);
}
else if ("wrappedJSObject" in node) {
node = node.wrappedJSObject;
}
}
return node;
} | javascript | function unwrapNode(aNode) {
var node = aNode;
if (node) {
// unwrap is not available on older branches (3.5 and 3.6) - Bug 533596
if ("unwrap" in XPCNativeWrapper) {
node = XPCNativeWrapper.unwrap(node);
}
else if ("wrappedJSObject" in node) {
node = node.wrappedJSObject;
}
}
return node;
} | [
"function",
"unwrapNode",
"(",
"aNode",
")",
"{",
"var",
"node",
"=",
"aNode",
";",
"if",
"(",
"node",
")",
"{",
"// unwrap is not available on older branches (3.5 and 3.6) - Bug 533596",
"if",
"(",
"\"unwrap\"",
"in",
"XPCNativeWrapper",
")",
"{",
"node",
"=",
"XPCNativeWrapper",
".",
"unwrap",
"(",
"node",
")",
";",
"}",
"else",
"if",
"(",
"\"wrappedJSObject\"",
"in",
"node",
")",
"{",
"node",
"=",
"node",
".",
"wrappedJSObject",
";",
"}",
"}",
"return",
"node",
";",
"}"
] | Unwraps a node which is wrapped into a XPCNativeWrapper or XrayWrapper
@param {DOMnode} Wrapped DOM node
@returns {DOMNode} Unwrapped DOM node | [
"Unwraps",
"a",
"node",
"which",
"is",
"wrapped",
"into",
"a",
"XPCNativeWrapper",
"or",
"XrayWrapper"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/dom-utils.js#L49-L63 |
534 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/dom-utils.js | DOMWalker_walk | function DOMWalker_walk(ids, root, waitFunction) {
if (typeof waitFunction == 'function')
this._controller.waitFor(waitFunction());
if (!root)
root = this._controller.window.document.documentElement;
var resultsArray = this._walk(root);
if (typeof this._callbackResults == 'function')
this._callbackResults(this._controller, resultsArray);
if (ids)
this._prepareTargetWindows(ids);
} | javascript | function DOMWalker_walk(ids, root, waitFunction) {
if (typeof waitFunction == 'function')
this._controller.waitFor(waitFunction());
if (!root)
root = this._controller.window.document.documentElement;
var resultsArray = this._walk(root);
if (typeof this._callbackResults == 'function')
this._callbackResults(this._controller, resultsArray);
if (ids)
this._prepareTargetWindows(ids);
} | [
"function",
"DOMWalker_walk",
"(",
"ids",
",",
"root",
",",
"waitFunction",
")",
"{",
"if",
"(",
"typeof",
"waitFunction",
"==",
"'function'",
")",
"this",
".",
"_controller",
".",
"waitFor",
"(",
"waitFunction",
"(",
")",
")",
";",
"if",
"(",
"!",
"root",
")",
"root",
"=",
"this",
".",
"_controller",
".",
"window",
".",
"document",
".",
"documentElement",
";",
"var",
"resultsArray",
"=",
"this",
".",
"_walk",
"(",
"root",
")",
";",
"if",
"(",
"typeof",
"this",
".",
"_callbackResults",
"==",
"'function'",
")",
"this",
".",
"_callbackResults",
"(",
"this",
".",
"_controller",
",",
"resultsArray",
")",
";",
"if",
"(",
"ids",
")",
"this",
".",
"_prepareTargetWindows",
"(",
"ids",
")",
";",
"}"
] | The main DOMWalker function.
It start's the _walk-method for a given window or other dialog, runs
a callback to process the results for that window/dialog.
After that switches to provided new windows/dialogs.
@param {array of objects} ids
Contains informations on the elements to open while
Object-elements: getBy - attribute-name of the attribute
containing the identification
information for the opener-element
subContent - array of ids of the opener-elements
in the window with the value of
the above getBy-attribute
target - information, where the new
elements will be opened
[1|2|4]
title - title of the opened dialog/window
waitFunction - The function used as an argument
for MozmillController.waitFor to
wait before starting the walk.
[optional - default: no waiting]
windowHandler - Window instance
[only needed for some tests]
@param {Node} root
Node to start testing from
[optional - default: this._controller.window.document.documentElement]
@param {Function} waitFunction
The function used as an argument for MozmillController.waitFor to
wait before starting the walk.
[optional - default: no waiting] | [
"The",
"main",
"DOMWalker",
"function",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/dom-utils.js#L171-L185 |
535 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/dom-utils.js | DOMWalker_getNode | function DOMWalker_getNode(idSet) {
var doc = this._controller.window.document;
// QuerySelector seems to be unusuale for id's in this case:
// https://developer.mozilla.org/En/Code_snippets/QuerySelector
switch (idSet.getBy) {
case DOMWalker.GET_BY_ID:
return doc.getElementById(idSet[idSet.getBy]);
case DOMWalker.GET_BY_SELECTOR:
return doc.querySelector(idSet[idSet.getBy]);
default:
throw new Error("Not supported getBy-attribute: " + idSet.getBy);
}
} | javascript | function DOMWalker_getNode(idSet) {
var doc = this._controller.window.document;
// QuerySelector seems to be unusuale for id's in this case:
// https://developer.mozilla.org/En/Code_snippets/QuerySelector
switch (idSet.getBy) {
case DOMWalker.GET_BY_ID:
return doc.getElementById(idSet[idSet.getBy]);
case DOMWalker.GET_BY_SELECTOR:
return doc.querySelector(idSet[idSet.getBy]);
default:
throw new Error("Not supported getBy-attribute: " + idSet.getBy);
}
} | [
"function",
"DOMWalker_getNode",
"(",
"idSet",
")",
"{",
"var",
"doc",
"=",
"this",
".",
"_controller",
".",
"window",
".",
"document",
";",
"// QuerySelector seems to be unusuale for id's in this case:",
"// https://developer.mozilla.org/En/Code_snippets/QuerySelector",
"switch",
"(",
"idSet",
".",
"getBy",
")",
"{",
"case",
"DOMWalker",
".",
"GET_BY_ID",
":",
"return",
"doc",
".",
"getElementById",
"(",
"idSet",
"[",
"idSet",
".",
"getBy",
"]",
")",
";",
"case",
"DOMWalker",
".",
"GET_BY_SELECTOR",
":",
"return",
"doc",
".",
"querySelector",
"(",
"idSet",
"[",
"idSet",
".",
"getBy",
"]",
")",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"\"Not supported getBy-attribute: \"",
"+",
"idSet",
".",
"getBy",
")",
";",
"}",
"}"
] | Retrieves and returns a wanted node based on the provided identification
set.
@param {array of objects} idSet
Contains informations on the elements to open while
Object-elements: getBy - attribute-name of the attribute
containing the identification
information for the opener-element
subContent - array of ids of the opener-elements
in the window with the value of
the above getBy-attribute
target - information, where the new
elements will be opened
[1|2|4]
title - title of the opened dialog/window
waitFunction - The function used as an argument
for MozmillController.waitFor to
wait before starting the walk.
[optional - default: no waiting]
windowHandler - Window instance
[only needed for some tests]
@returns Node
@type {Node} | [
"Retrieves",
"and",
"returns",
"a",
"wanted",
"node",
"based",
"on",
"the",
"provided",
"identification",
"set",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/dom-utils.js#L213-L226 |
536 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/dom-utils.js | DOMWalker_prepareTargetWindows | function DOMWalker_prepareTargetWindows(ids) {
var doc = this._controller.window.document;
// Go through all the provided ids
for (var i = 0; i < ids.length; i++) {
var node = this._getNode(ids[i]);
// Go further only, if the needed element exists
if (node) {
var idSet = ids[i];
// Decide if what we want to open is a new normal/modal window or if it
// will be opened in the current window.
switch (idSet.target) {
case DOMWalker.WINDOW_CURRENT:
this._processNode(node, idSet);
break;
case DOMWalker.WINDOW_MODAL:
// Modal windows have to be able to access that informations
var modalInfos = {ids : idSet.subContent,
callbackFilter : this._callbackFilter,
callbackNodeTest : this._callbackNodeTest,
callbackResults : this._callbackResults,
waitFunction : idSet.waitFunction}
persisted.modalInfos = modalInfos;
var md = new modalDialog.modalDialog(this._controller.window);
md.start(this._modalWindowHelper);
this._processNode(node, idSet);
md.waitForDialog();
break;
case DOMWalker.WINDOW_NEW:
this._processNode(node, idSet);
// Get the new non-modal window controller
var controller = utils.handleWindow('title', idSet.title,
false, true);
// Start a new DOMWalker instance
let domWalker = new DOMWalker(controller, this._callbackFilter,
this._callbackNodeTest,
this._callbackResults);
domWalker.walk(idSet.subContent,
controller.window.document.documentElement,
idSet.waitFunction);
// Close the window
controller.window.close();
break;
default:
throw new Error("Node does not exist: " + ids[i][ids[i].getBy]);
}
}
}
} | javascript | function DOMWalker_prepareTargetWindows(ids) {
var doc = this._controller.window.document;
// Go through all the provided ids
for (var i = 0; i < ids.length; i++) {
var node = this._getNode(ids[i]);
// Go further only, if the needed element exists
if (node) {
var idSet = ids[i];
// Decide if what we want to open is a new normal/modal window or if it
// will be opened in the current window.
switch (idSet.target) {
case DOMWalker.WINDOW_CURRENT:
this._processNode(node, idSet);
break;
case DOMWalker.WINDOW_MODAL:
// Modal windows have to be able to access that informations
var modalInfos = {ids : idSet.subContent,
callbackFilter : this._callbackFilter,
callbackNodeTest : this._callbackNodeTest,
callbackResults : this._callbackResults,
waitFunction : idSet.waitFunction}
persisted.modalInfos = modalInfos;
var md = new modalDialog.modalDialog(this._controller.window);
md.start(this._modalWindowHelper);
this._processNode(node, idSet);
md.waitForDialog();
break;
case DOMWalker.WINDOW_NEW:
this._processNode(node, idSet);
// Get the new non-modal window controller
var controller = utils.handleWindow('title', idSet.title,
false, true);
// Start a new DOMWalker instance
let domWalker = new DOMWalker(controller, this._callbackFilter,
this._callbackNodeTest,
this._callbackResults);
domWalker.walk(idSet.subContent,
controller.window.document.documentElement,
idSet.waitFunction);
// Close the window
controller.window.close();
break;
default:
throw new Error("Node does not exist: " + ids[i][ids[i].getBy]);
}
}
}
} | [
"function",
"DOMWalker_prepareTargetWindows",
"(",
"ids",
")",
"{",
"var",
"doc",
"=",
"this",
".",
"_controller",
".",
"window",
".",
"document",
";",
"// Go through all the provided ids",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"ids",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"node",
"=",
"this",
".",
"_getNode",
"(",
"ids",
"[",
"i",
"]",
")",
";",
"// Go further only, if the needed element exists",
"if",
"(",
"node",
")",
"{",
"var",
"idSet",
"=",
"ids",
"[",
"i",
"]",
";",
"// Decide if what we want to open is a new normal/modal window or if it",
"// will be opened in the current window.",
"switch",
"(",
"idSet",
".",
"target",
")",
"{",
"case",
"DOMWalker",
".",
"WINDOW_CURRENT",
":",
"this",
".",
"_processNode",
"(",
"node",
",",
"idSet",
")",
";",
"break",
";",
"case",
"DOMWalker",
".",
"WINDOW_MODAL",
":",
"// Modal windows have to be able to access that informations",
"var",
"modalInfos",
"=",
"{",
"ids",
":",
"idSet",
".",
"subContent",
",",
"callbackFilter",
":",
"this",
".",
"_callbackFilter",
",",
"callbackNodeTest",
":",
"this",
".",
"_callbackNodeTest",
",",
"callbackResults",
":",
"this",
".",
"_callbackResults",
",",
"waitFunction",
":",
"idSet",
".",
"waitFunction",
"}",
"persisted",
".",
"modalInfos",
"=",
"modalInfos",
";",
"var",
"md",
"=",
"new",
"modalDialog",
".",
"modalDialog",
"(",
"this",
".",
"_controller",
".",
"window",
")",
";",
"md",
".",
"start",
"(",
"this",
".",
"_modalWindowHelper",
")",
";",
"this",
".",
"_processNode",
"(",
"node",
",",
"idSet",
")",
";",
"md",
".",
"waitForDialog",
"(",
")",
";",
"break",
";",
"case",
"DOMWalker",
".",
"WINDOW_NEW",
":",
"this",
".",
"_processNode",
"(",
"node",
",",
"idSet",
")",
";",
"// Get the new non-modal window controller",
"var",
"controller",
"=",
"utils",
".",
"handleWindow",
"(",
"'title'",
",",
"idSet",
".",
"title",
",",
"false",
",",
"true",
")",
";",
"// Start a new DOMWalker instance",
"let",
"domWalker",
"=",
"new",
"DOMWalker",
"(",
"controller",
",",
"this",
".",
"_callbackFilter",
",",
"this",
".",
"_callbackNodeTest",
",",
"this",
".",
"_callbackResults",
")",
";",
"domWalker",
".",
"walk",
"(",
"idSet",
".",
"subContent",
",",
"controller",
".",
"window",
".",
"document",
".",
"documentElement",
",",
"idSet",
".",
"waitFunction",
")",
";",
"// Close the window",
"controller",
".",
"window",
".",
"close",
"(",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"\"Node does not exist: \"",
"+",
"ids",
"[",
"i",
"]",
"[",
"ids",
"[",
"i",
"]",
".",
"getBy",
"]",
")",
";",
"}",
"}",
"}",
"}"
] | Main entry point to open new elements like windows, tabpanels, prefpanes,
dialogs
@param {array of objects} ids
Contains informations on the elements to open while
Object-elements: getBy - attribute-name of the attribute
containing the identification
information for the opener-element
subContent - array of ids of the opener-elements
in the window with the value of
the above getBy-attribute
target - information, where the new
elements will be opened
[1|2|4]
title - title of the opened dialog/window
waitFunction - The function used as an argument
for MozmillController.waitFor to
wait before starting the walk.
[optional - default: no waiting]
windowHandler - Window instance
[only needed for some tests] | [
"Main",
"entry",
"point",
"to",
"open",
"new",
"elements",
"like",
"windows",
"tabpanels",
"prefpanes",
"dialogs"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/dom-utils.js#L251-L306 |
537 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/dom-utils.js | DOMWalker__walk | function DOMWalker__walk(root) {
if (!root.childNodes)
throw new Error("root.childNodes does not exist");
var collectedResults = [];
for (var i = 0; i < root.childNodes.length; i++) {
var nodeStatus = this._callbackFilter(root.childNodes[i]);
var nodeTestResults = [];
switch (nodeStatus) {
case DOMWalker.FILTER_ACCEPT:
nodeTestResults = this._callbackNodeTest(root.childNodes[i]);
collectedResults = collectedResults.concat(nodeTestResults);
// no break here as we have to perform the _walk below too
case DOMWalker.FILTER_SKIP:
nodeTestResults = this._walk(root.childNodes[i]);
break;
default:
break;
}
collectedResults = collectedResults.concat(nodeTestResults);
}
return collectedResults;
} | javascript | function DOMWalker__walk(root) {
if (!root.childNodes)
throw new Error("root.childNodes does not exist");
var collectedResults = [];
for (var i = 0; i < root.childNodes.length; i++) {
var nodeStatus = this._callbackFilter(root.childNodes[i]);
var nodeTestResults = [];
switch (nodeStatus) {
case DOMWalker.FILTER_ACCEPT:
nodeTestResults = this._callbackNodeTest(root.childNodes[i]);
collectedResults = collectedResults.concat(nodeTestResults);
// no break here as we have to perform the _walk below too
case DOMWalker.FILTER_SKIP:
nodeTestResults = this._walk(root.childNodes[i]);
break;
default:
break;
}
collectedResults = collectedResults.concat(nodeTestResults);
}
return collectedResults;
} | [
"function",
"DOMWalker__walk",
"(",
"root",
")",
"{",
"if",
"(",
"!",
"root",
".",
"childNodes",
")",
"throw",
"new",
"Error",
"(",
"\"root.childNodes does not exist\"",
")",
";",
"var",
"collectedResults",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"root",
".",
"childNodes",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"nodeStatus",
"=",
"this",
".",
"_callbackFilter",
"(",
"root",
".",
"childNodes",
"[",
"i",
"]",
")",
";",
"var",
"nodeTestResults",
"=",
"[",
"]",
";",
"switch",
"(",
"nodeStatus",
")",
"{",
"case",
"DOMWalker",
".",
"FILTER_ACCEPT",
":",
"nodeTestResults",
"=",
"this",
".",
"_callbackNodeTest",
"(",
"root",
".",
"childNodes",
"[",
"i",
"]",
")",
";",
"collectedResults",
"=",
"collectedResults",
".",
"concat",
"(",
"nodeTestResults",
")",
";",
"// no break here as we have to perform the _walk below too",
"case",
"DOMWalker",
".",
"FILTER_SKIP",
":",
"nodeTestResults",
"=",
"this",
".",
"_walk",
"(",
"root",
".",
"childNodes",
"[",
"i",
"]",
")",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"collectedResults",
"=",
"collectedResults",
".",
"concat",
"(",
"nodeTestResults",
")",
";",
"}",
"return",
"collectedResults",
";",
"}"
] | DOMWalker_walk goes recursively through the DOM, starting with a provided
root-node.
First, it filters nodes by submitting each node to the this._callbackFilter
method to decide, if a node should be submitted to a provided
this._callbackNodeTest method to test (that hapens in case of
FILTER_ACCEPT).
In case of FILTER_ACCEPT and FILTER_SKIP, the children of such a node
will be filtered recursively.
Nodes with the nodeStatus "FILTER_REJECT" and their descendants will be
completetly ignored.
@param {Node} root
Node to start testing from
[optional - default: this._controller.window.document.documentElement]
@returns An array with gathered all results from testing a given element
@type {array of elements} | [
"DOMWalker_walk",
"goes",
"recursively",
"through",
"the",
"DOM",
"starting",
"with",
"a",
"provided",
"root",
"-",
"node",
"."
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/dom-utils.js#L423-L449 |
538 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/dom-utils.js | DOMWalker_modalWindowHelper | function DOMWalker_modalWindowHelper(controller) {
let domWalker = new DOMWalker(controller,
persisted.modalInfos.callbackFilter,
persisted.modalInfos.callbackNodeTest,
persisted.modalInfos.callbackResults);
domWalker.walk(persisted.modalInfos.ids,
controller.window.document.documentElement,
persisted.modalInfos.waitFunction);
delete persisted.modalInfos;
controller.window.close();
} | javascript | function DOMWalker_modalWindowHelper(controller) {
let domWalker = new DOMWalker(controller,
persisted.modalInfos.callbackFilter,
persisted.modalInfos.callbackNodeTest,
persisted.modalInfos.callbackResults);
domWalker.walk(persisted.modalInfos.ids,
controller.window.document.documentElement,
persisted.modalInfos.waitFunction);
delete persisted.modalInfos;
controller.window.close();
} | [
"function",
"DOMWalker_modalWindowHelper",
"(",
"controller",
")",
"{",
"let",
"domWalker",
"=",
"new",
"DOMWalker",
"(",
"controller",
",",
"persisted",
".",
"modalInfos",
".",
"callbackFilter",
",",
"persisted",
".",
"modalInfos",
".",
"callbackNodeTest",
",",
"persisted",
".",
"modalInfos",
".",
"callbackResults",
")",
";",
"domWalker",
".",
"walk",
"(",
"persisted",
".",
"modalInfos",
".",
"ids",
",",
"controller",
".",
"window",
".",
"document",
".",
"documentElement",
",",
"persisted",
".",
"modalInfos",
".",
"waitFunction",
")",
";",
"delete",
"persisted",
".",
"modalInfos",
";",
"controller",
".",
"window",
".",
"close",
"(",
")",
";",
"}"
] | Callback function to handle new windows
@param {MozMillController} controller
MozMill controller of the new window to operate on. | [
"Callback",
"function",
"to",
"handle",
"new",
"windows"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/dom-utils.js#L457-L469 |
539 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/dom-utils.js | nodeCollector_filter | function nodeCollector_filter(aCallback, aThisObject) {
if (!aCallback)
throw new Error(arguments.callee.name + ": No callback specified");
this.nodes = Array.filter(this.nodes, aCallback, aThisObject);
return this;
} | javascript | function nodeCollector_filter(aCallback, aThisObject) {
if (!aCallback)
throw new Error(arguments.callee.name + ": No callback specified");
this.nodes = Array.filter(this.nodes, aCallback, aThisObject);
return this;
} | [
"function",
"nodeCollector_filter",
"(",
"aCallback",
",",
"aThisObject",
")",
"{",
"if",
"(",
"!",
"aCallback",
")",
"throw",
"new",
"Error",
"(",
"arguments",
".",
"callee",
".",
"name",
"+",
"\": No callback specified\"",
")",
";",
"this",
".",
"nodes",
"=",
"Array",
".",
"filter",
"(",
"this",
".",
"nodes",
",",
"aCallback",
",",
"aThisObject",
")",
";",
"return",
"this",
";",
"}"
] | Filter nodes given by the specified callback function
@param {function} aCallback
Function to test each element of the array.
Elements: node, index (optional) , array (optional)
@param {object} aThisObject
Object to use as 'this' when executing callback.
[optional - default: function scope]
@returns The class instance
@type {object} | [
"Filter",
"nodes",
"given",
"by",
"the",
"specified",
"callback",
"function"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/dom-utils.js#L566-L573 |
540 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/dom-utils.js | nodeCollector_filterByDOMProperty | function nodeCollector_filterByDOMProperty(aProperty, aValue) {
return this.filter(function(node) {
if (aProperty && aValue)
return node.getAttribute(aProperty) == aValue;
else if (aProperty)
return node.hasAttribute(aProperty);
else
return true;
});
} | javascript | function nodeCollector_filterByDOMProperty(aProperty, aValue) {
return this.filter(function(node) {
if (aProperty && aValue)
return node.getAttribute(aProperty) == aValue;
else if (aProperty)
return node.hasAttribute(aProperty);
else
return true;
});
} | [
"function",
"nodeCollector_filterByDOMProperty",
"(",
"aProperty",
",",
"aValue",
")",
"{",
"return",
"this",
".",
"filter",
"(",
"function",
"(",
"node",
")",
"{",
"if",
"(",
"aProperty",
"&&",
"aValue",
")",
"return",
"node",
".",
"getAttribute",
"(",
"aProperty",
")",
"==",
"aValue",
";",
"else",
"if",
"(",
"aProperty",
")",
"return",
"node",
".",
"hasAttribute",
"(",
"aProperty",
")",
";",
"else",
"return",
"true",
";",
"}",
")",
";",
"}"
] | Filter nodes by DOM property and its value
@param {string} aProperty
Property to filter for
@param {string} aValue
Expected value of the DOM property
[optional - default: n/a]
@returns The class instance
@type {object} | [
"Filter",
"nodes",
"by",
"DOM",
"property",
"and",
"its",
"value"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/dom-utils.js#L587-L596 |
541 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/dom-utils.js | nodeCollector_filterByJSProperty | function nodeCollector_filterByJSProperty(aProperty, aValue) {
return this.filter(function(node) {
if (aProperty && aValue)
return node.aProperty == aValue;
else if (aProperty)
return node.aProperty !== undefined;
else
return true;
});
} | javascript | function nodeCollector_filterByJSProperty(aProperty, aValue) {
return this.filter(function(node) {
if (aProperty && aValue)
return node.aProperty == aValue;
else if (aProperty)
return node.aProperty !== undefined;
else
return true;
});
} | [
"function",
"nodeCollector_filterByJSProperty",
"(",
"aProperty",
",",
"aValue",
")",
"{",
"return",
"this",
".",
"filter",
"(",
"function",
"(",
"node",
")",
"{",
"if",
"(",
"aProperty",
"&&",
"aValue",
")",
"return",
"node",
".",
"aProperty",
"==",
"aValue",
";",
"else",
"if",
"(",
"aProperty",
")",
"return",
"node",
".",
"aProperty",
"!==",
"undefined",
";",
"else",
"return",
"true",
";",
"}",
")",
";",
"}"
] | Filter nodes by JS property and its value
@param {string} aProperty
Property to filter for
@param {string} aValue
Expected value of the JS property
[optional - default: n/a]
@returns The class instance
@type {object} | [
"Filter",
"nodes",
"by",
"JS",
"property",
"and",
"its",
"value"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/dom-utils.js#L610-L619 |
542 | SeleniumHQ/selenium | third_party/js/mozmill/shared-modules/dom-utils.js | nodeCollector_queryAnonymousNodes | function nodeCollector_queryAnonymousNodes(aAttribute, aValue) {
var node = this._document.getAnonymousElementByAttribute(this._root,
aAttribute,
aValue);
this.nodes = node ? [node] : [ ];
return this;
} | javascript | function nodeCollector_queryAnonymousNodes(aAttribute, aValue) {
var node = this._document.getAnonymousElementByAttribute(this._root,
aAttribute,
aValue);
this.nodes = node ? [node] : [ ];
return this;
} | [
"function",
"nodeCollector_queryAnonymousNodes",
"(",
"aAttribute",
",",
"aValue",
")",
"{",
"var",
"node",
"=",
"this",
".",
"_document",
".",
"getAnonymousElementByAttribute",
"(",
"this",
".",
"_root",
",",
"aAttribute",
",",
"aValue",
")",
";",
"this",
".",
"nodes",
"=",
"node",
"?",
"[",
"node",
"]",
":",
"[",
"]",
";",
"return",
"this",
";",
"}"
] | Find anonymouse nodes with the specified attribute and value
@param {string} aAttribute
DOM attribute of the wanted node
@param {string} aValue
Value of the DOM attribute
@returns The class instance
@type {object} | [
"Find",
"anonymouse",
"nodes",
"with",
"the",
"specified",
"attribute",
"and",
"value"
] | 38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd | https://github.com/SeleniumHQ/selenium/blob/38d5e4440b2c866a78a1ccb2a18d9795a1bdeafd/third_party/js/mozmill/shared-modules/dom-utils.js#L632-L639 |
543 | tailwindcss/tailwindcss | src/cli/commands/build.js | stopWithHelp | function stopWithHelp(...msgs) {
utils.header()
utils.error(...msgs)
commands.help.forCommand(commands.build)
utils.die()
} | javascript | function stopWithHelp(...msgs) {
utils.header()
utils.error(...msgs)
commands.help.forCommand(commands.build)
utils.die()
} | [
"function",
"stopWithHelp",
"(",
"...",
"msgs",
")",
"{",
"utils",
".",
"header",
"(",
")",
"utils",
".",
"error",
"(",
"...",
"msgs",
")",
"commands",
".",
"help",
".",
"forCommand",
"(",
"commands",
".",
"build",
")",
"utils",
".",
"die",
"(",
")",
"}"
] | Prints the error message and help for this command, then stops the process.
@param {...string} [msgs] | [
"Prints",
"the",
"error",
"message",
"and",
"help",
"for",
"this",
"command",
"then",
"stops",
"the",
"process",
"."
] | 5066a1e97b3f06b899a4539767ca2bee4bde2da9 | https://github.com/tailwindcss/tailwindcss/blob/5066a1e97b3f06b899a4539767ca2bee4bde2da9/src/cli/commands/build.js#L53-L58 |
544 | tailwindcss/tailwindcss | src/cli/commands/build.js | buildToStdout | function buildToStdout(compileOptions) {
return compile(compileOptions).then(result => process.stdout.write(result.css))
} | javascript | function buildToStdout(compileOptions) {
return compile(compileOptions).then(result => process.stdout.write(result.css))
} | [
"function",
"buildToStdout",
"(",
"compileOptions",
")",
"{",
"return",
"compile",
"(",
"compileOptions",
")",
".",
"then",
"(",
"result",
"=>",
"process",
".",
"stdout",
".",
"write",
"(",
"result",
".",
"css",
")",
")",
"}"
] | Compiles CSS file and writes it to stdout.
@param {CompileOptions} compileOptions
@return {Promise} | [
"Compiles",
"CSS",
"file",
"and",
"writes",
"it",
"to",
"stdout",
"."
] | 5066a1e97b3f06b899a4539767ca2bee4bde2da9 | https://github.com/tailwindcss/tailwindcss/blob/5066a1e97b3f06b899a4539767ca2bee4bde2da9/src/cli/commands/build.js#L66-L68 |
545 | tailwindcss/tailwindcss | src/cli/commands/build.js | buildToFile | function buildToFile(compileOptions, startTime) {
utils.header()
utils.log()
utils.log(emoji.go, 'Building...', chalk.bold.cyan(compileOptions.inputFile))
return compile(compileOptions).then(result => {
utils.writeFile(compileOptions.outputFile, result.css)
const prettyTime = prettyHrtime(process.hrtime(startTime))
utils.log()
utils.log(emoji.yes, 'Finished in', chalk.bold.magenta(prettyTime))
utils.log(emoji.pack, 'Size:', chalk.bold.magenta(bytes(result.css.length)))
utils.log(emoji.disk, 'Saved to', chalk.bold.cyan(compileOptions.outputFile))
utils.footer()
})
} | javascript | function buildToFile(compileOptions, startTime) {
utils.header()
utils.log()
utils.log(emoji.go, 'Building...', chalk.bold.cyan(compileOptions.inputFile))
return compile(compileOptions).then(result => {
utils.writeFile(compileOptions.outputFile, result.css)
const prettyTime = prettyHrtime(process.hrtime(startTime))
utils.log()
utils.log(emoji.yes, 'Finished in', chalk.bold.magenta(prettyTime))
utils.log(emoji.pack, 'Size:', chalk.bold.magenta(bytes(result.css.length)))
utils.log(emoji.disk, 'Saved to', chalk.bold.cyan(compileOptions.outputFile))
utils.footer()
})
} | [
"function",
"buildToFile",
"(",
"compileOptions",
",",
"startTime",
")",
"{",
"utils",
".",
"header",
"(",
")",
"utils",
".",
"log",
"(",
")",
"utils",
".",
"log",
"(",
"emoji",
".",
"go",
",",
"'Building...'",
",",
"chalk",
".",
"bold",
".",
"cyan",
"(",
"compileOptions",
".",
"inputFile",
")",
")",
"return",
"compile",
"(",
"compileOptions",
")",
".",
"then",
"(",
"result",
"=>",
"{",
"utils",
".",
"writeFile",
"(",
"compileOptions",
".",
"outputFile",
",",
"result",
".",
"css",
")",
"const",
"prettyTime",
"=",
"prettyHrtime",
"(",
"process",
".",
"hrtime",
"(",
"startTime",
")",
")",
"utils",
".",
"log",
"(",
")",
"utils",
".",
"log",
"(",
"emoji",
".",
"yes",
",",
"'Finished in'",
",",
"chalk",
".",
"bold",
".",
"magenta",
"(",
"prettyTime",
")",
")",
"utils",
".",
"log",
"(",
"emoji",
".",
"pack",
",",
"'Size:'",
",",
"chalk",
".",
"bold",
".",
"magenta",
"(",
"bytes",
"(",
"result",
".",
"css",
".",
"length",
")",
")",
")",
"utils",
".",
"log",
"(",
"emoji",
".",
"disk",
",",
"'Saved to'",
",",
"chalk",
".",
"bold",
".",
"cyan",
"(",
"compileOptions",
".",
"outputFile",
")",
")",
"utils",
".",
"footer",
"(",
")",
"}",
")",
"}"
] | Compiles CSS file and writes it to a file.
@param {CompileOptions} compileOptions
@param {int[]} startTime
@return {Promise} | [
"Compiles",
"CSS",
"file",
"and",
"writes",
"it",
"to",
"a",
"file",
"."
] | 5066a1e97b3f06b899a4539767ca2bee4bde2da9 | https://github.com/tailwindcss/tailwindcss/blob/5066a1e97b3f06b899a4539767ca2bee4bde2da9/src/cli/commands/build.js#L77-L93 |
546 | uber/deck.gl | examples/experimental/bezier/src/bezier-graph-layer.js | computeControlPoint | function computeControlPoint(source, target, direction, offset) {
const midPoint = [(source[0] + target[0]) / 2, (source[1] + target[1]) / 2];
const dx = target[0] - source[0];
const dy = target[1] - source[1];
const normal = [dy, -dx];
const length = Math.sqrt(Math.pow(normal[0], 2.0) + Math.pow(normal[1], 2.0));
const normalized = [normal[0] / length, normal[1] / length];
return [
midPoint[0] + normalized[0] * offset * direction,
midPoint[1] + normalized[1] * offset * direction
];
} | javascript | function computeControlPoint(source, target, direction, offset) {
const midPoint = [(source[0] + target[0]) / 2, (source[1] + target[1]) / 2];
const dx = target[0] - source[0];
const dy = target[1] - source[1];
const normal = [dy, -dx];
const length = Math.sqrt(Math.pow(normal[0], 2.0) + Math.pow(normal[1], 2.0));
const normalized = [normal[0] / length, normal[1] / length];
return [
midPoint[0] + normalized[0] * offset * direction,
midPoint[1] + normalized[1] * offset * direction
];
} | [
"function",
"computeControlPoint",
"(",
"source",
",",
"target",
",",
"direction",
",",
"offset",
")",
"{",
"const",
"midPoint",
"=",
"[",
"(",
"source",
"[",
"0",
"]",
"+",
"target",
"[",
"0",
"]",
")",
"/",
"2",
",",
"(",
"source",
"[",
"1",
"]",
"+",
"target",
"[",
"1",
"]",
")",
"/",
"2",
"]",
";",
"const",
"dx",
"=",
"target",
"[",
"0",
"]",
"-",
"source",
"[",
"0",
"]",
";",
"const",
"dy",
"=",
"target",
"[",
"1",
"]",
"-",
"source",
"[",
"1",
"]",
";",
"const",
"normal",
"=",
"[",
"dy",
",",
"-",
"dx",
"]",
";",
"const",
"length",
"=",
"Math",
".",
"sqrt",
"(",
"Math",
".",
"pow",
"(",
"normal",
"[",
"0",
"]",
",",
"2.0",
")",
"+",
"Math",
".",
"pow",
"(",
"normal",
"[",
"1",
"]",
",",
"2.0",
")",
")",
";",
"const",
"normalized",
"=",
"[",
"normal",
"[",
"0",
"]",
"/",
"length",
",",
"normal",
"[",
"1",
"]",
"/",
"length",
"]",
";",
"return",
"[",
"midPoint",
"[",
"0",
"]",
"+",
"normalized",
"[",
"0",
"]",
"*",
"offset",
"*",
"direction",
",",
"midPoint",
"[",
"1",
"]",
"+",
"normalized",
"[",
"1",
"]",
"*",
"offset",
"*",
"direction",
"]",
";",
"}"
] | A helper function to compute the control point of a quadratic bezier curve
@param {number[]} source - the coordinates of source point, ex: [x, y, z]
@param {number[]} target - the coordinates of target point, ex: [x, y, z]
@param {number} direction - the direction of the curve, 1 or -1
@param {number} offset - offset from the midpoint
@return {number[]} - the coordinates of the control point | [
"A",
"helper",
"function",
"to",
"compute",
"the",
"control",
"point",
"of",
"a",
"quadratic",
"bezier",
"curve"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/examples/experimental/bezier/src/bezier-graph-layer.js#L54-L65 |
547 | uber/deck.gl | examples/experimental/bezier/src/bezier-graph-layer.js | layoutGraph | function layoutGraph(graph) {
// create a map for referencing node position by node id.
const nodePositionMap = graph.nodes.reduce((res, node) => {
res[node.id] = node.position;
return res;
}, {});
// bucket edges between the same source/target node pairs.
const nodePairs = graph.edges.reduce((res, edge) => {
const nodes = [edge.sourceId, edge.targetId];
// sort the node ids to count the edges with the same pair
// but different direction (a -> b or b -> a)
const pairId = nodes.sort().toString();
// push this edge into the bucket
if (!res[pairId]) {
res[pairId] = [edge];
} else {
res[pairId].push(edge);
}
return res;
}, {});
// start to create curved edges
const unitOffset = 30;
const layoutEdges = Object.keys(nodePairs).reduce((res, pairId) => {
const edges = nodePairs[pairId];
const curved = edges.length > 1;
// curve line is directional, pairId is a list of sorted node ids.
const nodeIds = pairId.split(',');
const curveSourceId = nodeIds[0];
const curveTargetId = nodeIds[1];
// generate new edges with layout information
const newEdges = edges.map((e, idx) => {
// curve direction (1 or -1)
const direction = idx % 2 ? 1 : -1;
// straight line if there's only one edge between this two nodes.
const offset = curved ? (1 + Math.floor(idx / 2)) * unitOffset : 0;
return {
...e,
source: nodePositionMap[e.sourceId],
target: nodePositionMap[e.targetId],
controlPoint: computeControlPoint(
nodePositionMap[curveSourceId],
nodePositionMap[curveTargetId],
direction,
offset
)
};
});
return res.concat(newEdges);
}, []);
return {
nodes: graph.nodes,
edges: layoutEdges
};
} | javascript | function layoutGraph(graph) {
// create a map for referencing node position by node id.
const nodePositionMap = graph.nodes.reduce((res, node) => {
res[node.id] = node.position;
return res;
}, {});
// bucket edges between the same source/target node pairs.
const nodePairs = graph.edges.reduce((res, edge) => {
const nodes = [edge.sourceId, edge.targetId];
// sort the node ids to count the edges with the same pair
// but different direction (a -> b or b -> a)
const pairId = nodes.sort().toString();
// push this edge into the bucket
if (!res[pairId]) {
res[pairId] = [edge];
} else {
res[pairId].push(edge);
}
return res;
}, {});
// start to create curved edges
const unitOffset = 30;
const layoutEdges = Object.keys(nodePairs).reduce((res, pairId) => {
const edges = nodePairs[pairId];
const curved = edges.length > 1;
// curve line is directional, pairId is a list of sorted node ids.
const nodeIds = pairId.split(',');
const curveSourceId = nodeIds[0];
const curveTargetId = nodeIds[1];
// generate new edges with layout information
const newEdges = edges.map((e, idx) => {
// curve direction (1 or -1)
const direction = idx % 2 ? 1 : -1;
// straight line if there's only one edge between this two nodes.
const offset = curved ? (1 + Math.floor(idx / 2)) * unitOffset : 0;
return {
...e,
source: nodePositionMap[e.sourceId],
target: nodePositionMap[e.targetId],
controlPoint: computeControlPoint(
nodePositionMap[curveSourceId],
nodePositionMap[curveTargetId],
direction,
offset
)
};
});
return res.concat(newEdges);
}, []);
return {
nodes: graph.nodes,
edges: layoutEdges
};
} | [
"function",
"layoutGraph",
"(",
"graph",
")",
"{",
"// create a map for referencing node position by node id.",
"const",
"nodePositionMap",
"=",
"graph",
".",
"nodes",
".",
"reduce",
"(",
"(",
"res",
",",
"node",
")",
"=>",
"{",
"res",
"[",
"node",
".",
"id",
"]",
"=",
"node",
".",
"position",
";",
"return",
"res",
";",
"}",
",",
"{",
"}",
")",
";",
"// bucket edges between the same source/target node pairs.",
"const",
"nodePairs",
"=",
"graph",
".",
"edges",
".",
"reduce",
"(",
"(",
"res",
",",
"edge",
")",
"=>",
"{",
"const",
"nodes",
"=",
"[",
"edge",
".",
"sourceId",
",",
"edge",
".",
"targetId",
"]",
";",
"// sort the node ids to count the edges with the same pair",
"// but different direction (a -> b or b -> a)",
"const",
"pairId",
"=",
"nodes",
".",
"sort",
"(",
")",
".",
"toString",
"(",
")",
";",
"// push this edge into the bucket",
"if",
"(",
"!",
"res",
"[",
"pairId",
"]",
")",
"{",
"res",
"[",
"pairId",
"]",
"=",
"[",
"edge",
"]",
";",
"}",
"else",
"{",
"res",
"[",
"pairId",
"]",
".",
"push",
"(",
"edge",
")",
";",
"}",
"return",
"res",
";",
"}",
",",
"{",
"}",
")",
";",
"// start to create curved edges",
"const",
"unitOffset",
"=",
"30",
";",
"const",
"layoutEdges",
"=",
"Object",
".",
"keys",
"(",
"nodePairs",
")",
".",
"reduce",
"(",
"(",
"res",
",",
"pairId",
")",
"=>",
"{",
"const",
"edges",
"=",
"nodePairs",
"[",
"pairId",
"]",
";",
"const",
"curved",
"=",
"edges",
".",
"length",
">",
"1",
";",
"// curve line is directional, pairId is a list of sorted node ids.",
"const",
"nodeIds",
"=",
"pairId",
".",
"split",
"(",
"','",
")",
";",
"const",
"curveSourceId",
"=",
"nodeIds",
"[",
"0",
"]",
";",
"const",
"curveTargetId",
"=",
"nodeIds",
"[",
"1",
"]",
";",
"// generate new edges with layout information",
"const",
"newEdges",
"=",
"edges",
".",
"map",
"(",
"(",
"e",
",",
"idx",
")",
"=>",
"{",
"// curve direction (1 or -1)",
"const",
"direction",
"=",
"idx",
"%",
"2",
"?",
"1",
":",
"-",
"1",
";",
"// straight line if there's only one edge between this two nodes.",
"const",
"offset",
"=",
"curved",
"?",
"(",
"1",
"+",
"Math",
".",
"floor",
"(",
"idx",
"/",
"2",
")",
")",
"*",
"unitOffset",
":",
"0",
";",
"return",
"{",
"...",
"e",
",",
"source",
":",
"nodePositionMap",
"[",
"e",
".",
"sourceId",
"]",
",",
"target",
":",
"nodePositionMap",
"[",
"e",
".",
"targetId",
"]",
",",
"controlPoint",
":",
"computeControlPoint",
"(",
"nodePositionMap",
"[",
"curveSourceId",
"]",
",",
"nodePositionMap",
"[",
"curveTargetId",
"]",
",",
"direction",
",",
"offset",
")",
"}",
";",
"}",
")",
";",
"return",
"res",
".",
"concat",
"(",
"newEdges",
")",
";",
"}",
",",
"[",
"]",
")",
";",
"return",
"{",
"nodes",
":",
"graph",
".",
"nodes",
",",
"edges",
":",
"layoutEdges",
"}",
";",
"}"
] | A helper function to generate a graph with curved edges.
@param {Object} graph - {nodes: [], edges: []}
expected input format: {
nodes: [{id: 'a', position: [0, -100]}, {id: 'b', position: [0, 100]}, ...],
edges: [{id: '1', sourceId: 'a',, targetId: 'b',}, ...]
}
@return {Object} Return new graph with curved edges.
expected output format: {
nodes: [{id: 'a', position: [0, -100]}, {id: 'b', position: [0, 100]}, ...],
edges: [{id: '1', sourceId: 'a', source: [0, -100], targetId: 'b', target: [0, 100], controlPoint: [50, 0]}, ...]
} | [
"A",
"helper",
"function",
"to",
"generate",
"a",
"graph",
"with",
"curved",
"edges",
"."
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/examples/experimental/bezier/src/bezier-graph-layer.js#L80-L133 |
548 | uber/deck.gl | modules/core/bundle/deckgl.js | createCanvas | function createCanvas(props) {
let {container = document.body} = props;
if (typeof container === 'string') {
container = document.getElementById(container);
}
if (!container) {
throw Error('Deck: container not found');
}
// Add DOM elements
const containerStyle = window.getComputedStyle(container);
if (containerStyle.position === 'static') {
container.style.position = 'relative';
}
const mapCanvas = document.createElement('div');
container.appendChild(mapCanvas);
Object.assign(mapCanvas.style, CANVAS_STYLE);
const deckCanvas = document.createElement('canvas');
container.appendChild(deckCanvas);
Object.assign(deckCanvas.style, CANVAS_STYLE);
return {container, mapCanvas, deckCanvas};
} | javascript | function createCanvas(props) {
let {container = document.body} = props;
if (typeof container === 'string') {
container = document.getElementById(container);
}
if (!container) {
throw Error('Deck: container not found');
}
// Add DOM elements
const containerStyle = window.getComputedStyle(container);
if (containerStyle.position === 'static') {
container.style.position = 'relative';
}
const mapCanvas = document.createElement('div');
container.appendChild(mapCanvas);
Object.assign(mapCanvas.style, CANVAS_STYLE);
const deckCanvas = document.createElement('canvas');
container.appendChild(deckCanvas);
Object.assign(deckCanvas.style, CANVAS_STYLE);
return {container, mapCanvas, deckCanvas};
} | [
"function",
"createCanvas",
"(",
"props",
")",
"{",
"let",
"{",
"container",
"=",
"document",
".",
"body",
"}",
"=",
"props",
";",
"if",
"(",
"typeof",
"container",
"===",
"'string'",
")",
"{",
"container",
"=",
"document",
".",
"getElementById",
"(",
"container",
")",
";",
"}",
"if",
"(",
"!",
"container",
")",
"{",
"throw",
"Error",
"(",
"'Deck: container not found'",
")",
";",
"}",
"// Add DOM elements",
"const",
"containerStyle",
"=",
"window",
".",
"getComputedStyle",
"(",
"container",
")",
";",
"if",
"(",
"containerStyle",
".",
"position",
"===",
"'static'",
")",
"{",
"container",
".",
"style",
".",
"position",
"=",
"'relative'",
";",
"}",
"const",
"mapCanvas",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"container",
".",
"appendChild",
"(",
"mapCanvas",
")",
";",
"Object",
".",
"assign",
"(",
"mapCanvas",
".",
"style",
",",
"CANVAS_STYLE",
")",
";",
"const",
"deckCanvas",
"=",
"document",
".",
"createElement",
"(",
"'canvas'",
")",
";",
"container",
".",
"appendChild",
"(",
"deckCanvas",
")",
";",
"Object",
".",
"assign",
"(",
"deckCanvas",
".",
"style",
",",
"CANVAS_STYLE",
")",
";",
"return",
"{",
"container",
",",
"mapCanvas",
",",
"deckCanvas",
"}",
";",
"}"
] | Create canvas elements for map and deck | [
"Create",
"canvas",
"elements",
"for",
"map",
"and",
"deck"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/core/bundle/deckgl.js#L26-L52 |
549 | uber/deck.gl | modules/aggregation-layers/src/utils/gpu-grid-aggregation/grid-aggregation-utils.js | getGPUAggregationParams | function getGPUAggregationParams({boundingBox, cellSize, worldOrigin}) {
const {yMin, yMax, xMin, xMax} = boundingBox;
// NOTE: this alignment will match grid cell boundaries with existing CPU implementation
// this gurantees identical aggregation results when switching between CPU and GPU aggregation.
// Also gurantees same cell boundaries, when overlapping between two different layers (like ScreenGrid and Contour)
// We first move worldOrigin to [0, 0], align the lower bounding box , then move worldOrigin to its original value.
const originX = alignToCell(xMin - worldOrigin[0], cellSize[0]) + worldOrigin[0];
const originY = alignToCell(yMin - worldOrigin[1], cellSize[1]) + worldOrigin[1];
// Setup transformation matrix so that every point is in +ve range
const gridTransformMatrix = new Matrix4().translate([-1 * originX, -1 * originY, 0]);
// const cellSize = [gridOffset.xOffset, gridOffset.yOffset];
const gridOrigin = [originX, originY];
const width = xMax - xMin + cellSize[0];
const height = yMax - yMin + cellSize[1];
const gridSize = [Math.ceil(width / cellSize[0]), Math.ceil(height / cellSize[1])];
return {
gridOrigin,
gridSize,
width,
height,
gridTransformMatrix
};
} | javascript | function getGPUAggregationParams({boundingBox, cellSize, worldOrigin}) {
const {yMin, yMax, xMin, xMax} = boundingBox;
// NOTE: this alignment will match grid cell boundaries with existing CPU implementation
// this gurantees identical aggregation results when switching between CPU and GPU aggregation.
// Also gurantees same cell boundaries, when overlapping between two different layers (like ScreenGrid and Contour)
// We first move worldOrigin to [0, 0], align the lower bounding box , then move worldOrigin to its original value.
const originX = alignToCell(xMin - worldOrigin[0], cellSize[0]) + worldOrigin[0];
const originY = alignToCell(yMin - worldOrigin[1], cellSize[1]) + worldOrigin[1];
// Setup transformation matrix so that every point is in +ve range
const gridTransformMatrix = new Matrix4().translate([-1 * originX, -1 * originY, 0]);
// const cellSize = [gridOffset.xOffset, gridOffset.yOffset];
const gridOrigin = [originX, originY];
const width = xMax - xMin + cellSize[0];
const height = yMax - yMin + cellSize[1];
const gridSize = [Math.ceil(width / cellSize[0]), Math.ceil(height / cellSize[1])];
return {
gridOrigin,
gridSize,
width,
height,
gridTransformMatrix
};
} | [
"function",
"getGPUAggregationParams",
"(",
"{",
"boundingBox",
",",
"cellSize",
",",
"worldOrigin",
"}",
")",
"{",
"const",
"{",
"yMin",
",",
"yMax",
",",
"xMin",
",",
"xMax",
"}",
"=",
"boundingBox",
";",
"// NOTE: this alignment will match grid cell boundaries with existing CPU implementation",
"// this gurantees identical aggregation results when switching between CPU and GPU aggregation.",
"// Also gurantees same cell boundaries, when overlapping between two different layers (like ScreenGrid and Contour)",
"// We first move worldOrigin to [0, 0], align the lower bounding box , then move worldOrigin to its original value.",
"const",
"originX",
"=",
"alignToCell",
"(",
"xMin",
"-",
"worldOrigin",
"[",
"0",
"]",
",",
"cellSize",
"[",
"0",
"]",
")",
"+",
"worldOrigin",
"[",
"0",
"]",
";",
"const",
"originY",
"=",
"alignToCell",
"(",
"yMin",
"-",
"worldOrigin",
"[",
"1",
"]",
",",
"cellSize",
"[",
"1",
"]",
")",
"+",
"worldOrigin",
"[",
"1",
"]",
";",
"// Setup transformation matrix so that every point is in +ve range",
"const",
"gridTransformMatrix",
"=",
"new",
"Matrix4",
"(",
")",
".",
"translate",
"(",
"[",
"-",
"1",
"*",
"originX",
",",
"-",
"1",
"*",
"originY",
",",
"0",
"]",
")",
";",
"// const cellSize = [gridOffset.xOffset, gridOffset.yOffset];",
"const",
"gridOrigin",
"=",
"[",
"originX",
",",
"originY",
"]",
";",
"const",
"width",
"=",
"xMax",
"-",
"xMin",
"+",
"cellSize",
"[",
"0",
"]",
";",
"const",
"height",
"=",
"yMax",
"-",
"yMin",
"+",
"cellSize",
"[",
"1",
"]",
";",
"const",
"gridSize",
"=",
"[",
"Math",
".",
"ceil",
"(",
"width",
"/",
"cellSize",
"[",
"0",
"]",
")",
",",
"Math",
".",
"ceil",
"(",
"height",
"/",
"cellSize",
"[",
"1",
"]",
")",
"]",
";",
"return",
"{",
"gridOrigin",
",",
"gridSize",
",",
"width",
",",
"height",
",",
"gridTransformMatrix",
"}",
";",
"}"
] | Calculate grid parameters | [
"Calculate",
"grid",
"parameters"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/aggregation-layers/src/utils/gpu-grid-aggregation/grid-aggregation-utils.js#L211-L238 |
550 | uber/deck.gl | modules/layers/src/icon-layer/icon-manager.js | resizeImage | function resizeImage(ctx, imageData, width, height) {
const {naturalWidth, naturalHeight} = imageData;
if (width === naturalWidth && height === naturalHeight) {
return imageData;
}
ctx.canvas.height = height;
ctx.canvas.width = width;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
// image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight
ctx.drawImage(imageData, 0, 0, naturalWidth, naturalHeight, 0, 0, width, height);
return ctx.canvas;
} | javascript | function resizeImage(ctx, imageData, width, height) {
const {naturalWidth, naturalHeight} = imageData;
if (width === naturalWidth && height === naturalHeight) {
return imageData;
}
ctx.canvas.height = height;
ctx.canvas.width = width;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
// image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight
ctx.drawImage(imageData, 0, 0, naturalWidth, naturalHeight, 0, 0, width, height);
return ctx.canvas;
} | [
"function",
"resizeImage",
"(",
"ctx",
",",
"imageData",
",",
"width",
",",
"height",
")",
"{",
"const",
"{",
"naturalWidth",
",",
"naturalHeight",
"}",
"=",
"imageData",
";",
"if",
"(",
"width",
"===",
"naturalWidth",
"&&",
"height",
"===",
"naturalHeight",
")",
"{",
"return",
"imageData",
";",
"}",
"ctx",
".",
"canvas",
".",
"height",
"=",
"height",
";",
"ctx",
".",
"canvas",
".",
"width",
"=",
"width",
";",
"ctx",
".",
"clearRect",
"(",
"0",
",",
"0",
",",
"ctx",
".",
"canvas",
".",
"width",
",",
"ctx",
".",
"canvas",
".",
"height",
")",
";",
"// image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight",
"ctx",
".",
"drawImage",
"(",
"imageData",
",",
"0",
",",
"0",
",",
"naturalWidth",
",",
"naturalHeight",
",",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
";",
"return",
"ctx",
".",
"canvas",
";",
"}"
] | resize image to given width and height | [
"resize",
"image",
"to",
"given",
"width",
"and",
"height"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/layers/src/icon-layer/icon-manager.js#L23-L38 |
551 | uber/deck.gl | modules/layers/src/icon-layer/icon-manager.js | buildRowMapping | function buildRowMapping(mapping, columns, yOffset) {
for (let i = 0; i < columns.length; i++) {
const {icon, xOffset} = columns[i];
const id = getIconId(icon);
mapping[id] = Object.assign({}, icon, {
x: xOffset,
y: yOffset
});
}
} | javascript | function buildRowMapping(mapping, columns, yOffset) {
for (let i = 0; i < columns.length; i++) {
const {icon, xOffset} = columns[i];
const id = getIconId(icon);
mapping[id] = Object.assign({}, icon, {
x: xOffset,
y: yOffset
});
}
} | [
"function",
"buildRowMapping",
"(",
"mapping",
",",
"columns",
",",
"yOffset",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"columns",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"{",
"icon",
",",
"xOffset",
"}",
"=",
"columns",
"[",
"i",
"]",
";",
"const",
"id",
"=",
"getIconId",
"(",
"icon",
")",
";",
"mapping",
"[",
"id",
"]",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"icon",
",",
"{",
"x",
":",
"xOffset",
",",
"y",
":",
"yOffset",
"}",
")",
";",
"}",
"}"
] | traverse icons in a row of icon atlas extend each icon with left-top coordinates | [
"traverse",
"icons",
"in",
"a",
"row",
"of",
"icon",
"atlas",
"extend",
"each",
"icon",
"with",
"left",
"-",
"top",
"coordinates"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/layers/src/icon-layer/icon-manager.js#L46-L55 |
552 | uber/deck.gl | modules/layers/src/icon-layer/icon-manager.js | resizeTexture | function resizeTexture(texture, width, height) {
const oldWidth = texture.width;
const oldHeight = texture.height;
const oldPixels = readPixelsToBuffer(texture, {});
texture.resize({width, height});
texture.setSubImageData({
data: oldPixels,
x: 0,
y: height - oldHeight,
width: oldWidth,
height: oldHeight,
parameters: DEFAULT_TEXTURE_PARAMETERS
});
texture.generateMipmap();
oldPixels.delete();
return texture;
} | javascript | function resizeTexture(texture, width, height) {
const oldWidth = texture.width;
const oldHeight = texture.height;
const oldPixels = readPixelsToBuffer(texture, {});
texture.resize({width, height});
texture.setSubImageData({
data: oldPixels,
x: 0,
y: height - oldHeight,
width: oldWidth,
height: oldHeight,
parameters: DEFAULT_TEXTURE_PARAMETERS
});
texture.generateMipmap();
oldPixels.delete();
return texture;
} | [
"function",
"resizeTexture",
"(",
"texture",
",",
"width",
",",
"height",
")",
"{",
"const",
"oldWidth",
"=",
"texture",
".",
"width",
";",
"const",
"oldHeight",
"=",
"texture",
".",
"height",
";",
"const",
"oldPixels",
"=",
"readPixelsToBuffer",
"(",
"texture",
",",
"{",
"}",
")",
";",
"texture",
".",
"resize",
"(",
"{",
"width",
",",
"height",
"}",
")",
";",
"texture",
".",
"setSubImageData",
"(",
"{",
"data",
":",
"oldPixels",
",",
"x",
":",
"0",
",",
"y",
":",
"height",
"-",
"oldHeight",
",",
"width",
":",
"oldWidth",
",",
"height",
":",
"oldHeight",
",",
"parameters",
":",
"DEFAULT_TEXTURE_PARAMETERS",
"}",
")",
";",
"texture",
".",
"generateMipmap",
"(",
")",
";",
"oldPixels",
".",
"delete",
"(",
")",
";",
"return",
"texture",
";",
"}"
] | resize texture without losing original data | [
"resize",
"texture",
"without",
"losing",
"original",
"data"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/layers/src/icon-layer/icon-manager.js#L58-L78 |
553 | uber/deck.gl | modules/aggregation-layers/src/grid-layer/grid-aggregator.js | _pointsToGridHashing | function _pointsToGridHashing(points = [], cellSize, getPosition) {
// find the geometric center of sample points
let latMin = Infinity;
let latMax = -Infinity;
let pLat;
for (const pt of points) {
pLat = getPosition(pt)[1];
if (Number.isFinite(pLat)) {
latMin = pLat < latMin ? pLat : latMin;
latMax = pLat > latMax ? pLat : latMax;
}
}
const centerLat = (latMin + latMax) / 2;
const gridOffset = _calculateGridLatLonOffset(cellSize, centerLat);
if (gridOffset.xOffset <= 0 || gridOffset.yOffset <= 0) {
return {gridHash: {}, gridOffset};
}
// calculate count per cell
const gridHash = {};
for (const pt of points) {
const [lng, lat] = getPosition(pt);
if (Number.isFinite(lat) && Number.isFinite(lng)) {
const latIdx = Math.floor((lat + 90) / gridOffset.yOffset);
const lonIdx = Math.floor((lng + 180) / gridOffset.xOffset);
const key = `${latIdx}-${lonIdx}`;
gridHash[key] = gridHash[key] || {count: 0, points: []};
gridHash[key].count += 1;
gridHash[key].points.push(pt);
}
}
return {gridHash, gridOffset};
} | javascript | function _pointsToGridHashing(points = [], cellSize, getPosition) {
// find the geometric center of sample points
let latMin = Infinity;
let latMax = -Infinity;
let pLat;
for (const pt of points) {
pLat = getPosition(pt)[1];
if (Number.isFinite(pLat)) {
latMin = pLat < latMin ? pLat : latMin;
latMax = pLat > latMax ? pLat : latMax;
}
}
const centerLat = (latMin + latMax) / 2;
const gridOffset = _calculateGridLatLonOffset(cellSize, centerLat);
if (gridOffset.xOffset <= 0 || gridOffset.yOffset <= 0) {
return {gridHash: {}, gridOffset};
}
// calculate count per cell
const gridHash = {};
for (const pt of points) {
const [lng, lat] = getPosition(pt);
if (Number.isFinite(lat) && Number.isFinite(lng)) {
const latIdx = Math.floor((lat + 90) / gridOffset.yOffset);
const lonIdx = Math.floor((lng + 180) / gridOffset.xOffset);
const key = `${latIdx}-${lonIdx}`;
gridHash[key] = gridHash[key] || {count: 0, points: []};
gridHash[key].count += 1;
gridHash[key].points.push(pt);
}
}
return {gridHash, gridOffset};
} | [
"function",
"_pointsToGridHashing",
"(",
"points",
"=",
"[",
"]",
",",
"cellSize",
",",
"getPosition",
")",
"{",
"// find the geometric center of sample points",
"let",
"latMin",
"=",
"Infinity",
";",
"let",
"latMax",
"=",
"-",
"Infinity",
";",
"let",
"pLat",
";",
"for",
"(",
"const",
"pt",
"of",
"points",
")",
"{",
"pLat",
"=",
"getPosition",
"(",
"pt",
")",
"[",
"1",
"]",
";",
"if",
"(",
"Number",
".",
"isFinite",
"(",
"pLat",
")",
")",
"{",
"latMin",
"=",
"pLat",
"<",
"latMin",
"?",
"pLat",
":",
"latMin",
";",
"latMax",
"=",
"pLat",
">",
"latMax",
"?",
"pLat",
":",
"latMax",
";",
"}",
"}",
"const",
"centerLat",
"=",
"(",
"latMin",
"+",
"latMax",
")",
"/",
"2",
";",
"const",
"gridOffset",
"=",
"_calculateGridLatLonOffset",
"(",
"cellSize",
",",
"centerLat",
")",
";",
"if",
"(",
"gridOffset",
".",
"xOffset",
"<=",
"0",
"||",
"gridOffset",
".",
"yOffset",
"<=",
"0",
")",
"{",
"return",
"{",
"gridHash",
":",
"{",
"}",
",",
"gridOffset",
"}",
";",
"}",
"// calculate count per cell",
"const",
"gridHash",
"=",
"{",
"}",
";",
"for",
"(",
"const",
"pt",
"of",
"points",
")",
"{",
"const",
"[",
"lng",
",",
"lat",
"]",
"=",
"getPosition",
"(",
"pt",
")",
";",
"if",
"(",
"Number",
".",
"isFinite",
"(",
"lat",
")",
"&&",
"Number",
".",
"isFinite",
"(",
"lng",
")",
")",
"{",
"const",
"latIdx",
"=",
"Math",
".",
"floor",
"(",
"(",
"lat",
"+",
"90",
")",
"/",
"gridOffset",
".",
"yOffset",
")",
";",
"const",
"lonIdx",
"=",
"Math",
".",
"floor",
"(",
"(",
"lng",
"+",
"180",
")",
"/",
"gridOffset",
".",
"xOffset",
")",
";",
"const",
"key",
"=",
"`",
"${",
"latIdx",
"}",
"${",
"lonIdx",
"}",
"`",
";",
"gridHash",
"[",
"key",
"]",
"=",
"gridHash",
"[",
"key",
"]",
"||",
"{",
"count",
":",
"0",
",",
"points",
":",
"[",
"]",
"}",
";",
"gridHash",
"[",
"key",
"]",
".",
"count",
"+=",
"1",
";",
"gridHash",
"[",
"key",
"]",
".",
"points",
".",
"push",
"(",
"pt",
")",
";",
"}",
"}",
"return",
"{",
"gridHash",
",",
"gridOffset",
"}",
";",
"}"
] | Project points into each cell, return a hash table of cells
@param {Iterable} points
@param {number} cellSize - unit size in meters
@param {function} getPosition - position accessor
@returns {object} - grid hash and cell dimension | [
"Project",
"points",
"into",
"each",
"cell",
"return",
"a",
"hash",
"table",
"of",
"cells"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/aggregation-layers/src/grid-layer/grid-aggregator.js#L46-L85 |
554 | uber/deck.gl | modules/core/src/lifecycle/props.js | diffDataProps | function diffDataProps(props, oldProps) {
if (oldProps === null) {
return 'oldProps is null, initial diff';
}
// Support optional app defined comparison of data
const {dataComparator} = props;
if (dataComparator) {
if (!dataComparator(props.data, oldProps.data)) {
return 'Data comparator detected a change';
}
// Otherwise, do a shallow equal on props
} else if (props.data !== oldProps.data) {
return 'A new data container was supplied';
}
return null;
} | javascript | function diffDataProps(props, oldProps) {
if (oldProps === null) {
return 'oldProps is null, initial diff';
}
// Support optional app defined comparison of data
const {dataComparator} = props;
if (dataComparator) {
if (!dataComparator(props.data, oldProps.data)) {
return 'Data comparator detected a change';
}
// Otherwise, do a shallow equal on props
} else if (props.data !== oldProps.data) {
return 'A new data container was supplied';
}
return null;
} | [
"function",
"diffDataProps",
"(",
"props",
",",
"oldProps",
")",
"{",
"if",
"(",
"oldProps",
"===",
"null",
")",
"{",
"return",
"'oldProps is null, initial diff'",
";",
"}",
"// Support optional app defined comparison of data",
"const",
"{",
"dataComparator",
"}",
"=",
"props",
";",
"if",
"(",
"dataComparator",
")",
"{",
"if",
"(",
"!",
"dataComparator",
"(",
"props",
".",
"data",
",",
"oldProps",
".",
"data",
")",
")",
"{",
"return",
"'Data comparator detected a change'",
";",
"}",
"// Otherwise, do a shallow equal on props",
"}",
"else",
"if",
"(",
"props",
".",
"data",
"!==",
"oldProps",
".",
"data",
")",
"{",
"return",
"'A new data container was supplied'",
";",
"}",
"return",
"null",
";",
"}"
] | The comparison of the data prop requires special handling the dataComparator should be used if supplied | [
"The",
"comparison",
"of",
"the",
"data",
"prop",
"requires",
"special",
"handling",
"the",
"dataComparator",
"should",
"be",
"used",
"if",
"supplied"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/core/src/lifecycle/props.js#L122-L139 |
555 | uber/deck.gl | modules/core/src/lifecycle/props.js | diffUpdateTriggers | function diffUpdateTriggers(props, oldProps) {
if (oldProps === null) {
return 'oldProps is null, initial diff';
}
// If the 'all' updateTrigger fires, ignore testing others
if ('all' in props.updateTriggers) {
const diffReason = diffUpdateTrigger(props, oldProps, 'all');
if (diffReason) {
return {all: true};
}
}
const triggerChanged = {};
let reason = false;
// If the 'all' updateTrigger didn't fire, need to check all others
for (const triggerName in props.updateTriggers) {
if (triggerName !== 'all') {
const diffReason = diffUpdateTrigger(props, oldProps, triggerName);
if (diffReason) {
triggerChanged[triggerName] = true;
reason = triggerChanged;
}
}
}
return reason;
} | javascript | function diffUpdateTriggers(props, oldProps) {
if (oldProps === null) {
return 'oldProps is null, initial diff';
}
// If the 'all' updateTrigger fires, ignore testing others
if ('all' in props.updateTriggers) {
const diffReason = diffUpdateTrigger(props, oldProps, 'all');
if (diffReason) {
return {all: true};
}
}
const triggerChanged = {};
let reason = false;
// If the 'all' updateTrigger didn't fire, need to check all others
for (const triggerName in props.updateTriggers) {
if (triggerName !== 'all') {
const diffReason = diffUpdateTrigger(props, oldProps, triggerName);
if (diffReason) {
triggerChanged[triggerName] = true;
reason = triggerChanged;
}
}
}
return reason;
} | [
"function",
"diffUpdateTriggers",
"(",
"props",
",",
"oldProps",
")",
"{",
"if",
"(",
"oldProps",
"===",
"null",
")",
"{",
"return",
"'oldProps is null, initial diff'",
";",
"}",
"// If the 'all' updateTrigger fires, ignore testing others",
"if",
"(",
"'all'",
"in",
"props",
".",
"updateTriggers",
")",
"{",
"const",
"diffReason",
"=",
"diffUpdateTrigger",
"(",
"props",
",",
"oldProps",
",",
"'all'",
")",
";",
"if",
"(",
"diffReason",
")",
"{",
"return",
"{",
"all",
":",
"true",
"}",
";",
"}",
"}",
"const",
"triggerChanged",
"=",
"{",
"}",
";",
"let",
"reason",
"=",
"false",
";",
"// If the 'all' updateTrigger didn't fire, need to check all others",
"for",
"(",
"const",
"triggerName",
"in",
"props",
".",
"updateTriggers",
")",
"{",
"if",
"(",
"triggerName",
"!==",
"'all'",
")",
"{",
"const",
"diffReason",
"=",
"diffUpdateTrigger",
"(",
"props",
",",
"oldProps",
",",
"triggerName",
")",
";",
"if",
"(",
"diffReason",
")",
"{",
"triggerChanged",
"[",
"triggerName",
"]",
"=",
"true",
";",
"reason",
"=",
"triggerChanged",
";",
"}",
"}",
"}",
"return",
"reason",
";",
"}"
] | Checks if any update triggers have changed also calls callback to invalidate attributes accordingly. | [
"Checks",
"if",
"any",
"update",
"triggers",
"have",
"changed",
"also",
"calls",
"callback",
"to",
"invalidate",
"attributes",
"accordingly",
"."
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/core/src/lifecycle/props.js#L143-L170 |
556 | uber/deck.gl | modules/core/src/lifecycle/create-props.js | getPropsPrototypeAndTypes | function getPropsPrototypeAndTypes(componentClass) {
const props = getOwnProperty(componentClass, '_mergedDefaultProps');
if (props) {
return {
defaultProps: props,
propTypes: getOwnProperty(componentClass, '_propTypes'),
deprecatedProps: getOwnProperty(componentClass, '_deprecatedProps')
};
}
return createPropsPrototypeAndTypes(componentClass);
} | javascript | function getPropsPrototypeAndTypes(componentClass) {
const props = getOwnProperty(componentClass, '_mergedDefaultProps');
if (props) {
return {
defaultProps: props,
propTypes: getOwnProperty(componentClass, '_propTypes'),
deprecatedProps: getOwnProperty(componentClass, '_deprecatedProps')
};
}
return createPropsPrototypeAndTypes(componentClass);
} | [
"function",
"getPropsPrototypeAndTypes",
"(",
"componentClass",
")",
"{",
"const",
"props",
"=",
"getOwnProperty",
"(",
"componentClass",
",",
"'_mergedDefaultProps'",
")",
";",
"if",
"(",
"props",
")",
"{",
"return",
"{",
"defaultProps",
":",
"props",
",",
"propTypes",
":",
"getOwnProperty",
"(",
"componentClass",
",",
"'_propTypes'",
")",
",",
"deprecatedProps",
":",
"getOwnProperty",
"(",
"componentClass",
",",
"'_deprecatedProps'",
")",
"}",
";",
"}",
"return",
"createPropsPrototypeAndTypes",
"(",
"componentClass",
")",
";",
"}"
] | Return precalculated defaultProps and propType objects if available build them if needed | [
"Return",
"precalculated",
"defaultProps",
"and",
"propType",
"objects",
"if",
"available",
"build",
"them",
"if",
"needed"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/core/src/lifecycle/create-props.js#L78-L89 |
557 | uber/deck.gl | modules/core/src/lifecycle/create-props.js | createPropsPrototypeAndTypes | function createPropsPrototypeAndTypes(componentClass) {
const parent = componentClass.prototype;
if (!parent) {
return {
defaultProps: {}
};
}
const parentClass = Object.getPrototypeOf(componentClass);
const parentPropDefs = (parent && getPropsPrototypeAndTypes(parentClass)) || null;
// Parse propTypes from Component.defaultProps
const componentDefaultProps = getOwnProperty(componentClass, 'defaultProps') || {};
const componentPropDefs = parsePropTypes(componentDefaultProps);
// Create a merged type object
const propTypes = Object.assign(
{},
parentPropDefs && parentPropDefs.propTypes,
componentPropDefs.propTypes
);
// Create any necessary property descriptors and create the default prop object
// Assign merged default props
const defaultProps = createPropsPrototype(
componentPropDefs.defaultProps,
parentPropDefs && parentPropDefs.defaultProps,
propTypes,
componentClass
);
// Create a map for prop whose default value is a callback
const deprecatedProps = Object.assign(
{},
parentPropDefs && parentPropDefs.deprecatedProps,
componentPropDefs.deprecatedProps
);
// Store the precalculated props
componentClass._mergedDefaultProps = defaultProps;
componentClass._propTypes = propTypes;
componentClass._deprecatedProps = deprecatedProps;
return {propTypes, defaultProps, deprecatedProps};
} | javascript | function createPropsPrototypeAndTypes(componentClass) {
const parent = componentClass.prototype;
if (!parent) {
return {
defaultProps: {}
};
}
const parentClass = Object.getPrototypeOf(componentClass);
const parentPropDefs = (parent && getPropsPrototypeAndTypes(parentClass)) || null;
// Parse propTypes from Component.defaultProps
const componentDefaultProps = getOwnProperty(componentClass, 'defaultProps') || {};
const componentPropDefs = parsePropTypes(componentDefaultProps);
// Create a merged type object
const propTypes = Object.assign(
{},
parentPropDefs && parentPropDefs.propTypes,
componentPropDefs.propTypes
);
// Create any necessary property descriptors and create the default prop object
// Assign merged default props
const defaultProps = createPropsPrototype(
componentPropDefs.defaultProps,
parentPropDefs && parentPropDefs.defaultProps,
propTypes,
componentClass
);
// Create a map for prop whose default value is a callback
const deprecatedProps = Object.assign(
{},
parentPropDefs && parentPropDefs.deprecatedProps,
componentPropDefs.deprecatedProps
);
// Store the precalculated props
componentClass._mergedDefaultProps = defaultProps;
componentClass._propTypes = propTypes;
componentClass._deprecatedProps = deprecatedProps;
return {propTypes, defaultProps, deprecatedProps};
} | [
"function",
"createPropsPrototypeAndTypes",
"(",
"componentClass",
")",
"{",
"const",
"parent",
"=",
"componentClass",
".",
"prototype",
";",
"if",
"(",
"!",
"parent",
")",
"{",
"return",
"{",
"defaultProps",
":",
"{",
"}",
"}",
";",
"}",
"const",
"parentClass",
"=",
"Object",
".",
"getPrototypeOf",
"(",
"componentClass",
")",
";",
"const",
"parentPropDefs",
"=",
"(",
"parent",
"&&",
"getPropsPrototypeAndTypes",
"(",
"parentClass",
")",
")",
"||",
"null",
";",
"// Parse propTypes from Component.defaultProps",
"const",
"componentDefaultProps",
"=",
"getOwnProperty",
"(",
"componentClass",
",",
"'defaultProps'",
")",
"||",
"{",
"}",
";",
"const",
"componentPropDefs",
"=",
"parsePropTypes",
"(",
"componentDefaultProps",
")",
";",
"// Create a merged type object",
"const",
"propTypes",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"parentPropDefs",
"&&",
"parentPropDefs",
".",
"propTypes",
",",
"componentPropDefs",
".",
"propTypes",
")",
";",
"// Create any necessary property descriptors and create the default prop object",
"// Assign merged default props",
"const",
"defaultProps",
"=",
"createPropsPrototype",
"(",
"componentPropDefs",
".",
"defaultProps",
",",
"parentPropDefs",
"&&",
"parentPropDefs",
".",
"defaultProps",
",",
"propTypes",
",",
"componentClass",
")",
";",
"// Create a map for prop whose default value is a callback",
"const",
"deprecatedProps",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"parentPropDefs",
"&&",
"parentPropDefs",
".",
"deprecatedProps",
",",
"componentPropDefs",
".",
"deprecatedProps",
")",
";",
"// Store the precalculated props",
"componentClass",
".",
"_mergedDefaultProps",
"=",
"defaultProps",
";",
"componentClass",
".",
"_propTypes",
"=",
"propTypes",
";",
"componentClass",
".",
"_deprecatedProps",
"=",
"deprecatedProps",
";",
"return",
"{",
"propTypes",
",",
"defaultProps",
",",
"deprecatedProps",
"}",
";",
"}"
] | Build defaultProps and propType objects by walking component prototype chain | [
"Build",
"defaultProps",
"and",
"propType",
"objects",
"by",
"walking",
"component",
"prototype",
"chain"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/core/src/lifecycle/create-props.js#L92-L136 |
558 | uber/deck.gl | modules/core/src/lifecycle/create-props.js | createPropsPrototype | function createPropsPrototype(props, parentProps, propTypes, componentClass) {
const defaultProps = Object.create(null);
Object.assign(defaultProps, parentProps, props);
// Avoid freezing `id` prop
const id = getComponentName(componentClass);
delete props.id;
// Add getters/setters for async prop properties
Object.defineProperties(defaultProps, {
// `id` is treated specially because layer might need to override it
id: {
configurable: false,
writable: true,
value: id
}
});
// Add getters/setters for async prop properties
addAsyncPropsToPropPrototype(defaultProps, propTypes);
return defaultProps;
} | javascript | function createPropsPrototype(props, parentProps, propTypes, componentClass) {
const defaultProps = Object.create(null);
Object.assign(defaultProps, parentProps, props);
// Avoid freezing `id` prop
const id = getComponentName(componentClass);
delete props.id;
// Add getters/setters for async prop properties
Object.defineProperties(defaultProps, {
// `id` is treated specially because layer might need to override it
id: {
configurable: false,
writable: true,
value: id
}
});
// Add getters/setters for async prop properties
addAsyncPropsToPropPrototype(defaultProps, propTypes);
return defaultProps;
} | [
"function",
"createPropsPrototype",
"(",
"props",
",",
"parentProps",
",",
"propTypes",
",",
"componentClass",
")",
"{",
"const",
"defaultProps",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"Object",
".",
"assign",
"(",
"defaultProps",
",",
"parentProps",
",",
"props",
")",
";",
"// Avoid freezing `id` prop",
"const",
"id",
"=",
"getComponentName",
"(",
"componentClass",
")",
";",
"delete",
"props",
".",
"id",
";",
"// Add getters/setters for async prop properties",
"Object",
".",
"defineProperties",
"(",
"defaultProps",
",",
"{",
"// `id` is treated specially because layer might need to override it",
"id",
":",
"{",
"configurable",
":",
"false",
",",
"writable",
":",
"true",
",",
"value",
":",
"id",
"}",
"}",
")",
";",
"// Add getters/setters for async prop properties",
"addAsyncPropsToPropPrototype",
"(",
"defaultProps",
",",
"propTypes",
")",
";",
"return",
"defaultProps",
";",
"}"
] | Builds a pre-merged default props object that component props can inherit from | [
"Builds",
"a",
"pre",
"-",
"merged",
"default",
"props",
"object",
"that",
"component",
"props",
"can",
"inherit",
"from"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/core/src/lifecycle/create-props.js#L139-L162 |
559 | uber/deck.gl | modules/core/src/lifecycle/create-props.js | addAsyncPropsToPropPrototype | function addAsyncPropsToPropPrototype(defaultProps, propTypes) {
const defaultValues = {};
const descriptors = {
// Default "resolved" values for async props, returned if value not yet resolved/set.
_asyncPropDefaultValues: {
enumerable: false,
value: defaultValues
},
// Shadowed object, just to make sure "early indexing" into the instance does not fail
_asyncPropOriginalValues: {
enumerable: false,
value: {}
}
};
// Move async props into shadow values
for (const propName in propTypes) {
const propType = propTypes[propName];
const {name, value} = propType;
// Note: async is ES7 keyword, can't destructure
if (propType.async) {
defaultValues[name] = value;
descriptors[name] = getDescriptorForAsyncProp(name, value);
}
}
Object.defineProperties(defaultProps, descriptors);
} | javascript | function addAsyncPropsToPropPrototype(defaultProps, propTypes) {
const defaultValues = {};
const descriptors = {
// Default "resolved" values for async props, returned if value not yet resolved/set.
_asyncPropDefaultValues: {
enumerable: false,
value: defaultValues
},
// Shadowed object, just to make sure "early indexing" into the instance does not fail
_asyncPropOriginalValues: {
enumerable: false,
value: {}
}
};
// Move async props into shadow values
for (const propName in propTypes) {
const propType = propTypes[propName];
const {name, value} = propType;
// Note: async is ES7 keyword, can't destructure
if (propType.async) {
defaultValues[name] = value;
descriptors[name] = getDescriptorForAsyncProp(name, value);
}
}
Object.defineProperties(defaultProps, descriptors);
} | [
"function",
"addAsyncPropsToPropPrototype",
"(",
"defaultProps",
",",
"propTypes",
")",
"{",
"const",
"defaultValues",
"=",
"{",
"}",
";",
"const",
"descriptors",
"=",
"{",
"// Default \"resolved\" values for async props, returned if value not yet resolved/set.",
"_asyncPropDefaultValues",
":",
"{",
"enumerable",
":",
"false",
",",
"value",
":",
"defaultValues",
"}",
",",
"// Shadowed object, just to make sure \"early indexing\" into the instance does not fail",
"_asyncPropOriginalValues",
":",
"{",
"enumerable",
":",
"false",
",",
"value",
":",
"{",
"}",
"}",
"}",
";",
"// Move async props into shadow values",
"for",
"(",
"const",
"propName",
"in",
"propTypes",
")",
"{",
"const",
"propType",
"=",
"propTypes",
"[",
"propName",
"]",
";",
"const",
"{",
"name",
",",
"value",
"}",
"=",
"propType",
";",
"// Note: async is ES7 keyword, can't destructure",
"if",
"(",
"propType",
".",
"async",
")",
"{",
"defaultValues",
"[",
"name",
"]",
"=",
"value",
";",
"descriptors",
"[",
"name",
"]",
"=",
"getDescriptorForAsyncProp",
"(",
"name",
",",
"value",
")",
";",
"}",
"}",
"Object",
".",
"defineProperties",
"(",
"defaultProps",
",",
"descriptors",
")",
";",
"}"
] | Create descriptors for overridable props | [
"Create",
"descriptors",
"for",
"overridable",
"props"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/core/src/lifecycle/create-props.js#L165-L194 |
560 | uber/deck.gl | modules/react/src/utils/extract-jsx-layers.js | wrapInView | function wrapInView(node) {
if (!node) {
return node;
}
if (typeof node === 'function') {
// React.Children does not traverse functions.
// All render callbacks must be protected under a <View>
return createElement(View, {}, node);
}
if (Array.isArray(node)) {
return node.map(wrapInView);
}
if (inheritsFrom(node.type, View)) {
return node;
}
return node;
} | javascript | function wrapInView(node) {
if (!node) {
return node;
}
if (typeof node === 'function') {
// React.Children does not traverse functions.
// All render callbacks must be protected under a <View>
return createElement(View, {}, node);
}
if (Array.isArray(node)) {
return node.map(wrapInView);
}
if (inheritsFrom(node.type, View)) {
return node;
}
return node;
} | [
"function",
"wrapInView",
"(",
"node",
")",
"{",
"if",
"(",
"!",
"node",
")",
"{",
"return",
"node",
";",
"}",
"if",
"(",
"typeof",
"node",
"===",
"'function'",
")",
"{",
"// React.Children does not traverse functions.",
"// All render callbacks must be protected under a <View>",
"return",
"createElement",
"(",
"View",
",",
"{",
"}",
",",
"node",
")",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"node",
")",
")",
"{",
"return",
"node",
".",
"map",
"(",
"wrapInView",
")",
";",
"}",
"if",
"(",
"inheritsFrom",
"(",
"node",
".",
"type",
",",
"View",
")",
")",
"{",
"return",
"node",
";",
"}",
"return",
"node",
";",
"}"
] | recursively wrap render callbacks in `View` | [
"recursively",
"wrap",
"render",
"callbacks",
"in",
"View"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/react/src/utils/extract-jsx-layers.js#L6-L22 |
561 | uber/deck.gl | examples/website/plot/plot-layer/utils.js | setTextStyle | function setTextStyle(ctx, fontSize) {
ctx.font = `${fontSize}px Helvetica,Arial,sans-serif`;
ctx.fillStyle = '#000';
ctx.textBaseline = 'top';
ctx.textAlign = 'center';
} | javascript | function setTextStyle(ctx, fontSize) {
ctx.font = `${fontSize}px Helvetica,Arial,sans-serif`;
ctx.fillStyle = '#000';
ctx.textBaseline = 'top';
ctx.textAlign = 'center';
} | [
"function",
"setTextStyle",
"(",
"ctx",
",",
"fontSize",
")",
"{",
"ctx",
".",
"font",
"=",
"`",
"${",
"fontSize",
"}",
"`",
";",
"ctx",
".",
"fillStyle",
"=",
"'#000'",
";",
"ctx",
".",
"textBaseline",
"=",
"'top'",
";",
"ctx",
".",
"textAlign",
"=",
"'center'",
";",
"}"
] | helper for textMatrixToTexture | [
"helper",
"for",
"textMatrixToTexture"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/examples/website/plot/plot-layer/utils.js#L6-L11 |
562 | uber/deck.gl | modules/core/src/utils/old-log.js | time | function time(priority, label) {
assert(Number.isFinite(priority), 'log priority must be a number');
if (priority <= log.priority) {
// In case the platform doesn't have console.time
if (console.time) {
console.time(label);
} else {
console.info(label);
}
}
} | javascript | function time(priority, label) {
assert(Number.isFinite(priority), 'log priority must be a number');
if (priority <= log.priority) {
// In case the platform doesn't have console.time
if (console.time) {
console.time(label);
} else {
console.info(label);
}
}
} | [
"function",
"time",
"(",
"priority",
",",
"label",
")",
"{",
"assert",
"(",
"Number",
".",
"isFinite",
"(",
"priority",
")",
",",
"'log priority must be a number'",
")",
";",
"if",
"(",
"priority",
"<=",
"log",
".",
"priority",
")",
"{",
"// In case the platform doesn't have console.time",
"if",
"(",
"console",
".",
"time",
")",
"{",
"console",
".",
"time",
"(",
"label",
")",
";",
"}",
"else",
"{",
"console",
".",
"info",
"(",
"label",
")",
";",
"}",
"}",
"}"
] | Logs a message with a time | [
"Logs",
"a",
"message",
"with",
"a",
"time"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/core/src/utils/old-log.js#L71-L81 |
563 | uber/deck.gl | modules/core/src/utils/old-log.js | checkForAssertionErrors | function checkForAssertionErrors(args) {
const isAssertion =
args &&
args.length > 0 &&
typeof args[0] === 'object' &&
args[0] !== null &&
args[0].name === 'AssertionError';
if (isAssertion) {
args = Array.prototype.slice.call(args);
args.unshift(`assert(${args[0].message})`);
}
return args;
} | javascript | function checkForAssertionErrors(args) {
const isAssertion =
args &&
args.length > 0 &&
typeof args[0] === 'object' &&
args[0] !== null &&
args[0].name === 'AssertionError';
if (isAssertion) {
args = Array.prototype.slice.call(args);
args.unshift(`assert(${args[0].message})`);
}
return args;
} | [
"function",
"checkForAssertionErrors",
"(",
"args",
")",
"{",
"const",
"isAssertion",
"=",
"args",
"&&",
"args",
".",
"length",
">",
"0",
"&&",
"typeof",
"args",
"[",
"0",
"]",
"===",
"'object'",
"&&",
"args",
"[",
"0",
"]",
"!==",
"null",
"&&",
"args",
"[",
"0",
"]",
".",
"name",
"===",
"'AssertionError'",
";",
"if",
"(",
"isAssertion",
")",
"{",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"args",
")",
";",
"args",
".",
"unshift",
"(",
"`",
"${",
"args",
"[",
"0",
"]",
".",
"message",
"}",
"`",
")",
";",
"}",
"return",
"args",
";",
"}"
] | Assertions don't generate standard exceptions and don't print nicely | [
"Assertions",
"don",
"t",
"generate",
"standard",
"exceptions",
"and",
"don",
"t",
"print",
"nicely"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/core/src/utils/old-log.js#L127-L140 |
564 | uber/deck.gl | modules/layers/src/solid-polygon-layer/polygon.js | isNestedRingClosed | function isNestedRingClosed(simplePolygon) {
// check if first and last vertex are the same
const p0 = simplePolygon[0];
const p1 = simplePolygon[simplePolygon.length - 1];
return p0[0] === p1[0] && p0[1] === p1[1] && p0[2] === p1[2];
} | javascript | function isNestedRingClosed(simplePolygon) {
// check if first and last vertex are the same
const p0 = simplePolygon[0];
const p1 = simplePolygon[simplePolygon.length - 1];
return p0[0] === p1[0] && p0[1] === p1[1] && p0[2] === p1[2];
} | [
"function",
"isNestedRingClosed",
"(",
"simplePolygon",
")",
"{",
"// check if first and last vertex are the same",
"const",
"p0",
"=",
"simplePolygon",
"[",
"0",
"]",
";",
"const",
"p1",
"=",
"simplePolygon",
"[",
"simplePolygon",
".",
"length",
"-",
"1",
"]",
";",
"return",
"p0",
"[",
"0",
"]",
"===",
"p1",
"[",
"0",
"]",
"&&",
"p0",
"[",
"1",
"]",
"===",
"p1",
"[",
"1",
"]",
"&&",
"p0",
"[",
"2",
"]",
"===",
"p1",
"[",
"2",
"]",
";",
"}"
] | Check if a simple polygon is a closed ring
@param {Array} simplePolygon - array of points
@return {Boolean} - true if the simple polygon is a closed ring | [
"Check",
"if",
"a",
"simple",
"polygon",
"is",
"a",
"closed",
"ring"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/layers/src/solid-polygon-layer/polygon.js#L57-L63 |
565 | uber/deck.gl | modules/layers/src/solid-polygon-layer/polygon.js | isFlatRingClosed | function isFlatRingClosed(positions, size, startIndex, endIndex) {
for (let i = 0; i < size; i++) {
if (positions[startIndex + i] !== positions[endIndex - size + i]) {
return false;
}
}
return true;
} | javascript | function isFlatRingClosed(positions, size, startIndex, endIndex) {
for (let i = 0; i < size; i++) {
if (positions[startIndex + i] !== positions[endIndex - size + i]) {
return false;
}
}
return true;
} | [
"function",
"isFlatRingClosed",
"(",
"positions",
",",
"size",
",",
"startIndex",
",",
"endIndex",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"++",
")",
"{",
"if",
"(",
"positions",
"[",
"startIndex",
"+",
"i",
"]",
"!==",
"positions",
"[",
"endIndex",
"-",
"size",
"+",
"i",
"]",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Check if a simple flat array is a closed ring
@param {Array} positions - array of numbers
@param {Number} size - size of a position, 2 (xy) or 3 (xyz)
@param {Number} startIndex - start index of the path in the positions array
@param {Number} endIndex - end index of the path in the positions array
@return {Boolean} - true if the simple flat array is a closed ring | [
"Check",
"if",
"a",
"simple",
"flat",
"array",
"is",
"a",
"closed",
"ring"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/layers/src/solid-polygon-layer/polygon.js#L73-L80 |
566 | uber/deck.gl | modules/layers/src/solid-polygon-layer/polygon.js | copyNestedRing | function copyNestedRing(target, targetStartIndex, simplePolygon, size) {
let targetIndex = targetStartIndex;
const len = simplePolygon.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < size; j++) {
target[targetIndex++] = simplePolygon[i][j] || 0;
}
}
if (!isNestedRingClosed(simplePolygon)) {
for (let j = 0; j < size; j++) {
target[targetIndex++] = simplePolygon[0][j] || 0;
}
}
return targetIndex;
} | javascript | function copyNestedRing(target, targetStartIndex, simplePolygon, size) {
let targetIndex = targetStartIndex;
const len = simplePolygon.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < size; j++) {
target[targetIndex++] = simplePolygon[i][j] || 0;
}
}
if (!isNestedRingClosed(simplePolygon)) {
for (let j = 0; j < size; j++) {
target[targetIndex++] = simplePolygon[0][j] || 0;
}
}
return targetIndex;
} | [
"function",
"copyNestedRing",
"(",
"target",
",",
"targetStartIndex",
",",
"simplePolygon",
",",
"size",
")",
"{",
"let",
"targetIndex",
"=",
"targetStartIndex",
";",
"const",
"len",
"=",
"simplePolygon",
".",
"length",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"size",
";",
"j",
"++",
")",
"{",
"target",
"[",
"targetIndex",
"++",
"]",
"=",
"simplePolygon",
"[",
"i",
"]",
"[",
"j",
"]",
"||",
"0",
";",
"}",
"}",
"if",
"(",
"!",
"isNestedRingClosed",
"(",
"simplePolygon",
")",
")",
"{",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"size",
";",
"j",
"++",
")",
"{",
"target",
"[",
"targetIndex",
"++",
"]",
"=",
"simplePolygon",
"[",
"0",
"]",
"[",
"j",
"]",
"||",
"0",
";",
"}",
"}",
"return",
"targetIndex",
";",
"}"
] | Copy a simple polygon coordinates into a flat array, closes the ring if needed.
@param {Float64Array} target - destination
@param {Number} targetStartIndex - index in the destination to start copying into
@param {Array} simplePolygon - array of points
@param {Number} size - size of a position, 2 (xy) or 3 (xyz)
@returns {Number} - the index of the write head in the destination | [
"Copy",
"a",
"simple",
"polygon",
"coordinates",
"into",
"a",
"flat",
"array",
"closes",
"the",
"ring",
"if",
"needed",
"."
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/layers/src/solid-polygon-layer/polygon.js#L90-L105 |
567 | uber/deck.gl | modules/layers/src/solid-polygon-layer/polygon.js | copyFlatRing | function copyFlatRing(target, targetStartIndex, positions, size, srcStartIndex = 0, srcEndIndex) {
srcEndIndex = srcEndIndex || positions.length;
const srcLength = srcEndIndex - srcStartIndex;
if (srcLength <= 0) {
return targetStartIndex;
}
let targetIndex = targetStartIndex;
for (let i = 0; i < srcLength; i++) {
target[targetIndex++] = positions[srcStartIndex + i];
}
if (!isFlatRingClosed(positions, size, srcStartIndex, srcEndIndex)) {
for (let i = 0; i < size; i++) {
target[targetIndex++] = positions[srcStartIndex + i];
}
}
return targetIndex;
} | javascript | function copyFlatRing(target, targetStartIndex, positions, size, srcStartIndex = 0, srcEndIndex) {
srcEndIndex = srcEndIndex || positions.length;
const srcLength = srcEndIndex - srcStartIndex;
if (srcLength <= 0) {
return targetStartIndex;
}
let targetIndex = targetStartIndex;
for (let i = 0; i < srcLength; i++) {
target[targetIndex++] = positions[srcStartIndex + i];
}
if (!isFlatRingClosed(positions, size, srcStartIndex, srcEndIndex)) {
for (let i = 0; i < size; i++) {
target[targetIndex++] = positions[srcStartIndex + i];
}
}
return targetIndex;
} | [
"function",
"copyFlatRing",
"(",
"target",
",",
"targetStartIndex",
",",
"positions",
",",
"size",
",",
"srcStartIndex",
"=",
"0",
",",
"srcEndIndex",
")",
"{",
"srcEndIndex",
"=",
"srcEndIndex",
"||",
"positions",
".",
"length",
";",
"const",
"srcLength",
"=",
"srcEndIndex",
"-",
"srcStartIndex",
";",
"if",
"(",
"srcLength",
"<=",
"0",
")",
"{",
"return",
"targetStartIndex",
";",
"}",
"let",
"targetIndex",
"=",
"targetStartIndex",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"srcLength",
";",
"i",
"++",
")",
"{",
"target",
"[",
"targetIndex",
"++",
"]",
"=",
"positions",
"[",
"srcStartIndex",
"+",
"i",
"]",
";",
"}",
"if",
"(",
"!",
"isFlatRingClosed",
"(",
"positions",
",",
"size",
",",
"srcStartIndex",
",",
"srcEndIndex",
")",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"++",
")",
"{",
"target",
"[",
"targetIndex",
"++",
"]",
"=",
"positions",
"[",
"srcStartIndex",
"+",
"i",
"]",
";",
"}",
"}",
"return",
"targetIndex",
";",
"}"
] | Copy a simple flat array into another flat array, closes the ring if needed.
@param {Float64Array} target - destination
@param {Number} targetStartIndex - index in the destination to start copying into
@param {Array} positions - array of numbers
@param {Number} size - size of a position, 2 (xy) or 3 (xyz)
@param {Number} [srcStartIndex] - start index of the path in the positions array
@param {Number} [srcEndIndex] - end index of the path in the positions array
@returns {Number} - the index of the write head in the destination | [
"Copy",
"a",
"simple",
"flat",
"array",
"into",
"another",
"flat",
"array",
"closes",
"the",
"ring",
"if",
"needed",
"."
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/layers/src/solid-polygon-layer/polygon.js#L117-L135 |
568 | uber/deck.gl | modules/layers/src/solid-polygon-layer/polygon.js | getFlatVertexCount | function getFlatVertexCount(positions, size, startIndex = 0, endIndex) {
endIndex = endIndex || positions.length;
if (startIndex >= endIndex) {
return 0;
}
return (
(isFlatRingClosed(positions, size, startIndex, endIndex) ? 0 : 1) +
(endIndex - startIndex) / size
);
} | javascript | function getFlatVertexCount(positions, size, startIndex = 0, endIndex) {
endIndex = endIndex || positions.length;
if (startIndex >= endIndex) {
return 0;
}
return (
(isFlatRingClosed(positions, size, startIndex, endIndex) ? 0 : 1) +
(endIndex - startIndex) / size
);
} | [
"function",
"getFlatVertexCount",
"(",
"positions",
",",
"size",
",",
"startIndex",
"=",
"0",
",",
"endIndex",
")",
"{",
"endIndex",
"=",
"endIndex",
"||",
"positions",
".",
"length",
";",
"if",
"(",
"startIndex",
">=",
"endIndex",
")",
"{",
"return",
"0",
";",
"}",
"return",
"(",
"(",
"isFlatRingClosed",
"(",
"positions",
",",
"size",
",",
"startIndex",
",",
"endIndex",
")",
"?",
"0",
":",
"1",
")",
"+",
"(",
"endIndex",
"-",
"startIndex",
")",
"/",
"size",
")",
";",
"}"
] | Counts the number of vertices in a simple flat array, closes the polygon if needed.
@param {Array} positions - array of numbers
@param {Number} size - size of a position, 2 (xy) or 3 (xyz)
@param {Number} [startIndex] - start index of the path in the positions array
@param {Number} [endIndex] - end index of the path in the positions array
@returns {Number} vertex count | [
"Counts",
"the",
"number",
"of",
"vertices",
"in",
"a",
"simple",
"flat",
"array",
"closes",
"the",
"polygon",
"if",
"needed",
"."
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/layers/src/solid-polygon-layer/polygon.js#L154-L163 |
569 | uber/deck.gl | modules/jupyter-widget/src/plugin.js | activateWidgetExtension | function activateWidgetExtension(app, registry) {
registry.registerWidget({
name: MODULE_NAME,
version: MODULE_VERSION,
exports: {
DeckGLModel,
DeckGLView
}
});
} | javascript | function activateWidgetExtension(app, registry) {
registry.registerWidget({
name: MODULE_NAME,
version: MODULE_VERSION,
exports: {
DeckGLModel,
DeckGLView
}
});
} | [
"function",
"activateWidgetExtension",
"(",
"app",
",",
"registry",
")",
"{",
"registry",
".",
"registerWidget",
"(",
"{",
"name",
":",
"MODULE_NAME",
",",
"version",
":",
"MODULE_VERSION",
",",
"exports",
":",
"{",
"DeckGLModel",
",",
"DeckGLView",
"}",
"}",
")",
";",
"}"
] | Registers the widget with the Jupyter notebook | [
"Registers",
"the",
"widget",
"with",
"the",
"Jupyter",
"notebook"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/jupyter-widget/src/plugin.js#L21-L30 |
570 | uber/deck.gl | modules/layers/src/text-layer/font-atlas-manager.js | getNewChars | function getNewChars(key, characterSet) {
const cachedFontAtlas = cache.get(key);
if (!cachedFontAtlas) {
return characterSet;
}
const newChars = [];
const cachedMapping = cachedFontAtlas.mapping;
let cachedCharSet = Object.keys(cachedMapping);
cachedCharSet = new Set(cachedCharSet);
let charSet = characterSet;
if (charSet instanceof Array) {
charSet = new Set(charSet);
}
charSet.forEach(char => {
if (!cachedCharSet.has(char)) {
newChars.push(char);
}
});
return newChars;
} | javascript | function getNewChars(key, characterSet) {
const cachedFontAtlas = cache.get(key);
if (!cachedFontAtlas) {
return characterSet;
}
const newChars = [];
const cachedMapping = cachedFontAtlas.mapping;
let cachedCharSet = Object.keys(cachedMapping);
cachedCharSet = new Set(cachedCharSet);
let charSet = characterSet;
if (charSet instanceof Array) {
charSet = new Set(charSet);
}
charSet.forEach(char => {
if (!cachedCharSet.has(char)) {
newChars.push(char);
}
});
return newChars;
} | [
"function",
"getNewChars",
"(",
"key",
",",
"characterSet",
")",
"{",
"const",
"cachedFontAtlas",
"=",
"cache",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"!",
"cachedFontAtlas",
")",
"{",
"return",
"characterSet",
";",
"}",
"const",
"newChars",
"=",
"[",
"]",
";",
"const",
"cachedMapping",
"=",
"cachedFontAtlas",
".",
"mapping",
";",
"let",
"cachedCharSet",
"=",
"Object",
".",
"keys",
"(",
"cachedMapping",
")",
";",
"cachedCharSet",
"=",
"new",
"Set",
"(",
"cachedCharSet",
")",
";",
"let",
"charSet",
"=",
"characterSet",
";",
"if",
"(",
"charSet",
"instanceof",
"Array",
")",
"{",
"charSet",
"=",
"new",
"Set",
"(",
"charSet",
")",
";",
"}",
"charSet",
".",
"forEach",
"(",
"char",
"=>",
"{",
"if",
"(",
"!",
"cachedCharSet",
".",
"has",
"(",
"char",
")",
")",
"{",
"newChars",
".",
"push",
"(",
"char",
")",
";",
"}",
"}",
")",
";",
"return",
"newChars",
";",
"}"
] | get all the chars not in cache
@param key cache key
@param characterSet (Array|Set)
@returns {Array} chars not in cache | [
"get",
"all",
"the",
"chars",
"not",
"in",
"cache"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/layers/src/text-layer/font-atlas-manager.js#L67-L90 |
571 | uber/deck.gl | modules/google-maps/src/utils.js | handleMouseEvent | function handleMouseEvent(deck, type, event) {
let callback;
switch (type) {
case 'click':
// Hack: because we do not listen to pointer down, perform picking now
deck._lastPointerDownInfo = deck.pickObject({
x: event.pixel.x,
y: event.pixel.y
});
callback = deck._onEvent;
break;
case 'mousemove':
callback = deck._onPointerMove;
break;
case 'mouseout':
callback = deck._onPointerLeave;
break;
default:
return;
}
callback({
type,
offsetCenter: event.pixel,
srcEvent: event
});
} | javascript | function handleMouseEvent(deck, type, event) {
let callback;
switch (type) {
case 'click':
// Hack: because we do not listen to pointer down, perform picking now
deck._lastPointerDownInfo = deck.pickObject({
x: event.pixel.x,
y: event.pixel.y
});
callback = deck._onEvent;
break;
case 'mousemove':
callback = deck._onPointerMove;
break;
case 'mouseout':
callback = deck._onPointerLeave;
break;
default:
return;
}
callback({
type,
offsetCenter: event.pixel,
srcEvent: event
});
} | [
"function",
"handleMouseEvent",
"(",
"deck",
",",
"type",
",",
"event",
")",
"{",
"let",
"callback",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"'click'",
":",
"// Hack: because we do not listen to pointer down, perform picking now",
"deck",
".",
"_lastPointerDownInfo",
"=",
"deck",
".",
"pickObject",
"(",
"{",
"x",
":",
"event",
".",
"pixel",
".",
"x",
",",
"y",
":",
"event",
".",
"pixel",
".",
"y",
"}",
")",
";",
"callback",
"=",
"deck",
".",
"_onEvent",
";",
"break",
";",
"case",
"'mousemove'",
":",
"callback",
"=",
"deck",
".",
"_onPointerMove",
";",
"break",
";",
"case",
"'mouseout'",
":",
"callback",
"=",
"deck",
".",
"_onPointerLeave",
";",
"break",
";",
"default",
":",
"return",
";",
"}",
"callback",
"(",
"{",
"type",
",",
"offsetCenter",
":",
"event",
".",
"pixel",
",",
"srcEvent",
":",
"event",
"}",
")",
";",
"}"
] | Triggers picking on a mouse event | [
"Triggers",
"picking",
"on",
"a",
"mouse",
"event"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/google-maps/src/utils.js#L130-L159 |
572 | uber/deck.gl | modules/geo-layers/src/s2-layer/s2-utils.js | getLevelFromToken | function getLevelFromToken(token) {
// leaf level token size is 16. Each 2 bit add a level
const lastHex = token.substr(token.length - 1);
// a) token = trailing-zero trimmed hex id
// b) 64 bit hex id - 3 face bit + 60 bits for 30 levels + 1 bit lsb marker
const level = 2 * (token.length - 1) - ((lastHex & 1) === 0);
// c) If lsb bit of last hex digit is zero, we have one more level less of
return level;
} | javascript | function getLevelFromToken(token) {
// leaf level token size is 16. Each 2 bit add a level
const lastHex = token.substr(token.length - 1);
// a) token = trailing-zero trimmed hex id
// b) 64 bit hex id - 3 face bit + 60 bits for 30 levels + 1 bit lsb marker
const level = 2 * (token.length - 1) - ((lastHex & 1) === 0);
// c) If lsb bit of last hex digit is zero, we have one more level less of
return level;
} | [
"function",
"getLevelFromToken",
"(",
"token",
")",
"{",
"// leaf level token size is 16. Each 2 bit add a level",
"const",
"lastHex",
"=",
"token",
".",
"substr",
"(",
"token",
".",
"length",
"-",
"1",
")",
";",
"// a) token = trailing-zero trimmed hex id",
"// b) 64 bit hex id - 3 face bit + 60 bits for 30 levels + 1 bit lsb marker",
"const",
"level",
"=",
"2",
"*",
"(",
"token",
".",
"length",
"-",
"1",
")",
"-",
"(",
"(",
"lastHex",
"&",
"1",
")",
"===",
"0",
")",
";",
"// c) If lsb bit of last hex digit is zero, we have one more level less of",
"return",
"level",
";",
"}"
] | Given a S2 hex token this function returns cell level
cells level is a number between 1 and 30
S2 cell id is a 64 bit number
S2 token removed all trailing zeros from the 16 bit converted number | [
"Given",
"a",
"S2",
"hex",
"token",
"this",
"function",
"returns",
"cell",
"level",
"cells",
"level",
"is",
"a",
"number",
"between",
"1",
"and",
"30"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/geo-layers/src/s2-layer/s2-utils.js#L12-L20 |
573 | uber/deck.gl | modules/core/src/utils/flatten.js | flattenArray | function flattenArray(array, filter, map, result) {
let index = -1;
while (++index < array.length) {
const value = array[index];
if (Array.isArray(value)) {
flattenArray(value, filter, map, result);
} else if (filter(value)) {
result.push(map(value));
}
}
return result;
} | javascript | function flattenArray(array, filter, map, result) {
let index = -1;
while (++index < array.length) {
const value = array[index];
if (Array.isArray(value)) {
flattenArray(value, filter, map, result);
} else if (filter(value)) {
result.push(map(value));
}
}
return result;
} | [
"function",
"flattenArray",
"(",
"array",
",",
"filter",
",",
"map",
",",
"result",
")",
"{",
"let",
"index",
"=",
"-",
"1",
";",
"while",
"(",
"++",
"index",
"<",
"array",
".",
"length",
")",
"{",
"const",
"value",
"=",
"array",
"[",
"index",
"]",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"flattenArray",
"(",
"value",
",",
"filter",
",",
"map",
",",
"result",
")",
";",
"}",
"else",
"if",
"(",
"filter",
"(",
"value",
")",
")",
"{",
"result",
".",
"push",
"(",
"map",
"(",
"value",
")",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | Deep flattens an array. Helper to `flatten`, see its parameters | [
"Deep",
"flattens",
"an",
"array",
".",
"Helper",
"to",
"flatten",
"see",
"its",
"parameters"
] | a2010448b7f268bbd03617b812334c68a6b9e5b2 | https://github.com/uber/deck.gl/blob/a2010448b7f268bbd03617b812334c68a6b9e5b2/modules/core/src/utils/flatten.js#L43-L54 |
574 | grpc/grpc | examples/node/static_codegen/greeter_server.js | sayHello | function sayHello(call, callback) {
var reply = new messages.HelloReply();
reply.setMessage('Hello ' + call.request.getName());
callback(null, reply);
} | javascript | function sayHello(call, callback) {
var reply = new messages.HelloReply();
reply.setMessage('Hello ' + call.request.getName());
callback(null, reply);
} | [
"function",
"sayHello",
"(",
"call",
",",
"callback",
")",
"{",
"var",
"reply",
"=",
"new",
"messages",
".",
"HelloReply",
"(",
")",
";",
"reply",
".",
"setMessage",
"(",
"'Hello '",
"+",
"call",
".",
"request",
".",
"getName",
"(",
")",
")",
";",
"callback",
"(",
"null",
",",
"reply",
")",
";",
"}"
] | Implements the SayHello RPC method. | [
"Implements",
"the",
"SayHello",
"RPC",
"method",
"."
] | cc75d93818410e2b0edd0fa3009a6def9ac403ca | https://github.com/grpc/grpc/blob/cc75d93818410e2b0edd0fa3009a6def9ac403ca/examples/node/static_codegen/greeter_server.js#L27-L31 |
575 | cypress-io/cypress | packages/server/lib/util/net_profiler.js | NetProfiler | function NetProfiler (options = {}) {
if (!(this instanceof NetProfiler)) return new NetProfiler(options)
if (!options.net) {
options.net = require('net')
}
this.net = options.net
this.proxies = {}
this.activeConnections = []
this.startTs = new Date() / 1000
this.tickMs = options.tickMs || 1000
this.tickWhenNoneActive = options.tickWhenNoneActive || false
this.logPath = getLogPath(options.logPath)
debug('logging to ', this.logPath)
this.startProfiling()
} | javascript | function NetProfiler (options = {}) {
if (!(this instanceof NetProfiler)) return new NetProfiler(options)
if (!options.net) {
options.net = require('net')
}
this.net = options.net
this.proxies = {}
this.activeConnections = []
this.startTs = new Date() / 1000
this.tickMs = options.tickMs || 1000
this.tickWhenNoneActive = options.tickWhenNoneActive || false
this.logPath = getLogPath(options.logPath)
debug('logging to ', this.logPath)
this.startProfiling()
} | [
"function",
"NetProfiler",
"(",
"options",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"NetProfiler",
")",
")",
"return",
"new",
"NetProfiler",
"(",
"options",
")",
"if",
"(",
"!",
"options",
".",
"net",
")",
"{",
"options",
".",
"net",
"=",
"require",
"(",
"'net'",
")",
"}",
"this",
".",
"net",
"=",
"options",
".",
"net",
"this",
".",
"proxies",
"=",
"{",
"}",
"this",
".",
"activeConnections",
"=",
"[",
"]",
"this",
".",
"startTs",
"=",
"new",
"Date",
"(",
")",
"/",
"1000",
"this",
".",
"tickMs",
"=",
"options",
".",
"tickMs",
"||",
"1000",
"this",
".",
"tickWhenNoneActive",
"=",
"options",
".",
"tickWhenNoneActive",
"||",
"false",
"this",
".",
"logPath",
"=",
"getLogPath",
"(",
"options",
".",
"logPath",
")",
"debug",
"(",
"'logging to '",
",",
"this",
".",
"logPath",
")",
"this",
".",
"startProfiling",
"(",
")",
"}"
] | Tracks all incoming and outgoing network connections and logs a timeline of network traffic to a file.
@param options.net the `net` object to stub, default: nodejs net object
@param options.tickMs the number of milliseconds between ticks in the profile, default: 1000
@param options.tickWhenNoneActive should ticks be recorded when no connections are active, default: false
@param options.logPath path to the file to append to, default: new file in your temp directory | [
"Tracks",
"all",
"incoming",
"and",
"outgoing",
"network",
"connections",
"and",
"logs",
"a",
"timeline",
"of",
"network",
"traffic",
"to",
"a",
"file",
"."
] | bf1a942944f0e99684ff7fe0e18314332e46f83e | https://github.com/cypress-io/cypress/blob/bf1a942944f0e99684ff7fe0e18314332e46f83e/packages/server/lib/util/net_profiler.js#L61-L79 |
576 | cypress-io/cypress | cli/lib/errors.js | formErrorText | function formErrorText (info, msg) {
const hr = '----------'
return addPlatformInformation(info)
.then((obj) => {
const formatted = []
function add (msg) {
formatted.push(
stripIndents(msg)
)
}
add(`
${obj.description}
${obj.solution}
`)
if (msg) {
add(`
${hr}
${msg}
`)
}
add(`
${hr}
${obj.platform}
`)
if (obj.footer) {
add(`
${hr}
${obj.footer}
`)
}
return formatted.join('\n\n')
})
} | javascript | function formErrorText (info, msg) {
const hr = '----------'
return addPlatformInformation(info)
.then((obj) => {
const formatted = []
function add (msg) {
formatted.push(
stripIndents(msg)
)
}
add(`
${obj.description}
${obj.solution}
`)
if (msg) {
add(`
${hr}
${msg}
`)
}
add(`
${hr}
${obj.platform}
`)
if (obj.footer) {
add(`
${hr}
${obj.footer}
`)
}
return formatted.join('\n\n')
})
} | [
"function",
"formErrorText",
"(",
"info",
",",
"msg",
")",
"{",
"const",
"hr",
"=",
"'----------'",
"return",
"addPlatformInformation",
"(",
"info",
")",
".",
"then",
"(",
"(",
"obj",
")",
"=>",
"{",
"const",
"formatted",
"=",
"[",
"]",
"function",
"add",
"(",
"msg",
")",
"{",
"formatted",
".",
"push",
"(",
"stripIndents",
"(",
"msg",
")",
")",
"}",
"add",
"(",
"`",
"${",
"obj",
".",
"description",
"}",
"${",
"obj",
".",
"solution",
"}",
"`",
")",
"if",
"(",
"msg",
")",
"{",
"add",
"(",
"`",
"${",
"hr",
"}",
"${",
"msg",
"}",
"`",
")",
"}",
"add",
"(",
"`",
"${",
"hr",
"}",
"${",
"obj",
".",
"platform",
"}",
"`",
")",
"if",
"(",
"obj",
".",
"footer",
")",
"{",
"add",
"(",
"`",
"${",
"hr",
"}",
"${",
"obj",
".",
"footer",
"}",
"`",
")",
"}",
"return",
"formatted",
".",
"join",
"(",
"'\\n\\n'",
")",
"}",
")",
"}"
] | Forms nice error message with error and platform information,
and if possible a way to solve it. Resolves with a string. | [
"Forms",
"nice",
"error",
"message",
"with",
"error",
"and",
"platform",
"information",
"and",
"if",
"possible",
"a",
"way",
"to",
"solve",
"it",
".",
"Resolves",
"with",
"a",
"string",
"."
] | bf1a942944f0e99684ff7fe0e18314332e46f83e | https://github.com/cypress-io/cypress/blob/bf1a942944f0e99684ff7fe0e18314332e46f83e/cli/lib/errors.js#L195-L241 |
577 | cypress-io/cypress | cli/lib/cli.js | unknownOption | function unknownOption (flag, type = 'option') {
if (this._allowUnknownOption) return
logger.error()
logger.error(` error: unknown ${type}:`, flag)
logger.error()
this.outputHelp()
util.exit(1)
} | javascript | function unknownOption (flag, type = 'option') {
if (this._allowUnknownOption) return
logger.error()
logger.error(` error: unknown ${type}:`, flag)
logger.error()
this.outputHelp()
util.exit(1)
} | [
"function",
"unknownOption",
"(",
"flag",
",",
"type",
"=",
"'option'",
")",
"{",
"if",
"(",
"this",
".",
"_allowUnknownOption",
")",
"return",
"logger",
".",
"error",
"(",
")",
"logger",
".",
"error",
"(",
"`",
"${",
"type",
"}",
"`",
",",
"flag",
")",
"logger",
".",
"error",
"(",
")",
"this",
".",
"outputHelp",
"(",
")",
"util",
".",
"exit",
"(",
"1",
")",
"}"
] | patch "commander" method called when a user passed an unknown option we want to print help for the current command and exit with an error | [
"patch",
"commander",
"method",
"called",
"when",
"a",
"user",
"passed",
"an",
"unknown",
"option",
"we",
"want",
"to",
"print",
"help",
"for",
"the",
"current",
"command",
"and",
"exit",
"with",
"an",
"error"
] | bf1a942944f0e99684ff7fe0e18314332e46f83e | https://github.com/cypress-io/cypress/blob/bf1a942944f0e99684ff7fe0e18314332e46f83e/cli/lib/cli.js#L12-L20 |
578 | serverless/serverless | lib/plugins/aws/package/compile/events/apiGateway/lib/resources.js | applyResource | function applyResource(resource, isMethod) {
let root;
let parent;
let currentPath;
const path = resource.path.replace(/^\//, '').replace(/\/$/, '');
const pathParts = path.split('/');
function applyNodeResource(node, parts, index) {
const n = node;
if (index === parts.length - 1) {
n.name = resource.name;
if (resource.resourceId) {
n.resourceId = resource.resourceId;
if (_.every(predefinedResourceNodes, (iter) => iter.path !== n.path)) {
predefinedResourceNodes.push(node);
}
}
if (isMethod && !node.hasMethod) {
n.hasMethod = true;
if (_.every(methodNodes, (iter) => iter.path !== n.path)) {
methodNodes.push(node);
}
}
}
parent = node;
}
pathParts.forEach((pathPart, index) => {
currentPath = currentPath ? `${currentPath}/${pathPart}` : pathPart;
root = root || _.find(trees, (node) => node.path === currentPath);
parent = parent || root;
let node;
if (parent) {
if (parent.path === currentPath) {
applyNodeResource(parent, pathParts, index);
return;
} else if (parent.children.length > 0) {
node = _.find(parent.children, (n) => n.path === currentPath);
if (node) {
applyNodeResource(node, pathParts, index);
return;
}
}
}
node = {
path: currentPath,
pathPart,
parent,
level: index,
children: [],
};
if (parent) {
parent.children.push(node);
}
if (!root) {
root = node;
trees.push(root);
}
applyNodeResource(node, pathParts, index);
});
} | javascript | function applyResource(resource, isMethod) {
let root;
let parent;
let currentPath;
const path = resource.path.replace(/^\//, '').replace(/\/$/, '');
const pathParts = path.split('/');
function applyNodeResource(node, parts, index) {
const n = node;
if (index === parts.length - 1) {
n.name = resource.name;
if (resource.resourceId) {
n.resourceId = resource.resourceId;
if (_.every(predefinedResourceNodes, (iter) => iter.path !== n.path)) {
predefinedResourceNodes.push(node);
}
}
if (isMethod && !node.hasMethod) {
n.hasMethod = true;
if (_.every(methodNodes, (iter) => iter.path !== n.path)) {
methodNodes.push(node);
}
}
}
parent = node;
}
pathParts.forEach((pathPart, index) => {
currentPath = currentPath ? `${currentPath}/${pathPart}` : pathPart;
root = root || _.find(trees, (node) => node.path === currentPath);
parent = parent || root;
let node;
if (parent) {
if (parent.path === currentPath) {
applyNodeResource(parent, pathParts, index);
return;
} else if (parent.children.length > 0) {
node = _.find(parent.children, (n) => n.path === currentPath);
if (node) {
applyNodeResource(node, pathParts, index);
return;
}
}
}
node = {
path: currentPath,
pathPart,
parent,
level: index,
children: [],
};
if (parent) {
parent.children.push(node);
}
if (!root) {
root = node;
trees.push(root);
}
applyNodeResource(node, pathParts, index);
});
} | [
"function",
"applyResource",
"(",
"resource",
",",
"isMethod",
")",
"{",
"let",
"root",
";",
"let",
"parent",
";",
"let",
"currentPath",
";",
"const",
"path",
"=",
"resource",
".",
"path",
".",
"replace",
"(",
"/",
"^\\/",
"/",
",",
"''",
")",
".",
"replace",
"(",
"/",
"\\/$",
"/",
",",
"''",
")",
";",
"const",
"pathParts",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
";",
"function",
"applyNodeResource",
"(",
"node",
",",
"parts",
",",
"index",
")",
"{",
"const",
"n",
"=",
"node",
";",
"if",
"(",
"index",
"===",
"parts",
".",
"length",
"-",
"1",
")",
"{",
"n",
".",
"name",
"=",
"resource",
".",
"name",
";",
"if",
"(",
"resource",
".",
"resourceId",
")",
"{",
"n",
".",
"resourceId",
"=",
"resource",
".",
"resourceId",
";",
"if",
"(",
"_",
".",
"every",
"(",
"predefinedResourceNodes",
",",
"(",
"iter",
")",
"=>",
"iter",
".",
"path",
"!==",
"n",
".",
"path",
")",
")",
"{",
"predefinedResourceNodes",
".",
"push",
"(",
"node",
")",
";",
"}",
"}",
"if",
"(",
"isMethod",
"&&",
"!",
"node",
".",
"hasMethod",
")",
"{",
"n",
".",
"hasMethod",
"=",
"true",
";",
"if",
"(",
"_",
".",
"every",
"(",
"methodNodes",
",",
"(",
"iter",
")",
"=>",
"iter",
".",
"path",
"!==",
"n",
".",
"path",
")",
")",
"{",
"methodNodes",
".",
"push",
"(",
"node",
")",
";",
"}",
"}",
"}",
"parent",
"=",
"node",
";",
"}",
"pathParts",
".",
"forEach",
"(",
"(",
"pathPart",
",",
"index",
")",
"=>",
"{",
"currentPath",
"=",
"currentPath",
"?",
"`",
"${",
"currentPath",
"}",
"${",
"pathPart",
"}",
"`",
":",
"pathPart",
";",
"root",
"=",
"root",
"||",
"_",
".",
"find",
"(",
"trees",
",",
"(",
"node",
")",
"=>",
"node",
".",
"path",
"===",
"currentPath",
")",
";",
"parent",
"=",
"parent",
"||",
"root",
";",
"let",
"node",
";",
"if",
"(",
"parent",
")",
"{",
"if",
"(",
"parent",
".",
"path",
"===",
"currentPath",
")",
"{",
"applyNodeResource",
"(",
"parent",
",",
"pathParts",
",",
"index",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"parent",
".",
"children",
".",
"length",
">",
"0",
")",
"{",
"node",
"=",
"_",
".",
"find",
"(",
"parent",
".",
"children",
",",
"(",
"n",
")",
"=>",
"n",
".",
"path",
"===",
"currentPath",
")",
";",
"if",
"(",
"node",
")",
"{",
"applyNodeResource",
"(",
"node",
",",
"pathParts",
",",
"index",
")",
";",
"return",
";",
"}",
"}",
"}",
"node",
"=",
"{",
"path",
":",
"currentPath",
",",
"pathPart",
",",
"parent",
",",
"level",
":",
"index",
",",
"children",
":",
"[",
"]",
",",
"}",
";",
"if",
"(",
"parent",
")",
"{",
"parent",
".",
"children",
".",
"push",
"(",
"node",
")",
";",
"}",
"if",
"(",
"!",
"root",
")",
"{",
"root",
"=",
"node",
";",
"trees",
".",
"push",
"(",
"root",
")",
";",
"}",
"applyNodeResource",
"(",
"node",
",",
"pathParts",
",",
"index",
")",
";",
"}",
")",
";",
"}"
] | organize all resource paths into N-ary tree | [
"organize",
"all",
"resource",
"paths",
"into",
"N",
"-",
"ary",
"tree"
] | 0626d5b5df06e4ed68969e324f1cb6b1b499c443 | https://github.com/serverless/serverless/blob/0626d5b5df06e4ed68969e324f1cb6b1b499c443/lib/plugins/aws/package/compile/events/apiGateway/lib/resources.js#L81-L148 |
579 | serverless/serverless | lib/utils/userStatsValidation.js | isValidProject | function isValidProject(project) {
const isValid = VALID_TRACKING_PROJECTS.indexOf(project) !== -1;
if (!isValid) {
console.log(chalk.red('Tracking Error:'));
console.log(`"${project}" is invalid project. Must be one of`, VALID_TRACKING_PROJECTS);
}
return isValid;
} | javascript | function isValidProject(project) {
const isValid = VALID_TRACKING_PROJECTS.indexOf(project) !== -1;
if (!isValid) {
console.log(chalk.red('Tracking Error:'));
console.log(`"${project}" is invalid project. Must be one of`, VALID_TRACKING_PROJECTS);
}
return isValid;
} | [
"function",
"isValidProject",
"(",
"project",
")",
"{",
"const",
"isValid",
"=",
"VALID_TRACKING_PROJECTS",
".",
"indexOf",
"(",
"project",
")",
"!==",
"-",
"1",
";",
"if",
"(",
"!",
"isValid",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"'Tracking Error:'",
")",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"project",
"}",
"`",
",",
"VALID_TRACKING_PROJECTS",
")",
";",
"}",
"return",
"isValid",
";",
"}"
] | Validate tracking project for clean events | [
"Validate",
"tracking",
"project",
"for",
"clean",
"events"
] | 0626d5b5df06e4ed68969e324f1cb6b1b499c443 | https://github.com/serverless/serverless/blob/0626d5b5df06e4ed68969e324f1cb6b1b499c443/lib/utils/userStatsValidation.js#L31-L38 |
580 | serverless/serverless | lib/utils/userStatsValidation.js | isValidObject | function isValidObject(key) {
const isValid = VALID_TRACKING_OBJECTS.indexOf(key) !== -1;
if (!isValid) {
console.log(chalk.red('Tracking Error:'));
console.log(`"${key}" is invalid tracking object. Must be one of`, VALID_TRACKING_OBJECTS);
}
return isValid;
} | javascript | function isValidObject(key) {
const isValid = VALID_TRACKING_OBJECTS.indexOf(key) !== -1;
if (!isValid) {
console.log(chalk.red('Tracking Error:'));
console.log(`"${key}" is invalid tracking object. Must be one of`, VALID_TRACKING_OBJECTS);
}
return isValid;
} | [
"function",
"isValidObject",
"(",
"key",
")",
"{",
"const",
"isValid",
"=",
"VALID_TRACKING_OBJECTS",
".",
"indexOf",
"(",
"key",
")",
"!==",
"-",
"1",
";",
"if",
"(",
"!",
"isValid",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"'Tracking Error:'",
")",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"key",
"}",
"`",
",",
"VALID_TRACKING_OBJECTS",
")",
";",
"}",
"return",
"isValid",
";",
"}"
] | Validate tracking objects for clean events | [
"Validate",
"tracking",
"objects",
"for",
"clean",
"events"
] | 0626d5b5df06e4ed68969e324f1cb6b1b499c443 | https://github.com/serverless/serverless/blob/0626d5b5df06e4ed68969e324f1cb6b1b499c443/lib/utils/userStatsValidation.js#L41-L48 |
581 | serverless/serverless | lib/utils/downloadTemplateFromRepo.js | getPathDirectory | function getPathDirectory(length, parts) {
if (!parts) {
return '';
}
return parts
.slice(length)
.filter(part => part !== '')
.join(path.sep);
} | javascript | function getPathDirectory(length, parts) {
if (!parts) {
return '';
}
return parts
.slice(length)
.filter(part => part !== '')
.join(path.sep);
} | [
"function",
"getPathDirectory",
"(",
"length",
",",
"parts",
")",
"{",
"if",
"(",
"!",
"parts",
")",
"{",
"return",
"''",
";",
"}",
"return",
"parts",
".",
"slice",
"(",
"length",
")",
".",
"filter",
"(",
"part",
"=>",
"part",
"!==",
"''",
")",
".",
"join",
"(",
"path",
".",
"sep",
")",
";",
"}"
] | Returns directory path
@param {Number} length
@param {Array} parts
@returns {String} directory path | [
"Returns",
"directory",
"path"
] | 0626d5b5df06e4ed68969e324f1cb6b1b499c443 | https://github.com/serverless/serverless/blob/0626d5b5df06e4ed68969e324f1cb6b1b499c443/lib/utils/downloadTemplateFromRepo.js#L22-L30 |
582 | serverless/serverless | lib/utils/downloadTemplateFromRepo.js | parseRepoURL | function parseRepoURL(inputUrl) {
if (!inputUrl) {
throw new ServerlessError('URL is required');
}
const url = URL.parse(inputUrl.replace(/\/$/, ''));
// check if url parameter is a valid url
if (!url.host) {
throw new ServerlessError('The URL you passed is not a valid URL');
}
switch (url.hostname) {
case 'github.com': {
return parseGitHubURL(url);
}
case 'bitbucket.org': {
return parseBitbucketURL(url);
}
case 'gitlab.com': {
return parseGitlabURL(url);
}
default: {
const msg =
'The URL you passed is not one of the valid providers: "GitHub", "Bitbucket", or "GitLab".';
throw new ServerlessError(msg);
}
}
} | javascript | function parseRepoURL(inputUrl) {
if (!inputUrl) {
throw new ServerlessError('URL is required');
}
const url = URL.parse(inputUrl.replace(/\/$/, ''));
// check if url parameter is a valid url
if (!url.host) {
throw new ServerlessError('The URL you passed is not a valid URL');
}
switch (url.hostname) {
case 'github.com': {
return parseGitHubURL(url);
}
case 'bitbucket.org': {
return parseBitbucketURL(url);
}
case 'gitlab.com': {
return parseGitlabURL(url);
}
default: {
const msg =
'The URL you passed is not one of the valid providers: "GitHub", "Bitbucket", or "GitLab".';
throw new ServerlessError(msg);
}
}
} | [
"function",
"parseRepoURL",
"(",
"inputUrl",
")",
"{",
"if",
"(",
"!",
"inputUrl",
")",
"{",
"throw",
"new",
"ServerlessError",
"(",
"'URL is required'",
")",
";",
"}",
"const",
"url",
"=",
"URL",
".",
"parse",
"(",
"inputUrl",
".",
"replace",
"(",
"/",
"\\/$",
"/",
",",
"''",
")",
")",
";",
"// check if url parameter is a valid url",
"if",
"(",
"!",
"url",
".",
"host",
")",
"{",
"throw",
"new",
"ServerlessError",
"(",
"'The URL you passed is not a valid URL'",
")",
";",
"}",
"switch",
"(",
"url",
".",
"hostname",
")",
"{",
"case",
"'github.com'",
":",
"{",
"return",
"parseGitHubURL",
"(",
"url",
")",
";",
"}",
"case",
"'bitbucket.org'",
":",
"{",
"return",
"parseBitbucketURL",
"(",
"url",
")",
";",
"}",
"case",
"'gitlab.com'",
":",
"{",
"return",
"parseGitlabURL",
"(",
"url",
")",
";",
"}",
"default",
":",
"{",
"const",
"msg",
"=",
"'The URL you passed is not one of the valid providers: \"GitHub\", \"Bitbucket\", or \"GitLab\".'",
";",
"throw",
"new",
"ServerlessError",
"(",
"msg",
")",
";",
"}",
"}",
"}"
] | Parse URL and call the appropriate adaptor
@param {string} inputUrl
@throws {ServerlessError}
@returns {Object} | [
"Parse",
"URL",
"and",
"call",
"the",
"appropriate",
"adaptor"
] | 0626d5b5df06e4ed68969e324f1cb6b1b499c443 | https://github.com/serverless/serverless/blob/0626d5b5df06e4ed68969e324f1cb6b1b499c443/lib/utils/downloadTemplateFromRepo.js#L143-L171 |
583 | serverless/serverless | lib/utils/config/index.js | set | function set(key, value) {
let config = getGlobalConfig();
if (key && typeof key === 'string' && typeof value !== 'undefined') {
config = _.set(config, key, value);
} else if (_.isObject(key)) {
config = _.merge(config, key);
} else if (typeof value !== 'undefined') {
config = _.merge(config, value);
}
// update config meta
config.meta = config.meta || {};
config.meta.updated_at = Math.round(+new Date() / 1000);
// write to .serverlessrc file
writeFileAtomic.sync(serverlessrcPath, JSON.stringify(config, null, 2));
return config;
} | javascript | function set(key, value) {
let config = getGlobalConfig();
if (key && typeof key === 'string' && typeof value !== 'undefined') {
config = _.set(config, key, value);
} else if (_.isObject(key)) {
config = _.merge(config, key);
} else if (typeof value !== 'undefined') {
config = _.merge(config, value);
}
// update config meta
config.meta = config.meta || {};
config.meta.updated_at = Math.round(+new Date() / 1000);
// write to .serverlessrc file
writeFileAtomic.sync(serverlessrcPath, JSON.stringify(config, null, 2));
return config;
} | [
"function",
"set",
"(",
"key",
",",
"value",
")",
"{",
"let",
"config",
"=",
"getGlobalConfig",
"(",
")",
";",
"if",
"(",
"key",
"&&",
"typeof",
"key",
"===",
"'string'",
"&&",
"typeof",
"value",
"!==",
"'undefined'",
")",
"{",
"config",
"=",
"_",
".",
"set",
"(",
"config",
",",
"key",
",",
"value",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isObject",
"(",
"key",
")",
")",
"{",
"config",
"=",
"_",
".",
"merge",
"(",
"config",
",",
"key",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"value",
"!==",
"'undefined'",
")",
"{",
"config",
"=",
"_",
".",
"merge",
"(",
"config",
",",
"value",
")",
";",
"}",
"// update config meta",
"config",
".",
"meta",
"=",
"config",
".",
"meta",
"||",
"{",
"}",
";",
"config",
".",
"meta",
".",
"updated_at",
"=",
"Math",
".",
"round",
"(",
"+",
"new",
"Date",
"(",
")",
"/",
"1000",
")",
";",
"// write to .serverlessrc file",
"writeFileAtomic",
".",
"sync",
"(",
"serverlessrcPath",
",",
"JSON",
".",
"stringify",
"(",
"config",
",",
"null",
",",
"2",
")",
")",
";",
"return",
"config",
";",
"}"
] | set global .serverlessrc config value. | [
"set",
"global",
".",
"serverlessrc",
"config",
"value",
"."
] | 0626d5b5df06e4ed68969e324f1cb6b1b499c443 | https://github.com/serverless/serverless/blob/0626d5b5df06e4ed68969e324f1cb6b1b499c443/lib/utils/config/index.js#L66-L81 |
584 | serverless/serverless | lib/plugins/aws/utils/findReferences.js | findReferences | function findReferences(root, value) {
const visitedObjects = [];
const resourcePaths = [];
const stack = [{ propValue: root, path: '' }];
while (!_.isEmpty(stack)) {
const property = stack.pop();
_.forOwn(property.propValue, (propValue, key) => {
let propKey;
if (_.isArray(property.propValue)) {
propKey = `[${key}]`;
} else {
propKey = _.isEmpty(property.path) ? `${key}` : `.${key}`;
}
if (propValue === value) {
resourcePaths.push(`${property.path}${propKey}`);
} else if (_.isObject(propValue)) {
// Prevent circular references
if (_.includes(visitedObjects, propValue)) {
return;
}
visitedObjects.push(propValue);
stack.push({ propValue, path: `${property.path}${propKey}` });
}
});
}
return resourcePaths;
} | javascript | function findReferences(root, value) {
const visitedObjects = [];
const resourcePaths = [];
const stack = [{ propValue: root, path: '' }];
while (!_.isEmpty(stack)) {
const property = stack.pop();
_.forOwn(property.propValue, (propValue, key) => {
let propKey;
if (_.isArray(property.propValue)) {
propKey = `[${key}]`;
} else {
propKey = _.isEmpty(property.path) ? `${key}` : `.${key}`;
}
if (propValue === value) {
resourcePaths.push(`${property.path}${propKey}`);
} else if (_.isObject(propValue)) {
// Prevent circular references
if (_.includes(visitedObjects, propValue)) {
return;
}
visitedObjects.push(propValue);
stack.push({ propValue, path: `${property.path}${propKey}` });
}
});
}
return resourcePaths;
} | [
"function",
"findReferences",
"(",
"root",
",",
"value",
")",
"{",
"const",
"visitedObjects",
"=",
"[",
"]",
";",
"const",
"resourcePaths",
"=",
"[",
"]",
";",
"const",
"stack",
"=",
"[",
"{",
"propValue",
":",
"root",
",",
"path",
":",
"''",
"}",
"]",
";",
"while",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"stack",
")",
")",
"{",
"const",
"property",
"=",
"stack",
".",
"pop",
"(",
")",
";",
"_",
".",
"forOwn",
"(",
"property",
".",
"propValue",
",",
"(",
"propValue",
",",
"key",
")",
"=>",
"{",
"let",
"propKey",
";",
"if",
"(",
"_",
".",
"isArray",
"(",
"property",
".",
"propValue",
")",
")",
"{",
"propKey",
"=",
"`",
"${",
"key",
"}",
"`",
";",
"}",
"else",
"{",
"propKey",
"=",
"_",
".",
"isEmpty",
"(",
"property",
".",
"path",
")",
"?",
"`",
"${",
"key",
"}",
"`",
":",
"`",
"${",
"key",
"}",
"`",
";",
"}",
"if",
"(",
"propValue",
"===",
"value",
")",
"{",
"resourcePaths",
".",
"push",
"(",
"`",
"${",
"property",
".",
"path",
"}",
"${",
"propKey",
"}",
"`",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isObject",
"(",
"propValue",
")",
")",
"{",
"// Prevent circular references",
"if",
"(",
"_",
".",
"includes",
"(",
"visitedObjects",
",",
"propValue",
")",
")",
"{",
"return",
";",
"}",
"visitedObjects",
".",
"push",
"(",
"propValue",
")",
";",
"stack",
".",
"push",
"(",
"{",
"propValue",
",",
"path",
":",
"`",
"${",
"property",
".",
"path",
"}",
"${",
"propKey",
"}",
"`",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"return",
"resourcePaths",
";",
"}"
] | Find all objects with a given value within a given root object.
The search is implemented non-recursive to prevent stackoverflows and will
do a complete deep search including arrays.
@param root {Object} Root object for search
@param value {Object} Value to search
@returns {Array<String>} Paths to all self references found within the object | [
"Find",
"all",
"objects",
"with",
"a",
"given",
"value",
"within",
"a",
"given",
"root",
"object",
".",
"The",
"search",
"is",
"implemented",
"non",
"-",
"recursive",
"to",
"prevent",
"stackoverflows",
"and",
"will",
"do",
"a",
"complete",
"deep",
"search",
"including",
"arrays",
"."
] | 0626d5b5df06e4ed68969e324f1cb6b1b499c443 | https://github.com/serverless/serverless/blob/0626d5b5df06e4ed68969e324f1cb6b1b499c443/lib/plugins/aws/utils/findReferences.js#L13-L42 |
585 | expressjs/express | lib/router/index.js | param | function param(err) {
if (err) {
return done(err);
}
if (i >= keys.length ) {
return done();
}
paramIndex = 0;
key = keys[i++];
name = key.name;
paramVal = req.params[name];
paramCallbacks = params[name];
paramCalled = called[name];
if (paramVal === undefined || !paramCallbacks) {
return param();
}
// param previously called with same value or error occurred
if (paramCalled && (paramCalled.match === paramVal
|| (paramCalled.error && paramCalled.error !== 'route'))) {
// restore value
req.params[name] = paramCalled.value;
// next param
return param(paramCalled.error);
}
called[name] = paramCalled = {
error: null,
match: paramVal,
value: paramVal
};
paramCallback();
} | javascript | function param(err) {
if (err) {
return done(err);
}
if (i >= keys.length ) {
return done();
}
paramIndex = 0;
key = keys[i++];
name = key.name;
paramVal = req.params[name];
paramCallbacks = params[name];
paramCalled = called[name];
if (paramVal === undefined || !paramCallbacks) {
return param();
}
// param previously called with same value or error occurred
if (paramCalled && (paramCalled.match === paramVal
|| (paramCalled.error && paramCalled.error !== 'route'))) {
// restore value
req.params[name] = paramCalled.value;
// next param
return param(paramCalled.error);
}
called[name] = paramCalled = {
error: null,
match: paramVal,
value: paramVal
};
paramCallback();
} | [
"function",
"param",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"done",
"(",
"err",
")",
";",
"}",
"if",
"(",
"i",
">=",
"keys",
".",
"length",
")",
"{",
"return",
"done",
"(",
")",
";",
"}",
"paramIndex",
"=",
"0",
";",
"key",
"=",
"keys",
"[",
"i",
"++",
"]",
";",
"name",
"=",
"key",
".",
"name",
";",
"paramVal",
"=",
"req",
".",
"params",
"[",
"name",
"]",
";",
"paramCallbacks",
"=",
"params",
"[",
"name",
"]",
";",
"paramCalled",
"=",
"called",
"[",
"name",
"]",
";",
"if",
"(",
"paramVal",
"===",
"undefined",
"||",
"!",
"paramCallbacks",
")",
"{",
"return",
"param",
"(",
")",
";",
"}",
"// param previously called with same value or error occurred",
"if",
"(",
"paramCalled",
"&&",
"(",
"paramCalled",
".",
"match",
"===",
"paramVal",
"||",
"(",
"paramCalled",
".",
"error",
"&&",
"paramCalled",
".",
"error",
"!==",
"'route'",
")",
")",
")",
"{",
"// restore value",
"req",
".",
"params",
"[",
"name",
"]",
"=",
"paramCalled",
".",
"value",
";",
"// next param",
"return",
"param",
"(",
"paramCalled",
".",
"error",
")",
";",
"}",
"called",
"[",
"name",
"]",
"=",
"paramCalled",
"=",
"{",
"error",
":",
"null",
",",
"match",
":",
"paramVal",
",",
"value",
":",
"paramVal",
"}",
";",
"paramCallback",
"(",
")",
";",
"}"
] | process params in order param callbacks can be async | [
"process",
"params",
"in",
"order",
"param",
"callbacks",
"can",
"be",
"async"
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/lib/router/index.js#L348-L385 |
586 | expressjs/express | lib/router/index.js | appendMethods | function appendMethods(list, addition) {
for (var i = 0; i < addition.length; i++) {
var method = addition[i];
if (list.indexOf(method) === -1) {
list.push(method);
}
}
} | javascript | function appendMethods(list, addition) {
for (var i = 0; i < addition.length; i++) {
var method = addition[i];
if (list.indexOf(method) === -1) {
list.push(method);
}
}
} | [
"function",
"appendMethods",
"(",
"list",
",",
"addition",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"addition",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"method",
"=",
"addition",
"[",
"i",
"]",
";",
"if",
"(",
"list",
".",
"indexOf",
"(",
"method",
")",
"===",
"-",
"1",
")",
"{",
"list",
".",
"push",
"(",
"method",
")",
";",
"}",
"}",
"}"
] | append methods to a list of methods | [
"append",
"methods",
"to",
"a",
"list",
"of",
"methods"
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/lib/router/index.js#L516-L523 |
587 | expressjs/express | lib/router/index.js | getProtohost | function getProtohost(url) {
if (typeof url !== 'string' || url.length === 0 || url[0] === '/') {
return undefined
}
var searchIndex = url.indexOf('?')
var pathLength = searchIndex !== -1
? searchIndex
: url.length
var fqdnIndex = url.substr(0, pathLength).indexOf('://')
return fqdnIndex !== -1
? url.substr(0, url.indexOf('/', 3 + fqdnIndex))
: undefined
} | javascript | function getProtohost(url) {
if (typeof url !== 'string' || url.length === 0 || url[0] === '/') {
return undefined
}
var searchIndex = url.indexOf('?')
var pathLength = searchIndex !== -1
? searchIndex
: url.length
var fqdnIndex = url.substr(0, pathLength).indexOf('://')
return fqdnIndex !== -1
? url.substr(0, url.indexOf('/', 3 + fqdnIndex))
: undefined
} | [
"function",
"getProtohost",
"(",
"url",
")",
"{",
"if",
"(",
"typeof",
"url",
"!==",
"'string'",
"||",
"url",
".",
"length",
"===",
"0",
"||",
"url",
"[",
"0",
"]",
"===",
"'/'",
")",
"{",
"return",
"undefined",
"}",
"var",
"searchIndex",
"=",
"url",
".",
"indexOf",
"(",
"'?'",
")",
"var",
"pathLength",
"=",
"searchIndex",
"!==",
"-",
"1",
"?",
"searchIndex",
":",
"url",
".",
"length",
"var",
"fqdnIndex",
"=",
"url",
".",
"substr",
"(",
"0",
",",
"pathLength",
")",
".",
"indexOf",
"(",
"'://'",
")",
"return",
"fqdnIndex",
"!==",
"-",
"1",
"?",
"url",
".",
"substr",
"(",
"0",
",",
"url",
".",
"indexOf",
"(",
"'/'",
",",
"3",
"+",
"fqdnIndex",
")",
")",
":",
"undefined",
"}"
] | Get get protocol + host for a URL | [
"Get",
"get",
"protocol",
"+",
"host",
"for",
"a",
"URL"
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/lib/router/index.js#L535-L549 |
588 | expressjs/express | lib/router/index.js | gettype | function gettype(obj) {
var type = typeof obj;
if (type !== 'object') {
return type;
}
// inspect [[Class]] for objects
return toString.call(obj)
.replace(objectRegExp, '$1');
} | javascript | function gettype(obj) {
var type = typeof obj;
if (type !== 'object') {
return type;
}
// inspect [[Class]] for objects
return toString.call(obj)
.replace(objectRegExp, '$1');
} | [
"function",
"gettype",
"(",
"obj",
")",
"{",
"var",
"type",
"=",
"typeof",
"obj",
";",
"if",
"(",
"type",
"!==",
"'object'",
")",
"{",
"return",
"type",
";",
"}",
"// inspect [[Class]] for objects",
"return",
"toString",
".",
"call",
"(",
"obj",
")",
".",
"replace",
"(",
"objectRegExp",
",",
"'$1'",
")",
";",
"}"
] | get type for error message | [
"get",
"type",
"for",
"error",
"message"
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/lib/router/index.js#L552-L562 |
589 | expressjs/express | lib/router/index.js | sendOptionsResponse | function sendOptionsResponse(res, options, next) {
try {
var body = options.join(',');
res.set('Allow', body);
res.send(body);
} catch (err) {
next(err);
}
} | javascript | function sendOptionsResponse(res, options, next) {
try {
var body = options.join(',');
res.set('Allow', body);
res.send(body);
} catch (err) {
next(err);
}
} | [
"function",
"sendOptionsResponse",
"(",
"res",
",",
"options",
",",
"next",
")",
"{",
"try",
"{",
"var",
"body",
"=",
"options",
".",
"join",
"(",
"','",
")",
";",
"res",
".",
"set",
"(",
"'Allow'",
",",
"body",
")",
";",
"res",
".",
"send",
"(",
"body",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"next",
"(",
"err",
")",
";",
"}",
"}"
] | send an OPTIONS response | [
"send",
"an",
"OPTIONS",
"response"
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/lib/router/index.js#L640-L648 |
590 | expressjs/express | lib/router/index.js | wrap | function wrap(old, fn) {
return function proxy() {
var args = new Array(arguments.length + 1);
args[0] = old;
for (var i = 0, len = arguments.length; i < len; i++) {
args[i + 1] = arguments[i];
}
fn.apply(this, args);
};
} | javascript | function wrap(old, fn) {
return function proxy() {
var args = new Array(arguments.length + 1);
args[0] = old;
for (var i = 0, len = arguments.length; i < len; i++) {
args[i + 1] = arguments[i];
}
fn.apply(this, args);
};
} | [
"function",
"wrap",
"(",
"old",
",",
"fn",
")",
"{",
"return",
"function",
"proxy",
"(",
")",
"{",
"var",
"args",
"=",
"new",
"Array",
"(",
"arguments",
".",
"length",
"+",
"1",
")",
";",
"args",
"[",
"0",
"]",
"=",
"old",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"arguments",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"args",
"[",
"i",
"+",
"1",
"]",
"=",
"arguments",
"[",
"i",
"]",
";",
"}",
"fn",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
";",
"}"
] | wrap a function | [
"wrap",
"a",
"function"
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/lib/router/index.js#L651-L662 |
591 | expressjs/express | lib/application.js | tryRender | function tryRender(view, options, callback) {
try {
view.render(options, callback);
} catch (err) {
callback(err);
}
} | javascript | function tryRender(view, options, callback) {
try {
view.render(options, callback);
} catch (err) {
callback(err);
}
} | [
"function",
"tryRender",
"(",
"view",
",",
"options",
",",
"callback",
")",
"{",
"try",
"{",
"view",
".",
"render",
"(",
"options",
",",
"callback",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"}"
] | Try rendering a view.
@private | [
"Try",
"rendering",
"a",
"view",
"."
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/lib/application.js#L638-L644 |
592 | expressjs/express | examples/auth/index.js | authenticate | function authenticate(name, pass, fn) {
if (!module.parent) console.log('authenticating %s:%s', name, pass);
var user = users[name];
// query the db for the given username
if (!user) return fn(new Error('cannot find user'));
// apply the same algorithm to the POSTed password, applying
// the hash against the pass / salt, if there is a match we
// found the user
hash({ password: pass, salt: user.salt }, function (err, pass, salt, hash) {
if (err) return fn(err);
if (hash === user.hash) return fn(null, user)
fn(new Error('invalid password'));
});
} | javascript | function authenticate(name, pass, fn) {
if (!module.parent) console.log('authenticating %s:%s', name, pass);
var user = users[name];
// query the db for the given username
if (!user) return fn(new Error('cannot find user'));
// apply the same algorithm to the POSTed password, applying
// the hash against the pass / salt, if there is a match we
// found the user
hash({ password: pass, salt: user.salt }, function (err, pass, salt, hash) {
if (err) return fn(err);
if (hash === user.hash) return fn(null, user)
fn(new Error('invalid password'));
});
} | [
"function",
"authenticate",
"(",
"name",
",",
"pass",
",",
"fn",
")",
"{",
"if",
"(",
"!",
"module",
".",
"parent",
")",
"console",
".",
"log",
"(",
"'authenticating %s:%s'",
",",
"name",
",",
"pass",
")",
";",
"var",
"user",
"=",
"users",
"[",
"name",
"]",
";",
"// query the db for the given username",
"if",
"(",
"!",
"user",
")",
"return",
"fn",
"(",
"new",
"Error",
"(",
"'cannot find user'",
")",
")",
";",
"// apply the same algorithm to the POSTed password, applying",
"// the hash against the pass / salt, if there is a match we",
"// found the user",
"hash",
"(",
"{",
"password",
":",
"pass",
",",
"salt",
":",
"user",
".",
"salt",
"}",
",",
"function",
"(",
"err",
",",
"pass",
",",
"salt",
",",
"hash",
")",
"{",
"if",
"(",
"err",
")",
"return",
"fn",
"(",
"err",
")",
";",
"if",
"(",
"hash",
"===",
"user",
".",
"hash",
")",
"return",
"fn",
"(",
"null",
",",
"user",
")",
"fn",
"(",
"new",
"Error",
"(",
"'invalid password'",
")",
")",
";",
"}",
")",
";",
"}"
] | Authenticate using our plain-object database of doom! | [
"Authenticate",
"using",
"our",
"plain",
"-",
"object",
"database",
"of",
"doom!"
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/examples/auth/index.js#L58-L71 |
593 | expressjs/express | lib/response.js | sendfile | function sendfile(res, file, options, callback) {
var done = false;
var streaming;
// request aborted
function onaborted() {
if (done) return;
done = true;
var err = new Error('Request aborted');
err.code = 'ECONNABORTED';
callback(err);
}
// directory
function ondirectory() {
if (done) return;
done = true;
var err = new Error('EISDIR, read');
err.code = 'EISDIR';
callback(err);
}
// errors
function onerror(err) {
if (done) return;
done = true;
callback(err);
}
// ended
function onend() {
if (done) return;
done = true;
callback();
}
// file
function onfile() {
streaming = false;
}
// finished
function onfinish(err) {
if (err && err.code === 'ECONNRESET') return onaborted();
if (err) return onerror(err);
if (done) return;
setImmediate(function () {
if (streaming !== false && !done) {
onaborted();
return;
}
if (done) return;
done = true;
callback();
});
}
// streaming
function onstream() {
streaming = true;
}
file.on('directory', ondirectory);
file.on('end', onend);
file.on('error', onerror);
file.on('file', onfile);
file.on('stream', onstream);
onFinished(res, onfinish);
if (options.headers) {
// set headers on successful transfer
file.on('headers', function headers(res) {
var obj = options.headers;
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
res.setHeader(k, obj[k]);
}
});
}
// pipe
file.pipe(res);
} | javascript | function sendfile(res, file, options, callback) {
var done = false;
var streaming;
// request aborted
function onaborted() {
if (done) return;
done = true;
var err = new Error('Request aborted');
err.code = 'ECONNABORTED';
callback(err);
}
// directory
function ondirectory() {
if (done) return;
done = true;
var err = new Error('EISDIR, read');
err.code = 'EISDIR';
callback(err);
}
// errors
function onerror(err) {
if (done) return;
done = true;
callback(err);
}
// ended
function onend() {
if (done) return;
done = true;
callback();
}
// file
function onfile() {
streaming = false;
}
// finished
function onfinish(err) {
if (err && err.code === 'ECONNRESET') return onaborted();
if (err) return onerror(err);
if (done) return;
setImmediate(function () {
if (streaming !== false && !done) {
onaborted();
return;
}
if (done) return;
done = true;
callback();
});
}
// streaming
function onstream() {
streaming = true;
}
file.on('directory', ondirectory);
file.on('end', onend);
file.on('error', onerror);
file.on('file', onfile);
file.on('stream', onstream);
onFinished(res, onfinish);
if (options.headers) {
// set headers on successful transfer
file.on('headers', function headers(res) {
var obj = options.headers;
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
res.setHeader(k, obj[k]);
}
});
}
// pipe
file.pipe(res);
} | [
"function",
"sendfile",
"(",
"res",
",",
"file",
",",
"options",
",",
"callback",
")",
"{",
"var",
"done",
"=",
"false",
";",
"var",
"streaming",
";",
"// request aborted",
"function",
"onaborted",
"(",
")",
"{",
"if",
"(",
"done",
")",
"return",
";",
"done",
"=",
"true",
";",
"var",
"err",
"=",
"new",
"Error",
"(",
"'Request aborted'",
")",
";",
"err",
".",
"code",
"=",
"'ECONNABORTED'",
";",
"callback",
"(",
"err",
")",
";",
"}",
"// directory",
"function",
"ondirectory",
"(",
")",
"{",
"if",
"(",
"done",
")",
"return",
";",
"done",
"=",
"true",
";",
"var",
"err",
"=",
"new",
"Error",
"(",
"'EISDIR, read'",
")",
";",
"err",
".",
"code",
"=",
"'EISDIR'",
";",
"callback",
"(",
"err",
")",
";",
"}",
"// errors",
"function",
"onerror",
"(",
"err",
")",
"{",
"if",
"(",
"done",
")",
"return",
";",
"done",
"=",
"true",
";",
"callback",
"(",
"err",
")",
";",
"}",
"// ended",
"function",
"onend",
"(",
")",
"{",
"if",
"(",
"done",
")",
"return",
";",
"done",
"=",
"true",
";",
"callback",
"(",
")",
";",
"}",
"// file",
"function",
"onfile",
"(",
")",
"{",
"streaming",
"=",
"false",
";",
"}",
"// finished",
"function",
"onfinish",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"&&",
"err",
".",
"code",
"===",
"'ECONNRESET'",
")",
"return",
"onaborted",
"(",
")",
";",
"if",
"(",
"err",
")",
"return",
"onerror",
"(",
"err",
")",
";",
"if",
"(",
"done",
")",
"return",
";",
"setImmediate",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"streaming",
"!==",
"false",
"&&",
"!",
"done",
")",
"{",
"onaborted",
"(",
")",
";",
"return",
";",
"}",
"if",
"(",
"done",
")",
"return",
";",
"done",
"=",
"true",
";",
"callback",
"(",
")",
";",
"}",
")",
";",
"}",
"// streaming",
"function",
"onstream",
"(",
")",
"{",
"streaming",
"=",
"true",
";",
"}",
"file",
".",
"on",
"(",
"'directory'",
",",
"ondirectory",
")",
";",
"file",
".",
"on",
"(",
"'end'",
",",
"onend",
")",
";",
"file",
".",
"on",
"(",
"'error'",
",",
"onerror",
")",
";",
"file",
".",
"on",
"(",
"'file'",
",",
"onfile",
")",
";",
"file",
".",
"on",
"(",
"'stream'",
",",
"onstream",
")",
";",
"onFinished",
"(",
"res",
",",
"onfinish",
")",
";",
"if",
"(",
"options",
".",
"headers",
")",
"{",
"// set headers on successful transfer",
"file",
".",
"on",
"(",
"'headers'",
",",
"function",
"headers",
"(",
"res",
")",
"{",
"var",
"obj",
"=",
"options",
".",
"headers",
";",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"k",
"=",
"keys",
"[",
"i",
"]",
";",
"res",
".",
"setHeader",
"(",
"k",
",",
"obj",
"[",
"k",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
"// pipe",
"file",
".",
"pipe",
"(",
"res",
")",
";",
"}"
] | pipe the send file stream | [
"pipe",
"the",
"send",
"file",
"stream"
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/lib/response.js#L1012-L1100 |
594 | expressjs/express | lib/response.js | stringify | function stringify (value, replacer, spaces, escape) {
// v8 checks arguments.length for optimizing simple call
// https://bugs.chromium.org/p/v8/issues/detail?id=4730
var json = replacer || spaces
? JSON.stringify(value, replacer, spaces)
: JSON.stringify(value);
if (escape) {
json = json.replace(/[<>&]/g, function (c) {
switch (c.charCodeAt(0)) {
case 0x3c:
return '\\u003c'
case 0x3e:
return '\\u003e'
case 0x26:
return '\\u0026'
default:
return c
}
})
}
return json
} | javascript | function stringify (value, replacer, spaces, escape) {
// v8 checks arguments.length for optimizing simple call
// https://bugs.chromium.org/p/v8/issues/detail?id=4730
var json = replacer || spaces
? JSON.stringify(value, replacer, spaces)
: JSON.stringify(value);
if (escape) {
json = json.replace(/[<>&]/g, function (c) {
switch (c.charCodeAt(0)) {
case 0x3c:
return '\\u003c'
case 0x3e:
return '\\u003e'
case 0x26:
return '\\u0026'
default:
return c
}
})
}
return json
} | [
"function",
"stringify",
"(",
"value",
",",
"replacer",
",",
"spaces",
",",
"escape",
")",
"{",
"// v8 checks arguments.length for optimizing simple call",
"// https://bugs.chromium.org/p/v8/issues/detail?id=4730",
"var",
"json",
"=",
"replacer",
"||",
"spaces",
"?",
"JSON",
".",
"stringify",
"(",
"value",
",",
"replacer",
",",
"spaces",
")",
":",
"JSON",
".",
"stringify",
"(",
"value",
")",
";",
"if",
"(",
"escape",
")",
"{",
"json",
"=",
"json",
".",
"replace",
"(",
"/",
"[<>&]",
"/",
"g",
",",
"function",
"(",
"c",
")",
"{",
"switch",
"(",
"c",
".",
"charCodeAt",
"(",
"0",
")",
")",
"{",
"case",
"0x3c",
":",
"return",
"'\\\\u003c'",
"case",
"0x3e",
":",
"return",
"'\\\\u003e'",
"case",
"0x26",
":",
"return",
"'\\\\u0026'",
"default",
":",
"return",
"c",
"}",
"}",
")",
"}",
"return",
"json",
"}"
] | Stringify JSON, like JSON.stringify, but v8 optimized, with the
ability to escape characters that can trigger HTML sniffing.
@param {*} value
@param {function} replaces
@param {number} spaces
@param {boolean} escape
@returns {string}
@private | [
"Stringify",
"JSON",
"like",
"JSON",
".",
"stringify",
"but",
"v8",
"optimized",
"with",
"the",
"ability",
"to",
"escape",
"characters",
"that",
"can",
"trigger",
"HTML",
"sniffing",
"."
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/lib/response.js#L1114-L1137 |
595 | expressjs/express | examples/params/index.js | createError | function createError(status, message) {
var err = new Error(message);
err.status = status;
return err;
} | javascript | function createError(status, message) {
var err = new Error(message);
err.status = status;
return err;
} | [
"function",
"createError",
"(",
"status",
",",
"message",
")",
"{",
"var",
"err",
"=",
"new",
"Error",
"(",
"message",
")",
";",
"err",
".",
"status",
"=",
"status",
";",
"return",
"err",
";",
"}"
] | Create HTTP error | [
"Create",
"HTTP",
"error"
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/examples/params/index.js#L20-L24 |
596 | expressjs/express | lib/view.js | View | function View(name, options) {
var opts = options || {};
this.defaultEngine = opts.defaultEngine;
this.ext = extname(name);
this.name = name;
this.root = opts.root;
if (!this.ext && !this.defaultEngine) {
throw new Error('No default engine was specified and no extension was provided.');
}
var fileName = name;
if (!this.ext) {
// get extension from default engine name
this.ext = this.defaultEngine[0] !== '.'
? '.' + this.defaultEngine
: this.defaultEngine;
fileName += this.ext;
}
if (!opts.engines[this.ext]) {
// load engine
var mod = this.ext.substr(1)
debug('require "%s"', mod)
// default engine export
var fn = require(mod).__express
if (typeof fn !== 'function') {
throw new Error('Module "' + mod + '" does not provide a view engine.')
}
opts.engines[this.ext] = fn
}
// store loaded engine
this.engine = opts.engines[this.ext];
// lookup path
this.path = this.lookup(fileName);
} | javascript | function View(name, options) {
var opts = options || {};
this.defaultEngine = opts.defaultEngine;
this.ext = extname(name);
this.name = name;
this.root = opts.root;
if (!this.ext && !this.defaultEngine) {
throw new Error('No default engine was specified and no extension was provided.');
}
var fileName = name;
if (!this.ext) {
// get extension from default engine name
this.ext = this.defaultEngine[0] !== '.'
? '.' + this.defaultEngine
: this.defaultEngine;
fileName += this.ext;
}
if (!opts.engines[this.ext]) {
// load engine
var mod = this.ext.substr(1)
debug('require "%s"', mod)
// default engine export
var fn = require(mod).__express
if (typeof fn !== 'function') {
throw new Error('Module "' + mod + '" does not provide a view engine.')
}
opts.engines[this.ext] = fn
}
// store loaded engine
this.engine = opts.engines[this.ext];
// lookup path
this.path = this.lookup(fileName);
} | [
"function",
"View",
"(",
"name",
",",
"options",
")",
"{",
"var",
"opts",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"defaultEngine",
"=",
"opts",
".",
"defaultEngine",
";",
"this",
".",
"ext",
"=",
"extname",
"(",
"name",
")",
";",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"root",
"=",
"opts",
".",
"root",
";",
"if",
"(",
"!",
"this",
".",
"ext",
"&&",
"!",
"this",
".",
"defaultEngine",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No default engine was specified and no extension was provided.'",
")",
";",
"}",
"var",
"fileName",
"=",
"name",
";",
"if",
"(",
"!",
"this",
".",
"ext",
")",
"{",
"// get extension from default engine name",
"this",
".",
"ext",
"=",
"this",
".",
"defaultEngine",
"[",
"0",
"]",
"!==",
"'.'",
"?",
"'.'",
"+",
"this",
".",
"defaultEngine",
":",
"this",
".",
"defaultEngine",
";",
"fileName",
"+=",
"this",
".",
"ext",
";",
"}",
"if",
"(",
"!",
"opts",
".",
"engines",
"[",
"this",
".",
"ext",
"]",
")",
"{",
"// load engine",
"var",
"mod",
"=",
"this",
".",
"ext",
".",
"substr",
"(",
"1",
")",
"debug",
"(",
"'require \"%s\"'",
",",
"mod",
")",
"// default engine export",
"var",
"fn",
"=",
"require",
"(",
"mod",
")",
".",
"__express",
"if",
"(",
"typeof",
"fn",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Module \"'",
"+",
"mod",
"+",
"'\" does not provide a view engine.'",
")",
"}",
"opts",
".",
"engines",
"[",
"this",
".",
"ext",
"]",
"=",
"fn",
"}",
"// store loaded engine",
"this",
".",
"engine",
"=",
"opts",
".",
"engines",
"[",
"this",
".",
"ext",
"]",
";",
"// lookup path",
"this",
".",
"path",
"=",
"this",
".",
"lookup",
"(",
"fileName",
")",
";",
"}"
] | Initialize a new `View` with the given `name`.
Options:
- `defaultEngine` the default template engine name
- `engines` template engine require() cache
- `root` root path for view lookup
@param {string} name
@param {object} options
@public | [
"Initialize",
"a",
"new",
"View",
"with",
"the",
"given",
"name",
"."
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/lib/view.js#L52-L95 |
597 | expressjs/express | examples/view-constructor/github-view.js | GithubView | function GithubView(name, options){
this.name = name;
options = options || {};
this.engine = options.engines[extname(name)];
// "root" is the app.set('views') setting, however
// in your own implementation you could ignore this
this.path = '/' + options.root + '/master/' + name;
} | javascript | function GithubView(name, options){
this.name = name;
options = options || {};
this.engine = options.engines[extname(name)];
// "root" is the app.set('views') setting, however
// in your own implementation you could ignore this
this.path = '/' + options.root + '/master/' + name;
} | [
"function",
"GithubView",
"(",
"name",
",",
"options",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"engine",
"=",
"options",
".",
"engines",
"[",
"extname",
"(",
"name",
")",
"]",
";",
"// \"root\" is the app.set('views') setting, however",
"// in your own implementation you could ignore this",
"this",
".",
"path",
"=",
"'/'",
"+",
"options",
".",
"root",
"+",
"'/master/'",
"+",
"name",
";",
"}"
] | Custom view that fetches and renders
remove github templates. You could
render templates from a database etc. | [
"Custom",
"view",
"that",
"fetches",
"and",
"renders",
"remove",
"github",
"templates",
".",
"You",
"could",
"render",
"templates",
"from",
"a",
"database",
"etc",
"."
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/examples/view-constructor/github-view.js#L21-L28 |
598 | expressjs/express | examples/view-locals/index.js | count | function count(req, res, next) {
User.count(function(err, count){
if (err) return next(err);
req.count = count;
next();
})
} | javascript | function count(req, res, next) {
User.count(function(err, count){
if (err) return next(err);
req.count = count;
next();
})
} | [
"function",
"count",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"User",
".",
"count",
"(",
"function",
"(",
"err",
",",
"count",
")",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"err",
")",
";",
"req",
".",
"count",
"=",
"count",
";",
"next",
"(",
")",
";",
"}",
")",
"}"
] | this approach is cleaner, less nesting and we have the variables available on the request object | [
"this",
"approach",
"is",
"cleaner",
"less",
"nesting",
"and",
"we",
"have",
"the",
"variables",
"available",
"on",
"the",
"request",
"object"
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/examples/view-locals/index.js#L46-L52 |
599 | expressjs/express | examples/view-locals/index.js | count2 | function count2(req, res, next) {
User.count(function(err, count){
if (err) return next(err);
res.locals.count = count;
next();
})
} | javascript | function count2(req, res, next) {
User.count(function(err, count){
if (err) return next(err);
res.locals.count = count;
next();
})
} | [
"function",
"count2",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"User",
".",
"count",
"(",
"function",
"(",
"err",
",",
"count",
")",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"err",
")",
";",
"res",
".",
"locals",
".",
"count",
"=",
"count",
";",
"next",
"(",
")",
";",
"}",
")",
"}"
] | this approach is much like the last however we're explicitly exposing the locals within each middleware note that this may not always work well, for example here we filter the users in the middleware, which may not be ideal for our application. so in that sense the previous example is more flexible with `req.users`. | [
"this",
"approach",
"is",
"much",
"like",
"the",
"last",
"however",
"we",
"re",
"explicitly",
"exposing",
"the",
"locals",
"within",
"each",
"middleware",
"note",
"that",
"this",
"may",
"not",
"always",
"work",
"well",
"for",
"example",
"here",
"we",
"filter",
"the",
"users",
"in",
"the",
"middleware",
"which",
"may",
"not",
"be",
"ideal",
"for",
"our",
"application",
".",
"so",
"in",
"that",
"sense",
"the",
"previous",
"example",
"is",
"more",
"flexible",
"with",
"req",
".",
"users",
"."
] | dc538f6e810bd462c98ee7e6aae24c64d4b1da93 | https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/examples/view-locals/index.js#L84-L90 |
Subsets and Splits