_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q26900 | train | function (customizations, layoutConfig) {
var customization = customizations[layoutConfig.view.type];
if (!customization) {
return layoutConfig;
}
return _.merge(layoutConfig, { view: customization });
} | javascript | {
"resource": ""
} | |
q26901 | MetricsProvider | train | function MetricsProvider(screen) {
/**
* Setup the process to aggregate the data as and when it is necessary.
*
* @returns {void}
*/
var setupAggregation =
function setupAggregation() {
// construct the aggregation container
this._aggregation = _.reduce(AGGREGATE_TIME_LEVELS, function (prev, timeLevel) {
prev[timeLevel] = {
data: [],
lastTimeIndex: undefined,
lastAggregateIndex: 0,
scrollOffset: 0
};
return prev;
}, {});
// an array of all available aggregation levels and metadata
this.aggregationLevels = _.keys(this._aggregation);
this.lowestAggregateTimeUnits = +this.aggregationLevels[0];
this.highestAggregationKey = _.last(this.aggregationLevels);
// remember when all this started
this._startTime = Date.now();
// this is where we stopped aggregating
this._lastAggregationIndex = 0;
}.bind(this);
EventEmitter.call(this);
// the low-level container of all metrics provided
this._metrics = [];
// setup for aggregation
setupAggregation();
// initialize the zoom level to the lowest level
this.setZoomLevel(0);
// callback handlers
screen.on("metrics", this._onMetrics.bind(this));
screen.on("zoomGraphs", this.adjustZoomLevel.bind(this));
screen.on("scrollGraphs", this.adjustScrollOffset.bind(this));
screen.on("startGraphs", this.startGraphs.bind(this));
screen.on("resetGraphs", this.resetGraphs.bind(this));
} | javascript | {
"resource": ""
} |
q26902 | getInitializedAverage | train | function getInitializedAverage(data) {
return _.reduce(data, function (prev, a, dataKey) {
// create a first-level object of the key
prev[dataKey] = {};
_.each(data[dataKey], function (b, dataMetricKey) {
// the metrics are properties inside this object
prev[dataKey][dataMetricKey] = 0;
});
return prev;
}, {});
} | javascript | {
"resource": ""
} |
q26903 | aggregateMetrics | train | function aggregateMetrics(currentTime, metricData) {
var aggregateKey;
/**
* Place aggregate data into the specified slot. If the current zoom
* level matches the aggregate level, the data is emitted to keep the
* display in sync.
*
* @param {Number} index
* The desired slot for the aggregate.
*
* @param {Object} data
* The aggregate data.
*
* @returns {void}
*/
var setAggregateData =
function setAggregateData(index, data) {
this._aggregation[aggregateKey].data[index] = data;
// if this view (current or not) is scrolled, adjust it
if (this._aggregation[aggregateKey].scrollOffset) {
this._aggregation[aggregateKey].scrollOffset--;
}
// emit to keep the display in sync
if (this.isCurrentZoom(aggregateKey)) {
if (this.isScrolled()) {
this.emit("refreshMetrics");
} else {
this.emit("metrics", data);
}
}
}.bind(this);
/**
* Given the current time time index, add any missing logical
* time slots to have a complete picture of data.
*
* @param {Number} currentTimeIndex
* The time index currently being processed.
*
* @returns {void}
*/
var addMissingTimeSlots =
function addMissingTimeSlots(currentTimeIndex) {
var aggregateIndex = this._aggregation[aggregateKey].data.length;
while (aggregateIndex < currentTimeIndex) {
setAggregateData(aggregateIndex++, this.emptyAverage);
}
}.bind(this);
/**
* After having detected a new sampling, aggregate the relevant data points
*
* @param {Object[]} rows
* The array reference.
*
* @param {Number} startIndex
* The starting index to derive an average.
*
* @param {Number} endIndex
* The ending index to derive an average.
*
* @returns {void}
*/
var getAveragedAggregate =
function getAveragedAggregate(rows, startIndex, endIndex) {
var averagedAggregate = getInitializedAverage(metricData);
// this is the number of elements we will aggregate
var aggregateCount = endIndex - startIndex + 1;
// you can compute an average of a set of numbers two ways
// first, you can add all the numbers together and then divide by the count
// second, you call divide each number by the count and add the quotients
// the first method is more accurate, however you can overflow an accumulator
// and result with NaN
// the second method is employed here to ensure no overflows
for (var dataKey in metricData) {
for (var dataMetricKey in metricData[dataKey]) {
for (var rowIndex = startIndex; rowIndex <= endIndex; rowIndex++) {
averagedAggregate[dataKey][dataMetricKey] +=
rows[rowIndex][dataKey][dataMetricKey] / aggregateCount;
}
// after the average is done, truncate the averages to one decimal point
averagedAggregate[dataKey][dataMetricKey] =
+averagedAggregate[dataKey][dataMetricKey].toFixed(1);
}
}
return averagedAggregate;
};
/**
* Process one row of metric data into aggregate.
*
* @param {Number} rowIndex
* The index of the row being processed.
*
* @param {Object[]} rows
* The array reference.
*
* @returns {void}
*/
var processRow = function processRow(rowIndex, rows) {
var averagedAggregate;
var lastTimeIndex = this._aggregation[aggregateKey].lastTimeIndex;
// get the time index of the aggregate
var currentTimeIndex =
convertElapsedTimeToTimeIndex(currentTime, this._startTime, +aggregateKey);
// when the time index changes, average the data for the time band
if (currentTimeIndex !== lastTimeIndex) {
// except for the first one
if (lastTimeIndex !== undefined) {
// add in any missing logical time slots
addMissingTimeSlots.call(this, lastTimeIndex);
// get the average across the discovered time band
averagedAggregate = getAveragedAggregate(
rows,
this._aggregation[aggregateKey].lastAggregateIndex,
rowIndex - 1
);
// place the average
setAggregateData(lastTimeIndex, averagedAggregate);
// now we know where the next aggregate begins
this._aggregation[aggregateKey].lastAggregateIndex = rowIndex;
}
// level-break
this._aggregation[aggregateKey].lastTimeIndex = currentTimeIndex;
}
}.bind(this);
// iterate over the configured aggregation time buckets
for (aggregateKey in this._aggregation) {
// iterate through metrics, beginning where we left off
processRow(this._lastAggregationIndex, this._metrics);
}
// remember where we will begin again
this._lastAggregationIndex++;
} | javascript | {
"resource": ""
} |
q26904 | getAveragedAggregate | train | function getAveragedAggregate(rows, startIndex, endIndex) {
var averagedAggregate = getInitializedAverage(metricData);
// this is the number of elements we will aggregate
var aggregateCount = endIndex - startIndex + 1;
// you can compute an average of a set of numbers two ways
// first, you can add all the numbers together and then divide by the count
// second, you call divide each number by the count and add the quotients
// the first method is more accurate, however you can overflow an accumulator
// and result with NaN
// the second method is employed here to ensure no overflows
for (var dataKey in metricData) {
for (var dataMetricKey in metricData[dataKey]) {
for (var rowIndex = startIndex; rowIndex <= endIndex; rowIndex++) {
averagedAggregate[dataKey][dataMetricKey] +=
rows[rowIndex][dataKey][dataMetricKey] / aggregateCount;
}
// after the average is done, truncate the averages to one decimal point
averagedAggregate[dataKey][dataMetricKey] =
+averagedAggregate[dataKey][dataMetricKey].toFixed(1);
}
}
return averagedAggregate;
} | javascript | {
"resource": ""
} |
q26905 | getFixedScrollOffset | train | function getFixedScrollOffset(offset, length) {
if (offset && length + offset <= limit) {
return Math.min(limit - length, 0);
}
return Math.min(offset, 0);
} | javascript | {
"resource": ""
} |
q26906 | train | function(logType, logSection) {
if (!enabled) return;
var args = Array.prototype.slice.call(arguments, 2);
args.splice(0, 0, colors[logType][0]+"["+logType+"]"+colors[logType][1]+"["+logSection+"]");
console.log.apply(console, args);
} | javascript | {
"resource": ""
} | |
q26907 | mousemove_callback | train | function mousemove_callback(e) {
var x = e.pageX || e.originalEvent.touches[0].pageX;
var y = e.pageY || e.originalEvent.touches[0].pageY;
if (Math.abs(oX - x) > maxMove || Math.abs(oY - y) > maxMove) {
if (timeout) clearTimeout(timeout);
}
} | javascript | {
"resource": ""
} |
q26908 | train | function() {
var context, main, pkgRequireConfig, pkgRequire, that = this
var d = Q.defer();
if (!this.get("browser")) return Q();
logger.log("Load", this.get("name"));
getScript(this.url()+"/pkg-build.js", function(err) {
if (!err) return d.resolve();
logger.exception("Error loading plugin:", err);
d.reject(err);
});
return d.promise.timeout(10000, "This addon took to long to load (> 10seconds)");
} | javascript | {
"resource": ""
} | |
q26909 | cleanFolder | train | function cleanFolder(outPath) {
try {
var stat = fs.lstatSync(outPath);
if (stat.isDirectory()) {
wrench.rmdirSyncRecursive(outPath);
} else {
fs.unlinkSync(outPath);
}
} catch (e) {
if (e.code != "ENOENT") throw e;
}
} | javascript | {
"resource": ""
} |
q26910 | cleanseText | train | function cleanseText( options, cb ) {
return function( error, text ) {
if ( !error ) {
// clean up text
text = util.replaceBadCharacters( text );
if ( options.preserveLineBreaks || options.preserveOnlyMultipleLineBreaks ) {
if ( options.preserveOnlyMultipleLineBreaks ) {
text = text.replace( STRIP_ONLY_SINGLE_LINEBREAKS, '$1 ' ).trim();
}
text = text.replace( WHITELIST_PRESERVE_LINEBREAKS, ' ' );
} else {
text = text.replace( WHITELIST_STRIP_LINEBREAKS, ' ' );
}
// multiple spaces, tabs, vertical tabs, non-breaking space]
text = text.replace( / (?! )/g, '' )
.replace( /[ \t\v\u00A0]{2,}/g, ' ' );
text = entities.decode( text );
}
cb( error, text );
};
} | javascript | {
"resource": ""
} |
q26911 | replaceBadCharacters | train | function replaceBadCharacters( text ) {
var i, repl;
for ( i = 0; i < rLen; i++ ) {
repl = replacements[i];
text = text.replace( repl[0], repl[1] );
}
return text;
} | javascript | {
"resource": ""
} |
q26912 | runExecIntoFile | train | function runExecIntoFile( label, filePath, options, execOptions, genCommand, cb ) {
// escape the file paths
var fileTempOutPath = path.join( outDir, path.basename( filePath, path.extname( filePath ) ) )
, escapedFilePath = filePath.replace( /\s/g, '\\ ' )
, escapedFileTempOutPath = fileTempOutPath.replace( /\s/g, '\\ ' )
, cmd = genCommand( options, escapedFilePath, escapedFileTempOutPath )
;
exec( cmd, execOptions,
function( error /* , stdout, stderr */ ) {
if ( error !== null ) {
error = new Error( 'Error extracting [[ ' +
path.basename( filePath ) + ' ]], exec error: ' + error.message );
cb( error, null );
return;
}
fs.exists( fileTempOutPath + '.txt', function( exists ) {
if ( exists ) {
fs.readFile( fileTempOutPath + '.txt', 'utf8', function( error2, text ) {
if ( error2 ) {
error2 = new Error( 'Error reading' + label +
' output at [[ ' + fileTempOutPath + ' ]], error: ' + error2.message );
cb( error2, null );
} else {
fs.unlink( fileTempOutPath + '.txt', function( error3 ) {
if ( error3 ) {
error3 = new Error( 'Error, ' + label +
' , cleaning up temp file [[ ' + fileTempOutPath +
' ]], error: ' + error3.message );
cb( error3, null );
} else {
cb( null, text.toString() );
}
});
}
});
} else {
error = new Error( 'Error reading ' + label +
' output at [[ ' + fileTempOutPath + ' ]], file does not exist' );
cb( error, null );
}
});
}
);
} | javascript | {
"resource": ""
} |
q26913 | extractText | train | function extractText( filePath, options, cb ) {
var result = ''
, error = null
, textutil = spawn( 'textutil', ['-convert', 'txt', '-stdout', filePath] )
;
textutil.stdout.on( 'data', function( buffer ) {
result += buffer.toString();
});
textutil.stderr.on( 'error', function( buffer ) {
if ( !error ) {
error = '';
}
error += buffer.toString();
});
textutil.on( 'close', function( /* code */ ) {
if ( error ) {
error = new Error( 'textutil read of file named [[ ' +
path.basename( filePath ) + ' ]] failed: ' + error );
cb( error, null );
return;
}
cb( null, result.trim() );
});
} | javascript | {
"resource": ""
} |
q26914 | yamlParse | train | function yamlParse (text, reviver) {
try {
return yaml.safeLoad(text);
}
catch (e) {
if (e instanceof Error) {
throw e;
}
else {
// https://github.com/nodeca/js-yaml/issues/153
throw ono(e, e.message);
}
}
} | javascript | {
"resource": ""
} |
q26915 | yamlStringify | train | function yamlStringify (value, replacer, space) {
try {
var indent = (typeof space === "string" ? space.length : space) || 2;
return yaml.safeDump(value, { indent: indent });
}
catch (e) {
if (e instanceof Error) {
throw e;
}
else {
// https://github.com/nodeca/js-yaml/issues/153
throw ono(e, e.message);
}
}
} | javascript | {
"resource": ""
} |
q26916 | parseJSON | train | function parseJSON (file) {
return new Promise(function (resolve, reject) {
var data = file.data;
if (Buffer.isBuffer(data)) {
data = data.toString();
}
if (typeof data === "string") {
if (data.trim().length === 0) {
resolve(undefined); // This mirrors the YAML behavior
}
else {
resolve(JSON.parse(data));
}
}
else {
// data is already a JavaScript value (object, array, number, null, NaN, etc.)
resolve(data);
}
});
} | javascript | {
"resource": ""
} |
q26917 | parse | train | function parse (path, $refs, options) {
try {
// Remove the URL fragment, if any
path = url.stripHash(path);
// Add a new $Ref for this file, even though we don't have the value yet.
// This ensures that we don't simultaneously read & parse the same file multiple times
var $ref = $refs._add(path);
// This "file object" will be passed to all resolvers and parsers.
var file = {
url: path,
extension: url.getExtension(path),
};
// Read the file and then parse the data
return readFile(file, options)
.then(function (resolver) {
$ref.pathType = resolver.plugin.name;
file.data = resolver.result;
return parseFile(file, options);
})
.then(function (parser) {
$ref.value = parser.result;
return parser.result;
});
}
catch (e) {
return Promise.reject(e);
}
} | javascript | {
"resource": ""
} |
q26918 | parseFile | train | function parseFile (file, options) {
return new Promise(function (resolve, reject) {
// console.log('Parsing %s', file.url);
// Find the parsers that can read this file type.
// If none of the parsers are an exact match for this file, then we'll try ALL of them.
// This handles situations where the file IS a supported type, just with an unknown extension.
var allParsers = plugins.all(options.parse);
var filteredParsers = plugins.filter(allParsers, "canParse", file);
var parsers = filteredParsers.length > 0 ? filteredParsers : allParsers;
// Run the parsers, in order, until one of them succeeds
plugins.sort(parsers);
plugins.run(parsers, "parse", file)
.then(onParsed, onError);
function onParsed (parser) {
if (!parser.plugin.allowEmpty && isEmpty(parser.result)) {
reject(ono.syntax('Error parsing "%s" as %s. \nParsed value is empty', file.url, parser.plugin.name));
}
else {
resolve(parser);
}
}
function onError (err) {
if (err) {
err = err instanceof Error ? err : new Error(err);
reject(ono.syntax(err, "Error parsing %s", file.url));
}
else {
reject(ono.syntax("Unable to parse %s", file.url));
}
}
});
} | javascript | {
"resource": ""
} |
q26919 | isEmpty | train | function isEmpty (value) {
return value === undefined ||
(typeof value === "object" && Object.keys(value).length === 0) ||
(typeof value === "string" && value.trim().length === 0) ||
(Buffer.isBuffer(value) && value.length === 0);
} | javascript | {
"resource": ""
} |
q26920 | merge | train | function merge (target, source) {
if (isMergeable(source)) {
var keys = Object.keys(source);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var sourceSetting = source[key];
var targetSetting = target[key];
if (isMergeable(sourceSetting)) {
// It's a nested object, so merge it recursively
target[key] = merge(targetSetting || {}, sourceSetting);
}
else if (sourceSetting !== undefined) {
// It's a scalar value, function, or array. No merging necessary. Just overwrite the target value.
target[key] = sourceSetting;
}
}
}
return target;
} | javascript | {
"resource": ""
} |
q26921 | isMergeable | train | function isMergeable (val) {
return val &&
(typeof val === "object") &&
!Array.isArray(val) &&
!(val instanceof RegExp) &&
!(val instanceof Date);
} | javascript | {
"resource": ""
} |
q26922 | crawl | train | function crawl (obj, path, $refs, options) {
var promises = [];
if (obj && typeof obj === "object") {
if ($Ref.isExternal$Ref(obj)) {
promises.push(resolve$Ref(obj, path, $refs, options));
}
else {
Object.keys(obj).forEach(function (key) {
var keyPath = Pointer.join(path, key);
var value = obj[key];
if ($Ref.isExternal$Ref(value)) {
promises.push(resolve$Ref(value, keyPath, $refs, options));
}
else {
promises = promises.concat(crawl(value, keyPath, $refs, options));
}
});
}
}
return promises;
} | javascript | {
"resource": ""
} |
q26923 | resolve$Ref | train | function resolve$Ref ($ref, path, $refs, options) {
// console.log('Resolving $ref pointer "%s" at %s', $ref.$ref, path);
var resolvedPath = url.resolve(path, $ref.$ref);
var withoutHash = url.stripHash(resolvedPath);
// Do we already have this $ref?
$ref = $refs._$refs[withoutHash];
if ($ref) {
// We've already parsed this $ref, so use the existing value
return Promise.resolve($ref.value);
}
// Parse the $referenced file/url
return parse(resolvedPath, $refs, options)
.then(function (result) {
// Crawl the parsed value
// console.log('Resolving $ref pointers in %s', withoutHash);
var promises = crawl(result, withoutHash + "#", $refs, options);
return Promise.all(promises);
});
} | javascript | {
"resource": ""
} |
q26924 | crawl | train | function crawl (parent, key, path, pathFromRoot, indirections, inventory, $refs, options) {
var obj = key === null ? parent : parent[key];
if (obj && typeof obj === "object") {
if ($Ref.isAllowed$Ref(obj)) {
inventory$Ref(parent, key, path, pathFromRoot, indirections, inventory, $refs, options);
}
else {
// Crawl the object in a specific order that's optimized for bundling.
// This is important because it determines how `pathFromRoot` gets built,
// which later determines which keys get dereferenced and which ones get remapped
var keys = Object.keys(obj)
.sort(function (a, b) {
// Most people will expect references to be bundled into the the "definitions" property,
// so we always crawl that property first, if it exists.
if (a === "definitions") {
return -1;
}
else if (b === "definitions") {
return 1;
}
else {
// Otherwise, crawl the keys based on their length.
// This produces the shortest possible bundled references
return a.length - b.length;
}
});
keys.forEach(function (key) {
var keyPath = Pointer.join(path, key);
var keyPathFromRoot = Pointer.join(pathFromRoot, key);
var value = obj[key];
if ($Ref.isAllowed$Ref(value)) {
inventory$Ref(obj, key, path, keyPathFromRoot, indirections, inventory, $refs, options);
}
else {
crawl(obj, key, keyPath, keyPathFromRoot, indirections, inventory, $refs, options);
}
});
}
}
} | javascript | {
"resource": ""
} |
q26925 | parseText | train | function parseText (file) {
if (typeof file.data === "string") {
return file.data;
}
else if (Buffer.isBuffer(file.data)) {
return file.data.toString(this.encoding);
}
else {
throw new Error("data is not text");
}
} | javascript | {
"resource": ""
} |
q26926 | getPaths | train | function getPaths ($refs, types) {
var paths = Object.keys($refs);
// Filter the paths by type
types = Array.isArray(types[0]) ? types[0] : Array.prototype.slice.call(types);
if (types.length > 0 && types[0]) {
paths = paths.filter(function (key) {
return types.indexOf($refs[key].pathType) !== -1;
});
}
// Decode local filesystem paths
return paths.map(function (path) {
return {
encoded: path,
decoded: $refs[path].pathType === "file" ? url.toFileSystemPath(path, true) : path
};
});
} | javascript | {
"resource": ""
} |
q26927 | Pointer | train | function Pointer ($ref, path, friendlyPath) {
/**
* The {@link $Ref} object that contains this {@link Pointer} object.
* @type {$Ref}
*/
this.$ref = $ref;
/**
* The file path or URL, containing the JSON pointer in the hash.
* This path is relative to the path of the main JSON schema file.
* @type {string}
*/
this.path = path;
/**
* The original path or URL, used for error messages.
* @type {string}
*/
this.originalPath = friendlyPath || path;
/**
* The value of the JSON pointer.
* Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays).
* @type {?*}
*/
this.value = undefined;
/**
* Indicates whether the pointer references itself.
* @type {boolean}
*/
this.circular = false;
/**
* The number of indirect references that were traversed to resolve the value.
* Resolving a single pointer may require resolving multiple $Refs.
* @type {number}
*/
this.indirections = 0;
} | javascript | {
"resource": ""
} |
q26928 | dereference | train | function dereference (parser, options) {
// console.log('Dereferencing $ref pointers in %s', parser.$refs._root$Ref.path);
var dereferenced = crawl(parser.schema, parser.$refs._root$Ref.path, "#", [], parser.$refs, options);
parser.$refs.circular = dereferenced.circular;
parser.schema = dereferenced.value;
} | javascript | {
"resource": ""
} |
q26929 | crawl | train | function crawl (obj, path, pathFromRoot, parents, $refs, options) {
var dereferenced;
var result = {
value: obj,
circular: false
};
if (obj && typeof obj === "object") {
parents.push(obj);
if ($Ref.isAllowed$Ref(obj, options)) {
dereferenced = dereference$Ref(obj, path, pathFromRoot, parents, $refs, options);
result.circular = dereferenced.circular;
result.value = dereferenced.value;
}
else {
Object.keys(obj).forEach(function (key) {
var keyPath = Pointer.join(path, key);
var keyPathFromRoot = Pointer.join(pathFromRoot, key);
var value = obj[key];
var circular = false;
if ($Ref.isAllowed$Ref(value, options)) {
dereferenced = dereference$Ref(value, keyPath, keyPathFromRoot, parents, $refs, options);
circular = dereferenced.circular;
obj[key] = dereferenced.value;
}
else {
if (parents.indexOf(value) === -1) {
dereferenced = crawl(value, keyPath, keyPathFromRoot, parents, $refs, options);
circular = dereferenced.circular;
obj[key] = dereferenced.value;
}
else {
circular = foundCircularReference(keyPath, $refs, options);
}
}
// Set the "isCircular" flag if this or any other property is circular
result.circular = result.circular || circular;
});
}
parents.pop();
}
return result;
} | javascript | {
"resource": ""
} |
q26930 | dereference$Ref | train | function dereference$Ref ($ref, path, pathFromRoot, parents, $refs, options) {
// console.log('Dereferencing $ref pointer "%s" at %s', $ref.$ref, path);
var $refPath = url.resolve(path, $ref.$ref);
var pointer = $refs._resolve($refPath, options);
// Check for circular references
var directCircular = pointer.circular;
var circular = directCircular || parents.indexOf(pointer.value) !== -1;
circular && foundCircularReference(path, $refs, options);
// Dereference the JSON reference
var dereferencedValue = $Ref.dereference($ref, pointer.value);
// Crawl the dereferenced value (unless it's circular)
if (!circular) {
// Determine if the dereferenced value is circular
var dereferenced = crawl(dereferencedValue, pointer.path, pathFromRoot, parents, $refs, options);
circular = dereferenced.circular;
dereferencedValue = dereferenced.value;
}
if (circular && !directCircular && options.dereference.circular === "ignore") {
// The user has chosen to "ignore" circular references, so don't change the value
dereferencedValue = $ref;
}
if (directCircular) {
// The pointer is a DIRECT circular reference (i.e. it references itself).
// So replace the $ref path with the absolute path from the JSON Schema root
dereferencedValue.$ref = pathFromRoot;
}
return {
circular: circular,
value: dereferencedValue
};
} | javascript | {
"resource": ""
} |
q26931 | readHttp | train | function readHttp (file) {
var u = url.parse(file.url);
if (process.browser && !u.protocol) {
// Use the protocol of the current page
u.protocol = url.parse(location.href).protocol;
}
return download(u, this);
} | javascript | {
"resource": ""
} |
q26932 | get | train | function get (u, httpOptions) {
return new Promise(function (resolve, reject) {
// console.log('GET', u.href);
var protocol = u.protocol === "https:" ? https : http;
var req = protocol.get({
hostname: u.hostname,
port: u.port,
path: u.path,
auth: u.auth,
protocol: u.protocol,
headers: httpOptions.headers || {},
withCredentials: httpOptions.withCredentials
});
if (typeof req.setTimeout === "function") {
req.setTimeout(httpOptions.timeout);
}
req.on("timeout", function () {
req.abort();
});
req.on("error", reject);
req.once("response", function (res) {
res.body = new Buffer(0);
res.on("data", function (data) {
res.body = Buffer.concat([res.body, new Buffer(data)]);
});
res.on("error", reject);
res.on("end", function () {
resolve(res);
});
});
});
} | javascript | {
"resource": ""
} |
q26933 | getResult | train | function getResult (obj, prop, file, callback) {
var value = obj[prop];
if (typeof value === "function") {
return value.apply(obj, [file, callback]);
}
if (!callback) {
// The synchronous plugin functions (canParse and canRead)
// allow a "shorthand" syntax, where the user can match
// files by RegExp or by file extension.
if (value instanceof RegExp) {
return value.test(file.url);
}
else if (typeof value === "string") {
return value === file.extension;
}
else if (Array.isArray(value)) {
return value.indexOf(file.extension) !== -1;
}
}
return value;
} | javascript | {
"resource": ""
} |
q26934 | parseYAML | train | function parseYAML (file) {
return new Promise(function (resolve, reject) {
var data = file.data;
if (Buffer.isBuffer(data)) {
data = data.toString();
}
if (typeof data === "string") {
resolve(YAML.parse(data));
}
else {
// data is already a JavaScript value (object, array, number, null, NaN, etc.)
resolve(data);
}
});
} | javascript | {
"resource": ""
} |
q26935 | normalizeArgs | train | function normalizeArgs (args) {
var path, schema, options, callback;
args = Array.prototype.slice.call(args);
if (typeof args[args.length - 1] === "function") {
// The last parameter is a callback function
callback = args.pop();
}
if (typeof args[0] === "string") {
// The first parameter is the path
path = args[0];
if (typeof args[2] === "object") {
// The second parameter is the schema, and the third parameter is the options
schema = args[1];
options = args[2];
}
else {
// The second parameter is the options
schema = undefined;
options = args[1];
}
}
else {
// The first parameter is the schema
path = "";
schema = args[0];
options = args[1];
}
if (!(options instanceof Options)) {
options = new Options(options);
}
return {
path: path,
schema: schema,
options: options,
callback: callback
};
} | javascript | {
"resource": ""
} |
q26936 | promisesWrapper | train | function promisesWrapper(func) {
return (options, callback) => {
// options is an optional argument
if (typeof options === 'function') {
callback = options;
options = undefined;
}
options = options || {};
// just call the function otherwise wrap a promise around its execution
if (typeof callback === 'function') {
func(options, callback);
return undefined;
} else {
return new Promise((fulfill, reject) => {
func(options, (err, result) => {
if (err) {
reject(err);
} else {
fulfill(result);
}
});
});
}
};
} | javascript | {
"resource": ""
} |
q26937 | domReady | train | function domReady(callback) {
if (doc.readyState === "complete" || (doc.readyState !== "loading" && !doc.documentElement.doScroll))
setTimeout(() => callback && callback(), 0)
else {
let handler = () => {
doc.removeEventListener("DOMContentLoaded", handler, false)
win.removeEventListener("load", handler, false)
callback && callback()
}
doc.addEventListener("DOMContentLoaded", handler, false)
win.addEventListener("load", handler, false)
}
} | javascript | {
"resource": ""
} |
q26938 | oReady | train | function oReady(o, callback) {
!!o && (callback && callback()) || setTimeout(() => oReady(o, callback), 10)
} | javascript | {
"resource": ""
} |
q26939 | isCyclic | train | function isCyclic (data) {
// Create an array that will store the nodes of the array that have already been iterated over
let seenObjects = [];
function detect (data) {
// If the data pass is an object
if (data && getType(data) === "Object") {
// If the data is already in the seen nodes array then we know there is a circular reference
// Therefore return true
if (seenObjects.indexOf(data) !== -1) {
return true;
}
// Add the data to the seen objects array
seenObjects.push(data);
// Begin iterating through the data passed to the method
for (var key in data) {
// Recall this method with the objects key
if (data.hasOwnProperty(key) === true && detect(data[key])) {
return true;
}
}
}
return false;
}
// Return the method
return detect(data);
} | javascript | {
"resource": ""
} |
q26940 | teardownAll | train | function teardownAll() {
var componentInfo = registry.findComponentInfo(this);
componentInfo && Object.keys(componentInfo.instances).forEach(function(k) {
var info = componentInfo.instances[k];
// It's possible that a previous teardown caused another component to teardown,
// so we can't assume that the instances object is as it was.
if (info && info.instance) {
info.instance.teardown();
}
});
} | javascript | {
"resource": ""
} |
q26941 | train | function(name, context, partials, indent) {
var partial = partials[name];
if (!partial) {
return '';
}
if (this.c && typeof partial == 'string') {
partial = this.c.compile(partial, this.options);
}
return partial.ri(context, partials, indent);
} | javascript | {
"resource": ""
} | |
q26942 | train | function(val, ctx, partials, inverted, start, end, tags) {
var cx = ctx[ctx.length - 1],
t = null;
if (!inverted && this.c && val.length > 0) {
return this.ho(val, cx, partials, this.text.substring(start, end), tags);
}
t = val.call(cx);
if (typeof t == 'function') {
if (inverted) {
return true;
} else if (this.c) {
return this.ho(t, cx, partials, this.text.substring(start, end), tags);
}
}
return t;
} | javascript | {
"resource": ""
} | |
q26943 | train | function(val, ctx, partials) {
var cx = ctx[ctx.length - 1];
var result = val.call(cx);
if (typeof result == 'function') {
result = result.call(cx);
}
result = coerceToString(result);
if (this.c && ~result.indexOf("{\u007B")) {
return this.c.compile(result, this.options).render(cx, partials);
}
return result;
} | javascript | {
"resource": ""
} | |
q26944 | getOrCreateSwarm | train | function getOrCreateSwarm (cb) {
self.getSwarm(params.info_hash, (err, swarm) => {
if (err) return cb(err)
if (swarm) return cb(null, swarm)
self.createSwarm(params.info_hash, (err, swarm) => {
if (err) return cb(err)
cb(null, swarm)
})
})
} | javascript | {
"resource": ""
} |
q26945 | fromUInt64 | train | function fromUInt64 (buf) {
var high = buf.readUInt32BE(0) | 0 // force
var low = buf.readUInt32BE(4) | 0
var lowUnsigned = (low >= 0) ? low : TWO_PWR_32 + low
return (high * TWO_PWR_32) + lowUnsigned
} | javascript | {
"resource": ""
} |
q26946 | shallowClone | train | function shallowClone(obj) {
let result = {};
for (let p in obj) {
if (obj.hasOwnProperty(p)) {
result[p] = obj[p];
}
}
return result;
} | javascript | {
"resource": ""
} |
q26947 | deepClone | train | function deepClone(obj) {
let result = Array.isArray(obj) ? [] : {};
for (let p in obj) {
if (obj.hasOwnProperty(p) || Array.isArray(obj)) {
result[p] = (typeof obj[p] === 'object') ? deepClone(obj[p]) : obj[p];
}
}
return result;
} | javascript | {
"resource": ""
} |
q26948 | recurse | train | function recurse(object, state, callback) {
if (!state) state = {depth:0};
if (!state.depth) {
state = Object.assign({},defaultState(),state);
}
if (typeof object !== 'object') return;
let oPath = state.path;
for (let key in object) {
state.key = key;
state.path = state.path + '/' + encodeURIComponent(jpescape(key));
state.identityPath = state.seen.get(object[key]);
state.identity = (typeof state.identityPath !== 'undefined');
callback(object, key, state);
if ((typeof object[key] === 'object') && (!state.identity)) {
if (state.identityDetection && !Array.isArray(object[key]) && object[key] !== null) {
state.seen.set(object[key],state.path);
}
let newState = {};
newState.parent = object;
newState.path = state.path;
newState.depth = state.depth ? state.depth+1 : 1;
newState.pkey = key;
newState.payload = state.payload;
newState.seen = state.seen;
newState.identity = false;
newState.identityDetection = state.identityDetection;
recurse(object[key], newState, callback);
}
state.path = oPath;
}
} | javascript | {
"resource": ""
} |
q26949 | getDefaultState | train | function getDefaultState() {
return { depth: 0, seen: new WeakMap(), top: true, combine: false, allowRefSiblings: false };
} | javascript | {
"resource": ""
} |
q26950 | hasIncomingEdge | train | function hasIncomingEdge(list, node) {
for (var i = 0, l = list.length; i < l; ++i) {
if (list[i].links.find(function(e,i,a){
return node._id == e;
})) return true;
}
return false;
} | javascript | {
"resource": ""
} |
q26951 | flatten | train | function flatten(obj,callback) {
let arr = [];
let iDepth, oDepth = 0;
let state = {identityDetection:true};
recurse(obj,state,function(obj,key,state){
let entry = {};
entry.name = key;
entry.value = obj[key];
entry.path = state.path;
entry.parent = obj;
entry.key = key;
if (callback) entry = callback(entry);
if (entry) {
if (state.depth > iDepth) {
oDepth++;
}
else if (state.depth < iDepth) {
oDepth--;
}
entry.depth = oDepth;
iDepth = state.depth;
arr.push(entry);
}
});
return arr;
} | javascript | {
"resource": ""
} |
q26952 | optionalResolve | train | function optionalResolve(options) {
setupOptions(options);
return new Promise(function (res, rej) {
if (options.resolve)
loopReferences(options, res, rej)
else
res(options);
});
} | javascript | {
"resource": ""
} |
q26953 | getStuffAndDeleteSecret | train | function getStuffAndDeleteSecret(opts, someArgument) {
// We depend on "stuffs" repository.
const stuffs = opts.stuffs
// We may now carry on.
return stuffs.getStuff(someArgument).then(stuff => {
// Modify return value. Just to prove this is testable.
delete stuff.secret
return stuff
})
} | javascript | {
"resource": ""
} |
q26954 | get | train | function get () {
var listener = this.listeners(method)[0]
return listener ? (listener._listener ? listener._listener : listener) : undefined
} | javascript | {
"resource": ""
} |
q26955 | getBinaryUrl | train | function getBinaryUrl() {
var site = getArgument('--fis-binary-site') ||
process.env.FIS_BINARY_SITE ||
process.env.npm_config_FIS_binary_site ||
(pkg.nodeConfig && pkg.nodeConfig.binarySite) ||
'https://github.com/' + repositoryName + '/releases/download';
return [site, 'v' + pkg.version, getBinaryName()].join('/');
} | javascript | {
"resource": ""
} |
q26956 | deepClone | train | function deepClone(obj) {
if (obj && typeof obj === 'object') {
if (Array.isArray(obj)) {
var newObj = [];
for (var i = 0, j = obj.length; i < j; i++) {
newObj[i] = deepClone(obj[i]);
}
return newObj;
} else if (isPlainObj(obj)) {
var _newObj = {};
for (var _i in obj) {
_newObj[_i] = deepClone(obj[_i]);
}
return _newObj;
}
}
return obj;
} | javascript | {
"resource": ""
} |
q26957 | profile | train | function profile(target, propertyKey, descriptor) {
if (flags_1.IS_PROFILE) {
return performProfile(target, propertyKey, descriptor);
}
else {
// return as-is
return descriptor;
}
} | javascript | {
"resource": ""
} |
q26958 | train | function(foo, self) {
return function() {
var arg, tmp, args = [];
for (var i = 0, l = arguments.length; i < l; i++) {
arg = arguments[i];
if (_isFunction(arg)) {
if (arg.tryWrap) {
arg = arg.tryWrap;
} else {
tmp = cat(arg);
arg.tryWrap = tmp;
arg = tmp;
}
}
args.push(arg);
}
return foo.apply(self || this, args);
};
} | javascript | {
"resource": ""
} | |
q26959 | train | function(obj) {
var key, value;
for (key in obj) {
value = obj[key];
if (_isFunction(value)) obj[key] = cat(value);
}
return obj;
} | javascript | {
"resource": ""
} | |
q26960 | encasedCallback | train | function encasedCallback( e, namespace, triggeredElement ){
var result;
if( e._namespace && e._namespace !== namespace ) {
return;
}
e.data = data;
e.namespace = e._namespace;
var returnTrue = function(){
return true;
};
e.isDefaultPrevented = function(){
return false;
};
var originalPreventDefault = e.preventDefault;
var preventDefaultConstructor = function(){
if( originalPreventDefault ) {
return function(){
e.isDefaultPrevented = returnTrue;
originalPreventDefault.call(e);
};
} else {
return function(){
e.isDefaultPrevented = returnTrue;
e.returnValue = false;
};
}
};
// thanks https://github.com/jonathantneal/EventListener
e.target = triggeredElement || e.target || e.srcElement;
e.preventDefault = preventDefaultConstructor();
e.stopPropagation = e.stopPropagation || function () {
e.cancelBubble = true;
};
result = originalCallback.apply(this, [ e ].concat( e._args ) );
if( result === false ){
e.preventDefault();
e.stopPropagation();
}
return result;
} | javascript | {
"resource": ""
} |
q26961 | checkBasicSupport | train | function checkBasicSupport(client, metadata, properties) {
try {
const supported = client.issuer.token_endpoint_auth_methods_supported;
if (!supported.includes(properties.token_endpoint_auth_method)) {
if (supported.includes('client_secret_post')) {
properties.token_endpoint_auth_method = 'client_secret_post';
}
}
} catch (err) {}
} | javascript | {
"resource": ""
} |
q26962 | train | function (html) {
var $ = cheerio.load(html, {
decodeEntities: false,
lowerCaseAttributeNames: false,
lowerCaseTags: false
});
var output = {
style: $.html('style'),
script: $.html('script')
};
var result;
$('style').remove();
$('script').remove();
result = '<template><section>' + $.html() + '</section></template>\n' +
output.style + '\n' +
output.script;
return result
} | javascript | {
"resource": ""
} | |
q26963 | guessAppName | train | function guessAppName (compilerWorkingDirectory) {
var packageJson = path.resolve(compilerWorkingDirectory, 'package.json');
if (!fs.existsSync(packageJson)) {
packageJson = path.resolve(compilerWorkingDirectory, '../package.json');
if (!fs.existsSync(packageJson)) {
return 'Webpack App';
}
}
return JSON.parse(fs.readFileSync(packageJson)).name;
} | javascript | {
"resource": ""
} |
q26964 | emitCacheInformationFile | train | function emitCacheInformationFile (loader, query, cacheFile, fileHash, iconResult) {
if (!query.persistentCache) {
return;
}
loader.emitFile(cacheFile, JSON.stringify({
hash: fileHash,
version: pluginVersion,
optionHash: generateHashForOptions(query),
result: iconResult
}));
} | javascript | {
"resource": ""
} |
q26965 | isCacheValid | train | function isCacheValid (cache, fileHash, query) {
// Verify that the source file is the same
return cache.hash === fileHash &&
// Verify that the options are the same
cache.optionHash === generateHashForOptions(query) &&
// Verify that the favicons version of the cache maches this version
cache.version === pluginVersion;
} | javascript | {
"resource": ""
} |
q26966 | loadIconsFromDiskCache | train | function loadIconsFromDiskCache (loader, query, cacheFile, fileHash, callback) {
// Stop if cache is disabled
if (!query.persistentCache) return callback(null);
var resolvedCacheFile = path.resolve(loader._compiler.parentCompilation.compiler.outputPath, cacheFile);
fs.exists(resolvedCacheFile, function (exists) {
if (!exists) return callback(null);
fs.readFile(resolvedCacheFile, function (err, content) {
if (err) return callback(err);
var cache;
try {
cache = JSON.parse(content);
// Bail out if the file or the option changed
if (!isCacheValid(cache, fileHash, query)) {
return callback(null);
}
} catch (e) {
return callback(e);
}
callback(null, cache.result);
});
});
} | javascript | {
"resource": ""
} |
q26967 | generateHashForOptions | train | function generateHashForOptions (options) {
var hash = crypto.createHash('md5');
hash.update(JSON.stringify(options));
return hash.digest('hex');
} | javascript | {
"resource": ""
} |
q26968 | getValueIfEnabled | train | function getValueIfEnabled(expr, source, path) {
if (!options.deep && expr.includes('@')) {
console.error(`[Vuex Pathify] Unable to access sub-property for path '${expr}':
- Set option 'deep' to 1 to allow it`)
return
}
return getValue(source, path)
} | javascript | {
"resource": ""
} |
q26969 | Get | train | function Get(path) {
if (typeof path !== 'string' || arguments.length > 1) { throw new Error('Property decorators can be used for single property access') }
return createDecorator((options, key) => {
if (!options.computed) options.computed = {}
options.computed[key] = get(path)
})
} | javascript | {
"resource": ""
} |
q26970 | Sync | train | function Sync(path) {
if (typeof path !== 'string' || arguments.length > 1) { throw new Error('Property decorators can be used for single property access') }
return createDecorator((options, key) => {
if (!options.computed) options.computed = {}
options.computed[key] = sync(path)
})
} | javascript | {
"resource": ""
} |
q26971 | Call | train | function Call(path) {
if (typeof path !== 'string' || arguments.length > 1) { throw new Error('Property decorators can be used for single property access') }
return createDecorator((options, key) => {
if (!options.methods) options.methods = {}
options.methods[key] = call(path)
})
} | javascript | {
"resource": ""
} |
q26972 | fixAnchors | train | function fixAnchors (hook) {
hook.afterEach(function (html, next) {
// find all headings and replace them
html = html.replace(/<(h\d).+?<\/\1>/g, function (html) {
// create temp node
var div = document.createElement('div')
div.innerHTML = html
// get anchor
var link = div.querySelector('a[href*="?id"]')
if (!link) {
return html
}
// work out id
var text = link.innerText
var id = text
.split('(')
.shift()
.toLowerCase()
.replace(/\W+/g, '-')
.replace(/^-+|-+$/g, '')
var href = link.getAttribute('href')
.replace(/\?id=.+/, '?id=' + id)
// update dom
link.setAttribute('href', href)
link.setAttribute('data-id', id)
link.parentElement.setAttribute('id', id)
// return html
return div.innerHTML
})
// continue
next(html)
})
} | javascript | {
"resource": ""
} |
q26973 | train | function(context) {
const androidHome = process.env['ANDROID_HOME']
const hasAndroidEnv = !context.strings.isBlank(androidHome)
const hasAndroid = hasAndroidEnv && context.filesystem.exists(`${androidHome}/tools`) === 'dir'
return Boolean(hasAndroid)
} | javascript | {
"resource": ""
} | |
q26974 | restoreService | train | function restoreService(service) {
if (services[service]) {
restoreAllMethods(service);
if (services[service].stub)
services[service].stub.restore();
delete services[service];
} else {
console.log('Service ' + service + ' was never instantiated yet you try to restore it.');
}
} | javascript | {
"resource": ""
} |
q26975 | copyReadmeFiles | train | function copyReadmeFiles() {
const resolvedSrcReadmePaths = path.resolve(rootDir, srcReadmePaths);
glob(resolvedSrcReadmePaths, void(0), function(error, files) {
files.forEach((filePath) => {
const destReadmePath = filePath.replace(/(\bsrc\b)(?!.*\1)/, destDir);
fs.copyFileSync(filePath, destReadmePath);
});
});
} | javascript | {
"resource": ""
} |
q26976 | execute | train | function execute() {
if (dryRun) {
console.log(`In ${destDir}, this script would...`);
} else {
console.log(`Generating API documentation using TypeDoc...`);
}
const packages = path.resolve(rootDir, srcDir);
glob(packages, {realpath:true}, function(error, srcFiles) {
srcFiles.forEach((srcPath) => {
var valid = true;
var packageName = srcPath
.split(path.sep)
.pop();
excludedPackages.forEach((excludedPackageName) => {
if (packageName === excludedPackageName) {
console.log(chalk.yellow(`...skip generating TypeDoc API files for ${packageName}`));
valid = false;
}
});
if(valid) {
dryRun ? console.log(`...generate TypeDoc API files for ${packageName}`) : createAPIFiles(packageName, srcPath);
}
});
});
} | javascript | {
"resource": ""
} |
q26977 | addHeaderToReadme | train | function addHeaderToReadme(packageName) {
const readmePath = path.join(destDir, packageName, 'api', 'README.md');
const readmeText = fs.readFileSync(readmePath).toString();
var docusaurusHeader =
`---\n` +
`id: index\n` +
`---\n\n`;
try {
fs.writeFileSync(readmePath, docusaurusHeader);
fs.appendFileSync(readmePath, readmeText);
} catch (err) {
console.log(chalk.red(err));
}
} | javascript | {
"resource": ""
} |
q26978 | addAPILinkToReadme | train | function addAPILinkToReadme(packageName) {
var readmePath = path.join(destDir, packageName, 'README.md');
var apiLink = "api";
var usageText =
"\n" +
`[API Reference](${apiLink})`;
fs.appendFile(readmePath, usageText, function (err) {
if (err) {
console.log(chalk.red(err));
}
})
} | javascript | {
"resource": ""
} |
q26979 | createDirectory | train | function createDirectory(dir) {
if (!fs.existsSync(dir)) {
dryRun ? console.log(`...CREATE the '${dir}' folder.`) : fs.mkdirSync(dir);
}
} | javascript | {
"resource": ""
} |
q26980 | exportReadme | train | function exportReadme(readmePath) {
const readmePaths = path.resolve(process.cwd(), srcDir);
glob(readmePaths, void(0), function(error, files) {
files.forEach((filePath) => {
let documentation = startFile;
const markdown = fs.readFileSync(filePath, "utf8");
const exportPath = filePath.replace(/README\.md/, readmePath);
if (markdown.length !== 0) {
documentation += md.render(markdown);
} else {
documentation += emptyFile;
}
documentation += endFile;
if (!fs.existsSync(exportPath)){
fs.mkdirSync(exportPath);
}
fs.writeFileSync(path.resolve(exportPath, "documentation.tsx"), documentation);
});
});
} | javascript | {
"resource": ""
} |
q26981 | cleanPath | train | function cleanPath(cleanPath) {
const removePath = path.resolve(process.cwd(), cleanPath)
rimraf(removePath, () => {
console.log(removePath, "cleaned");
});
} | javascript | {
"resource": ""
} |
q26982 | copySchemaFiles | train | function copySchemaFiles() {
const resolvedSrcSchemaPaths = path.resolve(rootDir, srcSchemaPaths);
glob(resolvedSrcSchemaPaths, void(0), function(error, files) {
files.forEach((filePath) => {
const destSchemaPath = filePath.replace(/(\bsrc\b)(?!.*\1)/, destDir);
fs.copyFileSync(filePath, destSchemaPath);
});
});
} | javascript | {
"resource": ""
} |
q26983 | js | train | function js(prefix) {
gulp.src('src/clockpicker.js')
.pipe(rename({
prefix: prefix + '-'
}))
.pipe(replace(versionRegExp, version))
.pipe(gulp.dest('dist'))
.pipe(uglify({
preserveComments: 'some'
}))
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('dist'));
} | javascript | {
"resource": ""
} |
q26984 | css | train | function css(prefix) {
var stream;
if (prefix === 'bootstrap') {
stream = gulp.src('src/clockpicker.css');
} else {
// Concat with some styles picked from bootstrap
stream = gulp.src(['src/standalone.css', 'src/clockpicker.css'])
.pipe(concat('clockpicker.css'));
}
stream.pipe(rename({
prefix: prefix + '-'
}))
.pipe(replace(versionRegExp, version))
.pipe(gulp.dest('dist'))
.pipe(minifyCSS({
keepSpecialComments: 1
}))
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('dist'));
} | javascript | {
"resource": ""
} |
q26985 | train | function (layer, targetCenter, targetZoom) {
map._stop();
var startZoom = map._zoom;
targetCenter = L.latLng(targetCenter);
targetZoom = targetZoom === undefined ? startZoom : targetZoom;
targetZoom = Math.min(targetZoom, map.getMaxZoom()); // don't go past max zoom
var start = Date.now(),
duration = 75;
function frame() {
var t = (Date.now() - start) / duration;
if (t <= 1) {
// reuse internal flyTo frame to ensure these animations are canceled like others
map._flyToFrame = L.Util.requestAnimFrame(frame, map);
setZoomAroundNoMoveEnd(layer, targetCenter, startZoom + (targetZoom - startZoom) * t);
} else {
setZoomAroundNoMoveEnd(layer, targetCenter, targetZoom)
._moveEnd(true);
}
}
map._moveStart(true);
frame.call(map);
return map;
} | javascript | {
"resource": ""
} | |
q26986 | addDebugLayers | train | function addDebugLayers (node, tree) {
for (let layer in node) {
let counts = node[layer];
addLayerDebugEntry(tree, layer, counts.features, counts.geoms, counts.styles, counts.base);
if (counts.layers) {
tree[layer].layers = tree[layer].layers || {};
addDebugLayers(counts.layers, tree[layer].layers); // process child layers
}
}
} | javascript | {
"resource": ""
} |
q26987 | meshSetString | train | function meshSetString (tiles) {
return JSON.stringify(
Object.entries(tiles).map(([,t]) => {
return Object.entries(t.meshes).map(([,s]) => {
return s.map(m => m.created_at);
});
})
);
} | javascript | {
"resource": ""
} |
q26988 | getCentroidFeatureForPolygon | train | function getCentroidFeatureForPolygon (coordinates, properties, newProperties) {
let centroid = Geo.centroid(coordinates);
if (!centroid) {
return;
}
// clone properties and mixix newProperties
let centroid_properties = {};
Object.assign(centroid_properties, properties, newProperties);
return {
type: 'Feature',
properties: centroid_properties,
geometry: {
type: 'Point',
coordinates: centroid
}
};
} | javascript | {
"resource": ""
} |
q26989 | flattenProperties | train | function flattenProperties (obj, prefix = null, globals = {}) {
prefix = prefix ? (prefix + '.') : 'global.';
for (const p in obj) {
const key = prefix + p;
const val = obj[p];
globals[key] = val;
if (typeof val === 'object' && !Array.isArray(val)) {
flattenProperties(val, key, globals);
}
}
return globals;
} | javascript | {
"resource": ""
} |
q26990 | compareArray | train | function compareArray(a1, a2) {
if (a1.length != a2.length) return false;
for (var i = 0; i < a1.length; i++) {
if (a1[i] !== a2[i]) return false;
}
return true;
} | javascript | {
"resource": ""
} |
q26991 | unbindKey | train | function unbindKey(key, scope) {
var multipleKeys, keys,
mods = [],
i, j, obj;
multipleKeys = getKeys(key);
for (j = 0; j < multipleKeys.length; j++) {
keys = multipleKeys[j].split('+');
if (keys.length > 1) {
mods = getMods(keys);
key = keys[keys.length - 1];
}
key = code(key);
if (scope === undefined) {
scope = getScope();
}
if (!_handlers[key]) {
return;
}
for (i = 0; i < _handlers[key].length; i++) {
obj = _handlers[key][i];
// only clear handlers if correct scope and mods match
if (obj.scope === scope && compareArray(obj.mods, mods)) {
_handlers[key][i] = {};
}
}
}
} | javascript | {
"resource": ""
} |
q26992 | deleteScope | train | function deleteScope(scope){
var key, handlers, i;
for (key in _handlers) {
handlers = _handlers[key];
for (i = 0; i < handlers.length; ) {
if (handlers[i].scope === scope) handlers.splice(i, 1);
else i++;
}
}
} | javascript | {
"resource": ""
} |
q26993 | getKeys | train | function getKeys(key) {
var keys;
key = key.replace(/\s/g, '');
keys = key.split(',');
if ((keys[keys.length - 1]) == '') {
keys[keys.length - 2] += ',';
}
return keys;
} | javascript | {
"resource": ""
} |
q26994 | getMods | train | function getMods(key) {
var mods = key.slice(0, key.length - 1);
for (var mi = 0; mi < mods.length; mi++)
mods[mi] = _MODIFIERS[mods[mi]];
return mods;
} | javascript | {
"resource": ""
} |
q26995 | freeTransferables | train | function freeTransferables(transferables) {
if (!Array.isArray(transferables)) {
return;
}
transferables.filter(t => t.parent && t.property).forEach(t => delete t.parent[t.property]);
} | javascript | {
"resource": ""
} |
q26996 | onHover | train | function onHover (selection) {
var feature = selection.feature;
if (feature) {
if (selection.changed) {
var info;
if (scene.introspection) {
info = getFeaturePropsHTML(feature);
}
else {
var name = feature.properties.name || feature.properties.kind ||
(Object.keys(feature.properties).length+' properties');
name = '<b>'+name+'</b>';
name += '<br>(click for details)';
name = '<span class="labelInner">' + name + '</span>';
info = name;
}
if (info) {
tooltip.setContent(info);
}
}
layer.openTooltip(selection.leaflet_event.latlng);
}
else {
layer.closeTooltip();
}
} | javascript | {
"resource": ""
} |
q26997 | getFeaturePropsHTML | train | function getFeaturePropsHTML (feature) {
var props = ['name', 'kind', 'kind_detail', 'id']; // show these properties first if available
Object.keys(feature.properties) // show rest of proeprties alphabetized
.sort()
.forEach(function(p) {
if (props.indexOf(p) === -1) {
props.push(p);
}
});
var info = '<div class="featureTable">';
props.forEach(function(p) {
if (feature.properties[p]) {
info += '<div class="featureRow"><div class="featureCell"><b>' + p + '</b></div>' +
'<div class="featureCell">' + feature.properties[p] + '</div></div>';
}
});
info += '<div class="featureRow"><div class="featureCell"><b>scene layers</b></div>' +
'<div class="featureCell">' + feature.layers.join('<br>') + '</div></div>';
info += '</div>';
return info;
} | javascript | {
"resource": ""
} |
q26998 | getNextNonBoundarySegment | train | function getNextNonBoundarySegment (line, startIndex, tolerance) {
var endIndex = startIndex;
while (line[endIndex + 1] && outsideTile(line[endIndex], line[endIndex + 1], tolerance)) {
endIndex++;
}
// If there is a line segment remaining that is within the tile, push it to the lines array
return (line.length - endIndex >= 2) ? line.slice(endIndex) : false;
} | javascript | {
"resource": ""
} |
q26999 | endPolygon | train | function endPolygon(coordCurr, normPrev, normNext, join_type, v, context) {
// If polygon ends on a tile boundary, don't add a join
if (isCoordOutsideTile(coordCurr)) {
addVertex(coordCurr, normPrev, normPrev, 1, v, context, 1);
addVertex(coordCurr, normPrev, normPrev, 0, v, context, -1);
indexPairs(1, context);
}
else {
// If polygon ends within a tile, add Miter or no joint (join added on startPolygon)
var miterVec = createMiterVec(normPrev, normNext);
if (join_type === JOIN_TYPE.miter && Vector.lengthSq(miterVec) > context.miter_len_sq) {
join_type = JOIN_TYPE.bevel; // switch to bevel
}
if (join_type === JOIN_TYPE.miter) {
addVertex(coordCurr, miterVec, normPrev, 1, v, context, 1);
addVertex(coordCurr, miterVec, normPrev, 0, v, context, -1);
indexPairs(1, context);
}
else {
addVertex(coordCurr, normPrev, normPrev, 1, v, context, 1);
addVertex(coordCurr, normPrev, normPrev, 0, v, context, -1);
indexPairs(1, context);
}
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.