repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
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",
";",
"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
|
train
|
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
|
train
|
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
|
train
|
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",
")",
"{",
"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
|
train
|
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
|
train
|
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",
")",
"{",
"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",
")",
";",
"file",
".",
"createUnique",
"(",
"Ci",
".",
"nsIFile",
".",
"NORMAL_FILE_TYPE",
",",
"parseInt",
"(",
"\"0666\"",
",",
"8",
")",
")",
";",
"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",
")",
"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",
";",
"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
|
train
|
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
|
train
|
|
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
|
train
|
|
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",
";",
"}",
"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",
")",
";",
"}",
"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
|
train
|
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
|
train
|
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",
";",
"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",
")",
"{",
"if",
"(",
"container",
"==",
"htmlElem",
")",
"{",
"return",
"true",
";",
"}",
"var",
"containerDisplay",
"=",
"(",
"bot",
".",
"dom",
".",
"getEffectiveStyle",
"(",
"container",
",",
"'display'",
")",
")",
";",
"if",
"(",
"goog",
".",
"string",
".",
"startsWith",
"(",
"containerDisplay",
",",
"'inline'",
")",
"||",
"(",
"containerDisplay",
"==",
"'contents'",
")",
")",
"{",
"return",
"false",
";",
"}",
"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
|
train
|
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",
")",
"{",
"var",
"overflowElem",
"=",
"e",
";",
"if",
"(",
"htmlOverflowStyle",
"==",
"'visible'",
")",
"{",
"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'",
")",
"}",
";",
"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
|
train
|
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
|
train
|
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
|
train
|
|
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",
")",
"{",
"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
|
train
|
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
|
train
|
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",
";",
"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
|
train
|
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",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"ids",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"node",
"=",
"this",
".",
"_getNode",
"(",
"ids",
"[",
"i",
"]",
")",
";",
"if",
"(",
"node",
")",
"{",
"var",
"idSet",
"=",
"ids",
"[",
"i",
"]",
";",
"switch",
"(",
"idSet",
".",
"target",
")",
"{",
"case",
"DOMWalker",
".",
"WINDOW_CURRENT",
":",
"this",
".",
"_processNode",
"(",
"node",
",",
"idSet",
")",
";",
"break",
";",
"case",
"DOMWalker",
".",
"WINDOW_MODAL",
":",
"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",
")",
";",
"var",
"controller",
"=",
"utils",
".",
"handleWindow",
"(",
"'title'",
",",
"idSet",
".",
"title",
",",
"false",
",",
"true",
")",
";",
"let",
"domWalker",
"=",
"new",
"DOMWalker",
"(",
"controller",
",",
"this",
".",
"_callbackFilter",
",",
"this",
".",
"_callbackNodeTest",
",",
"this",
".",
"_callbackResults",
")",
";",
"domWalker",
".",
"walk",
"(",
"idSet",
".",
"subContent",
",",
"controller",
".",
"window",
".",
"document",
".",
"documentElement",
",",
"idSet",
".",
"waitFunction",
")",
";",
"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
|
train
|
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",
")",
";",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
")",
"{",
"const",
"nodePositionMap",
"=",
"graph",
".",
"nodes",
".",
"reduce",
"(",
"(",
"res",
",",
"node",
")",
"=>",
"{",
"res",
"[",
"node",
".",
"id",
"]",
"=",
"node",
".",
"position",
";",
"return",
"res",
";",
"}",
",",
"{",
"}",
")",
";",
"const",
"nodePairs",
"=",
"graph",
".",
"edges",
".",
"reduce",
"(",
"(",
"res",
",",
"edge",
")",
"=>",
"{",
"const",
"nodes",
"=",
"[",
"edge",
".",
"sourceId",
",",
"edge",
".",
"targetId",
"]",
";",
"const",
"pairId",
"=",
"nodes",
".",
"sort",
"(",
")",
".",
"toString",
"(",
")",
";",
"if",
"(",
"!",
"res",
"[",
"pairId",
"]",
")",
"{",
"res",
"[",
"pairId",
"]",
"=",
"[",
"edge",
"]",
";",
"}",
"else",
"{",
"res",
"[",
"pairId",
"]",
".",
"push",
"(",
"edge",
")",
";",
"}",
"return",
"res",
";",
"}",
",",
"{",
"}",
")",
";",
"const",
"unitOffset",
"=",
"30",
";",
"const",
"layoutEdges",
"=",
"Object",
".",
"keys",
"(",
"nodePairs",
")",
".",
"reduce",
"(",
"(",
"res",
",",
"pairId",
")",
"=>",
"{",
"const",
"edges",
"=",
"nodePairs",
"[",
"pairId",
"]",
";",
"const",
"curved",
"=",
"edges",
".",
"length",
">",
"1",
";",
"const",
"nodeIds",
"=",
"pairId",
".",
"split",
"(",
"','",
")",
";",
"const",
"curveSourceId",
"=",
"nodeIds",
"[",
"0",
"]",
";",
"const",
"curveTargetId",
"=",
"nodeIds",
"[",
"1",
"]",
";",
"const",
"newEdges",
"=",
"edges",
".",
"map",
"(",
"(",
"e",
",",
"idx",
")",
"=>",
"{",
"const",
"direction",
"=",
"idx",
"%",
"2",
"?",
"1",
":",
"-",
"1",
";",
"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
|
train
|
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'",
")",
";",
"}",
"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
|
train
|
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",
";",
"const",
"originX",
"=",
"alignToCell",
"(",
"xMin",
"-",
"worldOrigin",
"[",
"0",
"]",
",",
"cellSize",
"[",
"0",
"]",
")",
"+",
"worldOrigin",
"[",
"0",
"]",
";",
"const",
"originY",
"=",
"alignToCell",
"(",
"yMin",
"-",
"worldOrigin",
"[",
"1",
"]",
",",
"cellSize",
"[",
"1",
"]",
")",
"+",
"worldOrigin",
"[",
"1",
"]",
";",
"const",
"gridTransformMatrix",
"=",
"new",
"Matrix4",
"(",
")",
".",
"translate",
"(",
"[",
"-",
"1",
"*",
"originX",
",",
"-",
"1",
"*",
"originY",
",",
"0",
"]",
")",
";",
"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
|
train
|
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",
")",
";",
"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
|
train
|
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
|
train
|
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
|
train
|
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",
")",
"{",
"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",
"}",
";",
"}",
"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
|
train
|
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'",
";",
"}",
"const",
"{",
"dataComparator",
"}",
"=",
"props",
";",
"if",
"(",
"dataComparator",
")",
"{",
"if",
"(",
"!",
"dataComparator",
"(",
"props",
".",
"data",
",",
"oldProps",
".",
"data",
")",
")",
"{",
"return",
"'Data comparator detected a change'",
";",
"}",
"}",
"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
|
train
|
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",
"(",
"'all'",
"in",
"props",
".",
"updateTriggers",
")",
"{",
"const",
"diffReason",
"=",
"diffUpdateTrigger",
"(",
"props",
",",
"oldProps",
",",
"'all'",
")",
";",
"if",
"(",
"diffReason",
")",
"{",
"return",
"{",
"all",
":",
"true",
"}",
";",
"}",
"}",
"const",
"triggerChanged",
"=",
"{",
"}",
";",
"let",
"reason",
"=",
"false",
";",
"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
|
train
|
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
|
train
|
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",
";",
"const",
"componentDefaultProps",
"=",
"getOwnProperty",
"(",
"componentClass",
",",
"'defaultProps'",
")",
"||",
"{",
"}",
";",
"const",
"componentPropDefs",
"=",
"parsePropTypes",
"(",
"componentDefaultProps",
")",
";",
"const",
"propTypes",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"parentPropDefs",
"&&",
"parentPropDefs",
".",
"propTypes",
",",
"componentPropDefs",
".",
"propTypes",
")",
";",
"const",
"defaultProps",
"=",
"createPropsPrototype",
"(",
"componentPropDefs",
".",
"defaultProps",
",",
"parentPropDefs",
"&&",
"parentPropDefs",
".",
"defaultProps",
",",
"propTypes",
",",
"componentClass",
")",
";",
"const",
"deprecatedProps",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"parentPropDefs",
"&&",
"parentPropDefs",
".",
"deprecatedProps",
",",
"componentPropDefs",
".",
"deprecatedProps",
")",
";",
"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
|
train
|
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",
")",
";",
"const",
"id",
"=",
"getComponentName",
"(",
"componentClass",
")",
";",
"delete",
"props",
".",
"id",
";",
"Object",
".",
"defineProperties",
"(",
"defaultProps",
",",
"{",
"id",
":",
"{",
"configurable",
":",
"false",
",",
"writable",
":",
"true",
",",
"value",
":",
"id",
"}",
"}",
")",
";",
"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
|
train
|
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",
"=",
"{",
"_asyncPropDefaultValues",
":",
"{",
"enumerable",
":",
"false",
",",
"value",
":",
"defaultValues",
"}",
",",
"_asyncPropOriginalValues",
":",
"{",
"enumerable",
":",
"false",
",",
"value",
":",
"{",
"}",
"}",
"}",
";",
"for",
"(",
"const",
"propName",
"in",
"propTypes",
")",
"{",
"const",
"propType",
"=",
"propTypes",
"[",
"propName",
"]",
";",
"const",
"{",
"name",
",",
"value",
"}",
"=",
"propType",
";",
"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
|
train
|
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'",
")",
"{",
"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
|
train
|
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
|
train
|
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",
")",
"{",
"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
|
train
|
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
|
train
|
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",
")",
"{",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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'",
":",
"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
|
train
|
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",
")",
"{",
"const",
"lastHex",
"=",
"token",
".",
"substr",
"(",
"token",
".",
"length",
"-",
"1",
")",
";",
"const",
"level",
"=",
"2",
"*",
"(",
"token",
".",
"length",
"-",
"1",
")",
"-",
"(",
"(",
"lastHex",
"&",
"1",
")",
"===",
"0",
")",
";",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
"(",
"/",
"\\/$",
"/",
",",
"''",
")",
")",
";",
"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
|
train
|
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",
")",
";",
"}",
"config",
".",
"meta",
"=",
"config",
".",
"meta",
"||",
"{",
"}",
";",
"config",
".",
"meta",
".",
"updated_at",
"=",
"Math",
".",
"round",
"(",
"+",
"new",
"Date",
"(",
")",
"/",
"1000",
")",
";",
"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
|
train
|
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",
")",
")",
"{",
"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
|
train
|
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",
"(",
")",
";",
"}",
"if",
"(",
"paramCalled",
"&&",
"(",
"paramCalled",
".",
"match",
"===",
"paramVal",
"||",
"(",
"paramCalled",
".",
"error",
"&&",
"paramCalled",
".",
"error",
"!==",
"'route'",
")",
")",
")",
"{",
"req",
".",
"params",
"[",
"name",
"]",
"=",
"paramCalled",
".",
"value",
";",
"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
|
train
|
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
|
train
|
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
|
train
|
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",
";",
"}",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
"]",
";",
"if",
"(",
"!",
"user",
")",
"return",
"fn",
"(",
"new",
"Error",
"(",
"'cannot find 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
|
train
|
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",
";",
"function",
"onaborted",
"(",
")",
"{",
"if",
"(",
"done",
")",
"return",
";",
"done",
"=",
"true",
";",
"var",
"err",
"=",
"new",
"Error",
"(",
"'Request aborted'",
")",
";",
"err",
".",
"code",
"=",
"'ECONNABORTED'",
";",
"callback",
"(",
"err",
")",
";",
"}",
"function",
"ondirectory",
"(",
")",
"{",
"if",
"(",
"done",
")",
"return",
";",
"done",
"=",
"true",
";",
"var",
"err",
"=",
"new",
"Error",
"(",
"'EISDIR, read'",
")",
";",
"err",
".",
"code",
"=",
"'EISDIR'",
";",
"callback",
"(",
"err",
")",
";",
"}",
"function",
"onerror",
"(",
"err",
")",
"{",
"if",
"(",
"done",
")",
"return",
";",
"done",
"=",
"true",
";",
"callback",
"(",
"err",
")",
";",
"}",
"function",
"onend",
"(",
")",
"{",
"if",
"(",
"done",
")",
"return",
";",
"done",
"=",
"true",
";",
"callback",
"(",
")",
";",
"}",
"function",
"onfile",
"(",
")",
"{",
"streaming",
"=",
"false",
";",
"}",
"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",
"(",
")",
";",
"}",
")",
";",
"}",
"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",
")",
"{",
"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",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
"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
|
train
|
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",
")",
"{",
"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'",
"}"
] |
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
|
train
|
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
|
train
|
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",
")",
"{",
"this",
".",
"ext",
"=",
"this",
".",
"defaultEngine",
"[",
"0",
"]",
"!==",
"'.'",
"?",
"'.'",
"+",
"this",
".",
"defaultEngine",
":",
"this",
".",
"defaultEngine",
";",
"fileName",
"+=",
"this",
".",
"ext",
";",
"}",
"if",
"(",
"!",
"opts",
".",
"engines",
"[",
"this",
".",
"ext",
"]",
")",
"{",
"var",
"mod",
"=",
"this",
".",
"ext",
".",
"substr",
"(",
"1",
")",
"debug",
"(",
"'require \"%s\"'",
",",
"mod",
")",
"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",
"}",
"this",
".",
"engine",
"=",
"opts",
".",
"engines",
"[",
"this",
".",
"ext",
"]",
";",
"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
|
train
|
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",
")",
"]",
";",
"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
|
train
|
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
|
train
|
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
|
train
|
expressjs/express
|
lib/utils.js
|
createETagGenerator
|
function createETagGenerator (options) {
return function generateETag (body, encoding) {
var buf = !Buffer.isBuffer(body)
? Buffer.from(body, encoding)
: body
return etag(buf, options)
}
}
|
javascript
|
function createETagGenerator (options) {
return function generateETag (body, encoding) {
var buf = !Buffer.isBuffer(body)
? Buffer.from(body, encoding)
: body
return etag(buf, options)
}
}
|
[
"function",
"createETagGenerator",
"(",
"options",
")",
"{",
"return",
"function",
"generateETag",
"(",
"body",
",",
"encoding",
")",
"{",
"var",
"buf",
"=",
"!",
"Buffer",
".",
"isBuffer",
"(",
"body",
")",
"?",
"Buffer",
".",
"from",
"(",
"body",
",",
"encoding",
")",
":",
"body",
"return",
"etag",
"(",
"buf",
",",
"options",
")",
"}",
"}"
] |
Create an ETag generator function, generating ETags with
the given options.
@param {object} options
@return {function}
@private
|
[
"Create",
"an",
"ETag",
"generator",
"function",
"generating",
"ETags",
"with",
"the",
"given",
"options",
"."
] |
dc538f6e810bd462c98ee7e6aae24c64d4b1da93
|
https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/lib/utils.js#L274-L282
|
train
|
ccxt/ccxt
|
examples/js/fetch-all-tickers-to-files.js
|
async function () {
// while the array of all exchanges is not empty
while (exchanges.length > 0) {
// pop one exchange from the array
const exchange = exchanges.pop ()
// check if it has the necessary method implemented
if (exchange.has['fetchTickers']) {
// try to do "the work" and handle errors if any
try {
// fetch the response for all tickers from the exchange
const tickers = await exchange.fetchTickers ()
// make a filename from exchange id
const filename = exchange.id + '.json'
// save the response to a file
fs.writeFileSync (filename, JSON.stringify ({ tickers }));
// print out a message on success
log.green (exchange.id, 'tickers saved to', filename)
} catch (e) {
// in case of error - print it out and ignore it further
log.red (e.constructor.name, e.message)
}
} else {
log.red (exchange.id, "has['fetchTickers'] = false");
}
}
}
|
javascript
|
async function () {
// while the array of all exchanges is not empty
while (exchanges.length > 0) {
// pop one exchange from the array
const exchange = exchanges.pop ()
// check if it has the necessary method implemented
if (exchange.has['fetchTickers']) {
// try to do "the work" and handle errors if any
try {
// fetch the response for all tickers from the exchange
const tickers = await exchange.fetchTickers ()
// make a filename from exchange id
const filename = exchange.id + '.json'
// save the response to a file
fs.writeFileSync (filename, JSON.stringify ({ tickers }));
// print out a message on success
log.green (exchange.id, 'tickers saved to', filename)
} catch (e) {
// in case of error - print it out and ignore it further
log.red (e.constructor.name, e.message)
}
} else {
log.red (exchange.id, "has['fetchTickers'] = false");
}
}
}
|
[
"async",
"function",
"(",
")",
"{",
"while",
"(",
"exchanges",
".",
"length",
">",
"0",
")",
"{",
"const",
"exchange",
"=",
"exchanges",
".",
"pop",
"(",
")",
"if",
"(",
"exchange",
".",
"has",
"[",
"'fetchTickers'",
"]",
")",
"{",
"try",
"{",
"const",
"tickers",
"=",
"await",
"exchange",
".",
"fetchTickers",
"(",
")",
"const",
"filename",
"=",
"exchange",
".",
"id",
"+",
"'.json'",
"fs",
".",
"writeFileSync",
"(",
"filename",
",",
"JSON",
".",
"stringify",
"(",
"{",
"tickers",
"}",
")",
")",
";",
"log",
".",
"green",
"(",
"exchange",
".",
"id",
",",
"'tickers saved to'",
",",
"filename",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"log",
".",
"red",
"(",
"e",
".",
"constructor",
".",
"name",
",",
"e",
".",
"message",
")",
"}",
"}",
"else",
"{",
"log",
".",
"red",
"(",
"exchange",
".",
"id",
",",
"\"has['fetchTickers'] = false\"",
")",
";",
"}",
"}",
"}"
] |
the worker function for each "async thread"
|
[
"the",
"worker",
"function",
"for",
"each",
"async",
"thread"
] |
8168069b9180a465532905e225586215e115a565
|
https://github.com/ccxt/ccxt/blob/8168069b9180a465532905e225586215e115a565/examples/js/fetch-all-tickers-to-files.js#L31-L68
|
train
|
|
quasarframework/quasar
|
cli/lib/generate.js
|
filterFiles
|
function filterFiles (filters) {
return (files, metalsmith, done) => {
filter(files, filters, metalsmith.metadata(), done)
}
}
|
javascript
|
function filterFiles (filters) {
return (files, metalsmith, done) => {
filter(files, filters, metalsmith.metadata(), done)
}
}
|
[
"function",
"filterFiles",
"(",
"filters",
")",
"{",
"return",
"(",
"files",
",",
"metalsmith",
",",
"done",
")",
"=>",
"{",
"filter",
"(",
"files",
",",
"filters",
",",
"metalsmith",
".",
"metadata",
"(",
")",
",",
"done",
")",
"}",
"}"
] |
Create a middleware for filtering files.
@param {Object} filters
@return {Function}
|
[
"Create",
"a",
"middleware",
"for",
"filtering",
"files",
"."
] |
5d2fb6c96bff6095236f8ca6fe07a037e32e06b3
|
https://github.com/quasarframework/quasar/blob/5d2fb6c96bff6095236f8ca6fe07a037e32e06b3/cli/lib/generate.js#L106-L110
|
train
|
quasarframework/quasar
|
cli/lib/generate.js
|
logMessage
|
function logMessage (message, data) {
if (!message) return
render(message, data, (err, res) => {
if (err) {
console.error('\n Error when rendering template complete message: ' + err.message.trim())
}
else {
console.log('\n' + res.split(/\r?\n/g).map(line => ' ' + line).join('\n'))
}
})
}
|
javascript
|
function logMessage (message, data) {
if (!message) return
render(message, data, (err, res) => {
if (err) {
console.error('\n Error when rendering template complete message: ' + err.message.trim())
}
else {
console.log('\n' + res.split(/\r?\n/g).map(line => ' ' + line).join('\n'))
}
})
}
|
[
"function",
"logMessage",
"(",
"message",
",",
"data",
")",
"{",
"if",
"(",
"!",
"message",
")",
"return",
"render",
"(",
"message",
",",
"data",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"'\\n Error when rendering template complete message: '",
"+",
"\\n",
")",
"}",
"else",
"err",
".",
"message",
".",
"trim",
"(",
")",
"}",
")",
"}"
] |
Display template complete message.
@param {String} message
@param {Object} data
|
[
"Display",
"template",
"complete",
"message",
"."
] |
5d2fb6c96bff6095236f8ca6fe07a037e32e06b3
|
https://github.com/quasarframework/quasar/blob/5d2fb6c96bff6095236f8ca6fe07a037e32e06b3/cli/lib/generate.js#L156-L166
|
train
|
vuejs/vue-cli
|
packages/@vue/cli/bin/vue.js
|
cleanArgs
|
function cleanArgs (cmd) {
const args = {}
cmd.options.forEach(o => {
const key = camelize(o.long.replace(/^--/, ''))
// if an option is not present and Command has a method with the same name
// it should not be copied
if (typeof cmd[key] !== 'function' && typeof cmd[key] !== 'undefined') {
args[key] = cmd[key]
}
})
return args
}
|
javascript
|
function cleanArgs (cmd) {
const args = {}
cmd.options.forEach(o => {
const key = camelize(o.long.replace(/^--/, ''))
// if an option is not present and Command has a method with the same name
// it should not be copied
if (typeof cmd[key] !== 'function' && typeof cmd[key] !== 'undefined') {
args[key] = cmd[key]
}
})
return args
}
|
[
"function",
"cleanArgs",
"(",
"cmd",
")",
"{",
"const",
"args",
"=",
"{",
"}",
"cmd",
".",
"options",
".",
"forEach",
"(",
"o",
"=>",
"{",
"const",
"key",
"=",
"camelize",
"(",
"o",
".",
"long",
".",
"replace",
"(",
"/",
"^--",
"/",
",",
"''",
")",
")",
"if",
"(",
"typeof",
"cmd",
"[",
"key",
"]",
"!==",
"'function'",
"&&",
"typeof",
"cmd",
"[",
"key",
"]",
"!==",
"'undefined'",
")",
"{",
"args",
"[",
"key",
"]",
"=",
"cmd",
"[",
"key",
"]",
"}",
"}",
")",
"return",
"args",
"}"
] |
commander passes the Command object itself as options, extract only actual options into a fresh object.
|
[
"commander",
"passes",
"the",
"Command",
"object",
"itself",
"as",
"options",
"extract",
"only",
"actual",
"options",
"into",
"a",
"fresh",
"object",
"."
] |
206803cbefefdfbc7d8ed12440b0b751688b77b2
|
https://github.com/vuejs/vue-cli/blob/206803cbefefdfbc7d8ed12440b0b751688b77b2/packages/@vue/cli/bin/vue.js#L239-L250
|
train
|
vuejs/vue-cli
|
packages/@vue/cli-service/lib/util/prepareProxy.js
|
mayProxy
|
function mayProxy (pathname) {
const maybePublicPath = path.resolve(appPublicFolder, pathname.slice(1))
return !fs.existsSync(maybePublicPath)
}
|
javascript
|
function mayProxy (pathname) {
const maybePublicPath = path.resolve(appPublicFolder, pathname.slice(1))
return !fs.existsSync(maybePublicPath)
}
|
[
"function",
"mayProxy",
"(",
"pathname",
")",
"{",
"const",
"maybePublicPath",
"=",
"path",
".",
"resolve",
"(",
"appPublicFolder",
",",
"pathname",
".",
"slice",
"(",
"1",
")",
")",
"return",
"!",
"fs",
".",
"existsSync",
"(",
"maybePublicPath",
")",
"}"
] |
Otherwise, if proxy is specified, we will let it handle any request except for files in the public folder.
|
[
"Otherwise",
"if",
"proxy",
"is",
"specified",
"we",
"will",
"let",
"it",
"handle",
"any",
"request",
"except",
"for",
"files",
"in",
"the",
"public",
"folder",
"."
] |
206803cbefefdfbc7d8ed12440b0b751688b77b2
|
https://github.com/vuejs/vue-cli/blob/206803cbefefdfbc7d8ed12440b0b751688b77b2/packages/@vue/cli-service/lib/util/prepareProxy.js#L48-L51
|
train
|
vuejs/vue-cli
|
packages/@vue/cli-ui/apollo-server/connectors/projects.js
|
autoOpenLastProject
|
async function autoOpenLastProject () {
const context = getContext()
const id = context.db.get('config.lastOpenProject').value()
if (id) {
try {
await open(id, context)
} catch (e) {
log(`Project can't be auto-opened`, id)
}
}
}
|
javascript
|
async function autoOpenLastProject () {
const context = getContext()
const id = context.db.get('config.lastOpenProject').value()
if (id) {
try {
await open(id, context)
} catch (e) {
log(`Project can't be auto-opened`, id)
}
}
}
|
[
"async",
"function",
"autoOpenLastProject",
"(",
")",
"{",
"const",
"context",
"=",
"getContext",
"(",
")",
"const",
"id",
"=",
"context",
".",
"db",
".",
"get",
"(",
"'config.lastOpenProject'",
")",
".",
"value",
"(",
")",
"if",
"(",
"id",
")",
"{",
"try",
"{",
"await",
"open",
"(",
"id",
",",
"context",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"log",
"(",
"`",
"`",
",",
"id",
")",
"}",
"}",
"}"
] |
Open last project
|
[
"Open",
"last",
"project"
] |
206803cbefefdfbc7d8ed12440b0b751688b77b2
|
https://github.com/vuejs/vue-cli/blob/206803cbefefdfbc7d8ed12440b0b751688b77b2/packages/@vue/cli-ui/apollo-server/connectors/projects.js#L457-L467
|
train
|
vuejs/vue-cli
|
packages/@vue/cli-plugin-eslint/ui/configDescriptor.js
|
getDefaultValue
|
function getDefaultValue (rule, data) {
const { category: ruleCategory } = rule.meta.docs
const currentCategory = getEslintConfigName(data.eslint)
if (!currentCategory || ruleCategory === undefined) return RULE_SETTING_OFF
return CATEGORIES.indexOf(ruleCategory) <= CATEGORIES.indexOf(currentCategory.split('/')[1])
? RULE_SETTING_ERROR
: RULE_SETTING_OFF
}
|
javascript
|
function getDefaultValue (rule, data) {
const { category: ruleCategory } = rule.meta.docs
const currentCategory = getEslintConfigName(data.eslint)
if (!currentCategory || ruleCategory === undefined) return RULE_SETTING_OFF
return CATEGORIES.indexOf(ruleCategory) <= CATEGORIES.indexOf(currentCategory.split('/')[1])
? RULE_SETTING_ERROR
: RULE_SETTING_OFF
}
|
[
"function",
"getDefaultValue",
"(",
"rule",
",",
"data",
")",
"{",
"const",
"{",
"category",
":",
"ruleCategory",
"}",
"=",
"rule",
".",
"meta",
".",
"docs",
"const",
"currentCategory",
"=",
"getEslintConfigName",
"(",
"data",
".",
"eslint",
")",
"if",
"(",
"!",
"currentCategory",
"||",
"ruleCategory",
"===",
"undefined",
")",
"return",
"RULE_SETTING_OFF",
"return",
"CATEGORIES",
".",
"indexOf",
"(",
"ruleCategory",
")",
"<=",
"CATEGORIES",
".",
"indexOf",
"(",
"currentCategory",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"]",
")",
"?",
"RULE_SETTING_ERROR",
":",
"RULE_SETTING_OFF",
"}"
] |
Sets default value regarding selected global config
|
[
"Sets",
"default",
"value",
"regarding",
"selected",
"global",
"config"
] |
206803cbefefdfbc7d8ed12440b0b751688b77b2
|
https://github.com/vuejs/vue-cli/blob/206803cbefefdfbc7d8ed12440b0b751688b77b2/packages/@vue/cli-plugin-eslint/ui/configDescriptor.js#L46-L55
|
train
|
vuejs/vue-cli
|
packages/@vue/babel-preset-app/polyfillsPlugin.js
|
getModulePath
|
function getModulePath (mod, useAbsolutePath) {
const modPath =
mod === 'regenerator-runtime'
? 'regenerator-runtime/runtime'
: `core-js/modules/${mod}`
return useAbsolutePath ? require.resolve(modPath) : modPath
}
|
javascript
|
function getModulePath (mod, useAbsolutePath) {
const modPath =
mod === 'regenerator-runtime'
? 'regenerator-runtime/runtime'
: `core-js/modules/${mod}`
return useAbsolutePath ? require.resolve(modPath) : modPath
}
|
[
"function",
"getModulePath",
"(",
"mod",
",",
"useAbsolutePath",
")",
"{",
"const",
"modPath",
"=",
"mod",
"===",
"'regenerator-runtime'",
"?",
"'regenerator-runtime/runtime'",
":",
"`",
"${",
"mod",
"}",
"`",
"return",
"useAbsolutePath",
"?",
"require",
".",
"resolve",
"(",
"modPath",
")",
":",
"modPath",
"}"
] |
slightly modifiled from @babel/preset-env/src/utils use an absolute path for core-js modules, to fix conflicts of different core-js versions
|
[
"slightly",
"modifiled",
"from"
] |
206803cbefefdfbc7d8ed12440b0b751688b77b2
|
https://github.com/vuejs/vue-cli/blob/206803cbefefdfbc7d8ed12440b0b751688b77b2/packages/@vue/babel-preset-app/polyfillsPlugin.js#L5-L11
|
train
|
vuejs/vue-cli
|
scripts/buildEditorConfig.js
|
convertRules
|
function convertRules (config) {
const result = {}
const eslintRules = new CLIEngine({
useEslintrc: false,
baseConfig: {
extends: [require.resolve(`@vue/eslint-config-${config}`)]
}
}).getConfigForFile().rules
const getRuleOptions = (ruleName, defaultOptions = []) => {
const ruleConfig = eslintRules[ruleName]
if (!ruleConfig || ruleConfig === 0 || ruleConfig === 'off') {
return
}
if (Array.isArray(ruleConfig) && (ruleConfig[0] === 0 || ruleConfig[0] === 'off')) {
return
}
if (Array.isArray(ruleConfig) && ruleConfig.length > 1) {
return ruleConfig.slice(1)
}
return defaultOptions
}
// https://eslint.org/docs/rules/indent
const indent = getRuleOptions('indent', [4])
if (indent) {
result.indent_style = indent[0] === 'tab' ? 'tab' : 'space'
if (typeof indent[0] === 'number') {
result.indent_size = indent[0]
}
}
// https://eslint.org/docs/rules/linebreak-style
const linebreakStyle = getRuleOptions('linebreak-style', ['unix'])
if (linebreakStyle) {
result.end_of_line = linebreakStyle[0] === 'unix' ? 'lf' : 'crlf'
}
// https://eslint.org/docs/rules/no-trailing-spaces
const noTrailingSpaces = getRuleOptions('no-trailing-spaces', [{ skipBlankLines: false, ignoreComments: false }])
if (noTrailingSpaces) {
if (!noTrailingSpaces[0].skipBlankLines && !noTrailingSpaces[0].ignoreComments) {
result.trim_trailing_whitespace = true
}
}
// https://eslint.org/docs/rules/eol-last
const eolLast = getRuleOptions('eol-last', ['always'])
if (eolLast) {
result.insert_final_newline = eolLast[0] !== 'never'
}
// https://eslint.org/docs/rules/max-len
const maxLen = getRuleOptions('max-len', [{ code: 80 }])
if (maxLen) {
// To simplify the implementation logic, we only read from the `code` option.
// `max-len` has an undocumented array-style configuration,
// where max code length specified directly as integers
// (used by `eslint-config-airbnb`).
if (typeof maxLen[0] === 'number') {
result.max_line_length = maxLen[0]
} else {
result.max_line_length = maxLen[0].code
}
}
return result
}
|
javascript
|
function convertRules (config) {
const result = {}
const eslintRules = new CLIEngine({
useEslintrc: false,
baseConfig: {
extends: [require.resolve(`@vue/eslint-config-${config}`)]
}
}).getConfigForFile().rules
const getRuleOptions = (ruleName, defaultOptions = []) => {
const ruleConfig = eslintRules[ruleName]
if (!ruleConfig || ruleConfig === 0 || ruleConfig === 'off') {
return
}
if (Array.isArray(ruleConfig) && (ruleConfig[0] === 0 || ruleConfig[0] === 'off')) {
return
}
if (Array.isArray(ruleConfig) && ruleConfig.length > 1) {
return ruleConfig.slice(1)
}
return defaultOptions
}
// https://eslint.org/docs/rules/indent
const indent = getRuleOptions('indent', [4])
if (indent) {
result.indent_style = indent[0] === 'tab' ? 'tab' : 'space'
if (typeof indent[0] === 'number') {
result.indent_size = indent[0]
}
}
// https://eslint.org/docs/rules/linebreak-style
const linebreakStyle = getRuleOptions('linebreak-style', ['unix'])
if (linebreakStyle) {
result.end_of_line = linebreakStyle[0] === 'unix' ? 'lf' : 'crlf'
}
// https://eslint.org/docs/rules/no-trailing-spaces
const noTrailingSpaces = getRuleOptions('no-trailing-spaces', [{ skipBlankLines: false, ignoreComments: false }])
if (noTrailingSpaces) {
if (!noTrailingSpaces[0].skipBlankLines && !noTrailingSpaces[0].ignoreComments) {
result.trim_trailing_whitespace = true
}
}
// https://eslint.org/docs/rules/eol-last
const eolLast = getRuleOptions('eol-last', ['always'])
if (eolLast) {
result.insert_final_newline = eolLast[0] !== 'never'
}
// https://eslint.org/docs/rules/max-len
const maxLen = getRuleOptions('max-len', [{ code: 80 }])
if (maxLen) {
// To simplify the implementation logic, we only read from the `code` option.
// `max-len` has an undocumented array-style configuration,
// where max code length specified directly as integers
// (used by `eslint-config-airbnb`).
if (typeof maxLen[0] === 'number') {
result.max_line_length = maxLen[0]
} else {
result.max_line_length = maxLen[0].code
}
}
return result
}
|
[
"function",
"convertRules",
"(",
"config",
")",
"{",
"const",
"result",
"=",
"{",
"}",
"const",
"eslintRules",
"=",
"new",
"CLIEngine",
"(",
"{",
"useEslintrc",
":",
"false",
",",
"baseConfig",
":",
"{",
"extends",
":",
"[",
"require",
".",
"resolve",
"(",
"`",
"${",
"config",
"}",
"`",
")",
"]",
"}",
"}",
")",
".",
"getConfigForFile",
"(",
")",
".",
"rules",
"const",
"getRuleOptions",
"=",
"(",
"ruleName",
",",
"defaultOptions",
"=",
"[",
"]",
")",
"=>",
"{",
"const",
"ruleConfig",
"=",
"eslintRules",
"[",
"ruleName",
"]",
"if",
"(",
"!",
"ruleConfig",
"||",
"ruleConfig",
"===",
"0",
"||",
"ruleConfig",
"===",
"'off'",
")",
"{",
"return",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"ruleConfig",
")",
"&&",
"(",
"ruleConfig",
"[",
"0",
"]",
"===",
"0",
"||",
"ruleConfig",
"[",
"0",
"]",
"===",
"'off'",
")",
")",
"{",
"return",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"ruleConfig",
")",
"&&",
"ruleConfig",
".",
"length",
">",
"1",
")",
"{",
"return",
"ruleConfig",
".",
"slice",
"(",
"1",
")",
"}",
"return",
"defaultOptions",
"}",
"const",
"indent",
"=",
"getRuleOptions",
"(",
"'indent'",
",",
"[",
"4",
"]",
")",
"if",
"(",
"indent",
")",
"{",
"result",
".",
"indent_style",
"=",
"indent",
"[",
"0",
"]",
"===",
"'tab'",
"?",
"'tab'",
":",
"'space'",
"if",
"(",
"typeof",
"indent",
"[",
"0",
"]",
"===",
"'number'",
")",
"{",
"result",
".",
"indent_size",
"=",
"indent",
"[",
"0",
"]",
"}",
"}",
"const",
"linebreakStyle",
"=",
"getRuleOptions",
"(",
"'linebreak-style'",
",",
"[",
"'unix'",
"]",
")",
"if",
"(",
"linebreakStyle",
")",
"{",
"result",
".",
"end_of_line",
"=",
"linebreakStyle",
"[",
"0",
"]",
"===",
"'unix'",
"?",
"'lf'",
":",
"'crlf'",
"}",
"const",
"noTrailingSpaces",
"=",
"getRuleOptions",
"(",
"'no-trailing-spaces'",
",",
"[",
"{",
"skipBlankLines",
":",
"false",
",",
"ignoreComments",
":",
"false",
"}",
"]",
")",
"if",
"(",
"noTrailingSpaces",
")",
"{",
"if",
"(",
"!",
"noTrailingSpaces",
"[",
"0",
"]",
".",
"skipBlankLines",
"&&",
"!",
"noTrailingSpaces",
"[",
"0",
"]",
".",
"ignoreComments",
")",
"{",
"result",
".",
"trim_trailing_whitespace",
"=",
"true",
"}",
"}",
"const",
"eolLast",
"=",
"getRuleOptions",
"(",
"'eol-last'",
",",
"[",
"'always'",
"]",
")",
"if",
"(",
"eolLast",
")",
"{",
"result",
".",
"insert_final_newline",
"=",
"eolLast",
"[",
"0",
"]",
"!==",
"'never'",
"}",
"const",
"maxLen",
"=",
"getRuleOptions",
"(",
"'max-len'",
",",
"[",
"{",
"code",
":",
"80",
"}",
"]",
")",
"if",
"(",
"maxLen",
")",
"{",
"if",
"(",
"typeof",
"maxLen",
"[",
"0",
"]",
"===",
"'number'",
")",
"{",
"result",
".",
"max_line_length",
"=",
"maxLen",
"[",
"0",
"]",
"}",
"else",
"{",
"result",
".",
"max_line_length",
"=",
"maxLen",
"[",
"0",
"]",
".",
"code",
"}",
"}",
"return",
"result",
"}"
] |
Convert eslint rules to editorconfig rules.
|
[
"Convert",
"eslint",
"rules",
"to",
"editorconfig",
"rules",
"."
] |
206803cbefefdfbc7d8ed12440b0b751688b77b2
|
https://github.com/vuejs/vue-cli/blob/206803cbefefdfbc7d8ed12440b0b751688b77b2/scripts/buildEditorConfig.js#L16-L91
|
train
|
hakimel/reveal.js
|
plugin/highlight/highlight.js
|
function( block, linesToHighlight ) {
linesToHighlight = linesToHighlight || block.getAttribute( 'data-line-numbers' );
if( typeof linesToHighlight === 'string' && linesToHighlight !== '' ) {
linesToHighlight.split( ',' ).forEach( function( lineNumbers ) {
// Avoid failures becase of whitespace
lineNumbers = lineNumbers.replace( /\s/g, '' );
// Ensure that we looking at a valid slide number (1 or 1-2)
if( /^[\d-]+$/.test( lineNumbers ) ) {
lineNumbers = lineNumbers.split( '-' );
var lineStart = lineNumbers[0];
var lineEnd = lineNumbers[1] || lineStart;
[].slice.call( block.querySelectorAll( 'table tr:nth-child(n+'+lineStart+'):nth-child(-n+'+lineEnd+')' ) ).forEach( function( lineElement ) {
lineElement.classList.add( 'highlight-line' );
} );
}
} );
}
}
|
javascript
|
function( block, linesToHighlight ) {
linesToHighlight = linesToHighlight || block.getAttribute( 'data-line-numbers' );
if( typeof linesToHighlight === 'string' && linesToHighlight !== '' ) {
linesToHighlight.split( ',' ).forEach( function( lineNumbers ) {
// Avoid failures becase of whitespace
lineNumbers = lineNumbers.replace( /\s/g, '' );
// Ensure that we looking at a valid slide number (1 or 1-2)
if( /^[\d-]+$/.test( lineNumbers ) ) {
lineNumbers = lineNumbers.split( '-' );
var lineStart = lineNumbers[0];
var lineEnd = lineNumbers[1] || lineStart;
[].slice.call( block.querySelectorAll( 'table tr:nth-child(n+'+lineStart+'):nth-child(-n+'+lineEnd+')' ) ).forEach( function( lineElement ) {
lineElement.classList.add( 'highlight-line' );
} );
}
} );
}
}
|
[
"function",
"(",
"block",
",",
"linesToHighlight",
")",
"{",
"linesToHighlight",
"=",
"linesToHighlight",
"||",
"block",
".",
"getAttribute",
"(",
"'data-line-numbers'",
")",
";",
"if",
"(",
"typeof",
"linesToHighlight",
"===",
"'string'",
"&&",
"linesToHighlight",
"!==",
"''",
")",
"{",
"linesToHighlight",
".",
"split",
"(",
"','",
")",
".",
"forEach",
"(",
"function",
"(",
"lineNumbers",
")",
"{",
"lineNumbers",
"=",
"lineNumbers",
".",
"replace",
"(",
"/",
"\\s",
"/",
"g",
",",
"''",
")",
";",
"if",
"(",
"/",
"^[\\d-]+$",
"/",
".",
"test",
"(",
"lineNumbers",
")",
")",
"{",
"lineNumbers",
"=",
"lineNumbers",
".",
"split",
"(",
"'-'",
")",
";",
"var",
"lineStart",
"=",
"lineNumbers",
"[",
"0",
"]",
";",
"var",
"lineEnd",
"=",
"lineNumbers",
"[",
"1",
"]",
"||",
"lineStart",
";",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"block",
".",
"querySelectorAll",
"(",
"'table tr:nth-child(n+'",
"+",
"lineStart",
"+",
"'):nth-child(-n+'",
"+",
"lineEnd",
"+",
"')'",
")",
")",
".",
"forEach",
"(",
"function",
"(",
"lineElement",
")",
"{",
"lineElement",
".",
"classList",
".",
"add",
"(",
"'highlight-line'",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] |
Visually emphasize specific lines within a code block.
This only works on blocks with line numbering turned on.
@param {HTMLElement} block a <code> block
@param {String} [linesToHighlight] The lines that should be
highlighted in this format:
"1" = highlights line 1
"2,5" = highlights lines 2 & 5
"2,5-7" = highlights lines 2, 5, 6 & 7
|
[
"Visually",
"emphasize",
"specific",
"lines",
"within",
"a",
"code",
"block",
".",
"This",
"only",
"works",
"on",
"blocks",
"with",
"line",
"numbering",
"turned",
"on",
"."
] |
33bed47daca3f08c396215415e6ece005970734a
|
https://github.com/hakimel/reveal.js/blob/33bed47daca3f08c396215415e6ece005970734a/plugin/highlight/highlight.js#L132-L161
|
train
|
|
hakimel/reveal.js
|
plugin/notes-server/client.js
|
post
|
function post() {
var slideElement = Reveal.getCurrentSlide(),
notesElement = slideElement.querySelector( 'aside.notes' );
var messageData = {
notes: '',
markdown: false,
socketId: socketId,
state: Reveal.getState()
};
// Look for notes defined in a slide attribute
if( slideElement.hasAttribute( 'data-notes' ) ) {
messageData.notes = slideElement.getAttribute( 'data-notes' );
}
// Look for notes defined in an aside element
if( notesElement ) {
messageData.notes = notesElement.innerHTML;
messageData.markdown = typeof notesElement.getAttribute( 'data-markdown' ) === 'string';
}
socket.emit( 'statechanged', messageData );
}
|
javascript
|
function post() {
var slideElement = Reveal.getCurrentSlide(),
notesElement = slideElement.querySelector( 'aside.notes' );
var messageData = {
notes: '',
markdown: false,
socketId: socketId,
state: Reveal.getState()
};
// Look for notes defined in a slide attribute
if( slideElement.hasAttribute( 'data-notes' ) ) {
messageData.notes = slideElement.getAttribute( 'data-notes' );
}
// Look for notes defined in an aside element
if( notesElement ) {
messageData.notes = notesElement.innerHTML;
messageData.markdown = typeof notesElement.getAttribute( 'data-markdown' ) === 'string';
}
socket.emit( 'statechanged', messageData );
}
|
[
"function",
"post",
"(",
")",
"{",
"var",
"slideElement",
"=",
"Reveal",
".",
"getCurrentSlide",
"(",
")",
",",
"notesElement",
"=",
"slideElement",
".",
"querySelector",
"(",
"'aside.notes'",
")",
";",
"var",
"messageData",
"=",
"{",
"notes",
":",
"''",
",",
"markdown",
":",
"false",
",",
"socketId",
":",
"socketId",
",",
"state",
":",
"Reveal",
".",
"getState",
"(",
")",
"}",
";",
"if",
"(",
"slideElement",
".",
"hasAttribute",
"(",
"'data-notes'",
")",
")",
"{",
"messageData",
".",
"notes",
"=",
"slideElement",
".",
"getAttribute",
"(",
"'data-notes'",
")",
";",
"}",
"if",
"(",
"notesElement",
")",
"{",
"messageData",
".",
"notes",
"=",
"notesElement",
".",
"innerHTML",
";",
"messageData",
".",
"markdown",
"=",
"typeof",
"notesElement",
".",
"getAttribute",
"(",
"'data-markdown'",
")",
"===",
"'string'",
";",
"}",
"socket",
".",
"emit",
"(",
"'statechanged'",
",",
"messageData",
")",
";",
"}"
] |
Posts the current slide data to the notes window
|
[
"Posts",
"the",
"current",
"slide",
"data",
"to",
"the",
"notes",
"window"
] |
33bed47daca3f08c396215415e6ece005970734a
|
https://github.com/hakimel/reveal.js/blob/33bed47daca3f08c396215415e6ece005970734a/plugin/notes-server/client.js#L16-L41
|
train
|
chartjs/Chart.js
|
src/scales/scale.linear.js
|
function() {
var me = this;
var tickFont;
if (me.isHorizontal()) {
return Math.ceil(me.width / 40);
}
tickFont = helpers.options._parseFont(me.options.ticks);
return Math.ceil(me.height / tickFont.lineHeight);
}
|
javascript
|
function() {
var me = this;
var tickFont;
if (me.isHorizontal()) {
return Math.ceil(me.width / 40);
}
tickFont = helpers.options._parseFont(me.options.ticks);
return Math.ceil(me.height / tickFont.lineHeight);
}
|
[
"function",
"(",
")",
"{",
"var",
"me",
"=",
"this",
";",
"var",
"tickFont",
";",
"if",
"(",
"me",
".",
"isHorizontal",
"(",
")",
")",
"{",
"return",
"Math",
".",
"ceil",
"(",
"me",
".",
"width",
"/",
"40",
")",
";",
"}",
"tickFont",
"=",
"helpers",
".",
"options",
".",
"_parseFont",
"(",
"me",
".",
"options",
".",
"ticks",
")",
";",
"return",
"Math",
".",
"ceil",
"(",
"me",
".",
"height",
"/",
"tickFont",
".",
"lineHeight",
")",
";",
"}"
] |
Returns the maximum number of ticks based on the scale dimension
|
[
"Returns",
"the",
"maximum",
"number",
"of",
"ticks",
"based",
"on",
"the",
"scale",
"dimension"
] |
f093c36574d290330ed623e60fbd070421c730d5
|
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/scales/scale.linear.js#L134-L143
|
train
|
|
chartjs/Chart.js
|
src/controllers/controller.bar.js
|
function(last) {
var me = this;
var chart = me.chart;
var scale = me._getIndexScale();
var stacked = scale.options.stacked;
var ilen = last === undefined ? chart.data.datasets.length : last + 1;
var stacks = [];
var i, meta;
for (i = 0; i < ilen; ++i) {
meta = chart.getDatasetMeta(i);
if (meta.bar && chart.isDatasetVisible(i) &&
(stacked === false ||
(stacked === true && stacks.indexOf(meta.stack) === -1) ||
(stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) {
stacks.push(meta.stack);
}
}
return stacks;
}
|
javascript
|
function(last) {
var me = this;
var chart = me.chart;
var scale = me._getIndexScale();
var stacked = scale.options.stacked;
var ilen = last === undefined ? chart.data.datasets.length : last + 1;
var stacks = [];
var i, meta;
for (i = 0; i < ilen; ++i) {
meta = chart.getDatasetMeta(i);
if (meta.bar && chart.isDatasetVisible(i) &&
(stacked === false ||
(stacked === true && stacks.indexOf(meta.stack) === -1) ||
(stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) {
stacks.push(meta.stack);
}
}
return stacks;
}
|
[
"function",
"(",
"last",
")",
"{",
"var",
"me",
"=",
"this",
";",
"var",
"chart",
"=",
"me",
".",
"chart",
";",
"var",
"scale",
"=",
"me",
".",
"_getIndexScale",
"(",
")",
";",
"var",
"stacked",
"=",
"scale",
".",
"options",
".",
"stacked",
";",
"var",
"ilen",
"=",
"last",
"===",
"undefined",
"?",
"chart",
".",
"data",
".",
"datasets",
".",
"length",
":",
"last",
"+",
"1",
";",
"var",
"stacks",
"=",
"[",
"]",
";",
"var",
"i",
",",
"meta",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"ilen",
";",
"++",
"i",
")",
"{",
"meta",
"=",
"chart",
".",
"getDatasetMeta",
"(",
"i",
")",
";",
"if",
"(",
"meta",
".",
"bar",
"&&",
"chart",
".",
"isDatasetVisible",
"(",
"i",
")",
"&&",
"(",
"stacked",
"===",
"false",
"||",
"(",
"stacked",
"===",
"true",
"&&",
"stacks",
".",
"indexOf",
"(",
"meta",
".",
"stack",
")",
"===",
"-",
"1",
")",
"||",
"(",
"stacked",
"===",
"undefined",
"&&",
"(",
"meta",
".",
"stack",
"===",
"undefined",
"||",
"stacks",
".",
"indexOf",
"(",
"meta",
".",
"stack",
")",
"===",
"-",
"1",
")",
")",
")",
")",
"{",
"stacks",
".",
"push",
"(",
"meta",
".",
"stack",
")",
";",
"}",
"}",
"return",
"stacks",
";",
"}"
] |
Returns the stacks based on groups and bar visibility.
@param {number} [last] - The dataset index
@returns {string[]} The list of stack IDs
@private
|
[
"Returns",
"the",
"stacks",
"based",
"on",
"groups",
"and",
"bar",
"visibility",
"."
] |
f093c36574d290330ed623e60fbd070421c730d5
|
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/controllers/controller.bar.js#L197-L217
|
train
|
|
chartjs/Chart.js
|
src/controllers/controller.bar.js
|
function(datasetIndex, name) {
var stacks = this._getStacks(datasetIndex);
var index = (name !== undefined)
? stacks.indexOf(name)
: -1; // indexOf returns -1 if element is not present
return (index === -1)
? stacks.length - 1
: index;
}
|
javascript
|
function(datasetIndex, name) {
var stacks = this._getStacks(datasetIndex);
var index = (name !== undefined)
? stacks.indexOf(name)
: -1; // indexOf returns -1 if element is not present
return (index === -1)
? stacks.length - 1
: index;
}
|
[
"function",
"(",
"datasetIndex",
",",
"name",
")",
"{",
"var",
"stacks",
"=",
"this",
".",
"_getStacks",
"(",
"datasetIndex",
")",
";",
"var",
"index",
"=",
"(",
"name",
"!==",
"undefined",
")",
"?",
"stacks",
".",
"indexOf",
"(",
"name",
")",
":",
"-",
"1",
";",
"return",
"(",
"index",
"===",
"-",
"1",
")",
"?",
"stacks",
".",
"length",
"-",
"1",
":",
"index",
";",
"}"
] |
Returns the stack index for the given dataset based on groups and bar visibility.
@param {number} [datasetIndex] - The dataset index
@param {string} [name] - The stack name to find
@returns {number} The stack index
@private
|
[
"Returns",
"the",
"stack",
"index",
"for",
"the",
"given",
"dataset",
"based",
"on",
"groups",
"and",
"bar",
"visibility",
"."
] |
f093c36574d290330ed623e60fbd070421c730d5
|
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/controllers/controller.bar.js#L234-L243
|
train
|
|
chartjs/Chart.js
|
src/helpers/helpers.options.js
|
toFontString
|
function toFontString(font) {
if (!font || helpers.isNullOrUndef(font.size) || helpers.isNullOrUndef(font.family)) {
return null;
}
return (font.style ? font.style + ' ' : '')
+ (font.weight ? font.weight + ' ' : '')
+ font.size + 'px '
+ font.family;
}
|
javascript
|
function toFontString(font) {
if (!font || helpers.isNullOrUndef(font.size) || helpers.isNullOrUndef(font.family)) {
return null;
}
return (font.style ? font.style + ' ' : '')
+ (font.weight ? font.weight + ' ' : '')
+ font.size + 'px '
+ font.family;
}
|
[
"function",
"toFontString",
"(",
"font",
")",
"{",
"if",
"(",
"!",
"font",
"||",
"helpers",
".",
"isNullOrUndef",
"(",
"font",
".",
"size",
")",
"||",
"helpers",
".",
"isNullOrUndef",
"(",
"font",
".",
"family",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"(",
"font",
".",
"style",
"?",
"font",
".",
"style",
"+",
"' '",
":",
"''",
")",
"+",
"(",
"font",
".",
"weight",
"?",
"font",
".",
"weight",
"+",
"' '",
":",
"''",
")",
"+",
"font",
".",
"size",
"+",
"'px '",
"+",
"font",
".",
"family",
";",
"}"
] |
Converts the given font object into a CSS font string.
@param {object} font - A font object.
@return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
@private
|
[
"Converts",
"the",
"given",
"font",
"object",
"into",
"a",
"CSS",
"font",
"string",
"."
] |
f093c36574d290330ed623e60fbd070421c730d5
|
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/helpers/helpers.options.js#L14-L23
|
train
|
chartjs/Chart.js
|
src/core/core.tooltip.js
|
function(elements, eventPosition) {
var x = eventPosition.x;
var y = eventPosition.y;
var minDistance = Number.POSITIVE_INFINITY;
var i, len, nearestElement;
for (i = 0, len = elements.length; i < len; ++i) {
var el = elements[i];
if (el && el.hasValue()) {
var center = el.getCenterPoint();
var d = helpers.distanceBetweenPoints(eventPosition, center);
if (d < minDistance) {
minDistance = d;
nearestElement = el;
}
}
}
if (nearestElement) {
var tp = nearestElement.tooltipPosition();
x = tp.x;
y = tp.y;
}
return {
x: x,
y: y
};
}
|
javascript
|
function(elements, eventPosition) {
var x = eventPosition.x;
var y = eventPosition.y;
var minDistance = Number.POSITIVE_INFINITY;
var i, len, nearestElement;
for (i = 0, len = elements.length; i < len; ++i) {
var el = elements[i];
if (el && el.hasValue()) {
var center = el.getCenterPoint();
var d = helpers.distanceBetweenPoints(eventPosition, center);
if (d < minDistance) {
minDistance = d;
nearestElement = el;
}
}
}
if (nearestElement) {
var tp = nearestElement.tooltipPosition();
x = tp.x;
y = tp.y;
}
return {
x: x,
y: y
};
}
|
[
"function",
"(",
"elements",
",",
"eventPosition",
")",
"{",
"var",
"x",
"=",
"eventPosition",
".",
"x",
";",
"var",
"y",
"=",
"eventPosition",
".",
"y",
";",
"var",
"minDistance",
"=",
"Number",
".",
"POSITIVE_INFINITY",
";",
"var",
"i",
",",
"len",
",",
"nearestElement",
";",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"elements",
".",
"length",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"var",
"el",
"=",
"elements",
"[",
"i",
"]",
";",
"if",
"(",
"el",
"&&",
"el",
".",
"hasValue",
"(",
")",
")",
"{",
"var",
"center",
"=",
"el",
".",
"getCenterPoint",
"(",
")",
";",
"var",
"d",
"=",
"helpers",
".",
"distanceBetweenPoints",
"(",
"eventPosition",
",",
"center",
")",
";",
"if",
"(",
"d",
"<",
"minDistance",
")",
"{",
"minDistance",
"=",
"d",
";",
"nearestElement",
"=",
"el",
";",
"}",
"}",
"}",
"if",
"(",
"nearestElement",
")",
"{",
"var",
"tp",
"=",
"nearestElement",
".",
"tooltipPosition",
"(",
")",
";",
"x",
"=",
"tp",
".",
"x",
";",
"y",
"=",
"tp",
".",
"y",
";",
"}",
"return",
"{",
"x",
":",
"x",
",",
"y",
":",
"y",
"}",
";",
"}"
] |
Gets the tooltip position nearest of the item nearest to the event position
@function Chart.Tooltip.positioners.nearest
@param elements {Chart.Element[]} the tooltip elements
@param eventPosition {object} the position of the event in canvas coordinates
@returns {object} the tooltip position
|
[
"Gets",
"the",
"tooltip",
"position",
"nearest",
"of",
"the",
"item",
"nearest",
"to",
"the",
"event",
"position"
] |
f093c36574d290330ed623e60fbd070421c730d5
|
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/core/core.tooltip.js#L145-L174
|
train
|
|
chartjs/Chart.js
|
src/core/core.tooltip.js
|
pushOrConcat
|
function pushOrConcat(base, toPush) {
if (toPush) {
if (helpers.isArray(toPush)) {
// base = base.concat(toPush);
Array.prototype.push.apply(base, toPush);
} else {
base.push(toPush);
}
}
return base;
}
|
javascript
|
function pushOrConcat(base, toPush) {
if (toPush) {
if (helpers.isArray(toPush)) {
// base = base.concat(toPush);
Array.prototype.push.apply(base, toPush);
} else {
base.push(toPush);
}
}
return base;
}
|
[
"function",
"pushOrConcat",
"(",
"base",
",",
"toPush",
")",
"{",
"if",
"(",
"toPush",
")",
"{",
"if",
"(",
"helpers",
".",
"isArray",
"(",
"toPush",
")",
")",
"{",
"Array",
".",
"prototype",
".",
"push",
".",
"apply",
"(",
"base",
",",
"toPush",
")",
";",
"}",
"else",
"{",
"base",
".",
"push",
"(",
"toPush",
")",
";",
"}",
"}",
"return",
"base",
";",
"}"
] |
Helper to push or concat based on if the 2nd parameter is an array or not
|
[
"Helper",
"to",
"push",
"or",
"concat",
"based",
"on",
"if",
"the",
"2nd",
"parameter",
"is",
"an",
"array",
"or",
"not"
] |
f093c36574d290330ed623e60fbd070421c730d5
|
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/core/core.tooltip.js#L178-L189
|
train
|
chartjs/Chart.js
|
src/core/core.tooltip.js
|
splitNewlines
|
function splitNewlines(str) {
if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
return str.split('\n');
}
return str;
}
|
javascript
|
function splitNewlines(str) {
if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
return str.split('\n');
}
return str;
}
|
[
"function",
"splitNewlines",
"(",
"str",
")",
"{",
"if",
"(",
"(",
"typeof",
"str",
"===",
"'string'",
"||",
"str",
"instanceof",
"String",
")",
"&&",
"str",
".",
"indexOf",
"(",
"'\\n'",
")",
">",
"\\n",
")",
"-",
"1",
"{",
"return",
"str",
".",
"split",
"(",
"'\\n'",
")",
";",
"}",
"}"
] |
Returns array of strings split by newline
@param {string} value - The value to split by newline.
@returns {string[]} value if newline present - Returned from String split() method
@function
|
[
"Returns",
"array",
"of",
"strings",
"split",
"by",
"newline"
] |
f093c36574d290330ed623e60fbd070421c730d5
|
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/core/core.tooltip.js#L197-L202
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.