_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q15500
|
privateBrowsing
|
train
|
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
|
{
"resource": ""
}
|
q15501
|
privateBrowsing_start
|
train
|
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
|
{
"resource": ""
}
|
q15502
|
privateBrowsing_stop
|
train
|
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
|
{
"resource": ""
}
|
q15503
|
privateBrowsing_waitForTransitionComplete
|
train
|
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
|
{
"resource": ""
}
|
q15504
|
create
|
train
|
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
|
{
"resource": ""
}
|
q15505
|
_saveCanvas
|
train
|
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
|
{
"resource": ""
}
|
q15506
|
train
|
function(requestedId) {
var requestedDeps =
this.getNotYetLoadedTransitiveDepIds_(requestedId);
return goog.array.some(failedIds, function(id) {
return goog.array.contains(requestedDeps, id);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q15507
|
train
|
function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.tag);
}
|
javascript
|
{
"resource": ""
}
|
|
q15508
|
positiveSize
|
train
|
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
|
{
"resource": ""
}
|
q15509
|
hiddenByOverflow
|
train
|
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
|
{
"resource": ""
}
|
q15510
|
getOverflowParent
|
train
|
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
|
{
"resource": ""
}
|
q15511
|
getOverflowStyles
|
train
|
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
|
{
"resource": ""
}
|
q15512
|
getScroll
|
train
|
function getScroll(e) {
if (e == htmlElem) {
return new goog.dom.DomHelper(ownerDoc).getDocumentScroll();
} else {
return new goog.math.Coordinate(e.scrollLeft, e.scrollTop);
}
}
|
javascript
|
{
"resource": ""
}
|
q15513
|
train
|
function() {
var obj = {};
for (var type in this.prefs_) {
if (this.prefs_.hasOwnProperty(type)) {
obj[type] = this.prefs_[type].name;
}
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q15514
|
unwrapNode
|
train
|
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
|
{
"resource": ""
}
|
q15515
|
DOMWalker_walk
|
train
|
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
|
{
"resource": ""
}
|
q15516
|
DOMWalker_getNode
|
train
|
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
|
{
"resource": ""
}
|
q15517
|
DOMWalker_prepareTargetWindows
|
train
|
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
|
{
"resource": ""
}
|
q15518
|
DOMWalker__walk
|
train
|
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
|
{
"resource": ""
}
|
q15519
|
DOMWalker_modalWindowHelper
|
train
|
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
|
{
"resource": ""
}
|
q15520
|
nodeCollector_filter
|
train
|
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
|
{
"resource": ""
}
|
q15521
|
nodeCollector_filterByDOMProperty
|
train
|
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
|
{
"resource": ""
}
|
q15522
|
nodeCollector_filterByJSProperty
|
train
|
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
|
{
"resource": ""
}
|
q15523
|
nodeCollector_queryAnonymousNodes
|
train
|
function nodeCollector_queryAnonymousNodes(aAttribute, aValue) {
var node = this._document.getAnonymousElementByAttribute(this._root,
aAttribute,
aValue);
this.nodes = node ? [node] : [ ];
return this;
}
|
javascript
|
{
"resource": ""
}
|
q15524
|
stopWithHelp
|
train
|
function stopWithHelp(...msgs) {
utils.header()
utils.error(...msgs)
commands.help.forCommand(commands.build)
utils.die()
}
|
javascript
|
{
"resource": ""
}
|
q15525
|
buildToStdout
|
train
|
function buildToStdout(compileOptions) {
return compile(compileOptions).then(result => process.stdout.write(result.css))
}
|
javascript
|
{
"resource": ""
}
|
q15526
|
buildToFile
|
train
|
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
|
{
"resource": ""
}
|
q15527
|
computeControlPoint
|
train
|
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
|
{
"resource": ""
}
|
q15528
|
layoutGraph
|
train
|
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
|
{
"resource": ""
}
|
q15529
|
createCanvas
|
train
|
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
|
{
"resource": ""
}
|
q15530
|
getGPUAggregationParams
|
train
|
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
|
{
"resource": ""
}
|
q15531
|
resizeImage
|
train
|
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
|
{
"resource": ""
}
|
q15532
|
buildRowMapping
|
train
|
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
|
{
"resource": ""
}
|
q15533
|
resizeTexture
|
train
|
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
|
{
"resource": ""
}
|
q15534
|
_pointsToGridHashing
|
train
|
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
|
{
"resource": ""
}
|
q15535
|
diffDataProps
|
train
|
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
|
{
"resource": ""
}
|
q15536
|
diffUpdateTriggers
|
train
|
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
|
{
"resource": ""
}
|
q15537
|
getPropsPrototypeAndTypes
|
train
|
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
|
{
"resource": ""
}
|
q15538
|
createPropsPrototypeAndTypes
|
train
|
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
|
{
"resource": ""
}
|
q15539
|
createPropsPrototype
|
train
|
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
|
{
"resource": ""
}
|
q15540
|
addAsyncPropsToPropPrototype
|
train
|
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
|
{
"resource": ""
}
|
q15541
|
wrapInView
|
train
|
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
|
{
"resource": ""
}
|
q15542
|
setTextStyle
|
train
|
function setTextStyle(ctx, fontSize) {
ctx.font = `${fontSize}px Helvetica,Arial,sans-serif`;
ctx.fillStyle = '#000';
ctx.textBaseline = 'top';
ctx.textAlign = 'center';
}
|
javascript
|
{
"resource": ""
}
|
q15543
|
time
|
train
|
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
|
{
"resource": ""
}
|
q15544
|
checkForAssertionErrors
|
train
|
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
|
{
"resource": ""
}
|
q15545
|
isNestedRingClosed
|
train
|
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
|
{
"resource": ""
}
|
q15546
|
isFlatRingClosed
|
train
|
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
|
{
"resource": ""
}
|
q15547
|
copyNestedRing
|
train
|
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
|
{
"resource": ""
}
|
q15548
|
copyFlatRing
|
train
|
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
|
{
"resource": ""
}
|
q15549
|
getFlatVertexCount
|
train
|
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
|
{
"resource": ""
}
|
q15550
|
activateWidgetExtension
|
train
|
function activateWidgetExtension(app, registry) {
registry.registerWidget({
name: MODULE_NAME,
version: MODULE_VERSION,
exports: {
DeckGLModel,
DeckGLView
}
});
}
|
javascript
|
{
"resource": ""
}
|
q15551
|
getNewChars
|
train
|
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
|
{
"resource": ""
}
|
q15552
|
handleMouseEvent
|
train
|
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
|
{
"resource": ""
}
|
q15553
|
getLevelFromToken
|
train
|
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
|
{
"resource": ""
}
|
q15554
|
flattenArray
|
train
|
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
|
{
"resource": ""
}
|
q15555
|
sayHello
|
train
|
function sayHello(call, callback) {
var reply = new messages.HelloReply();
reply.setMessage('Hello ' + call.request.getName());
callback(null, reply);
}
|
javascript
|
{
"resource": ""
}
|
q15556
|
NetProfiler
|
train
|
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
|
{
"resource": ""
}
|
q15557
|
formErrorText
|
train
|
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
|
{
"resource": ""
}
|
q15558
|
unknownOption
|
train
|
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
|
{
"resource": ""
}
|
q15559
|
applyResource
|
train
|
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
|
{
"resource": ""
}
|
q15560
|
isValidProject
|
train
|
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
|
{
"resource": ""
}
|
q15561
|
isValidObject
|
train
|
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
|
{
"resource": ""
}
|
q15562
|
getPathDirectory
|
train
|
function getPathDirectory(length, parts) {
if (!parts) {
return '';
}
return parts
.slice(length)
.filter(part => part !== '')
.join(path.sep);
}
|
javascript
|
{
"resource": ""
}
|
q15563
|
parseRepoURL
|
train
|
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
|
{
"resource": ""
}
|
q15564
|
set
|
train
|
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
|
{
"resource": ""
}
|
q15565
|
findReferences
|
train
|
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
|
{
"resource": ""
}
|
q15566
|
param
|
train
|
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
|
{
"resource": ""
}
|
q15567
|
appendMethods
|
train
|
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
|
{
"resource": ""
}
|
q15568
|
getProtohost
|
train
|
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
|
{
"resource": ""
}
|
q15569
|
gettype
|
train
|
function gettype(obj) {
var type = typeof obj;
if (type !== 'object') {
return type;
}
// inspect [[Class]] for objects
return toString.call(obj)
.replace(objectRegExp, '$1');
}
|
javascript
|
{
"resource": ""
}
|
q15570
|
sendOptionsResponse
|
train
|
function sendOptionsResponse(res, options, next) {
try {
var body = options.join(',');
res.set('Allow', body);
res.send(body);
} catch (err) {
next(err);
}
}
|
javascript
|
{
"resource": ""
}
|
q15571
|
wrap
|
train
|
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
|
{
"resource": ""
}
|
q15572
|
tryRender
|
train
|
function tryRender(view, options, callback) {
try {
view.render(options, callback);
} catch (err) {
callback(err);
}
}
|
javascript
|
{
"resource": ""
}
|
q15573
|
authenticate
|
train
|
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
|
{
"resource": ""
}
|
q15574
|
sendfile
|
train
|
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
|
{
"resource": ""
}
|
q15575
|
stringify
|
train
|
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
|
{
"resource": ""
}
|
q15576
|
createError
|
train
|
function createError(status, message) {
var err = new Error(message);
err.status = status;
return err;
}
|
javascript
|
{
"resource": ""
}
|
q15577
|
View
|
train
|
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
|
{
"resource": ""
}
|
q15578
|
GithubView
|
train
|
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
|
{
"resource": ""
}
|
q15579
|
count
|
train
|
function count(req, res, next) {
User.count(function(err, count){
if (err) return next(err);
req.count = count;
next();
})
}
|
javascript
|
{
"resource": ""
}
|
q15580
|
count2
|
train
|
function count2(req, res, next) {
User.count(function(err, count){
if (err) return next(err);
res.locals.count = count;
next();
})
}
|
javascript
|
{
"resource": ""
}
|
q15581
|
createETagGenerator
|
train
|
function createETagGenerator (options) {
return function generateETag (body, encoding) {
var buf = !Buffer.isBuffer(body)
? Buffer.from(body, encoding)
: body
return etag(buf, options)
}
}
|
javascript
|
{
"resource": ""
}
|
q15582
|
train
|
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
|
{
"resource": ""
}
|
|
q15583
|
filterFiles
|
train
|
function filterFiles (filters) {
return (files, metalsmith, done) => {
filter(files, filters, metalsmith.metadata(), done)
}
}
|
javascript
|
{
"resource": ""
}
|
q15584
|
logMessage
|
train
|
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
|
{
"resource": ""
}
|
q15585
|
cleanArgs
|
train
|
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
|
{
"resource": ""
}
|
q15586
|
mayProxy
|
train
|
function mayProxy (pathname) {
const maybePublicPath = path.resolve(appPublicFolder, pathname.slice(1))
return !fs.existsSync(maybePublicPath)
}
|
javascript
|
{
"resource": ""
}
|
q15587
|
autoOpenLastProject
|
train
|
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
|
{
"resource": ""
}
|
q15588
|
getDefaultValue
|
train
|
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
|
{
"resource": ""
}
|
q15589
|
getModulePath
|
train
|
function getModulePath (mod, useAbsolutePath) {
const modPath =
mod === 'regenerator-runtime'
? 'regenerator-runtime/runtime'
: `core-js/modules/${mod}`
return useAbsolutePath ? require.resolve(modPath) : modPath
}
|
javascript
|
{
"resource": ""
}
|
q15590
|
convertRules
|
train
|
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
|
{
"resource": ""
}
|
q15591
|
train
|
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
|
{
"resource": ""
}
|
|
q15592
|
post
|
train
|
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
|
{
"resource": ""
}
|
q15593
|
train
|
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
|
{
"resource": ""
}
|
|
q15594
|
train
|
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
|
{
"resource": ""
}
|
|
q15595
|
train
|
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
|
{
"resource": ""
}
|
|
q15596
|
toFontString
|
train
|
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
|
{
"resource": ""
}
|
q15597
|
train
|
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
|
{
"resource": ""
}
|
|
q15598
|
pushOrConcat
|
train
|
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
|
{
"resource": ""
}
|
q15599
|
splitNewlines
|
train
|
function splitNewlines(str) {
if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
return str.split('\n');
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.