_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q48000
customizer
train
function customizer(objValue, srcValue) { if (isUndefined(objValue) && !isUndefined(srcValue)) return srcValue if (isArray(objValue) && isArray(srcValue)) return srcValue if (isRegExp(objValue) || isRegExp(srcValue)) return srcValue if (isObject(objValue) || isObject(srcValue)) return mergeWith(objValue, srcValue, customizer) }
javascript
{ "resource": "" }
q48001
buildMidiNumberAttributes
train
function buildMidiNumberAttributes(midiNumber) { const pitchIndex = (midiNumber - MIDI_NUMBER_C0) % NOTES_IN_OCTAVE; const octave = Math.floor((midiNumber - MIDI_NUMBER_C0) / NOTES_IN_OCTAVE); const pitchName = SORTED_PITCHES[pitchIndex]; return { note: `${pitchName}${octave}`, pitchName, octave, midiNumber, isAccidental: ACCIDENTAL_PITCHES.includes(pitchName), }; }
javascript
{ "resource": "" }
q48002
getCompiledChildModuleDocsPath
train
function getCompiledChildModuleDocsPath(moduleName) { let rootPath = c.rootPath; if (process.cwd() !== c.rootPath) { rootPath = path.join(process.cwd(), c.rootPath); } const childModuleRootPath = path.join(rootPath, c.dependenciesPath, moduleName), cmc = config.get(childModuleRootPath), childCompiledDocs = path.join(childModuleRootPath, cmc.webroot, cmc.latestVersionPath, '**/*.html'); return childCompiledDocs; }
javascript
{ "resource": "" }
q48003
parseSimpleNumbers
train
function parseSimpleNumbers (parser) { const length = parser.buffer.length - 1 var offset = parser.offset var number = 0 var sign = 1 if (parser.buffer[offset] === 45) { sign = -1 offset++ } while (offset < length) { const c1 = parser.buffer[offset++] if (c1 === 13) { // \r\n parser.offset = offset + 1 return sign * number } number = (number * 10) + (c1 - 48) } }
javascript
{ "resource": "" }
q48004
parseStringNumbers
train
function parseStringNumbers (parser) { const length = parser.buffer.length - 1 var offset = parser.offset var number = 0 var res = '' if (parser.buffer[offset] === 45) { res += '-' offset++ } while (offset < length) { var c1 = parser.buffer[offset++] if (c1 === 13) { // \r\n parser.offset = offset + 1 if (number !== 0) { res += number } return res } else if (number > 429496728) { res += (number * 10) + (c1 - 48) number = 0 } else if (c1 === 48 && number === 0) { res += 0 } else { number = (number * 10) + (c1 - 48) } } }
javascript
{ "resource": "" }
q48005
parseSimpleString
train
function parseSimpleString (parser) { const start = parser.offset const buffer = parser.buffer const length = buffer.length - 1 var offset = start while (offset < length) { if (buffer[offset++] === 13) { // \r\n parser.offset = offset + 1 if (parser.optionReturnBuffers === true) { return parser.buffer.slice(start, offset - 1) } return parser.buffer.toString('utf8', start, offset - 1) } } }
javascript
{ "resource": "" }
q48006
parseLength
train
function parseLength (parser) { const length = parser.buffer.length - 1 var offset = parser.offset var number = 0 while (offset < length) { const c1 = parser.buffer[offset++] if (c1 === 13) { parser.offset = offset + 1 return number } number = (number * 10) + (c1 - 48) } }
javascript
{ "resource": "" }
q48007
parseError
train
function parseError (parser) { var string = parseSimpleString(parser) if (string !== undefined) { if (parser.optionReturnBuffers === true) { string = string.toString() } return new ReplyError(string) } }
javascript
{ "resource": "" }
q48008
handleError
train
function handleError (parser, type) { const err = new ParserError( 'Protocol error, got ' + JSON.stringify(String.fromCharCode(type)) + ' as reply type byte', JSON.stringify(parser.buffer), parser.offset ) parser.buffer = null parser.returnFatalError(err) }
javascript
{ "resource": "" }
q48009
pushArrayCache
train
function pushArrayCache (parser, array, pos) { parser.arrayCache.push(array) parser.arrayPos.push(pos) }
javascript
{ "resource": "" }
q48010
parseArrayChunks
train
function parseArrayChunks (parser) { var arr = parser.arrayCache.pop() var pos = parser.arrayPos.pop() if (parser.arrayCache.length) { const res = parseArrayChunks(parser) if (res === undefined) { pushArrayCache(parser, arr, pos) return } arr[pos++] = res } return parseArrayElements(parser, arr, pos) }
javascript
{ "resource": "" }
q48011
parseArrayElements
train
function parseArrayElements (parser, responses, i) { const bufferLength = parser.buffer.length while (i < responses.length) { const offset = parser.offset if (parser.offset >= bufferLength) { pushArrayCache(parser, responses, i) return } const response = parseType(parser, parser.buffer[parser.offset++]) if (response === undefined) { if (!(parser.arrayCache.length || parser.bufferCache.length)) { parser.offset = offset } pushArrayCache(parser, responses, i) return } responses[i] = response i++ } return responses }
javascript
{ "resource": "" }
q48012
decreaseBufferPool
train
function decreaseBufferPool () { if (bufferPool.length > 50 * 1024) { if (counter === 1 || notDecreased > counter * 2) { const minSliceLen = Math.floor(bufferPool.length / 10) const sliceLength = minSliceLen < bufferOffset ? bufferOffset : minSliceLen bufferOffset = 0 bufferPool = bufferPool.slice(sliceLength, bufferPool.length) } else { notDecreased++ counter-- } } else { clearInterval(interval) counter = 0 notDecreased = 0 interval = null } }
javascript
{ "resource": "" }
q48013
resizeBuffer
train
function resizeBuffer (length) { if (bufferPool.length < length + bufferOffset) { const multiplier = length > 1024 * 1024 * 75 ? 2 : 3 if (bufferOffset > 1024 * 1024 * 111) { bufferOffset = 1024 * 1024 * 50 } bufferPool = Buffer.allocUnsafe(length * multiplier + bufferOffset) bufferOffset = 0 counter++ if (interval === null) { interval = setInterval(decreaseBufferPool, 50) } } }
javascript
{ "resource": "" }
q48014
concatBulkString
train
function concatBulkString (parser) { const list = parser.bufferCache const oldOffset = parser.offset var chunks = list.length var offset = parser.bigStrSize - parser.totalChunkSize parser.offset = offset if (offset <= 2) { if (chunks === 2) { return list[0].toString('utf8', oldOffset, list[0].length + offset - 2) } chunks-- offset = list[list.length - 2].length + offset } var res = decoder.write(list[0].slice(oldOffset)) for (var i = 1; i < chunks - 1; i++) { res += decoder.write(list[i]) } res += decoder.end(list[i].slice(0, offset - 2)) return res }
javascript
{ "resource": "" }
q48015
concatBulkBuffer
train
function concatBulkBuffer (parser) { const list = parser.bufferCache const oldOffset = parser.offset const length = parser.bigStrSize - oldOffset - 2 var chunks = list.length var offset = parser.bigStrSize - parser.totalChunkSize parser.offset = offset if (offset <= 2) { if (chunks === 2) { return list[0].slice(oldOffset, list[0].length + offset - 2) } chunks-- offset = list[list.length - 2].length + offset } resizeBuffer(length) const start = bufferOffset list[0].copy(bufferPool, start, oldOffset, list[0].length) bufferOffset += list[0].length - oldOffset for (var i = 1; i < chunks - 1; i++) { list[i].copy(bufferPool, bufferOffset) bufferOffset += list[i].length } list[i].copy(bufferPool, bufferOffset, 0, offset - 2) bufferOffset += offset - 2 return bufferPool.slice(start, bufferOffset) }
javascript
{ "resource": "" }
q48016
train
function (options, callback) { var licenseSrc = path.join(options.src, 'LICENSE') try { fs.accessSync(licenseSrc) } catch (err) { try { licenseSrc = path.join(options.src, 'LICENSE.txt') fs.accessSync(licenseSrc) } catch (err) { licenseSrc = path.join(options.src, 'LICENSE.md') fs.accessSync(licenseSrc) } } options.logger('Reading license file from ' + licenseSrc) fs.readFile(licenseSrc, callback) }
javascript
{ "resource": "" }
q48017
train
function (data, callback) { async.parallel([ async.apply(readMeta, data) ], function (err, results) { var pkg = results[0] || {} var defaults = { id: getAppId(pkg.name, pkg.homepage), productName: pkg.productName || pkg.name, genericName: pkg.genericName || pkg.productName || pkg.name, description: pkg.description, branch: 'master', arch: undefined, base: 'io.atom.electron.BaseApp', baseVersion: 'master', baseFlatpakref: 'https://s3-us-west-2.amazonaws.com/electron-flatpak.endlessm.com/electron-base-app-master.flatpakref', runtime: 'org.freedesktop.Platform', runtimeVersion: '1.4', runtimeFlatpakref: 'https://raw.githubusercontent.com/endlessm/flatpak-bundler/master/refs/freedesktop-runtime-1.4.flatpakref', sdk: 'org.freedesktop.Sdk', sdkFlatpakref: 'https://raw.githubusercontent.com/endlessm/flatpak-bundler/master/refs/freedesktop-sdk-1.4.flatpakref', finishArgs: [ // X Rendering '--socket=x11', '--share=ipc', // Open GL '--device=dri', // Audio output '--socket=pulseaudio', // Read/write home directory access '--filesystem=home', // Chromium uses a socket in tmp for its singleton check '--filesystem=/tmp', // Allow communication with network '--share=network', // System notifications with libnotify '--talk-name=org.freedesktop.Notifications' ], modules: [], bin: pkg.productName || pkg.name || 'electron', icon: path.resolve(__dirname, '../resources/icon.png'), files: [], symlinks: [], categories: [ 'GNOME', 'GTK', 'Utility' ], mimeType: [] } callback(err, defaults) }) }
javascript
{ "resource": "" }
q48018
train
function (data, defaults, callback) { // Flatten everything for ease of use. var options = _.defaults({}, data, data.options, defaults) callback(null, options) }
javascript
{ "resource": "" }
q48019
train
function (options, file, callback) { options.logger('Generating template from ' + file) async.waterfall([ async.apply(fs.readFile, file), function (template, callback) { var result = _.template(template)(options) options.logger('Generated template from ' + file + '\n' + result) callback(null, result) } ], callback) }
javascript
{ "resource": "" }
q48020
train
function (options, dir, callback) { var desktopSrc = path.resolve(__dirname, '../resources/desktop.ejs') var desktopDest = path.join(dir, 'share/applications', options.id + '.desktop') options.logger('Creating desktop file at ' + desktopDest) async.waterfall([ async.apply(generateTemplate, options, desktopSrc), async.apply(fs.outputFile, desktopDest) ], function (err) { callback(err && new Error('Error creating desktop file: ' + (err.message || err))) }) }
javascript
{ "resource": "" }
q48021
train
function (options, dir, callback) { var iconFile = path.join(dir, getPixmapPath(options)) options.logger('Creating icon file at ' + iconFile) fs.copy(options.icon, iconFile, function (err) { callback(err && new Error('Error creating icon file: ' + (err.message || err))) }) }
javascript
{ "resource": "" }
q48022
train
function (options, dir, callback) { async.forEachOf(options.icon, function (icon, resolution, callback) { var iconFile = path.join(dir, 'share/icons/hicolor', resolution, 'apps', options.id + '.png') options.logger('Creating icon file at ' + iconFile) fs.copy(icon, iconFile, callback) }, function (err) { callback(err && new Error('Error creating icon file: ' + (err.message || err))) }) }
javascript
{ "resource": "" }
q48023
train
function (options, dir, callback) { if (_.isObject(options.icon)) { createHicolorIcon(options, dir, callback) } else if (options.icon) { createPixmapIcon(options, dir, callback) } else { callback() } }
javascript
{ "resource": "" }
q48024
train
function (options, dir, callback) { var copyrightFile = path.join(dir, 'share/doc', options.id, 'copyright') options.logger('Creating copyright file at ' + copyrightFile) async.waterfall([ async.apply(readLicense, options), async.apply(fs.outputFile, copyrightFile) ], function (err) { callback(err && new Error('Error creating copyright file: ' + (err.message || err))) }) }
javascript
{ "resource": "" }
q48025
train
function (options, dir, callback) { var applicationDir = path.join(dir, 'lib', options.id) options.logger('Copying application to ' + applicationDir) async.waterfall([ async.apply(fs.ensureDir, applicationDir), async.apply(fs.copy, options.src, applicationDir) ], function (err) { callback(err && new Error('Error copying application directory: ' + (err.message || err))) }) }
javascript
{ "resource": "" }
q48026
train
function (options, callback) { options.logger('Creating temporary directory') async.waterfall([ async.apply(temp.mkdir, 'electron-'), function (dir, callback) { dir = path.join(dir, options.id + '_' + options.version + '_' + options.arch) fs.ensureDir(dir, callback) } ], function (err, dir) { callback(err && new Error('Error creating temporary directory: ' + (err.message || err)), dir) }) }
javascript
{ "resource": "" }
q48027
train
function (options, dir, callback) { options.logger('Creating contents of package') async.parallel([ async.apply(createDesktop, options, dir), async.apply(createIcon, options, dir), async.apply(createCopyright, options, dir), async.apply(createApplication, options, dir) ], function (err) { callback(err, dir) }) }
javascript
{ "resource": "" }
q48028
train
function (options, dir, callback) { var name = _.template('<%= id %>_<%= branch %>_<%= arch %>.flatpak')(options) var dest = options.rename(options.dest, name) options.logger('Creating package at ' + dest) var extraExports = [] if (options.icon && !_.isObject(options.icon)) extraExports.push(getPixmapPath(options)) var files = [ [dir, '/'] ] var symlinks = [ [path.join('/lib', options.id, options.bin), path.join('/bin', options.bin)] ] flatpak.bundle({ id: options.id, branch: options.branch, base: options.base, baseVersion: options.baseVersion, baseFlatpakref: options.baseFlatpakref, runtime: options.runtime, runtimeVersion: options.runtimeVersion, runtimeFlatpakref: options.runtimeFlatpakref, sdk: options.sdk, sdkFlatpakref: options.sdkFlatpakref, finishArgs: options.finishArgs, command: options.bin, files: files.concat(options.files), symlinks: symlinks.concat(options.symlinks), extraExports: extraExports, modules: options.modules }, { arch: options.arch, bundlePath: dest }, function (err) { callback(err, dir) }) }
javascript
{ "resource": "" }
q48029
makeShapeAstForShapeIntersectRuntime
train
function makeShapeAstForShapeIntersectRuntime(propTypeData) { const runtimeMerge = makeObjectMergeAstForShapeIntersectRuntime(propTypeData); return t.callExpression( t.memberExpression( makePropTypeImportNode(), t.identifier('shape'), ), [runtimeMerge], ); }
javascript
{ "resource": "" }
q48030
findByHash
train
function findByHash(config, hash) { const re = new RegExp(injectHashIntoPath(config.sourceMapPath, hash)); return glob .sync('./**') .filter(file => re.test(file)) .map(sourceMapPath => { // strip relative path characters const sourceMapPathMatch = sourceMapPath.match(re); if (sourceMapPathMatch) { const minifiedUrl = sourceMapPathMatch[0].replace( re, injectHashIntoPath(config.minifiedUrl, hash), ); return { sourceMapPath, minifiedUrl, }; } }) .filter(Boolean); }
javascript
{ "resource": "" }
q48031
parseurl
train
function parseurl (req) { var url = req.url if (url === undefined) { // URL is undefined return undefined } var parsed = req._parsedUrl if (fresh(url, parsed)) { // Return cached URL parse return parsed } // Parse the URL parsed = fastparse(url) parsed._raw = url return (req._parsedUrl = parsed) }
javascript
{ "resource": "" }
q48032
originalurl
train
function originalurl (req) { var url = req.originalUrl if (typeof url !== 'string') { // Fallback return parseurl(req) } var parsed = req._parsedOriginalUrl if (fresh(url, parsed)) { // Return cached URL parse return parsed } // Parse the URL parsed = fastparse(url) parsed._raw = url return (req._parsedOriginalUrl = parsed) }
javascript
{ "resource": "" }
q48033
fastparse
train
function fastparse (str) { if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { return parse(str) } var pathname = str var query = null var search = null // This takes the regexp from https://github.com/joyent/node/pull/7878 // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ // And unrolls it into a for loop for (var i = 1; i < str.length; i++) { switch (str.charCodeAt(i)) { case 0x3f: /* ? */ if (search === null) { pathname = str.substring(0, i) query = str.substring(i + 1) search = str.substring(i) } break case 0x09: /* \t */ case 0x0a: /* \n */ case 0x0c: /* \f */ case 0x0d: /* \r */ case 0x20: /* */ case 0x23: /* # */ case 0xa0: case 0xfeff: return parse(str) } } var url = Url !== undefined ? new Url() : {} url.path = str url.href = str url.pathname = pathname if (search !== null) { url.query = query url.search = search } return url }
javascript
{ "resource": "" }
q48034
fresh
train
function fresh (url, parsedUrl) { return typeof parsedUrl === 'object' && parsedUrl !== null && (Url === undefined || parsedUrl instanceof Url) && parsedUrl._raw === url }
javascript
{ "resource": "" }
q48035
customUnique
train
function customUnique(array) { const unique = uniqBy(array, 'fname'); // we construct unique portlets array will all linked categories (reversing category and portlets child) unique.forEach((elem) => { const dupl = array.filter((e) => e.fname === elem.fname); const allCategories = dupl.flatMap(({categories}) => categories); elem.categories = [...new Set(allCategories)]; }); return unique; }
javascript
{ "resource": "" }
q48036
train
function( buffer, enFamilyName, noMerge) { //cancelling in browser merge clearTimeout(this.mergeTimeout); if ( !enFamilyName ) { enFamilyName = this.ot.getEnglishName('fontFamily'); } if ( this.fontMap[ enFamilyName ] ) { document.fonts.delete( this.fontMap[ enFamilyName ] ); } var fontface = this.fontMap[ enFamilyName ] = ( new window.FontFace( enFamilyName, buffer || this.toArrayBuffer() ) ); if ( fontface.status === 'error' ) { throw new Error('Fontface is invalid and cannot be displayed'); } document.fonts.add( fontface ); //we merge font that haven't been merge if ( !noMerge ) { var timeoutRef = this.mergeTimeout = setTimeout(function() { mergeFont( 'https://merge.prototypo.io', { style: 'forbrowserdisplay', template: 'noidea', family: 'forbrowserdisplay' }, 'plumin', buffer, true, function(mergedBuffer) { if (timeoutRef === this.mergeTimeout) { this.addToFonts(mergedBuffer, enFamilyName, true); } }.bind(this) ); }.bind(this), 300); } return this; }
javascript
{ "resource": "" }
q48037
train
function(target, source) { target = cloneJSON(target); for (var key in source) { if (source.hasOwnProperty(key)) { if (isObject(target[key]) && isObject(source[key])) { target[key] = merge(target[key], source[key]); } else { target[key] = source[key]; } } } return target; }
javascript
{ "resource": "" }
q48038
train
function(path, definitions) { path = path.replace(/^#\/definitions\//, '').split('/'); var find = function(path, root) { var key = path.shift(); if (!root[key]) { return {}; } else if (!path.length) { return root[key]; } else { return find(path, root[key]); } }; var result = find(path, definitions); if (!isObject(result)) { return result; } return cloneJSON(result); }
javascript
{ "resource": "" }
q48039
train
function(schema, definitions) { if (typeof schema['default'] !== 'undefined') { return schema['default']; } else if (typeof schema.allOf !== 'undefined') { var mergedItem = mergeAllOf(schema.allOf, definitions); return defaults(mergedItem, definitions); } else if (typeof schema.$ref !== 'undefined') { var reference = getLocalRef(schema.$ref, definitions); return defaults(reference, definitions); } else if (schema.type === 'object') { if (!schema.properties) { return {}; } for (var key in schema.properties) { if (schema.properties.hasOwnProperty(key)) { schema.properties[key] = defaults(schema.properties[key], definitions); if (typeof schema.properties[key] === 'undefined') { delete schema.properties[key]; } } } return schema.properties; } else if (schema.type === 'array') { if (!schema.items) { return []; } // minimum item count var ct = schema.minItems || 0; // tuple-typed arrays if (schema.items.constructor === Array) { var values = schema.items.map(function (item) { return defaults(item, definitions); }); // remove undefined items at the end (unless required by minItems) for (var i = values.length - 1; i >= 0; i--) { if (typeof values[i] !== 'undefined') { break; } if (i + 1 > ct) { values.pop(); } } return values; } // object-typed arrays var value = defaults(schema.items, definitions); if (typeof value === 'undefined') { return []; } else { var values = []; for (var i = 0; i < Math.max(1, ct); i++) { values.push(cloneJSON(value)); } return values; } } }
javascript
{ "resource": "" }
q48040
highlight
train
function highlight(language, value, options) { var settings = options || {} var prefix = settings.prefix if (prefix === null || prefix === undefined) { prefix = defaultPrefix } return normalize(coreHighlight(language, value, true, prefix)) }
javascript
{ "resource": "" }
q48041
registerLanguage
train
function registerLanguage(name, syntax) { var lang = syntax(low) languages[name] = lang languageNames.push(name) if (lang.aliases) { registerAlias(name, lang.aliases) } }
javascript
{ "resource": "" }
q48042
registerAlias
train
function registerAlias(name, alias) { var map = name var key var list var length var index if (alias) { map = {} map[name] = alias } for (key in map) { list = map[key] list = typeof list === 'string' ? [list] : list length = list.length index = -1 while (++index < length) { aliases[list[index]] = key } } }
javascript
{ "resource": "" }
q48043
processLexeme
train
function processLexeme(buffer, lexeme) { var newMode var endMode var origin modeBuffer += buffer if (lexeme === undefined) { addSiblings(processBuffer(), currentChildren) return 0 } newMode = subMode(lexeme, top) if (newMode) { addSiblings(processBuffer(), currentChildren) startNewMode(newMode, lexeme) return newMode.returnBegin ? 0 : lexeme.length } endMode = endOfMode(top, lexeme) if (endMode) { origin = top if (!(origin.returnEnd || origin.excludeEnd)) { modeBuffer += lexeme } addSiblings(processBuffer(), currentChildren) // Close open modes. do { if (top.className) { pop() } relevance += top.relevance top = top.parent } while (top !== endMode.parent) if (origin.excludeEnd) { addText(lexeme, currentChildren) } modeBuffer = '' if (endMode.starts) { startNewMode(endMode.starts, '') } return origin.returnEnd ? 0 : lexeme.length } if (isIllegal(lexeme, top)) { throw fault( 'Illegal lexeme "%s" for mode "%s"', lexeme, top.className || '<unnamed>' ) } // Parser should not reach this point as all types of lexemes should be // caught earlier, but if it does due to some bug make sure it advances // at least one character forward to prevent infinite looping. modeBuffer += lexeme return lexeme.length || /* istanbul ignore next */ 1 }
javascript
{ "resource": "" }
q48044
startNewMode
train
function startNewMode(mode, lexeme) { var node if (mode.className) { node = build(mode.className, []) } if (mode.returnBegin) { modeBuffer = '' } else if (mode.excludeBegin) { addText(lexeme, currentChildren) modeBuffer = '' } else { modeBuffer = lexeme } // Enter a new mode. if (node) { currentChildren.push(node) stack.push(currentChildren) currentChildren = node.children } top = Object.create(mode, {parent: {value: top}}) }
javascript
{ "resource": "" }
q48045
processKeywords
train
function processKeywords() { var nodes = [] var lastIndex var keyword var node var submatch if (!top.keywords) { return addText(modeBuffer, nodes) } lastIndex = 0 top.lexemesRe.lastIndex = 0 keyword = top.lexemesRe.exec(modeBuffer) while (keyword) { addText(modeBuffer.substring(lastIndex, keyword.index), nodes) submatch = keywordMatch(top, keyword) if (submatch) { relevance += submatch[1] node = build(submatch[0], []) nodes.push(node) addText(keyword[0], node.children) } else { addText(keyword[0], nodes) } lastIndex = top.lexemesRe.lastIndex keyword = top.lexemesRe.exec(modeBuffer) } addText(modeBuffer.substr(lastIndex), nodes) return nodes }
javascript
{ "resource": "" }
q48046
addSiblings
train
function addSiblings(siblings, nodes) { var length = siblings.length var index = -1 var sibling while (++index < length) { sibling = siblings[index] if (sibling.type === 'text') { addText(sibling.value, nodes) } else { nodes.push(sibling) } } }
javascript
{ "resource": "" }
q48047
addText
train
function addText(value, nodes) { var tail if (value) { tail = nodes[nodes.length - 1] if (tail && tail.type === 'text') { tail.value += value } else { nodes.push(buildText(value)) } } return nodes }
javascript
{ "resource": "" }
q48048
build
train
function build(name, contents, noPrefix) { return { type: 'element', tagName: 'span', properties: { className: [(noPrefix ? '' : prefix) + name] }, children: contents } }
javascript
{ "resource": "" }
q48049
keywordMatch
train
function keywordMatch(mode, keywords) { var keyword = keywords[0] if (language[keyInsensitive]) { keyword = keyword.toLowerCase() } return own.call(mode.keywords, keyword) && mode.keywords[keyword] }
javascript
{ "resource": "" }
q48050
endOfMode
train
function endOfMode(mode, lexeme) { if (test(mode.endRe, lexeme)) { while (mode.endsParent && mode.parent) { mode = mode.parent } return mode } if (mode.endsWithParent) { return endOfMode(mode.parent, lexeme) } }
javascript
{ "resource": "" }
q48051
subMode
train
function subMode(lexeme, mode) { var values = mode.contains var length = values.length var index = -1 while (++index < length) { if (test(values[index].beginRe, lexeme)) { return values[index] } } }
javascript
{ "resource": "" }
q48052
compileLanguage
train
function compileLanguage(language) { compileMode(language) // Compile a language mode, optionally with a parent. function compileMode(mode, parent) { var compiledKeywords = {} var terminators if (mode.compiled) { return } mode.compiled = true mode.keywords = mode.keywords || mode.beginKeywords if (mode.keywords) { if (typeof mode.keywords === 'string') { flatten('keyword', mode.keywords) } else { Object.keys(mode.keywords).forEach(function(className) { flatten(className, mode.keywords[className]) }) } mode.keywords = compiledKeywords } mode.lexemesRe = langRe(mode.lexemes || /\w+/, true) if (parent) { if (mode.beginKeywords) { mode.begin = '\\b(' + mode.beginKeywords.split(space).join(verticalBar) + ')\\b' } if (!mode.begin) { mode.begin = /\B|\b/ } mode.beginRe = langRe(mode.begin) if (!mode.end && !mode.endsWithParent) { mode.end = /\B|\b/ } if (mode.end) { mode.endRe = langRe(mode.end) } mode.terminatorEnd = source(mode.end) || '' if (mode.endsWithParent && parent.terminatorEnd) { mode.terminatorEnd += (mode.end ? verticalBar : '') + parent.terminatorEnd } } if (mode.illegal) { mode.illegalRe = langRe(mode.illegal) } if (mode.relevance === undefined) { mode.relevance = 1 } if (!mode.contains) { mode.contains = [] } mode.contains = concat.apply( [], mode.contains.map(function(c) { return expandMode(c === 'self' ? mode : c) }) ) mode.contains.forEach(function(c) { compileMode(c, mode) }) if (mode.starts) { compileMode(mode.starts, parent) } terminators = mode.contains .map(map) .concat([mode.terminatorEnd, mode.illegal]) .map(source) .filter(Boolean) mode.terminators = terminators.length === 0 ? {exec: execNoop} : langRe(terminators.join(verticalBar), true) function map(c) { return c.beginKeywords ? '\\.?(' + c.begin + ')\\.?' : c.begin } // Flatten a classname. function flatten(className, value) { var pairs var pair var index var length if (language[keyInsensitive]) { value = value.toLowerCase() } pairs = value.split(space) length = pairs.length index = -1 while (++index < length) { pair = pairs[index].split(verticalBar) compiledKeywords[pair[0]] = [className, pair[1] ? Number(pair[1]) : 1] } } } // Create a regex for `value`. function langRe(value, global) { return new RegExp( source(value), 'm' + (language[keyInsensitive] ? 'i' : '') + (global ? 'g' : '') ) } // Get the source of an expression or string. function source(re) { return (re && re.source) || re } }
javascript
{ "resource": "" }
q48053
flatten
train
function flatten(className, value) { var pairs var pair var index var length if (language[keyInsensitive]) { value = value.toLowerCase() } pairs = value.split(space) length = pairs.length index = -1 while (++index < length) { pair = pairs[index].split(verticalBar) compiledKeywords[pair[0]] = [className, pair[1] ? Number(pair[1]) : 1] } }
javascript
{ "resource": "" }
q48054
normalize
train
function normalize(result) { return { relevance: result.relevance || 0, language: result.language || null, value: result.value || [] } }
javascript
{ "resource": "" }
q48055
train
function(cache) { var tips = cache[""].tips; // Sort labels: metadata, then branch tips by first add, // then user entries by first add, then last run // Then return without metadata return Object.keys(cache) .sort(function(a, b) { var keys = Object.keys(cache); return ( (a ? 1 : 0) - (b ? 1 : 0) || (a in tips ? 0 : 1) - (b in tips ? 0 : 1) || (a.charAt(0) === " " ? 1 : 0) - (b.charAt(0) === " " ? 1 : 0) || keys.indexOf(a) - keys.indexOf(b) ); }) .slice(1); }
javascript
{ "resource": "" }
q48056
train
function(delta) { var color = "green"; if (delta > 0) { delta = "+" + delta; color = "red"; } else if (!delta) { delta = delta === 0 ? "=" : "?"; color = "grey"; } return chalk[color](delta); }
javascript
{ "resource": "" }
q48057
train
function(src) { var cache; try { cache = fs.existsSync(src) ? file.readJSON(src) : undefined; } catch (e) { debug(e); } // Progressively upgrade `cache`, which is one of: // empty // {} // { file: size [,...] } // { "": { tips: { label: SHA1, ... } }, label: { file: size, ... }, ... } // { "": { version: 0.4, tips: { label: SHA1, ... } }, // label: { file: { "": size, compressor: size, ... }, ... }, ... } if (typeof cache !== "object") { cache = undefined; } if (!cache || !cache[""]) { // If promoting cache to dictionary, assume that data are for last run cache = _.zipObject(["", lastrun], [{ version: 0, tips: {} }, cache]); } if (!cache[""].version) { cache[""].version = 0.4; _.forEach(cache, function(sizes, label) { if (!label || !sizes) { return; } // If promoting sizes to dictionary, assume that compressed size data are indicated by suffixes Object.keys(sizes) .sort() .forEach(function(file) { var parts = file.split("."), prefix = parts.shift(); // Append compressed size data to a matching prefix while (parts.length) { if (typeof sizes[prefix] === "object") { sizes[prefix][parts.join(".")] = sizes[file]; delete sizes[file]; return; } prefix += "." + parts.shift(); } // Store uncompressed size data sizes[file] = { "": sizes[file] }; }); }); } return cache; }
javascript
{ "resource": "" }
q48058
train
function(task, compressors) { var sizes = {}, files = processPatterns(task.files, function(pattern) { // Find all matching files for this pattern. return glob.sync(pattern, { filter: "isFile" }); }); files.forEach(function(src) { var contents = file.read(src), fileSizes = (sizes[src] = { "": contents.length }); if (compressors) { Object.keys(compressors).forEach(function(compressor) { fileSizes[compressor] = compressors[compressor](contents); }); } }); return sizes; }
javascript
{ "resource": "" }
q48059
train
function(done) { debug("Running `git branch` command..."); exec( "git branch --no-color --verbose --no-abbrev --contains HEAD", function(err, stdout) { var status = {}, matches = /^\* (.+?)\s+([0-9a-f]{8,})/im.exec(stdout); if (err || !matches) { done(err || "branch not found"); } else if (matches[1].indexOf(" ") >= 0) { done("not a branch tip: " + matches[2]); } else { status.branch = matches[1]; status.head = matches[2]; exec("git diff --quiet HEAD", function(err) { status.changed = !!err; done(null, status); }); } } ); }
javascript
{ "resource": "" }
q48060
compareSizes
train
function compareSizes(task) { var compressors = task.options.compress, newsizes = helpers.sizes(task, compressors), files = Object.keys(newsizes), sizecache = defaultCache, cache = helpers.get_cache(sizecache), tips = cache[""].tips, labels = helpers.sorted_labels(cache); // Obtain the current branch and continue... helpers.git_status(function(err, status) { var prefixes = compressors ? [""].concat(Object.keys(compressors)) : [""], commonHeader = prefixes.map( (label, i) => (i === 0 && compressors ? "raw" : label) ); const tableOptions = { align: prefixes.map(() => "r").concat("l"), // eslint-disable-next-line no-control-regex stringLength: s => s.replace(/\x1B\[\d+m/g, "").length // Return a string, uncolored (suitable for testing .length, etc). }; if (err) { console.warn(err); status = {}; } let rows = []; rows.push(commonHeader.concat("Sizes")); // Raw sizes files.forEach(function(key) { rows.push(prefixes.map(prefix => newsizes[key][prefix]).concat(key + "")); }); console.log(table(rows, tableOptions)); // Comparisons labels.forEach(function(label) { var oldsizes = cache[label]; // Skip metadata key and empty cache entries if (label === "" || !cache[label]) { return; } rows = []; // Header rows.push( commonHeader.concat("Compared to " + helpers.label(label, tips[label])) ); // Data files.forEach(function(key) { var old = oldsizes && oldsizes[key]; rows.push( prefixes .map(function(prefix) { return helpers.delta(old && newsizes[key][prefix] - old[prefix]); }) .concat(key + "") ); }); console.log(); console.log(table(rows, tableOptions)); }); // Update "last run" sizes cache[lastrun] = newsizes; // Remember if we're at a branch tip and the branch name is an available key if ( status.branch && !status.changed && (status.branch in tips || !cache[status.branch]) ) { tips[status.branch] = status.head; cache[status.branch] = newsizes; console.log("\nSaved as: " + status.branch); } // Write to file file.write(sizecache, JSON.stringify(cache)); }); }
javascript
{ "resource": "" }
q48061
train
function ( functionCodeBuilder, parserName, libLocations, libPath, runnerImpl ) { if ( THREE.LoaderSupport.Validator.isValid( this.loaderWorker.worker ) ) return; if ( this.logging.enabled ) { console.info( 'WorkerSupport: Building worker code...' ); console.time( 'buildWebWorkerCode' ); } if ( THREE.LoaderSupport.Validator.isValid( runnerImpl ) ) { if ( this.logging.enabled ) console.info( 'WorkerSupport: Using "' + runnerImpl.runnerName + '" as Runner class for worker.' ); // Browser implementation } else if ( typeof window !== "undefined" ) { runnerImpl = THREE.LoaderSupport.WorkerRunnerRefImpl; if ( this.logging.enabled ) console.info( 'WorkerSupport: Using DEFAULT "THREE.LoaderSupport.WorkerRunnerRefImpl" as Runner class for worker.' ); // NodeJS implementation } else { runnerImpl = THREE.LoaderSupport.NodeWorkerRunnerRefImpl; if ( this.logging.enabled ) console.info( 'WorkerSupport: Using DEFAULT "THREE.LoaderSupport.NodeWorkerRunnerRefImpl" as Runner class for worker.' ); } var userWorkerCode = functionCodeBuilder( THREE.LoaderSupport.WorkerSupport.CodeSerializer ); userWorkerCode += 'var Parser = '+ parserName + ';\n\n'; userWorkerCode += THREE.LoaderSupport.WorkerSupport.CodeSerializer.serializeClass( runnerImpl.runnerName, runnerImpl ); userWorkerCode += 'new ' + runnerImpl.runnerName + '();\n\n'; var scope = this; if ( THREE.LoaderSupport.Validator.isValid( libLocations ) && libLocations.length > 0 ) { var libsContent = ''; var loadAllLibraries = function ( path, locations ) { if ( locations.length === 0 ) { scope.loaderWorker.initWorker( libsContent + userWorkerCode, runnerImpl.runnerName ); if ( scope.logging.enabled ) console.timeEnd( 'buildWebWorkerCode' ); } else { var loadedLib = function ( contentAsString ) { libsContent += contentAsString; loadAllLibraries( path, locations ); }; var fileLoader = new THREE.FileLoader(); fileLoader.setPath( path ); fileLoader.setResponseType( 'text' ); fileLoader.load( locations[ 0 ], loadedLib ); locations.shift(); } }; loadAllLibraries( libPath, libLocations ); } else { this.loaderWorker.initWorker( userWorkerCode, runnerImpl.runnerName ); if ( this.logging.enabled ) console.timeEnd( 'buildWebWorkerCode' ); } }
javascript
{ "resource": "" }
q48062
train
function ( e ) { var payload = e.data; switch ( payload.cmd ) { case 'meshData': case 'materialData': case 'imageData': this.runtimeRef.callbacks.meshBuilder( payload ); break; case 'complete': this.runtimeRef.queuedMessage = null; this.started = false; this.runtimeRef.callbacks.onLoad( payload.msg ); if ( this.runtimeRef.terminateRequested ) { if ( this.runtimeRef.logging.enabled ) console.info( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Run is complete. Terminating application on request!' ); this.runtimeRef._terminate(); } break; case 'error': console.error( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Reported error: ' + payload.msg ); this.runtimeRef.queuedMessage = null; this.started = false; this.runtimeRef.callbacks.onLoad( payload.msg ); if ( this.runtimeRef.terminateRequested ) { if ( this.runtimeRef.logging.enabled ) console.info( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Run reported error. Terminating application on request!' ); this.runtimeRef._terminate(); } break; default: console.error( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Received unknown command: ' + payload.cmd ); break; } }
javascript
{ "resource": "" }
q48063
train
function ( parser, params ) { var property, funcName, values; for ( property in params ) { funcName = 'set' + property.substring( 0, 1 ).toLocaleUpperCase() + property.substring( 1 ); values = params[ property ]; if ( typeof parser[ funcName ] === 'function' ) { parser[ funcName ]( values ); } else if ( parser.hasOwnProperty( property ) ) { parser[ property ] = values; } } }
javascript
{ "resource": "" }
q48064
train
function ( payload ) { if ( payload.cmd === 'run' ) { var self = this.getParentScope(); var callbacks = { callbackOnAssetAvailable: function ( payload ) { self.postMessage( payload ); }, callbackOnProgress: function ( text ) { if ( payload.logging.enabled && payload.logging.debug ) console.debug( 'WorkerRunner: progress: ' + text ); } }; // Parser is expected to be named as such var parser = new Parser(); if ( typeof parser[ 'setLogging' ] === 'function' ) parser.setLogging( payload.logging.enabled, payload.logging.debug ); this.applyProperties( parser, payload.params ); this.applyProperties( parser, payload.materials ); this.applyProperties( parser, callbacks ); parser.workerScope = self; parser.parse( payload.data.input, payload.data.options ); if ( payload.logging.enabled ) console.log( 'WorkerRunner: Run complete!' ); callbacks.callbackOnAssetAvailable( { cmd: 'complete', msg: 'WorkerRunner completed run.' } ); } else { console.error( 'WorkerRunner: Received unknown command: ' + payload.cmd ); } }
javascript
{ "resource": "" }
q48065
train
function ( url, onLoad, onProgress, onError, onMeshAlter, useAsync ) { var resource = new THREE.LoaderSupport.ResourceDescriptor( url, 'OBJ' ); this._loadObj( resource, onLoad, onProgress, onError, onMeshAlter, useAsync ); }
javascript
{ "resource": "" }
q48066
train
function ( prepData, workerSupportExternal ) { this._applyPrepData( prepData ); var available = prepData.checkResourceDescriptorFiles( prepData.resources, [ { ext: "obj", type: "ArrayBuffer", ignore: false }, { ext: "mtl", type: "String", ignore: false }, { ext: "zip", type: "String", ignore: true } ] ); if ( THREE.LoaderSupport.Validator.isValid( workerSupportExternal ) ) { this.terminateWorkerOnLoad = false; this.workerSupport = workerSupportExternal; this.logging.enabled = this.workerSupport.logging.enabled; this.logging.debug = this.workerSupport.logging.debug; } var scope = this; var onMaterialsLoaded = function ( materials ) { if ( materials !== null ) scope.meshBuilder.setMaterials( materials ); scope._loadObj( available.obj, scope.callbacks.onLoad, null, null, scope.callbacks.onMeshAlter, prepData.useAsync ); }; this._loadMtl( available.mtl, onMaterialsLoaded, null, null, prepData.crossOrigin, prepData.materialOptions ); }
javascript
{ "resource": "" }
q48067
train
function ( content ) { // fast-fail in case of illegal data if ( content === null || content === undefined ) { throw 'Provided content is not a valid ArrayBuffer or String. Unable to continue parsing'; } if ( this.logging.enabled ) console.time( 'OBJLoader2 parse: ' + this.modelName ); this.meshBuilder.init(); var parser = new THREE.OBJLoader2.Parser(); parser.setLogging( this.logging.enabled, this.logging.debug ); parser.setMaterialPerSmoothingGroup( this.materialPerSmoothingGroup ); parser.setUseOAsMesh( this.useOAsMesh ); parser.setUseIndices( this.useIndices ); parser.setDisregardNormals( this.disregardNormals ); // sync code works directly on the material references parser.setMaterials( this.meshBuilder.getMaterials() ); var scope = this; var onMeshLoaded = function ( payload ) { var meshes = scope.meshBuilder.processPayload( payload ); var mesh; for ( var i in meshes ) { mesh = meshes[ i ]; scope.loaderRootNode.add( mesh ); } }; parser.setCallbackOnAssetAvailable( onMeshLoaded ); var onProgressScoped = function ( text, numericalValue ) { scope.onProgress( 'progressParse', text, numericalValue ); }; parser.setCallbackOnProgress( onProgressScoped ); var onErrorScoped = function ( message ) { scope._onError( message ); }; parser.setCallbackOnError( onErrorScoped ); if ( content instanceof ArrayBuffer || content instanceof Uint8Array ) { if ( this.logging.enabled ) console.info( 'Parsing arrayBuffer...' ); parser.parse( content ); } else if ( typeof( content ) === 'string' || content instanceof String ) { if ( this.logging.enabled ) console.info( 'Parsing text...' ); parser.parseText( content ); } else { this._onError( 'Provided content was neither of type String nor Uint8Array! Aborting...' ); } if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2 parse: ' + this.modelName ); return this.loaderRootNode; }
javascript
{ "resource": "" }
q48068
train
function ( content, onLoad ) { var scope = this; var measureTime = false; var scopedOnLoad = function () { onLoad( { detail: { loaderRootNode: scope.loaderRootNode, modelName: scope.modelName, instanceNo: scope.instanceNo } } ); if ( measureTime && scope.logging.enabled ) console.timeEnd( 'OBJLoader2 parseAsync: ' + scope.modelName ); }; // fast-fail in case of illegal data if ( content === null || content === undefined ) { throw 'Provided content is not a valid ArrayBuffer or String. Unable to continue parsing'; } else { measureTime = true; } if ( measureTime && this.logging.enabled ) console.time( 'OBJLoader2 parseAsync: ' + this.modelName ); this.meshBuilder.init(); var scopedOnMeshLoaded = function ( payload ) { var meshes = scope.meshBuilder.processPayload( payload ); var mesh; for ( var i in meshes ) { mesh = meshes[ i ]; scope.loaderRootNode.add( mesh ); } }; var buildCode = function ( codeSerializer ) { var workerCode = ''; workerCode += '/**\n'; workerCode += ' * This code was constructed by OBJLoader2 buildCode.\n'; workerCode += ' */\n\n'; workerCode += 'THREE = { LoaderSupport: {}, OBJLoader2: {} };\n\n'; workerCode += codeSerializer.serializeClass( 'THREE.OBJLoader2.Parser', THREE.OBJLoader2.Parser ); return workerCode; }; this.workerSupport.validate( buildCode, 'THREE.OBJLoader2.Parser' ); this.workerSupport.setCallbacks( scopedOnMeshLoaded, scopedOnLoad ); if ( scope.terminateWorkerOnLoad ) this.workerSupport.setTerminateRequested( true ); var materialNames = {}; var materials = this.meshBuilder.getMaterials(); for ( var materialName in materials ) { materialNames[ materialName ] = materialName; } this.workerSupport.run( { params: { useAsync: true, materialPerSmoothingGroup: this.materialPerSmoothingGroup, useOAsMesh: this.useOAsMesh, useIndices: this.useIndices, disregardNormals: this.disregardNormals }, logging: { enabled: this.logging.enabled, debug: this.logging.debug }, materials: { // in async case only material names are supplied to parser materials: materialNames }, data: { input: content, options: null } } ); }
javascript
{ "resource": "" }
q48069
train
function ( url, content, onLoad, onProgress, onError, crossOrigin, materialOptions ) { var resource = new THREE.LoaderSupport.ResourceDescriptor( url, 'MTL' ); resource.setContent( content ); this._loadMtl( resource, onLoad, onProgress, onError, crossOrigin, materialOptions ); }
javascript
{ "resource": "" }
q48070
train
function ( arrayBuffer ) { if ( this.logging.enabled ) console.time( 'OBJLoader2.Parser.parse' ); this.configure(); var arrayBufferView = new Uint8Array( arrayBuffer ); this.contentRef = arrayBufferView; var length = arrayBufferView.byteLength; this.globalCounts.totalBytes = length; var buffer = new Array( 128 ); for ( var code, word = '', bufferPointer = 0, slashesCount = 0, i = 0; i < length; i++ ) { code = arrayBufferView[ i ]; switch ( code ) { // space case 32: if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; word = ''; break; // slash case 47: if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; slashesCount++; word = ''; break; // LF case 10: if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; word = ''; this.globalCounts.lineByte = this.globalCounts.currentByte; this.globalCounts.currentByte = i; this.processLine( buffer, bufferPointer, slashesCount ); bufferPointer = 0; slashesCount = 0; break; // CR case 13: break; default: word += String.fromCharCode( code ); break; } } this.finalizeParsing(); if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2.Parser.parse' ); }
javascript
{ "resource": "" }
q48071
train
function ( text ) { if ( this.logging.enabled ) console.time( 'OBJLoader2.Parser.parseText' ); this.configure(); this.legacyMode = true; this.contentRef = text; var length = text.length; this.globalCounts.totalBytes = length; var buffer = new Array( 128 ); for ( var char, word = '', bufferPointer = 0, slashesCount = 0, i = 0; i < length; i++ ) { char = text[ i ]; switch ( char ) { case ' ': if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; word = ''; break; case '/': if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; slashesCount++; word = ''; break; case '\n': if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; word = ''; this.globalCounts.lineByte = this.globalCounts.currentByte; this.globalCounts.currentByte = i; this.processLine( buffer, bufferPointer, slashesCount ); bufferPointer = 0; slashesCount = 0; break; case '\r': break; default: word += char; } } this.finalizeParsing(); if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2.Parser.parseText' ); }
javascript
{ "resource": "" }
q48072
train
function () { var meshOutputGroupTemp = []; var meshOutputGroup; var absoluteVertexCount = 0; var absoluteIndexMappingsCount = 0; var absoluteIndexCount = 0; var absoluteColorCount = 0; var absoluteNormalCount = 0; var absoluteUvCount = 0; var indices; for ( var name in this.rawMesh.subGroups ) { meshOutputGroup = this.rawMesh.subGroups[ name ]; if ( meshOutputGroup.vertices.length > 0 ) { indices = meshOutputGroup.indices; if ( indices.length > 0 && absoluteIndexMappingsCount > 0 ) { for ( var i in indices ) indices[ i ] = indices[ i ] + absoluteIndexMappingsCount; } meshOutputGroupTemp.push( meshOutputGroup ); absoluteVertexCount += meshOutputGroup.vertices.length; absoluteIndexMappingsCount += meshOutputGroup.indexMappingsCount; absoluteIndexCount += meshOutputGroup.indices.length; absoluteColorCount += meshOutputGroup.colors.length; absoluteUvCount += meshOutputGroup.uvs.length; absoluteNormalCount += meshOutputGroup.normals.length; } } // do not continue if no result var result = null; if ( meshOutputGroupTemp.length > 0 ) { result = { name: this.rawMesh.groupName !== '' ? this.rawMesh.groupName : this.rawMesh.objectName, subGroups: meshOutputGroupTemp, absoluteVertexCount: absoluteVertexCount, absoluteIndexCount: absoluteIndexCount, absoluteColorCount: absoluteColorCount, absoluteNormalCount: absoluteNormalCount, absoluteUvCount: absoluteUvCount, faceCount: this.rawMesh.counts.faceCount, doubleIndicesCount: this.rawMesh.counts.doubleIndicesCount }; } return result; }
javascript
{ "resource": "" }
q48073
train
function () { var materialsJSON = {}; var material; for ( var materialName in this.materials ) { material = this.materials[ materialName ]; materialsJSON[ materialName ] = material.toJSON(); } return materialsJSON; }
javascript
{ "resource": "" }
q48074
train
function ( globalCallbacks, maxQueueSize, maxWebWorkers ) { if ( THREE.LoaderSupport.Validator.isValid( globalCallbacks ) ) this.workerDescription.globalCallbacks = globalCallbacks; this.maxQueueSize = Math.min( maxQueueSize, THREE.LoaderSupport.WorkerDirector.MAX_QUEUE_SIZE ); this.maxWebWorkers = Math.min( maxWebWorkers, THREE.LoaderSupport.WorkerDirector.MAX_WEB_WORKER ); this.maxWebWorkers = Math.min( this.maxWebWorkers, this.maxQueueSize ); this.objectsCompleted = 0; this.instructionQueue = []; this.instructionQueuePointer = 0; for ( var instanceNo = 0; instanceNo < this.maxWebWorkers; instanceNo++ ) { var workerSupport = new THREE.LoaderSupport.WorkerSupport(); workerSupport.setLogging( this.logging.enabled, this.logging.debug ); workerSupport.setForceWorkerDataCopy( this.workerDescription.forceWorkerDataCopy ); this.workerDescription.workerSupports[ instanceNo ] = { instanceNo: instanceNo, inUse: false, terminateRequested: false, workerSupport: workerSupport, loader: null }; } }
javascript
{ "resource": "" }
q48075
train
function () { var wsKeys = Object.keys( this.workerDescription.workerSupports ); return ( ( this.instructionQueue.length > 0 && this.instructionQueuePointer < this.instructionQueue.length ) || wsKeys.length > 0 ); }
javascript
{ "resource": "" }
q48076
train
function () { var prepData, supportDesc; for ( var instanceNo in this.workerDescription.workerSupports ) { supportDesc = this.workerDescription.workerSupports[ instanceNo ]; if ( ! supportDesc.inUse ) { if ( this.instructionQueuePointer < this.instructionQueue.length ) { prepData = this.instructionQueue[ this.instructionQueuePointer ]; this._kickWorkerRun( prepData, supportDesc ); this.instructionQueuePointer++; } else { this._deregister( supportDesc ); } } } if ( ! this.isRunning() && this.callbackOnFinishedProcessing !== null ) { this.callbackOnFinishedProcessing(); this.callbackOnFinishedProcessing = null; } }
javascript
{ "resource": "" }
q48077
train
function ( callbackOnFinishedProcessing ) { if ( this.logging.enabled ) console.info( 'WorkerDirector received the deregister call. Terminating all workers!' ); this.instructionQueuePointer = this.instructionQueue.length; this.callbackOnFinishedProcessing = THREE.LoaderSupport.Validator.verifyInput( callbackOnFinishedProcessing, null ); for ( var name in this.workerDescription.workerSupports ) { this.workerDescription.workerSupports[ name ].terminateRequested = true; } }
javascript
{ "resource": "" }
q48078
train
function ( item ) { // function to obtain the URL of the thumbnail image var href; if (item.element) { href = $(item.element).find('img').attr('src'); } if (!href && item.type === 'image' && item.href) { href = item.href; } return href; }
javascript
{ "resource": "" }
q48079
train
function( url, rez, params ) { params = params || ''; if ( $.type( params ) === "object" ) { params = $.param(params, true); } $.each(rez, function(key, value) { url = url.replace( '$' + key, value || '' ); }); if (params.length) { url += ( url.indexOf('?') > 0 ? '&' : '?' ) + params; } return url; }
javascript
{ "resource": "" }
q48080
createMongoosePromise
train
function createMongoosePromise(resolver) { var promise // mongoose 5 and up if (parseInt(mongoose.version) >= 5) { promise = new mongoose.Promise(resolver) } // mongoose 4.1 and up else if (mongoose.Promise.ES6) { promise = new mongoose.Promise.ES6(resolver) } // backward compatibility else { promise = new mongoose.Promise resolver(promise.resolve.bind(promise, null), promise.reject.bind(promise)) } return promise }
javascript
{ "resource": "" }
q48081
deepPopulatePlugin
train
function deepPopulatePlugin(schema, defaultOptions) { schema._defaultDeepPopulateOptions = defaultOptions = defaultOptions || {} /** * Populates this document with the specified paths. * @param paths the paths to be populated. * @param options (optional) the population options. * @param cb (optional) the callback. * @return {MongoosePromise} */ schema.methods.deepPopulate = function (paths, options, cb) { return deepPopulate(this.constructor, this, paths, options, cb) } /** * Populates provided documents with the specified paths. * @param docs the documents to be populated. * @param paths the paths to be populated. * @param options (optional) the population options. * @param cb (optional) the callback. * @return {MongoosePromise} */ schema.statics.deepPopulate = function (docs, paths, options, cb) { return deepPopulate(this, docs, paths, options, cb) } function deepPopulate(model, docs, paths, options, cb) { if (isFunction(options)) { cb = options options = null } else { cb = cb || noop } return createMongoosePromise(function (resolve, reject) { if (docs == null || docs.length === 0) { return resolve(docs), cb(null, docs) } execute(model, docs, paths, options, defaultOptions, false, function (err, docs) { if (err) reject(err), cb(err) else resolve(docs), cb(null, docs) }) }) } }
javascript
{ "resource": "" }
q48082
findPossibleIndexes
train
function findPossibleIndexes(code, identifiers, filter) { const possibleIndexes = []; if (identifiers.length === 0) { return possibleIndexes; } const pattern = new RegExp( "\\b(?:" + identifiers.join("|") + ")\\b", "g" ); let match; pattern.lastIndex = 0; while ((match = pattern.exec(code))) { if (typeof filter !== "function" || filter(match)) { possibleIndexes.push(match.index); } } return possibleIndexes; }
javascript
{ "resource": "" }
q48083
moduleExport
train
function moduleExport(getters, constant) { utils.setESModule(this.exports); var entry = Entry.getOrCreate(this.id, this); entry.addGetters(getters, constant); if (this.loaded) { // If the module has already been evaluated, then we need to trigger // another round of entry.runSetters calls, which begins by calling // entry.runModuleGetters(module). entry.runSetters(); } }
javascript
{ "resource": "" }
q48084
nodeModules
train
function nodeModules() { return fs.readdirSync('node_modules') .filter(dir => ['.bin'].indexOf(dir) === -1) .reduce((modules, m) => { modules[m] = 'commonjs2 ' + m return modules }, {}) }
javascript
{ "resource": "" }
q48085
train
function (seq, begin, end) { var sliced = seq.reduce( function (state, chunk) { var index = state.index; if (chunk instanceof Token) { var code = sgr.extractCode(chunk.token); if (index <= begin) { if (code in sgr.openers) { sgr.openStyle(state.preOpeners, code); } if (code in sgr.closers) { sgr.closeStyle(state.preOpeners, code); } } else if (index < end) { if (code in sgr.openers) { sgr.openStyle(state.inOpeners, code); state.seq.push(chunk); } else if (code in sgr.closers) { state.inClosers.push(code); state.seq.push(chunk); } } } else { var nextChunk = ""; if (isChunkInSlice(chunk, index, begin, end)) { var relBegin = Math.max(begin - index, 0) , relEnd = Math.min(end - index, chunk.length); nextChunk = chunk.slice(relBegin, relEnd); } state.seq.push(nextChunk); state.index = index + chunk.length; } return state; }, { index: 0, seq: [], // preOpeners -> [ mod ] // preOpeners must be prepended to the slice if they wasn't closed til the end of it // preOpeners must be closed if they wasn't closed til the end of the slice preOpeners: [], // inOpeners -> [ mod ] // inOpeners already in the slice and must not be prepended to the slice // inOpeners must be closed if they wasn't closed til the end of the slice inOpeners: [], // opener CSI inside slice // inClosers -> [ code ] // closer CSIs for determining which pre/in-Openers must be closed inClosers: [] } ); sliced.seq = [].concat( sgr.prepend(sliced.preOpeners), sliced.seq, sgr.complete([].concat(sliced.preOpeners, sliced.inOpeners), sliced.inClosers) ); return sliced.seq; }
javascript
{ "resource": "" }
q48086
transform
train
function transform({ babel, filename, documentFilename }) { if (!filename) { throw new Error( `You must pass a filename to importMDX(). Please see the mdx.macro documentation`, ) } let documentPath = path.join(filename, '..', documentFilename); let imports = `import React from 'react'\nimport { MDXTag } from '@mdx-js/tag'\n` // In development mode, we want to import the original document so that // changes will be picked up and cause a re-build. // Note: this relies on files with macros *not* being cached by babel. if (process.env.NODE_ENV === "development") { imports += `import '${documentPath}'\n` } let source = fs.readFileSync(documentPath, 'utf8'); let transformedSource = babel.transformSync( imports+mdx.sync(source), { presets: [babelPresetReactApp], filename: documentPath, }, ).code return writeTempFile(documentPath, transformedSource) }
javascript
{ "resource": "" }
q48087
parseJSXContent
train
function parseJSXContent(state, start, type) { var text, result, max = state.posMax, prevPos, oldPos = state.pos; state.pos = start; while (state.pos < max) { text = state.src.slice(state.pos) result = JSX_INLINE_CLOSE_TAG_PARSER.parse(text) prevPos = state.pos; state.md.inline.skipToken(state); if (result.status && result.value.value === type && prevPos === state.pos - 1) { // restore old state state.pos = oldPos; return { contentEnd: prevPos, closeEnd: prevPos + result.value.end.offset } } } // restore old state state.pos = oldPos; }
javascript
{ "resource": "" }
q48088
checkLinks
train
function checkLinks (transaction, record, fields, links, meta) { var Promise = promise.Promise var enforceLinks = this.options.settings.enforceLinks return Promise.all(map(links, function (field) { var ids = Array.isArray(record[field]) ? record[field] : !record.hasOwnProperty(field) || record[field] === null ? [] : [ record[field] ] var fieldLink = fields[field][linkKey] var fieldInverse = fields[field][inverseKey] var findOptions = { fields: {} } // Don't need the entire records. findOptions.fields[fieldInverse] = true return new Promise(function (resolve, reject) { if (!ids.length) return resolve() return transaction.find(fieldLink, ids, findOptions, meta) .then(function (records) { var recordIds, i, j if (enforceLinks) { recordIds = unique(map(records, function (record) { return record[primaryKey] })) for (i = 0, j = ids.length; i < j; i++) if (!includes(recordIds, ids[i])) return reject(new BadRequestError( message('RelatedRecordNotFound', meta.language, { field: field }) )) } return resolve(records) }) }) })) .then(function (partialRecords) { var object = {}, records, i, j for (i = 0, j = partialRecords.length; i < j; i++) { records = partialRecords[i] if (records) object[links[i]] = fields[links[i]][isArrayKey] ? records : records[0] } return object }) }
javascript
{ "resource": "" }
q48089
validateUpdates
train
function validateUpdates (updates, meta) { var language = meta.language var i, j, update if (!updates || !updates.length) throw new BadRequestError( message('UpdateRecordsInvalid', language)) for (i = 0, j = updates.length; i < j; i++) { update = updates[i] if (!update[primaryKey]) throw new BadRequestError( message('UpdateRecordMissingID', language)) } }
javascript
{ "resource": "" }
q48090
AdapterSingleton
train
function AdapterSingleton (properties) { var CustomAdapter, input input = Array.isArray(properties.adapter) ? properties.adapter : [ properties.adapter ] if (typeof input[0] !== 'function') throw new TypeError('The adapter must be a function.') CustomAdapter = Adapter.prototype .isPrototypeOf(input[0].prototype) ? input[0] : input[0](Adapter) if (!Adapter.prototype.isPrototypeOf(CustomAdapter.prototype)) throw new TypeError('The adapter must inherit the Adapter class.') return new CustomAdapter({ options: input[1] || {}, recordTypes: properties.recordTypes, features: CustomAdapter.features, common: common, errors: errors, keys: keys, message: properties.message, Promise: promise.Promise }) }
javascript
{ "resource": "" }
q48091
validateField
train
function validateField (fields, key) { var value = fields[key] = castShorthand(fields[key]) if (typeof value !== 'object') throw new TypeError('The definition of "' + key + '" must be an object.') if (key === primaryKey) throw new Error('Can not define primary key "' + primaryKey + '".') if (key in plainObject) throw new Error('Can not define field name "' + key + '" which is in Object.prototype.') if (!value[typeKey] && !value[linkKey]) throw new Error('The definition of "' + key + '" must contain either ' + 'the "' + typeKey + '" or "' + linkKey + '" property.') if (value[typeKey] && value[linkKey]) throw new Error('Can not define both "' + typeKey + '" and "' + linkKey + '" on "' + key + '".') if (value[typeKey]) { if (typeof value[typeKey] === 'string') value[typeKey] = nativeTypes[ stringifiedTypes.indexOf(value[typeKey].toLowerCase())] if (typeof value[typeKey] !== 'function') throw new Error('The "' + typeKey + '" on "' + key + '" must be a function.') if (!find(nativeTypes, function (type) { var hasMatch = type === value[typeKey] || type.name === value[typeKey].name // In case this errors due to security sandboxing, just skip this check. if (!hasMatch) try { hasMatch = Object.create(value[typeKey]) instanceof type } catch (e) { hasMatch = true } return hasMatch })) throw new Error('The "' + typeKey + '" on "' + key + '" must be or ' + 'inherit from a valid native type.') if (value[inverseKey]) throw new Error('The field "' + inverseKey + '" may not be defined ' + 'on "' + key + '".') } if (value[linkKey]) { if (typeof value[linkKey] !== 'string') throw new TypeError('The "' + linkKey + '" on "' + key + '" must be a string.') if (value[inverseKey] && typeof value[inverseKey] !== 'string') throw new TypeError('The "' + inverseKey + '" on "' + key + '" ' + 'must be a string.') } if (value[isArrayKey] && typeof value[isArrayKey] !== 'boolean') throw new TypeError('The key "' + isArrayKey + '" on "' + key + '" ' + 'must be a boolean.') }
javascript
{ "resource": "" }
q48092
castShorthand
train
function castShorthand (value) { var obj if (typeof value === 'string') obj = { link: value } else if (typeof value === 'function') obj = { type: value } else if (Array.isArray(value)) { obj = {} if (value[1]) obj.inverse = value[1] else obj.isArray = true // Extract type or link. if (Array.isArray(value[0])) { obj.isArray = true value = value[0][0] } else value = value[0] if (typeof value === 'string') obj.link = value else if (typeof value === 'function') obj.type = value } else return value return obj }
javascript
{ "resource": "" }
q48093
message
train
function message (id, language, data) { var genericMessage = 'GenericError' var self = this || message var str, key, subtag if (!self.hasOwnProperty(language)) { subtag = language && language.match(/.+?(?=-)/) if (subtag) subtag = subtag[0] if (self.hasOwnProperty(subtag)) language = subtag else language = self.defaultLanguage } str = self[language].hasOwnProperty(id) ? self[language][id] : self[language][genericMessage] || self.en[genericMessage] if (typeof str === 'string') for (key in data) str = str.replace('{' + key + '}', data[key]) if (typeof str === 'function') str = str(data) return str }
javascript
{ "resource": "" }
q48094
deepEqual
train
function deepEqual (a, b) { var key, value, compare, aLength = 0, bLength = 0 // If they are the same object, don't need to go further. if (a === b) return true // Both objects must be defined. if (!a || !b) return false // Objects must be of the same type. if (a.prototype !== b.prototype) return false for (key in a) { aLength++ value = a[key] compare = b[key] if (typeof value === 'object') { if (typeof compare !== 'object' || !deepEqual(value, compare)) return false continue } if (Buffer.isBuffer(value)) { if (!Buffer.isBuffer(compare) || !value.equals(compare)) return false continue } if (value && typeof value.getTime === 'function') { if (!compare || typeof compare.getTime !== 'function' || value.getTime() !== compare.getTime()) return false continue } if (value !== compare) return false } for (key in b) bLength++ // Keys must be of same length. return aLength === bLength }
javascript
{ "resource": "" }
q48095
createIndices
train
function createIndices(callback) { const q = queue(); geojson_files.forEach((gj) => { q.defer(createIndex, gj); }); q.awaitAll((err) => { if (err) return callback(err); return callback(); }); }
javascript
{ "resource": "" }
q48096
archiveOriginal
train
function archiveOriginal(callback) { const archivedOriginal = path.join(outdirectory, '/archived.kml'); const infileContents = fs.readFileSync(infile); fs.writeFile(archivedOriginal, infileContents, (err) => { if (err) return callback(err); return callback(); }); }
javascript
{ "resource": "" }
q48097
applicable
train
function applicable(filepath, info, callback) { const q = queue(); preprocessors.forEach((preprocessor) => { q.defer(preprocessor.criteria, filepath, info); }); q.awaitAll((err, results) => { if (err) return callback(err); callback(null, preprocessors.filter((preprocessor, i) => { return !!results[i]; })); }); }
javascript
{ "resource": "" }
q48098
descriptions
train
function descriptions(filepath, info, callback) { applicable(filepath, info, (err, preprocessors) => { if (err) return callback(err); callback(null, preprocessors.map((preprocessor) => { return preprocessor.description; })); }); }
javascript
{ "resource": "" }
q48099
newfile
train
function newfile(filepath) { let dir = path.dirname(filepath); if (path.extname(filepath) === '.shp') dir = path.resolve(dir, '..'); const name = crypto.randomBytes(8).toString('hex'); return path.join(dir, name); }
javascript
{ "resource": "" }