_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q39300
flush
train
function flush(done) { this.once('done', done); if (this._res.finished) { this.emit('done', new Error('Response was closed, unable to flush content')); } if (!this._queue.length) this.emit('done'); var data = new Buffer(this.join(), this.charset); if (data.length) { this.debug('Writing %d bytes of %s to response', data.length, this.charset); this._res.write(data, this.emits('done')); } // // Optional write confirmation, it got added in more recent versions of // node, so if it's not supported we're just going to call the callback // our selfs. // if (this._res.write.length !== 3 || !data.length) this.emit('done'); }
javascript
{ "resource": "" }
q39301
constructor
train
function constructor(options) { Pagelet.prototype.constructor.call(this, options = options || {}); // // Store the provided global dependencies. // this.dependencies = this._bigpipe._compiler.page(this).concat( options.dependencies ); var req = options.req || {} , uri = req.uri || {} , query = req.query || {}; // // Set a number of properties on the response as it is available to all pagelets. // This will ensure the correct amount of pagelets are processed and that the // entire queue is written to the client. // this._queue = []; // // Prepare several properties that are used to render the HTML fragment. // this.length = options.length || 0; this.child = options.child || 'root'; this.once('contentType', this.contentTypeHeader, this); // // Set the default fallback script, see explanation above. // this.debug('Initialized in %s mode', options.mode); this.fallback = 'sync' === options.mode ? script : noscript.replace( '{path}', uri.pathname || 'http://localhost/' ).replace( '{query}', qs.stringify(this.merge({ no_pagelet_js: 1 }, query)) ); }
javascript
{ "resource": "" }
q39302
train
function (callbackId, data, keepAlive) { const args = [callbackId] data && args.push(data) keepAlive && args.push(keepAlive) _send(this.instanceId, { method: 'callback', args: args }) }
javascript
{ "resource": "" }
q39303
BenderReporter
train
function BenderReporter() { var timer = new jasmine.Timer(), current = new Suite(), passed = 0, failed = 0, errors = 0, ignored = 0, total = 0; function buildError( result ) { var pattern = /\n.*jasmine.js.*/gi, error = [], exp, i; for ( i = 0; i < result.failedExpectations.length; i++ ) { errors++; exp = result.failedExpectations[ i ]; if ( exp.stack ) { if ( exp.stack.indexOf( exp.message ) === -1 ) { error.push( exp.message ); } error.push( exp.stack .replace( pattern, '' ) ); } else { error.push( exp.message ); } } return error.join( '\n' ); } this.jasmineStarted = function() { timer.start(); }; this.jasmineDone = function() { bender.next( { duration: timer.elapsed(), passed: passed, failed: failed, errors: errors, ignored: ignored, total: total, coverage: window.__coverage__ } ); }; this.suiteStarted = function( suite ) { current = new Suite( suite.description, current ); }; this.suiteDone = function() { current = current.parent; }; this.specStarted = function( result ) { total++; result.startTime = +new Date(); }; this.specDone = function( result ) { var modules = [], p = current; while ( p ) { if ( p.name ) { modules.push( p.name ); } p = p.parent; } result.module = modules.reverse().join( ' / ' ); result.name = result.description; result.success = true; result.duration = +new Date() - result.startTime; if ( result.status === 'passed' ) { passed++; } else if ( result.status === 'disabled' || result.status === 'pending' ) { result.ignored = true; ignored++; } else { result.success = false; result.error = buildError( result ); result.errors = errors; failed++; } bender.result( result ); }; }
javascript
{ "resource": "" }
q39304
HiddenServer
train
function HiddenServer(opts) { if (!(this instanceof HiddenServer)) return new HiddenServer(opts); this.set(require('../settings.json')); this.set(opts); this.uri = this.get('publicServer') + this.get('pingUri').replace(':hiddenServerName', this.get('hiddenServerName')); debug('uri', this.uri); this.init(); }
javascript
{ "resource": "" }
q39305
train
function(options) { return new Promise( (resolve, reject) => { if (options) { options.logger.info('[PROGENIC] Starting "%s" daemon with %s workers...', options.name, options.workers); options.logger.info('[PROGENIC] [from "%s"]', options.main); // Write the PID file: helpers.writePidFile(options.name, options.devMode, options.logger); cluster.setupMaster( { exec: path.join(__dirname, 'worker.js'), args: [options.main, process.env.INSTANCE_NAME], silent: true }); const promises = []; let count = options.workers; while (count-- > 0) { options.logger.info('[PROGENIC] Creating worker #%s...', (options.workers - count)); promises.push(helpers.forkWorker(options.name, options.devMode, options.logger, options.logsBasePath, options.checkPingsEnabled)); } Promise.all(promises) .then(resolve) .catch(reject); } else { reject(new Error('Missing options')); } }); }
javascript
{ "resource": "" }
q39306
train
function(signal) { return new Promise( resolve => { for (let uniqueID in cluster.workers) { if (cluster.workers.hasOwnProperty(uniqueID)) { const worker = cluster.workers[uniqueID]; worker.kill(signal); } } resolve(); }); }
javascript
{ "resource": "" }
q39307
map
train
function map(callable, children) { var iterator = (0, _cmap.default)(callable, children)[Symbol.asyncIterator](); return new _Children.default(iterator, undefined); }
javascript
{ "resource": "" }
q39308
cleanupPrep
train
function cleanupPrep(options) { var sourceResource = options.source; var targetResource = options.target; var targetReactor = options.reactor; var reactor; // if there is a target reactor, just use that cleanupPrep if (targetReactor) { reactor = reactors[targetReactor]; if (reactor && reactor.cleanupPrep) { log.info('Running cleanupPrep for ' + targetReactor); return reactors[targetReactor].cleanupPrep(); } } // else if source and target resources don't exist (i.e. we are doing everything) the try to call all else if (!sourceResource && !targetResource) { return Q.all(reactors.map(function (rctr) { log.info('Running cleanupPrep for ' + rctr); return rctr.cleanupPrep ? rctr.cleanupPrep() : true; })); } // else just return a resolved promise return new Q(); }
javascript
{ "resource": "" }
q39309
getCleanupData
train
function getCleanupData(options) { var sourceResource = options.source; var targetResource = options.target === 'all' ? null : options.target; var targetReactor = options.reactor; var targetField = options.field; var cleanupData = []; // if source resource an option, we only use that, else we look at all resources var srcs = sourceResource === 'all' ? resources : [resources[sourceResource]]; // loop through all resources _.each(srcs, function (resource) { // loop through all reactors in each resource _.each(resource.reactors, function (reactData) { // apply the options filters to determine if we are adding this resource and reactData if ((!targetReactor || reactData.type === targetReactor) && (!targetResource || reactData.target === targetResource || reactData.parent === targetResource || reactData.child === targetResource) && (!targetField || reactData.targetField === targetField)) { cleanupData.push({ resource: resource, reactData: reactData }); } }); }); return cleanupData; }
javascript
{ "resource": "" }
q39310
train
function(object, defaultValue, property) { if (!_.isUndefined(defaultValue)) { object.__setPropertyParam(property, 'default', defaultValue); } }
javascript
{ "resource": "" }
q39311
train
function(psRec,sProcId){ if(!sProcId){throw new Error("No Proc Id found in data");} var iFind,sArgs iFind=psRec.CommandLine.indexOf(psRec.Name); sArgs = psRec.CommandLine.substring(iFind+psRec.Name.length+1); psRecs[sProcId]={ pid: psRec.ProcessId ,ppid: psRec.ParentProcessId ,commandPath: psRec.ExecutablePath ,command: psRec.Name ,args: sArgs } }
javascript
{ "resource": "" }
q39312
watch
train
function watch(conf, undertaker) { const root = conf.themeConfig.root; /** * STYLE WATCHING. */ undertaker.watch( path.join(root, conf.themeConfig.sass.src, '**', '*.scss'), undertaker.series( require('../styles/lintStyles').bind(null, conf, undertaker), require('../styles/buildStyles').bind(null, conf, undertaker), require('../styles/holograph').bind(null, conf, undertaker) ) ); /** * SCRIPT WATCHING. */ undertaker.watch( path.join(root, conf.themeConfig.js.src, '**', '*.js'), undertaker.series( require('../scripts/lintScripts').bind(null, conf, undertaker), require('../scripts/buildScripts').bind(null, conf, undertaker) ) ); /** * IMAGE WATCHING. */ undertaker.watch( path.join(root, conf.themeConfig.images.src, '**', '*'), undertaker.series( require('../assets/buildImages').bind(null, conf, undertaker) ) ); /** * FONT WATCHING. */ undertaker.watch( path.join(root, conf.themeConfig.fonts.src, '**', '*'), undertaker.series( require('../assets/buildFonts').bind(null, conf, undertaker) ) ); }
javascript
{ "resource": "" }
q39313
Builder
train
function Builder (data) { if (!(this instanceof Builder)) return new Builder(data); debug('new builder', data); events.EventEmitter.call(this); this.message = Message(data); }
javascript
{ "resource": "" }
q39314
rounddeg
train
function rounddeg(angle) { var result = 360.0 * (angle / 360.0 - Math.floor(angle / 360.0)); if (result < 0.0) { result += 360.0; } if (result >= 360.0) { result -= 360.0; } return result; }
javascript
{ "resource": "" }
q39315
getViewRoot
train
function getViewRoot(source) { const tokens = parse(source); let position = tokens.length; let tagDepth = 0; let tagName; let token; /** * Loop backwards through the view's source and find the last closing tag * and its matching opening tag to determine the view's root node position. */ while (token = tokens[--position]) { if (token.type !== TokenTypes.TagStart) { continue; } let tag = parseTag(position, tokens); // the last node in the source is a self-closing tag; use that if (!tagName && tag.self) { break; } // this is the last tag in the source; save the name and find its pair if (!tagName) { tagName = tag.name; tagDepth++; continue; } // ignore any tags with a different name if (tag.name !== tagName) { continue; } // increase tags' depth in the tree for closing tags if (!tag.open) { tagDepth++; } // decrease tags' depth in the tree for opening (not self-closing) tags if (tag.open && !tag.self) { tagDepth--; } // if the tag's depth reached 0, it means this is the opening tag if (tagDepth === 0) { break; } } token = tokens[position]; return token ? token.start : 0; }
javascript
{ "resource": "" }
q39316
train
function(next) { S3.getObject({ Bucket: S3Handler.options.S3BucketName, Key: S3Handler.options.mboxName + S3Handler.options.S3MessageListKeySuffix }, next ); }
javascript
{ "resource": "" }
q39317
train
function(messagelist, next) { var keyList = JSON.parse(messagelist.Body); if (CONSOLE_MESSAGES) console.log(new Date().toISOString(),'Raw messageList object:',keyList); // update last modified timestamp // also reset message list count // not using yet so don't modify and save //keyList.last_checked = new Date().getTime(); keyList.messages.forEach(function(item, index) { //if (item.key.search('.json') > -1) return; // skip non-message files data.INBOX.messages.push({ key: item.key, raw: '', flags: [], internaldate: formatInternalDate(new Date(item.created)) }); // push //data.INBOX.marker = item.Key; // update marker }); // forEach indexFolders(); if (CONSOLE_MESSAGES) console.log(new Date().toISOString(),'Refreshed INBOX:',data); if (CONSOLE_MESSAGES) console.log(new Date().toISOString(),'INBOX message detail:',data.INBOX.messages); // should save data here next(null); }
javascript
{ "resource": "" }
q39318
train
function(callback) { var params = { Bucket: S3Handler.options.S3BucketName, Key: S3Handler.options.mboxName + S3Handler.options.S3MboxKeySuffix, Body: JSON.stringify(data) }; s3.upload(params, function(err, response) { if (err) { if (CONSOLE_MESSAGES) console.log(new Date().toISOString(),'Error saving Mbox:',err); } callback(err, response); }); }
javascript
{ "resource": "" }
q39319
Event
train
function Event(type, listener, scope, once, instance) { // Store arguments this.type = type; this.listener = listener; this.scope = scope; this.once = once; this.instance = instance; }
javascript
{ "resource": "" }
q39320
render
train
function render(form, template) { const compiledRowTemplate = handlebars.compile( '<tr class="form-element">' + '<td class="key">{{key}}</td>' + '<td class="value">{{value}}</td>' + '</tr>'); const compiledTable = handlebars.compile( '<table><tbody>{{{rows}}}</tbody></table>'); const compiledTemplate = handlebars.compile(template); const formElements = form.map(({key, value}) => { if (key !== 'File') { return compiledRowTemplate({key, value: unescape(value)}); } return null; }); const formData = compiledTable({rows: formElements.join(' ')}); return compiledTemplate({formData}); }
javascript
{ "resource": "" }
q39321
encode
train
function encode(cache, API_URL, obj) { if (!obj) return null; if (!obj.href) return obj; var href = API_URL ? pack(obj.href, API_URL) : obj.href; var cached = cache.get(href); if (cached) return cached; var encoded = base64.encode(new Buffer(href)).toString(); cache.set(href, encoded); return encoded; }
javascript
{ "resource": "" }
q39322
encodeParams
train
function encodeParams(cache, API_URL, params) { var obj = {}, v; for (var k in params) { if (!params.hasOwnProperty(k)) continue; v = obj[k] = encode(cache, API_URL, params[k]); if (!v) return; } return obj; }
javascript
{ "resource": "" }
q39323
decode
train
function decode(cache, API_URL, str) { var cached = cache.get(str); if (typeof cached !== 'undefined') return cached; if (typeof str !== 'string') return null; var decoded = base64.decode(str).toString().replace(/\0/g, ''); var out = validate(decoded) ? {href: unpack(decoded, API_URL)} : str; // cache the decoded value since this ends up being pretty expensive cache.set(str, out); return out; }
javascript
{ "resource": "" }
q39324
decodeParams
train
function decodeParams(cache, API_URL, params) { var obj = {}, v; for (var k in params) { if (!params.hasOwnProperty(k)) continue; obj[k] = decode(cache, API_URL, params[k]); } return obj; }
javascript
{ "resource": "" }
q39325
pack
train
function pack(href, API_URL) { var parts = url.parse(href); var pn = API_URL.pathname || '/'; if (parts.host !== API_URL.host || parts.pathname.indexOf(pn) !== 0) return href; if (pn === '/') pn = ''; return parts.pathname.replace(pn, '~') + (parts.search || ''); }
javascript
{ "resource": "" }
q39326
callNativeComponent
train
function callNativeComponent (instanceId, ref, method, args, options) { return processCall(instanceId, { component: options.component, ref, method, args }) }
javascript
{ "resource": "" }
q39327
callNativeModule
train
function callNativeModule (instanceId, module, method, args, options) { return processCall(instanceId, { module, method, args }) }
javascript
{ "resource": "" }
q39328
train
function(v) { if(v instanceof Vec3){ return this.toVec3()._cross(v); } return new Vec3(0,0, this.x * v.y - this.y * v.x); }
javascript
{ "resource": "" }
q39329
train
function(m){ return new Vec2( this.x*m[0][0]+this.y*m[0][1], this.x*m[1][0]+this.y*m[1][1] ); }
javascript
{ "resource": "" }
q39330
train
function(theta){ return new Vec2( this.x*Math.cos(theta)-this.y*Math.sin(theta), this.x*Math.sin(theta)+this.y*Math.cos(theta) ); }
javascript
{ "resource": "" }
q39331
train
function(p){ this.x = Math.pow(this.x, p); this.y = Math.pow(this.y, p); return this; }
javascript
{ "resource": "" }
q39332
permuteOrder
train
function permuteOrder(order) { var norder = order.slice() norder.splice(order.indexOf(0), 1) norder.unshift(0) return norder }
javascript
{ "resource": "" }
q39333
train
function() { var config = {} registry.listServices(config, function(err, result) { if (err) return console.log(err); main.poll(registry, result, function(err) { if (err) return console.log(err); }); }) }
javascript
{ "resource": "" }
q39334
train
function(){ return { request: this.request.toJSON(), response: this.response.toJSON(), app: this.app.toJSON(), originalUrl: this.originalUrl, req: '<original node req>', res: '<original node res>', socket: '<original node socket>', }; }
javascript
{ "resource": "" }
q39335
mergeDefaultConfig
train
function mergeDefaultConfig(opts) { let devModeEnabled = isDevelopMode(); let debugModeEnabled = isDebugMode(); console.log('------------------------------------------------------------------------------------'); console.log(`Executing build for ` + (devModeEnabled ? ENV_DEVELOPMENT : ENV_PROD)); console.log('------------------------------------------------------------------------------------'); let config = { metadata: { ENV: devModeEnabled ? ENV_DEVELOPMENT : ENV_PROD }, devtool: 'source-map', debug: debugModeEnabled, entry: {}, output: { filename: devModeEnabled ? '[name].bundle.js' : '[name].[chunkhash].bundle.js', sourceMapFilename: devModeEnabled ? '[name].bundle.map' : '[name].[chunkhash].bundle.map', chunkFilename: devModeEnabled ? '[id].chunk.js' : '[id].[chunkhash].chunk.js' }, resolve: { cache: false, extensions: ['', '.ts', '.tsx', '.js', '.json', '.css', '.html'] }, module: { preLoaders: [], loaders: [] }, plugins: [], // we need this due to problems with es6-shim node: { global: 'window', progress: false, crypto: 'empty', module: false, clearImmediate: false, setImmediate: false } }; if (debugModeEnabled) { console.log(merge(config, opts)); console.log('------------------------------------------------------------------------------------'); } return merge(config, opts); }
javascript
{ "resource": "" }
q39336
resolveAnyGlobPatternsAsync
train
function resolveAnyGlobPatternsAsync(filesAndPatterns, rootSrcDir) { return resolveGlobsAsync(filesAndPatterns, rootSrcDir) .then(function(resolvedFiles) { var allFiles = insertResolvedFiles(filesAndPatterns, resolvedFiles); return allFiles.map(convertBackslashes); }); }
javascript
{ "resource": "" }
q39337
resolveGlobsAsync
train
function resolveGlobsAsync(filesAndPatterns, rootSrcDir) { var options = {cwd: rootSrcDir}; var tasks = {}; filesAndPatterns.forEach(function(fileOrPattern) { if (isGlobPattern(fileOrPattern)) { tasks[fileOrPattern] = underscore.partial(resolveGlobAsync, fileOrPattern, options); } }); // TODO: Add kew.nfcall() and use that instead. // https://github.com/Obvious/kew/pull/21 var deferred = kew.defer(); async.parallel(tasks, deferred.makeNodeResolver()); return deferred.promise; }
javascript
{ "resource": "" }
q39338
train
function() { if (xhr.readyState === 4 && xhr.status === 200) { return cb(null, JSON.parse(xhr.response)); } cb('error requesting ' + uri); }
javascript
{ "resource": "" }
q39339
extractTravelPlan
train
function extractTravelPlan(data) { let tickets = data.fullJourneys[0].cheapestTickets if (!tickets || tickets.length === 0) { return [] } let secondClass = tickets[0].tickets let firstClass = tickets[1].tickets let journeys = data.fullJourneys[0].journeys let date = data.fullJourneys[0].date // "25 Sep 2016" let journeyFromId = [] journeys.forEach(journey => journeyFromId[journey.id] = journey) let plans = [] let getPlan = (from, to, departure, arrival) => { return plans.find(plan => (plan.legs[0].from === from) && (plan.legs[0].to === to) && (plan.legs[0].departure === departure) && (plan.legs[0].arrival === arrival)) } let mkticket = (ticket, travelClass) => { let journey = journeyFromId[ticket.journeyId] let price = ticket.price // "81.40" if (!journey || !price) { return } let origin = station.name(journey.departureName) let destination = station.name(journey.arrivalName) let from = origin ? origin.id : journey.departureName let to = destination ? destination.id : journey.arrivalName let departure = String(parseTime(date, journey.departureTime)) let arrival = String(parseTime(date, journey.arrivalTime)) let plan = getPlan(from, to, departure, arrival) if (plan === undefined) { plan = { fares: [], legs: [{from, to, departure, arrival}], } plans.push(plan) } plan.fares.push({ class: travelClass, flexibility: 1, price: [{ cents: parsePrice(ticket.price), currency: 'GBP' }], }) } secondClass.map(ticket => mkticket(ticket, 2)) firstClass.map(ticket => mkticket(ticket, 1)) return plans }
javascript
{ "resource": "" }
q39340
getCookies
train
function getCookies() { return new Promise((resolve, reject) => { request.get(rootUrl, function(err, res, body) { if (err != null && res.statusCode !== 200) { reject(err || new Error('Accessing UK information failed')) return } resolve() }) }) }
javascript
{ "resource": "" }
q39341
WTFAmazon
train
function WTFAmazon (array) { var result = {}; array.map(function (item) { result[item.Key] = item.Value; }); return result; }
javascript
{ "resource": "" }
q39342
_prependPath
train
function _prependPath(key, base) { if ((typeof key) === "number" || key.match(/^[0-9]+$/)) key = "[" + key + "]"; else if (!key.match(Match.IdentifierString) || _jsKeywords.indexOf(key) !== -1) key = JSON.stringify([key]); if (base && base[0] !== "[") return key + '.' + base; return key + base; }
javascript
{ "resource": "" }
q39343
detach
train
function detach(el) { var parent = el.parentNode var next = el.nextSibling parent.removeChild(el) return function() { if (next) parent.insertBefore(el, next) else parent.appendChild(el) } }
javascript
{ "resource": "" }
q39344
train
function(sliceCount, options) { validateSliceCount(sliceCount) options = options || {} var slices = [] var step = 360 / sliceCount var halfStep = step / 2 var min = 0 var max = min + step var sliceNumber = 0 if (options.firstSliceFacesUp) { // first slice straddles angle 0 and is actually two slice objects slices.push(createSlice(0, 360 - halfStep, 360)) slices.push(createSlice(0, 0, halfStep)) // tweak to account for first slice already existing sliceNumber = 1 min = halfStep max = min + step } for (; sliceNumber < sliceCount; sliceNumber++, min += step, max += step) { slices.push(createSlice(sliceNumber, min, max)) } return createPie(slices, !!options.yDown) }
javascript
{ "resource": "" }
q39345
parseComment
train
function parseComment (comment) { const body = j('[' + comment + ']').nodes()[0].program.body const array = body[0].expression return array.elements }
javascript
{ "resource": "" }
q39346
identifierFactory
train
function identifierFactory (ast, reserved) { reserved = reserved || new Set ast.find(j.Identifier).forEach(path => { reserved.add(path.node.name) }) ast.find(j.FunctionDeclaration).forEach(path => { reserved.add(path.node.id.name) }) function identifier (name, suffix) { return j.identifier(identifier.string(name, suffix)) } identifier.string = function (name, suffix) { let sfx = suffix == null ? '' : suffix , unique = name + sfx , n = 0 while (reserved.has(unique)) { unique = name + (n++) + sfx } return unique } return identifier }
javascript
{ "resource": "" }
q39347
getFunctionSignature
train
function getFunctionSignature(fn) { let str = fn.toString() // Strip comments. str = str.replace(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, '') const match = str.match(/\(([^)]*)\)/) if (match) { let res = match[1] // Strip leading and trailing whitespace. res = res.replace(/^\s+|\s+$/g, '') let sig = res.split(/\s*,\s*/) if (sig.length === 1 && !sig[0]) { sig.length = 0 } const signature = [] for (let key of sig) { // TODO: Handle rest parameters. The position of the rest // parameter matters, so this requires some thought. The // following signatures are all different: // * function (...rest, foo, bar) // * function (foo, ...rest, bar) // * function (foo, bar, ...rest) // For now, just ignore rest parameters... if (key.indexOf('...') === 0) { continue } // If there is a default value defined, remove it from the // key. key = key.replace(/\s*=.*$/, '') // TODO: Should we do something with destructuring // assignments? signature.push(key) } return signature } else { return [] } }
javascript
{ "resource": "" }
q39348
blur
train
function blur(selector) { $timeout(function blurFocus() { // fix for iOS if (document && document.activeElement && document.activeElement.blur) { document.activeElement.blur(); } var el = jQuery(selector); if (el && el.length) { el[0].blur(); } }, 100); }
javascript
{ "resource": "" }
q39349
train
function() { var lib, name, names, _i, _len; lib = arguments[0], names = 2 <= arguments.length ? __slice.call(arguments, 1) : []; for (_i = 0, _len = names.length; _i < _len; _i++) { name = names[_i]; if (lib[name] == null) { return; } if (this[name] == null) { this[name] = {}; } if (!isObject(this[name])) { return; } mixin(this[name], lib[name]); } return this; }
javascript
{ "resource": "" }
q39350
menu
train
function menu( items, nextStep ) { const rl = RL.createInterface( { input: process.stdin, output: process.stdout } ); console.log(); items.forEach( function ( item, idx ) { var out = idx < 10 ? ' ' : ''; out += ( "" + ( 1 + idx ) + ") " ).yellow; out += item; console.log( out ); } ); console.log(); rl.question( "Your choice: ", ( ans ) => { rl.close(); var choice = parseInt( ans ); if ( isNaN( ans ) || ans < 1 || ans > items.length ) { menu( items, nextStep ); } else { console.log(); nextStep( choice ); } } ); }
javascript
{ "resource": "" }
q39351
isInEmptyFolder
train
function isInEmptyFolder() { var files = FS.readdirSync( '.' ); try { if ( files.length == 0 ) return true; console.log( Fatal.format( "You should be in an empty folder to create a new project!\n" + "If you continue, all the files in this folder will be DELETED!" ) ); console.log( "\nWe suggest that you create an fresh new directory, like this:" ); console.log( "\n> " + "mkdir my-project-folder".yellow.italic ); console.log( "> " + "cd my-project-folder".yellow.italic ); console.log( "> " + "tfw init".yellow.italic ); return false; } catch ( ex ) { fatal( "Fatal error in function `files`!\n" + JSON.stringify( ex, null, ' ' ) ); } }
javascript
{ "resource": "" }
q39352
isGitInstalled
train
function isGitInstalled() { var result = exec( "git --version", true ); try { if ( !result || result.indexOf( "git" ) < 0 || result.indexOf( "version" ) < 0 ) { console.log( Fatal.format( "`git` is required by the ToloFrameWork!\n" + "Please install it:" ) ); console.log( "\n> " + "sudo apt-get install git".yellow.italic ); return false; } return true; } catch ( ex ) { fatal( "Fatal error in function `result`!\n" + JSON.stringify( ex, null, ' ' ) ); } }
javascript
{ "resource": "" }
q39353
cleanDir
train
function cleanDir( path ) { var files = FS.readdirSync( path ); try { files.forEach( function ( file ) { var fullpath = Path.join( path, file ); if ( !FS.existsSync( fullpath ) ) return; var stat = FS.statSync( fullpath ); try { if ( stat.isDirectory() ) PathUtils.rmdir( fullpath ); else FS.unlinkSync( fullpath ); } catch ( ex ) { console.error( "Unable to delete `" + fullpath + "`!" ); console.error( ex ); } } ); } catch ( ex ) { fatal( "Fatal error in function `files`!\n" + JSON.stringify( ex, null, ' ' ) ); } }
javascript
{ "resource": "" }
q39354
checkHost
train
function checkHost(host,callback) { if(hostCache.get(host,callback)) { console.log('checkHost: Resolved %s from hostCache...',host); return true; } console.log('checkHost: Looking up %s...',host); var options = { host: host, port: 80, path: '/', method: 'GET' }; var req = http.request(options, function(res) { var data = ''; res.setEncoding('utf8'); res.on('data', function (chunk) { data += chunk; }); res.on('end', function () { hostCache.set(host,true); }); res.on('error',function() { hostCache.set(host,false); }); }); req.on('error',function() { hostCache.set(host,false); }); req.end(); }
javascript
{ "resource": "" }
q39355
gitCurrentBranch
train
function gitCurrentBranch() { return git('status --porcelain -b', stdout => { const status = gitUtil.extractStatus(stdout); return status.branch.split('...')[0]; }); }
javascript
{ "resource": "" }
q39356
node
train
function node(name, accessor) { if (!name) { return false } return { name: name, accessor: accessor ? accessor : false } }
javascript
{ "resource": "" }
q39357
execute
train
function execute(req, res) { // if we have a sparse db store we need // to ensure a database exists if(!this.store.databases[req.args[0]]) { this.store.getDatabase(req.args[0], {pattern: this.pattern}); } // update the connection with their selected db index req.conn.db = req.args[0]; res.send(null, Constants.OK); }
javascript
{ "resource": "" }
q39358
validate
train
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); var index = parseInt(args[0]); if(isNaN(index) || index < 0 || index >= info.conf.databases) { throw DatabaseIndex; } // update the index with the integer value // connection expects an integer args[0] = index; }
javascript
{ "resource": "" }
q39359
getOpenshiftEnvVars
train
function getOpenshiftEnvVars(params){ var appMbaas = params.appMbaas; var mbaasUrl = _parseMbaasUrl(appMbaas.mbaasUrl); var appEnvs = {}; appEnvs.FH_MBAAS_PROTOCOL = mbaasUrl.protocol; //App Mbaas Host. Used for apps calling mbaas hosts. appEnvs.FH_MBAAS_HOST = mbaasUrl.host; //Access key to verify apps calling Mbaas App APIs. appEnvs.FH_MBAAS_ENV_ACCESS_KEY = appMbaas.accessKey; //If the app is a service, ensure the FH_SERVICE_ACCESS_KEY env var is set. //This will allow authorised data sources to access the service using the X-FH-SERViCE-ACCESS-KEY header. if(appMbaas.isServiceApp){ appEnvs.FH_SERVICE_ACCESS_KEY = appMbaas.serviceAccessKey; } return appEnvs; }
javascript
{ "resource": "" }
q39360
getPath
train
function getPath(pathname) { var _paths = { }; _paths["app.home"] = path.join(process.env.HOME, ".docvy"); _paths["app.cache"] = path.join(_paths["app.home"], "cache"); _paths["app.cache.plugins"] = path.join(_paths["app.cache"], "plugins"); _paths["app.logs"] = path.join(_paths["app.home"], "logs"); _paths["app.plugins"] = path.join(_paths["app.home"], "plugins"); var target = _paths[pathname] || null; if (target) { mkdirp.sync(target); } return target; }
javascript
{ "resource": "" }
q39361
defineError
train
function defineError(code, message) { var ErrorClass = errors.helpers.generateClass(code); function ExportedError(err) { ErrorClass.call(this, message, err); return this; } util.inherits(ExportedError, ErrorClass); return ExportedError; }
javascript
{ "resource": "" }
q39362
updateVersion
train
async function updateVersion(file) { const { default: config } = await import(`${CONFIGS_PATH}/${file}`); const { packageName } = config; const packageInfoFile = `${PACKAGES_PATH}/${packageName}/package.json`; const { default: packageInfo } = await import(packageInfoFile); if (info.version !== packageInfo.version) { const newPackageInfo = { ...packageInfo, version: info.version, }; writeFileAsync(packageInfoFile, JSON.stringify(newPackageInfo, null, ' ')) .then( () => console.log(`Updated ${packageName} to ${info.version}`), error => console.log(error), ); } }
javascript
{ "resource": "" }
q39363
createFromMetadata
train
function createFromMetadata (connector, modelsMetadata) { if (!connector || !modelsMetadata) { throw new Error('Please provide both connector and metadata so Arrow could create models') } const loadModels = connector.config.generateModels return Object.keys(modelsMetadata).reduce(function (previousModels, modelName) { const persistModels = connector.config.persistModels if (loadModels && loadModels.indexOf(modelName) === -1) { return previousModels } const metadata = modelsMetadata[modelName] metadata.autogen = !!connector.config.modelAutogen metadata.generated = true metadata.connector = connector.name metadata.name = modelName dataValidator.validate(metadata, metadataSchema) if (persistModels) { utils.saveModelSync(createModelName(connector, modelName), metadata, connector.modelDir) } else { previousModels[modelName] = Arrow.createModel(createModelName(connector, modelName), metadata) } return previousModels }, {}) }
javascript
{ "resource": "" }
q39364
getRootModelName
train
function getRootModelName (model) { if (!model) { throw new Error('Please provide Arrow Model') } const namespaceDelimiter = '/' var parent = model while (parent._parent && parent._parent.name) { parent = parent._parent } if (!parent.name) { throw new Error('The provided model has no name or parent with name') } const name = parent.name.split(namespaceDelimiter).pop() return { nameOnly: name, nameOnlyPlural: pluralize(name), withNamespace: parent.name } }
javascript
{ "resource": "" }
q39365
train
function(options) { if (!_.isString(options.method)) { throw new Error('"method" must be a string, got ' + options.method); } else if (!_.isString(options.url)) { throw new Error('"url" must be a string, got ' + options.url); } return options; }
javascript
{ "resource": "" }
q39366
train
function(filterIndex, options) { if (options === undefined) { throw new Error('Request filter at index ' + filterIndex + ' returned nothing; it must return the filtered request options'); } else if (!_.isObject(options)) { throw new Error('Expected request filter at index ' + filterIndex + ' to return the request options as an object, got ' + typeof(options)); } return options; }
javascript
{ "resource": "" }
q39367
MailjetProvider
train
function MailjetProvider(apiKey, apiSecret, options) { if (typeof apiKey !== 'string' || typeof apiSecret !== 'string') { throw new Error('Invalid parameters'); } options = options || {}; if (typeof options.apiSecure === 'undefined') options.apiSecure = true; options.apiHostname = options.apiHostname || 'api.mailjet.com'; options.apiPort = options.apiPort || (options.apiSecure ? 443 : 80); this.apiKey = apiKey; this.apiSecret = apiSecret; this.options = options; }
javascript
{ "resource": "" }
q39368
getFormattedDate
train
function getFormattedDate(date, lang, type) { date = date || new Date(); lang = lang || 'en'; type = type || 'long'; // set the language for en if (lang === 'en' && type === 'short') { lang = 'enshort'; } if (lang === 'en' && type === 'medium') { lang = 'enmedium'; } // get the date string return moment(date).locale(lang).fromNow(); }
javascript
{ "resource": "" }
q39369
train
function (username, channel) { var userChannels = this.getUserNotifications(username); // if the user doesn't already have an entry add one if (userChannels === null) { userChannels = []; // update the user to add them to the latest videos list this.latestVideos.getLatestVideos(username); this.notifications.push({ username: username, channels: userChannels }); } // dont allow duplicate channel names if (userChannels.indexOf(channel) !== -1) { return false; } // add the channel to the user and save data userChannels.push(channel); this.saveNotifications(); return true; }
javascript
{ "resource": "" }
q39370
train
function (username, channel) { var userChannels = this.getUserNotifications(username); // dont remove if they dont exist if (userChannels === null) { return false; } var index = userChannels.indexOf(channel); // dont remove if the channel doesnt exist if (index < 0) { return false; } // remove the channel userChannels.splice(index, 1); //if no channels left remove the entire user if (userChannels.length === 0) { var userIndex = -1; this.notifications.some(function (element, index) { if (element.username === username) { userIndex = index; return true; } return false; }); this.notifications.splice(userIndex, 1); this.latestVideos.removeUser(username); } // save the new data this.saveNotifications(); return true; }
javascript
{ "resource": "" }
q39371
train
function (username, channel) { var list = this.getUserNotifications(username); // if we are not tracking the user there is no notifications if (list === null) { return false; } // return if the channel is in the users list return list.indexOf(channel) >= 0; }
javascript
{ "resource": "" }
q39372
train
function (username) { var channels = null; // get the user's object this.notifications.some(function (element) { if (element.username === username) { channels = element.channels; return true; } return false; }); return channels; }
javascript
{ "resource": "" }
q39373
createServer
train
function createServer() { function app(req, res, next){ app.handle(req, res, function(){ res.end("", 'utf8'); }); } merge(app, proto); merge(app, EventEmitter.prototype); app.route = '/'; app.stack = []; return app; }
javascript
{ "resource": "" }
q39374
Request
train
function Request(method, args, callback) { this.handle.send('layer', [method, args], function (content) { callback.apply({}, content); }); }
javascript
{ "resource": "" }
q39375
runAsyncMiddleware
train
function runAsyncMiddleware(wares, event, payload, callback) { if (wares.length) { var ware = wares[0]; var restWares = wares.slice(1); ware(event, payload, function () { runAsyncMiddleware(restWares, event, payload, callback); }); } else { callback && callback(payload); } }
javascript
{ "resource": "" }
q39376
isEmptyObject
train
function isEmptyObject(item) { if (item === undefined || item === null) { return false; } return (Object.keys(item).length === 0 && JSON.stringify(item) === JSON.stringify({})); }
javascript
{ "resource": "" }
q39377
execute
train
function execute(req, res) { res.send(null, this.info.toString(req.args[0] ? '' + req.args[0] : null)); }
javascript
{ "resource": "" }
q39378
next
train
function next( session ) { if ( session !== this._session ) return; if ( this._index >= this._tasks.length ) { this._index = 0; this._started = false; delete this._session; this._onEnd( this ); return; } const that = this, tsk = this._tasks[ this._index++ ]; if ( this._debug ) { console.info( `[dom.fx] tsk[${this._index - 1}]: `, tsk.label, `(${Date.now() - this._startTime} ms)`, tsk.args, session ); } tsk( function () { delay( next.bind( that, session ) ); }, true ); }
javascript
{ "resource": "" }
q39379
combineReducers
train
function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (process.env.NODE_ENV !== 'production') { if (typeof reducers[key] === 'undefined') { (0, _warning2.default)('No reducer provided for key "' + key + '"'); } } if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); var unexpectedKeyCache = void 0; if (process.env.NODE_ENV !== 'production') { unexpectedKeyCache = {}; } var shapeAssertionError = void 0; try { assertReducerShape(finalReducers); } catch (e) { shapeAssertionError = e; } return function combination() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var action = arguments[1]; if (shapeAssertionError) { throw shapeAssertionError; } if (process.env.NODE_ENV !== 'production') { var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache); if (warningMessage) { (0, _warning2.default)(warningMessage); } } var hasChanged = false; var nextState = {}; for (var _i = 0; _i < finalReducerKeys.length; _i++) { var _key = finalReducerKeys[_i]; var reducer = finalReducers[_key]; var previousStateForKey = state[_key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(_key, action); throw new Error(errorMessage); } nextState[_key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; }
javascript
{ "resource": "" }
q39380
bind
train
function bind(element, properties) { var bindings = Object.keys(properties).filter(function (name) { var property = properties[name]; if (Object.prototype.hasOwnProperty.call(property, 'statePath')) { if (!property.readOnly && property.notify) { console.warn('PolymerRedux: <' + element.constructor.is + '>.' + name + ' has "notify" enabled, two-way bindings goes against Redux\'s paradigm'); } return true; } return false; }); /** * Updates an element's properties with the given state. * * @private * @param {Object} state */ var update = function update(state) { var propertiesChanged = false; bindings.forEach(function (name) { // Perhaps .reduce() to a boolean? var statePath = properties[name].statePath; var value = typeof statePath === 'function' ? statePath.call(element, state) : (0, _path.get)(state, statePath); var changed = element._setPendingPropertyOrPath(name, value, true); propertiesChanged = propertiesChanged || changed; }); if (propertiesChanged) { element._invalidateProperties(); } }; // Redux listener var unsubscribe = store.subscribe(function () { var detail = store.getState(); update(detail); element.dispatchEvent(new window.CustomEvent('state-changed', { detail: detail })); }); subscribers.set(element, unsubscribe); return update(store.getState()); }
javascript
{ "resource": "" }
q39381
update
train
function update(state) { var propertiesChanged = false; bindings.forEach(function (name) { // Perhaps .reduce() to a boolean? var statePath = properties[name].statePath; var value = typeof statePath === 'function' ? statePath.call(element, state) : (0, _path.get)(state, statePath); var changed = element._setPendingPropertyOrPath(name, value, true); propertiesChanged = propertiesChanged || changed; }); if (propertiesChanged) { element._invalidateProperties(); } }
javascript
{ "resource": "" }
q39382
collect
train
function collect(what, which) { var res = {}; while (what) { res = Object.assign({}, what[which], res); // Respect prototype priority what = Object.getPrototypeOf(what); } return res; }
javascript
{ "resource": "" }
q39383
Range
train
function Range(min, max, step) { var scope = null , re = /^([A-Za-z]|\d+)\.{2}([A-Za-z]|\d+)$/; if (typeof min === 'string' && min.match(re)) { step = max; scope = min.split('..'); min = cast(scope[0]); max = cast(scope[1]); } this.min(min); this.max(max); this.step(step); }
javascript
{ "resource": "" }
q39384
ip
train
async function ip(options = {}) { const { host = 'https://api.ipify.org', } = options const res = await rqt(host) return res }
javascript
{ "resource": "" }
q39385
trim
train
function trim( str, chr ){ if ( !chr ){ chr = '\\s'; } return str.replace( new RegExp('^'+chr+'+|'+chr+'+$','g'), '' ); }
javascript
{ "resource": "" }
q39386
shareEvent
train
function shareEvent(eventName, source, target, once = false) { verifyEventEmitter(source, 'source') verifyEventEmitter(target, 'target') const cb = target.emit.bind(target, eventName) source[once ? 'once' : 'on'](eventName, cb) return cb }
javascript
{ "resource": "" }
q39387
stat
train
function stat(p) { var def = Q.defer(); fs.stat(p, def.makeNodeResolver()); return def.promise; }
javascript
{ "resource": "" }
q39388
list
train
function list(p) { var def = Q.defer(); fs.readdir(p, def.makeNodeResolver()); return def.promise; }
javascript
{ "resource": "" }
q39389
writeFile
train
function writeFile(p, data, encoding) { var def = Q.defer(); fs.writeFile(p, data, encoding, def.makeNodeResolver()); return def.promise }
javascript
{ "resource": "" }
q39390
readFile
train
function readFile(p, encoding) { var def = Q.defer(); fs.readFile(p, encoding, def.makeNodeResolver()); return def.promise }
javascript
{ "resource": "" }
q39391
listTree
train
function listTree(basePath, guard) { basePath = path.resolve(basePath); return stat(basePath).then( function(topStat) { var results = []; if (!guard || guard(basePath, topStat)) { results.push(basePath); } if (topStat.isDirectory()) { return list(basePath).then( function(items) { return Q.all(items.map( function(item) { var fullPath = path.join(basePath, item); return listTree(fullPath, guard); } )); } ).then( function(sets) { return Array.prototype.concat.apply(results, sets).sort(); } ); } return results; }, function() { // not found or not accessible, so the list is empty return []; } ); }
javascript
{ "resource": "" }
q39392
popcount
train
function popcount(i) { i = i - ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; }
javascript
{ "resource": "" }
q39393
insertAt
train
function insertAt(items, item, index) { var copy = items.slice(); copy.splice(index, 0, item); return copy; }
javascript
{ "resource": "" }
q39394
replaceAt
train
function replaceAt(items, item, index) { var copy = items.slice(); copy.splice(index, 1, item); return copy; }
javascript
{ "resource": "" }
q39395
removeAt
train
function removeAt(items, index) { var copy = items.slice(); copy.splice(index, 1); return copy; }
javascript
{ "resource": "" }
q39396
find
train
function find(items, pred) { var len = items.length, i = -1; while(++i < len) { if (pred(items[i], i)) { return items[i]; } } return null; }
javascript
{ "resource": "" }
q39397
watchCompiler
train
function watchCompiler(compiler, options={}){ let watching = false log('Watch Building') const startWatchTime = Date.now() const watchConfig = { // watch options: //aggregateTimeout: 300, // wait so long for more changes //poll: true // use polling instead of native watchers // pass a number to set the polling interval } options.onRebuild = options.onRebuild || function(){} return new Promise(function(res,rej){ //webpack watch functionality compiler.watch(watchConfig, function(err,stats){ if(err)return rej(err) if(watching){ log('Rebuilt '+getServerTime()) options.onRebuild(stats) }else{ watching = true log('Watching '+(Date.now()-startWatchTime)/1000+' seconds') res( this ) } }); }) }
javascript
{ "resource": "" }
q39398
step4
train
function step4 ( folder ) { while ( folder.nodes.length === 1 && folder.nodes [ 0 ].nodes ) { //folder.hidden = true; folder = folder.nodes [ 0 ]; } return folder; }
javascript
{ "resource": "" }
q39399
step5
train
function step5 ( folder ) { folder.filenames = folder.filenames || folder.nodes.map ( function ( node ) { return node.nodes ? step5 ( node ).filenames : node.name.toLowerCase (); }).join ( " " ); return folder; }
javascript
{ "resource": "" }