_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q5700
getModifiedFiles
train
async function getModifiedFiles() { return (await execa.stdout('git', ['ls-files', '-m', '-o', '--exclude-standard'])) .split('\n') .map(tag => tag.trim()) .filter(tag => Boolean(tag)); }
javascript
{ "resource": "" }
q5701
level
train
function level (pipe, cachedLevelOf, taskKey) { var taskLevel = 0 var parentsOf = parents.bind(null, pipe) if (typeof cachedLevelOf[taskKey] === 'number') { return cachedLevelOf[taskKey] } function computeLevel (parentTaskKey) { // ↓ Recursion here: the level of a task is the max level of its parents + 1. taskLevel = Math.max(taskLevel, level(pipe, cachedLevelOf, parentTaskKey) + 1) } parentsOf(taskKey).forEach(computeLevel) cachedLevelOf[taskKey] = taskLevel return taskLevel }
javascript
{ "resource": "" }
q5702
train
function (callback) { fs.readFile(clientSecretPath, function processClientSecrets(err, content) { if (err) { debug('Error loading client secret file: ' + err); return callback(err); } else { credentials = JSON.parse(content); return callback(); } }); }
javascript
{ "resource": "" }
q5703
isDflowFun
train
function isDflowFun (f) { var isFunction = typeof f === 'function' var hasFuncsObject = typeof f.funcs === 'object' var hasGraphObject = typeof f.graph === 'object' var hasValidGraph = true if (!isFunction || !hasFuncsObject || !hasGraphObject) return false if (isFunction && hasGraphObject && hasFuncsObject) { try { validate(f.graph, f.funcs) } catch (ignore) { hasValidGraph = false } } return hasValidGraph }
javascript
{ "resource": "" }
q5704
Formats
train
function Formats(options) { options = options || {}; this.debugConstructor = options.debug || debug; this.debug = this.debugConstructor('oada:formats'); this.errorConstructor = options.error || debug; this.error = this.errorConstructor('oada:formats:error'); this.Model = Model; this.models = {}; this.mediatypes = {}; // Add the built in models this.use(require('./JsonModel')); // Add the built in media types this.use(require('./formats/index.js')); }
javascript
{ "resource": "" }
q5705
inputArgs
train
function inputArgs (outs, pipe, taskKey) { var args = [] var inputPipesOf = inputPipes.bind(null, pipe) function populateArg (inputPipe) { var index = inputPipe[2] || 0 var value = outs[inputPipe[0]] args[index] = value } inputPipesOf(taskKey).forEach(populateArg) return args }
javascript
{ "resource": "" }
q5706
evaluate
train
function evaluate(request, policies, engines) { const decisions = policies.map((policy) => ( engines[policy.type].evaluate(request, policy) )); return combineDecisionsDenyOverrides(decisions); }
javascript
{ "resource": "" }
q5707
toGemoji
train
function toGemoji(node) { var value = toString(node) var info = (unicodes[value] || emoticons[value] || {}).shortcode if (info) { node.value = info } }
javascript
{ "resource": "" }
q5708
toEmoji
train
function toEmoji(node) { var value = toString(node) var info = (shortcodes[value] || emoticons[value] || {}).emoji if (info) { node.value = info } }
javascript
{ "resource": "" }
q5709
minifyTemplate
train
function minifyTemplate(file) { try { let minifiedFile = htmlMinifier.minify(file, { collapseWhitespace: true, caseSensitive: true, removeComments: true }); return minifiedFile; } catch (err) { console.log(err); } }
javascript
{ "resource": "" }
q5710
transpile
train
function transpile() { return exec('node_modules/.bin/ngc -p tsconfig.json', function (err, stdout, stderr) { console.log(stdout); console.log(stderr); if (err !== null) { process.exit(1); } }); }
javascript
{ "resource": "" }
q5711
clearValue
train
function clearValue() { clearSelectedItem(); setInputClearButton(); if (self.parentForm && self.parentForm !== null) { self.parentForm.$setDirty(); } }
javascript
{ "resource": "" }
q5712
handleSearchText
train
function handleSearchText(searchText, previousSearchText) { self.index = -1; // do nothing on init if (searchText === previousSearchText) return; else if (self.selectedItem && self.displayProperty1) { setLoading(false); if (self.selectedItem[self.displayProperty1] !== searchText) { self.selectedItem = null; self.hidden = shouldHide(); if (self.itemList && self.itemListCopy) { self.itemList = angular.copy(self.itemListCopy); } } } else if (self.remoteMethod) { fetchResults(searchText); } else if (self.itemList) { self.itemList = $filter('filter')(self.itemListCopy, searchText); } }
javascript
{ "resource": "" }
q5713
selectedItemChange
train
function selectedItemChange(selectedItem, previousSelectedItem) { if (selectedItem) { if (self.displayProperty1) { self.searchText = selectedItem[self.displayProperty1]; } if (self.parentForm && self.parentForm !== null) { self.parentForm.$setDirty(); } } else if (previousSelectedItem && self.searchText) { if (previousSelectedItem[self.displayProperty1] === self.searchText) { self.searchText = ''; } } if (selectedItem !== previousSelectedItem) announceItemChange(); }
javascript
{ "resource": "" }
q5714
updateScroll
train
function updateScroll() { if (!self.element.li[0]) return; var height = self.element.li[0].offsetHeight, top = height * self.index, bot = top + height, hgt = self.element.scroller.clientHeight, scrollTop = self.element.scroller.scrollTop; if (top<scrollTop) { scrollTo(top); }else if (bot>scrollTop + hgt) { scrollTo(bot - hgt); } }
javascript
{ "resource": "" }
q5715
handleUniqueResult
train
function handleUniqueResult(results) { var res = [], flag = {}; for (var i = 0; i<results.length; i++) { if (flag[results[i][self.displayProperty1]]) continue; flag[results[i][self.displayProperty1]] = true; res.push(results[i]); } return res; }
javascript
{ "resource": "" }
q5716
convertArrayToObject
train
function convertArrayToObject(array) { var temp = []; array.forEach(function (text) { temp.push({ index: text }); }); return temp; }
javascript
{ "resource": "" }
q5717
train
function(retCode) { retCode = (typeof retCode !== 'undefined') ? retCode : 0; if (server) { if (shutdownInProgress) { return; } shutdownInProgress = true; console.info('Shutting down gracefully...'); server.close(function() { console.info('Closed out remaining connections'); process.exit(retCode); }); setTimeout(function() { console.error('Could not close out connections in time, force shutdown'); process.exit(retCode); }, 10 * 1000).unref(); } else { console.debug('Http server is not running. Exiting'); process.exit(retCode); } }
javascript
{ "resource": "" }
q5718
injectArguments
train
function injectArguments (funcs, task, args) { function getArgument (index) { return args[index] } /** * Inject arguments. */ function inject (taskKey) { var funcName = task[taskKey] if (funcName === 'arguments') { funcs[funcName] = function getArguments () { return args } } else { var arg = regexArgument.exec(funcName) if (arg) { funcs[funcName] = getArgument.bind(null, arg[1]) } } } Object.keys(task) .forEach(inject) }
javascript
{ "resource": "" }
q5719
inject
train
function inject (taskKey) { var funcName = task[taskKey] if (funcName === 'arguments') { funcs[funcName] = function getArguments () { return args } } else { var arg = regexArgument.exec(funcName) if (arg) { funcs[funcName] = getArgument.bind(null, arg[1]) } } }
javascript
{ "resource": "" }
q5720
injectGlobals
train
function injectGlobals (funcs, task) { /** * Inject task */ function inject (taskKey) { var taskName = task[taskKey] // Do not overwrite a function if already defined. // For example, console.log cannot be used as is, it must binded to console. if (typeof funcs[taskName] === 'function') return // Skip also reserved keywords. if (reservedKeys.indexOf(taskName) > -1) return var globalValue = walkGlobal(taskName) if (no(globalValue)) return if (typeof globalValue === 'function') { funcs[taskName] = globalValue } else { funcs[taskName] = function () { return globalValue } } } Object.keys(task) .forEach(inject) }
javascript
{ "resource": "" }
q5721
renderExample
train
function renderExample (divId, example) { var graph = graphs[example] var canvas = new Canvas(divId, { node: { DefaultNode: Node, InvalidNode, ToggleNode }, util: { typeOfNode } }) canvas.render(graph.view) dflow.fun(graph)() }
javascript
{ "resource": "" }
q5722
injectReferences
train
function injectReferences (funcs, task) { /** * Inject task. * * @param {String} taskKey */ function inject (taskKey) { var referenceName = null var referencedFunction = null var taskName = task[taskKey] /** * Inject reference. */ function reference () { return referencedFunction } if (regexReference.test(taskName)) { referenceName = taskName.substring(1) if (typeof funcs[referenceName] === 'function') { referencedFunction = funcs[referenceName] } else { referencedFunction = walkGlobal(referenceName) } if (typeof referencedFunction === 'function') { funcs[taskName] = reference } } } Object.keys(task).forEach(inject) }
javascript
{ "resource": "" }
q5723
inject
train
function inject (taskKey) { var referenceName = null var referencedFunction = null var taskName = task[taskKey] /** * Inject reference. */ function reference () { return referencedFunction } if (regexReference.test(taskName)) { referenceName = taskName.substring(1) if (typeof funcs[referenceName] === 'function') { referencedFunction = funcs[referenceName] } else { referencedFunction = walkGlobal(referenceName) } if (typeof referencedFunction === 'function') { funcs[taskName] = reference } } }
javascript
{ "resource": "" }
q5724
injectStrings
train
function injectStrings (funcs, task) { /** * Inject a function that returns a string. */ function inject (taskKey) { var taskName = task[taskKey] if (regexQuoted.test(taskName)) { funcs[taskName] = function () { return taskName.substr(1, taskName.length - 2) } } } Object.keys(task) .forEach(inject) }
javascript
{ "resource": "" }
q5725
inject
train
function inject (taskKey) { var taskName = task[taskKey] if (regexQuoted.test(taskName)) { funcs[taskName] = function () { return taskName.substr(1, taskName.length - 2) } } }
javascript
{ "resource": "" }
q5726
request
train
function request(url, options, callback) { var debug = require('debug')('wayback:http'); debug('req', url); callback = typeof callback === 'undefined' ? options : callback; // @see https://www.npmjs.com/package/fetch var stream = new fetch(url, typeof options === 'object' ? options : undefined); stream.on('error', function(err) { debug('error', err); callback(err, null); }); stream.on('meta', function(meta) { debug('resp', 'HTTP ' + meta.status); debug('resp', meta.responseHeaders); callback(null, stream); }); }
javascript
{ "resource": "" }
q5727
filePersister
train
function filePersister(filepath) { var self = this; this.initialized = false; this.filepath = filepath; /** * Check to see if the specified file path is available. * @returns A promise appropriately resolving or rejecting. */ this.start = function() { if (!this.initialized) { return fsp.emptyDir(this.filepath) .then(function() { self.initialized = true; return Promise.resolve('User has permissions to write to that file.'); }) .catch(function(err) { return Promise.reject('User does not have permissions to write to that folder.'); }); } return Promise.reject('Error: Persister already initialized.'); }; /** * Save the passed state to the file. * @param {Object} passedState - State to be saved in the file. * @returns A promise resolving to an appropriate success message or an error message. */ this.save = function(brain, package) { var filepath = this.filepath; if (this.initialized) { return fsp.remove(filepath + '/' + package + '.txt') .then(function(){ return fsp.writeFile(filepath + '/' + package + '.txt', JSON.stringify(brain)); }) .then(function(){ return Promise.resolve('Saved.'); }) } return Promise.reject('Error: Persister not initialized.'); }; /** * Retrieve data from the file. * @returns The most recent entry to the file, as a JavaScript object. */ this.recover = function(package) { if (this.initialized) { var filepath = this.filepath return fsp.ensureFile(filepath +'/' + package + '.txt') .then(function(){ return fsp.readFile(filepath + '/' + package + '.txt', 'utf8') }) .then(function(data) { if (data === ''){ return Promise.resolve({}); } else { return Promise.resolve(JSON.parse(data)); } }); } return Promise.reject('Error: Persister not initialized.'); }; }
javascript
{ "resource": "" }
q5728
addAction
train
function addAction(action, ctrl) { this.addActionIcon(action, ctrl); if (!this.actionExists(action, ctrl)) { ctrl.actionListService.requiredActionsList.splice(action.index, 0, action.name); ctrl.actionListService.actionsToIndex[action.name] = action.index; ctrl.actionListService.onToggle[action.name] = action.onToggle; ctrl.actionListService.actionsToDisplay.unshift(action.name); } }
javascript
{ "resource": "" }
q5729
removeAction
train
function removeAction(action, ctrl) { if (this.actionExists(action, ctrl)) { this.removeActionIcon(action, ctrl); delete ctrl.actionListService.actionsToIndex[action.name]; delete ctrl.actionListService.onToggle[action.name]; var i = ctrl.actionListService.actionsToDisplay.indexOf(action.name); ctrl.actionListService.actionsToDisplay.splice(i, 1); i = ctrl.actionListService.requiredActionsList.indexOf(action.name); ctrl.actionListService.requiredActionsList.splice(i, 1); } }
javascript
{ "resource": "" }
q5730
dataFormatter
train
function dataFormatter(data) { var instanceInfoArray = []; var instanceInfoObject = {}; var reservations = data.Reservations; for (var reservation in reservations) { var instances = reservations[reservation].Instances; for (var instance in instances) { var tags = instances[instance].Tags; for (var tag in tags) { if (tags[tag].Key === 'Name') { instanceInfoObject = _.assign(instanceInfoObject, {Name: tags[tag].Value}); } } instanceInfoObject = _.assign(instanceInfoObject, {State: instances[instance].State.Name}, {id: instances[instance].InstanceId}); instanceInfoArray.push(instanceInfoObject); instanceInfoObject = {}; } } return Promise.resolve(instanceInfoArray); }
javascript
{ "resource": "" }
q5731
Extractor
train
function Extractor(ac , options) { EventEmitter.call(this); var self = this; self.matchers = []; self.vars = ac || {}; self.options = options || {}; self.watchers = []; self._listen = function (car, file) { car.once('end', function () { self.emit('end', self.vars); }); car.on('line', function (line) { var i; var firstMatch = true; for (i = 0; i < self.matchers.length; i++) { var matcher = self.matchers[i]; var m; while(matcher.handler && (m = matcher.re.exec(line)) !== null){ matcher.handler(m, self.vars, file , firstMatch); firstMatch = false; if(!self.options.successive){ i = self.matchers.length; break; } } } }); return self; }; }
javascript
{ "resource": "" }
q5732
wildcards
train
function wildcards(f, cb, ctxt) { var starmatch = f.match(/([^*]*)\*.*/); if (!starmatch) { //keep async process.nextTick(function () { cb.apply(ctxt, [f]); }); return; } var basedirPath = starmatch[1].split(/\//); basedirPath.pop(); var wkdir = basedirPath.join('/'); //console.log('search base : %s', wkdir); var r = f.substring(wkdir.length + 1); //console.log('match pattern: %s', r); glob(r, { cwd: wkdir }, function (err, matches) { if (err) { ctxt.emit('error', err); } else { console.log(matches); matches.forEach(function (f) { cb.apply(ctxt, [path.join(wkdir, f)]); }); } }); }
javascript
{ "resource": "" }
q5733
Censoring
train
function Censoring() { /** * The string to replaces found matches with. Defaults to *** * * @type {String} */ this.replacementString = '***'; /** * The color used for highlighting * * @type {string} */ this.highlightColor = 'F2B8B8'; /** * Holds the currently matched text. * * @type {{replace: string, hasMatches: boolean}} */ this.currentMatch = { replace: '', hasMatches: false, matches: [] }; /** * The available patterns. These are as follows: * [name] [description] * - long_number ; Matches long, consecutive numbers * - phone_number ; Matches phone numbers. * - email_address ; Matches email addresses in many formats. * - url ; Matches URL patterns/ * - words ; Finds words, even when in disguise. * * @type {{long_number: {pattern: RegExp, enabled: boolean}, phone_number: {pattern: RegExp, enabled: boolean}, email_address: {pattern: RegExp, enabled: boolean}, url: {pattern: RegExp, enabled: boolean}, words: {enabled: boolean, pattern: Array}}} */ this.patterns = { long_number: { pattern: /\d{8,}/, enabled: false }, phone_number: { pattern: /([+-]?[\d]{1,}[\d\s-]+|\([\d]+\))[-\d.\s]{8,}/gi, enabled: false }, email_address: { pattern: /[\w._%+-]+(@|\[at\]|\(at\))[\w.-]+(\.|\[dot\]|\(dot\)|\(punt\)|\[punt\])[a-zA-Z]{2,4}/gi, enabled: false }, url: { pattern: /((https?:\/{1,2})?([-\w]\.{0,1}){2,}(\.|\[dot\]|\(dot\)|\(punt\)|\[punt\])([a-zA-Z]{2}\.[a-zA-Z]{2,3}|[a-zA-Z]{2,4}).*?(?=$|[^\w\/-]))/gi, enabled: false }, words: { pattern: [], enabled: false } }; /** * A mapping that maps regular characters to 1337 characters. * * @type {{o: string, g: string, b: Array, t: string, s: string, a: string, e: string, z: string, i: string, l: string}} */ this.map1337 = { o: '0', g: '9', b: ['8', '6'], t: '7', s: '5', a: '4', e: '3', z: '2', i: '1', l: '1' }; }
javascript
{ "resource": "" }
q5734
train
function (filters) { if (!this.isArray(filters)) { throw 'Invalid filters type supplied. Expected Array.'; } for (var i = 0; i < filters.length; i++) { this.enableFilter(filters[i]); } return this; }
javascript
{ "resource": "" }
q5735
train
function (words) { if (!this.isArray(words)) { throw 'Invalid type supplied for addFilterWords. Expected array.'; } for (var i = 0; i < words.length; i++) { this.addFilterWord(words[i]); } return this; }
javascript
{ "resource": "" }
q5736
train
function (word) { var pattern = '', any = '[^a-z0-9]?', last = false, character; for (var i = 0; i < word.length; i++) { last = i === (word.length - 1); character = word.charAt(i); if (typeof this.map1337[character] === 'undefined') { pattern += (character + (!last ? any : '')); continue; } if (typeof this.map1337[character] === 'string') { pattern += ('((' + character + '|' + this.map1337[character] + ')' + (!last ? any : '') + ')'); continue; } pattern += '((' + character; for (var m = 0; m < this.map1337[character].length; m++) { pattern += '|' + this.map1337[character][m]; } pattern += ')' + (!last ? any : '') + ')'; } this.patterns.words.pattern.push(new RegExp(pattern, 'ig')); return this; }
javascript
{ "resource": "" }
q5737
train
function (str, highlight) { this.currentMatch.replace = this.filterString(str, highlight); this.currentMatch.hasMatches = str !== this.currentMatch.replace; return this; }
javascript
{ "resource": "" }
q5738
train
function (str, highlight) { highlight = highlight || false; var self = this; var highlightColor = this.highlightColor; var replace = function (str, pattern) { if (!highlight) { return str.replace(pattern, function (match) { self.currentMatch.matches.push(match); return self.replacementString; }); } return str.replace(pattern, function (match) { self.currentMatch.matches.push(match); return '<span style="background: #' + highlightColor + ';">' + match + '</span>'; }); }.bind(this); if (typeof str !== 'string') { throw 'Invalid "str" type supplied in filterString. Expected string.'; } for (var p in this.patterns) { if (!this.patterns[p].enabled) { continue; } if (this.patterns[p].pattern instanceof RegExp) { str = replace(str, this.patterns[p].pattern); continue; } if (!this.isArray(this.patterns[p].pattern)) { throw 'Invalid pattern type supplied. Expected Array.'; } for (var i = 0; i < this.patterns[p].pattern.length; i++) { if (!this.patterns[p].pattern[i] instanceof RegExp) { throw 'Expected valid RegExp.'; } str = replace(str, this.patterns[p].pattern[i]); } } return str; }
javascript
{ "resource": "" }
q5739
addCssExtension
train
function addCssExtension(args, styleExts, extensions) { for (let x = 0, len = args.length; x < len; x++) { if (styleExts.includes(args[x])) { extensions.push('.' + args[x].slice(2)); } } }
javascript
{ "resource": "" }
q5740
train
function (values, next) { const api = path.basename(__filename, '.js').toLowerCase(); if (strapi.api.hasOwnProperty(api) && _.size(strapi.api[api].templates)) { const template = _.includes(strapi.api[api].templates, values.template) ? values.template : strapi.models[api].defaultTemplate; // Set template with correct value values.template = template; // Merge model type with template validations const templateAttributes = _.merge(_.pick(strapi.models[api].attributes, 'lang'), strapi.api[api].templates[template].attributes); const err = []; _.forEach(templateAttributes, function (rules, key) { if (values.hasOwnProperty(key) || key === 'lang') { if (key === 'lang') { // Set lang with correct value values[key] = _.includes(strapi.config.i18n.locales, values[key]) ? values[key] : strapi.config.i18n.defaultLocale; } else { // Check validations const rulesTest = anchor(values[key]).to(rules); if (rulesTest) { err.push(rulesTest[0]); } } } else { rules.required && err.push({ rule: 'required', message: 'Missing attributes ' + key }); } }); // Go next step or not _.isEmpty(err) ? next() : next(err); } else { next(new Error('Unknow API or no template detected')); } }
javascript
{ "resource": "" }
q5741
getItem
train
function getItem(ATR) { var item; while( item === undefined ) { item = slist[ATR]; if(!ATR) break; ATR = ATR.substring(0, ATR.length-1); } return item; }
javascript
{ "resource": "" }
q5742
Log
train
function Log(keyboardInfo) { var log = keyboardInfo.querySelector('ul') var st = keyboardInfo.querySelector('.statistic') var totalAvgTime = 0 var totalCount = 0 return function (key, statistic) { var count = statistic.count var average = statistic.average totalCount = totalCount + 1 totalAvgTime = totalAvgTime + statistic.average totalAvg = +(totalAvgTime/totalCount).toFixed(2) || 0 var li = document.createElement('li') li.className = "bounceIn animated" li.innerHTML = '<kbd>'+key+'</kbd><div><p><span class="avg">avg: </span><span class="value">'+average.toFixed(2)+'</span>ms</p><p><span class="count">count: </span><span class="value">'+count+'</span></p></div>' log.insertBefore(li, log.firstChild) // http://callmenick.com/post/prepend-child-javascript if (log.children.length > 10) { log.lastChild.remove() } st.innerHTML = '<div><span class="avg">Total Avg: </span><span class="value">'+totalAvg+' ms</span></div><div><span class="count">Total Count: </span><span class="value">'+totalCount+'</span></div>' } }
javascript
{ "resource": "" }
q5743
extname
train
function extname(ext) { var str = ext.charAt(0) === '.' ? ext.slice(1) : ext; if (str === 'yml') str = 'yaml'; return str; }
javascript
{ "resource": "" }
q5744
buildQuery
train
function buildQuery(query, builder = new Builder()) { for (let i = 0; i < query.length; i++) { const method = query[i] if (Array.isArray(method)) { builder.and(buildQuery(method, new NonCapture())) continue } if (!method instanceof Method) { // At this point, there should only be methods left, since all parameters are already taken care of. // If that's not the case, something didn't work out. throw new SyntaxException(`Unexpected statement: ${method}`) } const parameters = [] // If there are parameters, walk through them and apply them if they don't start a new method. while (query[i + 1] && !(query[i + 1] instanceof Method)) { parameters.push(query[i + 1]) // Since the parameters will be appended to the method object, they are already parsed and can be // removed from further parsing. Don't use unset to keep keys incrementing. query.splice(i + 1, 1) } try { // Now, append that method to the builder object. method.setParameters(parameters).callMethodOn(builder) } catch (e) { const lastIndex = parameters.length - 1 if (Array.isArray(parameters[lastIndex])) { if (lastIndex !== 0) { method.setParameters(parameters.slice(0, lastIndex)) } method.callMethodOn(builder) builder.and(buildQuery(parameters[lastIndex], new NonCapture())) } else { throw new SyntaxException(`Invalid parameter given for ${method.origin}`) } } } return builder }
javascript
{ "resource": "" }
q5745
setClassName
train
function setClassName(element, cssClass) { cssClass = snippet.isArray(cssClass) ? cssClass.join(' ') : cssClass; cssClass = trim(cssClass); if (snippet.isUndefined(element.className.baseVal)) { element.className = cssClass; return; } element.className.baseVal = cssClass; }
javascript
{ "resource": "" }
q5746
getNamespace
train
function getNamespace(file, path) { const files = namespaces.filter(ns => ns.meta.filename === file && ns.meta.path === path); if (files.length > 0) { return files[files.length - 1]; } const paths = namespaces.filter(ns => isIndex(ns.meta.filename) && isParent(ns.meta.path, path)); if (paths.length > 0) { paths.sort((ns1, ns2) => ns1.meta.path.length - ns2.meta.path.length); return paths[paths.length - 1]; } return null; }
javascript
{ "resource": "" }
q5747
expandPropertyNameGlobs
train
function expandPropertyNameGlobs(object, globPatterns) { const result = []; if (!globPatterns.length) return result; const arrayGroupPattern = globPatterns[0]; const indexOfArrayGroup = arrayGroupPattern.indexOf('[]'); if (indexOfArrayGroup !== -1) { const {arrayProp, arrayPropName} = getArrayProperty(object, arrayGroupPattern, indexOfArrayGroup); arrayProp.forEach((v, i) => { const pp = `${arrayPropName}[${i}]`; const propertyGroup = []; for (let i = 1; i < globPatterns.length; i++) { const pattern = `${pp}.${globPatterns[i]}`; propertyGroup.push(pattern); } result.push(propertyGroup); }); return result; } for (let pattern of globPatterns) { let indexOfGlob = pattern.indexOf('*'); if (indexOfGlob === -1) { result.push(pattern); } else { const {arrayProp, arrayPropName} = getArrayProperty(object, pattern, indexOfGlob); arrayProp.forEach((v, i) => { const pp = `${arrayPropName}[${i}]`; if (indexOfGlob < pattern.length - 1) result.push(pp + pattern.substring(indexOfGlob + 1)); else if (typeof v === 'object') Object.getOwnPropertyNames(v).forEach(n => result.push(`${pp}.${n}`)); else result.push(pp); }); } } return result; }
javascript
{ "resource": "" }
q5748
fromRpcSig
train
function fromRpcSig(flatSig) { const expandedSig = ethutil.fromRpcSig(flatSig); return { s: ethutil.bufferToHex(expandedSig.s), r: ethutil.bufferToHex(expandedSig.r), v: expandedSig.v }; }
javascript
{ "resource": "" }
q5749
isSignedBy
train
function isSignedBy(message, signature, address) { try { const ethMessage = ethHash(message); return caseInsensitiveCompare(recoverAddress(ethMessage, signature), prefix0x(address)); } catch (e) { return false; } }
javascript
{ "resource": "" }
q5750
methodMatch
train
function methodMatch(part) { let maxMatch = null let maxMatchCount = 0 // Go through each mapper and check if the name matches. Then, take the highest match to avoid matching // 'any', if 'any character' was given, and so on. Object.keys(mapper).forEach((key) => { const regex = new RegExp(`^(${key.replace(' ', ') (')})`, 'i') const matches = part.match(regex) const count = matches ? matches.length : 0 if (count > maxMatchCount) { maxMatchCount = count maxMatch = key } }) if (maxMatch) { // We've got a match. Create the desired object and populate it. const item = mapper[maxMatch] return new item['class'](maxMatch, item.method, buildQuery) } throw new SyntaxException(`Invalid method: ${part}`) }
javascript
{ "resource": "" }
q5751
train
function () { // <<<<<< public var newMono, newMonoTo, toFirstOutSeg, fromRevSeg; for ( var i = 0, j = this.segments.length; i < j; i++) { newMono = this.segments[i]; if ( this.PolyLeftArr[newMono.chainId] ) { // preserve winding order newMonoTo = newMono.vTo; // target of segment newMono.mprev = newMono.sprev; // doubly linked list for monotone chains (sub-polygons) newMono.mnext = newMono.snext; } else { // reverse winding order newMonoTo = newMono.vFrom; newMono = newMono.snext; newMono.mprev = newMono.snext; newMono.mnext = newMono.sprev; } if ( fromRevSeg = newMono.vFrom.lastInDiag ) { // assignment ! fromRevSeg.mnext = newMono; newMono.mprev = fromRevSeg; newMono.vFrom.lastInDiag = null; // cleanup } if ( toFirstOutSeg = newMonoTo.firstOutDiag ) { // assignment ! toFirstOutSeg.mprev = newMono; newMono.mnext = toFirstOutSeg; newMonoTo.firstOutDiag = null; // cleanup } } }
javascript
{ "resource": "" }
q5752
train
function () { // <<<<<<<<<< public var normedMonoChains = this.polyData.getMonoSubPolys(); this.polyData.clearTriangles(); for ( var i=0; i<normedMonoChains.length; i++ ) { // loop through uni-y-monotone chains // => monoPosmin is next to monoPosmax (left or right) var monoPosmax = normedMonoChains[i]; var prevMono = monoPosmax.mprev; var nextMono = monoPosmax.mnext; if ( nextMono.mnext == prevMono ) { // already a triangle this.polyData.addTriangle( monoPosmax.vFrom, nextMono.vFrom, prevMono.vFrom ); } else { // triangulate the polygon this.triangulate_monotone_polygon( monoPosmax ); } } }
javascript
{ "resource": "" }
q5753
Server
train
function Server (options, origins) { var me = this; this.origins = origins || ['*:*']; this.port = 843; this.log = console.log; // merge `this` with the options Object.keys(options).forEach(function (key) { me[key] && (me[key] = options[key]) }); // create the net server this.socket = net.createServer(function createServer (socket) { socket.on('error', function socketError () { me.responder.call(me, socket); }); me.responder.call(me, socket); }); // Listen for errors as the port might be blocked because we do not have root priv. this.socket.on('error', function serverError (err) { // Special and common case error handling if (err.errno == 13) { me.log && me.log( 'Unable to listen to port `' + me.port + '` as your Node.js instance does not have root privileges. ' + ( me.server ? 'The Flash Policy File requests will only be served inline over the supplied HTTP server. Inline serving is slower than a dedicated server instance.' : 'No fallback server supplied, we will be unable to answer Flash Policy File requests.' ) ); me.emit('connect_failed', err); me.socket.removeAllListeners(); delete me.socket; } else { me.log && me.log('FlashPolicyFileServer received an error event:\n' + (err.message ? err.message : err)); } }); this.socket.on('timeout', function serverTimeout () {}); this.socket.on('close', function serverClosed (err) { err && me.log && me.log('Server closing due to an error: \n' + (err.message ? err.message : err)); if (me.server) { // Remove the inline policy listener if we close down // but only when the server was `online` (see listen prototype) if (me.server['@'] && me.server.online) { me.server.removeListener('connection', me.server['@']); } // not online anymore delete me.server.online; } }); // Compile the initial `buffer` this.compile(); }
javascript
{ "resource": "" }
q5754
determineNonceFromReceipt
train
function determineNonceFromReceipt(receipt, address) { const {sender, recipient} = receipt; return caseInsensitiveCompare(sender.wallet, address) ? sender.nonce : recipient.nonce; }
javascript
{ "resource": "" }
q5755
train
function(seriesCallback) { async.eachLimit(groupedPinIds, 50, function(groupOfPinIds, eachCallback) { var pinIdsString = groupOfPinIds.join(','); getCache(pinIdsString, true, function (cacheData) { if (cacheData === null) { get('http://api.pinterest.com/v3/pidgets/pins/info/?pin_ids=' + pinIdsString, true, function (response) { putCache(pinIdsString, JSON.stringify(response)); allPinsData = allPinsData.concat(response.data ? response.data : []); eachCallback(); return; }); } else { allPinsData = allPinsData.concat(cacheData.data ? cacheData.data : []); eachCallback(); return; } }); }, function (err) { if(err) { throw err; } seriesCallback(); return; }); }
javascript
{ "resource": "" }
q5756
train
function(seriesCallback) { var userBoardAlreadyAdded = {}; for(var i = 0; i < allPinsData.length; i++) { var pin = allPinsData[i]; if(pin.board) { var boardUrlParts = pin.board.url.split('/'); var user = boardUrlParts[1]; var board = boardUrlParts[2]; if(!userBoardAlreadyAdded[user + board]) { userBoardAlreadyAdded[user + board] = true; boards.push({user: user, board: board}); } } } seriesCallback(); return; }
javascript
{ "resource": "" }
q5757
train
function(seriesCallback) { if(!obtainDates) { seriesCallback(); return; } var pinDateMaps = []; async.eachLimit(boards, 5, function(board, eachCallback) { getDatesForBoardPinsFromRss(board.user, board.board, function(result) { pinDateMaps.push(result); eachCallback(); }); }, function (err) { if(err) { throw err; } var pinDateMap = mergeMaps(pinDateMaps); for (var i = 0; i < allPinsData.length; i++) { allPinsData[i].created_at = null; allPinsData[i].created_at_source = null; if (pinDateMap[allPinsData[i].id]) { allPinsData[i].created_at = pinDateMap[allPinsData[i].id]; allPinsData[i].created_at_source = 'rss'; } else { pinsThatNeedScrapedDates.push(allPinsData[i].id); } } seriesCallback(); return; }); }
javascript
{ "resource": "" }
q5758
train
function(seriesCallback) { if(!obtainDates) { seriesCallback(); return; } getDatesForPinsFromScraping(pinsThatNeedScrapedDates, null, function (pinDateMap) { for (var i = 0; i < allPinsData.length; i++) { if (allPinsData[i].created_at == null && pinDateMap[allPinsData[i].id] && pinDateMap[allPinsData[i].id].date) { allPinsData[i].created_at = pinDateMap[allPinsData[i].id].date; allPinsData[i].created_at_source = pinDateMap[allPinsData[i].id].source; } } seriesCallback(); return; }); }
javascript
{ "resource": "" }
q5759
stash
train
function stash(storage, storageKey, key, value) { // get the squirrel storage object. var store = window.JSON.parse(storage.getItem(storageKey)); // if it doesn't exist, create an empty object. if (store === null) { store = {}; } // if a value isn't specified. if (isUndefined(value) || value === null) { // return the store value if the store value exists; otherwise, null. return !isUndefined(store[key]) ? store[key] : null; } // if a value is specified. // create an append object literal. var append = {}; // add the new value to the object that we'll append to the store object. append[key] = value; // extend the squirrel store object. // in ES6 this can be shortened to just $.extend(store, {[key]: value}), as there would be no need // to create a temporary storage object. $.extend(store, append); // re-session the squirrel store again. storage.setItem(storageKey, window.JSON.stringify(store)); // return the value. return value; }
javascript
{ "resource": "" }
q5760
createLiterallyObjects
train
function createLiterallyObjects(query, openPos, stringPositions) { const firstRaw = query.substr(0, openPos) const result = [firstRaw.trim()] let pointer = 0 stringPositions.forEach((stringPosition) => { if (!stringPosition.end) { throw new SyntaxException('Invalid string ending found.') } if (stringPosition.end < firstRaw.length) { // At least one string exists in first part, create a new object. // Remove the last part, since this wasn't parsed. result.pop() // Add part between pointer and string occurrence. result.push(firstRaw.substr(pointer, stringPosition.start - pointer).trim()) // Add the string as object. result.push(new Literally(firstRaw.substr( stringPosition.start + 1, stringPosition.end - stringPosition.start ))) result.push(firstRaw.substr(stringPosition.end + 2).trim()) pointer = stringPosition.end + 2 } }) return result }
javascript
{ "resource": "" }
q5761
memorizeHandler
train
function memorizeHandler(element, type, keyFn, valueFn) { const map = safeEvent(element, type); let items = map.get(keyFn); if (items) { items.push(valueFn); } else { items = [valueFn]; map.set(keyFn, items); } }
javascript
{ "resource": "" }
q5762
bindEvent
train
function bindEvent(element, type, handler, context) { /** * Event handler * @param {Event} e - event object */ function eventHandler(e) { handler.call(context || element, e || window.event); } /** * Event handler for normalize mouseenter event * @param {MouseEvent} e - event object */ function mouseEnterHandler(e) { e = e || window.event; if (checkMouse(element, e)) { eventHandler(e); } } if ('addEventListener' in element) { if (type === 'mouseenter' || type === 'mouseleave') { type = (type === 'mouseenter') ? 'mouseover' : 'mouseout'; element.addEventListener(type, mouseEnterHandler); memorizeHandler(element, type, handler, mouseEnterHandler); } else { element.addEventListener(type, eventHandler); memorizeHandler(element, type, handler, eventHandler); } } else if ('attachEvent' in element) { element.attachEvent(`on${type}`, eventHandler); memorizeHandler(element, type, handler, eventHandler); } }
javascript
{ "resource": "" }
q5763
mouseEnterHandler
train
function mouseEnterHandler(e) { e = e || window.event; if (checkMouse(element, e)) { eventHandler(e); } }
javascript
{ "resource": "" }
q5764
unbindEvent
train
function unbindEvent(element, type, handler) { const events = safeEvent(element, type); const items = events.get(handler); if (!items) { return; } forgetHandler(element, type, handler); util.forEach(items, func => { if ('removeEventListener' in element) { element.removeEventListener(type, func); } else if ('detachEvent' in element) { element.detachEvent(`on${type}`, func); } }); }
javascript
{ "resource": "" }
q5765
execute
train
function execute(context, action) { if (!remote) return fail(context, "Not connected to a server"); // prepare source path if (context.args.length < 1) return fail(context, "Remote path missing"); var path = remote.join(remotePath, context.args[0]); action(path); }
javascript
{ "resource": "" }
q5766
list
train
function list(context, err, items, paths) { if (err) return fail(context, err); var long = context.options["l"]; if (typeof long === "undefined") long = (context.command.slice(-3) === "dir"); items.forEach(function (item) { if (item.filename == "." || item.filename == "..") return; if (paths) { shell.write(item.path); } else if (long) { shell.write(item.longname); } else { shell.write(item.filename); } }); context.end(); }
javascript
{ "resource": "" }
q5767
done
train
function done(context, err, message) { if (err) return fail(context, err); if (typeof message !== "undefined") shell.write(message); context.end(); }
javascript
{ "resource": "" }
q5768
fail
train
function fail(context, err) { var message; switch (err.code) { case "ENOENT": message = err.path + ": No such file or directory"; break; case "ENOSYS": message = "Command not supported"; break; default: message = err["description"] || err.message; break; } return context.fail(message); }
javascript
{ "resource": "" }
q5769
umd
train
function umd() { let bundler = browserify(src, { debug: true, standalone: 'luhn' }) .transform(babelify) // .configure({ optional: ['runtime'] }) .bundle(); return bundler .pipe(source(pack.main)) // gives streaming vinyl file object .pipe(buffer()) // convert from streaming to buffered vinyl file object .pipe(sourcemaps.init({ loadMaps: true })) // loads map from browserify file .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./')); }
javascript
{ "resource": "" }
q5770
min
train
function min() { return gulp.src(pack.main) .pipe(uglify()) .on('error', gutil.log) .pipe(rename({ extname: minext + '.js' })) .pipe(gulp.dest('./')); }
javascript
{ "resource": "" }
q5771
subscribeToEvents
train
function subscribeToEvents() { const socket = _socket.get(this); function onEventApiError(error) { dbg('Event API connection error: ' + JSON.stringify(error)); } socket.on('pong', (latency) => { dbg(`Event API latency: ${latency} ms`); }); socket.on('connect_error', onEventApiError); socket.on('error', onEventApiError); socket.on('disconnect', onEventApiError); socket.on('reconnect_error', onEventApiError); socket.on('reconnect_failed', () => { onEventApiError('Reconnecting to the Event API failed'); }); socket.on('new_receipt', receiptJSON => { const receipt = Receipt.from(receiptJSON, _provider.get(this)); _eventEmitter.get(this).emit(EventNames.newReceipt, receipt); }); }
javascript
{ "resource": "" }
q5772
train
function(line) { // example: def bar(a, b) do // // (^\s*) begining of line // (def|defp) $1 public or private def // (.*?) $2 in betweend def ... do // \s* optional space // do opening keyword (bracket in JS) // \s*$ end of line var parts = line.match(/^(\s*)(defp\s|def\s)(.*?)\s*do\s*$/); if (!parts) return line; // ^( $1 // \s*[\w$]+ function name // ) // ( $2 optional params including parens // \( literal parens // (.*?) $3 just params // \) literal parens // )? // \s*$ trailing space var middle = /^(\s*[\w$]+)(\((.*?)\))?\s*$/; var leading = parts[1]; var funcName = parts[3].trim().match(middle)[1]; var params = parts[3].trim().match(middle)[3] || ''; var _export = (parts[2].trim() === 'def') ? 'export ' : ''; return leading + _export + 'function ' + funcName + '('+ params +') {'; }
javascript
{ "resource": "" }
q5773
train
function(line) { var newLine; // ex: [foo <- 1,2,3] // [ opening array // (.*) $1 array to concat into // (<-) $2 // (.*) $3 content to be merged // ] closing array var regexArr = /\[(.*)(\<\-)(.*)\]/; // ex: {foo <- foo: true, bar: 2} // { opening object // (.*) $1 obj to merge into // (<-) $2 // (.*) $3 content to be merged // } closing object var regexObj = /\{(.*)(\<\-)(.*)\}/; newLine = line.replace(regexArr, function($0, $1, $2, $3) { return $1.trim() + '.concat([' + $3 + ']);'; }); return newLine.replace(regexObj, function($0, $1, $2, $3) { return $1.trim() + '.merge({' + $3 + '});'; }); }
javascript
{ "resource": "" }
q5774
train
function(line, index, lines) { var newLine; if (insideString('|>', line)) return line; // line does not have a one liner pipeline if (!line.match(/(\=|return)(.*?)(\|\>)/)) return line; // if next line has a pipe operator if (lines[index] && lines[index + 1].match(/^\s*\|\>/)) return line; // http://rubular.com/r/wiBJtf12Vn // (^.+?) $1 value to pipe // \s* optional spaces // (\|\>) $2 |> pipe operator // (.*?)$ $3 tail minus first pipe ($2) // var parts = line.match(/(^.+?)\s*(\|\>)(.*?)$/); var head = parts[1] var tail = parts[2].concat(parts[3]); // process head depending on if it's immuttable or not if (head.match('Immutable')) { head = head.replace('Immutable', '_.chain(Immutable'); } else if (head.match(/^\s*return/)) { head = head.replace('return ', 'return _.chain('); } else if (head.match(/\s=\s/)) { head = head.replace('= ', '= _.chain('); } tail = tail.replace(/(\s*\|\>\s*)/g, function($0, $1) { return ').pipesCall('; }) return head + tail + ').value();' }
javascript
{ "resource": "" }
q5775
train
function(line) { //^ // (\s*) $1 opts leading spaces // ([\w$]+\s*) $2 variable name & trailing spaces // (\=) $3 division equals OR // \s* opt spaces // (.*?) rest of expression to assign // $ var parts = line.match(/^(\s*)([\w$]+)\s*(\=)\s*(.*?)$/); if (!parts) return line; var leadingSpace = parts[1]; var name = parts[2].trim(); var operator = parts[3].trim(); var rest = parts[4]; return leadingSpace + 'const ' + name + ' ' + operator + ' ' + rest; }
javascript
{ "resource": "" }
q5776
magnify
train
function magnify( pageOffsetX, pageOffsetY, elementOffsetX, elementOffsetY, scale ) { if( supportsTransforms ) { var origin = pageOffsetX +'px '+ pageOffsetY +'px', transform = 'translate('+ -elementOffsetX +'px,'+ -elementOffsetY +'px) scale('+ scale +')'; document.body.style.transformOrigin = origin; document.body.style.OTransformOrigin = origin; document.body.style.msTransformOrigin = origin; document.body.style.MozTransformOrigin = origin; document.body.style.WebkitTransformOrigin = origin; document.body.style.transform = transform; document.body.style.OTransform = transform; document.body.style.msTransform = transform; document.body.style.MozTransform = transform; document.body.style.WebkitTransform = transform; } else { // Reset all values if( scale === 1 ) { document.body.style.position = ''; document.body.style.left = ''; document.body.style.top = ''; document.body.style.width = ''; document.body.style.height = ''; document.body.style.zoom = ''; } // Apply scale else { document.body.style.position = 'relative'; document.body.style.left = ( - ( pageOffsetX + elementOffsetX ) / scale ) + 'px'; document.body.style.top = ( - ( pageOffsetY + elementOffsetY ) / scale ) + 'px'; document.body.style.width = ( scale * 100 ) + '%'; document.body.style.height = ( scale * 100 ) + '%'; document.body.style.zoom = scale; } } level = scale; if( level !== 1 && document.documentElement.classList ) { document.documentElement.classList.add( 'zoomed' ); } else { document.documentElement.classList.remove( 'zoomed' ); } }
javascript
{ "resource": "" }
q5777
pan
train
function pan() { var range = 0.12, rangeX = window.innerWidth * range, rangeY = window.innerHeight * range, scrollOffset = getScrollOffset(); // Up if( mouseY < rangeY ) { window.scroll( scrollOffset.x, scrollOffset.y - ( 1 - ( mouseY / rangeY ) ) * ( 14 / level ) ); } // Down else if( mouseY > window.innerHeight - rangeY ) { window.scroll( scrollOffset.x, scrollOffset.y + ( 1 - ( window.innerHeight - mouseY ) / rangeY ) * ( 14 / level ) ); } // Left if( mouseX < rangeX ) { window.scroll( scrollOffset.x - ( 1 - ( mouseX / rangeX ) ) * ( 14 / level ), scrollOffset.y ); } // Right else if( mouseX > window.innerWidth - rangeX ) { window.scroll( scrollOffset.x + ( 1 - ( window.innerWidth - mouseX ) / rangeX ) * ( 14 / level ), scrollOffset.y ); } }
javascript
{ "resource": "" }
q5778
train
function() { clearTimeout( panEngageTimeout ); clearInterval( panUpdateInterval ); var scrollOffset = getScrollOffset(); if( currentOptions && currentOptions.element ) { scrollOffset.x -= ( window.innerWidth - ( currentOptions.width * currentOptions.scale ) ) / 2; } magnify( scrollOffset.x, scrollOffset.y, 0, 0, 1 ); level = 1; }
javascript
{ "resource": "" }
q5779
buildResponseCard
train
function buildResponseCard(title, subTitle, options) { let buttons = null; if (options != null) { buttons = []; for (let i = 0; i < Math.min(5, options.length); i++) { buttons.push(options[i]); } } return { contentType: 'application/vnd.amazonaws.card.generic', version: 1, genericAttachments: [{ title, subTitle, buttons, }], }; }
javascript
{ "resource": "" }
q5780
getAvailabilities
train
function getAvailabilities(date) { const dayOfWeek = parseLocalDate(date).getDay(); const availabilities = []; const availableProbability = 0.3; if (dayOfWeek === 1) { let startHour = 10; while (startHour <= 16) { if (Math.random() < availableProbability) { // Add an availability window for the given hour, with duration determined by another random number. const appointmentType = getRandomInt(1, 4); if (appointmentType === 1) { availabilities.push(`${startHour}:00`); } else if (appointmentType === 2) { availabilities.push(`${startHour}:30`); } else { availabilities.push(`${startHour}:00`); availabilities.push(`${startHour}:30`); } } startHour++; } } if (dayOfWeek === 3 || dayOfWeek === 5) { availabilities.push('10:00'); availabilities.push('16:00'); availabilities.push('16:30'); } return availabilities; }
javascript
{ "resource": "" }
q5781
getAvailabilitiesForDuration
train
function getAvailabilitiesForDuration(duration, availabilities) { const durationAvailabilities = []; let startTime = '10:00'; while (startTime !== '17:00') { if (availabilities.indexOf(startTime) !== -1) { if (duration === 30) { durationAvailabilities.push(startTime); } else if (availabilities.indexOf(incrementTimeByThirtyMins(startTime)) !== -1) { durationAvailabilities.push(startTime); } } startTime = incrementTimeByThirtyMins(startTime); } return durationAvailabilities; }
javascript
{ "resource": "" }
q5782
buildAvailableTimeString
train
function buildAvailableTimeString(availabilities) { let prefix = 'We have availabilities at '; if (availabilities.length > 3) { prefix = 'We have plenty of availability, including '; } prefix += buildTimeOutputString(availabilities[0]); if (availabilities.length === 2) { return `${prefix} and ${buildTimeOutputString(availabilities[1])}`; } return `${prefix}, ${buildTimeOutputString(availabilities[1])} and ${buildTimeOutputString(availabilities[2])}`; }
javascript
{ "resource": "" }
q5783
buildOptions
train
function buildOptions(slot, appointmentType, date, bookingMap) { const dayStrings = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; if (slot === 'AppointmentType') { return [ { text: 'cleaning (30 min)', value: 'cleaning' }, { text: 'root canal (60 min)', value: 'root canal' }, { text: 'whitening (30 min)', value: 'whitening' }, ]; } else if (slot === 'Date') { // Return the next five weekdays. const options = []; const potentialDate = new Date(); while (options.length < 5) { potentialDate.setDate(potentialDate.getDate() + 1); if (potentialDate.getDay() > 0 && potentialDate.getDay() < 6) { options.push({ text: `${potentialDate.getMonth() + 1}-${potentialDate.getDate()} (${dayStrings[potentialDate.getDay()]})`, value: potentialDate.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) }); } } return options; } else if (slot === 'Time') { // Return the availabilities on the given date. if (!appointmentType || !date) { return null; } let availabilities = bookingMap[`${date}`]; if (!availabilities) { return null; } availabilities = getAvailabilitiesForDuration(getDuration(appointmentType), availabilities); if (availabilities.length === 0) { return null; } const options = []; for (let i = 0; i < Math.min(availabilities.length, 5); i++) { options.push({ text: buildTimeOutputString(availabilities[i]), value: buildTimeOutputString(availabilities[i]) }); } return options; } }
javascript
{ "resource": "" }
q5784
makeRequest
train
function makeRequest () { request = self.request.apply(null, args); requestMiddleware.use(request); request.on("response", function (response) { var contentEncoding, gzipper; //Only cache successful responses if (response.statusCode >= 200 && response.statusCode < 300) { response.on('error', function (error) { self.handleError(error); }); fs.writeFile(self.cacheDirectory + key + ".json", JSON.stringify(response.headers), function (error) { if (error) self.handleError(error); }); responseWriter = fs.createWriteStream(self.cacheDirectory + key); responseWriter.on('error', function (error) { self.handleError(error); }); contentEncoding = response.headers['content-encoding'] || ''; contentEncoding = contentEncoding.trim().toLowerCase(); if (contentEncoding === 'gzip') { response.on('error', function (error) { responseWriter.end(); }); response.pipe(responseWriter); } else { gzipper = zlib.createGzip(); response.on('error', function (error) { gzipper.end(); }); gzipper.on('error', function (error) { self.handleError(error); responseWriter.end(); }); responseWriter.on('error', function (error) { response.unpipe(gzipper); gzipper.end(); }); response.pipe(gzipper).pipe(responseWriter); } } }); self.emit("request", args[0]); }
javascript
{ "resource": "" }
q5785
dynamicLoad
train
function dynamicLoad(dynamicOptions, options, defaultOptions) { let loadableFn = Loadable let loadableOptions = defaultOptions if (typeof dynamicOptions.then === 'function') { // Support for direct import(), // eg: dynamic(import('../hello-world')) loadableOptions.loader = () => dynamicOptions } else if (typeof dynamicOptions === 'object') { // Support for having first argument being options, // eg: dynamic({loader: import('../hello-world')}) loadableOptions = { ...loadableOptions, ...dynamicOptions } } // Support for passing options, // eg: dynamic(import('../hello-world'), {loading: () => <p>Loading something</p>}) loadableOptions = { ...loadableOptions, ...options } // Support for `render` when using a mapping, // eg: `dynamic({ modules: () => {return {HelloWorld: import('../hello-world')}, render(props, loaded) {} } }) if (dynamicOptions.render) { loadableOptions.render = (loaded, props) => dynamicOptions.render(props, loaded) } // Support for `modules` when using a mapping, // eg: `dynamic({ modules: () => {return {HelloWorld: import('../hello-world')}, render(props, loaded) {} } }) if (dynamicOptions.modules) { loadableFn = Loadable.Map const loadModules = {} const modules = dynamicOptions.modules() Object.keys(modules).forEach(key => { const value = modules[key] if (typeof value.then === 'function') { loadModules[key] = () => value.then(mod => mod.default || mod) return } loadModules[key] = value }) loadableOptions.loader = loadModules } return loadableFn(loadableOptions) }
javascript
{ "resource": "" }
q5786
train
function(host, username, password) { var defaultUrl = "http://localhost:8085"; host = host || defaultUrl; if (username && password) { var protocol = host.match(/(^|\s)(https?:\/\/)/i); if (_.isArray(protocol)) { protocol = _.first(protocol); var url = host.substr(protocol.length); host = protocol + username + ":" + password + "@" + url; } } this.host = host || defaultUrl; }
javascript
{ "resource": "" }
q5787
checkErrorsWithResult
train
function checkErrorsWithResult(error, response) { var errors = checkErrors(error, response); if (errors !== false) { return errors; } try { var body = JSON.parse(response.body); } catch (parseError) { return parseError; } var results = body.results; if (typeof results === "undefined" || results.result.length === 0) { return new Error("The plan doesn't contain any result"); } return false; }
javascript
{ "resource": "" }
q5788
checkErrors
train
function checkErrors(error, response) { if (error) { return error instanceof Error ? error : new Error(error); } // Bamboo API enable plan returns 204 with empty response in case of success if ((response.statusCode !== 200) && (response.statusCode !== 204)) { return new Error("Unreachable endpoint! Response status code: " + response.statusCode); } return false; }
javascript
{ "resource": "" }
q5789
mergeUrlWithParams
train
function mergeUrlWithParams(url, params) { params = params || {}; return _.isEmpty(params) ? url : url + "?" + qs.stringify(params); }
javascript
{ "resource": "" }
q5790
client
train
function client (root) { return { tasks: { // Create a new task create: function (task, done) { post(root + 'tasks', task, done); }, // Get all tasks get: function (query, done) { get(root + 'tasks', query, done); }, // Get results for all tasks results: function (query, done) { get(root + 'tasks/results', query, done); } }, task: function (id) { return { // Get a task get: function (query, done) { get(root + 'tasks/' + id, query, done); }, // Edit a task edit: function (edits, done) { patch(root + 'tasks/' + id, edits, done); }, // Remove a task remove: function (done) { del(root + 'tasks/' + id, null, done); }, // Run a task run: function (done) { post(root + 'tasks/' + id + '/run', null, done); }, // Get results for a task results: function (query, done) { get(root + 'tasks/' + id + '/results', query, done); }, result: function (rid) { return { // Get a result get: function (query, done) { get(root + 'tasks/' + id + '/results/' + rid, query, done); } }; } }; } }; }
javascript
{ "resource": "" }
q5791
routeUrl
train
function routeUrl(location) { if (location.hash.indexOf('#/register') == 0) { var hashparts = location.hash.split('?'); var params = {}; if (hashparts.length == 2) { var pairs = hashparts[1].split('&'); for (var i = 0; i < pairs.length; ++i) { var parts = pairs[i].split('='); if (parts.length != 2) continue; params[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); } } window.matrixChat.showScreen('register', params); } }
javascript
{ "resource": "" }
q5792
processSlides
train
function processSlides() { var sections = document.querySelectorAll( '[data-markdown]'), section; for( var i = 0, len = sections.length; i < len; i++ ) { section = sections[i]; if( section.getAttribute( 'data-markdown' ).length ) { var xhr = new XMLHttpRequest(), url = section.getAttribute( 'data-markdown' ); datacharset = section.getAttribute( 'data-charset' ); // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes if( datacharset != null && datacharset != '' ) { xhr.overrideMimeType( 'text/html; charset=' + datacharset ); } xhr.onreadystatechange = function() { if( xhr.readyState === 4 ) { if ( xhr.status >= 200 && xhr.status < 300 ) { section.outerHTML = slidify( xhr.responseText, { separator: section.getAttribute( 'data-separator' ), verticalSeparator: section.getAttribute( 'data-vertical' ), notesSeparator: section.getAttribute( 'data-notes' ), attributes: getForwardedAttributes( section ) }); } else { section.outerHTML = '<section data-state="alert">' + 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' + 'Check your browser\'s JavaScript console for more details.' + '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' + '</section>'; } } }; xhr.open( 'GET', url, false ); try { xhr.send(); } catch ( e ) { alert( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e ); } } else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-vertical' ) || section.getAttribute( 'data-notes' ) ) { section.outerHTML = slidify( getMarkdownFromSlide( section ), { separator: section.getAttribute( 'data-separator' ), verticalSeparator: section.getAttribute( 'data-vertical' ), notesSeparator: section.getAttribute( 'data-notes' ), attributes: getForwardedAttributes( section ) }); } else { section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) ); } } }
javascript
{ "resource": "" }
q5793
insertAnchors
train
function insertAnchors(content) { var $ = cheerio.load(content); $(':header').each(function(i, elem) { var header = $(elem); var id = header.attr("id"); if (!id) { id = slug(header.text()); header.attr("id", id); } header.prepend('<a name="' + id + '" class="plugin-anchor" ' + 'href="#' + id + '">' + '<i class="fa fa-link" aria-hidden="true"></i>' + '</a>'); }); return $.html(); }
javascript
{ "resource": "" }
q5794
simplecryptor
train
function simplecryptor (password, options = {}) { const db = this // set default ignore options.ignore = ['_id', '_rev', '_deleted'].concat(options.ignore) const simpleCryptoJS = new SimpleCryptoJS(password) // https://github.com/pouchdb-community/transform-pouch#example-encryption db.transform({ incoming: function (doc) { return cryptor(simpleCryptoJS, doc, options.ignore, true) }, outgoing: function (doc) { return cryptor(simpleCryptoJS, doc, options.ignore, false) }, }) }
javascript
{ "resource": "" }
q5795
mergeToMap
train
function mergeToMap(arrFileObj) { return arrFileObj.reduce(function(result, fileObj) { var name; var libData; for (name in fileObj) { libData = fileObj[name]; obj.setObject(result, [libData.suite, libData.browser, libData.name], libData); } return result; }, {}); }
javascript
{ "resource": "" }
q5796
createActionType
train
function createActionType(prefix, stage, separator) { if (typeof prefix !== 'string' || typeof stage !== 'string') { throw new Error('Invalid routine prefix or stage. It should be string.'); } return '' + prefix + separator + stage; }
javascript
{ "resource": "" }
q5797
toFixedWidth
train
function toFixedWidth(value, maxChars) { var result = value.toFixed(2).substr(0, maxChars); if (result[result.length - 1] == '.') { result = result.substr(0, result.length - 2) + ' '; } return result; }
javascript
{ "resource": "" }
q5798
_getPushContext
train
function _getPushContext(context) { var pushContext; if (context && typeof context.push === "function") { // `context` is an `Assert` context pushContext = context; } else if (context && context.assert && typeof context.assert.push === "function") { // `context` is a `Test` context pushContext = context.assert; } else if ( QUnit && QUnit.config && QUnit.config.current && QUnit.config.current.assert && typeof QUnit.config.current.assert.push === "function" ) { // `context` is an unknown context but we can find the `Assert` context via QUnit pushContext = QUnit.config.current.assert; } else if (QUnit && typeof QUnit.push === "function") { pushContext = QUnit.push; } else { throw new Error("Could not find the QUnit `Assert` context to push results"); } return pushContext; }
javascript
{ "resource": "" }
q5799
shouldSkip
train
function shouldSkip(file, rough) { // Basically, if rough, any small change should still process the content return rough ? file.cache.status === LocalStatus.Unchanged : file.content.status === LocalStatus.Unchanged; }
javascript
{ "resource": "" }