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
chartjs/Chart.js
src/core/core.tooltip.js
determineAlignment
function determineAlignment(tooltip, size) { var model = tooltip._model; var chart = tooltip._chart; var chartArea = tooltip._chart.chartArea; var xAlign = 'center'; var yAlign = 'center'; if (model.y < size.height) { yAlign = 'top'; } else if (model.y > (chart.height - size.height)) { yAlign = 'bottom'; } var lf, rf; // functions to determine left, right alignment var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges var midX = (chartArea.left + chartArea.right) / 2; var midY = (chartArea.top + chartArea.bottom) / 2; if (yAlign === 'center') { lf = function(x) { return x <= midX; }; rf = function(x) { return x > midX; }; } else { lf = function(x) { return x <= (size.width / 2); }; rf = function(x) { return x >= (chart.width - (size.width / 2)); }; } olf = function(x) { return x + size.width + model.caretSize + model.caretPadding > chart.width; }; orf = function(x) { return x - size.width - model.caretSize - model.caretPadding < 0; }; yf = function(y) { return y <= midY ? 'top' : 'bottom'; }; if (lf(model.x)) { xAlign = 'left'; // Is tooltip too wide and goes over the right side of the chart.? if (olf(model.x)) { xAlign = 'center'; yAlign = yf(model.y); } } else if (rf(model.x)) { xAlign = 'right'; // Is tooltip too wide and goes outside left edge of canvas? if (orf(model.x)) { xAlign = 'center'; yAlign = yf(model.y); } } var opts = tooltip._options; return { xAlign: opts.xAlign ? opts.xAlign : xAlign, yAlign: opts.yAlign ? opts.yAlign : yAlign }; }
javascript
function determineAlignment(tooltip, size) { var model = tooltip._model; var chart = tooltip._chart; var chartArea = tooltip._chart.chartArea; var xAlign = 'center'; var yAlign = 'center'; if (model.y < size.height) { yAlign = 'top'; } else if (model.y > (chart.height - size.height)) { yAlign = 'bottom'; } var lf, rf; // functions to determine left, right alignment var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges var midX = (chartArea.left + chartArea.right) / 2; var midY = (chartArea.top + chartArea.bottom) / 2; if (yAlign === 'center') { lf = function(x) { return x <= midX; }; rf = function(x) { return x > midX; }; } else { lf = function(x) { return x <= (size.width / 2); }; rf = function(x) { return x >= (chart.width - (size.width / 2)); }; } olf = function(x) { return x + size.width + model.caretSize + model.caretPadding > chart.width; }; orf = function(x) { return x - size.width - model.caretSize - model.caretPadding < 0; }; yf = function(y) { return y <= midY ? 'top' : 'bottom'; }; if (lf(model.x)) { xAlign = 'left'; // Is tooltip too wide and goes over the right side of the chart.? if (olf(model.x)) { xAlign = 'center'; yAlign = yf(model.y); } } else if (rf(model.x)) { xAlign = 'right'; // Is tooltip too wide and goes outside left edge of canvas? if (orf(model.x)) { xAlign = 'center'; yAlign = yf(model.y); } } var opts = tooltip._options; return { xAlign: opts.xAlign ? opts.xAlign : xAlign, yAlign: opts.yAlign ? opts.yAlign : yAlign }; }
[ "function", "determineAlignment", "(", "tooltip", ",", "size", ")", "{", "var", "model", "=", "tooltip", ".", "_model", ";", "var", "chart", "=", "tooltip", ".", "_chart", ";", "var", "chartArea", "=", "tooltip", ".", "_chart", ".", "chartArea", ";", "var", "xAlign", "=", "'center'", ";", "var", "yAlign", "=", "'center'", ";", "if", "(", "model", ".", "y", "<", "size", ".", "height", ")", "{", "yAlign", "=", "'top'", ";", "}", "else", "if", "(", "model", ".", "y", ">", "(", "chart", ".", "height", "-", "size", ".", "height", ")", ")", "{", "yAlign", "=", "'bottom'", ";", "}", "var", "lf", ",", "rf", ";", "var", "olf", ",", "orf", ";", "var", "yf", ";", "var", "midX", "=", "(", "chartArea", ".", "left", "+", "chartArea", ".", "right", ")", "/", "2", ";", "var", "midY", "=", "(", "chartArea", ".", "top", "+", "chartArea", ".", "bottom", ")", "/", "2", ";", "if", "(", "yAlign", "===", "'center'", ")", "{", "lf", "=", "function", "(", "x", ")", "{", "return", "x", "<=", "midX", ";", "}", ";", "rf", "=", "function", "(", "x", ")", "{", "return", "x", ">", "midX", ";", "}", ";", "}", "else", "{", "lf", "=", "function", "(", "x", ")", "{", "return", "x", "<=", "(", "size", ".", "width", "/", "2", ")", ";", "}", ";", "rf", "=", "function", "(", "x", ")", "{", "return", "x", ">=", "(", "chart", ".", "width", "-", "(", "size", ".", "width", "/", "2", ")", ")", ";", "}", ";", "}", "olf", "=", "function", "(", "x", ")", "{", "return", "x", "+", "size", ".", "width", "+", "model", ".", "caretSize", "+", "model", ".", "caretPadding", ">", "chart", ".", "width", ";", "}", ";", "orf", "=", "function", "(", "x", ")", "{", "return", "x", "-", "size", ".", "width", "-", "model", ".", "caretSize", "-", "model", ".", "caretPadding", "<", "0", ";", "}", ";", "yf", "=", "function", "(", "y", ")", "{", "return", "y", "<=", "midY", "?", "'top'", ":", "'bottom'", ";", "}", ";", "if", "(", "lf", "(", "model", ".", "x", ")", ")", "{", "xAlign", "=", "'left'", ";", "if", "(", "olf", "(", "model", ".", "x", ")", ")", "{", "xAlign", "=", "'center'", ";", "yAlign", "=", "yf", "(", "model", ".", "y", ")", ";", "}", "}", "else", "if", "(", "rf", "(", "model", ".", "x", ")", ")", "{", "xAlign", "=", "'right'", ";", "if", "(", "orf", "(", "model", ".", "x", ")", ")", "{", "xAlign", "=", "'center'", ";", "yAlign", "=", "yf", "(", "model", ".", "y", ")", ";", "}", "}", "var", "opts", "=", "tooltip", ".", "_options", ";", "return", "{", "xAlign", ":", "opts", ".", "xAlign", "?", "opts", ".", "xAlign", ":", "xAlign", ",", "yAlign", ":", "opts", ".", "yAlign", "?", "opts", ".", "yAlign", ":", "yAlign", "}", ";", "}" ]
Helper to get the alignment of a tooltip given the size
[ "Helper", "to", "get", "the", "alignment", "of", "a", "tooltip", "given", "the", "size" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/core/core.tooltip.js#L354-L422
train
chartjs/Chart.js
src/core/core.plugins.js
function(chart, hook, args) { var descriptors = this.descriptors(chart); var ilen = descriptors.length; var i, descriptor, plugin, params, method; for (i = 0; i < ilen; ++i) { descriptor = descriptors[i]; plugin = descriptor.plugin; method = plugin[hook]; if (typeof method === 'function') { params = [chart].concat(args || []); params.push(descriptor.options); if (method.apply(plugin, params) === false) { return false; } } } return true; }
javascript
function(chart, hook, args) { var descriptors = this.descriptors(chart); var ilen = descriptors.length; var i, descriptor, plugin, params, method; for (i = 0; i < ilen; ++i) { descriptor = descriptors[i]; plugin = descriptor.plugin; method = plugin[hook]; if (typeof method === 'function') { params = [chart].concat(args || []); params.push(descriptor.options); if (method.apply(plugin, params) === false) { return false; } } } return true; }
[ "function", "(", "chart", ",", "hook", ",", "args", ")", "{", "var", "descriptors", "=", "this", ".", "descriptors", "(", "chart", ")", ";", "var", "ilen", "=", "descriptors", ".", "length", ";", "var", "i", ",", "descriptor", ",", "plugin", ",", "params", ",", "method", ";", "for", "(", "i", "=", "0", ";", "i", "<", "ilen", ";", "++", "i", ")", "{", "descriptor", "=", "descriptors", "[", "i", "]", ";", "plugin", "=", "descriptor", ".", "plugin", ";", "method", "=", "plugin", "[", "hook", "]", ";", "if", "(", "typeof", "method", "===", "'function'", ")", "{", "params", "=", "[", "chart", "]", ".", "concat", "(", "args", "||", "[", "]", ")", ";", "params", ".", "push", "(", "descriptor", ".", "options", ")", ";", "if", "(", "method", ".", "apply", "(", "plugin", ",", "params", ")", "===", "false", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
Calls enabled plugins for `chart` on the specified hook and with the given args. This method immediately returns as soon as a plugin explicitly returns false. The returned value can be used, for instance, to interrupt the current action. @param {Chart} chart - The chart instance for which plugins should be called. @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate'). @param {Array} [args] - Extra arguments to apply to the hook call. @returns {boolean} false if any of the plugins return false, else returns true.
[ "Calls", "enabled", "plugins", "for", "chart", "on", "the", "specified", "hook", "and", "with", "the", "given", "args", ".", "This", "method", "immediately", "returns", "as", "soon", "as", "a", "plugin", "explicitly", "returns", "false", ".", "The", "returned", "value", "can", "be", "used", "for", "instance", "to", "interrupt", "the", "current", "action", "." ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/core/core.plugins.js#L97-L116
train
chartjs/Chart.js
src/core/core.plugins.js
function(chart) { var cache = chart.$plugins || (chart.$plugins = {}); if (cache.id === this._cacheId) { return cache.descriptors; } var plugins = []; var descriptors = []; var config = (chart && chart.config) || {}; var options = (config.options && config.options.plugins) || {}; this._plugins.concat(config.plugins || []).forEach(function(plugin) { var idx = plugins.indexOf(plugin); if (idx !== -1) { return; } var id = plugin.id; var opts = options[id]; if (opts === false) { return; } if (opts === true) { opts = helpers.clone(defaults.global.plugins[id]); } plugins.push(plugin); descriptors.push({ plugin: plugin, options: opts || {} }); }); cache.descriptors = descriptors; cache.id = this._cacheId; return descriptors; }
javascript
function(chart) { var cache = chart.$plugins || (chart.$plugins = {}); if (cache.id === this._cacheId) { return cache.descriptors; } var plugins = []; var descriptors = []; var config = (chart && chart.config) || {}; var options = (config.options && config.options.plugins) || {}; this._plugins.concat(config.plugins || []).forEach(function(plugin) { var idx = plugins.indexOf(plugin); if (idx !== -1) { return; } var id = plugin.id; var opts = options[id]; if (opts === false) { return; } if (opts === true) { opts = helpers.clone(defaults.global.plugins[id]); } plugins.push(plugin); descriptors.push({ plugin: plugin, options: opts || {} }); }); cache.descriptors = descriptors; cache.id = this._cacheId; return descriptors; }
[ "function", "(", "chart", ")", "{", "var", "cache", "=", "chart", ".", "$plugins", "||", "(", "chart", ".", "$plugins", "=", "{", "}", ")", ";", "if", "(", "cache", ".", "id", "===", "this", ".", "_cacheId", ")", "{", "return", "cache", ".", "descriptors", ";", "}", "var", "plugins", "=", "[", "]", ";", "var", "descriptors", "=", "[", "]", ";", "var", "config", "=", "(", "chart", "&&", "chart", ".", "config", ")", "||", "{", "}", ";", "var", "options", "=", "(", "config", ".", "options", "&&", "config", ".", "options", ".", "plugins", ")", "||", "{", "}", ";", "this", ".", "_plugins", ".", "concat", "(", "config", ".", "plugins", "||", "[", "]", ")", ".", "forEach", "(", "function", "(", "plugin", ")", "{", "var", "idx", "=", "plugins", ".", "indexOf", "(", "plugin", ")", ";", "if", "(", "idx", "!==", "-", "1", ")", "{", "return", ";", "}", "var", "id", "=", "plugin", ".", "id", ";", "var", "opts", "=", "options", "[", "id", "]", ";", "if", "(", "opts", "===", "false", ")", "{", "return", ";", "}", "if", "(", "opts", "===", "true", ")", "{", "opts", "=", "helpers", ".", "clone", "(", "defaults", ".", "global", ".", "plugins", "[", "id", "]", ")", ";", "}", "plugins", ".", "push", "(", "plugin", ")", ";", "descriptors", ".", "push", "(", "{", "plugin", ":", "plugin", ",", "options", ":", "opts", "||", "{", "}", "}", ")", ";", "}", ")", ";", "cache", ".", "descriptors", "=", "descriptors", ";", "cache", ".", "id", "=", "this", ".", "_cacheId", ";", "return", "descriptors", ";", "}" ]
Returns descriptors of enabled plugins for the given chart. @returns {object[]} [{ plugin, options }] @private
[ "Returns", "descriptors", "of", "enabled", "plugins", "for", "the", "given", "chart", "." ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/core/core.plugins.js#L123-L160
train
chartjs/Chart.js
src/elements/element.rectangle.js
getBarBounds
function getBarBounds(vm) { var x1, x2, y1, y2, half; if (isVertical(vm)) { half = vm.width / 2; x1 = vm.x - half; x2 = vm.x + half; y1 = Math.min(vm.y, vm.base); y2 = Math.max(vm.y, vm.base); } else { half = vm.height / 2; x1 = Math.min(vm.x, vm.base); x2 = Math.max(vm.x, vm.base); y1 = vm.y - half; y2 = vm.y + half; } return { left: x1, top: y1, right: x2, bottom: y2 }; }
javascript
function getBarBounds(vm) { var x1, x2, y1, y2, half; if (isVertical(vm)) { half = vm.width / 2; x1 = vm.x - half; x2 = vm.x + half; y1 = Math.min(vm.y, vm.base); y2 = Math.max(vm.y, vm.base); } else { half = vm.height / 2; x1 = Math.min(vm.x, vm.base); x2 = Math.max(vm.x, vm.base); y1 = vm.y - half; y2 = vm.y + half; } return { left: x1, top: y1, right: x2, bottom: y2 }; }
[ "function", "getBarBounds", "(", "vm", ")", "{", "var", "x1", ",", "x2", ",", "y1", ",", "y2", ",", "half", ";", "if", "(", "isVertical", "(", "vm", ")", ")", "{", "half", "=", "vm", ".", "width", "/", "2", ";", "x1", "=", "vm", ".", "x", "-", "half", ";", "x2", "=", "vm", ".", "x", "+", "half", ";", "y1", "=", "Math", ".", "min", "(", "vm", ".", "y", ",", "vm", ".", "base", ")", ";", "y2", "=", "Math", ".", "max", "(", "vm", ".", "y", ",", "vm", ".", "base", ")", ";", "}", "else", "{", "half", "=", "vm", ".", "height", "/", "2", ";", "x1", "=", "Math", ".", "min", "(", "vm", ".", "x", ",", "vm", ".", "base", ")", ";", "x2", "=", "Math", ".", "max", "(", "vm", ".", "x", ",", "vm", ".", "base", ")", ";", "y1", "=", "vm", ".", "y", "-", "half", ";", "y2", "=", "vm", ".", "y", "+", "half", ";", "}", "return", "{", "left", ":", "x1", ",", "top", ":", "y1", ",", "right", ":", "x2", ",", "bottom", ":", "y2", "}", ";", "}" ]
Helper function to get the bounds of the bar regardless of the orientation @param bar {Chart.Element.Rectangle} the bar @return {Bounds} bounds of the bar @private
[ "Helper", "function", "to", "get", "the", "bounds", "of", "the", "bar", "regardless", "of", "the", "orientation" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/elements/element.rectangle.js#L30-L53
train
chartjs/Chart.js
src/scales/scale.radialLinear.js
fitWithPointLabels
function fitWithPointLabels(scale) { // Right, this is really confusing and there is a lot of maths going on here // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9 // // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif // // Solution: // // We assume the radius of the polygon is half the size of the canvas at first // at each index we check if the text overlaps. // // Where it does, we store that angle and that index. // // After finding the largest index and angle we calculate how much we need to remove // from the shape radius to move the point inwards by that x. // // We average the left and right distances to get the maximum shape radius that can fit in the box // along with labels. // // Once we have that, we can find the centre point for the chart, by taking the x text protrusion // on each side, removing that from the size, halving it and adding the left x protrusion width. // // This will mean we have a shape fitted to the canvas, as large as it can be with the labels // and position it in the most space efficient manner // // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif var plFont = helpers.options._parseFont(scale.options.pointLabels); // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points var furthestLimits = { l: 0, r: scale.width, t: 0, b: scale.height - scale.paddingTop }; var furthestAngles = {}; var i, textSize, pointPosition; scale.ctx.font = plFont.string; scale._pointLabelSizes = []; var valueCount = getValueCount(scale); for (i = 0; i < valueCount; i++) { pointPosition = scale.getPointPosition(i, scale.drawingArea + 5); textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i] || ''); scale._pointLabelSizes[i] = textSize; // Add quarter circle to make degree 0 mean top of circle var angleRadians = scale.getIndexAngle(i); var angle = helpers.toDegrees(angleRadians) % 360; var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180); var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270); if (hLimits.start < furthestLimits.l) { furthestLimits.l = hLimits.start; furthestAngles.l = angleRadians; } if (hLimits.end > furthestLimits.r) { furthestLimits.r = hLimits.end; furthestAngles.r = angleRadians; } if (vLimits.start < furthestLimits.t) { furthestLimits.t = vLimits.start; furthestAngles.t = angleRadians; } if (vLimits.end > furthestLimits.b) { furthestLimits.b = vLimits.end; furthestAngles.b = angleRadians; } } scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles); }
javascript
function fitWithPointLabels(scale) { // Right, this is really confusing and there is a lot of maths going on here // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9 // // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif // // Solution: // // We assume the radius of the polygon is half the size of the canvas at first // at each index we check if the text overlaps. // // Where it does, we store that angle and that index. // // After finding the largest index and angle we calculate how much we need to remove // from the shape radius to move the point inwards by that x. // // We average the left and right distances to get the maximum shape radius that can fit in the box // along with labels. // // Once we have that, we can find the centre point for the chart, by taking the x text protrusion // on each side, removing that from the size, halving it and adding the left x protrusion width. // // This will mean we have a shape fitted to the canvas, as large as it can be with the labels // and position it in the most space efficient manner // // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif var plFont = helpers.options._parseFont(scale.options.pointLabels); // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points var furthestLimits = { l: 0, r: scale.width, t: 0, b: scale.height - scale.paddingTop }; var furthestAngles = {}; var i, textSize, pointPosition; scale.ctx.font = plFont.string; scale._pointLabelSizes = []; var valueCount = getValueCount(scale); for (i = 0; i < valueCount; i++) { pointPosition = scale.getPointPosition(i, scale.drawingArea + 5); textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i] || ''); scale._pointLabelSizes[i] = textSize; // Add quarter circle to make degree 0 mean top of circle var angleRadians = scale.getIndexAngle(i); var angle = helpers.toDegrees(angleRadians) % 360; var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180); var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270); if (hLimits.start < furthestLimits.l) { furthestLimits.l = hLimits.start; furthestAngles.l = angleRadians; } if (hLimits.end > furthestLimits.r) { furthestLimits.r = hLimits.end; furthestAngles.r = angleRadians; } if (vLimits.start < furthestLimits.t) { furthestLimits.t = vLimits.start; furthestAngles.t = angleRadians; } if (vLimits.end > furthestLimits.b) { furthestLimits.b = vLimits.end; furthestAngles.b = angleRadians; } } scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles); }
[ "function", "fitWithPointLabels", "(", "scale", ")", "{", "var", "plFont", "=", "helpers", ".", "options", ".", "_parseFont", "(", "scale", ".", "options", ".", "pointLabels", ")", ";", "var", "furthestLimits", "=", "{", "l", ":", "0", ",", "r", ":", "scale", ".", "width", ",", "t", ":", "0", ",", "b", ":", "scale", ".", "height", "-", "scale", ".", "paddingTop", "}", ";", "var", "furthestAngles", "=", "{", "}", ";", "var", "i", ",", "textSize", ",", "pointPosition", ";", "scale", ".", "ctx", ".", "font", "=", "plFont", ".", "string", ";", "scale", ".", "_pointLabelSizes", "=", "[", "]", ";", "var", "valueCount", "=", "getValueCount", "(", "scale", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "valueCount", ";", "i", "++", ")", "{", "pointPosition", "=", "scale", ".", "getPointPosition", "(", "i", ",", "scale", ".", "drawingArea", "+", "5", ")", ";", "textSize", "=", "measureLabelSize", "(", "scale", ".", "ctx", ",", "plFont", ".", "lineHeight", ",", "scale", ".", "pointLabels", "[", "i", "]", "||", "''", ")", ";", "scale", ".", "_pointLabelSizes", "[", "i", "]", "=", "textSize", ";", "var", "angleRadians", "=", "scale", ".", "getIndexAngle", "(", "i", ")", ";", "var", "angle", "=", "helpers", ".", "toDegrees", "(", "angleRadians", ")", "%", "360", ";", "var", "hLimits", "=", "determineLimits", "(", "angle", ",", "pointPosition", ".", "x", ",", "textSize", ".", "w", ",", "0", ",", "180", ")", ";", "var", "vLimits", "=", "determineLimits", "(", "angle", ",", "pointPosition", ".", "y", ",", "textSize", ".", "h", ",", "90", ",", "270", ")", ";", "if", "(", "hLimits", ".", "start", "<", "furthestLimits", ".", "l", ")", "{", "furthestLimits", ".", "l", "=", "hLimits", ".", "start", ";", "furthestAngles", ".", "l", "=", "angleRadians", ";", "}", "if", "(", "hLimits", ".", "end", ">", "furthestLimits", ".", "r", ")", "{", "furthestLimits", ".", "r", "=", "hLimits", ".", "end", ";", "furthestAngles", ".", "r", "=", "angleRadians", ";", "}", "if", "(", "vLimits", ".", "start", "<", "furthestLimits", ".", "t", ")", "{", "furthestLimits", ".", "t", "=", "vLimits", ".", "start", ";", "furthestAngles", ".", "t", "=", "angleRadians", ";", "}", "if", "(", "vLimits", ".", "end", ">", "furthestLimits", ".", "b", ")", "{", "furthestLimits", ".", "b", "=", "vLimits", ".", "end", ";", "furthestAngles", ".", "b", "=", "angleRadians", ";", "}", "}", "scale", ".", "setReductions", "(", "scale", ".", "drawingArea", ",", "furthestLimits", ",", "furthestAngles", ")", ";", "}" ]
Helper function to fit a radial linear scale with point labels
[ "Helper", "function", "to", "fit", "a", "radial", "linear", "scale", "with", "point", "labels" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/scales/scale.radialLinear.js#L112-L190
train
chartjs/Chart.js
src/scales/scale.radialLinear.js
function(largestPossibleRadius, furthestLimits, furthestAngles) { var me = this; var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l); var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r); var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t); var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b); radiusReductionLeft = numberOrZero(radiusReductionLeft); radiusReductionRight = numberOrZero(radiusReductionRight); radiusReductionTop = numberOrZero(radiusReductionTop); radiusReductionBottom = numberOrZero(radiusReductionBottom); me.drawingArea = Math.min( Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2), Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2)); me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom); }
javascript
function(largestPossibleRadius, furthestLimits, furthestAngles) { var me = this; var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l); var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r); var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t); var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b); radiusReductionLeft = numberOrZero(radiusReductionLeft); radiusReductionRight = numberOrZero(radiusReductionRight); radiusReductionTop = numberOrZero(radiusReductionTop); radiusReductionBottom = numberOrZero(radiusReductionBottom); me.drawingArea = Math.min( Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2), Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2)); me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom); }
[ "function", "(", "largestPossibleRadius", ",", "furthestLimits", ",", "furthestAngles", ")", "{", "var", "me", "=", "this", ";", "var", "radiusReductionLeft", "=", "furthestLimits", ".", "l", "/", "Math", ".", "sin", "(", "furthestAngles", ".", "l", ")", ";", "var", "radiusReductionRight", "=", "Math", ".", "max", "(", "furthestLimits", ".", "r", "-", "me", ".", "width", ",", "0", ")", "/", "Math", ".", "sin", "(", "furthestAngles", ".", "r", ")", ";", "var", "radiusReductionTop", "=", "-", "furthestLimits", ".", "t", "/", "Math", ".", "cos", "(", "furthestAngles", ".", "t", ")", ";", "var", "radiusReductionBottom", "=", "-", "Math", ".", "max", "(", "furthestLimits", ".", "b", "-", "(", "me", ".", "height", "-", "me", ".", "paddingTop", ")", ",", "0", ")", "/", "Math", ".", "cos", "(", "furthestAngles", ".", "b", ")", ";", "radiusReductionLeft", "=", "numberOrZero", "(", "radiusReductionLeft", ")", ";", "radiusReductionRight", "=", "numberOrZero", "(", "radiusReductionRight", ")", ";", "radiusReductionTop", "=", "numberOrZero", "(", "radiusReductionTop", ")", ";", "radiusReductionBottom", "=", "numberOrZero", "(", "radiusReductionBottom", ")", ";", "me", ".", "drawingArea", "=", "Math", ".", "min", "(", "Math", ".", "floor", "(", "largestPossibleRadius", "-", "(", "radiusReductionLeft", "+", "radiusReductionRight", ")", "/", "2", ")", ",", "Math", ".", "floor", "(", "largestPossibleRadius", "-", "(", "radiusReductionTop", "+", "radiusReductionBottom", ")", "/", "2", ")", ")", ";", "me", ".", "setCenterPoint", "(", "radiusReductionLeft", ",", "radiusReductionRight", ",", "radiusReductionTop", ",", "radiusReductionBottom", ")", ";", "}" ]
Set radius reductions and determine new radius and center point @private
[ "Set", "radius", "reductions", "and", "determine", "new", "radius", "and", "center", "point" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/scales/scale.radialLinear.js#L396-L412
train
chartjs/Chart.js
src/controllers/controller.doughnut.js
function(datasetIndex) { var ringWeightOffset = 0; for (var i = 0; i < datasetIndex; ++i) { if (this.chart.isDatasetVisible(i)) { ringWeightOffset += this._getRingWeight(i); } } return ringWeightOffset; }
javascript
function(datasetIndex) { var ringWeightOffset = 0; for (var i = 0; i < datasetIndex; ++i) { if (this.chart.isDatasetVisible(i)) { ringWeightOffset += this._getRingWeight(i); } } return ringWeightOffset; }
[ "function", "(", "datasetIndex", ")", "{", "var", "ringWeightOffset", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "datasetIndex", ";", "++", "i", ")", "{", "if", "(", "this", ".", "chart", ".", "isDatasetVisible", "(", "i", ")", ")", "{", "ringWeightOffset", "+=", "this", ".", "_getRingWeight", "(", "i", ")", ";", "}", "}", "return", "ringWeightOffset", ";", "}" ]
Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly @private
[ "Get", "radius", "length", "offset", "of", "the", "dataset", "in", "relation", "to", "the", "visible", "datasets", "weights", ".", "This", "allows", "determining", "the", "inner", "and", "outer", "radius", "correctly" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/controllers/controller.doughnut.js#L401-L411
train
chartjs/Chart.js
src/scales/scale.time.js
determineUnitForAutoTicks
function determineUnitForAutoTicks(minUnit, min, max, capacity) { var ilen = UNITS.length; var i, interval, factor; for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) { interval = INTERVALS[UNITS[i]]; factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER; if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) { return UNITS[i]; } } return UNITS[ilen - 1]; }
javascript
function determineUnitForAutoTicks(minUnit, min, max, capacity) { var ilen = UNITS.length; var i, interval, factor; for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) { interval = INTERVALS[UNITS[i]]; factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER; if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) { return UNITS[i]; } } return UNITS[ilen - 1]; }
[ "function", "determineUnitForAutoTicks", "(", "minUnit", ",", "min", ",", "max", ",", "capacity", ")", "{", "var", "ilen", "=", "UNITS", ".", "length", ";", "var", "i", ",", "interval", ",", "factor", ";", "for", "(", "i", "=", "UNITS", ".", "indexOf", "(", "minUnit", ")", ";", "i", "<", "ilen", "-", "1", ";", "++", "i", ")", "{", "interval", "=", "INTERVALS", "[", "UNITS", "[", "i", "]", "]", ";", "factor", "=", "interval", ".", "steps", "?", "interval", ".", "steps", "[", "interval", ".", "steps", ".", "length", "-", "1", "]", ":", "MAX_INTEGER", ";", "if", "(", "interval", ".", "common", "&&", "Math", ".", "ceil", "(", "(", "max", "-", "min", ")", "/", "(", "factor", "*", "interval", ".", "size", ")", ")", "<=", "capacity", ")", "{", "return", "UNITS", "[", "i", "]", ";", "}", "}", "return", "UNITS", "[", "ilen", "-", "1", "]", ";", "}" ]
Figures out what unit results in an appropriate number of auto-generated ticks
[ "Figures", "out", "what", "unit", "results", "in", "an", "appropriate", "number", "of", "auto", "-", "generated", "ticks" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/scales/scale.time.js#L278-L292
train
chartjs/Chart.js
src/scales/scale.time.js
determineUnitForFormatting
function determineUnitForFormatting(scale, ticks, minUnit, min, max) { var ilen = UNITS.length; var i, unit; for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) { unit = UNITS[i]; if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= ticks.length) { return unit; } } return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0]; }
javascript
function determineUnitForFormatting(scale, ticks, minUnit, min, max) { var ilen = UNITS.length; var i, unit; for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) { unit = UNITS[i]; if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= ticks.length) { return unit; } } return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0]; }
[ "function", "determineUnitForFormatting", "(", "scale", ",", "ticks", ",", "minUnit", ",", "min", ",", "max", ")", "{", "var", "ilen", "=", "UNITS", ".", "length", ";", "var", "i", ",", "unit", ";", "for", "(", "i", "=", "ilen", "-", "1", ";", "i", ">=", "UNITS", ".", "indexOf", "(", "minUnit", ")", ";", "i", "--", ")", "{", "unit", "=", "UNITS", "[", "i", "]", ";", "if", "(", "INTERVALS", "[", "unit", "]", ".", "common", "&&", "scale", ".", "_adapter", ".", "diff", "(", "max", ",", "min", ",", "unit", ")", ">=", "ticks", ".", "length", ")", "{", "return", "unit", ";", "}", "}", "return", "UNITS", "[", "minUnit", "?", "UNITS", ".", "indexOf", "(", "minUnit", ")", ":", "0", "]", ";", "}" ]
Figures out what unit to format a set of ticks with
[ "Figures", "out", "what", "unit", "to", "format", "a", "set", "of", "ticks", "with" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/scales/scale.time.js#L297-L309
train
chartjs/Chart.js
src/core/core.scale.js
function() { var me = this; if (me.margins) { me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0); me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0); me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0); me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0); } }
javascript
function() { var me = this; if (me.margins) { me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0); me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0); me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0); me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0); } }
[ "function", "(", ")", "{", "var", "me", "=", "this", ";", "if", "(", "me", ".", "margins", ")", "{", "me", ".", "paddingLeft", "=", "Math", ".", "max", "(", "me", ".", "paddingLeft", "-", "me", ".", "margins", ".", "left", ",", "0", ")", ";", "me", ".", "paddingTop", "=", "Math", ".", "max", "(", "me", ".", "paddingTop", "-", "me", ".", "margins", ".", "top", ",", "0", ")", ";", "me", ".", "paddingRight", "=", "Math", ".", "max", "(", "me", ".", "paddingRight", "-", "me", ".", "margins", ".", "right", ",", "0", ")", ";", "me", ".", "paddingBottom", "=", "Math", ".", "max", "(", "me", ".", "paddingBottom", "-", "me", ".", "margins", ".", "bottom", ",", "0", ")", ";", "}", "}" ]
Handle margins and padding interactions @private
[ "Handle", "margins", "and", "padding", "interactions" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/core/core.scale.js#L556-L564
train
chartjs/Chart.js
src/core/core.scale.js
function(ticks) { var me = this; var isHorizontal = me.isHorizontal(); var optionTicks = me.options.ticks; var tickCount = ticks.length; var skipRatio = false; var maxTicks = optionTicks.maxTicksLimit; // Total space needed to display all ticks. First and last ticks are // drawn as their center at end of axis, so tickCount-1 var ticksLength = me._tickSize() * (tickCount - 1); // Axis length var axisLength = isHorizontal ? me.width - (me.paddingLeft + me.paddingRight) : me.height - (me.paddingTop + me.PaddingBottom); var result = []; var i, tick; if (ticksLength > axisLength) { skipRatio = 1 + Math.floor(ticksLength / axisLength); } // if they defined a max number of optionTicks, // increase skipRatio until that number is met if (tickCount > maxTicks) { skipRatio = Math.max(skipRatio, 1 + Math.floor(tickCount / maxTicks)); } for (i = 0; i < tickCount; i++) { tick = ticks[i]; if (skipRatio > 1 && i % skipRatio > 0) { // leave tick in place but make sure it's not displayed (#4635) delete tick.label; } result.push(tick); } return result; }
javascript
function(ticks) { var me = this; var isHorizontal = me.isHorizontal(); var optionTicks = me.options.ticks; var tickCount = ticks.length; var skipRatio = false; var maxTicks = optionTicks.maxTicksLimit; // Total space needed to display all ticks. First and last ticks are // drawn as their center at end of axis, so tickCount-1 var ticksLength = me._tickSize() * (tickCount - 1); // Axis length var axisLength = isHorizontal ? me.width - (me.paddingLeft + me.paddingRight) : me.height - (me.paddingTop + me.PaddingBottom); var result = []; var i, tick; if (ticksLength > axisLength) { skipRatio = 1 + Math.floor(ticksLength / axisLength); } // if they defined a max number of optionTicks, // increase skipRatio until that number is met if (tickCount > maxTicks) { skipRatio = Math.max(skipRatio, 1 + Math.floor(tickCount / maxTicks)); } for (i = 0; i < tickCount; i++) { tick = ticks[i]; if (skipRatio > 1 && i % skipRatio > 0) { // leave tick in place but make sure it's not displayed (#4635) delete tick.label; } result.push(tick); } return result; }
[ "function", "(", "ticks", ")", "{", "var", "me", "=", "this", ";", "var", "isHorizontal", "=", "me", ".", "isHorizontal", "(", ")", ";", "var", "optionTicks", "=", "me", ".", "options", ".", "ticks", ";", "var", "tickCount", "=", "ticks", ".", "length", ";", "var", "skipRatio", "=", "false", ";", "var", "maxTicks", "=", "optionTicks", ".", "maxTicksLimit", ";", "var", "ticksLength", "=", "me", ".", "_tickSize", "(", ")", "*", "(", "tickCount", "-", "1", ")", ";", "var", "axisLength", "=", "isHorizontal", "?", "me", ".", "width", "-", "(", "me", ".", "paddingLeft", "+", "me", ".", "paddingRight", ")", ":", "me", ".", "height", "-", "(", "me", ".", "paddingTop", "+", "me", ".", "PaddingBottom", ")", ";", "var", "result", "=", "[", "]", ";", "var", "i", ",", "tick", ";", "if", "(", "ticksLength", ">", "axisLength", ")", "{", "skipRatio", "=", "1", "+", "Math", ".", "floor", "(", "ticksLength", "/", "axisLength", ")", ";", "}", "if", "(", "tickCount", ">", "maxTicks", ")", "{", "skipRatio", "=", "Math", ".", "max", "(", "skipRatio", ",", "1", "+", "Math", ".", "floor", "(", "tickCount", "/", "maxTicks", ")", ")", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "tickCount", ";", "i", "++", ")", "{", "tick", "=", "ticks", "[", "i", "]", ";", "if", "(", "skipRatio", ">", "1", "&&", "i", "%", "skipRatio", ">", "0", ")", "{", "delete", "tick", ".", "label", ";", "}", "result", ".", "push", "(", "tick", ")", ";", "}", "return", "result", ";", "}" ]
Returns a subset of ticks to be plotted to avoid overlapping labels. @private
[ "Returns", "a", "subset", "of", "ticks", "to", "be", "plotted", "to", "avoid", "overlapping", "labels", "." ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/core/core.scale.js#L690-L730
train
chartjs/Chart.js
src/core/core.datasetController.js
function() { var me = this; me._config = helpers.merge({}, [ me.chart.options.datasets[me._type], me.getDataset(), ], { merger: function(key, target, source) { if (key !== '_meta' && key !== 'data') { helpers._merger(key, target, source); } } }); }
javascript
function() { var me = this; me._config = helpers.merge({}, [ me.chart.options.datasets[me._type], me.getDataset(), ], { merger: function(key, target, source) { if (key !== '_meta' && key !== 'data') { helpers._merger(key, target, source); } } }); }
[ "function", "(", ")", "{", "var", "me", "=", "this", ";", "me", ".", "_config", "=", "helpers", ".", "merge", "(", "{", "}", ",", "[", "me", ".", "chart", ".", "options", ".", "datasets", "[", "me", ".", "_type", "]", ",", "me", ".", "getDataset", "(", ")", ",", "]", ",", "{", "merger", ":", "function", "(", "key", ",", "target", ",", "source", ")", "{", "if", "(", "key", "!==", "'_meta'", "&&", "key", "!==", "'data'", ")", "{", "helpers", ".", "_merger", "(", "key", ",", "target", ",", "source", ")", ";", "}", "}", "}", ")", ";", "}" ]
Returns the merged user-supplied and default dataset-level options @private
[ "Returns", "the", "merged", "user", "-", "supplied", "and", "default", "dataset", "-", "level", "options" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/core/core.datasetController.js#L244-L256
train
chartjs/Chart.js
src/helpers/helpers.core.js
function(value, index, defaultValue) { return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue); }
javascript
function(value, index, defaultValue) { return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue); }
[ "function", "(", "value", ",", "index", ",", "defaultValue", ")", "{", "return", "helpers", ".", "valueOrDefault", "(", "helpers", ".", "isArray", "(", "value", ")", "?", "value", "[", "index", "]", ":", "value", ",", "defaultValue", ")", ";", "}" ]
Returns value at the given `index` in array if defined, else returns `defaultValue`. @param {Array} value - The array to lookup for value at `index`. @param {number} index - The index in `value` to lookup for value. @param {*} defaultValue - The value to return if `value[index]` is undefined. @returns {*}
[ "Returns", "value", "at", "the", "given", "index", "in", "array", "if", "defined", "else", "returns", "defaultValue", "." ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/helpers/helpers.core.js#L87-L89
train
chartjs/Chart.js
src/helpers/helpers.core.js
function(fn, args, thisArg) { if (fn && typeof fn.call === 'function') { return fn.apply(thisArg, args); } }
javascript
function(fn, args, thisArg) { if (fn && typeof fn.call === 'function') { return fn.apply(thisArg, args); } }
[ "function", "(", "fn", ",", "args", ",", "thisArg", ")", "{", "if", "(", "fn", "&&", "typeof", "fn", ".", "call", "===", "'function'", ")", "{", "return", "fn", ".", "apply", "(", "thisArg", ",", "args", ")", ";", "}", "}" ]
Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the value returned by `fn`. If `fn` is not a function, this method returns undefined. @param {function} fn - The function to call. @param {Array|undefined|null} args - The arguments with which `fn` should be called. @param {object} [thisArg] - The value of `this` provided for the call to `fn`. @returns {*}
[ "Calls", "fn", "with", "the", "given", "args", "in", "the", "scope", "defined", "by", "thisArg", "and", "returns", "the", "value", "returned", "by", "fn", ".", "If", "fn", "is", "not", "a", "function", "this", "method", "returns", "undefined", "." ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/helpers/helpers.core.js#L99-L103
train
chartjs/Chart.js
src/helpers/helpers.core.js
function(a0, a1) { var i, ilen, v0, v1; if (!a0 || !a1 || a0.length !== a1.length) { return false; } for (i = 0, ilen = a0.length; i < ilen; ++i) { v0 = a0[i]; v1 = a1[i]; if (v0 instanceof Array && v1 instanceof Array) { if (!helpers.arrayEquals(v0, v1)) { return false; } } else if (v0 !== v1) { // NOTE: two different object instances will never be equal: {x:20} != {x:20} return false; } } return true; }
javascript
function(a0, a1) { var i, ilen, v0, v1; if (!a0 || !a1 || a0.length !== a1.length) { return false; } for (i = 0, ilen = a0.length; i < ilen; ++i) { v0 = a0[i]; v1 = a1[i]; if (v0 instanceof Array && v1 instanceof Array) { if (!helpers.arrayEquals(v0, v1)) { return false; } } else if (v0 !== v1) { // NOTE: two different object instances will never be equal: {x:20} != {x:20} return false; } } return true; }
[ "function", "(", "a0", ",", "a1", ")", "{", "var", "i", ",", "ilen", ",", "v0", ",", "v1", ";", "if", "(", "!", "a0", "||", "!", "a1", "||", "a0", ".", "length", "!==", "a1", ".", "length", ")", "{", "return", "false", ";", "}", "for", "(", "i", "=", "0", ",", "ilen", "=", "a0", ".", "length", ";", "i", "<", "ilen", ";", "++", "i", ")", "{", "v0", "=", "a0", "[", "i", "]", ";", "v1", "=", "a1", "[", "i", "]", ";", "if", "(", "v0", "instanceof", "Array", "&&", "v1", "instanceof", "Array", ")", "{", "if", "(", "!", "helpers", ".", "arrayEquals", "(", "v0", ",", "v1", ")", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "v0", "!==", "v1", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Returns true if the `a0` and `a1` arrays have the same content, else returns false. @see https://stackoverflow.com/a/14853974 @param {Array} a0 - The array to compare @param {Array} a1 - The array to compare @returns {boolean}
[ "Returns", "true", "if", "the", "a0", "and", "a1", "arrays", "have", "the", "same", "content", "else", "returns", "false", "." ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/helpers/helpers.core.js#L143-L165
train
chartjs/Chart.js
src/helpers/helpers.core.js
function(source) { if (helpers.isArray(source)) { return source.map(helpers.clone); } if (helpers.isObject(source)) { var target = {}; var keys = Object.keys(source); var klen = keys.length; var k = 0; for (; k < klen; ++k) { target[keys[k]] = helpers.clone(source[keys[k]]); } return target; } return source; }
javascript
function(source) { if (helpers.isArray(source)) { return source.map(helpers.clone); } if (helpers.isObject(source)) { var target = {}; var keys = Object.keys(source); var klen = keys.length; var k = 0; for (; k < klen; ++k) { target[keys[k]] = helpers.clone(source[keys[k]]); } return target; } return source; }
[ "function", "(", "source", ")", "{", "if", "(", "helpers", ".", "isArray", "(", "source", ")", ")", "{", "return", "source", ".", "map", "(", "helpers", ".", "clone", ")", ";", "}", "if", "(", "helpers", ".", "isObject", "(", "source", ")", ")", "{", "var", "target", "=", "{", "}", ";", "var", "keys", "=", "Object", ".", "keys", "(", "source", ")", ";", "var", "klen", "=", "keys", ".", "length", ";", "var", "k", "=", "0", ";", "for", "(", ";", "k", "<", "klen", ";", "++", "k", ")", "{", "target", "[", "keys", "[", "k", "]", "]", "=", "helpers", ".", "clone", "(", "source", "[", "keys", "[", "k", "]", "]", ")", ";", "}", "return", "target", ";", "}", "return", "source", ";", "}" ]
Returns a deep copy of `source` without keeping references on objects and arrays. @param {*} source - The value to clone. @returns {*}
[ "Returns", "a", "deep", "copy", "of", "source", "without", "keeping", "references", "on", "objects", "and", "arrays", "." ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/helpers/helpers.core.js#L172-L191
train
chartjs/Chart.js
src/scales/scale.category.js
function() { var data = this.chart.data; return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels; }
javascript
function() { var data = this.chart.data; return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels; }
[ "function", "(", ")", "{", "var", "data", "=", "this", ".", "chart", ".", "data", ";", "return", "this", ".", "options", ".", "labels", "||", "(", "this", ".", "isHorizontal", "(", ")", "?", "data", ".", "xLabels", ":", "data", ".", "yLabels", ")", "||", "data", ".", "labels", ";", "}" ]
Internal function to get the correct labels. If data.xLabels or data.yLabels are defined, use those else fall back to data.labels @private
[ "Internal", "function", "to", "get", "the", "correct", "labels", ".", "If", "data", ".", "xLabels", "or", "data", ".", "yLabels", "are", "defined", "use", "those", "else", "fall", "back", "to", "data", ".", "labels" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/scales/scale.category.js#L15-L18
train
chartjs/Chart.js
src/plugins/plugin.legend.js
function(e, legendItem) { var index = legendItem.datasetIndex; var ci = this.chart; var meta = ci.getDatasetMeta(index); // See controller.isDatasetVisible comment meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null; // We hid a dataset ... rerender the chart ci.update(); }
javascript
function(e, legendItem) { var index = legendItem.datasetIndex; var ci = this.chart; var meta = ci.getDatasetMeta(index); // See controller.isDatasetVisible comment meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null; // We hid a dataset ... rerender the chart ci.update(); }
[ "function", "(", "e", ",", "legendItem", ")", "{", "var", "index", "=", "legendItem", ".", "datasetIndex", ";", "var", "ci", "=", "this", ".", "chart", ";", "var", "meta", "=", "ci", ".", "getDatasetMeta", "(", "index", ")", ";", "meta", ".", "hidden", "=", "meta", ".", "hidden", "===", "null", "?", "!", "ci", ".", "data", ".", "datasets", "[", "index", "]", ".", "hidden", ":", "null", ";", "ci", ".", "update", "(", ")", ";", "}" ]
a callback that will handle
[ "a", "callback", "that", "will", "handle" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/plugins/plugin.legend.js#L21-L31
train
chartjs/Chart.js
src/plugins/plugin.legend.js
getBoxWidth
function getBoxWidth(labelOpts, fontSize) { return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ? fontSize : labelOpts.boxWidth; }
javascript
function getBoxWidth(labelOpts, fontSize) { return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ? fontSize : labelOpts.boxWidth; }
[ "function", "getBoxWidth", "(", "labelOpts", ",", "fontSize", ")", "{", "return", "labelOpts", ".", "usePointStyle", "&&", "labelOpts", ".", "boxWidth", ">", "fontSize", "?", "fontSize", ":", "labelOpts", ".", "boxWidth", ";", "}" ]
Helper function to get the box width based on the usePointStyle option @param {object} labelopts - the label options on the legend @param {number} fontSize - the label font size @return {number} width of the color box area
[ "Helper", "function", "to", "get", "the", "box", "width", "based", "on", "the", "usePointStyle", "option" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/plugins/plugin.legend.js#L94-L98
train
chartjs/Chart.js
src/core/core.interaction.js
getNearestItems
function getNearestItems(chart, position, intersect, distanceMetric) { var minDistance = Number.POSITIVE_INFINITY; var nearestItems = []; parseVisibleItems(chart, function(element) { if (intersect && !element.inRange(position.x, position.y)) { return; } var center = element.getCenterPoint(); var distance = distanceMetric(position, center); if (distance < minDistance) { nearestItems = [element]; minDistance = distance; } else if (distance === minDistance) { // Can have multiple items at the same distance in which case we sort by size nearestItems.push(element); } }); return nearestItems; }
javascript
function getNearestItems(chart, position, intersect, distanceMetric) { var minDistance = Number.POSITIVE_INFINITY; var nearestItems = []; parseVisibleItems(chart, function(element) { if (intersect && !element.inRange(position.x, position.y)) { return; } var center = element.getCenterPoint(); var distance = distanceMetric(position, center); if (distance < minDistance) { nearestItems = [element]; minDistance = distance; } else if (distance === minDistance) { // Can have multiple items at the same distance in which case we sort by size nearestItems.push(element); } }); return nearestItems; }
[ "function", "getNearestItems", "(", "chart", ",", "position", ",", "intersect", ",", "distanceMetric", ")", "{", "var", "minDistance", "=", "Number", ".", "POSITIVE_INFINITY", ";", "var", "nearestItems", "=", "[", "]", ";", "parseVisibleItems", "(", "chart", ",", "function", "(", "element", ")", "{", "if", "(", "intersect", "&&", "!", "element", ".", "inRange", "(", "position", ".", "x", ",", "position", ".", "y", ")", ")", "{", "return", ";", "}", "var", "center", "=", "element", ".", "getCenterPoint", "(", ")", ";", "var", "distance", "=", "distanceMetric", "(", "position", ",", "center", ")", ";", "if", "(", "distance", "<", "minDistance", ")", "{", "nearestItems", "=", "[", "element", "]", ";", "minDistance", "=", "distance", ";", "}", "else", "if", "(", "distance", "===", "minDistance", ")", "{", "nearestItems", ".", "push", "(", "element", ")", ";", "}", "}", ")", ";", "return", "nearestItems", ";", "}" ]
Helper function to get the items nearest to the event position considering all visible items in teh chart @param {Chart} chart - the chart to look at elements from @param {object} position - the point to be nearest to @param {boolean} intersect - if true, only consider items that intersect the position @param {function} distanceMetric - function to provide the distance between points @return {ChartElement[]} the nearest items
[ "Helper", "function", "to", "get", "the", "items", "nearest", "to", "the", "event", "position", "considering", "all", "visible", "items", "in", "teh", "chart" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/core/core.interaction.js#L72-L93
train
chartjs/Chart.js
src/core/core.interaction.js
getDistanceMetricForAxis
function getDistanceMetricForAxis(axis) { var useX = axis.indexOf('x') !== -1; var useY = axis.indexOf('y') !== -1; return function(pt1, pt2) { var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0; var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0; return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); }; }
javascript
function getDistanceMetricForAxis(axis) { var useX = axis.indexOf('x') !== -1; var useY = axis.indexOf('y') !== -1; return function(pt1, pt2) { var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0; var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0; return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); }; }
[ "function", "getDistanceMetricForAxis", "(", "axis", ")", "{", "var", "useX", "=", "axis", ".", "indexOf", "(", "'x'", ")", "!==", "-", "1", ";", "var", "useY", "=", "axis", ".", "indexOf", "(", "'y'", ")", "!==", "-", "1", ";", "return", "function", "(", "pt1", ",", "pt2", ")", "{", "var", "deltaX", "=", "useX", "?", "Math", ".", "abs", "(", "pt1", ".", "x", "-", "pt2", ".", "x", ")", ":", "0", ";", "var", "deltaY", "=", "useY", "?", "Math", ".", "abs", "(", "pt1", ".", "y", "-", "pt2", ".", "y", ")", ":", "0", ";", "return", "Math", ".", "sqrt", "(", "Math", ".", "pow", "(", "deltaX", ",", "2", ")", "+", "Math", ".", "pow", "(", "deltaY", ",", "2", ")", ")", ";", "}", ";", "}" ]
Get a distance metric function for two points based on the axis mode setting @param {string} axis - the axis mode. x|y|xy
[ "Get", "a", "distance", "metric", "function", "for", "two", "points", "based", "on", "the", "axis", "mode", "setting" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/core/core.interaction.js#L100-L109
train
chartjs/Chart.js
src/core/core.interaction.js
function(chart, e, options) { var position = getRelativePosition(e, chart); options.axis = options.axis || 'xy'; var distanceMetric = getDistanceMetricForAxis(options.axis); return getNearestItems(chart, position, options.intersect, distanceMetric); }
javascript
function(chart, e, options) { var position = getRelativePosition(e, chart); options.axis = options.axis || 'xy'; var distanceMetric = getDistanceMetricForAxis(options.axis); return getNearestItems(chart, position, options.intersect, distanceMetric); }
[ "function", "(", "chart", ",", "e", ",", "options", ")", "{", "var", "position", "=", "getRelativePosition", "(", "e", ",", "chart", ")", ";", "options", ".", "axis", "=", "options", ".", "axis", "||", "'xy'", ";", "var", "distanceMetric", "=", "getDistanceMetricForAxis", "(", "options", ".", "axis", ")", ";", "return", "getNearestItems", "(", "chart", ",", "position", ",", "options", ".", "intersect", ",", "distanceMetric", ")", ";", "}" ]
nearest mode returns the element closest to the point @function Chart.Interaction.modes.intersect @param {Chart} chart - the chart we are returning items from @param {Event} e - the event we are find things at @param {IInteractionOptions} options - options to use @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
[ "nearest", "mode", "returns", "the", "element", "closest", "to", "the", "point" ]
f093c36574d290330ed623e60fbd070421c730d5
https://github.com/chartjs/Chart.js/blob/f093c36574d290330ed623e60fbd070421c730d5/src/core/core.interaction.js#L241-L246
train
google/material-design-icons
gulpfile.babel.js
generateIjmap
function generateIjmap(ijmapPath) { return through2.obj((codepointsFile, encoding, callback) => { const ijmap = { icons: codepointsToIjmap(codepointsFile.contents.toString()) }; callback(null, new File({ path: ijmapPath, contents: new Buffer(JSON.stringify(ijmap), 'utf8') })); function codepointsToIjmap(codepoints) { return _(codepoints) .split('\n') // split into lines .reject(_.isEmpty) // remove empty lines .reduce((codepointMap, line) => { // build up the codepoint map let [ name, codepoint ] = line.split(' '); codepointMap[codepoint] = { name: titleize(humanize(name)) }; return codepointMap; }, {}); } }); }
javascript
function generateIjmap(ijmapPath) { return through2.obj((codepointsFile, encoding, callback) => { const ijmap = { icons: codepointsToIjmap(codepointsFile.contents.toString()) }; callback(null, new File({ path: ijmapPath, contents: new Buffer(JSON.stringify(ijmap), 'utf8') })); function codepointsToIjmap(codepoints) { return _(codepoints) .split('\n') // split into lines .reject(_.isEmpty) // remove empty lines .reduce((codepointMap, line) => { // build up the codepoint map let [ name, codepoint ] = line.split(' '); codepointMap[codepoint] = { name: titleize(humanize(name)) }; return codepointMap; }, {}); } }); }
[ "function", "generateIjmap", "(", "ijmapPath", ")", "{", "return", "through2", ".", "obj", "(", "(", "codepointsFile", ",", "encoding", ",", "callback", ")", "=>", "{", "const", "ijmap", "=", "{", "icons", ":", "codepointsToIjmap", "(", "codepointsFile", ".", "contents", ".", "toString", "(", ")", ")", "}", ";", "callback", "(", "null", ",", "new", "File", "(", "{", "path", ":", "ijmapPath", ",", "contents", ":", "new", "Buffer", "(", "JSON", ".", "stringify", "(", "ijmap", ")", ",", "'utf8'", ")", "}", ")", ")", ";", "function", "codepointsToIjmap", "(", "codepoints", ")", "{", "return", "_", "(", "codepoints", ")", ".", "split", "(", "'\\n'", ")", ".", "\\n", "reject", ".", "(", "_", ".", "isEmpty", ")", "reduce", ";", "}", "}", ")", ";", "}" ]
Returns a stream that transforms between our icon font's codepoint file and an Iconjar ijmap.
[ "Returns", "a", "stream", "that", "transforms", "between", "our", "icon", "font", "s", "codepoint", "file", "and", "an", "Iconjar", "ijmap", "." ]
224895a86501195e7a7ff3dde18e39f00b8e3d5a
https://github.com/google/material-design-icons/blob/224895a86501195e7a7ff3dde18e39f00b8e3d5a/gulpfile.babel.js#L94-L116
train
google/material-design-icons
gulpfile.babel.js
getSvgSpriteConfig
function getSvgSpriteConfig(category) { return { shape: { dimension: { maxWidth: 24, maxHeight: 24 }, }, mode: { css : { bust: false, dest: './', sprite: `./svg-sprite-${ category }.svg`, example: { dest: `./svg-sprite-${ category }.html` }, render: { css: { dest: `./svg-sprite-${ category }.css` } } }, symbol : { bust: false, dest: './', sprite: `./svg-sprite-${ category }-symbol.svg`, example: { dest: `./svg-sprite-${ category }-symbol.html` } } } }; }
javascript
function getSvgSpriteConfig(category) { return { shape: { dimension: { maxWidth: 24, maxHeight: 24 }, }, mode: { css : { bust: false, dest: './', sprite: `./svg-sprite-${ category }.svg`, example: { dest: `./svg-sprite-${ category }.html` }, render: { css: { dest: `./svg-sprite-${ category }.css` } } }, symbol : { bust: false, dest: './', sprite: `./svg-sprite-${ category }-symbol.svg`, example: { dest: `./svg-sprite-${ category }-symbol.html` } } } }; }
[ "function", "getSvgSpriteConfig", "(", "category", ")", "{", "return", "{", "shape", ":", "{", "dimension", ":", "{", "maxWidth", ":", "24", ",", "maxHeight", ":", "24", "}", ",", "}", ",", "mode", ":", "{", "css", ":", "{", "bust", ":", "false", ",", "dest", ":", "'./'", ",", "sprite", ":", "`", "${", "category", "}", "`", ",", "example", ":", "{", "dest", ":", "`", "${", "category", "}", "`", "}", ",", "render", ":", "{", "css", ":", "{", "dest", ":", "`", "${", "category", "}", "`", "}", "}", "}", ",", "symbol", ":", "{", "bust", ":", "false", ",", "dest", ":", "'./'", ",", "sprite", ":", "`", "${", "category", "}", "`", ",", "example", ":", "{", "dest", ":", "`", "${", "category", "}", "`", "}", "}", "}", "}", ";", "}" ]
Returns the SVG sprite configuration for the specified category.
[ "Returns", "the", "SVG", "sprite", "configuration", "for", "the", "specified", "category", "." ]
224895a86501195e7a7ff3dde18e39f00b8e3d5a
https://github.com/google/material-design-icons/blob/224895a86501195e7a7ff3dde18e39f00b8e3d5a/gulpfile.babel.js#L122-L154
train
google/material-design-icons
gulpfile.babel.js
getCategoryColorPairs
function getCategoryColorPairs() { return _(ICON_CATEGORIES) .map((category) => _.zip(_.times(PNG_COLORS.length, () => category), PNG_COLORS)) .flatten() // flattens 1 level .value(); }
javascript
function getCategoryColorPairs() { return _(ICON_CATEGORIES) .map((category) => _.zip(_.times(PNG_COLORS.length, () => category), PNG_COLORS)) .flatten() // flattens 1 level .value(); }
[ "function", "getCategoryColorPairs", "(", ")", "{", "return", "_", "(", "ICON_CATEGORIES", ")", ".", "map", "(", "(", "category", ")", "=>", "_", ".", "zip", "(", "_", ".", "times", "(", "PNG_COLORS", ".", "length", ",", "(", ")", "=>", "category", ")", ",", "PNG_COLORS", ")", ")", ".", "flatten", "(", ")", ".", "value", "(", ")", ";", "}" ]
Returns the catesian product of categories and colors.
[ "Returns", "the", "catesian", "product", "of", "categories", "and", "colors", "." ]
224895a86501195e7a7ff3dde18e39f00b8e3d5a
https://github.com/google/material-design-icons/blob/224895a86501195e7a7ff3dde18e39f00b8e3d5a/gulpfile.babel.js#L160-L166
train
socketio/socket.io
lib/index.js
Server
function Server(srv, opts){ if (!(this instanceof Server)) return new Server(srv, opts); if ('object' == typeof srv && srv instanceof Object && !srv.listen) { opts = srv; srv = null; } opts = opts || {}; this.nsps = {}; this.parentNsps = new Map(); this.path(opts.path || '/socket.io'); this.serveClient(false !== opts.serveClient); this.parser = opts.parser || parser; this.encoder = new this.parser.Encoder(); this.adapter(opts.adapter || Adapter); this.origins(opts.origins || '*:*'); this.sockets = this.of('/'); if (srv) this.attach(srv, opts); }
javascript
function Server(srv, opts){ if (!(this instanceof Server)) return new Server(srv, opts); if ('object' == typeof srv && srv instanceof Object && !srv.listen) { opts = srv; srv = null; } opts = opts || {}; this.nsps = {}; this.parentNsps = new Map(); this.path(opts.path || '/socket.io'); this.serveClient(false !== opts.serveClient); this.parser = opts.parser || parser; this.encoder = new this.parser.Encoder(); this.adapter(opts.adapter || Adapter); this.origins(opts.origins || '*:*'); this.sockets = this.of('/'); if (srv) this.attach(srv, opts); }
[ "function", "Server", "(", "srv", ",", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Server", ")", ")", "return", "new", "Server", "(", "srv", ",", "opts", ")", ";", "if", "(", "'object'", "==", "typeof", "srv", "&&", "srv", "instanceof", "Object", "&&", "!", "srv", ".", "listen", ")", "{", "opts", "=", "srv", ";", "srv", "=", "null", ";", "}", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "nsps", "=", "{", "}", ";", "this", ".", "parentNsps", "=", "new", "Map", "(", ")", ";", "this", ".", "path", "(", "opts", ".", "path", "||", "'/socket.io'", ")", ";", "this", ".", "serveClient", "(", "false", "!==", "opts", ".", "serveClient", ")", ";", "this", ".", "parser", "=", "opts", ".", "parser", "||", "parser", ";", "this", ".", "encoder", "=", "new", "this", ".", "parser", ".", "Encoder", "(", ")", ";", "this", ".", "adapter", "(", "opts", ".", "adapter", "||", "Adapter", ")", ";", "this", ".", "origins", "(", "opts", ".", "origins", "||", "'*:*'", ")", ";", "this", ".", "sockets", "=", "this", ".", "of", "(", "'/'", ")", ";", "if", "(", "srv", ")", "this", ".", "attach", "(", "srv", ",", "opts", ")", ";", "}" ]
Server constructor. @param {http.Server|Number|Object} srv http server, port or options @param {Object} [opts] @api public
[ "Server", "constructor", "." ]
9c1e73c752aec63f48b511330a506d037783d897
https://github.com/socketio/socket.io/blob/9c1e73c752aec63f48b511330a506d037783d897/lib/index.js#L43-L60
train
socketio/socket.io
lib/client.js
Client
function Client(server, conn){ this.server = server; this.conn = conn; this.encoder = server.encoder; this.decoder = new server.parser.Decoder(); this.id = conn.id; this.request = conn.request; this.setup(); this.sockets = {}; this.nsps = {}; this.connectBuffer = []; }
javascript
function Client(server, conn){ this.server = server; this.conn = conn; this.encoder = server.encoder; this.decoder = new server.parser.Decoder(); this.id = conn.id; this.request = conn.request; this.setup(); this.sockets = {}; this.nsps = {}; this.connectBuffer = []; }
[ "function", "Client", "(", "server", ",", "conn", ")", "{", "this", ".", "server", "=", "server", ";", "this", ".", "conn", "=", "conn", ";", "this", ".", "encoder", "=", "server", ".", "encoder", ";", "this", ".", "decoder", "=", "new", "server", ".", "parser", ".", "Decoder", "(", ")", ";", "this", ".", "id", "=", "conn", ".", "id", ";", "this", ".", "request", "=", "conn", ".", "request", ";", "this", ".", "setup", "(", ")", ";", "this", ".", "sockets", "=", "{", "}", ";", "this", ".", "nsps", "=", "{", "}", ";", "this", ".", "connectBuffer", "=", "[", "]", ";", "}" ]
Client constructor. @param {Server} server instance @param {Socket} conn @api private
[ "Client", "constructor", "." ]
9c1e73c752aec63f48b511330a506d037783d897
https://github.com/socketio/socket.io/blob/9c1e73c752aec63f48b511330a506d037783d897/lib/client.js#L24-L35
train
socketio/socket.io
lib/client.js
writeToEngine
function writeToEngine(encodedPackets) { if (opts.volatile && !self.conn.transport.writable) return; for (var i = 0; i < encodedPackets.length; i++) { self.conn.write(encodedPackets[i], { compress: opts.compress }); } }
javascript
function writeToEngine(encodedPackets) { if (opts.volatile && !self.conn.transport.writable) return; for (var i = 0; i < encodedPackets.length; i++) { self.conn.write(encodedPackets[i], { compress: opts.compress }); } }
[ "function", "writeToEngine", "(", "encodedPackets", ")", "{", "if", "(", "opts", ".", "volatile", "&&", "!", "self", ".", "conn", ".", "transport", ".", "writable", ")", "return", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "encodedPackets", ".", "length", ";", "i", "++", ")", "{", "self", ".", "conn", ".", "write", "(", "encodedPackets", "[", "i", "]", ",", "{", "compress", ":", "opts", ".", "compress", "}", ")", ";", "}", "}" ]
this writes to the actual connection
[ "this", "writes", "to", "the", "actual", "connection" ]
9c1e73c752aec63f48b511330a506d037783d897
https://github.com/socketio/socket.io/blob/9c1e73c752aec63f48b511330a506d037783d897/lib/client.js#L167-L172
train
socketio/socket.io
lib/namespace.js
Namespace
function Namespace(server, name){ this.name = name; this.server = server; this.sockets = {}; this.connected = {}; this.fns = []; this.ids = 0; this.rooms = []; this.flags = {}; this.initAdapter(); }
javascript
function Namespace(server, name){ this.name = name; this.server = server; this.sockets = {}; this.connected = {}; this.fns = []; this.ids = 0; this.rooms = []; this.flags = {}; this.initAdapter(); }
[ "function", "Namespace", "(", "server", ",", "name", ")", "{", "this", ".", "name", "=", "name", ";", "this", ".", "server", "=", "server", ";", "this", ".", "sockets", "=", "{", "}", ";", "this", ".", "connected", "=", "{", "}", ";", "this", ".", "fns", "=", "[", "]", ";", "this", ".", "ids", "=", "0", ";", "this", ".", "rooms", "=", "[", "]", ";", "this", ".", "flags", "=", "{", "}", ";", "this", ".", "initAdapter", "(", ")", ";", "}" ]
Namespace constructor. @param {Server} server instance @param {Socket} name @api private
[ "Namespace", "constructor", "." ]
9c1e73c752aec63f48b511330a506d037783d897
https://github.com/socketio/socket.io/blob/9c1e73c752aec63f48b511330a506d037783d897/lib/namespace.js#L52-L62
train
socketio/socket.io
examples/whiteboard/public/main.js
throttle
function throttle(callback, delay) { var previousCall = new Date().getTime(); return function() { var time = new Date().getTime(); if ((time - previousCall) >= delay) { previousCall = time; callback.apply(null, arguments); } }; }
javascript
function throttle(callback, delay) { var previousCall = new Date().getTime(); return function() { var time = new Date().getTime(); if ((time - previousCall) >= delay) { previousCall = time; callback.apply(null, arguments); } }; }
[ "function", "throttle", "(", "callback", ",", "delay", ")", "{", "var", "previousCall", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "return", "function", "(", ")", "{", "var", "time", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "if", "(", "(", "time", "-", "previousCall", ")", ">=", "delay", ")", "{", "previousCall", "=", "time", ";", "callback", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}", "}", ";", "}" ]
limit the number of events per second
[ "limit", "the", "number", "of", "events", "per", "second" ]
9c1e73c752aec63f48b511330a506d037783d897
https://github.com/socketio/socket.io/blob/9c1e73c752aec63f48b511330a506d037783d897/examples/whiteboard/public/main.js#L82-L92
train
socketio/socket.io
lib/socket.js
Socket
function Socket(nsp, client, query){ this.nsp = nsp; this.server = nsp.server; this.adapter = this.nsp.adapter; this.id = nsp.name !== '/' ? nsp.name + '#' + client.id : client.id; this.client = client; this.conn = client.conn; this.rooms = {}; this.acks = {}; this.connected = true; this.disconnected = false; this.handshake = this.buildHandshake(query); this.fns = []; this.flags = {}; this._rooms = []; }
javascript
function Socket(nsp, client, query){ this.nsp = nsp; this.server = nsp.server; this.adapter = this.nsp.adapter; this.id = nsp.name !== '/' ? nsp.name + '#' + client.id : client.id; this.client = client; this.conn = client.conn; this.rooms = {}; this.acks = {}; this.connected = true; this.disconnected = false; this.handshake = this.buildHandshake(query); this.fns = []; this.flags = {}; this._rooms = []; }
[ "function", "Socket", "(", "nsp", ",", "client", ",", "query", ")", "{", "this", ".", "nsp", "=", "nsp", ";", "this", ".", "server", "=", "nsp", ".", "server", ";", "this", ".", "adapter", "=", "this", ".", "nsp", ".", "adapter", ";", "this", ".", "id", "=", "nsp", ".", "name", "!==", "'/'", "?", "nsp", ".", "name", "+", "'#'", "+", "client", ".", "id", ":", "client", ".", "id", ";", "this", ".", "client", "=", "client", ";", "this", ".", "conn", "=", "client", ".", "conn", ";", "this", ".", "rooms", "=", "{", "}", ";", "this", ".", "acks", "=", "{", "}", ";", "this", ".", "connected", "=", "true", ";", "this", ".", "disconnected", "=", "false", ";", "this", ".", "handshake", "=", "this", ".", "buildHandshake", "(", "query", ")", ";", "this", ".", "fns", "=", "[", "]", ";", "this", ".", "flags", "=", "{", "}", ";", "this", ".", "_rooms", "=", "[", "]", ";", "}" ]
Interface to a `Client` for a given `Namespace`. @param {Namespace} nsp @param {Client} client @api public
[ "Interface", "to", "a", "Client", "for", "a", "given", "Namespace", "." ]
9c1e73c752aec63f48b511330a506d037783d897
https://github.com/socketio/socket.io/blob/9c1e73c752aec63f48b511330a506d037783d897/lib/socket.js#L60-L75
train
jquery/jquery
build/release.js
function() { var corePath = __dirname + "/../src/core.js", contents = fs.readFileSync( corePath, "utf8" ); contents = contents.replace( /@VERSION/g, Release.newVersion ); fs.writeFileSync( corePath, contents, "utf8" ); }
javascript
function() { var corePath = __dirname + "/../src/core.js", contents = fs.readFileSync( corePath, "utf8" ); contents = contents.replace( /@VERSION/g, Release.newVersion ); fs.writeFileSync( corePath, contents, "utf8" ); }
[ "function", "(", ")", "{", "var", "corePath", "=", "__dirname", "+", "\"/../src/core.js\"", ",", "contents", "=", "fs", ".", "readFileSync", "(", "corePath", ",", "\"utf8\"", ")", ";", "contents", "=", "contents", ".", "replace", "(", "/", "@VERSION", "/", "g", ",", "Release", ".", "newVersion", ")", ";", "fs", ".", "writeFileSync", "(", "corePath", ",", "contents", ",", "\"utf8\"", ")", ";", "}" ]
Set the version in the src folder for distributing AMD
[ "Set", "the", "version", "in", "the", "src", "folder", "for", "distributing", "AMD" ]
ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3
https://github.com/jquery/jquery/blob/ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3/build/release.js#L36-L41
train
jquery/jquery
build/release.js
function( callback ) { Release.exec( "grunt", "Grunt command failed" ); Release.exec( "grunt custom:-ajax,-effects --filename=jquery.slim.js && " + "grunt remove_map_comment --filename=jquery.slim.js", "Grunt custom failed" ); cdn.makeReleaseCopies( Release ); Release._setSrcVersion(); callback( files ); }
javascript
function( callback ) { Release.exec( "grunt", "Grunt command failed" ); Release.exec( "grunt custom:-ajax,-effects --filename=jquery.slim.js && " + "grunt remove_map_comment --filename=jquery.slim.js", "Grunt custom failed" ); cdn.makeReleaseCopies( Release ); Release._setSrcVersion(); callback( files ); }
[ "function", "(", "callback", ")", "{", "Release", ".", "exec", "(", "\"grunt\"", ",", "\"Grunt command failed\"", ")", ";", "Release", ".", "exec", "(", "\"grunt custom:-ajax,-effects --filename=jquery.slim.js && \"", "+", "\"grunt remove_map_comment --filename=jquery.slim.js\"", ",", "\"Grunt custom failed\"", ")", ";", "cdn", ".", "makeReleaseCopies", "(", "Release", ")", ";", "Release", ".", "_setSrcVersion", "(", ")", ";", "callback", "(", "files", ")", ";", "}" ]
Generates any release artifacts that should be included in the release. The callback must be invoked with an array of files that should be committed before creating the tag. @param {Function} callback
[ "Generates", "any", "release", "artifacts", "that", "should", "be", "included", "in", "the", "release", ".", "The", "callback", "must", "be", "invoked", "with", "an", "array", "of", "files", "that", "should", "be", "committed", "before", "creating", "the", "tag", "." ]
ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3
https://github.com/jquery/jquery/blob/ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3/build/release.js#L49-L59
train
jquery/jquery
build/release.js
function() { // origRepo is not defined if dist was skipped Release.dir.repo = Release.dir.origRepo || Release.dir.repo; return npmTags(); }
javascript
function() { // origRepo is not defined if dist was skipped Release.dir.repo = Release.dir.origRepo || Release.dir.repo; return npmTags(); }
[ "function", "(", ")", "{", "Release", ".", "dir", ".", "repo", "=", "Release", ".", "dir", ".", "origRepo", "||", "Release", ".", "dir", ".", "repo", ";", "return", "npmTags", "(", ")", ";", "}" ]
Acts as insertion point for restoring Release.dir.repo It was changed to reuse npm publish code in jquery-release for publishing the distribution repo instead
[ "Acts", "as", "insertion", "point", "for", "restoring", "Release", ".", "dir", ".", "repo", "It", "was", "changed", "to", "reuse", "npm", "publish", "code", "in", "jquery", "-", "release", "for", "publishing", "the", "distribution", "repo", "instead" ]
ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3
https://github.com/jquery/jquery/blob/ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3/build/release.js#L66-L71
train
jquery/jquery
build/release/dist.js
clone
function clone() { Release.chdir( Release.dir.base ); Release.dir.dist = Release.dir.base + "/dist"; console.log( "Using distribution repo: ", distRemote ); Release.exec( "git clone " + distRemote + " " + Release.dir.dist, "Error cloning repo." ); // Distribution always works on master Release.chdir( Release.dir.dist ); Release.exec( "git checkout master", "Error checking out branch." ); console.log(); }
javascript
function clone() { Release.chdir( Release.dir.base ); Release.dir.dist = Release.dir.base + "/dist"; console.log( "Using distribution repo: ", distRemote ); Release.exec( "git clone " + distRemote + " " + Release.dir.dist, "Error cloning repo." ); // Distribution always works on master Release.chdir( Release.dir.dist ); Release.exec( "git checkout master", "Error checking out branch." ); console.log(); }
[ "function", "clone", "(", ")", "{", "Release", ".", "chdir", "(", "Release", ".", "dir", ".", "base", ")", ";", "Release", ".", "dir", ".", "dist", "=", "Release", ".", "dir", ".", "base", "+", "\"/dist\"", ";", "console", ".", "log", "(", "\"Using distribution repo: \"", ",", "distRemote", ")", ";", "Release", ".", "exec", "(", "\"git clone \"", "+", "distRemote", "+", "\" \"", "+", "Release", ".", "dir", ".", "dist", ",", "\"Error cloning repo.\"", ")", ";", "Release", ".", "chdir", "(", "Release", ".", "dir", ".", "dist", ")", ";", "Release", ".", "exec", "(", "\"git checkout master\"", ",", "\"Error checking out branch.\"", ")", ";", "console", ".", "log", "(", ")", ";", "}" ]
Clone the distribution repo
[ "Clone", "the", "distribution", "repo" ]
ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3
https://github.com/jquery/jquery/blob/ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3/build/release/dist.js#L23-L35
train
jquery/jquery
build/release/dist.js
generateBower
function generateBower() { return JSON.stringify( { name: pkg.name, main: pkg.main, license: "MIT", ignore: [ "package.json" ], keywords: pkg.keywords }, null, 2 ); }
javascript
function generateBower() { return JSON.stringify( { name: pkg.name, main: pkg.main, license: "MIT", ignore: [ "package.json" ], keywords: pkg.keywords }, null, 2 ); }
[ "function", "generateBower", "(", ")", "{", "return", "JSON", ".", "stringify", "(", "{", "name", ":", "pkg", ".", "name", ",", "main", ":", "pkg", ".", "main", ",", "license", ":", "\"MIT\"", ",", "ignore", ":", "[", "\"package.json\"", "]", ",", "keywords", ":", "pkg", ".", "keywords", "}", ",", "null", ",", "2", ")", ";", "}" ]
Generate bower file for jquery-dist
[ "Generate", "bower", "file", "for", "jquery", "-", "dist" ]
ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3
https://github.com/jquery/jquery/blob/ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3/build/release/dist.js#L40-L50
train
jquery/jquery
build/release/dist.js
editReadme
function editReadme( readme ) { var rprev = new RegExp( Release.prevVersion, "g" ); return readme.replace( rprev, Release.newVersion ); }
javascript
function editReadme( readme ) { var rprev = new RegExp( Release.prevVersion, "g" ); return readme.replace( rprev, Release.newVersion ); }
[ "function", "editReadme", "(", "readme", ")", "{", "var", "rprev", "=", "new", "RegExp", "(", "Release", ".", "prevVersion", ",", "\"g\"", ")", ";", "return", "readme", ".", "replace", "(", "rprev", ",", "Release", ".", "newVersion", ")", ";", "}" ]
Replace the version in the README @param {string} readme
[ "Replace", "the", "version", "in", "the", "README" ]
ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3
https://github.com/jquery/jquery/blob/ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3/build/release/dist.js#L56-L59
train
jquery/jquery
build/release/dist.js
commit
function commit() { console.log( "Adding files to dist..." ); Release.exec( "git add -A", "Error adding files." ); Release.exec( "git commit -m \"Release " + Release.newVersion + "\"", "Error committing files." ); console.log(); console.log( "Tagging release on dist..." ); Release.exec( "git tag " + Release.newVersion, "Error tagging " + Release.newVersion + " on dist repo." ); Release.tagTime = Release.exec( "git log -1 --format=\"%ad\"", "Error getting tag timestamp." ).trim(); }
javascript
function commit() { console.log( "Adding files to dist..." ); Release.exec( "git add -A", "Error adding files." ); Release.exec( "git commit -m \"Release " + Release.newVersion + "\"", "Error committing files." ); console.log(); console.log( "Tagging release on dist..." ); Release.exec( "git tag " + Release.newVersion, "Error tagging " + Release.newVersion + " on dist repo." ); Release.tagTime = Release.exec( "git log -1 --format=\"%ad\"", "Error getting tag timestamp." ).trim(); }
[ "function", "commit", "(", ")", "{", "console", ".", "log", "(", "\"Adding files to dist...\"", ")", ";", "Release", ".", "exec", "(", "\"git add -A\"", ",", "\"Error adding files.\"", ")", ";", "Release", ".", "exec", "(", "\"git commit -m \\\"Release \"", "+", "\\\"", "+", "Release", ".", "newVersion", ",", "\"\\\"\"", ")", ";", "\\\"", "\"Error committing files.\"", "console", ".", "log", "(", ")", ";", "console", ".", "log", "(", "\"Tagging release on dist...\"", ")", ";", "}" ]
Add, commit, and tag the dist files
[ "Add", "commit", "and", "tag", "the", "dist", "files" ]
ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3
https://github.com/jquery/jquery/blob/ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3/build/release/dist.js#L115-L129
train
jquery/jquery
build/release/dist.js
push
function push() { Release.chdir( Release.dir.dist ); console.log( "Pushing release to dist repo..." ); Release.exec( "git push " + distRemote + " master --tags", "Error pushing master and tags to git repo." ); // Set repo for npm publish Release.dir.origRepo = Release.dir.repo; Release.dir.repo = Release.dir.dist; }
javascript
function push() { Release.chdir( Release.dir.dist ); console.log( "Pushing release to dist repo..." ); Release.exec( "git push " + distRemote + " master --tags", "Error pushing master and tags to git repo." ); // Set repo for npm publish Release.dir.origRepo = Release.dir.repo; Release.dir.repo = Release.dir.dist; }
[ "function", "push", "(", ")", "{", "Release", ".", "chdir", "(", "Release", ".", "dir", ".", "dist", ")", ";", "console", ".", "log", "(", "\"Pushing release to dist repo...\"", ")", ";", "Release", ".", "exec", "(", "\"git push \"", "+", "distRemote", "+", "\" master --tags\"", ",", "\"Error pushing master and tags to git repo.\"", ")", ";", "Release", ".", "dir", ".", "origRepo", "=", "Release", ".", "dir", ".", "repo", ";", "Release", ".", "dir", ".", "repo", "=", "Release", ".", "dir", ".", "dist", ";", "}" ]
Push files to dist repo
[ "Push", "files", "to", "dist", "repo" ]
ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3
https://github.com/jquery/jquery/blob/ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3/build/release/dist.js#L134-L144
train
jquery/jquery
build/release/cdn.js
makeReleaseCopies
function makeReleaseCopies( Release ) { shell.mkdir( "-p", cdnFolder ); Object.keys( releaseFiles ).forEach( function( key ) { var text, builtFile = releaseFiles[ key ], unpathedFile = key.replace( /VER/g, Release.newVersion ), releaseFile = cdnFolder + "/" + unpathedFile; if ( /\.map$/.test( releaseFile ) ) { // Map files need to reference the new uncompressed name; // assume that all files reside in the same directory. // "file":"jquery.min.js" ... "sources":["jquery.js"] text = fs.readFileSync( builtFile, "utf8" ) .replace( /"file":"([^"]+)"/, "\"file\":\"" + unpathedFile.replace( /\.min\.map/, ".min.js\"" ) ) .replace( /"sources":\["([^"]+)"\]/, "\"sources\":[\"" + unpathedFile.replace( /\.min\.map/, ".js" ) + "\"]" ); fs.writeFileSync( releaseFile, text ); } else if ( builtFile !== releaseFile ) { shell.cp( "-f", builtFile, releaseFile ); } } ); }
javascript
function makeReleaseCopies( Release ) { shell.mkdir( "-p", cdnFolder ); Object.keys( releaseFiles ).forEach( function( key ) { var text, builtFile = releaseFiles[ key ], unpathedFile = key.replace( /VER/g, Release.newVersion ), releaseFile = cdnFolder + "/" + unpathedFile; if ( /\.map$/.test( releaseFile ) ) { // Map files need to reference the new uncompressed name; // assume that all files reside in the same directory. // "file":"jquery.min.js" ... "sources":["jquery.js"] text = fs.readFileSync( builtFile, "utf8" ) .replace( /"file":"([^"]+)"/, "\"file\":\"" + unpathedFile.replace( /\.min\.map/, ".min.js\"" ) ) .replace( /"sources":\["([^"]+)"\]/, "\"sources\":[\"" + unpathedFile.replace( /\.min\.map/, ".js" ) + "\"]" ); fs.writeFileSync( releaseFile, text ); } else if ( builtFile !== releaseFile ) { shell.cp( "-f", builtFile, releaseFile ); } } ); }
[ "function", "makeReleaseCopies", "(", "Release", ")", "{", "shell", ".", "mkdir", "(", "\"-p\"", ",", "cdnFolder", ")", ";", "Object", ".", "keys", "(", "releaseFiles", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "text", ",", "builtFile", "=", "releaseFiles", "[", "key", "]", ",", "unpathedFile", "=", "key", ".", "replace", "(", "/", "VER", "/", "g", ",", "Release", ".", "newVersion", ")", ",", "releaseFile", "=", "cdnFolder", "+", "\"/\"", "+", "unpathedFile", ";", "if", "(", "/", "\\.map$", "/", ".", "test", "(", "releaseFile", ")", ")", "{", "text", "=", "fs", ".", "readFileSync", "(", "builtFile", ",", "\"utf8\"", ")", ".", "replace", "(", "/", "\"file\":\"([^\"]+)\"", "/", ",", "\"\\\"file\\\":\\\"\"", "+", "\\\"", ")", ".", "\\\"", "\\\"", ";", "unpathedFile", ".", "replace", "(", "/", "\\.min\\.map", "/", ",", "\".min.js\\\"\"", ")", "}", "else", "\\\"", "}", ")", ";", "}" ]
Generates copies for the CDNs
[ "Generates", "copies", "for", "the", "CDNs" ]
ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3
https://github.com/jquery/jquery/blob/ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3/build/release/cdn.js#L30-L54
train
jquery/jquery
src/css/finalPropName.js
finalPropName
function finalPropName( name ) { var final = vendorProps[ name ]; if ( final ) { return final; } if ( name in emptyStyle ) { return name; } return vendorProps[ name ] = vendorPropName( name ) || name; }
javascript
function finalPropName( name ) { var final = vendorProps[ name ]; if ( final ) { return final; } if ( name in emptyStyle ) { return name; } return vendorProps[ name ] = vendorPropName( name ) || name; }
[ "function", "finalPropName", "(", "name", ")", "{", "var", "final", "=", "vendorProps", "[", "name", "]", ";", "if", "(", "final", ")", "{", "return", "final", ";", "}", "if", "(", "name", "in", "emptyStyle", ")", "{", "return", "name", ";", "}", "return", "vendorProps", "[", "name", "]", "=", "vendorPropName", "(", "name", ")", "||", "name", ";", "}" ]
Return a potentially-mapped vendor prefixed property
[ "Return", "a", "potentially", "-", "mapped", "vendor", "prefixed", "property" ]
ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3
https://github.com/jquery/jquery/blob/ccbd6b93424cbdbf86f07a86c2e55cbab497d7a3/src/css/finalPropName.js#L27-L37
train
vuejs/vue-devtools
src/backend/index.js
scan
function scan () { rootInstances.length = 0 let inFragment = false let currentFragment = null function processInstance (instance) { if (instance) { if (rootInstances.indexOf(instance.$root) === -1) { instance = instance.$root } if (instance._isFragment) { inFragment = true currentFragment = instance } // respect Vue.config.devtools option let baseVue = instance.constructor while (baseVue.super) { baseVue = baseVue.super } if (baseVue.config && baseVue.config.devtools) { // give a unique id to root instance so we can // 'namespace' its children if (typeof instance.__VUE_DEVTOOLS_ROOT_UID__ === 'undefined') { instance.__VUE_DEVTOOLS_ROOT_UID__ = ++rootUID } rootInstances.push(instance) } return true } } if (isBrowser) { walk(document, function (node) { if (inFragment) { if (node === currentFragment._fragmentEnd) { inFragment = false currentFragment = null } return true } let instance = node.__vue__ return processInstance(instance) }) } else { if (Array.isArray(target.__VUE_ROOT_INSTANCES__)) { target.__VUE_ROOT_INSTANCES__.map(processInstance) } } hook.emit('router:init') flush() }
javascript
function scan () { rootInstances.length = 0 let inFragment = false let currentFragment = null function processInstance (instance) { if (instance) { if (rootInstances.indexOf(instance.$root) === -1) { instance = instance.$root } if (instance._isFragment) { inFragment = true currentFragment = instance } // respect Vue.config.devtools option let baseVue = instance.constructor while (baseVue.super) { baseVue = baseVue.super } if (baseVue.config && baseVue.config.devtools) { // give a unique id to root instance so we can // 'namespace' its children if (typeof instance.__VUE_DEVTOOLS_ROOT_UID__ === 'undefined') { instance.__VUE_DEVTOOLS_ROOT_UID__ = ++rootUID } rootInstances.push(instance) } return true } } if (isBrowser) { walk(document, function (node) { if (inFragment) { if (node === currentFragment._fragmentEnd) { inFragment = false currentFragment = null } return true } let instance = node.__vue__ return processInstance(instance) }) } else { if (Array.isArray(target.__VUE_ROOT_INSTANCES__)) { target.__VUE_ROOT_INSTANCES__.map(processInstance) } } hook.emit('router:init') flush() }
[ "function", "scan", "(", ")", "{", "rootInstances", ".", "length", "=", "0", "let", "inFragment", "=", "false", "let", "currentFragment", "=", "null", "function", "processInstance", "(", "instance", ")", "{", "if", "(", "instance", ")", "{", "if", "(", "rootInstances", ".", "indexOf", "(", "instance", ".", "$root", ")", "===", "-", "1", ")", "{", "instance", "=", "instance", ".", "$root", "}", "if", "(", "instance", ".", "_isFragment", ")", "{", "inFragment", "=", "true", "currentFragment", "=", "instance", "}", "let", "baseVue", "=", "instance", ".", "constructor", "while", "(", "baseVue", ".", "super", ")", "{", "baseVue", "=", "baseVue", ".", "super", "}", "if", "(", "baseVue", ".", "config", "&&", "baseVue", ".", "config", ".", "devtools", ")", "{", "if", "(", "typeof", "instance", ".", "__VUE_DEVTOOLS_ROOT_UID__", "===", "'undefined'", ")", "{", "instance", ".", "__VUE_DEVTOOLS_ROOT_UID__", "=", "++", "rootUID", "}", "rootInstances", ".", "push", "(", "instance", ")", "}", "return", "true", "}", "}", "if", "(", "isBrowser", ")", "{", "walk", "(", "document", ",", "function", "(", "node", ")", "{", "if", "(", "inFragment", ")", "{", "if", "(", "node", "===", "currentFragment", ".", "_fragmentEnd", ")", "{", "inFragment", "=", "false", "currentFragment", "=", "null", "}", "return", "true", "}", "let", "instance", "=", "node", ".", "__vue__", "return", "processInstance", "(", "instance", ")", "}", ")", "}", "else", "{", "if", "(", "Array", ".", "isArray", "(", "target", ".", "__VUE_ROOT_INSTANCES__", ")", ")", "{", "target", ".", "__VUE_ROOT_INSTANCES__", ".", "map", "(", "processInstance", ")", "}", "}", "hook", ".", "emit", "(", "'router:init'", ")", "flush", "(", ")", "}" ]
Scan the page for root level Vue instances.
[ "Scan", "the", "page", "for", "root", "level", "Vue", "instances", "." ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/backend/index.js#L189-L242
train
vuejs/vue-devtools
src/backend/index.js
walk
function walk (node, fn) { if (node.childNodes) { for (let i = 0, l = node.childNodes.length; i < l; i++) { const child = node.childNodes[i] const stop = fn(child) if (!stop) { walk(child, fn) } } } // also walk shadow DOM if (node.shadowRoot) { walk(node.shadowRoot, fn) } }
javascript
function walk (node, fn) { if (node.childNodes) { for (let i = 0, l = node.childNodes.length; i < l; i++) { const child = node.childNodes[i] const stop = fn(child) if (!stop) { walk(child, fn) } } } // also walk shadow DOM if (node.shadowRoot) { walk(node.shadowRoot, fn) } }
[ "function", "walk", "(", "node", ",", "fn", ")", "{", "if", "(", "node", ".", "childNodes", ")", "{", "for", "(", "let", "i", "=", "0", ",", "l", "=", "node", ".", "childNodes", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "const", "child", "=", "node", ".", "childNodes", "[", "i", "]", "const", "stop", "=", "fn", "(", "child", ")", "if", "(", "!", "stop", ")", "{", "walk", "(", "child", ",", "fn", ")", "}", "}", "}", "if", "(", "node", ".", "shadowRoot", ")", "{", "walk", "(", "node", ".", "shadowRoot", ",", "fn", ")", "}", "}" ]
DOM walk helper @param {NodeList} nodes @param {Function} fn
[ "DOM", "walk", "helper" ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/backend/index.js#L251-L266
train
vuejs/vue-devtools
src/backend/index.js
isQualified
function isQualified (instance) { const name = classify(instance.name || getInstanceName(instance)).toLowerCase() return name.indexOf(filter) > -1 }
javascript
function isQualified (instance) { const name = classify(instance.name || getInstanceName(instance)).toLowerCase() return name.indexOf(filter) > -1 }
[ "function", "isQualified", "(", "instance", ")", "{", "const", "name", "=", "classify", "(", "instance", ".", "name", "||", "getInstanceName", "(", "instance", ")", ")", ".", "toLowerCase", "(", ")", "return", "name", ".", "indexOf", "(", "filter", ")", ">", "-", "1", "}" ]
Check if an instance is qualified. @param {Vue|Vnode} instance @return {Boolean}
[ "Check", "if", "an", "instance", "is", "qualified", "." ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/backend/index.js#L340-L343
train
vuejs/vue-devtools
src/backend/index.js
mark
function mark (instance) { if (!instanceMap.has(instance.__VUE_DEVTOOLS_UID__)) { instanceMap.set(instance.__VUE_DEVTOOLS_UID__, instance) instance.$on('hook:beforeDestroy', function () { instanceMap.delete(instance.__VUE_DEVTOOLS_UID__) }) } }
javascript
function mark (instance) { if (!instanceMap.has(instance.__VUE_DEVTOOLS_UID__)) { instanceMap.set(instance.__VUE_DEVTOOLS_UID__, instance) instance.$on('hook:beforeDestroy', function () { instanceMap.delete(instance.__VUE_DEVTOOLS_UID__) }) } }
[ "function", "mark", "(", "instance", ")", "{", "if", "(", "!", "instanceMap", ".", "has", "(", "instance", ".", "__VUE_DEVTOOLS_UID__", ")", ")", "{", "instanceMap", ".", "set", "(", "instance", ".", "__VUE_DEVTOOLS_UID__", ",", "instance", ")", "instance", ".", "$on", "(", "'hook:beforeDestroy'", ",", "function", "(", ")", "{", "instanceMap", ".", "delete", "(", "instance", ".", "__VUE_DEVTOOLS_UID__", ")", "}", ")", "}", "}" ]
Mark an instance as captured and store it in the instance map. @param {Vue} instance
[ "Mark", "an", "instance", "as", "captured", "and", "store", "it", "in", "the", "instance", "map", "." ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/backend/index.js#L479-L486
train
vuejs/vue-devtools
src/backend/index.js
getInstanceDetails
function getInstanceDetails (id) { const instance = instanceMap.get(id) if (!instance) { const vnode = findInstanceOrVnode(id) if (!vnode) return {} const data = { id, name: getComponentName(vnode.fnOptions), file: vnode.fnOptions.__file || null, state: processProps({ $options: vnode.fnOptions, ...(vnode.devtoolsMeta && vnode.devtoolsMeta.renderContext.props) }), functional: true } return data } else { const data = { id: id, name: getInstanceName(instance), state: getInstanceState(instance) } let i if ((i = instance.$vnode) && (i = i.componentOptions) && (i = i.Ctor) && (i = i.options)) { data.file = i.__file || null } return data } }
javascript
function getInstanceDetails (id) { const instance = instanceMap.get(id) if (!instance) { const vnode = findInstanceOrVnode(id) if (!vnode) return {} const data = { id, name: getComponentName(vnode.fnOptions), file: vnode.fnOptions.__file || null, state: processProps({ $options: vnode.fnOptions, ...(vnode.devtoolsMeta && vnode.devtoolsMeta.renderContext.props) }), functional: true } return data } else { const data = { id: id, name: getInstanceName(instance), state: getInstanceState(instance) } let i if ((i = instance.$vnode) && (i = i.componentOptions) && (i = i.Ctor) && (i = i.options)) { data.file = i.__file || null } return data } }
[ "function", "getInstanceDetails", "(", "id", ")", "{", "const", "instance", "=", "instanceMap", ".", "get", "(", "id", ")", "if", "(", "!", "instance", ")", "{", "const", "vnode", "=", "findInstanceOrVnode", "(", "id", ")", "if", "(", "!", "vnode", ")", "return", "{", "}", "const", "data", "=", "{", "id", ",", "name", ":", "getComponentName", "(", "vnode", ".", "fnOptions", ")", ",", "file", ":", "vnode", ".", "fnOptions", ".", "__file", "||", "null", ",", "state", ":", "processProps", "(", "{", "$options", ":", "vnode", ".", "fnOptions", ",", "...", "(", "vnode", ".", "devtoolsMeta", "&&", "vnode", ".", "devtoolsMeta", ".", "renderContext", ".", "props", ")", "}", ")", ",", "functional", ":", "true", "}", "return", "data", "}", "else", "{", "const", "data", "=", "{", "id", ":", "id", ",", "name", ":", "getInstanceName", "(", "instance", ")", ",", "state", ":", "getInstanceState", "(", "instance", ")", "}", "let", "i", "if", "(", "(", "i", "=", "instance", ".", "$vnode", ")", "&&", "(", "i", "=", "i", ".", "componentOptions", ")", "&&", "(", "i", "=", "i", ".", "Ctor", ")", "&&", "(", "i", "=", "i", ".", "options", ")", ")", "{", "data", ".", "file", "=", "i", ".", "__file", "||", "null", "}", "return", "data", "}", "}" ]
Get the detailed information of an inspected instance. @param {Number} id
[ "Get", "the", "detailed", "information", "of", "an", "inspected", "instance", "." ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/backend/index.js#L506-L536
train
vuejs/vue-devtools
src/backend/index.js
processState
function processState (instance) { const props = isLegacy ? instance._props : instance.$options.props const getters = instance.$options.vuex && instance.$options.vuex.getters return Object.keys(instance._data) .filter(key => ( !(props && key in props) && !(getters && key in getters) )) .map(key => ({ key, value: instance._data[key], editable: true })) }
javascript
function processState (instance) { const props = isLegacy ? instance._props : instance.$options.props const getters = instance.$options.vuex && instance.$options.vuex.getters return Object.keys(instance._data) .filter(key => ( !(props && key in props) && !(getters && key in getters) )) .map(key => ({ key, value: instance._data[key], editable: true })) }
[ "function", "processState", "(", "instance", ")", "{", "const", "props", "=", "isLegacy", "?", "instance", ".", "_props", ":", "instance", ".", "$options", ".", "props", "const", "getters", "=", "instance", ".", "$options", ".", "vuex", "&&", "instance", ".", "$options", ".", "vuex", ".", "getters", "return", "Object", ".", "keys", "(", "instance", ".", "_data", ")", ".", "filter", "(", "key", "=>", "(", "!", "(", "props", "&&", "key", "in", "props", ")", "&&", "!", "(", "getters", "&&", "key", "in", "getters", ")", ")", ")", ".", "map", "(", "key", "=>", "(", "{", "key", ",", "value", ":", "instance", ".", "_data", "[", "key", "]", ",", "editable", ":", "true", "}", ")", ")", "}" ]
Process state, filtering out props and "clean" the result with a JSON dance. This removes functions which can cause errors during structured clone used by window.postMessage. @param {Vue} instance @return {Array}
[ "Process", "state", "filtering", "out", "props", "and", "clean", "the", "result", "with", "a", "JSON", "dance", ".", "This", "removes", "functions", "which", "can", "cause", "errors", "during", "structured", "clone", "used", "by", "window", ".", "postMessage", "." ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/backend/index.js#L680-L697
train
vuejs/vue-devtools
src/backend/index.js
processComputed
function processComputed (instance) { const computed = [] const defs = instance.$options.computed || {} // use for...in here because if 'computed' is not defined // on component, computed properties will be placed in prototype // and Object.keys does not include // properties from object's prototype for (const key in defs) { const def = defs[key] const type = typeof def === 'function' && def.vuex ? 'vuex bindings' : 'computed' // use try ... catch here because some computed properties may // throw error during its evaluation let computedProp = null try { computedProp = { type, key, value: instance[key] } } catch (e) { computedProp = { type, key, value: '(error during evaluation)' } } computed.push(computedProp) } return computed }
javascript
function processComputed (instance) { const computed = [] const defs = instance.$options.computed || {} // use for...in here because if 'computed' is not defined // on component, computed properties will be placed in prototype // and Object.keys does not include // properties from object's prototype for (const key in defs) { const def = defs[key] const type = typeof def === 'function' && def.vuex ? 'vuex bindings' : 'computed' // use try ... catch here because some computed properties may // throw error during its evaluation let computedProp = null try { computedProp = { type, key, value: instance[key] } } catch (e) { computedProp = { type, key, value: '(error during evaluation)' } } computed.push(computedProp) } return computed }
[ "function", "processComputed", "(", "instance", ")", "{", "const", "computed", "=", "[", "]", "const", "defs", "=", "instance", ".", "$options", ".", "computed", "||", "{", "}", "for", "(", "const", "key", "in", "defs", ")", "{", "const", "def", "=", "defs", "[", "key", "]", "const", "type", "=", "typeof", "def", "===", "'function'", "&&", "def", ".", "vuex", "?", "'vuex bindings'", ":", "'computed'", "let", "computedProp", "=", "null", "try", "{", "computedProp", "=", "{", "type", ",", "key", ",", "value", ":", "instance", "[", "key", "]", "}", "}", "catch", "(", "e", ")", "{", "computedProp", "=", "{", "type", ",", "key", ",", "value", ":", "'(error during evaluation)'", "}", "}", "computed", ".", "push", "(", "computedProp", ")", "}", "return", "computed", "}" ]
Process the computed properties of an instance. @param {Vue} instance @return {Array}
[ "Process", "the", "computed", "properties", "of", "an", "instance", "." ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/backend/index.js#L719-L752
train
vuejs/vue-devtools
src/backend/index.js
processFirebaseBindings
function processFirebaseBindings (instance) { var refs = instance.$firebaseRefs if (refs) { return Object.keys(refs).map(key => { return { type: 'firebase bindings', key, value: instance[key] } }) } else { return [] } }
javascript
function processFirebaseBindings (instance) { var refs = instance.$firebaseRefs if (refs) { return Object.keys(refs).map(key => { return { type: 'firebase bindings', key, value: instance[key] } }) } else { return [] } }
[ "function", "processFirebaseBindings", "(", "instance", ")", "{", "var", "refs", "=", "instance", ".", "$firebaseRefs", "if", "(", "refs", ")", "{", "return", "Object", ".", "keys", "(", "refs", ")", ".", "map", "(", "key", "=>", "{", "return", "{", "type", ":", "'firebase bindings'", ",", "key", ",", "value", ":", "instance", "[", "key", "]", "}", "}", ")", "}", "else", "{", "return", "[", "]", "}", "}" ]
Process Firebase bindings. @param {Vue} instance @return {Array}
[ "Process", "Firebase", "bindings", "." ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/backend/index.js#L842-L855
train
vuejs/vue-devtools
src/backend/index.js
processObservables
function processObservables (instance) { var obs = instance.$observables if (obs) { return Object.keys(obs).map(key => { return { type: 'observables', key, value: instance[key] } }) } else { return [] } }
javascript
function processObservables (instance) { var obs = instance.$observables if (obs) { return Object.keys(obs).map(key => { return { type: 'observables', key, value: instance[key] } }) } else { return [] } }
[ "function", "processObservables", "(", "instance", ")", "{", "var", "obs", "=", "instance", ".", "$observables", "if", "(", "obs", ")", "{", "return", "Object", ".", "keys", "(", "obs", ")", ".", "map", "(", "key", "=>", "{", "return", "{", "type", ":", "'observables'", ",", "key", ",", "value", ":", "instance", "[", "key", "]", "}", "}", ")", "}", "else", "{", "return", "[", "]", "}", "}" ]
Process vue-rx observable bindings. @param {Vue} instance @return {Array}
[ "Process", "vue", "-", "rx", "observable", "bindings", "." ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/backend/index.js#L864-L877
train
vuejs/vue-devtools
src/backend/index.js
scrollIntoView
function scrollIntoView (instance) { const rect = getInstanceOrVnodeRect(instance) if (rect) { // TODO: Handle this for non-browser environments. window.scrollBy(0, rect.top + (rect.height - window.innerHeight) / 2) } }
javascript
function scrollIntoView (instance) { const rect = getInstanceOrVnodeRect(instance) if (rect) { // TODO: Handle this for non-browser environments. window.scrollBy(0, rect.top + (rect.height - window.innerHeight) / 2) } }
[ "function", "scrollIntoView", "(", "instance", ")", "{", "const", "rect", "=", "getInstanceOrVnodeRect", "(", "instance", ")", "if", "(", "rect", ")", "{", "window", ".", "scrollBy", "(", "0", ",", "rect", ".", "top", "+", "(", "rect", ".", "height", "-", "window", ".", "innerHeight", ")", "/", "2", ")", "}", "}" ]
Sroll a node into view. @param {Vue} instance
[ "Sroll", "a", "node", "into", "view", "." ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/backend/index.js#L885-L891
train
vuejs/vue-devtools
shells/chrome/src/devtools-background.js
onContextMenu
function onContextMenu ({ id }) { if (id === 'vue-inspect-instance') { const src = `window.__VUE_DEVTOOLS_CONTEXT_MENU_HAS_TARGET__` chrome.devtools.inspectedWindow.eval(src, function (res, err) { if (err) { console.log(err) } if (typeof res !== 'undefined' && res) { panelAction(() => { chrome.runtime.sendMessage('vue-get-context-menu-target') }, 'Open Vue devtools to see component details') } else { pendingAction = null toast('No Vue component was found', 'warn') } }) } }
javascript
function onContextMenu ({ id }) { if (id === 'vue-inspect-instance') { const src = `window.__VUE_DEVTOOLS_CONTEXT_MENU_HAS_TARGET__` chrome.devtools.inspectedWindow.eval(src, function (res, err) { if (err) { console.log(err) } if (typeof res !== 'undefined' && res) { panelAction(() => { chrome.runtime.sendMessage('vue-get-context-menu-target') }, 'Open Vue devtools to see component details') } else { pendingAction = null toast('No Vue component was found', 'warn') } }) } }
[ "function", "onContextMenu", "(", "{", "id", "}", ")", "{", "if", "(", "id", "===", "'vue-inspect-instance'", ")", "{", "const", "src", "=", "`", "`", "chrome", ".", "devtools", ".", "inspectedWindow", ".", "eval", "(", "src", ",", "function", "(", "res", ",", "err", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", "}", "if", "(", "typeof", "res", "!==", "'undefined'", "&&", "res", ")", "{", "panelAction", "(", "(", ")", "=>", "{", "chrome", ".", "runtime", ".", "sendMessage", "(", "'vue-get-context-menu-target'", ")", "}", ",", "'Open Vue devtools to see component details'", ")", "}", "else", "{", "pendingAction", "=", "null", "toast", "(", "'No Vue component was found'", ",", "'warn'", ")", "}", "}", ")", "}", "}" ]
Page context menu entry
[ "Page", "context", "menu", "entry" ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/shells/chrome/src/devtools-background.js#L56-L74
train
vuejs/vue-devtools
shells/chrome/src/devtools-background.js
panelAction
function panelAction (cb, message = null) { if (created && panelLoaded && panelShown) { cb() } else { pendingAction = cb message && toast(message) } }
javascript
function panelAction (cb, message = null) { if (created && panelLoaded && panelShown) { cb() } else { pendingAction = cb message && toast(message) } }
[ "function", "panelAction", "(", "cb", ",", "message", "=", "null", ")", "{", "if", "(", "created", "&&", "panelLoaded", "&&", "panelShown", ")", "{", "cb", "(", ")", "}", "else", "{", "pendingAction", "=", "cb", "message", "&&", "toast", "(", "message", ")", "}", "}" ]
Action that may execute immediatly or later when the Vue panel is ready
[ "Action", "that", "may", "execute", "immediatly", "or", "later", "when", "the", "Vue", "panel", "is", "ready" ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/shells/chrome/src/devtools-background.js#L79-L86
train
vuejs/vue-devtools
shells/chrome/src/devtools.js
injectScript
function injectScript (scriptName, cb) { const src = ` (function() { var script = document.constructor.prototype.createElement.call(document, 'script'); script.src = "${scriptName}"; document.documentElement.appendChild(script); script.parentNode.removeChild(script); })() ` chrome.devtools.inspectedWindow.eval(src, function (res, err) { if (err) { console.log(err) } cb() }) }
javascript
function injectScript (scriptName, cb) { const src = ` (function() { var script = document.constructor.prototype.createElement.call(document, 'script'); script.src = "${scriptName}"; document.documentElement.appendChild(script); script.parentNode.removeChild(script); })() ` chrome.devtools.inspectedWindow.eval(src, function (res, err) { if (err) { console.log(err) } cb() }) }
[ "function", "injectScript", "(", "scriptName", ",", "cb", ")", "{", "const", "src", "=", "`", "${", "scriptName", "}", "`", "chrome", ".", "devtools", ".", "inspectedWindow", ".", "eval", "(", "src", ",", "function", "(", "res", ",", "err", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", "}", "cb", "(", ")", "}", ")", "}" ]
Inject a globally evaluated script, in the same context with the actual user app. @param {String} scriptName @param {Function} cb
[ "Inject", "a", "globally", "evaluated", "script", "in", "the", "same", "context", "with", "the", "actual", "user", "app", "." ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/shells/chrome/src/devtools.js#L60-L75
train
vuejs/vue-devtools
src/backend/highlighter.js
getFragmentRect
function getFragmentRect ({ _fragmentStart, _fragmentEnd }) { let top, bottom, left, right util().mapNodeRange(_fragmentStart, _fragmentEnd, function (node) { let rect if (node.nodeType === 1 || node.getBoundingClientRect) { rect = node.getBoundingClientRect() } else if (node.nodeType === 3 && node.data.trim()) { rect = getTextRect(node) } if (rect) { if (!top || rect.top < top) { top = rect.top } if (!bottom || rect.bottom > bottom) { bottom = rect.bottom } if (!left || rect.left < left) { left = rect.left } if (!right || rect.right > right) { right = rect.right } } }) return { top, left, width: right - left, height: bottom - top } }
javascript
function getFragmentRect ({ _fragmentStart, _fragmentEnd }) { let top, bottom, left, right util().mapNodeRange(_fragmentStart, _fragmentEnd, function (node) { let rect if (node.nodeType === 1 || node.getBoundingClientRect) { rect = node.getBoundingClientRect() } else if (node.nodeType === 3 && node.data.trim()) { rect = getTextRect(node) } if (rect) { if (!top || rect.top < top) { top = rect.top } if (!bottom || rect.bottom > bottom) { bottom = rect.bottom } if (!left || rect.left < left) { left = rect.left } if (!right || rect.right > right) { right = rect.right } } }) return { top, left, width: right - left, height: bottom - top } }
[ "function", "getFragmentRect", "(", "{", "_fragmentStart", ",", "_fragmentEnd", "}", ")", "{", "let", "top", ",", "bottom", ",", "left", ",", "right", "util", "(", ")", ".", "mapNodeRange", "(", "_fragmentStart", ",", "_fragmentEnd", ",", "function", "(", "node", ")", "{", "let", "rect", "if", "(", "node", ".", "nodeType", "===", "1", "||", "node", ".", "getBoundingClientRect", ")", "{", "rect", "=", "node", ".", "getBoundingClientRect", "(", ")", "}", "else", "if", "(", "node", ".", "nodeType", "===", "3", "&&", "node", ".", "data", ".", "trim", "(", ")", ")", "{", "rect", "=", "getTextRect", "(", "node", ")", "}", "if", "(", "rect", ")", "{", "if", "(", "!", "top", "||", "rect", ".", "top", "<", "top", ")", "{", "top", "=", "rect", ".", "top", "}", "if", "(", "!", "bottom", "||", "rect", ".", "bottom", ">", "bottom", ")", "{", "bottom", "=", "rect", ".", "bottom", "}", "if", "(", "!", "left", "||", "rect", ".", "left", "<", "left", ")", "{", "left", "=", "rect", ".", "left", "}", "if", "(", "!", "right", "||", "rect", ".", "right", ">", "right", ")", "{", "right", "=", "rect", ".", "right", "}", "}", "}", ")", "return", "{", "top", ",", "left", ",", "width", ":", "right", "-", "left", ",", "height", ":", "bottom", "-", "top", "}", "}" ]
Highlight a fragment instance. Loop over its node range and determine its bounding box. @param {Vue} instance @return {Object}
[ "Highlight", "a", "fragment", "instance", ".", "Loop", "over", "its", "node", "range", "and", "determine", "its", "bounding", "box", "." ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/backend/highlighter.js#L106-L136
train
vuejs/vue-devtools
src/backend/highlighter.js
getTextRect
function getTextRect (node) { if (!isBrowser) return if (!range) range = document.createRange() range.selectNode(node) return range.getBoundingClientRect() }
javascript
function getTextRect (node) { if (!isBrowser) return if (!range) range = document.createRange() range.selectNode(node) return range.getBoundingClientRect() }
[ "function", "getTextRect", "(", "node", ")", "{", "if", "(", "!", "isBrowser", ")", "return", "if", "(", "!", "range", ")", "range", "=", "document", ".", "createRange", "(", ")", "range", ".", "selectNode", "(", "node", ")", "return", "range", ".", "getBoundingClientRect", "(", ")", "}" ]
Get the bounding rect for a text node using a Range. @param {Text} node @return {Rect}
[ "Get", "the", "bounding", "rect", "for", "a", "text", "node", "using", "a", "Range", "." ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/backend/highlighter.js#L145-L152
train
vuejs/vue-devtools
src/backend/highlighter.js
showOverlay
function showOverlay ({ width = 0, height = 0, top = 0, left = 0 }, content = []) { if (!isBrowser) return overlay.style.width = ~~width + 'px' overlay.style.height = ~~height + 'px' overlay.style.top = ~~top + 'px' overlay.style.left = ~~left + 'px' overlayContent.innerHTML = '' content.forEach(child => overlayContent.appendChild(child)) document.body.appendChild(overlay) }
javascript
function showOverlay ({ width = 0, height = 0, top = 0, left = 0 }, content = []) { if (!isBrowser) return overlay.style.width = ~~width + 'px' overlay.style.height = ~~height + 'px' overlay.style.top = ~~top + 'px' overlay.style.left = ~~left + 'px' overlayContent.innerHTML = '' content.forEach(child => overlayContent.appendChild(child)) document.body.appendChild(overlay) }
[ "function", "showOverlay", "(", "{", "width", "=", "0", ",", "height", "=", "0", ",", "top", "=", "0", ",", "left", "=", "0", "}", ",", "content", "=", "[", "]", ")", "{", "if", "(", "!", "isBrowser", ")", "return", "overlay", ".", "style", ".", "width", "=", "~", "~", "width", "+", "'px'", "overlay", ".", "style", ".", "height", "=", "~", "~", "height", "+", "'px'", "overlay", ".", "style", ".", "top", "=", "~", "~", "top", "+", "'px'", "overlay", ".", "style", ".", "left", "=", "~", "~", "left", "+", "'px'", "overlayContent", ".", "innerHTML", "=", "''", "content", ".", "forEach", "(", "child", "=>", "overlayContent", ".", "appendChild", "(", "child", ")", ")", "document", ".", "body", ".", "appendChild", "(", "overlay", ")", "}" ]
Display the overlay with given rect. @param {Rect}
[ "Display", "the", "overlay", "with", "given", "rect", "." ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/backend/highlighter.js#L160-L172
train
vuejs/vue-devtools
src/util.js
basename
function basename (filename, ext) { return path.basename( filename.replace(/^[a-zA-Z]:/, '').replace(/\\/g, '/'), ext ) }
javascript
function basename (filename, ext) { return path.basename( filename.replace(/^[a-zA-Z]:/, '').replace(/\\/g, '/'), ext ) }
[ "function", "basename", "(", "filename", ",", "ext", ")", "{", "return", "path", ".", "basename", "(", "filename", ".", "replace", "(", "/", "^[a-zA-Z]:", "/", ",", "''", ")", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'/'", ")", ",", "ext", ")", "}" ]
Use a custom basename functions instead of the shimed version because it doesn't work on Windows
[ "Use", "a", "custom", "basename", "functions", "instead", "of", "the", "shimed", "version", "because", "it", "doesn", "t", "work", "on", "Windows" ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/util.js#L231-L236
train
vuejs/vue-devtools
src/util.js
sanitize
function sanitize (data) { if ( !isPrimitive(data) && !Array.isArray(data) && !isPlainObject(data) ) { // handle types that will probably cause issues in // the structured clone return Object.prototype.toString.call(data) } else { return data } }
javascript
function sanitize (data) { if ( !isPrimitive(data) && !Array.isArray(data) && !isPlainObject(data) ) { // handle types that will probably cause issues in // the structured clone return Object.prototype.toString.call(data) } else { return data } }
[ "function", "sanitize", "(", "data", ")", "{", "if", "(", "!", "isPrimitive", "(", "data", ")", "&&", "!", "Array", ".", "isArray", "(", "data", ")", "&&", "!", "isPlainObject", "(", "data", ")", ")", "{", "return", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "data", ")", "}", "else", "{", "return", "data", "}", "}" ]
Sanitize data to be posted to the other side. Since the message posted is sent with structured clone, we need to filter out any types that might cause an error. @param {*} data @return {*}
[ "Sanitize", "data", "to", "be", "posted", "to", "the", "other", "side", ".", "Since", "the", "message", "posted", "is", "sent", "with", "structured", "clone", "we", "need", "to", "filter", "out", "any", "types", "that", "might", "cause", "an", "error", "." ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/util.js#L368-L380
train
vuejs/vue-devtools
src/util.js
internalSearchObject
function internalSearchObject (obj, searchTerm, seen, depth) { if (depth > SEARCH_MAX_DEPTH) { return false } let match = false const keys = Object.keys(obj) let key, value for (let i = 0; i < keys.length; i++) { key = keys[i] value = obj[key] match = internalSearchCheck(searchTerm, key, value, seen, depth + 1) if (match) { break } } return match }
javascript
function internalSearchObject (obj, searchTerm, seen, depth) { if (depth > SEARCH_MAX_DEPTH) { return false } let match = false const keys = Object.keys(obj) let key, value for (let i = 0; i < keys.length; i++) { key = keys[i] value = obj[key] match = internalSearchCheck(searchTerm, key, value, seen, depth + 1) if (match) { break } } return match }
[ "function", "internalSearchObject", "(", "obj", ",", "searchTerm", ",", "seen", ",", "depth", ")", "{", "if", "(", "depth", ">", "SEARCH_MAX_DEPTH", ")", "{", "return", "false", "}", "let", "match", "=", "false", "const", "keys", "=", "Object", ".", "keys", "(", "obj", ")", "let", "key", ",", "value", "for", "(", "let", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "key", "=", "keys", "[", "i", "]", "value", "=", "obj", "[", "key", "]", "match", "=", "internalSearchCheck", "(", "searchTerm", ",", "key", ",", "value", ",", "seen", ",", "depth", "+", "1", ")", "if", "(", "match", ")", "{", "break", "}", "}", "return", "match", "}" ]
Executes a search on each field of the provided object @param {*} obj Search target @param {string} searchTerm Search string @param {Map<any,boolean>} seen Map containing the search result to prevent stack overflow by walking on the same object multiple times @param {number} depth Deep search depth level, which is capped to prevent performance issues @returns {boolean} Search match
[ "Executes", "a", "search", "on", "each", "field", "of", "the", "provided", "object" ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/util.js#L421-L437
train
vuejs/vue-devtools
src/util.js
internalSearchArray
function internalSearchArray (array, searchTerm, seen, depth) { if (depth > SEARCH_MAX_DEPTH) { return false } let match = false let value for (let i = 0; i < array.length; i++) { value = array[i] match = internalSearchCheck(searchTerm, null, value, seen, depth + 1) if (match) { break } } return match }
javascript
function internalSearchArray (array, searchTerm, seen, depth) { if (depth > SEARCH_MAX_DEPTH) { return false } let match = false let value for (let i = 0; i < array.length; i++) { value = array[i] match = internalSearchCheck(searchTerm, null, value, seen, depth + 1) if (match) { break } } return match }
[ "function", "internalSearchArray", "(", "array", ",", "searchTerm", ",", "seen", ",", "depth", ")", "{", "if", "(", "depth", ">", "SEARCH_MAX_DEPTH", ")", "{", "return", "false", "}", "let", "match", "=", "false", "let", "value", "for", "(", "let", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "value", "=", "array", "[", "i", "]", "match", "=", "internalSearchCheck", "(", "searchTerm", ",", "null", ",", "value", ",", "seen", ",", "depth", "+", "1", ")", "if", "(", "match", ")", "{", "break", "}", "}", "return", "match", "}" ]
Executes a search on each value of the provided array @param {*} array Search target @param {string} searchTerm Search string @param {Map<any,boolean>} seen Map containing the search result to prevent stack overflow by walking on the same object multiple times @param {number} depth Deep search depth level, which is capped to prevent performance issues @returns {boolean} Search match
[ "Executes", "a", "search", "on", "each", "value", "of", "the", "provided", "array" ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/util.js#L447-L461
train
vuejs/vue-devtools
src/util.js
internalSearchCheck
function internalSearchCheck (searchTerm, key, value, seen, depth) { let match = false let result if (key === '_custom') { key = value.display value = value.value } (result = specialTokenToString(value)) && (value = result) if (key && compare(key, searchTerm)) { match = true seen.set(value, true) } else if (seen.has(value)) { match = seen.get(value) } else if (Array.isArray(value)) { seen.set(value, null) match = internalSearchArray(value, searchTerm, seen, depth) seen.set(value, match) } else if (isPlainObject(value)) { seen.set(value, null) match = internalSearchObject(value, searchTerm, seen, depth) seen.set(value, match) } else if (compare(value, searchTerm)) { match = true seen.set(value, true) } return match }
javascript
function internalSearchCheck (searchTerm, key, value, seen, depth) { let match = false let result if (key === '_custom') { key = value.display value = value.value } (result = specialTokenToString(value)) && (value = result) if (key && compare(key, searchTerm)) { match = true seen.set(value, true) } else if (seen.has(value)) { match = seen.get(value) } else if (Array.isArray(value)) { seen.set(value, null) match = internalSearchArray(value, searchTerm, seen, depth) seen.set(value, match) } else if (isPlainObject(value)) { seen.set(value, null) match = internalSearchObject(value, searchTerm, seen, depth) seen.set(value, match) } else if (compare(value, searchTerm)) { match = true seen.set(value, true) } return match }
[ "function", "internalSearchCheck", "(", "searchTerm", ",", "key", ",", "value", ",", "seen", ",", "depth", ")", "{", "let", "match", "=", "false", "let", "result", "if", "(", "key", "===", "'_custom'", ")", "{", "key", "=", "value", ".", "display", "value", "=", "value", ".", "value", "}", "(", "result", "=", "specialTokenToString", "(", "value", ")", ")", "&&", "(", "value", "=", "result", ")", "if", "(", "key", "&&", "compare", "(", "key", ",", "searchTerm", ")", ")", "{", "match", "=", "true", "seen", ".", "set", "(", "value", ",", "true", ")", "}", "else", "if", "(", "seen", ".", "has", "(", "value", ")", ")", "{", "match", "=", "seen", ".", "get", "(", "value", ")", "}", "else", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "seen", ".", "set", "(", "value", ",", "null", ")", "match", "=", "internalSearchArray", "(", "value", ",", "searchTerm", ",", "seen", ",", "depth", ")", "seen", ".", "set", "(", "value", ",", "match", ")", "}", "else", "if", "(", "isPlainObject", "(", "value", ")", ")", "{", "seen", ".", "set", "(", "value", ",", "null", ")", "match", "=", "internalSearchObject", "(", "value", ",", "searchTerm", ",", "seen", ",", "depth", ")", "seen", ".", "set", "(", "value", ",", "match", ")", "}", "else", "if", "(", "compare", "(", "value", ",", "searchTerm", ")", ")", "{", "match", "=", "true", "seen", ".", "set", "(", "value", ",", "true", ")", "}", "return", "match", "}" ]
Checks if the provided field matches the search terms @param {string} searchTerm Search string @param {string} key Field key (null if from array) @param {*} value Field value @param {Map<any,boolean>} seen Map containing the search result to prevent stack overflow by walking on the same object multiple times @param {number} depth Deep search depth level, which is capped to prevent performance issues @returns {boolean} Search match
[ "Checks", "if", "the", "provided", "field", "matches", "the", "search", "terms" ]
4de4b86388453cd07f0c1bf967d43a4dd4b011c9
https://github.com/vuejs/vue-devtools/blob/4de4b86388453cd07f0c1bf967d43a4dd4b011c9/src/util.js#L472-L498
train
pixijs/pixi.js
packages/canvas/canvas-renderer/src/utils/canUseNewCanvasBlendModes.js
createColoredCanvas
function createColoredCanvas(color) { const canvas = document.createElement('canvas'); canvas.width = 6; canvas.height = 1; const context = canvas.getContext('2d'); context.fillStyle = color; context.fillRect(0, 0, 6, 1); return canvas; }
javascript
function createColoredCanvas(color) { const canvas = document.createElement('canvas'); canvas.width = 6; canvas.height = 1; const context = canvas.getContext('2d'); context.fillStyle = color; context.fillRect(0, 0, 6, 1); return canvas; }
[ "function", "createColoredCanvas", "(", "color", ")", "{", "const", "canvas", "=", "document", ".", "createElement", "(", "'canvas'", ")", ";", "canvas", ".", "width", "=", "6", ";", "canvas", ".", "height", "=", "1", ";", "const", "context", "=", "canvas", ".", "getContext", "(", "'2d'", ")", ";", "context", ".", "fillStyle", "=", "color", ";", "context", ".", "fillRect", "(", "0", ",", "0", ",", "6", ",", "1", ")", ";", "return", "canvas", ";", "}" ]
Creates a little colored canvas @ignore @param {string} color - The color to make the canvas @return {canvas} a small canvas element
[ "Creates", "a", "little", "colored", "canvas" ]
99ae03b7565ae7ca5a6de633b0a277f7128fa4d0
https://github.com/pixijs/pixi.js/blob/99ae03b7565ae7ca5a6de633b0a277f7128fa4d0/packages/canvas/canvas-renderer/src/utils/canUseNewCanvasBlendModes.js#L8-L21
train
pixijs/pixi.js
packages/graphics/src/utils/buildRoundedRectangle.js
getPt
function getPt(n1, n2, perc) { const diff = n2 - n1; return n1 + (diff * perc); }
javascript
function getPt(n1, n2, perc) { const diff = n2 - n1; return n1 + (diff * perc); }
[ "function", "getPt", "(", "n1", ",", "n2", ",", "perc", ")", "{", "const", "diff", "=", "n2", "-", "n1", ";", "return", "n1", "+", "(", "diff", "*", "perc", ")", ";", "}" ]
Calculate a single point for a quadratic bezier curve. Utility function used by quadraticBezierCurve. Ignored from docs since it is not directly exposed. @ignore @private @param {number} n1 - first number @param {number} n2 - second number @param {number} perc - percentage @return {number} the result
[ "Calculate", "a", "single", "point", "for", "a", "quadratic", "bezier", "curve", ".", "Utility", "function", "used", "by", "quadraticBezierCurve", ".", "Ignored", "from", "docs", "since", "it", "is", "not", "directly", "exposed", "." ]
99ae03b7565ae7ca5a6de633b0a277f7128fa4d0
https://github.com/pixijs/pixi.js/blob/99ae03b7565ae7ca5a6de633b0a277f7128fa4d0/packages/graphics/src/utils/buildRoundedRectangle.js#L90-L95
train
pixijs/pixi.js
packages/prepare/src/Prepare.js
uploadGraphics
function uploadGraphics(renderer, item) { if (item instanceof Graphics) { // if the item is not dirty and already has webgl data, then it got prepared or rendered // before now and we shouldn't waste time updating it again if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { renderer.plugins.graphics.updateGraphics(item); } return true; } return false; }
javascript
function uploadGraphics(renderer, item) { if (item instanceof Graphics) { // if the item is not dirty and already has webgl data, then it got prepared or rendered // before now and we shouldn't waste time updating it again if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { renderer.plugins.graphics.updateGraphics(item); } return true; } return false; }
[ "function", "uploadGraphics", "(", "renderer", ",", "item", ")", "{", "if", "(", "item", "instanceof", "Graphics", ")", "{", "if", "(", "item", ".", "dirty", "||", "item", ".", "clearDirty", "||", "!", "item", ".", "_webGL", "[", "renderer", ".", "plugins", ".", "graphics", ".", "CONTEXT_UID", "]", ")", "{", "renderer", ".", "plugins", ".", "graphics", ".", "updateGraphics", "(", "item", ")", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Built-in hook to upload PIXI.Graphics to the GPU. @private @param {PIXI.Renderer} renderer - instance of the webgl renderer @param {PIXI.DisplayObject} item - Item to check @return {boolean} If item was uploaded.
[ "Built", "-", "in", "hook", "to", "upload", "PIXI", ".", "Graphics", "to", "the", "GPU", "." ]
99ae03b7565ae7ca5a6de633b0a277f7128fa4d0
https://github.com/pixijs/pixi.js/blob/99ae03b7565ae7ca5a6de633b0a277f7128fa4d0/packages/prepare/src/Prepare.js#L65-L80
train
pixijs/pixi.js
packages/prepare/src/Prepare.js
findGraphics
function findGraphics(item, queue) { if (item instanceof Graphics) { queue.push(item); return true; } return false; }
javascript
function findGraphics(item, queue) { if (item instanceof Graphics) { queue.push(item); return true; } return false; }
[ "function", "findGraphics", "(", "item", ",", "queue", ")", "{", "if", "(", "item", "instanceof", "Graphics", ")", "{", "queue", ".", "push", "(", "item", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Built-in hook to find graphics. @private @param {PIXI.DisplayObject} item - Display object to check @param {Array<*>} queue - Collection of items to upload @return {boolean} if a PIXI.Graphics object was found.
[ "Built", "-", "in", "hook", "to", "find", "graphics", "." ]
99ae03b7565ae7ca5a6de633b0a277f7128fa4d0
https://github.com/pixijs/pixi.js/blob/99ae03b7565ae7ca5a6de633b0a277f7128fa4d0/packages/prepare/src/Prepare.js#L90-L100
train
pixijs/pixi.js
packages/prepare/src/BasePrepare.js
findMultipleBaseTextures
function findMultipleBaseTextures(item, queue) { let result = false; // Objects with multiple textures if (item && item._textures && item._textures.length) { for (let i = 0; i < item._textures.length; i++) { if (item._textures[i] instanceof Texture) { const baseTexture = item._textures[i].baseTexture; if (queue.indexOf(baseTexture) === -1) { queue.push(baseTexture); result = true; } } } } return result; }
javascript
function findMultipleBaseTextures(item, queue) { let result = false; // Objects with multiple textures if (item && item._textures && item._textures.length) { for (let i = 0; i < item._textures.length; i++) { if (item._textures[i] instanceof Texture) { const baseTexture = item._textures[i].baseTexture; if (queue.indexOf(baseTexture) === -1) { queue.push(baseTexture); result = true; } } } } return result; }
[ "function", "findMultipleBaseTextures", "(", "item", ",", "queue", ")", "{", "let", "result", "=", "false", ";", "if", "(", "item", "&&", "item", ".", "_textures", "&&", "item", ".", "_textures", ".", "length", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "item", ".", "_textures", ".", "length", ";", "i", "++", ")", "{", "if", "(", "item", ".", "_textures", "[", "i", "]", "instanceof", "Texture", ")", "{", "const", "baseTexture", "=", "item", ".", "_textures", "[", "i", "]", ".", "baseTexture", ";", "if", "(", "queue", ".", "indexOf", "(", "baseTexture", ")", "===", "-", "1", ")", "{", "queue", ".", "push", "(", "baseTexture", ")", ";", "result", "=", "true", ";", "}", "}", "}", "}", "return", "result", ";", "}" ]
Built-in hook to find multiple textures from objects like AnimatedSprites. @private @param {PIXI.DisplayObject} item - Display object to check @param {Array<*>} queue - Collection of items to upload @return {boolean} if a PIXI.Texture object was found.
[ "Built", "-", "in", "hook", "to", "find", "multiple", "textures", "from", "objects", "like", "AnimatedSprites", "." ]
99ae03b7565ae7ca5a6de633b0a277f7128fa4d0
https://github.com/pixijs/pixi.js/blob/99ae03b7565ae7ca5a6de633b0a277f7128fa4d0/packages/prepare/src/BasePrepare.js#L323-L346
train
pixijs/pixi.js
packages/prepare/src/BasePrepare.js
findBaseTexture
function findBaseTexture(item, queue) { // Objects with textures, like Sprites/Text if (item instanceof BaseTexture) { if (queue.indexOf(item) === -1) { queue.push(item); } return true; } return false; }
javascript
function findBaseTexture(item, queue) { // Objects with textures, like Sprites/Text if (item instanceof BaseTexture) { if (queue.indexOf(item) === -1) { queue.push(item); } return true; } return false; }
[ "function", "findBaseTexture", "(", "item", ",", "queue", ")", "{", "if", "(", "item", "instanceof", "BaseTexture", ")", "{", "if", "(", "queue", ".", "indexOf", "(", "item", ")", "===", "-", "1", ")", "{", "queue", ".", "push", "(", "item", ")", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Built-in hook to find BaseTextures from Sprites. @private @param {PIXI.DisplayObject} item - Display object to check @param {Array<*>} queue - Collection of items to upload @return {boolean} if a PIXI.Texture object was found.
[ "Built", "-", "in", "hook", "to", "find", "BaseTextures", "from", "Sprites", "." ]
99ae03b7565ae7ca5a6de633b0a277f7128fa4d0
https://github.com/pixijs/pixi.js/blob/99ae03b7565ae7ca5a6de633b0a277f7128fa4d0/packages/prepare/src/BasePrepare.js#L356-L370
train
pixijs/pixi.js
packages/prepare/src/BasePrepare.js
findTexture
function findTexture(item, queue) { if (item._texture && item._texture instanceof Texture) { const texture = item._texture.baseTexture; if (queue.indexOf(texture) === -1) { queue.push(texture); } return true; } return false; }
javascript
function findTexture(item, queue) { if (item._texture && item._texture instanceof Texture) { const texture = item._texture.baseTexture; if (queue.indexOf(texture) === -1) { queue.push(texture); } return true; } return false; }
[ "function", "findTexture", "(", "item", ",", "queue", ")", "{", "if", "(", "item", ".", "_texture", "&&", "item", ".", "_texture", "instanceof", "Texture", ")", "{", "const", "texture", "=", "item", ".", "_texture", ".", "baseTexture", ";", "if", "(", "queue", ".", "indexOf", "(", "texture", ")", "===", "-", "1", ")", "{", "queue", ".", "push", "(", "texture", ")", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Built-in hook to find textures from objects. @private @param {PIXI.DisplayObject} item - Display object to check @param {Array<*>} queue - Collection of items to upload @return {boolean} if a PIXI.Texture object was found.
[ "Built", "-", "in", "hook", "to", "find", "textures", "from", "objects", "." ]
99ae03b7565ae7ca5a6de633b0a277f7128fa4d0
https://github.com/pixijs/pixi.js/blob/99ae03b7565ae7ca5a6de633b0a277f7128fa4d0/packages/prepare/src/BasePrepare.js#L380-L395
train
pixijs/pixi.js
packages/prepare/src/BasePrepare.js
drawText
function drawText(helper, item) { if (item instanceof Text) { // updating text will return early if it is not dirty item.updateText(true); return true; } return false; }
javascript
function drawText(helper, item) { if (item instanceof Text) { // updating text will return early if it is not dirty item.updateText(true); return true; } return false; }
[ "function", "drawText", "(", "helper", ",", "item", ")", "{", "if", "(", "item", "instanceof", "Text", ")", "{", "item", ".", "updateText", "(", "true", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Built-in hook to draw PIXI.Text to its texture. @private @param {PIXI.Renderer|PIXI.CanvasPrepare} helper - Not used by this upload handler @param {PIXI.DisplayObject} item - Item to check @return {boolean} If item was uploaded.
[ "Built", "-", "in", "hook", "to", "draw", "PIXI", ".", "Text", "to", "its", "texture", "." ]
99ae03b7565ae7ca5a6de633b0a277f7128fa4d0
https://github.com/pixijs/pixi.js/blob/99ae03b7565ae7ca5a6de633b0a277f7128fa4d0/packages/prepare/src/BasePrepare.js#L405-L416
train
pixijs/pixi.js
packages/prepare/src/BasePrepare.js
calculateTextStyle
function calculateTextStyle(helper, item) { if (item instanceof TextStyle) { const font = item.toFontString(); TextMetrics.measureFont(font); return true; } return false; }
javascript
function calculateTextStyle(helper, item) { if (item instanceof TextStyle) { const font = item.toFontString(); TextMetrics.measureFont(font); return true; } return false; }
[ "function", "calculateTextStyle", "(", "helper", ",", "item", ")", "{", "if", "(", "item", "instanceof", "TextStyle", ")", "{", "const", "font", "=", "item", ".", "toFontString", "(", ")", ";", "TextMetrics", ".", "measureFont", "(", "font", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Built-in hook to calculate a text style for a PIXI.Text object. @private @param {PIXI.Renderer|PIXI.CanvasPrepare} helper - Not used by this upload handler @param {PIXI.DisplayObject} item - Item to check @return {boolean} If item was uploaded.
[ "Built", "-", "in", "hook", "to", "calculate", "a", "text", "style", "for", "a", "PIXI", ".", "Text", "object", "." ]
99ae03b7565ae7ca5a6de633b0a277f7128fa4d0
https://github.com/pixijs/pixi.js/blob/99ae03b7565ae7ca5a6de633b0a277f7128fa4d0/packages/prepare/src/BasePrepare.js#L426-L438
train
pixijs/pixi.js
packages/prepare/src/BasePrepare.js
findText
function findText(item, queue) { if (item instanceof Text) { // push the text style to prepare it - this can be really expensive if (queue.indexOf(item.style) === -1) { queue.push(item.style); } // also push the text object so that we can render it (to canvas/texture) if needed if (queue.indexOf(item) === -1) { queue.push(item); } // also push the Text's texture for upload to GPU const texture = item._texture.baseTexture; if (queue.indexOf(texture) === -1) { queue.push(texture); } return true; } return false; }
javascript
function findText(item, queue) { if (item instanceof Text) { // push the text style to prepare it - this can be really expensive if (queue.indexOf(item.style) === -1) { queue.push(item.style); } // also push the text object so that we can render it (to canvas/texture) if needed if (queue.indexOf(item) === -1) { queue.push(item); } // also push the Text's texture for upload to GPU const texture = item._texture.baseTexture; if (queue.indexOf(texture) === -1) { queue.push(texture); } return true; } return false; }
[ "function", "findText", "(", "item", ",", "queue", ")", "{", "if", "(", "item", "instanceof", "Text", ")", "{", "if", "(", "queue", ".", "indexOf", "(", "item", ".", "style", ")", "===", "-", "1", ")", "{", "queue", ".", "push", "(", "item", ".", "style", ")", ";", "}", "if", "(", "queue", ".", "indexOf", "(", "item", ")", "===", "-", "1", ")", "{", "queue", ".", "push", "(", "item", ")", ";", "}", "const", "texture", "=", "item", ".", "_texture", ".", "baseTexture", ";", "if", "(", "queue", ".", "indexOf", "(", "texture", ")", "===", "-", "1", ")", "{", "queue", ".", "push", "(", "texture", ")", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Built-in hook to find Text objects. @private @param {PIXI.DisplayObject} item - Display object to check @param {Array<*>} queue - Collection of items to upload @return {boolean} if a PIXI.Text object was found.
[ "Built", "-", "in", "hook", "to", "find", "Text", "objects", "." ]
99ae03b7565ae7ca5a6de633b0a277f7128fa4d0
https://github.com/pixijs/pixi.js/blob/99ae03b7565ae7ca5a6de633b0a277f7128fa4d0/packages/prepare/src/BasePrepare.js#L448-L474
train
pixijs/pixi.js
packages/prepare/src/BasePrepare.js
findTextStyle
function findTextStyle(item, queue) { if (item instanceof TextStyle) { if (queue.indexOf(item) === -1) { queue.push(item); } return true; } return false; }
javascript
function findTextStyle(item, queue) { if (item instanceof TextStyle) { if (queue.indexOf(item) === -1) { queue.push(item); } return true; } return false; }
[ "function", "findTextStyle", "(", "item", ",", "queue", ")", "{", "if", "(", "item", "instanceof", "TextStyle", ")", "{", "if", "(", "queue", ".", "indexOf", "(", "item", ")", "===", "-", "1", ")", "{", "queue", ".", "push", "(", "item", ")", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Built-in hook to find TextStyle objects. @private @param {PIXI.TextStyle} item - Display object to check @param {Array<*>} queue - Collection of items to upload @return {boolean} if a PIXI.TextStyle object was found.
[ "Built", "-", "in", "hook", "to", "find", "TextStyle", "objects", "." ]
99ae03b7565ae7ca5a6de633b0a277f7128fa4d0
https://github.com/pixijs/pixi.js/blob/99ae03b7565ae7ca5a6de633b0a277f7128fa4d0/packages/prepare/src/BasePrepare.js#L484-L497
train
pixijs/pixi.js
packages/text/src/TextStyle.js
getSingleColor
function getSingleColor(color) { if (typeof color === 'number') { return hex2string(color); } else if ( typeof color === 'string' ) { if ( color.indexOf('0x') === 0 ) { color = color.replace('0x', '#'); } } return color; }
javascript
function getSingleColor(color) { if (typeof color === 'number') { return hex2string(color); } else if ( typeof color === 'string' ) { if ( color.indexOf('0x') === 0 ) { color = color.replace('0x', '#'); } } return color; }
[ "function", "getSingleColor", "(", "color", ")", "{", "if", "(", "typeof", "color", "===", "'number'", ")", "{", "return", "hex2string", "(", "color", ")", ";", "}", "else", "if", "(", "typeof", "color", "===", "'string'", ")", "{", "if", "(", "color", ".", "indexOf", "(", "'0x'", ")", "===", "0", ")", "{", "color", "=", "color", ".", "replace", "(", "'0x'", ",", "'#'", ")", ";", "}", "}", "return", "color", ";", "}" ]
Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. @private @param {number|number[]} color @return {string} The color as a string.
[ "Utility", "function", "to", "convert", "hexadecimal", "colors", "to", "strings", "and", "simply", "return", "the", "color", "if", "it", "s", "a", "string", "." ]
99ae03b7565ae7ca5a6de633b0a277f7128fa4d0
https://github.com/pixijs/pixi.js/blob/99ae03b7565ae7ca5a6de633b0a277f7128fa4d0/packages/text/src/TextStyle.js#L727-L742
train
pixijs/pixi.js
packages/text/src/TextStyle.js
deepCopyProperties
function deepCopyProperties(target, source, propertyObj) { for (const prop in propertyObj) { if (Array.isArray(source[prop])) { target[prop] = source[prop].slice(); } else { target[prop] = source[prop]; } } }
javascript
function deepCopyProperties(target, source, propertyObj) { for (const prop in propertyObj) { if (Array.isArray(source[prop])) { target[prop] = source[prop].slice(); } else { target[prop] = source[prop]; } } }
[ "function", "deepCopyProperties", "(", "target", ",", "source", ",", "propertyObj", ")", "{", "for", "(", "const", "prop", "in", "propertyObj", ")", "{", "if", "(", "Array", ".", "isArray", "(", "source", "[", "prop", "]", ")", ")", "{", "target", "[", "prop", "]", "=", "source", "[", "prop", "]", ".", "slice", "(", ")", ";", "}", "else", "{", "target", "[", "prop", "]", "=", "source", "[", "prop", "]", ";", "}", "}", "}" ]
Utility function to ensure that object properties are copied by value, and not by reference @private @param {Object} target Target object to copy properties into @param {Object} source Source object for the properties to copy @param {string} propertyObj Object containing properties names we want to loop over
[ "Utility", "function", "to", "ensure", "that", "object", "properties", "are", "copied", "by", "value", "and", "not", "by", "reference" ]
99ae03b7565ae7ca5a6de633b0a277f7128fa4d0
https://github.com/pixijs/pixi.js/blob/99ae03b7565ae7ca5a6de633b0a277f7128fa4d0/packages/text/src/TextStyle.js#L806-L814
train
pixijs/pixi.js
packages/utils/src/color/premultiply.js
mapPremultipliedBlendModes
function mapPremultipliedBlendModes() { const pm = []; const npm = []; for (let i = 0; i < 32; i++) { pm[i] = i; npm[i] = i; } pm[BLEND_MODES.NORMAL_NPM] = BLEND_MODES.NORMAL; pm[BLEND_MODES.ADD_NPM] = BLEND_MODES.ADD; pm[BLEND_MODES.SCREEN_NPM] = BLEND_MODES.SCREEN; npm[BLEND_MODES.NORMAL] = BLEND_MODES.NORMAL_NPM; npm[BLEND_MODES.ADD] = BLEND_MODES.ADD_NPM; npm[BLEND_MODES.SCREEN] = BLEND_MODES.SCREEN_NPM; const array = []; array.push(npm); array.push(pm); return array; }
javascript
function mapPremultipliedBlendModes() { const pm = []; const npm = []; for (let i = 0; i < 32; i++) { pm[i] = i; npm[i] = i; } pm[BLEND_MODES.NORMAL_NPM] = BLEND_MODES.NORMAL; pm[BLEND_MODES.ADD_NPM] = BLEND_MODES.ADD; pm[BLEND_MODES.SCREEN_NPM] = BLEND_MODES.SCREEN; npm[BLEND_MODES.NORMAL] = BLEND_MODES.NORMAL_NPM; npm[BLEND_MODES.ADD] = BLEND_MODES.ADD_NPM; npm[BLEND_MODES.SCREEN] = BLEND_MODES.SCREEN_NPM; const array = []; array.push(npm); array.push(pm); return array; }
[ "function", "mapPremultipliedBlendModes", "(", ")", "{", "const", "pm", "=", "[", "]", ";", "const", "npm", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "32", ";", "i", "++", ")", "{", "pm", "[", "i", "]", "=", "i", ";", "npm", "[", "i", "]", "=", "i", ";", "}", "pm", "[", "BLEND_MODES", ".", "NORMAL_NPM", "]", "=", "BLEND_MODES", ".", "NORMAL", ";", "pm", "[", "BLEND_MODES", ".", "ADD_NPM", "]", "=", "BLEND_MODES", ".", "ADD", ";", "pm", "[", "BLEND_MODES", ".", "SCREEN_NPM", "]", "=", "BLEND_MODES", ".", "SCREEN", ";", "npm", "[", "BLEND_MODES", ".", "NORMAL", "]", "=", "BLEND_MODES", ".", "NORMAL_NPM", ";", "npm", "[", "BLEND_MODES", ".", "ADD", "]", "=", "BLEND_MODES", ".", "ADD_NPM", ";", "npm", "[", "BLEND_MODES", ".", "SCREEN", "]", "=", "BLEND_MODES", ".", "SCREEN_NPM", ";", "const", "array", "=", "[", "]", ";", "array", ".", "push", "(", "npm", ")", ";", "array", ".", "push", "(", "pm", ")", ";", "return", "array", ";", "}" ]
Corrects PixiJS blend, takes premultiplied alpha into account @memberof PIXI.utils @function mapPremultipliedBlendModes @private @param {Array<number[]>} [array] - The array to output into. @return {Array<number[]>} Mapped modes.
[ "Corrects", "PixiJS", "blend", "takes", "premultiplied", "alpha", "into", "account" ]
99ae03b7565ae7ca5a6de633b0a277f7128fa4d0
https://github.com/pixijs/pixi.js/blob/99ae03b7565ae7ca5a6de633b0a277f7128fa4d0/packages/utils/src/color/premultiply.js#L12-L37
train
SheetJS/js-xlsx
xlsx.js
sleuth_fat
function sleuth_fat(idx, cnt, sectors, ssz, fat_addrs) { var q = ENDOFCHAIN; if(idx === ENDOFCHAIN) { if(cnt !== 0) throw new Error("DIFAT chain shorter than expected"); } else if(idx !== -1 /*FREESECT*/) { var sector = sectors[idx], m = (ssz>>>2)-1; if(!sector) return; for(var i = 0; i < m; ++i) { if((q = __readInt32LE(sector,i*4)) === ENDOFCHAIN) break; fat_addrs.push(q); } sleuth_fat(__readInt32LE(sector,ssz-4),cnt - 1, sectors, ssz, fat_addrs); } }
javascript
function sleuth_fat(idx, cnt, sectors, ssz, fat_addrs) { var q = ENDOFCHAIN; if(idx === ENDOFCHAIN) { if(cnt !== 0) throw new Error("DIFAT chain shorter than expected"); } else if(idx !== -1 /*FREESECT*/) { var sector = sectors[idx], m = (ssz>>>2)-1; if(!sector) return; for(var i = 0; i < m; ++i) { if((q = __readInt32LE(sector,i*4)) === ENDOFCHAIN) break; fat_addrs.push(q); } sleuth_fat(__readInt32LE(sector,ssz-4),cnt - 1, sectors, ssz, fat_addrs); } }
[ "function", "sleuth_fat", "(", "idx", ",", "cnt", ",", "sectors", ",", "ssz", ",", "fat_addrs", ")", "{", "var", "q", "=", "ENDOFCHAIN", ";", "if", "(", "idx", "===", "ENDOFCHAIN", ")", "{", "if", "(", "cnt", "!==", "0", ")", "throw", "new", "Error", "(", "\"DIFAT chain shorter than expected\"", ")", ";", "}", "else", "if", "(", "idx", "!==", "-", "1", ")", "{", "var", "sector", "=", "sectors", "[", "idx", "]", ",", "m", "=", "(", "ssz", ">>>", "2", ")", "-", "1", ";", "if", "(", "!", "sector", ")", "return", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "m", ";", "++", "i", ")", "{", "if", "(", "(", "q", "=", "__readInt32LE", "(", "sector", ",", "i", "*", "4", ")", ")", "===", "ENDOFCHAIN", ")", "break", ";", "fat_addrs", ".", "push", "(", "q", ")", ";", "}", "sleuth_fat", "(", "__readInt32LE", "(", "sector", ",", "ssz", "-", "4", ")", ",", "cnt", "-", "1", ",", "sectors", ",", "ssz", ",", "fat_addrs", ")", ";", "}", "}" ]
Chase down the rest of the DIFAT chain to build a comprehensive list DIFAT chains by storing the next sector number as the last 32 bits
[ "Chase", "down", "the", "rest", "of", "the", "DIFAT", "chain", "to", "build", "a", "comprehensive", "list", "DIFAT", "chains", "by", "storing", "the", "next", "sector", "number", "as", "the", "last", "32", "bits" ]
9a6d8a1d3d80c78dad5201fb389316f935279cdc
https://github.com/SheetJS/js-xlsx/blob/9a6d8a1d3d80c78dad5201fb389316f935279cdc/xlsx.js#L1537-L1550
train
SheetJS/js-xlsx
xlsx.js
get_sector_list
function get_sector_list(sectors, start, fat_addrs, ssz, chkd) { var buf = [], buf_chain = []; if(!chkd) chkd = []; var modulus = ssz - 1, j = 0, jj = 0; for(j=start; j>=0;) { chkd[j] = true; buf[buf.length] = j; buf_chain.push(sectors[j]); var addr = fat_addrs[Math.floor(j*4/ssz)]; jj = ((j*4) & modulus); if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz); if(!sectors[addr]) break; j = __readInt32LE(sectors[addr], jj); } return {nodes: buf, data:__toBuffer([buf_chain])}; }
javascript
function get_sector_list(sectors, start, fat_addrs, ssz, chkd) { var buf = [], buf_chain = []; if(!chkd) chkd = []; var modulus = ssz - 1, j = 0, jj = 0; for(j=start; j>=0;) { chkd[j] = true; buf[buf.length] = j; buf_chain.push(sectors[j]); var addr = fat_addrs[Math.floor(j*4/ssz)]; jj = ((j*4) & modulus); if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz); if(!sectors[addr]) break; j = __readInt32LE(sectors[addr], jj); } return {nodes: buf, data:__toBuffer([buf_chain])}; }
[ "function", "get_sector_list", "(", "sectors", ",", "start", ",", "fat_addrs", ",", "ssz", ",", "chkd", ")", "{", "var", "buf", "=", "[", "]", ",", "buf_chain", "=", "[", "]", ";", "if", "(", "!", "chkd", ")", "chkd", "=", "[", "]", ";", "var", "modulus", "=", "ssz", "-", "1", ",", "j", "=", "0", ",", "jj", "=", "0", ";", "for", "(", "j", "=", "start", ";", "j", ">=", "0", ";", ")", "{", "chkd", "[", "j", "]", "=", "true", ";", "buf", "[", "buf", ".", "length", "]", "=", "j", ";", "buf_chain", ".", "push", "(", "sectors", "[", "j", "]", ")", ";", "var", "addr", "=", "fat_addrs", "[", "Math", ".", "floor", "(", "j", "*", "4", "/", "ssz", ")", "]", ";", "jj", "=", "(", "(", "j", "*", "4", ")", "&", "modulus", ")", ";", "if", "(", "ssz", "<", "4", "+", "jj", ")", "throw", "new", "Error", "(", "\"FAT boundary crossed: \"", "+", "j", "+", "\" 4 \"", "+", "ssz", ")", ";", "if", "(", "!", "sectors", "[", "addr", "]", ")", "break", ";", "j", "=", "__readInt32LE", "(", "sectors", "[", "addr", "]", ",", "jj", ")", ";", "}", "return", "{", "nodes", ":", "buf", ",", "data", ":", "__toBuffer", "(", "[", "buf_chain", "]", ")", "}", ";", "}" ]
Follow the linked list of sectors for a given starting point
[ "Follow", "the", "linked", "list", "of", "sectors", "for", "a", "given", "starting", "point" ]
9a6d8a1d3d80c78dad5201fb389316f935279cdc
https://github.com/SheetJS/js-xlsx/blob/9a6d8a1d3d80c78dad5201fb389316f935279cdc/xlsx.js#L1553-L1568
train
SheetJS/js-xlsx
xlsx.js
make_sector_list
function make_sector_list(sectors, dir_start, fat_addrs, ssz) { var sl = sectors.length, sector_list = ([]); var chkd = [], buf = [], buf_chain = []; var modulus = ssz - 1, i=0, j=0, k=0, jj=0; for(i=0; i < sl; ++i) { buf = ([]); k = (i + dir_start); if(k >= sl) k-=sl; if(chkd[k]) continue; buf_chain = []; for(j=k; j>=0;) { chkd[j] = true; buf[buf.length] = j; buf_chain.push(sectors[j]); var addr = fat_addrs[Math.floor(j*4/ssz)]; jj = ((j*4) & modulus); if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz); if(!sectors[addr]) break; j = __readInt32LE(sectors[addr], jj); } sector_list[k] = ({nodes: buf, data:__toBuffer([buf_chain])}); } return sector_list; }
javascript
function make_sector_list(sectors, dir_start, fat_addrs, ssz) { var sl = sectors.length, sector_list = ([]); var chkd = [], buf = [], buf_chain = []; var modulus = ssz - 1, i=0, j=0, k=0, jj=0; for(i=0; i < sl; ++i) { buf = ([]); k = (i + dir_start); if(k >= sl) k-=sl; if(chkd[k]) continue; buf_chain = []; for(j=k; j>=0;) { chkd[j] = true; buf[buf.length] = j; buf_chain.push(sectors[j]); var addr = fat_addrs[Math.floor(j*4/ssz)]; jj = ((j*4) & modulus); if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz); if(!sectors[addr]) break; j = __readInt32LE(sectors[addr], jj); } sector_list[k] = ({nodes: buf, data:__toBuffer([buf_chain])}); } return sector_list; }
[ "function", "make_sector_list", "(", "sectors", ",", "dir_start", ",", "fat_addrs", ",", "ssz", ")", "{", "var", "sl", "=", "sectors", ".", "length", ",", "sector_list", "=", "(", "[", "]", ")", ";", "var", "chkd", "=", "[", "]", ",", "buf", "=", "[", "]", ",", "buf_chain", "=", "[", "]", ";", "var", "modulus", "=", "ssz", "-", "1", ",", "i", "=", "0", ",", "j", "=", "0", ",", "k", "=", "0", ",", "jj", "=", "0", ";", "for", "(", "i", "=", "0", ";", "i", "<", "sl", ";", "++", "i", ")", "{", "buf", "=", "(", "[", "]", ")", ";", "k", "=", "(", "i", "+", "dir_start", ")", ";", "if", "(", "k", ">=", "sl", ")", "k", "-=", "sl", ";", "if", "(", "chkd", "[", "k", "]", ")", "continue", ";", "buf_chain", "=", "[", "]", ";", "for", "(", "j", "=", "k", ";", "j", ">=", "0", ";", ")", "{", "chkd", "[", "j", "]", "=", "true", ";", "buf", "[", "buf", ".", "length", "]", "=", "j", ";", "buf_chain", ".", "push", "(", "sectors", "[", "j", "]", ")", ";", "var", "addr", "=", "fat_addrs", "[", "Math", ".", "floor", "(", "j", "*", "4", "/", "ssz", ")", "]", ";", "jj", "=", "(", "(", "j", "*", "4", ")", "&", "modulus", ")", ";", "if", "(", "ssz", "<", "4", "+", "jj", ")", "throw", "new", "Error", "(", "\"FAT boundary crossed: \"", "+", "j", "+", "\" 4 \"", "+", "ssz", ")", ";", "if", "(", "!", "sectors", "[", "addr", "]", ")", "break", ";", "j", "=", "__readInt32LE", "(", "sectors", "[", "addr", "]", ",", "jj", ")", ";", "}", "sector_list", "[", "k", "]", "=", "(", "{", "nodes", ":", "buf", ",", "data", ":", "__toBuffer", "(", "[", "buf_chain", "]", ")", "}", ")", ";", "}", "return", "sector_list", ";", "}" ]
Chase down the sector linked lists
[ "Chase", "down", "the", "sector", "linked", "lists" ]
9a6d8a1d3d80c78dad5201fb389316f935279cdc
https://github.com/SheetJS/js-xlsx/blob/9a6d8a1d3d80c78dad5201fb389316f935279cdc/xlsx.js#L1571-L1593
train
vuejs/vuepress
packages/@vuepress/core/lib/node/theme-api/index.js
resolveSFCs
function resolveSFCs (dirs) { return dirs.map( layoutDir => readdirSync(layoutDir) .filter(filename => filename.endsWith('.vue')) .map(filename => { const componentName = getComponentName(filename) return { filename, componentName, isInternal: isInternal(componentName), path: resolve(layoutDir, filename) } }) ).reduce((arr, next) => { arr.push(...next) return arr }, []).reduce((map, component) => { map[component.componentName] = component return map }, {}) }
javascript
function resolveSFCs (dirs) { return dirs.map( layoutDir => readdirSync(layoutDir) .filter(filename => filename.endsWith('.vue')) .map(filename => { const componentName = getComponentName(filename) return { filename, componentName, isInternal: isInternal(componentName), path: resolve(layoutDir, filename) } }) ).reduce((arr, next) => { arr.push(...next) return arr }, []).reduce((map, component) => { map[component.componentName] = component return map }, {}) }
[ "function", "resolveSFCs", "(", "dirs", ")", "{", "return", "dirs", ".", "map", "(", "layoutDir", "=>", "readdirSync", "(", "layoutDir", ")", ".", "filter", "(", "filename", "=>", "filename", ".", "endsWith", "(", "'.vue'", ")", ")", ".", "map", "(", "filename", "=>", "{", "const", "componentName", "=", "getComponentName", "(", "filename", ")", "return", "{", "filename", ",", "componentName", ",", "isInternal", ":", "isInternal", "(", "componentName", ")", ",", "path", ":", "resolve", "(", "layoutDir", ",", "filename", ")", "}", "}", ")", ")", ".", "reduce", "(", "(", "arr", ",", "next", ")", "=>", "{", "arr", ".", "push", "(", "...", "next", ")", "return", "arr", "}", ",", "[", "]", ")", ".", "reduce", "(", "(", "map", ",", "component", ")", "=>", "{", "map", "[", "component", ".", "componentName", "]", "=", "component", "return", "map", "}", ",", "{", "}", ")", "}" ]
Resolve Vue SFCs, return a Map @param dirs @returns {*}
[ "Resolve", "Vue", "SFCs", "return", "a", "Map" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/theme-api/index.js#L106-L126
train
vuejs/vuepress
packages/@vuepress/core/lib/node/build/index.js
compile
function compile (config) { return new Promise((resolve, reject) => { webpack(config, (err, stats) => { if (err) { return reject(err) } if (stats.hasErrors()) { stats.toJson().errors.forEach(err => { console.error(err) }) reject(new Error(`Failed to compile with errors.`)) return } if (env.isDebug && stats.hasWarnings()) { stats.toJson().warnings.forEach(warning => { console.warn(warning) }) } resolve(stats.toJson({ modules: false })) }) }) }
javascript
function compile (config) { return new Promise((resolve, reject) => { webpack(config, (err, stats) => { if (err) { return reject(err) } if (stats.hasErrors()) { stats.toJson().errors.forEach(err => { console.error(err) }) reject(new Error(`Failed to compile with errors.`)) return } if (env.isDebug && stats.hasWarnings()) { stats.toJson().warnings.forEach(warning => { console.warn(warning) }) } resolve(stats.toJson({ modules: false })) }) }) }
[ "function", "compile", "(", "config", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "webpack", "(", "config", ",", "(", "err", ",", "stats", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", "}", "if", "(", "stats", ".", "hasErrors", "(", ")", ")", "{", "stats", ".", "toJson", "(", ")", ".", "errors", ".", "forEach", "(", "err", "=>", "{", "console", ".", "error", "(", "err", ")", "}", ")", "reject", "(", "new", "Error", "(", "`", "`", ")", ")", "return", "}", "if", "(", "env", ".", "isDebug", "&&", "stats", ".", "hasWarnings", "(", ")", ")", "{", "stats", ".", "toJson", "(", ")", ".", "warnings", ".", "forEach", "(", "warning", "=>", "{", "console", ".", "warn", "(", "warning", ")", "}", ")", "}", "resolve", "(", "stats", ".", "toJson", "(", "{", "modules", ":", "false", "}", ")", ")", "}", ")", "}", ")", "}" ]
Compile a webpack application and return stats json. @param {Object} config @returns {Promise<Object>}
[ "Compile", "a", "webpack", "application", "and", "return", "stats", "json", "." ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/build/index.js#L176-L197
train
vuejs/vuepress
packages/@vuepress/core/lib/node/build/index.js
renderHeadTag
function renderHeadTag (tag) { const { tagName, attributes, innerHTML, closeTag } = normalizeHeadTag(tag) return `<${tagName}${renderAttrs(attributes)}>${innerHTML}${closeTag ? `</${tagName}>` : ``}` }
javascript
function renderHeadTag (tag) { const { tagName, attributes, innerHTML, closeTag } = normalizeHeadTag(tag) return `<${tagName}${renderAttrs(attributes)}>${innerHTML}${closeTag ? `</${tagName}>` : ``}` }
[ "function", "renderHeadTag", "(", "tag", ")", "{", "const", "{", "tagName", ",", "attributes", ",", "innerHTML", ",", "closeTag", "}", "=", "normalizeHeadTag", "(", "tag", ")", "return", "`", "${", "tagName", "}", "${", "renderAttrs", "(", "attributes", ")", "}", "${", "innerHTML", "}", "${", "closeTag", "?", "`", "${", "tagName", "}", "`", ":", "`", "`", "}", "`", "}" ]
Render head tag @param {Object} tag @returns {string}
[ "Render", "head", "tag" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/build/index.js#L206-L209
train
vuejs/vuepress
packages/@vuepress/core/lib/node/build/index.js
renderAttrs
function renderAttrs (attrs = {}) { const keys = Object.keys(attrs) if (keys.length) { return ' ' + keys.map(name => `${name}="${escape(attrs[name])}"`).join(' ') } else { return '' } }
javascript
function renderAttrs (attrs = {}) { const keys = Object.keys(attrs) if (keys.length) { return ' ' + keys.map(name => `${name}="${escape(attrs[name])}"`).join(' ') } else { return '' } }
[ "function", "renderAttrs", "(", "attrs", "=", "{", "}", ")", "{", "const", "keys", "=", "Object", ".", "keys", "(", "attrs", ")", "if", "(", "keys", ".", "length", ")", "{", "return", "' '", "+", "keys", ".", "map", "(", "name", "=>", "`", "${", "name", "}", "${", "escape", "(", "attrs", "[", "name", "]", ")", "}", "`", ")", ".", "join", "(", "' '", ")", "}", "else", "{", "return", "''", "}", "}" ]
Render html attributes @param {Object} attrs @returns {string}
[ "Render", "html", "attributes" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/build/index.js#L218-L225
train
vuejs/vuepress
packages/@vuepress/core/lib/node/build/index.js
renderPageMeta
function renderPageMeta (meta) { if (!meta) return '' return meta.map(m => { let res = `<meta` Object.keys(m).forEach(key => { res += ` ${key}="${escape(m[key])}"` }) return res + `>` }).join('') }
javascript
function renderPageMeta (meta) { if (!meta) return '' return meta.map(m => { let res = `<meta` Object.keys(m).forEach(key => { res += ` ${key}="${escape(m[key])}"` }) return res + `>` }).join('') }
[ "function", "renderPageMeta", "(", "meta", ")", "{", "if", "(", "!", "meta", ")", "return", "''", "return", "meta", ".", "map", "(", "m", "=>", "{", "let", "res", "=", "`", "`", "Object", ".", "keys", "(", "m", ")", ".", "forEach", "(", "key", "=>", "{", "res", "+=", "`", "${", "key", "}", "${", "escape", "(", "m", "[", "key", "]", ")", "}", "`", "}", ")", "return", "res", "+", "`", "`", "}", ")", ".", "join", "(", "''", ")", "}" ]
Render meta tags @param {Array} meta @returns {Array<string>}
[ "Render", "meta", "tags" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/build/index.js#L234-L243
train
vuejs/vuepress
packages/vuepress/lib/util.js
CLI
async function CLI ({ beforeParse, afterParse }) { const cli = CAC() beforeParse && await beforeParse(cli) cli.parse(process.argv) afterParse && await afterParse(cli) }
javascript
async function CLI ({ beforeParse, afterParse }) { const cli = CAC() beforeParse && await beforeParse(cli) cli.parse(process.argv) afterParse && await afterParse(cli) }
[ "async", "function", "CLI", "(", "{", "beforeParse", ",", "afterParse", "}", ")", "{", "const", "cli", "=", "CAC", "(", ")", "beforeParse", "&&", "await", "beforeParse", "(", "cli", ")", "cli", ".", "parse", "(", "process", ".", "argv", ")", "afterParse", "&&", "await", "afterParse", "(", "cli", ")", "}" ]
Bootstrap a CAC cli @param {function} beforeParse @param {function} adterParse @returns {Promise<void>}
[ "Bootstrap", "a", "CAC", "cli" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/vuepress/lib/util.js#L17-L25
train
vuejs/vuepress
packages/vuepress/lib/util.js
wrapCommand
function wrapCommand (fn) { return (...args) => { return fn(...args).catch(err => { console.error(chalk.red(err.stack)) process.exitCode = 1 }) } }
javascript
function wrapCommand (fn) { return (...args) => { return fn(...args).catch(err => { console.error(chalk.red(err.stack)) process.exitCode = 1 }) } }
[ "function", "wrapCommand", "(", "fn", ")", "{", "return", "(", "...", "args", ")", "=>", "{", "return", "fn", "(", "...", "args", ")", ".", "catch", "(", "err", "=>", "{", "console", ".", "error", "(", "chalk", ".", "red", "(", "err", ".", "stack", ")", ")", "process", ".", "exitCode", "=", "1", "}", ")", "}", "}" ]
Wrap a function to catch error. @param {function} fn @returns {function(...[*]): (*|Promise|Promise<T | never>)}
[ "Wrap", "a", "function", "to", "catch", "error", "." ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/vuepress/lib/util.js#L33-L40
train
vuejs/vuepress
packages/@vuepress/core/lib/node/dev/index.js
resolveHost
function resolveHost (host) { const defaultHost = '0.0.0.0' host = host || defaultHost const displayHost = host === defaultHost ? 'localhost' : host return { displayHost, host } }
javascript
function resolveHost (host) { const defaultHost = '0.0.0.0' host = host || defaultHost const displayHost = host === defaultHost ? 'localhost' : host return { displayHost, host } }
[ "function", "resolveHost", "(", "host", ")", "{", "const", "defaultHost", "=", "'0.0.0.0'", "host", "=", "host", "||", "defaultHost", "const", "displayHost", "=", "host", "===", "defaultHost", "?", "'localhost'", ":", "host", "return", "{", "displayHost", ",", "host", "}", "}" ]
Resolve host. @param {string} host user's host @returns {{displayHost: string, host: string}}
[ "Resolve", "host", "." ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/dev/index.js#L268-L278
train
vuejs/vuepress
packages/@vuepress/core/lib/node/dev/index.js
resolvePort
async function resolvePort (port) { const portfinder = require('portfinder') portfinder.basePort = parseInt(port) || 8080 port = await portfinder.getPortPromise() return port }
javascript
async function resolvePort (port) { const portfinder = require('portfinder') portfinder.basePort = parseInt(port) || 8080 port = await portfinder.getPortPromise() return port }
[ "async", "function", "resolvePort", "(", "port", ")", "{", "const", "portfinder", "=", "require", "(", "'portfinder'", ")", "portfinder", ".", "basePort", "=", "parseInt", "(", "port", ")", "||", "8080", "port", "=", "await", "portfinder", ".", "getPortPromise", "(", ")", "return", "port", "}" ]
Resolve port. @param {number} port user's port @returns {Promise<number>}
[ "Resolve", "port", "." ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/dev/index.js#L287-L292
train
vuejs/vuepress
packages/@vuepress/core/lib/node/dev/index.js
normalizeWatchFilePath
function normalizeWatchFilePath (filepath, baseDir) { const { isAbsolute, relative } = require('path') if (isAbsolute(filepath)) { return relative(baseDir, filepath) } return filepath }
javascript
function normalizeWatchFilePath (filepath, baseDir) { const { isAbsolute, relative } = require('path') if (isAbsolute(filepath)) { return relative(baseDir, filepath) } return filepath }
[ "function", "normalizeWatchFilePath", "(", "filepath", ",", "baseDir", ")", "{", "const", "{", "isAbsolute", ",", "relative", "}", "=", "require", "(", "'path'", ")", "if", "(", "isAbsolute", "(", "filepath", ")", ")", "{", "return", "relative", "(", "baseDir", ",", "filepath", ")", "}", "return", "filepath", "}" ]
Normalize file path and always return relative path, @param {string} filepath user's path @param {string} baseDir source directory @returns {string}
[ "Normalize", "file", "path", "and", "always", "return", "relative", "path" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/dev/index.js#L302-L308
train
vuejs/vuepress
packages/@vuepress/core/lib/node/internal-plugins/routes.js
routesCode
function routesCode (pages) { function genRoute ({ path: pagePath, key: componentName, frontmatter: { layout }, regularPath, _meta }) { let code = ` { name: ${JSON.stringify(componentName)}, path: ${JSON.stringify(pagePath)}, component: GlobalLayout, beforeEnter: (to, from, next) => { ensureAsyncComponentsLoaded(${JSON.stringify(layout || 'Layout')}, ${JSON.stringify(componentName)}).then(next) },${_meta ? `\n meta: ${JSON.stringify(_meta)}` : ''} }` const dncodedPath = decodeURIComponent(pagePath) if (dncodedPath !== pagePath) { code += `, { path: ${JSON.stringify(dncodedPath)}, redirect: ${JSON.stringify(pagePath)} }` } if (/\/$/.test(pagePath)) { code += `, { path: ${JSON.stringify(pagePath + 'index.html')}, redirect: ${JSON.stringify(pagePath)} }` } if (regularPath !== pagePath) { code += `, { path: ${JSON.stringify(regularPath)}, redirect: ${JSON.stringify(pagePath)} }` } return code } const notFoundRoute = `, { path: '*', component: GlobalLayout }` return ( `export const routes = [${pages.map(genRoute).join(',')}${notFoundRoute}\n]` ) }
javascript
function routesCode (pages) { function genRoute ({ path: pagePath, key: componentName, frontmatter: { layout }, regularPath, _meta }) { let code = ` { name: ${JSON.stringify(componentName)}, path: ${JSON.stringify(pagePath)}, component: GlobalLayout, beforeEnter: (to, from, next) => { ensureAsyncComponentsLoaded(${JSON.stringify(layout || 'Layout')}, ${JSON.stringify(componentName)}).then(next) },${_meta ? `\n meta: ${JSON.stringify(_meta)}` : ''} }` const dncodedPath = decodeURIComponent(pagePath) if (dncodedPath !== pagePath) { code += `, { path: ${JSON.stringify(dncodedPath)}, redirect: ${JSON.stringify(pagePath)} }` } if (/\/$/.test(pagePath)) { code += `, { path: ${JSON.stringify(pagePath + 'index.html')}, redirect: ${JSON.stringify(pagePath)} }` } if (regularPath !== pagePath) { code += `, { path: ${JSON.stringify(regularPath)}, redirect: ${JSON.stringify(pagePath)} }` } return code } const notFoundRoute = `, { path: '*', component: GlobalLayout }` return ( `export const routes = [${pages.map(genRoute).join(',')}${notFoundRoute}\n]` ) }
[ "function", "routesCode", "(", "pages", ")", "{", "function", "genRoute", "(", "{", "path", ":", "pagePath", ",", "key", ":", "componentName", ",", "frontmatter", ":", "{", "layout", "}", ",", "regularPath", ",", "_meta", "}", ")", "{", "let", "code", "=", "`", "${", "JSON", ".", "stringify", "(", "componentName", ")", "}", "${", "JSON", ".", "stringify", "(", "pagePath", ")", "}", "${", "JSON", ".", "stringify", "(", "layout", "||", "'Layout'", ")", "}", "${", "JSON", ".", "stringify", "(", "componentName", ")", "}", "${", "_meta", "?", "`", "\\n", "${", "JSON", ".", "stringify", "(", "_meta", ")", "}", "`", ":", "''", "}", "`", "const", "dncodedPath", "=", "decodeURIComponent", "(", "pagePath", ")", "if", "(", "dncodedPath", "!==", "pagePath", ")", "{", "code", "+=", "`", "${", "JSON", ".", "stringify", "(", "dncodedPath", ")", "}", "${", "JSON", ".", "stringify", "(", "pagePath", ")", "}", "`", "}", "if", "(", "/", "\\/$", "/", ".", "test", "(", "pagePath", ")", ")", "{", "code", "+=", "`", "${", "JSON", ".", "stringify", "(", "pagePath", "+", "'index.html'", ")", "}", "${", "JSON", ".", "stringify", "(", "pagePath", ")", "}", "`", "}", "if", "(", "regularPath", "!==", "pagePath", ")", "{", "code", "+=", "`", "${", "JSON", ".", "stringify", "(", "regularPath", ")", "}", "${", "JSON", ".", "stringify", "(", "pagePath", ")", "}", "`", "}", "return", "code", "}", "const", "notFoundRoute", "=", "`", "`", "return", "(", "`", "${", "pages", ".", "map", "(", "genRoute", ")", ".", "join", "(", "','", ")", "}", "${", "notFoundRoute", "}", "\\n", "`", ")", "}" ]
Get Vue routes code. @param {array} pages @returns {string}
[ "Get", "Vue", "routes", "code", "." ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/internal-plugins/routes.js#L31-L88
train
vuejs/vuepress
packages/vuepress/lib/handleUnknownCommand.js
registerUnknownCommands
function registerUnknownCommands (cli, options) { cli.on('command:*', async () => { const { args, options: commandoptions } = cli logger.debug('global_options', options) logger.debug('cli_options', commandoptions) logger.debug('cli_args', args) const [commandName] = args const sourceDir = args[1] ? path.resolve(args[1]) : pwd const inferredUserDocsDirectory = await inferUserDocsDirectory(pwd) logger.developer('inferredUserDocsDirectory', inferredUserDocsDirectory) logger.developer('sourceDir', sourceDir) if (inferredUserDocsDirectory && sourceDir !== inferredUserDocsDirectory) { logUnknownCommand(cli) console.log() logger.tip(`Did you miss to specify the target docs dir? e.g. ${chalk.cyan(`vuepress ${commandName} [targetDir]`)}.`) logger.tip(`A custom command registered by a plugin requires VuePress to locate your site configuration like ${chalk.cyan('vuepress dev')} or ${chalk.cyan('vuepress build')}.`) console.log() process.exit(1) } if (!inferredUserDocsDirectory) { logUnknownCommand(cli) process.exit(1) } logger.debug('Custom command', chalk.cyan(commandName)) CLI({ async beforeParse (subCli) { const app = createApp({ sourceDir: sourceDir, ...options, ...commandoptions }) await app.process() app.pluginAPI.applySyncOption('extendCli', subCli, app) console.log() }, async afterParse (subCli) { if (!subCli.matchedCommand) { logUnknownCommand(subCli) console.log() } } }) }) }
javascript
function registerUnknownCommands (cli, options) { cli.on('command:*', async () => { const { args, options: commandoptions } = cli logger.debug('global_options', options) logger.debug('cli_options', commandoptions) logger.debug('cli_args', args) const [commandName] = args const sourceDir = args[1] ? path.resolve(args[1]) : pwd const inferredUserDocsDirectory = await inferUserDocsDirectory(pwd) logger.developer('inferredUserDocsDirectory', inferredUserDocsDirectory) logger.developer('sourceDir', sourceDir) if (inferredUserDocsDirectory && sourceDir !== inferredUserDocsDirectory) { logUnknownCommand(cli) console.log() logger.tip(`Did you miss to specify the target docs dir? e.g. ${chalk.cyan(`vuepress ${commandName} [targetDir]`)}.`) logger.tip(`A custom command registered by a plugin requires VuePress to locate your site configuration like ${chalk.cyan('vuepress dev')} or ${chalk.cyan('vuepress build')}.`) console.log() process.exit(1) } if (!inferredUserDocsDirectory) { logUnknownCommand(cli) process.exit(1) } logger.debug('Custom command', chalk.cyan(commandName)) CLI({ async beforeParse (subCli) { const app = createApp({ sourceDir: sourceDir, ...options, ...commandoptions }) await app.process() app.pluginAPI.applySyncOption('extendCli', subCli, app) console.log() }, async afterParse (subCli) { if (!subCli.matchedCommand) { logUnknownCommand(subCli) console.log() } } }) }) }
[ "function", "registerUnknownCommands", "(", "cli", ",", "options", ")", "{", "cli", ".", "on", "(", "'command:*'", ",", "async", "(", ")", "=>", "{", "const", "{", "args", ",", "options", ":", "commandoptions", "}", "=", "cli", "logger", ".", "debug", "(", "'global_options'", ",", "options", ")", "logger", ".", "debug", "(", "'cli_options'", ",", "commandoptions", ")", "logger", ".", "debug", "(", "'cli_args'", ",", "args", ")", "const", "[", "commandName", "]", "=", "args", "const", "sourceDir", "=", "args", "[", "1", "]", "?", "path", ".", "resolve", "(", "args", "[", "1", "]", ")", ":", "pwd", "const", "inferredUserDocsDirectory", "=", "await", "inferUserDocsDirectory", "(", "pwd", ")", "logger", ".", "developer", "(", "'inferredUserDocsDirectory'", ",", "inferredUserDocsDirectory", ")", "logger", ".", "developer", "(", "'sourceDir'", ",", "sourceDir", ")", "if", "(", "inferredUserDocsDirectory", "&&", "sourceDir", "!==", "inferredUserDocsDirectory", ")", "{", "logUnknownCommand", "(", "cli", ")", "console", ".", "log", "(", ")", "logger", ".", "tip", "(", "`", "${", "chalk", ".", "cyan", "(", "`", "${", "commandName", "}", "`", ")", "}", "`", ")", "logger", ".", "tip", "(", "`", "${", "chalk", ".", "cyan", "(", "'vuepress dev'", ")", "}", "${", "chalk", ".", "cyan", "(", "'vuepress build'", ")", "}", "`", ")", "console", ".", "log", "(", ")", "process", ".", "exit", "(", "1", ")", "}", "if", "(", "!", "inferredUserDocsDirectory", ")", "{", "logUnknownCommand", "(", "cli", ")", "process", ".", "exit", "(", "1", ")", "}", "logger", ".", "debug", "(", "'Custom command'", ",", "chalk", ".", "cyan", "(", "commandName", ")", ")", "CLI", "(", "{", "async", "beforeParse", "(", "subCli", ")", "{", "const", "app", "=", "createApp", "(", "{", "sourceDir", ":", "sourceDir", ",", "...", "options", ",", "...", "commandoptions", "}", ")", "await", "app", ".", "process", "(", ")", "app", ".", "pluginAPI", ".", "applySyncOption", "(", "'extendCli'", ",", "subCli", ",", "app", ")", "console", ".", "log", "(", ")", "}", ",", "async", "afterParse", "(", "subCli", ")", "{", "if", "(", "!", "subCli", ".", "matchedCommand", ")", "{", "logUnknownCommand", "(", "subCli", ")", "console", ".", "log", "(", ")", "}", "}", "}", ")", "}", ")", "}" ]
Register a command to match all unmatched commands @param {CAC} cli
[ "Register", "a", "command", "to", "match", "all", "unmatched", "commands" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/vuepress/lib/handleUnknownCommand.js#L76-L124
train
vuejs/vuepress
packages/@vuepress/markdown/lib/tableOfContents.js
vBindEscape
function vBindEscape (strs, ...args) { return strs.reduce((prev, curr, index) => { return prev + curr + (index >= args.length ? '' : `"${JSON.stringify(args[index]) .replace(/"/g, "'") .replace(/([^\\])(\\\\)*\\'/g, (_, char) => char + '\\u0022')}"`) }, '') }
javascript
function vBindEscape (strs, ...args) { return strs.reduce((prev, curr, index) => { return prev + curr + (index >= args.length ? '' : `"${JSON.stringify(args[index]) .replace(/"/g, "'") .replace(/([^\\])(\\\\)*\\'/g, (_, char) => char + '\\u0022')}"`) }, '') }
[ "function", "vBindEscape", "(", "strs", ",", "...", "args", ")", "{", "return", "strs", ".", "reduce", "(", "(", "prev", ",", "curr", ",", "index", ")", "=>", "{", "return", "prev", "+", "curr", "+", "(", "index", ">=", "args", ".", "length", "?", "''", ":", "`", "${", "JSON", ".", "stringify", "(", "args", "[", "index", "]", ")", ".", "replace", "(", "/", "\"", "/", "g", ",", "\"'\"", ")", ".", "replace", "(", "/", "([^\\\\])(\\\\\\\\)*\\\\'", "/", "g", ",", "(", "_", ",", "char", ")", "=>", "char", "+", "'\\\\u0022'", ")", "}", "`", ")", "}", ",", "\\\\", ")", "}" ]
escape double quotes in v-bind derivatives
[ "escape", "double", "quotes", "in", "v", "-", "bind", "derivatives" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/markdown/lib/tableOfContents.js#L75-L83
train
juliangarnier/anime
src/index.js
setTargetsValue
function setTargetsValue(targets, properties) { const animatables = getAnimatables(targets); animatables.forEach(animatable => { for (let property in properties) { const value = getFunctionValue(properties[property], animatable); const target = animatable.target; const valueUnit = getUnit(value); const originalValue = getOriginalTargetValue(target, property, valueUnit, animatable); const unit = valueUnit || getUnit(originalValue); const to = getRelativeValue(validateValue(value, unit), originalValue); const animType = getAnimationType(target, property); setProgressValue[animType](target, property, to, animatable.transforms, true); } }); }
javascript
function setTargetsValue(targets, properties) { const animatables = getAnimatables(targets); animatables.forEach(animatable => { for (let property in properties) { const value = getFunctionValue(properties[property], animatable); const target = animatable.target; const valueUnit = getUnit(value); const originalValue = getOriginalTargetValue(target, property, valueUnit, animatable); const unit = valueUnit || getUnit(originalValue); const to = getRelativeValue(validateValue(value, unit), originalValue); const animType = getAnimationType(target, property); setProgressValue[animType](target, property, to, animatable.transforms, true); } }); }
[ "function", "setTargetsValue", "(", "targets", ",", "properties", ")", "{", "const", "animatables", "=", "getAnimatables", "(", "targets", ")", ";", "animatables", ".", "forEach", "(", "animatable", "=>", "{", "for", "(", "let", "property", "in", "properties", ")", "{", "const", "value", "=", "getFunctionValue", "(", "properties", "[", "property", "]", ",", "animatable", ")", ";", "const", "target", "=", "animatable", ".", "target", ";", "const", "valueUnit", "=", "getUnit", "(", "value", ")", ";", "const", "originalValue", "=", "getOriginalTargetValue", "(", "target", ",", "property", ",", "valueUnit", ",", "animatable", ")", ";", "const", "unit", "=", "valueUnit", "||", "getUnit", "(", "originalValue", ")", ";", "const", "to", "=", "getRelativeValue", "(", "validateValue", "(", "value", ",", "unit", ")", ",", "originalValue", ")", ";", "const", "animType", "=", "getAnimationType", "(", "target", ",", "property", ")", ";", "setProgressValue", "[", "animType", "]", "(", "target", ",", "property", ",", "to", ",", "animatable", ".", "transforms", ",", "true", ")", ";", "}", "}", ")", ";", "}" ]
Set Value helper
[ "Set", "Value", "helper" ]
875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a
https://github.com/juliangarnier/anime/blob/875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a/src/index.js#L777-L791
train
juliangarnier/anime
src/index.js
removeTargetsFromAnimations
function removeTargetsFromAnimations(targetsArray, animations) { for (let a = animations.length; a--;) { if (arrayContains(targetsArray, animations[a].animatable.target)) { animations.splice(a, 1); } } }
javascript
function removeTargetsFromAnimations(targetsArray, animations) { for (let a = animations.length; a--;) { if (arrayContains(targetsArray, animations[a].animatable.target)) { animations.splice(a, 1); } } }
[ "function", "removeTargetsFromAnimations", "(", "targetsArray", ",", "animations", ")", "{", "for", "(", "let", "a", "=", "animations", ".", "length", ";", "a", "--", ";", ")", "{", "if", "(", "arrayContains", "(", "targetsArray", ",", "animations", "[", "a", "]", ".", "animatable", ".", "target", ")", ")", "{", "animations", ".", "splice", "(", "a", ",", "1", ")", ";", "}", "}", "}" ]
Remove targets from animation
[ "Remove", "targets", "from", "animation" ]
875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a
https://github.com/juliangarnier/anime/blob/875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a/src/index.js#L1150-L1156
train
juliangarnier/anime
documentation/assets/js/website.js
onScroll
function onScroll(cb) { var isTicking = false; var scrollY = 0; var body = document.body; var html = document.documentElement; var scrollHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); function scroll() { scrollY = window.scrollY; if (cb) cb(scrollY, scrollHeight); requestTick(); } function requestTick() { if (!isTicking) requestAnimationFrame(updateScroll); isTicking = true; } function updateScroll() { isTicking = false; var currentScrollY = scrollY; } scroll(); window.onscroll = scroll; }
javascript
function onScroll(cb) { var isTicking = false; var scrollY = 0; var body = document.body; var html = document.documentElement; var scrollHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); function scroll() { scrollY = window.scrollY; if (cb) cb(scrollY, scrollHeight); requestTick(); } function requestTick() { if (!isTicking) requestAnimationFrame(updateScroll); isTicking = true; } function updateScroll() { isTicking = false; var currentScrollY = scrollY; } scroll(); window.onscroll = scroll; }
[ "function", "onScroll", "(", "cb", ")", "{", "var", "isTicking", "=", "false", ";", "var", "scrollY", "=", "0", ";", "var", "body", "=", "document", ".", "body", ";", "var", "html", "=", "document", ".", "documentElement", ";", "var", "scrollHeight", "=", "Math", ".", "max", "(", "body", ".", "scrollHeight", ",", "body", ".", "offsetHeight", ",", "html", ".", "clientHeight", ",", "html", ".", "scrollHeight", ",", "html", ".", "offsetHeight", ")", ";", "function", "scroll", "(", ")", "{", "scrollY", "=", "window", ".", "scrollY", ";", "if", "(", "cb", ")", "cb", "(", "scrollY", ",", "scrollHeight", ")", ";", "requestTick", "(", ")", ";", "}", "function", "requestTick", "(", ")", "{", "if", "(", "!", "isTicking", ")", "requestAnimationFrame", "(", "updateScroll", ")", ";", "isTicking", "=", "true", ";", "}", "function", "updateScroll", "(", ")", "{", "isTicking", "=", "false", ";", "var", "currentScrollY", "=", "scrollY", ";", "}", "scroll", "(", ")", ";", "window", ".", "onscroll", "=", "scroll", ";", "}" ]
Better scroll events
[ "Better", "scroll", "events" ]
875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a
https://github.com/juliangarnier/anime/blob/875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a/documentation/assets/js/website.js#L66-L87
train
juliangarnier/anime
documentation/assets/js/website.js
scrollToElement
function scrollToElement(el, offset) { var off = offset || 0; var rect = el.getBoundingClientRect(); var top = rect.top + off; var animation = anime({ targets: [document.body, document.documentElement], scrollTop: '+='+top, easing: 'easeInOutSine', duration: 1500 }); // onScroll(animation.pause); }
javascript
function scrollToElement(el, offset) { var off = offset || 0; var rect = el.getBoundingClientRect(); var top = rect.top + off; var animation = anime({ targets: [document.body, document.documentElement], scrollTop: '+='+top, easing: 'easeInOutSine', duration: 1500 }); // onScroll(animation.pause); }
[ "function", "scrollToElement", "(", "el", ",", "offset", ")", "{", "var", "off", "=", "offset", "||", "0", ";", "var", "rect", "=", "el", ".", "getBoundingClientRect", "(", ")", ";", "var", "top", "=", "rect", ".", "top", "+", "off", ";", "var", "animation", "=", "anime", "(", "{", "targets", ":", "[", "document", ".", "body", ",", "document", ".", "documentElement", "]", ",", "scrollTop", ":", "'+='", "+", "top", ",", "easing", ":", "'easeInOutSine'", ",", "duration", ":", "1500", "}", ")", ";", "}" ]
Scroll to element
[ "Scroll", "to", "element" ]
875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a
https://github.com/juliangarnier/anime/blob/875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a/documentation/assets/js/website.js#L91-L102
train
juliangarnier/anime
documentation/assets/js/website.js
isElementInViewport
function isElementInViewport(el, inCB, outCB, rootMargin) { var margin = rootMargin || '-10%'; function handleIntersect(entries, observer) { var entry = entries[0]; if (entry.isIntersecting) { if (inCB && typeof inCB === 'function') inCB(el, entry); } else { if (outCB && typeof outCB === 'function') outCB(el, entry); } } var observer = new IntersectionObserver(handleIntersect, {rootMargin: margin}); observer.observe(el); }
javascript
function isElementInViewport(el, inCB, outCB, rootMargin) { var margin = rootMargin || '-10%'; function handleIntersect(entries, observer) { var entry = entries[0]; if (entry.isIntersecting) { if (inCB && typeof inCB === 'function') inCB(el, entry); } else { if (outCB && typeof outCB === 'function') outCB(el, entry); } } var observer = new IntersectionObserver(handleIntersect, {rootMargin: margin}); observer.observe(el); }
[ "function", "isElementInViewport", "(", "el", ",", "inCB", ",", "outCB", ",", "rootMargin", ")", "{", "var", "margin", "=", "rootMargin", "||", "'-10%'", ";", "function", "handleIntersect", "(", "entries", ",", "observer", ")", "{", "var", "entry", "=", "entries", "[", "0", "]", ";", "if", "(", "entry", ".", "isIntersecting", ")", "{", "if", "(", "inCB", "&&", "typeof", "inCB", "===", "'function'", ")", "inCB", "(", "el", ",", "entry", ")", ";", "}", "else", "{", "if", "(", "outCB", "&&", "typeof", "outCB", "===", "'function'", ")", "outCB", "(", "el", ",", "entry", ")", ";", "}", "}", "var", "observer", "=", "new", "IntersectionObserver", "(", "handleIntersect", ",", "{", "rootMargin", ":", "margin", "}", ")", ";", "observer", ".", "observe", "(", "el", ")", ";", "}" ]
Check if element is in viewport
[ "Check", "if", "element", "is", "in", "viewport" ]
875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a
https://github.com/juliangarnier/anime/blob/875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a/documentation/assets/js/website.js#L106-L118
train
babel/babel
packages/babel-traverse/src/path/conversion.js
getThisBinding
function getThisBinding(thisEnvFn, inConstructor) { return getBinding(thisEnvFn, "this", thisBinding => { if (!inConstructor || !hasSuperClass(thisEnvFn)) return t.thisExpression(); const supers = new WeakSet(); thisEnvFn.traverse({ Function(child) { if (child.isArrowFunctionExpression()) return; child.skip(); }, ClassProperty(child) { child.skip(); }, CallExpression(child) { if (!child.get("callee").isSuper()) return; if (supers.has(child.node)) return; supers.add(child.node); child.replaceWithMultiple([ child.node, t.assignmentExpression( "=", t.identifier(thisBinding), t.identifier("this"), ), ]); }, }); }); }
javascript
function getThisBinding(thisEnvFn, inConstructor) { return getBinding(thisEnvFn, "this", thisBinding => { if (!inConstructor || !hasSuperClass(thisEnvFn)) return t.thisExpression(); const supers = new WeakSet(); thisEnvFn.traverse({ Function(child) { if (child.isArrowFunctionExpression()) return; child.skip(); }, ClassProperty(child) { child.skip(); }, CallExpression(child) { if (!child.get("callee").isSuper()) return; if (supers.has(child.node)) return; supers.add(child.node); child.replaceWithMultiple([ child.node, t.assignmentExpression( "=", t.identifier(thisBinding), t.identifier("this"), ), ]); }, }); }); }
[ "function", "getThisBinding", "(", "thisEnvFn", ",", "inConstructor", ")", "{", "return", "getBinding", "(", "thisEnvFn", ",", "\"this\"", ",", "thisBinding", "=>", "{", "if", "(", "!", "inConstructor", "||", "!", "hasSuperClass", "(", "thisEnvFn", ")", ")", "return", "t", ".", "thisExpression", "(", ")", ";", "const", "supers", "=", "new", "WeakSet", "(", ")", ";", "thisEnvFn", ".", "traverse", "(", "{", "Function", "(", "child", ")", "{", "if", "(", "child", ".", "isArrowFunctionExpression", "(", ")", ")", "return", ";", "child", ".", "skip", "(", ")", ";", "}", ",", "ClassProperty", "(", "child", ")", "{", "child", ".", "skip", "(", ")", ";", "}", ",", "CallExpression", "(", "child", ")", "{", "if", "(", "!", "child", ".", "get", "(", "\"callee\"", ")", ".", "isSuper", "(", ")", ")", "return", ";", "if", "(", "supers", ".", "has", "(", "child", ".", "node", ")", ")", "return", ";", "supers", ".", "add", "(", "child", ".", "node", ")", ";", "child", ".", "replaceWithMultiple", "(", "[", "child", ".", "node", ",", "t", ".", "assignmentExpression", "(", "\"=\"", ",", "t", ".", "identifier", "(", "thisBinding", ")", ",", "t", ".", "identifier", "(", "\"this\"", ")", ",", ")", ",", "]", ")", ";", "}", ",", "}", ")", ";", "}", ")", ";", "}" ]
Create a binding that evaluates to the "this" of the given function.
[ "Create", "a", "binding", "that", "evaluates", "to", "the", "this", "of", "the", "given", "function", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-traverse/src/path/conversion.js#L444-L473
train
babel/babel
packages/babel-generator/src/generators/statements.js
getLastStatement
function getLastStatement(statement) { if (!t.isStatement(statement.body)) return statement; return getLastStatement(statement.body); }
javascript
function getLastStatement(statement) { if (!t.isStatement(statement.body)) return statement; return getLastStatement(statement.body); }
[ "function", "getLastStatement", "(", "statement", ")", "{", "if", "(", "!", "t", ".", "isStatement", "(", "statement", ".", "body", ")", ")", "return", "statement", ";", "return", "getLastStatement", "(", "statement", ".", "body", ")", ";", "}" ]
Recursively get the last statement.
[ "Recursively", "get", "the", "last", "statement", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-generator/src/generators/statements.js#L45-L48
train
babel/babel
packages/babel-plugin-transform-block-scoping/src/index.js
isInLoop
function isInLoop(path) { const loopOrFunctionParent = path.find( path => path.isLoop() || path.isFunction(), ); return loopOrFunctionParent && loopOrFunctionParent.isLoop(); }
javascript
function isInLoop(path) { const loopOrFunctionParent = path.find( path => path.isLoop() || path.isFunction(), ); return loopOrFunctionParent && loopOrFunctionParent.isLoop(); }
[ "function", "isInLoop", "(", "path", ")", "{", "const", "loopOrFunctionParent", "=", "path", ".", "find", "(", "path", "=>", "path", ".", "isLoop", "(", ")", "||", "path", ".", "isFunction", "(", ")", ",", ")", ";", "return", "loopOrFunctionParent", "&&", "loopOrFunctionParent", ".", "isLoop", "(", ")", ";", "}" ]
If there is a loop ancestor closer than the closest function, we consider ourselves to be in a loop.
[ "If", "there", "is", "a", "loop", "ancestor", "closer", "than", "the", "closest", "function", "we", "consider", "ourselves", "to", "be", "in", "a", "loop", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-plugin-transform-block-scoping/src/index.js#L123-L129
train