_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q45000
_runInDataframes
train
function _runInDataframes (viewportExpressions, renderLayer, dataframes) { const processedFeaturesIDs = new Set(); // same feature can belong to multiple dataframes const viz = renderLayer.viz; const inViewportFeaturesIDs = new Set(); dataframes.forEach(dataframe => { _runInDataframe(viz, viewportExpressions, dataframe, processedFeaturesIDs, inViewportFeaturesIDs); }); return inViewportFeaturesIDs; }
javascript
{ "resource": "" }
q45001
_runForPartialViewportFeatures
train
function _runForPartialViewportFeatures (viewportFeaturesExpressions, renderLayer, featuresIDs) { // Reset previous expressions with (possibly 1 partial) features viewportFeaturesExpressions.forEach(expr => expr._resetViewportAgg(null, renderLayer)); // Gather all pieces per feature const piecesPerFeature = renderLayer.getAllPiecesPerFeature(featuresIDs); // Run viewportFeatures with the whole set of feature pieces viewportFeaturesExpressions.forEach(expr => { for (const featureId in piecesPerFeature) { expr.accumViewportAgg(piecesPerFeature[featureId]); } }); }
javascript
{ "resource": "" }
q45002
checkAuth
train
function checkAuth (auth) { if (util.isUndefined(auth)) { throw new CartoValidationError('\'auth\'', CartoValidationErrorTypes.MISSING_REQUIRED); } if (!util.isObject(auth)) { throw new CartoValidationError('\'auth\' property must be an object.', CartoValidationErrorTypes.INCORRECT_TYPE); } auth.username = util.isUndefined(auth.username) ? auth.user : auth.username; // backwards compatibility checkApiKey(auth.apiKey); checkUsername(auth.username); }
javascript
{ "resource": "" }
q45003
resolveConfigPath
train
function resolveConfigPath(configPath) { // Specify a default configPath = configPath || '.pa11yci'; if (configPath[0] !== '/') { configPath = path.join(process.cwd(), configPath); } if (/\.js(on)?$/.test(configPath)) { configPath = configPath.replace(/\.js(on)?$/, ''); } return configPath; }
javascript
{ "resource": "" }
q45004
loadLocalConfigUnmodified
train
function loadLocalConfigUnmodified(configPath) { try { return JSON.parse(fs.readFileSync(configPath, 'utf-8')); } catch (error) { if (error.code !== 'ENOENT') { throw error; } } }
javascript
{ "resource": "" }
q45005
defaultConfig
train
function defaultConfig(config) { config.urls = config.urls || []; config.defaults = config.defaults || {}; config.defaults.log = config.defaults.log || console; // Setting to undefined rather than 0 allows for a fallback to the default config.defaults.wrapWidth = process.stdout.columns || undefined; if (program.json) { delete config.defaults.log; } return config; }
javascript
{ "resource": "" }
q45006
loadSitemapIntoConfig
train
function loadSitemapIntoConfig(program, config) { const sitemapUrl = program.sitemap; const sitemapFind = ( program.sitemapFind ? new RegExp(program.sitemapFind, 'gi') : null ); const sitemapReplace = program.sitemapReplace || ''; const sitemapExclude = ( program.sitemapExclude ? new RegExp(program.sitemapExclude, 'gi') : null ); return Promise.resolve() .then(() => { return fetch(sitemapUrl); }) .then(response => { return response.text(); }) .then(body => { const $ = cheerio.load(body, { xmlMode: true }); $('url > loc').toArray().forEach(element => { let url = $(element).text(); if (sitemapExclude && url.match(sitemapExclude)) { return; } if (sitemapFind) { url = url.replace(sitemapFind, sitemapReplace); } config.urls.push(url); }); return config; }) .catch(error => { if (error.stack && error.stack.includes('node-fetch')) { throw new Error(`The sitemap "${sitemapUrl}" could not be loaded`); } throw new Error(`The sitemap "${sitemapUrl}" could not be parsed`); }); }
javascript
{ "resource": "" }
q45007
WaveformDataSegment
train
function WaveformDataSegment(context, start, end) { this.context = context; /** * Start index. * * ```javascript * var waveform = new WaveformData({ ... }, WaveformData.adapters.object); * waveform.set_segment(10, 50, "example"); * * console.log(waveform.segments.example.start); // -> 10 * * waveform.offset(20, 50); * console.log(waveform.segments.example.start); // -> 10 * * waveform.offset(70, 100); * console.log(waveform.segments.example.start); // -> 10 * ``` * @type {Integer} Initial starting point of the segment. */ this.start = start; /** * End index. * * ```javascript * var waveform = new WaveformData({ ... }, WaveformData.adapters.object); * waveform.set_segment(10, 50, "example"); * * console.log(waveform.segments.example.end); // -> 50 * * waveform.offset(20, 50); * console.log(waveform.segments.example.end); // -> 50 * * waveform.offset(70, 100); * console.log(waveform.segments.example.end); // -> 50 * ``` * @type {Integer} Initial ending point of the segment. */ this.end = end; }
javascript
{ "resource": "" }
q45008
WaveformData
train
function WaveformData(response_data, adapter) { /** * Backend adapter used to manage access to the data. * * @type {Object} */ this.adapter = adapter.fromResponseData(response_data); /** * Defined segments. * * ```javascript * var waveform = new WaveformData({ ... }, WaveformData.adapters.object); * * console.log(waveform.segments.speakerA); // -> undefined * * waveform.set_segment(30, 90, "speakerA"); * * console.log(waveform.segments.speakerA.start); // -> 30 * ``` * * @type {Object} A hash of `WaveformDataSegment` objects. */ this.segments = {}; /** * Defined points. * * ```javascript * var waveform = new WaveformData({ ... }, WaveformData.adapters.object); * * console.log(waveform.points.speakerA); // -> undefined * * waveform.set_point(30, "speakerA"); * * console.log(waveform.points.speakerA.timeStamp); // -> 30 * ``` * * @type {Object} A hash of `WaveformDataPoint` objects. */ this.points = {}; this.offset(0, this.adapter.length); }
javascript
{ "resource": "" }
q45009
setSegment
train
function setSegment(start, end, identifier) { if (identifier === undefined || identifier === null || identifier.length === 0) { identifier = "default"; } this.segments[identifier] = new WaveformDataSegment(this, start, end); return this.segments[identifier]; }
javascript
{ "resource": "" }
q45010
setPoint
train
function setPoint(timeStamp, identifier) { if (identifier === undefined || identifier === null || identifier.length === 0) { identifier = "default"; } this.points[identifier] = new WaveformDataPoint(this, timeStamp); return this.points[identifier]; }
javascript
{ "resource": "" }
q45011
getOffsetValues
train
function getOffsetValues(start, length, correction) { var adapter = this.adapter; var values = []; correction += (start * 2); // offset the positioning query for (var i = 0; i < length; i++) { values.push(adapter.at((i * 2) + correction)); } return values; }
javascript
{ "resource": "" }
q45012
fromAudioObjectBuilder
train
function fromAudioObjectBuilder(audio_context, raw_response, options, callback) { var audioContext = window.AudioContext || window.webkitAudioContext; if (!(audio_context instanceof audioContext)) { throw new TypeError("First argument should be an AudioContext instance"); } var opts = getOptions(options, callback); callback = opts.callback; options = opts.options; // The following function is a workaround for a Webkit bug where decodeAudioData // invokes the errorCallback with null instead of a DOMException. // See https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-decodeaudiodata // and http://stackoverflow.com/q/10365335/103396 function errorCallback(error) { if (!error) { error = new DOMException("EncodingError"); } callback(error); } return audio_context.decodeAudioData( raw_response, getAudioDecoder(options, callback), errorCallback ); }
javascript
{ "resource": "" }
q45013
ADD_LOCALE
train
function ADD_LOCALE(state, payload) { // reduce the given translations to a single-depth tree var translations = flattenTranslations(payload.translations); if (state.translations.hasOwnProperty(payload.locale)) { // get the existing translations var existingTranslations = state.translations[payload.locale]; // merge the translations state.translations[payload.locale] = Object.assign({}, existingTranslations, translations); } else { // just set the locale if it does not yet exist state.translations[payload.locale] = translations; } // make sure to notify vue of changes (this might break with new vue versions) try { if (state.translations.__ob__) { state.translations.__ob__.dep.notify(); } } catch (ex) {} }
javascript
{ "resource": "" }
q45014
REPLACE_LOCALE
train
function REPLACE_LOCALE(state, payload) { // reduce the given translations to a single-depth tree var translations = flattenTranslations(payload.translations); // replace the translations entirely state.translations[payload.locale] = translations; // make sure to notify vue of changes (this might break with new vue versions) try { if (state.translations.__ob__) { state.translations.__ob__.dep.notify(); } } catch (ex) {} }
javascript
{ "resource": "" }
q45015
REMOVE_LOCALE
train
function REMOVE_LOCALE(state, payload) { // check if the given locale is present in the state if (state.translations.hasOwnProperty(payload.locale)) { // check if the current locale is the given locale to remvoe if (state.locale === payload.locale) { // reset the current locale state.locale = null; } // create a copy of the translations object var translationCopy = Object.assign({}, state.translations); // remove the given locale delete translationCopy[payload.locale]; // set the state to the new object state.translations = translationCopy; } }
javascript
{ "resource": "" }
q45016
addLocale
train
function addLocale(context, payload) { context.commit({ type: 'ADD_LOCALE', locale: payload.locale, translations: payload.translations }); }
javascript
{ "resource": "" }
q45017
replaceLocale
train
function replaceLocale(context, payload) { context.commit({ type: 'REPLACE_LOCALE', locale: payload.locale, translations: payload.translations }); }
javascript
{ "resource": "" }
q45018
removeLocale
train
function removeLocale(context, payload) { context.commit({ type: 'REMOVE_LOCALE', locale: payload.locale, translations: payload.translations }); }
javascript
{ "resource": "" }
q45019
flattenTranslations
train
function flattenTranslations(translations) { var toReturn = {}; for (var i in translations) { // check if the property is present if (!translations.hasOwnProperty(i)) { continue; } // get the type of the property var objType = _typeof(translations[i]); // allow unflattened array of strings if (isArray(translations[i])) { var count = translations[i].length; for (var index = 0; index < count; index++) { var itemType = _typeof(translations[i][index]); if (itemType !== 'string') { console.warn('i18n:', 'currently only arrays of strings are fully supported', translations[i]); break; } } toReturn[i] = translations[i]; } else if (objType == 'object' && objType !== null) { var flatObject = flattenTranslations(translations[i]); for (var x in flatObject) { if (!flatObject.hasOwnProperty(x)) continue; toReturn[i + '.' + x] = flatObject[x]; } } else { toReturn[i] = translations[i]; } } return toReturn; }
javascript
{ "resource": "" }
q45020
$t
train
function $t() { // get the current language from the store var locale = store.state[moduleName].locale; return translateInLanguage.apply(void 0, [locale].concat(Array.prototype.slice.call(arguments))); }
javascript
{ "resource": "" }
q45021
checkKeyExists
train
function checkKeyExists(key) { var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'fallback'; // get the current language from the store var locale = store.state[moduleName].locale; var fallback = store.state[moduleName].fallback; var translations = store.state[moduleName].translations; // check the current translation if (translations.hasOwnProperty(locale) && translations[locale].hasOwnProperty(key)) { return true; } if (scope == 'strict') { return false; } // check any localized translations var localeRegional = locale.split('-'); if (localeRegional.length > 1 && translations.hasOwnProperty(localeRegional[0]) && translations[localeRegional[0]].hasOwnProperty(key)) { return true; } if (scope == 'locale') { return false; } // check if a fallback locale exists if (translations.hasOwnProperty(fallback) && translations[fallback].hasOwnProperty(key)) { return true; } // key does not exist in the store return false; }
javascript
{ "resource": "" }
q45022
replaceLocale
train
function replaceLocale(locale, translations) { return store.dispatch({ type: "".concat(moduleName, "/replaceLocale"), locale: locale, translations: translations }); }
javascript
{ "resource": "" }
q45023
removeLocale
train
function removeLocale(locale) { if (store.state[moduleName].translations.hasOwnProperty(locale)) { store.dispatch({ type: "".concat(moduleName, "/removeLocale"), locale: locale }); } }
javascript
{ "resource": "" }
q45024
replace
train
function replace(translation, replacements) { // check if the object has a replace property if (!translation.replace) { return translation; } return translation.replace(matcher, function (placeholder) { // remove the identifiers (can be set on the module level) var key = placeholder.replace(identifiers[0], '').replace(identifiers[1], ''); if (replacements[key] !== undefined) { return replacements[key]; } // warn user that the placeholder has not been found if (warnings) { console.group ? console.group('i18n: Not all placeholders found') : console.warn('i18n: Not all placeholders found'); console.warn('Text:', translation); console.warn('Placeholder:', placeholder); if (console.groupEnd) { console.groupEnd(); } } // return the original placeholder return placeholder; }); }
javascript
{ "resource": "" }
q45025
render
train
function render(locale, translation) { var replacements = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var pluralization = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; // get the type of the property var objType = _typeof(translation); var pluralizationType = _typeof(pluralization); var resolvePlaceholders = function resolvePlaceholders() { if (isArray$1(translation)) { // replace the placeholder elements in all sub-items return translation.map(function (item) { return replace(item, replacements, false); }); } else if (objType === 'string') { return replace(translation, replacements, true); } }; // return translation item directly if (pluralization === null) { return resolvePlaceholders(); } // check if pluralization value is countable if (pluralizationType !== 'number') { if (warnings) console.warn('i18n: pluralization is not a number'); return resolvePlaceholders(); } // --- handle pluralizations --- // replace all placeholders var resolvedTranslation = resolvePlaceholders(); // initialize pluralizations var pluralizations = null; // if translations are already an array and have more than one entry, // we will not perform a split operation on ::: if (isArray$1(resolvedTranslation) && resolvedTranslation.length > 0) { pluralizations = resolvedTranslation; } else { // split translation strings by ::: to find create the pluralization array pluralizations = resolvedTranslation.split(':::'); } // determine the pluralization version to use by locale var index = plurals.getTranslationIndex(locale, pluralization); // check if the specified index is present in the pluralization if (typeof pluralizations[index] === 'undefined') { if (warnings) { console.warn('i18n: pluralization not provided in locale', translation, locale, index); } // return the first element of the pluralization by default return pluralizations[0].trim(); } // return the requested item from the pluralizations return pluralizations[index].trim(); }
javascript
{ "resource": "" }
q45026
findInheritedProperties
train
function findInheritedProperties(ci, properties) { while (ci && ci.extends) { ci = findTypeMetaInfo(ci.extends); if (!ci) { console.warn('no meta info for: ' + ci.extends); continue; } mergeProperties(ci).forEach(p => { if (properties.find(pp => pp.name === p.name)) { return; } if (p.inheritance) { return; } // deep copy p = JSON.parse(JSON.stringify(p)); delete p.inheritance; p.inheritInfo = {from: ci.name, type: ci.type || ci.subtype}; properties.push(p); }); } }
javascript
{ "resource": "" }
q45027
findInheritedMethods
train
function findInheritedMethods(ci, methods) { while (ci && ci.extends) { ci = findTypeMetaInfo(ci.extends); if (!ci) { console.warn('no meta info for: ' + ci.extends); continue; } (ci.methodsClass || ci.methods).forEach(m => { if (methods.find(mm => mm.name === m.name && getArgumentsString(mm) == getArgumentsString(m))) { return; } if (m.inheritance || isAngularLifeCircle(m.name)) { return; } // deep copy m = JSON.parse(JSON.stringify(m)); delete m.inheritance; m.inheritInfo = {from: ci.name, type: ci.type || ci.subtype}; methods.push(m); }); } }
javascript
{ "resource": "" }
q45028
multipleFilterFn
train
function multipleFilterFn () { return this.choices.choices .filter((choice) => choice.checked) .map((choice) => choice.key) }
javascript
{ "resource": "" }
q45029
train
function(msg, levelMsg) { if (console.isTimestamped()) { return "[" + levelMsg + " - " + new Date().toJSON() + "] " + msg; } else { return "[" + levelMsg + "] " + msg; } }
javascript
{ "resource": "" }
q45030
train
function(d, val) { val = val > 86399 ? 0 : val; var next = later.date.next( later.Y.val(d), later.M.val(d), later.D.val(d) + (val <= later.t.val(d) ? 1 : 0), 0, 0, val); // correct for passing over a daylight savings boundry if(!later.date.isUTC && next.getTime() < d.getTime()) { next = later.date.next( later.Y.val(next), later.M.val(next), later.D.val(next), later.h.val(next), later.m.val(next), val + 7200); } return next; }
javascript
{ "resource": "" }
q45031
train
function(d) { if (d.wy) return d.wy; // move to the Thursday in the target week and find Thurs of target year var wThur = later.dw.next(later.wy.start(d), 5), YThur = later.dw.next(later.Y.prev(wThur, later.Y.val(wThur)-1), 5); // caculate the difference between the two dates in weeks return (d.wy = 1 + Math.ceil((wThur.getTime() - YThur.getTime()) / later.WEEK)); }
javascript
{ "resource": "" }
q45032
train
function(d) { if (d.wyExtent) return d.wyExtent; // go to start of ISO week to get to the right year var year = later.dw.next(later.wy.start(d), 5), dwFirst = later.dw.val(later.Y.start(year)), dwLast = later.dw.val(later.Y.end(year)); return (d.wyExtent = [1, dwFirst === 5 || dwLast === 5 ? 53 : 52]); }
javascript
{ "resource": "" }
q45033
train
function(d, val) { var wyThur = later.dw.next(later.wy.start(d), 5), year = later.date.prevRollover(wyThur, val, later.wy, later.Y); // handle case where 1st of year is last week of previous month if(later.wy.val(year) !== 1) { year = later.dw.next(year, 2); } var wyMax = later.wy.extent(year)[1], wyEnd = later.wy.end(year); val = val > wyMax ? wyMax : val || wyMax; return later.wy.end(later.date.next( later.Y.val(wyEnd), later.M.val(wyEnd), later.D.val(wyEnd) + 7 * (val-1) )); }
javascript
{ "resource": "" }
q45034
train
function(d) { return d.dc || (d.dc = Math.floor((later.D.val(d)-1)/7)+1); }
javascript
{ "resource": "" }
q45035
train
function(d) { return d.dcExtent || (d.dcExtent = [1, Math.ceil(later.D.extent(d)[1] /7)]); }
javascript
{ "resource": "" }
q45036
train
function(d) { return d.dcStart || (d.dcStart = later.date.next( later.Y.val(d), later.M.val(d), Math.max(1, ((later.dc.val(d) - 1) * 7) + 1 || 1))); }
javascript
{ "resource": "" }
q45037
train
function(d) { return d.dcEnd || (d.dcEnd = later.date.prev( later.Y.val(d), later.M.val(d), Math.min(later.dc.val(d) * 7, later.D.extent(d)[1]))); }
javascript
{ "resource": "" }
q45038
train
function(d, val) { val = val > later.dc.extent(d)[1] ? 1 : val; var month = later.date.nextRollover(d, val, later.dc, later.M), dcMax = later.dc.extent(month)[1]; val = val > dcMax ? 1 : val; var next = later.date.next( later.Y.val(month), later.M.val(month), val === 0 ? later.D.extent(month)[1] - 6 : 1 + (7 * (val - 1)) ); if(next.getTime() <= d.getTime()) { month = later.M.next(d, later.M.val(d)+1); return later.date.next( later.Y.val(month), later.M.val(month), val === 0 ? later.D.extent(month)[1] - 6 : 1 + (7 * (val - 1)) ); } return next; }
javascript
{ "resource": "" }
q45039
train
function(d, val) { var month = later.date.prevRollover(d, val, later.dc, later.M), dcMax = later.dc.extent(month)[1]; val = val > dcMax ? dcMax : val || dcMax; return later.dc.end(later.date.prev( later.Y.val(month), later.M.val(month), 1 + (7 * (val - 1)) )); }
javascript
{ "resource": "" }
q45040
train
function(d) { return d.wm || (d.wm = (later.D.val(d) + (later.dw.val(later.M.start(d)) - 1) + (7 - later.dw.val(d))) / 7); }
javascript
{ "resource": "" }
q45041
train
function(d) { return d.wmExtent || (d.wmExtent = [1, (later.D.extent(d)[1] + (later.dw.val(later.M.start(d)) - 1) + (7 - later.dw.val(later.M.end(d)))) / 7]); }
javascript
{ "resource": "" }
q45042
train
function(d) { return d.wmStart || (d.wmStart = later.date.next( later.Y.val(d), later.M.val(d), Math.max(later.D.val(d) - later.dw.val(d) + 1, 1))); }
javascript
{ "resource": "" }
q45043
train
function(d) { return d.wmEnd || (d.wmEnd = later.date.prev( later.Y.val(d), later.M.val(d), Math.min(later.D.val(d) + (7 - later.dw.val(d)), later.D.extent(d)[1]))); }
javascript
{ "resource": "" }
q45044
train
function(d, val) { val = val > later.wm.extent(d)[1] ? 1 : val; var month = later.date.nextRollover(d, val, later.wm, later.M), wmMax = later.wm.extent(month)[1]; val = val > wmMax ? 1 : val || wmMax; // jump to the Sunday of the desired week, set to 1st of month for week 1 return later.date.next( later.Y.val(month), later.M.val(month), Math.max(1, (val-1) * 7 - (later.dw.val(month)-2))); }
javascript
{ "resource": "" }
q45045
train
function (id, vals) { var custom = later.modifier[id]; if(!custom) throw new Error('Custom modifier ' + id + ' not recognized!'); modifier = id; values = arguments[1] instanceof Array ? arguments[1] : [arguments[1]]; return this; }
javascript
{ "resource": "" }
q45046
train
function (id) { var custom = later[id]; if(!custom) throw new Error('Custom time period ' + id + ' not recognized!'); add(id, custom.extent(new Date())[0], custom.extent(new Date())[1]); return this; }
javascript
{ "resource": "" }
q45047
train
function(d) { return d.s || (d.s = later.date.getSec.call(d)); }
javascript
{ "resource": "" }
q45048
train
function(d) { var year = later.Y.val(d); // shortcut on finding leap years since this function gets called a lot // works between 1901 and 2099 return d.dyExtent || (d.dyExtent = [1, year % 4 ? 365 : 366]); }
javascript
{ "resource": "" }
q45049
train
function(d, val) { var m = later.m.val(d), s = later.s.val(d), inc = val > 59 ? 60-m : (val <= m ? (60-m) + val : val-m), next = new Date(d.getTime() + (inc * later.MIN) - (s * later.SEC)); // correct for passing over a daylight savings boundry if(!later.date.isUTC && next.getTime() <= d.getTime()) { next = new Date(d.getTime() + ((inc + 120) * later.MIN) - (s * later.SEC)); } return next; }
javascript
{ "resource": "" }
q45050
calcEnd
train
function calcEnd(dir, schedArr, startsArr, startDate, maxEndDate) { var compare = compareFn(dir), result; for(var i = 0, len = schedArr.length; i < len; i++) { var start = startsArr[i]; if(start && start.getTime() === startDate.getTime()) { var end = schedArr[i].end(dir, start); // if the end date is past the maxEndDate, just return the maxEndDate if(maxEndDate && (!end || compare(end, maxEndDate))) { return maxEndDate; } // otherwise, return the maximum end date that was calculated if(!result || compare(end, result)) { result = end; } } } return result; }
javascript
{ "resource": "" }
q45051
cloneSchedule
train
function cloneSchedule(sched) { var clone = {}, field; for(field in sched) { if (field !== 'dc' && field !== 'd') { clone[field] = sched[field].slice(0); } } return clone; }
javascript
{ "resource": "" }
q45052
parse
train
function parse(item, s, name, min, max, offset) { var value, split, schedules = s.schedules, curSched = schedules[schedules.length-1]; // L just means min - 1 (this also makes it work for any field) if (item === 'L') { item = min - 1; } // parse x if ((value = getValue(item, offset, max)) !== null) { add(curSched, name, value, value); } // parse xW else if ((value = getValue(item.replace('W', ''), offset, max)) !== null) { addWeekday(s, curSched, value); } // parse xL else if ((value = getValue(item.replace('L', ''), offset, max)) !== null) { addHash(schedules, curSched, value, min-1); } // parse x#y else if ((split = item.split('#')).length === 2) { value = getValue(split[0], offset, max); addHash(schedules, curSched, value, getValue(split[1])); } // parse x-y or x-y/z or */z or 0/z else { addRange(item, curSched, name, min, max, offset); } }
javascript
{ "resource": "" }
q45053
extend
train
function extend(src, props) { props = props || {}; var p; for (p in src) { if (src.hasOwnProperty(p)) { if (!props.hasOwnProperty(p)) { props[p] = src[p]; } } } return props; }
javascript
{ "resource": "" }
q45054
createElement
train
function createElement(name, props) { var c = document, d = c.createElement(name); if (props && "[object Object]" === Object.prototype.toString.call(props)) { var e; for (e in props) if ("html" === e) d.innerHTML = props[e]; else if ("text" === e) { var f = c.createTextNode(props[e]); d.appendChild(f); } else d.setAttribute(e, props[e]); } return d; }
javascript
{ "resource": "" }
q45055
style
train
function style(el, obj) { if ( !obj ) { return window.getComputedStyle(el); } if ("[object Object]" === Object.prototype.toString.call(obj)) { var s = ""; each(obj, function(prop, val) { if ( typeof val !== "string" && prop !== "opacity" ) { val += "px"; } s += prop + ": " + val + ";"; }); el.style.cssText += s; } }
javascript
{ "resource": "" }
q45056
rect
train
function rect(t, e) { var o = window, r = t.getBoundingClientRect(), x = o.pageXOffset, y = o.pageYOffset, m = {}, f = "none"; if (e) { var s = style(t); m = { top: parseInt(s["margin-top"], 10), left: parseInt(s["margin-left"], 10), right: parseInt(s["margin-right"], 10), bottom: parseInt(s["margin-bottom"], 10) }; f = s.float; } return { w: r.width, h: r.height, x1: r.left + x, x2: r.right + x, y1: r.top + y, y2: r.bottom + y, margin: m, float: f }; }
javascript
{ "resource": "" }
q45057
getScrollBarWidth
train
function getScrollBarWidth() { var width = 0, div = createElement("div", { class: "scrollbar-measure" }); style(div, { width: 100, height: 100, overflow: "scroll", position: "absolute", top: -9999 }); document.body.appendChild(div); width = div.offsetWidth - div.clientWidth; document.body.removeChild(div); return width; }
javascript
{ "resource": "" }
q45058
createExchangeErrorHandlerFor
train
function createExchangeErrorHandlerFor (exchange) { return function (err) { if (!exchange.options.confirm) return; // should requeue instead? // https://www.rabbitmq.com/reliability.html#producer debug && debug('Exchange error handler triggered, erroring and wiping all unacked publishes'); for (var id in exchange._unAcked) { var task = exchange._unAcked[id]; task.emit('ack error', err); delete exchange._unAcked[id]; } }; }
javascript
{ "resource": "" }
q45059
parseInt
train
function parseInt (buffer, size) { switch (size) { case 1: return buffer[buffer.read++]; case 2: return (buffer[buffer.read++] << 8) + buffer[buffer.read++]; case 4: return (buffer[buffer.read++] << 24) + (buffer[buffer.read++] << 16) + (buffer[buffer.read++] << 8) + buffer[buffer.read++]; case 8: return (buffer[buffer.read++] << 56) + (buffer[buffer.read++] << 48) + (buffer[buffer.read++] << 40) + (buffer[buffer.read++] << 32) + (buffer[buffer.read++] << 24) + (buffer[buffer.read++] << 16) + (buffer[buffer.read++] << 8) + buffer[buffer.read++]; default: throw new Error("cannot parse ints of that size"); } }
javascript
{ "resource": "" }
q45060
registerable
train
function registerable (cfgObj) { _.forIn(cfgObj, function (value, key) { if (registerableCfg.indexOf(key) !== -1) { register(key, cfgObj) } }) }
javascript
{ "resource": "" }
q45061
parse
train
function parse(str, options) { if (typeof str !== 'string') { throw new TypeError('argument str must be a string'); } var obj = {} var opt = options || {}; var pairs = str.split(pairSplitRegExp); var dec = opt.decode || decode; for (var i = 0; i < pairs.length; i++) { var pair = pairs[i]; var eq_idx = pair.indexOf('='); // skip things that don't look like key=value if (eq_idx < 0) { continue; } var key = pair.substr(0, eq_idx).trim() var val = pair.substr(++eq_idx, pair.length).trim(); // quoted values if ('"' == val[0]) { val = val.slice(1, -1); } // only assign once if (undefined == obj[key]) { obj[key] = tryDecode(val, dec); } } return obj; }
javascript
{ "resource": "" }
q45062
findByNodeName
train
function findByNodeName(el, nodeName) { if (!el.prop) { // not a jQuery or jqLite object -> wrap it el = angular.element(el) } if (el.prop('nodeName') === nodeName.toUpperCase()) { return el } const c = el.children() for (let i = 0; c && i < c.length; i++) { const node = findByNodeName(c[i], nodeName) if (node) { return node } } }
javascript
{ "resource": "" }
q45063
write
train
function write(rows, geometry_type, geometries, callback) { var TYPE = types.geometries[geometry_type], writer = writers[TYPE], parts = writer.parts(geometries, TYPE), shpLength = 100 + (parts - geometries.length) * 4 + writer.shpLength(geometries), shxLength = 100 + writer.shxLength(geometries), shpBuffer = new ArrayBuffer(shpLength), shpView = new DataView(shpBuffer), shxBuffer = new ArrayBuffer(shxLength), shxView = new DataView(shxBuffer), extent = writer.extent(geometries); writeHeader(shpView, TYPE); writeHeader(shxView, TYPE); writeExtent(extent, shpView); writeExtent(extent, shxView); writer.write(geometries, extent, new DataView(shpBuffer, 100), new DataView(shxBuffer, 100), TYPE); shpView.setInt32(24, shpLength / 2); shxView.setInt32(24, (50 + geometries.length * 4)); var dbfBuf = dbf.structure(rows); callback(null, { shp: shpView, shx: shxView, dbf: dbfBuf, prj: prj }); }
javascript
{ "resource": "" }
q45064
train
function(otherUserId, callback){ // if there is only one other user or the other user is the same user if (otherUserIdsWhoRated.length === 1 || userId === otherUserId){ // then call the callback and exciting the similarity check callback(); } // if the userid is not the same as the user if (userId !== otherUserId){ // calculate the jaccard coefficient for similarity. it will return a value between -1 and 1 showing the two users // similarity jaccardCoefficient(userId, otherUserId, function(result) { // with the returned similarity score, add it to a sorted set named above client.zadd(similarityZSet, result, otherUserId, function(err){ // call the async callback function once finished to indicate that the process is finished callback(); }); }); } }
javascript
{ "resource": "" }
q45065
train
function(err){ client.del(recommendedZSet, function(err){ async.each(scoreMap, function(scorePair, callback){ client.zadd(recommendedZSet, scorePair[0], scorePair[1], function(err){ callback(); }); }, // after all the additions have been made to the recommended set, function(err){ client.del(tempAllLikedSet, function(err){ client.zcard(recommendedZSet, function(err, length){ client.zremrangebyrank(recommendedZSet, 0, length-config.numOfRecsStore-1, function(err){ cb(); }); }); }); } ); }); }
javascript
{ "resource": "" }
q45066
findReplace
train
function findReplace (array, testFn) { const found = []; const replaceWiths = arrayify$1(arguments); replaceWiths.splice(0, 2); arrayify$1(array).forEach((value, index) => { let expanded = []; replaceWiths.forEach(replaceWith => { if (typeof replaceWith === 'function') { expanded = expanded.concat(replaceWith(value)); } else { expanded.push(replaceWith); } }); if (testFn(value)) { found.push({ index: index, replaceWithValue: expanded }); } }); found.reverse().forEach(item => { const spliceArgs = [ item.index, 1 ].concat(item.replaceWithValue); array.splice.apply(array, spliceArgs); }); return array }
javascript
{ "resource": "" }
q45067
isClass
train
function isClass (input) { if (isFunction(input)) { return /^class /.test(Function.prototype.toString.call(input)) } else { return false } }
javascript
{ "resource": "" }
q45068
isPromise
train
function isPromise (input) { if (input) { const isPromise = isDefined(Promise) && input instanceof Promise; const isThenable = input.then && typeof input.then === 'function'; return !!(isPromise || isThenable) } else { return false } }
javascript
{ "resource": "" }
q45069
warnIfNotLocal
train
function warnIfNotLocal() { if (config.esclient.hosts.some((env) => { return env.host !== 'localhost'; } )) { console.log(colors.red(`WARNING: DROPPING SCHEMA NOT ON LOCALHOST: ${config.esclient.hosts[0].host}`)); } }
javascript
{ "resource": "" }
q45070
makeAction
train
function makeAction (controller, method, opts) { let action = {action: controller + '@' + method}; return extend (action, opts); }
javascript
{ "resource": "" }
q45071
registerParticipant
train
function registerParticipant (name, participant) { let barrier = barriers[name]; if (!barrier) { debug (`creating barrier ${name}`); barrier = barriers[name] = new Barrier ({name}); } debug (`registering participant with barrier ${name}`); return barrier.registerParticipant (participant); }
javascript
{ "resource": "" }
q45072
getResponseHeaders
train
function getResponseHeaders(xhr) { let raw = xhr.getAllResponseHeaders(); let parts = raw.replace(/\s+$/, '').split(/\n/); for (let i = 0; i < parts.length; i++) { parts[i] = parts[i].replace(/\r/g, '').replace(/^\s+/, '').replace(/\s+$/, ''); } return parts; }
javascript
{ "resource": "" }
q45073
queryUserInfo
train
function queryUserInfo(parentSpan, username, callback) { // Aggregated user information across multiple API calls var user = { login : null, type : null, repoNames : [], recentEvents : 0, eventCounts : {}, }; // Call the callback only when all three API requests finish or on the // first error. var remainingCalls = 3; var next = function (err) { // Early terminate on any error remainingCalls -= err ? Math.max(remainingCalls, 1) : 1; if (remainingCalls === 0) { callback(err, err ? null : user); } }; // First query the user info for the given username httpGet(parentSpan, 'http://api.github.com/users/' + username, function (err, json) { if (err) { return next(err); } user.login = json.login; user.type = json.type; // Use the user info to query names of all the user's public repositories httpGet(parentSpan, json.repos_url, function (err, json) { if (err) { return next(err); } for (var i = 0; i < json.length; i++) { user.repoNames.push(json[i].name); } next(null); }); // In parallel, query the recent events activity for the user httpGet(parentSpan, json.received_events_url, function (err, json) { if (err) { return next(err); } user.recentEvents = json.length; for (var i = 0; i < json.length; i++) { var eventType = json[i].type; user.eventCounts[eventType] = user.eventCounts[eventType] || 0; user.eventCounts[eventType]++; } next(null); }); next(null); }); }
javascript
{ "resource": "" }
q45074
httpGet
train
function httpGet(parentSpan, urlString, callback) { var span = opentracing.globalTracer().startSpan('http.get', { childOf : parentSpan }); var callbackWrapper = function (err, data) { span.finish(); callback(err, data); }; try { var carrier = {}; opentracing.globalTracer().inject(span, opentracing.FORMAT_TEXT_MAP, carrier); var dest = url.parse(urlString); var options = { host : PROXY_HOST, path : dest.path, port : PROXY_PORT, headers: { // User-Agent is required by the GitHub APIs 'User-Agent': 'LightStep Example', } }; for (var key in carrier) { options.headers[key] = carrier[key]; } // Create a span representing the https request span.setTag('url', urlString); span.log({ event : 'options', 'options': options, }); return http.get(options, function(response) { var bodyBuffer = ''; response.on('data', function(chunk) { bodyBuffer += chunk; }); response.on('end', function() { span.log({ body : bodyBuffer, length : bodyBuffer.length, }); var parsedJSON, err; try { parsedJSON = JSON.parse(bodyBuffer); } catch (exception) { err = { buffer : bodyBuffer, exception : exception, }; span.setTag('error', true); span.log({ event : 'error', 'error.object': err, }); } callbackWrapper(err, parsedJSON); }); }); } catch (exception) { span.setTag('error', true); span.log({ event : 'error', 'error.object': exception, }); callbackWrapper(exception, null); } }
javascript
{ "resource": "" }
q45075
filterInPlace
train
function filterInPlace (arr, pred) { var idx = 0; for (var ii = 0; ii < arr.length; ++ii) { if (pred(arr[ii])) { arr[idx] = arr[ii]; ++idx; } } arr.length = idx; }
javascript
{ "resource": "" }
q45076
normalizeList
train
function normalizeList(dom) { for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) { let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null if (name && listTags.hasOwnProperty(name) && prevItem) { prevItem.appendChild(child) child = prevItem } else if (name == "li") { prevItem = child } else if (name) { prevItem = null } } }
javascript
{ "resource": "" }
q45077
matches
train
function matches(dom, selector) { return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector) }
javascript
{ "resource": "" }
q45078
nullFrom
train
function nullFrom(nfa, node) { let result = [] scan(node) return result.sort(cmp) function scan(node) { let edges = nfa[node] if (edges.length == 1 && !edges[0].term) return scan(edges[0].to) result.push(node) for (let i = 0; i < edges.length; i++) { let {term, to} = edges[i] if (!term && result.indexOf(to) == -1) scan(to) } } }
javascript
{ "resource": "" }
q45079
connect
train
function connect(orbs, callback) { var total = Object.keys(orbs).length, finished = 0; function done() { finished++; if (finished >= total) { callback(); } } for (var name in orbs) { orbs[name].connect(done); } }
javascript
{ "resource": "" }
q45080
start
train
function start(name) { var orb = spheros[name], contacts = 0, age = 0, alive = false; orb.detectCollisions(); born(); orb.on("collision", function() { contacts += 1; }); setInterval(function() { if (alive) { move(); } }, 3000); setInterval(birthday, 10000); // roll Sphero in a random direction function move() { orb.roll(60, Math.floor(Math.random() * 360)); } // stop Sphero function stop() { orb.stop(); } // set Sphero's color function color(str) { orb.color(str); } function born() { contacts = 0; age = 0; life(); move(); } function life() { alive = true; color("green"); } function death() { alive = false; color("red"); stop(); } function enoughContacts() { return contacts >= 2 && contacts < 7; } function birthday() { age += 1; if (alive) { console.log("Happy birthday,", name); console.log("You are", age, "and had", contacts, "contacts."); } if (enoughContacts()) { if (!alive) { born(); } } else { death(); } } }
javascript
{ "resource": "" }
q45081
calculateLuminance
train
function calculateLuminance(hex, lum) { return Math.round(Math.min(Math.max(0, hex + (hex * lum)), 255)); }
javascript
{ "resource": "" }
q45082
adjustLuminance
train
function adjustLuminance(rgb, lum) { var newRgb = {}; newRgb.red = calculateLuminance(rgb.red, lum); newRgb.green = calculateLuminance(rgb.green, lum); newRgb.blue = calculateLuminance(rgb.blue, lum); return newRgb; }
javascript
{ "resource": "" }
q45083
warn
train
function warn( message ) { if ( message in warn.cache ) { return; } const prefix = chalk.hex('#CC4A8B')('WARNING:'); console.warn(chalk`${prefix} ${message}`); }
javascript
{ "resource": "" }
q45084
filterHashes
train
function filterHashes( hashes ) { const validHashes = crypto.getHashes(); return hashes.filter( hash => { if ( validHashes.includes(hash) ) { return true; } warn(chalk`{blueBright ${hash}} is not a supported hash algorithm`); return false; }); }
javascript
{ "resource": "" }
q45085
varType
train
function varType( v ) { const [ , type ] = Object.prototype.toString.call( v ).match(/\[object\s(\w+)\]/); return type; }
javascript
{ "resource": "" }
q45086
getSortedObject
train
function getSortedObject(object, compareFunction) { const keys = Object.keys(object); keys.sort( compareFunction ); return keys.reduce( (sorted, key) => (sorted[ key ] = object[ key ], sorted), Object.create(null) ); }
javascript
{ "resource": "" }
q45087
createTag
train
function createTag(tagName, attrMap, publicPath) { publicPath = publicPath || ''; // add trailing slash if we have a publicPath and it doesn't have one. if (publicPath && !RE_ENDS_WITH_BS.test(publicPath)) { publicPath += '/'; } const attributes = Object.getOwnPropertyNames(attrMap) .filter(function(name) { return name[0] !== '='; } ) .map(function(name) { var value = attrMap[name]; if (publicPath) { // check if we have explicit instruction, use it if so (e.g: =herf: false) // if no instruction, use public path if it's href attribute. const usePublicPath = attrMap.hasOwnProperty('=' + name) ? !!attrMap['=' + name] : name === 'href'; if (usePublicPath) { // remove a starting trailing slash if the value has one so we wont have // value = publicPath + (value[0] === '/' ? value.substr(1) : value); } } return `${name}="${value}"`; }); const closingTag = tagName === 'script' ? '</script>' : ''; return `<${tagName} ${attributes.join(' ')}>${closingTag}`; }
javascript
{ "resource": "" }
q45088
getHtmlElementString
train
function getHtmlElementString(dataSource, publicPath) { return Object.getOwnPropertyNames(dataSource) .map(function(name) { if (Array.isArray(dataSource[name])) { return dataSource[name].map(function(attrs) { return createTag(name, attrs, publicPath); } ); } else { return [ createTag(name, dataSource[name], publicPath) ]; } }) .reduce(function(arr, curr) { return arr.concat(curr); }, []) .join('\n\t'); }
javascript
{ "resource": "" }
q45089
copyToDemo
train
function copyToDemo(srcArr) { return gulp.src(srcArr) .pipe(gulp.dest(function (file) { return demoDist + file.base.slice(__dirname.length); // save directly to demo })); }
javascript
{ "resource": "" }
q45090
copyToDist
train
function copyToDist(srcArr) { return gulp.src(srcArr.concat(globalExcludes)) .pipe(gulp.dest(function (file) { return libraryDist + file.base.slice(__dirname.length); // save directly to dist })); }
javascript
{ "resource": "" }
q45091
transpileMinifyLESS
train
function transpileMinifyLESS(src) { return gulp.src(src) .pipe(sourcemaps.init()) .pipe(lessCompiler({ paths: [ path.join(__dirname, 'less', 'includes') ] })) .pipe(cssmin().on('error', function(err) { console.log(err); })) .pipe(rename({suffix: '.min'})) .pipe(sourcemaps.write()) .pipe(gulp.dest(function (file) { return __dirname + file.base.slice(__dirname.length); })); }
javascript
{ "resource": "" }
q45092
inlineTemplate
train
function inlineTemplate() { return gulp.src(['./src/app/**/*.ts'].concat(globalExcludes), {base: './'}) .pipe(replace(/templateUrl.*\'/g, function (matched) { var fileName = matched.match(/\/.*html/g).toString(); var dirName = this.file.relative.substring(0, this.file.relative.lastIndexOf('/')); var fileContent = fs.readFileSync(dirName + fileName, "utf8"); return 'template: \`' + minifyTemplate(fileContent) + '\`'; })) .pipe(gulp.dest(libraryBuild)); }
javascript
{ "resource": "" }
q45093
transpileAot
train
function transpileAot() { // https://stackoverflow.com/questions/36897877/gulp-error-the-following-tasks-did-not-complete-did-you-forget-to-signal-async return new Promise(function(resolve, reject) { // Need to capture the exit code exec('node_modules/.bin/ngc -p tsconfig-aot.json', function (err, stdout, stderr) { console.log(stdout); console.log(stderr); if (err !== null) { process.exit(1); } }); resolve(); }); }
javascript
{ "resource": "" }
q45094
updateWatchDist
train
function updateWatchDist() { return gulp .src([libraryDist + '/**'].concat(globalExcludes)) .pipe(changed(watchDist)) .pipe(gulp.dest(watchDist)); }
javascript
{ "resource": "" }
q45095
checkBinaryReady
train
function checkBinaryReady(uuid) { if (!(uuid in api._blobs && uuid in api._binaryMessages)) { return; } log('receive full binary message', uuid); var blob = api._blobs[uuid]; var msg = api._binaryMessages[uuid]; delete api._blobs[uuid]; delete api._binaryMessages[uuid]; var blobToDeliver; if (isBrowser) { blobToDeliver = blobUtil.createBlob([blob], {type: msg.contentType}); } else { blobToDeliver = blob; blob.type = msg.contentType; // non-standard, but we do it for the tests } msg.cb(null, blobToDeliver); }
javascript
{ "resource": "" }
q45096
train
function(){ if (controller.connection.opts.requestProtocolVersion < 5 && controller.streamingCount == 0){ controller.streamingCount = 1; var info = { attached: true, streaming: true, type: 'unknown', id: "Lx00000000000" }; controller.devices[info.id] = info; controller.emit('deviceAttached', info); controller.emit('deviceStreaming', info); controller.emit('streamingStarted', info); controller.connection.removeListener('frame', backfillStreamingStartedEventsHandler) } }
javascript
{ "resource": "" }
q45097
train
function(data) { /** * The center point of the circle within the Leap frame of reference. * * @member center * @memberof Leap.CircleGesture.prototype * @type {number[]} */ this.center = data.center; /** * The normal vector for the circle being traced. * * If you draw the circle clockwise, the normal vector points in the same * general direction as the pointable object drawing the circle. If you draw * the circle counterclockwise, the normal points back toward the * pointable. If the angle between the normal and the pointable object * drawing the circle is less than 90 degrees, then the circle is clockwise. * * ```javascript * var clockwiseness; * if (circle.pointable.direction.angleTo(circle.normal) <= PI/4) { * clockwiseness = "clockwise"; * } * else * { * clockwiseness = "counterclockwise"; * } * ``` * * @member normal * @memberof Leap.CircleGesture.prototype * @type {number[]} */ this.normal = data.normal; /** * The number of times the finger tip has traversed the circle. * * Progress is reported as a positive number of the number. For example, * a progress value of .5 indicates that the finger has gone halfway * around, while a value of 3 indicates that the finger has gone around * the the circle three times. * * Progress starts where the circle gesture began. Since the circle * must be partially formed before the Leap can recognize it, progress * will be greater than zero when a circle gesture first appears in the * frame. * * @member progress * @memberof Leap.CircleGesture.prototype * @type {number} */ this.progress = data.progress; /** * The radius of the circle in mm. * * @member radius * @memberof Leap.CircleGesture.prototype * @type {number} */ this.radius = data.radius; }
javascript
{ "resource": "" }
q45098
train
function(data) { /** * The starting position within the Leap frame of * reference, in mm. * * @member startPosition * @memberof Leap.SwipeGesture.prototype * @type {number[]} */ this.startPosition = data.startPosition; /** * The current swipe position within the Leap frame of * reference, in mm. * * @member position * @memberof Leap.SwipeGesture.prototype * @type {number[]} */ this.position = data.position; /** * The unit direction vector parallel to the swipe motion. * * You can compare the components of the vector to classify the swipe as * appropriate for your application. For example, if you are using swipes * for two dimensional scrolling, you can compare the x and y values to * determine if the swipe is primarily horizontal or vertical. * * @member direction * @memberof Leap.SwipeGesture.prototype * @type {number[]} */ this.direction = data.direction; /** * The speed of the finger performing the swipe gesture in * millimeters per second. * * @member speed * @memberof Leap.SwipeGesture.prototype * @type {number} */ this.speed = data.speed; }
javascript
{ "resource": "" }
q45099
train
function(data) { /** * The position where the key tap is registered. * * @member position * @memberof Leap.KeyTapGesture.prototype * @type {number[]} */ this.position = data.position; /** * The direction of finger tip motion. * * @member direction * @memberof Leap.KeyTapGesture.prototype * @type {number[]} */ this.direction = data.direction; /** * The progess value is always 1.0 for a key tap gesture. * * @member progress * @memberof Leap.KeyTapGesture.prototype * @type {number} */ this.progress = data.progress; }
javascript
{ "resource": "" }