_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q31800
polygonize
train
function polygonize (str, properties) { var coordinates = str.split(' ').map(function (pairStr) { return pairStr.split(',').reverse().map(Number); }); return polygon([coordinates], properties); }
javascript
{ "resource": "" }
q31801
decodify
train
function decodify (featureCollection, code, properties) { var feature = find(featureCollection.features, {'id': code}); if (feature) { feature.properties = properties; } return feature; }
javascript
{ "resource": "" }
q31802
toCSSProp
train
function toCSSProp(prop) { var dashed = prop.replace(regex, '-$&').toLowerCase(); return dashed[0] === 'm' && dashed[1] === 's' ? '-' + dashed : dashed; }
javascript
{ "resource": "" }
q31803
reduceFunctionCall
train
function reduceFunctionCall(string, functionRE, callback) { var call = string return getFunctionCalls(string, functionRE).reduce(function(string, obj) { return string.replace(obj.functionIdentifier + "(" + obj.matches.body + ")", evalFunctionCall(obj.matches.body, obj.functionIdentifier, callback, call, functionRE)) }, string) }
javascript
{ "resource": "" }
q31804
getFunctionCalls
train
function getFunctionCalls(call, functionRE) { var expressions = [] var fnRE = typeof functionRE === "string" ? new RegExp("\\b(" + functionRE + ")\\(") : functionRE do { var searchMatch = fnRE.exec(call) if (!searchMatch) { return expressions } if (searchMatch[1] === undefined) { throw new Error("Missing the first couple of parenthesis to get the function identifier in " + functionRE) } var fn = searchMatch[1] var startIndex = searchMatch.index var matches = balanced("(", ")", call.substring(startIndex)) if (!matches || matches.start !== searchMatch[0].length - 1) { throw new SyntaxError(fn + "(): missing closing ')' in the value '" + call + "'") } expressions.push({matches: matches, functionIdentifier: fn}) call = matches.post } while (fnRE.test(call)) return expressions }
javascript
{ "resource": "" }
q31805
evalFunctionCall
train
function evalFunctionCall (string, functionIdentifier, callback, call, functionRE) { // allow recursivity return callback(reduceFunctionCall(string, functionRE, callback), functionIdentifier, call) }
javascript
{ "resource": "" }
q31806
space
train
function space(json) { var match = json.match(/^(?:(\t+)|( +))"/m) return match ? (match[1] ? '\t' : match[2].length) : '' }
javascript
{ "resource": "" }
q31807
mergeInto
train
function mergeInto(one, two) { checkMergeObjectArg(one); if (two != null) { checkMergeObjectArg(two); for (var key in two) { if (!two.hasOwnProperty(key)) { continue; } one[key] = two[key]; } } }
javascript
{ "resource": "" }
q31808
getRawRequest
train
function getRawRequest ( { resource, loaderIndex, loaders }, excludedPreLoaders = /eslint-loader/ ) { return loaderUtils.getRemainingRequest({ resource: resource, loaderIndex: loaderIndex, loaders: loaders.filter(loader => !excludedPreLoaders.test(loader.path)) }) }
javascript
{ "resource": "" }
q31809
stringifyLoaders
train
function stringifyLoaders (loaders) { return loaders .map( obj => obj && typeof obj === 'object' && typeof obj.loader === 'string' ? obj.loader + (obj.options ? '?' + JSON.stringify(obj.options) : '') : obj ) .join('!') }
javascript
{ "resource": "" }
q31810
_hash
train
function _hash() { var set = Array.prototype.map.call(arguments, function(v) { return typeof v === 'string' ? v : Object.keys(v).join(' '); }).join(' '); return set.split(/\s+/) .reduce(function(res, keyword) { res[keyword] = true; return res; }, {}); }
javascript
{ "resource": "" }
q31811
matchRoute
train
function matchRoute(route, path) { if (route.pattern === undefined && route.path !== undefined) { var routePattern; if (route.path instanceof RegExp) { routePattern = route.path; } else { var routePath = normalize(route.path); routePattern = route.children.length > 0 ? routePath + '*' : routePath; } Object.defineProperty(route, 'pattern', { enumerable: false, value: pattern.newPattern(routePattern) }); } if (route.pattern) { var match = route.pattern.match(path); if (match) { if (route.pattern.isRegex) { match = {_: match}; } if (!match._ || match._[0] === '/' || match._[0] === '') { delete match._; } } return match; } else { return path === '/' || path === '' ? {} : {_: [path]}; } }
javascript
{ "resource": "" }
q31812
matchRoutes
train
function matchRoutes(routes, path, query) { query = query === undefined ? {} : isString(query) ? qs.parse(query) : query; return matchRoutesImpl(routes, path, query); }
javascript
{ "resource": "" }
q31813
AsyncHelpers
train
function AsyncHelpers(options) { if (!(this instanceof AsyncHelpers)) { return new AsyncHelpers(options); } this.options = Object.assign({}, options); this.prefix = this.options.prefix || '{$ASYNCID$'; this.globalCounter = AsyncHelpers.globalCounter++; this.helpers = {}; this.counter = 0; this.prefixRegex = toRegex(this.prefix); }
javascript
{ "resource": "" }
q31814
wrapper
train
function wrapper() { var num = self.counter++; var id = createId(prefix, num); var token = { name: name, async: !!fn.async, prefix: prefix, num: num, id: id, fn: fn, args: [].slice.call(arguments) }; define(token, 'context', this); stash[id] = token; return id; }
javascript
{ "resource": "" }
q31815
formatError
train
function formatError(err, helper, args) { err.helper = helper; define(err, 'args', args); return err; }
javascript
{ "resource": "" }
q31816
toRegex
train
function toRegex(prefix) { var key = appendPrefix(prefix, '(\\d+)'); if (cache.hasOwnProperty(key)) { return cache[key]; } var regex = new RegExp(createRegexString(key), 'g'); cache[key] = regex; return regex; }
javascript
{ "resource": "" }
q31817
createRegexString
train
function createRegexString(prefix) { var key = 'createRegexString:' + prefix; if (cache.hasOwnProperty(key)) { return cache[key]; } var str = (prefix + '(\\d+)$}').replace(/\\?([${}])/g, '\\$1'); cache[key] = str; return str; }
javascript
{ "resource": "" }
q31818
getCss
train
function getCss(shapes, options) { const spriteRelative = path.relative(options.styleOutput, options.spritePath); return new CSS(shapes, { nameSpace: options.nameSpace, block: options.dirname, separator: options.cssSeparator, spriteRelative: path.normalize(spriteRelative).replace(/\\/g, '/') }).getCss(); }
javascript
{ "resource": "" }
q31819
_isSvgFile
train
function _isSvgFile(file, dirPath) { let flag = false, isFile = fs.statSync(path.resolve(dirPath, file)).isFile(); if (isFile) { // Exclude directory if (path.extname(file) === '.svg') { // Only accept files which with svg suffix flag = true; } } return flag; }
javascript
{ "resource": "" }
q31820
log
train
function log(msg, type) { switch (type) { case 'error': fancyLog(`${PLUGINNAME}: ${colors.red(`Error, ${msg}`)}`); break; case 'warn': fancyLog(`${PLUGINNAME}: ${colors.yellow(`Warning, ${msg}`)}`); break; case 'info': fancyLog(`${PLUGINNAME}: ${colors.green(`Info, ${msg}`)}`); break; default: fancyLog(`${PLUGINNAME}: ${colors.green(`Info, ${msg}`)}`); break; } }
javascript
{ "resource": "" }
q31821
parseProcesses
train
function parseProcesses(list, ps) { var p = ps.split(/ +/); list.push({ user: p[0], pid: p[1], cpu: parseFloat(p[2]), mem: parseFloat(p[3]), vsz: p[4], rss: p[5], tt: p[6], stat: p[7], started: p[8], time: p[9], command: p.slice(10).join(' ') }); return list; }
javascript
{ "resource": "" }
q31822
cleanValue
train
function cleanValue(val, char) { var num; var conditions = val.split(' '); var i = 0; while (!num && i < conditions.length) { if (conditions[i].indexOf(char) > -1) { num = conditions[i].replace(/<|>|~/g, ''); } i++; } return parseFloat(num); }
javascript
{ "resource": "" }
q31823
ancestorMatch
train
function ancestorMatch(el, tokens, dividedTokens, root) { var cand // recursively work backwards through the tokens and up the dom, covering all options function crawl(e, i, p) { while (p = walker[dividedTokens[i]](p, e)) { if (isNode(p) && (found = interpret.apply(p, q(tokens[i])))) { if (i) { if (cand = crawl(p, i - 1, p)) return cand } else return p } } } return (cand = crawl(el, tokens.length - 1, el)) && (!root || isAncestor(cand, root)) }
javascript
{ "resource": "" }
q31824
train
function(callback) { async.each(task.files, function(file, callback2) { var srcPath = file.src[0], extName = path.extname(srcPath).toLowerCase(); // if it’s an SVG or a PDF, copy the file to the output dir if (extName === '.svg' || extName === '.pdf') { var dstPath = getDestination(srcPath, file.dest, false, options); fs.copy(srcPath, dstPath, function(err){ if (err) { grunt.fail.fatal(err); } outputFiles.push(dstPath); callback2(null); }); } else { callback2(null); } }, callback); }
javascript
{ "resource": "" }
q31825
train
function(response) { delete self._requestState[transactionId]; if (typeof callback === 'function') { // negative response if (response.error) { var owner = response.answerRecords[0].nb.entries[0].address; callback(null, false, owner); // positive response } else { // ignore as this should not happen for 'broadcast' nodes } } }
javascript
{ "resource": "" }
q31826
train
function() { delete self._requestState[transactionId]; self._localMap.add(nbname, group, address, ttl, self._type); self._sendRefresh(nbname, function(error) { if (typeof callback === 'function') { callback(error, !error); } }); }
javascript
{ "resource": "" }
q31827
getWatcherByPath
train
function getWatcherByPath(path) { var rlt = undefined; watchers.forEach(function(watcher) { if (watcher.path == path) rlt = watcher; }); return rlt; }
javascript
{ "resource": "" }
q31828
makeViewFactoryForMatch
train
function makeViewFactoryForMatch(match) { var views = {}; for (var i = match.activeTrace.length - 1; i >= 0; i--) { var step = match.activeTrace[i]; var stepProps = getStepProps(step); views = merge(views, collectSubViews(stepProps, views)); if (step.route.view !== undefined) { return makeViewFactory(step.route.view, merge(stepProps, views)); } } }
javascript
{ "resource": "" }
q31829
AsyncRoute
train
function AsyncRoute(props) { props = merge(props, { viewPromise: loadViewModule, viewModule: props.view, view: undefined }) return Route(props); }
javascript
{ "resource": "" }
q31830
CanIHazIp
train
function CanIHazIp(callback) { return new Promise(function (resolve) { var httpCallback = function (response) { var responseData = ''; // When data is received, append it to `responseData`. response.on('data', function (chunk) { responseData += chunk; }); // When response ends, resolve returned Promise and call `callback` if it's a function. response.on('end', function () { resolve(responseData); if (typeof callback === 'function') { callback(responseData); } }); }; // Connect options for canihazip API, GET method is implicit. var canihazipOptions = { host: 'canihazip.com', path: '/s' }; // Make a request to canihazip and end it immediately. protocol.request(canihazipOptions, httpCallback) .end(); }); }
javascript
{ "resource": "" }
q31831
mapDependencyData
train
function mapDependencyData(bowerInfo) { return { name: bowerInfo.name, commit: bowerInfo._resolution !== undefined ? bowerInfo._resolution.commit : undefined, release: bowerInfo._release, src: bowerInfo._source, originalSrc: bowerInfo._originalSource }; }
javascript
{ "resource": "" }
q31832
getDependency
train
function getDependency(filepath) { var bowerInfoStr = fs.readFileSync(filepath, {encoding: 'utf8'}); var bowerInfo = JSON.parse(bowerInfoStr); return mapDependencyData(bowerInfo); }
javascript
{ "resource": "" }
q31833
getBowerFolder
train
function getBowerFolder() { var bowerRC = getBowerRC(); if (bowerRC === null || bowerRC.directory === undefined) { return 'bower_components'; } return bowerRC.directory; }
javascript
{ "resource": "" }
q31834
getAllDependencies
train
function getAllDependencies() { var folder = './' + getBowerFolder(); var bowerDependencies = fs.readdirSync(folder, {encoding: 'utf8'}); var dependencyInfos = []; bowerDependencies.forEach(function(dirname) { var filepath = nodePath.resolve(cwd, folder, dirname, '.bower.json'); if (fs.existsSync(filepath)) { var dependencyInfo = getDependency(filepath); dependencyInfo.dirName = dirname; dependencyInfos.push(dependencyInfo); } }); return dependencyInfos; }
javascript
{ "resource": "" }
q31835
optimizeHistogram
train
function optimizeHistogram(histogram, options) { options = _.defaults(options || {}, { colorDistanceThreshold: 22 }); for (var i = 0; i < histogram.length - 1; i++) { if (histogram[i].count === 0) { continue; } for (var j = i + 1; j < histogram.length; j++) { var distance = getColorDistance(histogram[i].color, histogram[j].color); if (distance <= options.colorDistanceThreshold) { histogram[i].count += histogram[j].count; histogram[j].count = 0; } } } histogram = _.filter(histogram, function (group) { return group.count > 0; }); return sortByCountDesc(histogram); }
javascript
{ "resource": "" }
q31836
train
function (filepath) { // console.log('processing: ' + filepath); // read file source, saved in RAM var content = grunt.file.read(filepath); /* * Reset pattern's last search index to 0 * at the beginning for each file content. * * NOTE: * Since the pattern is always the same regex instance, * property 'lastIndex' changes each time when .exec() is performed. * To avoid 'lastIndex' affected by recursive function call, * its value MUST be cached for each file content. */ var cacheLastIndex = 0; _.pattern.lastIndex = cacheLastIndex; var matches = _.pattern.exec(content); cacheLastIndex = _.pattern.lastIndex; // While there are matches (of import-links) in file content while (matches !== null) { /* * Construct the imported file's absolute path * (doesn't matter whether or not a relative path), * and recursively search in imported file. (dept-first) * * NOTE: * - the regex uses capture group, the first match is the fragment file path. */ var currentDir = path.dirname(filepath), relativeFilepath = matches[1].trim(), importedFilepath = path.resolve(currentDir, relativeFilepath); var returnContent = getReplacedFileContent(importedFilepath); /* * For current file content, * replace import-link tag with return value. * * NOTE: * Because of dept-first search, * should ONLY replace the first match in current content. * rather than search globally. */ content = content.replace(_.patternNonGlobal, returnContent); // console.log(content); // console.log(matches); // console.log('-----'); /* * Keep searching in current file. * * NOTE: * After replacing part of the content (the step above), * the content's length changes accordingly. * Thus the 'lastIndex' property should shift to * the proper position to ensure next search. */ var deltaLength = returnContent.length - matches[0].length; _.pattern.lastIndex = cacheLastIndex + deltaLength; matches = _.pattern.exec(content); cacheLastIndex = _.pattern.lastIndex; } // When searching and replacing is done, return the result. return content; }
javascript
{ "resource": "" }
q31837
unpackQuestion
train
function unpackQuestion(buf, offset) { var bytes = 0; var question = {}; // - variable length compressed question name var nbname = NBName.fromBuffer(buf, offset + bytes); if (nbname.error) { return {error: nbname.error}; } question.nbname = nbname; bytes += nbname.bytesRead; // Ensure we have enough space left before proceeding to avoid throwing if (offset + bytes + 4 > buf.length) { return { error: new Error('Question section is too large to fit in remaining ' + 'packet bytes.') }; } // - 16-bit question type var t = buf.readUInt16BE(offset + bytes); bytes += 2; question.type = con.QUESTION_TYPE_TO_STRING[t]; if (question.type === undefined) { return { error: new Error('Unexpected question type [' + t + '] for name [' + question.nbname + ']; should be either [nb] or ' + '[nbstat]') }; } // - 16-bit question class var clazz = buf.readUInt16BE(offset + bytes); bytes += 2; if (clazz !== con.CLASS_IN) { return { error: new Error('Unexpected question class [' + clazz + '] for name [' + question.nbname + ']; should be [' + CLASS_IN + ']') }; } return {bytesRead: bytes, record: question}; }
javascript
{ "resource": "" }
q31838
detectUserOptions
train
function detectUserOptions () { let outputPath = program.output; let userOptions = { output: false }; cliProps.forEach(prop => { let value = program[prop]; if ((prop === 'stream' || prop === 'langdetect') && value) { return; } if (value !== undefined) { userOptions[prop] = value; } }); if (typeof outputPath === 'string' && outputPath.length) { userOptions.output = outputPath; } return userOptions; }
javascript
{ "resource": "" }
q31839
detectUserInput
train
function detectUserInput () { let validatePath = program.input; if (typeof validatePath !== 'string') { validatePath = process.cwd(); } else { if (!(/^(http(s)?:)?\/\//i.test(validatePath))) { if (/^\//.test(validatePath)) { validatePath = path.resolve(validatePath); } } } return validatePath; }
javascript
{ "resource": "" }
q31840
getOptions
train
function getOptions (userOptions = {}) { let options = _.cloneDeep(userOptions); if (options.format === 'html') { options.outputAsHtml = true; options.verbose = true; options.format = 'json'; } return options; }
javascript
{ "resource": "" }
q31841
getArgvFromObject
train
function getArgvFromObject (options) { let argv = []; let format = options.format; if (formatList.get(format)) { argv.push(`--format ${format}`); } if (options.asciiquotes) { argv.push('--asciiquotes yes'); } if (options.stream === false) { argv.push('--no-stream'); } if (options.langdetect === false) { argv.push('--no-langdetect'); } if (options.filterfile) { argv.push(`--filterfile ${options.filterfile}`); } if (options.filterpattern) { argv.push(`--filterpattern ${options.filterpattern}`); } booleanArgs.forEach(key => { if (options[key]) { argv.push(`--${camel2dash(key)}`); } }); return argv; }
javascript
{ "resource": "" }
q31842
doSomethingUninteresting
train
function doSomethingUninteresting(data) { // simulate latency var wait = randomWait(1000); return Promise.delay(wait).then( () => `It took me ${wait} milliseconds to notice you gave me ${data}.` ); }
javascript
{ "resource": "" }
q31843
fetchProps
train
function fetchProps(props, match) { var newProps = {}; var deferreds = {}; var promises = {}; var tasks = {}; var name; for (name in props) { var m = isPromisePropRe.exec(name); if (m) { var promiseName = m[1]; var deferred = Promise.defer(); tasks[promiseName] = makeTask(props[name], deferred); deferreds[promiseName] = deferred.promise; } else { newProps[name] = props[name]; } } // not *Promise props, shortcircuit! if (Object.keys(deferreds).length === 0) { return Promise.resolve(props); } var isFulfilled = true; for (name in tasks) { var promise = tasks[name](newProps, deferreds, match); isFulfilled = isFulfilled && promise.isFulfilled(); promises[name] = promise.isFulfilled() ? promise.value() : promise; } // every promise is resolved (probably from some DB cache?), shortcircuit! if (isFulfilled) { return Promise.resolve(merge(newProps, promises)); } return Promise.props(promises) .then((props) => merge(newProps, props)) .finally(() => { for (var name in deferreds) { deferreds[name].catch(emptyFunction); } }); }
javascript
{ "resource": "" }
q31844
renderScene
train
function renderScene () { gl.clearColor(0, 0, 0, 1) gl.clear(gl.COLOR_BUFFER_BIT) gl.viewport(0, 0, shape[0], shape[1]) shader.bind() shader.uniforms.iResolution = shape shader.uniforms.iGlobalTime = 0 triangle(gl) }
javascript
{ "resource": "" }
q31845
FileSystem
train
function FileSystem(base, options) { options || (options = {}); this.base = this.pathResolve(base); if(options.captureFile) { this._readFiles = []; } if(options.globalAct) { this.globalAct = options.globalAct; } }
javascript
{ "resource": "" }
q31846
train
function(pos) { var topOffset = $(this).css(pos).offset().top; if (topOffset < 0) { $(this).css('top', pos.top - topOffset); } }
javascript
{ "resource": "" }
q31847
train
function(force, event) { var self = this, options = self.options, saveScroll; if ((options.modal && !force) || (!options.stack && !options.modal)) { return self._trigger('focus', event); } if (options.zIndex > $.ui.dialog.maxZ) { $.ui.dialog.maxZ = options.zIndex; } if (self.overlay) { $.ui.dialog.maxZ += 1; self.overlay.$el.css('z-index', $.ui.dialog.overlay.maxZ = $.ui.dialog.maxZ); } //Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed. // http://ui.jquery.com/bugs/ticket/3193 saveScroll = { scrollTop: self.element.scrollTop(), scrollLeft: self.element.scrollLeft() }; $.ui.dialog.maxZ += 1; self.uiDialog.css('z-index', $.ui.dialog.maxZ); self.element.attr(saveScroll); self._trigger('focus', event); return self; }
javascript
{ "resource": "" }
q31848
train
function(match, value, len) { var num = '' + value; if (lookAhead(match)) while (num.length < len) num = '0' + num; return num; }
javascript
{ "resource": "" }
q31849
asciifyImage
train
function asciifyImage( canvasRenderer, oAscii ) { oCtx.clearRect( 0, 0, iWidth, iHeight ); oCtx.drawImage( oCanvasImg, 0, 0, iWidth, iHeight ); var oImgData = oCtx.getImageData( 0, 0, iWidth, iHeight ).data; // Coloring loop starts now var strChars = ""; // console.time('rendering'); for ( var y = 0; y < iHeight; y += 2 ) { for ( var x = 0; x < iWidth; x ++ ) { var iOffset = ( y * iWidth + x ) * 4; var iRed = oImgData[ iOffset ]; var iGreen = oImgData[ iOffset + 1 ]; var iBlue = oImgData[ iOffset + 2 ]; var iAlpha = oImgData[ iOffset + 3 ]; var iCharIdx; var fBrightness; fBrightness = ( 0.3 * iRed + 0.59 * iGreen + 0.11 * iBlue ) / 255; // fBrightness = (0.3*iRed + 0.5*iGreen + 0.3*iBlue) / 255; if ( iAlpha == 0 ) { // should calculate alpha instead, but quick hack :) //fBrightness *= (iAlpha / 255); fBrightness = 1; } iCharIdx = Math.floor( ( 1 - fBrightness ) * ( aCharList.length - 1 ) ); if ( bInvert ) { iCharIdx = aCharList.length - iCharIdx - 1; } // good for debugging //fBrightness = Math.floor(fBrightness * 10); //strThisChar = fBrightness; var strThisChar = aCharList[ iCharIdx ]; if ( strThisChar === undefined || strThisChar == " " ) strThisChar = "&nbsp;"; if ( bColor ) { strChars += "<span style='" + "color:rgb(" + iRed + "," + iGreen + "," + iBlue + ");" + ( bBlock ? "background-color:rgb(" + iRed + "," + iGreen + "," + iBlue + ");" : "" ) + ( bAlpha ? "opacity:" + ( iAlpha / 255 ) + ";" : "" ) + "'>" + strThisChar + "</span>"; } else { strChars += strThisChar; } } strChars += "<br/>"; } oAscii.innerHTML = "<tr><td>" + strChars + "</td></tr>"; // console.timeEnd('rendering'); // return oAscii; }
javascript
{ "resource": "" }
q31850
BrokenLinkChecker
train
function BrokenLinkChecker(options) { this.runningScope = options.scope || BrokenLinkChecker.RUNNING_SCOPE_COMMAND; this.pluginConfig = {}; this.pluginConfig.enabled = (typeof userConfig.enabled !== 'undefined')? userConfig.enabled : true; this.pluginConfig.storageDir = userConfig.storage_dir || 'temp/link_checker'; this.pluginConfig.silentLogs = options.silentLogs || userConfig.silent_logs || false; this.workingDirectory = hexo.base_dir + this.pluginConfig.storageDir; this.storageFile = 'data.json'; this.logFile = 'log.json'; this._storageTemplateFile = __dirname + '/../data/storageTemplate.json'; this._jsonStorage = null; // the path must end with a slash if (this.workingDirectory.substr(-1) != '/') { this.workingDirectory += '/'; } var loggerOptions = { defaultPrefix: null, infoPrefix: null, warnPrefix: null, errPrefix: null, silent: this.pluginConfig.silentLogs, logFile: this.workingDirectory+this.logFile }; // change the log prefix based on the running scope // command: // (i) Text // filter: // [BrokenLinkChecker Info] Text switch (this.runningScope) { case BrokenLinkChecker.RUNNING_SCOPE_COMMAND: loggerOptions.defaultPrefix = '(i) '.cyan; loggerOptions.warnPrefix = '(!) '.yellow; loggerOptions.errPrefix = '(x) '.red; break; case BrokenLinkChecker.RUNNING_SCOPE_FILTER: loggerOptions.defaultPrefix = '['+(this.toString()+' Info').cyan+'] '; loggerOptions.warnPrefix = '['+(this.toString()+' Warning').yellow+'] '; loggerOptions.errPrefix = '['+(this.toString()+' Error').red+'] '; break; } this.logger = new Logger(loggerOptions); }
javascript
{ "resource": "" }
q31851
train
function(src, dest) { if (grunt.file.isDir(src)) { grunt.file.mkdir(dest); if (options.log) { Utils.writeln(chalk.gray.bold(' create dir => ' + dest)); } return true; } return false; }
javascript
{ "resource": "" }
q31852
train
function (names) { this.names = Object.keys(names); // store the keys this.hash = util.map(names, function (value) { // store values for corresponding keys return parseInt(value, 10); }); }
javascript
{ "resource": "" }
q31853
train
function (name, lazy) { return Array.isArray(name) ? (name.length ? name.every(function (name) { return this.defined(name, lazy); }, this) : !!lazy) : (name ? !!this.hash[name] : !!lazy); }
javascript
{ "resource": "" }
q31854
train
function (name) { return Array.isArray(name) ? (name.map(this.valueOf.bind(this))) : this.hash[name]; }
javascript
{ "resource": "" }
q31855
train
function(file) { var FileSystem = require('./fs.js'); var ReadStream = require('./read_stream.js'); if(FileSystem.fs.existFile(file)) { file = FileSystem.fs.pathResolve(file); var readStream = new ReadStream(file); return _.clone(readStream.trackStack); } else { return false; } }
javascript
{ "resource": "" }
q31856
get
train
function get(code) { if (!Object.prototype.hasOwnProperty.call(osm, code)) { throw new TypeError('The alpha-3 code provided was not found: ' + code); } return osm[code]; }
javascript
{ "resource": "" }
q31857
registerDual
train
function registerDual(numberType, numericType, checkFn, toJSONSchema) { context.registerType(numberType, 'number', checkFn, numberType, extra => toJSONSchema('number', extra)) context.registerType(numericType, 'string', value => { let numberValue = toNumber(value) checkFn(numberValue) return numberValue }, numericType, () => ({ type: 'string', format: numericType })) }
javascript
{ "resource": "" }
q31858
registerTaggedDual
train
function registerTaggedDual(numberTag, numericTag, checkFn, toJSONSchema) { context.registerTaggedType({ tag: numberTag, jsonType: 'number', minArgs: 2, maxArgs: 2, sparse: true, numeric: true }, checkFn, returnOriginal, toJSONSchema) context.registerTaggedType({ tag: numericTag, jsonType: 'string', minArgs: 2, maxArgs: 2, sparse: true, numeric: true }, (value, args) => { let numberValue = toNumber(value) checkFn(numberValue, args) return numberValue }, returnOriginal, extra => ({ type: 'string', format: extra.original })) }
javascript
{ "resource": "" }
q31859
createFunction
train
function createFunction(sCode, settings) { /*jshint evil:true, laxbreak:true, quotmark:false*/ var nI, params, sName; if (! settings) { settings = {}; } params = settings.paramNames; if (settings.expression) { sCode = "return (" + sCode + ");"; } if (settings.scope) { if (params) { nI = params.indexOf(","); if (nI > -1) { sName = params.substring(0, nI); } else { sName = params; } } else { params = sName = "sc"; } sCode = "with(" + sName + ") {" + sCode + "}"; } if (settings.debug && (settings.debugFunc || (typeof console === "object" && console && typeof console.log === "function"))) { sCode = 'try{' + sCode + '}catch(_e_){' + (settings.debugFunc || 'console.log') + '("' + (settings.debugMessage ? settings.debugMessage.replace(/"/g, '\\\"') : 'Error in created function:') + '", _e_);}'; } return params ? new Function(params, sCode) : new Function(sCode); }
javascript
{ "resource": "" }
q31860
createDelegateMethod
train
function createDelegateMethod(delegate, sMethod, settings) { var result = function() { return delegate[sMethod].apply(delegate, arguments); }; if (settings && settings.destination) { settings.destination[settings.destinationMethod || sMethod] = result; } return result; }
javascript
{ "resource": "" }
q31861
closure
train
function closure(action, paramList, context, settings) { if (! settings) { settings = {}; } var bUseArgs = ! settings.ignoreArgs, bAppendArgs = ! settings.prependArgs; return function() { var params; if (bUseArgs) { params = paramList ? Array.prototype.slice.call(paramList, 0) : []; if (bAppendArgs) { params.push.apply(params, arguments); } else { params = Array.prototype.slice.call(arguments, 0).concat(params); } } else { params = paramList || []; } return action.apply(context || null, params); }; }
javascript
{ "resource": "" }
q31862
map
train
function map(funcList, paramList, context, settings) { /*jshint laxbreak:true*/ var result = [], nL = funcList.length, bGetContext, bGetParamList, func, nI; if (! paramList) { paramList = []; } if (! context) { context = null; } if (! settings) { settings = {}; } bGetContext = typeof context === "function" && ! settings.funcContext; bGetParamList = typeof paramList === "function"; for (nI = 0; nI < nL; nI++) { func = funcList[nI]; result[nI] = func.apply(bGetContext ? context(func, nI, funcList) : context, bGetParamList ? paramList(func, nI, funcList) : paramList); } return result; }
javascript
{ "resource": "" }
q31863
train
function(response, body) { var responseCodes = [ { codes: 400, message: 'Request was invalid.' }, { codes: 401, message: 'Bad access token.' }, { codes: 403, message: 'Bad OAuth scope.' }, { codes: 404, message: 'Selector did not match any lights.' }, { codes: 422, message: 'Missing or malformed parameters' }, { codes: 426, message: 'HTTP was used to make the request instead of HTTPS. Repeat the request using HTTPS instead.' }, { codes: 429, message: 'The request exceeded a rate limit.' }, { codes: [ 500, 502, 503, 523 ], message: 'Something went wrong on Lif\'s end.' } ]; var error = ''; responseCodes.every(function(responseCode) { if(_.isArray(responseCode.codes)) { responseCode.codes.forEach(function(code) { if (code === response.statusCode) { error = responseCode.message; return false; } return true; }); } }); // Special case HTTP code 422 Unprocessable Entity if(response && response.statusCode === 422) { error = body.error; } return error; }
javascript
{ "resource": "" }
q31864
train
function(selector) { var validSelectors = [ 'all', 'label:', 'id:', 'group_id:', 'group:', 'location_id:', 'location:', 'scene_id:' ], isValid = false; if(!selector || !selector.length) { return false; } validSelectors.every(function(sel) { if(selector.startsWith(sel)) { isValid = true; return false; } return true; }); return isValid; }
javascript
{ "resource": "" }
q31865
context
train
function context(schema, value, options) { schema = context.parse(schema) let ret = schema.validate(value, options) context.lastError = schema.lastError context.lastErrorMessage = schema.lastErrorMessage context.lastErrorPath = schema.lastErrorPath return ret }
javascript
{ "resource": "" }
q31866
parseTagged
train
function parseTagged(definition, taggedTypes) { let match = definition.match(/^(\w+)(?:\((.*)\))?$/), tag, args, typeInfo if (!match) { return } // Get type info tag = match[1] typeInfo = taggedTypes[tag] if (!typeInfo) { return } // Special no-'()' case: only match 'tag' if minArgs is zero if (typeInfo.minArgs > 0 && match[2] === undefined) { return } // Parse and check args args = (match[2] || '').trim().split(/\s*,\s*/) if (args.length === 1 && args[0] === '') { // Especial empty case args = [] } args = args.map((arg, i) => { if (!arg) { if (!typeInfo.sparse) { throw new Error('Missing argument at position ' + i + ' for tagged type ' + tag) } return } if (typeInfo.numeric) { arg = Number(arg) if (isNaN(arg)) { throw new Error('Invalid numeric argument at position ' + i + ' for tagged type ' + tag) } } return arg }) args.original = definition if (args.length < typeInfo.minArgs) { throw new Error('Too few arguments for tagged type ' + tag) } else if (typeInfo.maxArgs && args.length > typeInfo.maxArgs) { throw new Error('Too many arguments for tagged type ' + tag) } return new Field(typeInfo.type, typeInfo.parseArgs ? typeInfo.parseArgs(args) : args) }
javascript
{ "resource": "" }
q31867
train
function (recipient, donor) { for (var prop in donor) { donor.hasOwnProperty(prop) && (recipient[prop] = donor[prop]); } return recipient; }
javascript
{ "resource": "" }
q31868
train
function (obj, mapper, scope) { var map = {}, prop; scope = scope || obj; for (prop in obj) { obj.hasOwnProperty(prop) && (map[prop] = mapper.call(scope, obj[prop], prop, obj)); } return map; }
javascript
{ "resource": "" }
q31869
verifyDevice
train
async function verifyDevice (userId, deviceId) { await exports.matrixClient.setDeviceKnown(userId, deviceId, true); await exports.matrixClient.setDeviceVerified(userId, deviceId, true); }
javascript
{ "resource": "" }
q31870
fixParagraphNode
train
function fixParagraphNode(node, fullText) { const firstNode = node.children[0]; const lastNode = node.children[node.children.length - 1]; node.range = [firstNode.range[0], lastNode.range[1]]; node.raw = fullText.slice(node.range[0], node.range[1]); node.loc = { start: { line: firstNode.loc.start.line, column: firstNode.loc.start.column }, end: { line: lastNode.loc.end.line, column: lastNode.loc.end.column } }; }
javascript
{ "resource": "" }
q31871
fixSignatureParams
train
function fixSignatureParams(node, item, signature) { signature.params = []; for (var i = 0; i < signature.arity; i++) { var paramCopy = _.extend({}, item.params[i]); if (node && node.paramTags) { if (node.paramTags[paramCopy.name]) { _.extend(paramCopy, node.paramTags[paramCopy.name]); } } signature.params.push(paramCopy); } }
javascript
{ "resource": "" }
q31872
closeHost
train
function closeHost() { // close the host itself me.addresses = {}; if (me.server) { me.server.close(); me.server = null; me.address = null; me.port = null; me.url = null; } return me; }
javascript
{ "resource": "" }
q31873
FFParameterRejected
train
function FFParameterRejected(parameter) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.message = 'A parameter provided is absent, malformed or invalid for other reasons: '+parameter; }
javascript
{ "resource": "" }
q31874
collectRefs
train
function collectRefs() { // check if there's a shadow root in the element if (typeof this.shadowRoot === 'undefined') { throw new Error('You must create a shadowRoot on the element'); } // create refs base object this.refs = {}; var refsList = this.shadowRoot.querySelectorAll('[ref]'); // collect refs if any if (refsList.length > 0) { var refsArray = _toArray(refsList); refsArray.map(_assignRef.bind(this)); } // observe added and removed child nodes var refsMutationObserver = new MutationObserver(_handleMutations.bind(this)); refsMutationObserver.observe(this.shadowRoot, { childList: true, subtree: true }); }
javascript
{ "resource": "" }
q31875
_isRefNode
train
function _isRefNode(node) { return ( node.nodeType && node.nodeType === 1 && (node.hasAttribute('ref') || typeof node.__refString__ === 'string') ); }
javascript
{ "resource": "" }
q31876
_handleSingleMutation
train
function _handleSingleMutation(mutation) { var addedNodes = _toArray(mutation.addedNodes); var addedRefs = addedNodes.filter(_isRefNode); // assign added nodes addedRefs.map(_assignRef.bind(this)); var removedNodes = _toArray(mutation.removedNodes); var removedRefs = removedNodes.filter(_isRefNode); // assign removed nodes removedRefs.map(_deleteRef.bind(this)); }
javascript
{ "resource": "" }
q31877
action_putpost
train
function action_putpost(si,args,done) { var ent_type = parse_ent(args) var ent = si.make(ent_type.zone,ent_type.base,ent_type.name) var data = args.data || {} var good = _.filter(_.keys(data),function(k){return !~k.indexOf('$')}) var fields = _.pick(data,good) ent.data$(fields) if( null != ent_type.entid ) { ent.id = ent_type.entid } else if( null != data.id$ && options.allow_id ) { ent.id$ = data.id$ } save_aspect(si,{args:args,ent:ent},done,function(ctxt,done){ ctxt.ent.save$(function(err,ent){ var data = ent ? ent.data$(true,'string') : null done(err, data) }) }) }
javascript
{ "resource": "" }
q31878
handleVisibilityChange
train
function handleVisibilityChange() { if (document[hidden]) { let gifPlayers = document.querySelectorAll('.vjs-gifplayer'); for (let gifPlayer of gifPlayers) { let player = gifPlayer.player; if (player) { player.pause(); } } } else { autoPlayGifs(); } }
javascript
{ "resource": "" }
q31879
_getKeyInfo
train
function _getKeyInfo(combination, action) { var keys, key, i, modifiers = []; // take the keys from this pattern and figure out what the actual // pattern is all about keys = _keysFromString(combination); for (i = 0; i < keys.length; ++i) { key = keys[i]; // normalize key names if (_SPECIAL_ALIASES[key]) { key = _SPECIAL_ALIASES[key]; } // if this is not a keypress event then we should // be smart about using shift keys // this will only work for US keyboards however if (action && action != 'keypress' && _SHIFT_MAP[key]) { key = _SHIFT_MAP[key]; modifiers.push('shift'); } // if this key is a modifier then add it to the list of modifiers if (_isModifier(key)) { modifiers.push(key); } } // depending on what the key combination is // we will try to pick the best event for it action = _pickBestAction(key, modifiers, action); return { key: key, modifiers: modifiers, action: action }; }
javascript
{ "resource": "" }
q31880
train
function(keys, callback, action) { keys = keys instanceof Array ? keys : [keys]; _bindMultiple(keys, callback, action); return this; }
javascript
{ "resource": "" }
q31881
train
function(e, element) { // if the element has the class "mousetrap" then no need to stop if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { return false; } // stop for input, select, and textarea return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable; }
javascript
{ "resource": "" }
q31882
train
function (name, transform, config, filefog_options){ this.name = name; this.config = config || {}; this._transform = transform; this.filefog_options = extend(true, {transform:true, include_raw:true, auto_paginate:true,root_identifier:null}, filefog_options || {}); base_provider.call(this, name); }
javascript
{ "resource": "" }
q31883
on
train
function on(emitter, eventName, handler, context) { handler = context ? handler.bind(context) : handler; emitter.addEventListener(eventName, handler); return handler; }
javascript
{ "resource": "" }
q31884
once
train
function once(emitter, eventName, handler, context) { handler = context ? handler.bind(context) : handler; let wrapper = function onceHandler(event) { emitter.removeEventListener(eventName, onceHandler); handler(event); }; emitter.addEventListener(eventName, wrapper); return wrapper; }
javascript
{ "resource": "" }
q31885
until
train
function until(emitter, eventName, handler, context) { handler = context ? handler.bind(context) : handler; let wrapper = function untilHandler(event) { if (handler(event)) emitter.removeEventListener(eventName, untilHandler); }; emitter.addEventListener(eventName, wrapper); return wrapper; }
javascript
{ "resource": "" }
q31886
train
function(cb, settings) { if (!VK._apiId) { return false; } var url = VK._domain.main + VK._path.login + '?client_id='+VK._apiId+'&display=popup&redirect_uri=close.html&response_type=token'; if (settings && parseInt(settings, 10) > 0) { url += '&scope=' + settings; } VK.Observer.unsubscribe('auth.onLogin'); VK.Observer.subscribe('auth.onLogin', cb); VK.UI.popup({ width: 665, height: 370, url: url }); var authCallback = function() { VK.Auth.getLoginStatus(function(resp) { VK.Observer.publish('auth.onLogin', resp); VK.Observer.unsubscribe('auth.onLogin'); }, true); } VK.UI.popupOpened = true; var popupCheck = function() { if (!VK.UI.popupOpened) { return false; } try { if (!VK.UI.active.top || VK.UI.active.closed) { VK.UI.popupOpened = false; authCallback(); return true; } } catch(e) { VK.UI.popupOpened = false; authCallback(); return true; } setTimeout(popupCheck, 100); }; setTimeout(popupCheck, 100); }
javascript
{ "resource": "" }
q31887
postMessage
train
function postMessage(ctx) { var queue = [], message = "nextTick"; function handle(event) { if (event.source === ctx && event.data === message) { if (!!event.stopPropogation) { event.stopPropogation(); } if (queue.length > 0) { queue.shift()(); } } } if (!!ctx.addEventListener) { ctx.addEventListener("message", handle, true); } else { ctx.attachEvent("onmessage", handle); } return function defer(fn) { queue.push(fn); ctx.postMessage(message, '*'); }; }
javascript
{ "resource": "" }
q31888
send
train
function send(ev, data, fn) { /* jshint validthis: true */ // ignore newListener event to avoid this error in node 0.8 // https://github.com/cayasso/primus-emitter/issues/3 if (/^(newListener|removeListener)/.test(ev)) return this; this.emitter.send.apply(this.emitter, arguments); return this; }
javascript
{ "resource": "" }
q31889
Emitter
train
function Emitter(conn) { if (!(this instanceof Emitter)) return new Emitter(conn); this.ids = 1; this.acks = {}; this.conn = conn; if (this.conn) this.bind(); }
javascript
{ "resource": "" }
q31890
renderToString
train
function renderToString(reactClass, data) { let classPath = path.join(viewsDir, reactClass); let element = React.createElement(require(classPath).default, data); return ReactDOMServer.renderToString(element); }
javascript
{ "resource": "" }
q31891
installed
train
function installed(){ findUp('README.*') .then(function(filepath){ if(filepath === null){ return process.cwd(); }else{ return path.resolve(filepath[0], '../'); } }) .then(function(parent){ return config.readLocal(parent); }) .then(data => { if(data.installed.length === 0){ console.log(chalk.bold('No badges installed.')); }else{ // console.log(chalk.bold.underline(`Installed(${data.installed.length}):`)); _.each(data.installed, i => { console.log(i) }); console.log(chalk.bgBlue.bold(`Total: ${data.installed.length} `)) } }); }
javascript
{ "resource": "" }
q31892
train
function(name,transform, provider_config, credentials, filefog_options){ this.name = name; this.config = provider_config || {}; this.credentials = credentials || {}; this.filefog_options = extend(true, {transform:true, include_raw:true, auto_paginate:true,root_identifier:null}, filefog_options || {}); this._transform = transform; base_client.call(this); }
javascript
{ "resource": "" }
q31893
convertOutline
train
function convertOutline (jstruct) { //7/16/14 by DW var theNewOutline = {}, atts, subs; if (jstruct ["source:outline"] != undefined) { if (jstruct ["@"] != undefined) { atts = jstruct ["@"]; subs = jstruct ["source:outline"]; } else { atts = jstruct ["source:outline"] ["@"]; subs = jstruct ["source:outline"] ["source:outline"]; } } else { atts = jstruct ["@"]; subs = undefined; } for (var x in atts) { theNewOutline [x] = atts [x]; } if (subs != undefined) { theNewOutline.subs = []; if (subs instanceof Array) { for (var i = 0; i < subs.length; i++) { theNewOutline.subs [i] = convertOutline (subs [i]); } } else { theNewOutline.subs = []; theNewOutline.subs [0] = {}; for (var x in subs ["@"]) { theNewOutline.subs [0] [x] = subs ["@"] [x]; } } } return (theNewOutline); }
javascript
{ "resource": "" }
q31894
getDebugger
train
function getDebugger() { const isCustom = arguments.length === 1; const layoutDebug = isCustom ? new Debugger(arguments[0]) : defaultDebugger; return isCustom ? debuggerDecorator.bind(layoutDebug) : debuggerDecorator.call(layoutDebug, ...arguments); }
javascript
{ "resource": "" }
q31895
consume
train
function consume (len) { count -= len if (count < 0) { count = 0; console.warn('Not enough samples fed for the next data frame. Expected frame is ' + samplesPerFrame + ' samples ' + channels + ' channels') } if (!callbackMarks.length) return for (let i = 0, l = callbackMarks.length; i < l; i++) { callbackMarks[i] = Math.max(callbackMarks[i] - len, 0) } while (callbackMarks[0] <= 0) { callbackMarks.shift() let cb = callbackQueue.shift() cb() } }
javascript
{ "resource": "" }
q31896
getLibPaths
train
function getLibPaths(libs, inject) { inject = inject || false; var libName, libSrcs = [], outSrcs = []; for (libName in libs) { libSrcs = libs[libName]; if (typeof libSrcs === "string") { libSrcs = [libSrcs]; } var basePath; if (inject === true) { // Adapt basepath for inject basePath = path.join(p.dest, p.libsDestSubDir, libName); } else { // Adapt basepath for libs' origin basePath = path.join(p.libsDir, libName); } libSrcs = libSrcs.map(function(src) { return path.join(basePath, src); }); outSrcs = outSrcs.concat(libSrcs); } return outSrcs; }
javascript
{ "resource": "" }
q31897
train
function (valueKey, signed) { return function (bytes) { var result = {}; result[valueKey] = misc.bufferToInt(bytes, signed); return result; }; }
javascript
{ "resource": "" }
q31898
train
function (options) { return function (bytes) { var result = { min: options.min, max: options.max, range: options.max - options.min, raw: misc.bufferToInt(bytes) }; result.magnitude = 1.0 * result.raw / result.range; return result; }; }
javascript
{ "resource": "" }
q31899
train
function (name, id, bytes, parser) { this.name = name; this.id = id; this.bytes = bytes; // the parser is null by default, otherwise the specified function this.parser = _.isFunction(parser) ? parser : function () {}; }
javascript
{ "resource": "" }