_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q40500
train
function (req, res, next) { if (periodic.app.controller.extension.reactadmin) { let reactadmin = periodic.app.controller.extension.reactadmin; // console.log({ reactadmin }); // console.log('ensureAuthenticated req.session', req.session); // console.log('ensureAuthenticated req.user', req.user); next(); } else { let adminPostRoute = res.locals.adminPostRoute || 'auth'; var token = req.controllerData.token, // current_user, decode_token; decode(token, function (err, decode) { if (err) { CoreController.handleDocumentQueryErrorResponse({ err: err, res: res, req: req, errorflash: err.message, }); } else { decode_token = decode; //Find the User by their token User.findOne({ 'attributes.reset_token': token, }, function (err, found_user) { if (err || !found_user) { req.flash('error', 'Password reset token is invalid.'); res.redirect(loginExtSettings.settings.authLoginPath); } // current_user = found_user; //Check to make sure token hasn't expired //Check to make sure token is valid and sign by us else if (found_user.email !== decode_token.email && found_user.api_key !== decode_token.api_key) { req.flash('error', 'This token is not valid please try again'); res.redirect(loginExtSettings.settings.authLoginPath); } else { CoreController.getPluginViewDefaultTemplate({ viewname: 'user/reset', themefileext: appSettings.templatefileextension, extname: 'periodicjs.ext.login', }, function (err, templatepath) { CoreController.handleDocumentQueryRender({ res: res, req: req, renderView: templatepath, responseData: { pagedata: { title: 'Reset Password', current_user: found_user, }, user: req.user, adminPostRoute: adminPostRoute, }, }); }); } }); } }); } }
javascript
{ "resource": "" }
q40501
train
function (req, res, next) { // console.log('req.body', req.body); // console.log('req.params', req.params); var user_token = req.params.token || req.body.token; //req.controllerData.token; waterfall([ function (cb) { cb(null, req, res, next); }, invalidateUserToken, resetPassword, saveUser, emailResetPasswordNotification, ], function (err, results) { if (periodic.app.controller.extension.reactadmin) { let reactadmin = periodic.app.controller.extension.reactadmin; if (err) { res.status(400).send({ result: 'error', data: { error:err.toString(), }, }); } else { res.status(200).send({ result: 'success', data:'Password successfully changed', }); } } else { // console.log('These are the err', err); // console.log('These are the results', results); CoreController.respondInKind({ req: req, res: res, err: err, responseData: results || {}, callback: function (req, res /*,responseData*/ ) { // console.log('err',err,'/auth/reset/' + user_token); if (err) { // console.log('return to reset'); req.flash('error', err.message); res.redirect('/auth/reset/' + user_token); } else { // console.log('no return to x'); req.flash('success', 'Password Sucessfully Changed!'); res.redirect(loginExtSettings.settings.authLoginPath); } }, }); } }); }
javascript
{ "resource": "" }
q40502
createSub
train
function createSub(value, computed) { if (isArray(value)) { return new List(value, computed); } else if (isObject(value)) { if (isImmutable(value)) { return value; } else if (value.constructor === Object) { return new Struct(value, computed); } return new Value(value, computed); } return new Value(value, computed); }
javascript
{ "resource": "" }
q40503
Abstract
train
function Abstract(value, data, computed) { this.value = value; this.data = data && each(data, function (item) { return createSub(item); }); this.computedProps = computed; }
javascript
{ "resource": "" }
q40504
train
function(name, schema, callback){ var self = this; this.db.serialize(function() { self.db.run("CREATE TABLE IF NOT EXISTS\"" + name + "\" " + schema, callback); }); }
javascript
{ "resource": "" }
q40505
train
function () { this.el = element(by.tagName('todo')); this.available = function() { return this.el.element(by.binding('$ctrl.todos.length')).getText(); }; this.uncompleted = function() { return this.el.element(by.binding('$ctrl.uncompleted()')).getText(); }; this.todos = function() { return this.el.all(by.repeater('todo in $ctrl.todos')); }; this.todo = function (index) { return new Todo(this.todos().get(index)); }; this.error = function() { return this.el.element(by.binding('$ctrl.error')).getText(); }; // actions this.add = function (description) { return this.el.element(by.model('$ctrl.description')).clear().sendKeys(description, protractor.Key.ENTER); }; this.archive = function() { return this.el.element(by.css('[ng-click="$ctrl.archive()"]')).click(); }; }
javascript
{ "resource": "" }
q40506
train
function (id) { var self = this; self._unpublishedBuffer.remove(id); // To keep the contract "buffer is never empty in STEADY phase unless the // everything matching fits into published" true, we poll everything as soon // as we see the buffer becoming empty. if (! self._unpublishedBuffer.size() && ! self._safeAppendToBuffer) self._needToPollQuery(); }
javascript
{ "resource": "" }
q40507
train
function (doc) { var self = this; var id = doc._id; if (self._published.has(id)) throw Error("tried to add something already published " + id); if (self._limit && self._unpublishedBuffer.has(id)) throw Error("tried to add something already existed in buffer " + id); var limit = self._limit; var comparator = self._comparator; var maxPublished = (limit && self._published.size() > 0) ? self._published.get(self._published.maxElementId()) : null; var maxBuffered = (limit && self._unpublishedBuffer.size() > 0) ? self._unpublishedBuffer.get(self._unpublishedBuffer.maxElementId()) : null; // The query is unlimited or didn't publish enough documents yet or the new // document would fit into published set pushing the maximum element out, // then we need to publish the doc. var toPublish = ! limit || self._published.size() < limit || comparator(doc, maxPublished) < 0; // Otherwise we might need to buffer it (only in case of limited query). // Buffering is allowed if the buffer is not filled up yet and all matching // docs are either in the published set or in the buffer. var canAppendToBuffer = !toPublish && self._safeAppendToBuffer && self._unpublishedBuffer.size() < limit; // Or if it is small enough to be safely inserted to the middle or the // beginning of the buffer. var canInsertIntoBuffer = !toPublish && maxBuffered && comparator(doc, maxBuffered) <= 0; var toBuffer = canAppendToBuffer || canInsertIntoBuffer; if (toPublish) { self._addPublished(id, doc); } else if (toBuffer) { self._addBuffered(id, doc); } else { // dropping it and not saving to the cache self._safeAppendToBuffer = false; } }
javascript
{ "resource": "" }
q40508
train
function (id) { var self = this; if (! self._published.has(id) && ! self._limit) throw Error("tried to remove something matching but not cached " + id); if (self._published.has(id)) { self._removePublished(id); } else if (self._unpublishedBuffer.has(id)) { self._removeBuffered(id); } }
javascript
{ "resource": "" }
q40509
train
function () { var self = this; if (self._stopped) return; self._stopped = true; _.each(self._stopHandles, function (handle) { handle.stop(); }); // Note: we *don't* use multiplexer.onFlush here because this stop // callback is actually invoked by the multiplexer itself when it has // determined that there are no handles left. So nothing is actually going // to get flushed (and it's probably not valid to call methods on the // dying multiplexer). _.each(self._writesToCommitWhenWeReachSteady, function (w) { w.committed(); }); self._writesToCommitWhenWeReachSteady = null; // Proactively drop references to potentially big things. self._published = null; self._unpublishedBuffer = null; self._needToFetch = null; self._currentlyFetching = null; self._oplogEntryHandle = null; self._listenersHandle = null; Package.facts && Package.facts.Facts.incrementServerFact( "mongo-livedata", "observe-drivers-oplog", -1); }
javascript
{ "resource": "" }
q40510
addBinaries
train
function addBinaries(binaries) { var SLICE = Array.prototype.slice; //iterate backwards to mimic normal resolution order for (var i = binaries.length-1; i >= 0; i--) { var parts = binaries[i].split('/'); (function() {var name = parts[parts.length-1]; exports[name] = function() { //grab the last argument, which might be a callback var cbs = SLICE.call(arguments, 3); //assume none of the args we got were handlers var args = SLICE.call(arguments); var argLength = args.length; var cb, stdoutHandler, stderrHandler, options; if (args[argLength-3] instanceof Function) { //we have all 3 stderrHandler = args.pop(); stdoutHandler = args.pop(); cb = args.pop(); } else if (arguments[argLength-2] instanceof Function) { //we have cb and stdout stdoutHandler = args.pop(); cb = args.pop(); } else if (arguments[argLength-1] instanceof Function) { //we have cb only cb = args.pop(); } //if the last arg is an object, it's the options object var lastArg = args[args.length-1]; if (typeof lastArg == 'object' && !lastArg.length) { options = args.pop(); } //if the first argument was an array, the args were passed as //an array if (args[0] instanceof Array) { args = args[0]; } return runCommand(name, args, options, cb, stdoutHandler, stderrHandler); };})(); } }
javascript
{ "resource": "" }
q40511
train
function() { var extended = {}, deep = false, i = 0, length = arguments.length; if (Object.prototype.toString.call(arguments[0]) === '[object Boolean]'){ deep = arguments[0]; i++; } var merge = function(obj) { for (var prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') { extended[prop] = window.AB.extend(true, extended[prop], obj[prop]); } else { extended[prop] = obj[prop]; } } } }; for (; i < length; i++) { merge(arguments[i]); } return extended; }
javascript
{ "resource": "" }
q40512
createApp
train
async function createApp(middlewareConfig) { const app = new Koa() const middleware = await setupMiddleware(middlewareConfig, app) if (app.env == 'production') { app.proxy = true } return { app, middleware, } }
javascript
{ "resource": "" }
q40513
train
function (defaults, attr, custom) { var resolvedPath; if (defaults === undefined || defaults[attr] === undefined) { throw new Error('Missing Parameter', 'Expect a given defaults object'); } if (attr === undefined) { throw new Error('Missing Parameter', 'Expect a given attribute'); } if (custom === undefined || custom[attr] === undefined) { resolvedPath = path.resolve(defaults[attr]); } else { resolvedPath = path.resolve(custom[attr]); } return resolvedPath; }
javascript
{ "resource": "" }
q40514
train
function (content, type) { var results = {}; if (content === undefined) { return results; } _.forEach(content, function (element, key) { if (element === undefined || element.type === undefined || element.type !== type) { return; } results[key] = element; }); return results; }
javascript
{ "resource": "" }
q40515
train
function (content, type) { var results = []; if (content === undefined) { return results; } _.forEach(content, function (element) { if (element === undefined || element.type === undefined || element.type !== type) { return; } _.forEach(element.files, function (file) { var fragment = element[file]; // filter collection of posts, these are commonly category fragments if (fragment === undefined || fragment.posts !== undefined) { return; } results.push(fragment); }); }); return results; }
javascript
{ "resource": "" }
q40516
train
function (file, parent, type) { var fileDetails = path.parse(file), filePath = (type === 'static') ? path.join(fileDetails.dir, fileDetails.name + fileDetails.ext) : path.join(fileDetails.dir, fileDetails.name); return { name: filePath, parentDir: parent, href: parent + filePath }; }
javascript
{ "resource": "" }
q40517
Accumulator
train
function Accumulator(name, deps, fragment, resultsFn, options) { if (!(this instanceof Accumulator)) { return new Accumulator(name, deps, fragment, resultsFn, options); } Task.apply(this, Array.prototype.slice.call(arguments)); this.fragment = fragment; if (!_.isFunction(resultsFn)) { throw new Error('You must provide a function to indicate when the accumulator is complete'); } this.resultsFn = resultsFn; this.options = options || {}; }
javascript
{ "resource": "" }
q40518
constructor
train
function constructor(options, error, name) { Pagelet.prototype.constructor.call(this, options); if (name) this.name = name; this.data = error instanceof Error ? error : {}; }
javascript
{ "resource": "" }
q40519
get
train
function get(render) { render(null, { env: this.env, message: this.data.message, stack: this.env !== 'production' ? this.data.stack : '' }); }
javascript
{ "resource": "" }
q40520
pushTask
train
function pushTask(client, task) { /*jshint validthis: true */ if (!this.tasks[client]) { this.tasks[client] = []; } this.tasks[client].push(task); }
javascript
{ "resource": "" }
q40521
Cache
train
function Cache(opts) { //debug.log('new Cache'); opts = opts || {}; debug.assert(opts).is('object'); /** {boolean} True if this cache is using cursors */ this._has_cursors = opts.cursors ? true : false; // All cursors in a VariableStore if(this._has_cursors) { this._cursors = new VariableStore(); this._parents = new VariableStore(); this._cursor_map = {}; } /** Store for all objects */ this.objects = new VariableStore(); /** Array of current parents of the element which we are scanning -- this is used to find circular references */ this._current_parents = []; /** Array of cursors pointing to circular references */ this.circulars = []; }
javascript
{ "resource": "" }
q40522
train
function(plugin_dir, src, project_dir, dest, link) { var target_path = common.resolveTargetPath(project_dir, dest); if (fs.existsSync(target_path)) throw new Error('"' + target_path + '" already exists!'); common.copyFile(plugin_dir, src, project_dir, dest, !!link); }
javascript
{ "resource": "" }
q40523
Peer
train
function Peer(internalPeer){ Emitter.Target.call(this,emitter); this[rooms] = {}; this[pids] = {}; this[ip] = internalPeer; plugins.give('peer',this); }
javascript
{ "resource": "" }
q40524
Info
train
function Info(state) { this.state = state; this.conf = state.conf; this.stats = state.stats; this.name = pkg.name; this.version = pkg.version; }
javascript
{ "resource": "" }
q40525
getServer
train
function getServer() { var o = {} , uptime = process.uptime() o.version = this.version; o.os = process.platform; o.arch = process.arch; o.process_id = process.pid; o.tcp_port = this.state.addr && this.state.addr.port ? this.state.addr.port : NA; o.uptime_in_seconds = uptime; o.uptime_in_days = Math.floor(uptime / DAY_SECS); o.hz = this.conf.get(ConfigKey.HZ); o.config_file = this.conf.isDefault() ? '' : this.conf.getFile(); return o; }
javascript
{ "resource": "" }
q40526
getMemory
train
function getMemory(rusage) { var o = {}, mem = process.memoryUsage(); o.used_memory = mem.heapUsed; o.used_memory_human = bytes.humanize(mem.heapUsed, 2, true); o.used_memory_rss = mem.rss; o.used_memory_peak = rusage.maxrss; o.used_memory_peak_human = bytes.humanize(rusage.maxrss, 2, true); return o; }
javascript
{ "resource": "" }
q40527
getStats
train
function getStats() { var o = {}; o.total_connections_received = this.stats.connections; o.total_commands_processed = this.stats.commands; o.total_net_input_bytes = this.stats.ibytes; o.total_net_output_bytes = this.stats.obytes; o.rejected_connections = this.stats.rejected; o.expired_keys = this.stats.expired; o.keyspace_hits = this.stats.hits; o.keyspace_misses = this.stats.misses; o.pubsub_channels = this.stats.pubsub_channels; o.pubsub_patterns = this.stats.pubsub_patterns; return o; }
javascript
{ "resource": "" }
q40528
getCpu
train
function getCpu(rusage) { var o = {}; //console.dir(rusage); o.used_cpu_sys = rusage.stime.toFixed(2); o.used_cpu_user = rusage.utime.toFixed(2); return o; }
javascript
{ "resource": "" }
q40529
getKeyspace
train
function getKeyspace() { var o = {} , i , db , size; for(i in this.state.store.databases) { db = this.state.store.databases[i]; size = db.dbsize(); if(size) { o['db' + i] = util.format('keys=%s,expires=%s', size, db.expiring); } } return o; }
javascript
{ "resource": "" }
q40530
getObject
train
function getObject(section) { var o = {} , i , k , name , method , sections = section ? [section] : keys , rusage = proc.usage(); for(i = 0;i < sections.length;i++) { k = sections[i]; name = k.charAt(0).toUpperCase() + k.substr(1); method = 'get' + name o[k] = { header: name, data: this[method](rusage) } } return o; }
javascript
{ "resource": "" }
q40531
execute
train
function execute(req, res) { var t = systime(); res.send(null, [t.s, t.m]); }
javascript
{ "resource": "" }
q40532
train
function (filePath) { if (0 === filePath.indexOf(process.cwd())) { filePath = path.relative(process.cwd(), filePath); } if (0 !== filePath.indexOf("./") && 0 !== filePath.indexOf("/")) { filePath = "./" + filePath; } return filePath; }
javascript
{ "resource": "" }
q40533
train
function(body, error, code, errorTraceId, errorUserTitle, errorUserMessage) { _$jscmd("utils.js", "line", 104); //TODO: support errorTraceId //TODO: errorUserTitle and errorUserMessage should be change from strings to ints (==code) to support localization var response = {}; //set code if (_$jscmd("utils.js", "cond", "107_7_26", !__isNullOrUndefined(code))) { _$jscmd("utils.js", "line", 108); response.code = code; } else { if (_$jscmd("utils.js", "cond", "111_8_26", !__isNullOrUndefined(body))) response.code = 0; else //if (!__isNullOrUndefined(error)) response.code = 1e3; } //set body if (_$jscmd("utils.js", "cond", "118_7_26", !__isNullOrUndefined(body))) response.body = body; //set error if (_$jscmd("utils.js", "cond", "122_7_27", !__isNullOrUndefined(error))) { _$jscmd("utils.js", "line", 123); response.error = error; //set errorTraceId if (_$jscmd("utils.js", "cond", "126_8_34", !__isNullOrUndefined(errorTraceId))) response.errorTraceId = errorTraceId; //set errorUserTitle if (_$jscmd("utils.js", "cond", "130_8_36", !__isNullOrUndefined(errorUserTitle))) response.errorUserTitle = errorUserTitle; else { _$jscmd("utils.js", "line", 134); //TODO: this is not the real implementation response.errorUserTitle = "Bolt Error " + response.code.toString(); } //set errorUserMessage if (_$jscmd("utils.js", "cond", "138_8_38", !__isNullOrUndefined(errorUserMessage))) response.errorUserMessage = errorUserMessage; else { _$jscmd("utils.js", "line", 142); //TODO: this is not the real implementation response.errorUserMessage = errors[response.code]; } } _$jscmd("utils.js", "line", 146); return JSON.stringify(response); }
javascript
{ "resource": "" }
q40534
ErrorNotFound
train
function ErrorNotFound (message, data) { Error.call(this); // Add Information this.name = 'ErrorNotFound'; this.type = 'client'; this.status = 404; if (message) { this.message = message; } if (data) { this.data = {}; if (data.method) { this.data.method = data.method; } if (data.path) { this.data.path = data.path; } } }
javascript
{ "resource": "" }
q40535
hasChild
train
function hasChild(child, element) { assert(child !== undefined, 'Child is undefined'); assertType(element, Node, true, 'Parameter \'element\', if specified, must be a Node'); if (typeof child === 'string') { return !noval(getChild(element, child, true)); } else { if (!element || element === window || element === document) element = document.body; if (element.shadowRoot) element = element.shadowRoot; while (!noval(child) && child !== document) { child = child.parentNode; if (child === element) return true; } return false; } }
javascript
{ "resource": "" }
q40536
lint
train
function lint(p) { return () => { gulp.src(p).pipe(g.eslint()) .pipe(g.eslint.format()) .pipe(g.eslint.failOnError()); }; }
javascript
{ "resource": "" }
q40537
train
function(data, done) { if(!this._key) { done('no key found for metadata'); return; } var key = data[this._key]; var self = this; this._getCollection(function(err) { if(err) { done(err); } var kobj = {}; kobj[self._key.getName()] = key; self._collection.find(kobj).toArray(function(err, docs) { if(docs.length > 0) { data._id = docs[0]._id; } self._collection.save(data, function(err, count) { self._db.close(); done(err); }); }); }); }
javascript
{ "resource": "" }
q40538
train
function(key, done) { if(!this._key) { done('no key found for metadata'); return; } var self = this; this._getCollection(function(err) { if(err) { done(err); } var kobj = {}; kobj[self._key.getName()] = key; self._collection.find(kobj).toArray(function(err, docs) { var ret; if(!err && docs.length !== 0) { ret = docs[0]; } self._collection.remove(kobj, function(err, result) { self._db.close(); done(err, ret); }); }); }); }
javascript
{ "resource": "" }
q40539
addRepository
train
function addRepository(name, rep, directory, gitOptions, options) { var userConfig = options || {}; REPOSITORIES.push(_.extend({ name: name, options: _.extend({ repository: rep, directory: directory || name }, gitOptions || {}) }, userConfig)); }
javascript
{ "resource": "" }
q40540
checkCRLF
train
function checkCRLF() { /*function check if the current character is NEWLINE or RETURN if RETURN it checks if the next is NEWLINE (CRLF) afterwards it sets the charIndex after the NEWLINE, RETURN OR CRLF and currentCharacter to the character at index charIndex*/ //check if current character at charIndex is NEWLINE (set eol) //adds 1 to charIndex if ((currentCharacter = text.charCodeAt(charIndex++)) === NEWLINE) eol = true; //checks if equal to RETURN else if (currentCharacter === RETURN) { eol = true; //checks next character equal to NEWLINE and adds 1 to charindex (total =2) if (text.charCodeAt(charIndex) === NEWLINE) ++charIndex; } return eol; }
javascript
{ "resource": "" }
q40541
validate
train
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); var source = '' + args[0] , destination = '' + args[1]; if(!info.db.getKey(args[0], info)) { throw NoSuchKey; }else if(source === destination) { throw SourceDestination; } args[0] = source; args[1] = destination; }
javascript
{ "resource": "" }
q40542
getIntersectRect
train
function getIntersectRect() { let n = arguments.length; if (!assert(n > 0, 'This method requires at least 1 argument specified.')) return null; let rect = {}; let currRect, nextRect; for (let i = 0; i < n; i++) { if (!currRect) currRect = getRect(arguments[i]); if (!assert(currRect, 'Invalid computed rect.')) return null; if (i === 0 && ((i + 1) === n)) { nextRect = getRect(window); } else if ((i + 1) < n) { nextRect = getRect(arguments[i + 1]); } else { break; } if (!assert(nextRect, 'Invalid computed rect.')) return null; rect.width = Math.max(0.0, Math.min(currRect.right, nextRect.right) - Math.max(currRect.left, nextRect.left)); rect.height = Math.max(0.0, Math.min(currRect.bottom, nextRect.bottom) - Math.max(currRect.top, nextRect.top)); rect.top = Math.max(currRect.top, nextRect.top); rect.left = Math.max(currRect.left, nextRect.left); rect.bottom = rect.top + rect.height; rect.right = rect.left + rect.width; if (rect.width * rect.height === 0) { rect.width = 0; rect.height = 0; rect.top = 0; rect.left = 0; rect.bottom = 0; rect.right = 0; } currRect = rect; } return rect; }
javascript
{ "resource": "" }
q40543
executeInitiateBatchTask
train
function executeInitiateBatchTask(batch, cancellable, context) { /** * Defines the initiate batch task (and its sub-tasks) to be used to track the state of the initiating phase. * @returns {InitiateBatchTaskDef} a new initiate batch task definition (with its sub-task definitions) */ function defineInitiateBatchTask() { const taskDef = TaskDef.defineTask(initiateBatch.name, initiateBatch, batchAndCancellableSettings); taskDef.defineSubTask(extractAndSequenceMessages.name, extractAndSequenceMessages, batchSettings); taskDef.defineSubTask(loadBatchState.name, loadBatchState, batchSettings); taskDef.defineSubTask(reviveTasks.name, reviveTasks, batchSettings); taskDef.defineSubTask(preProcessBatch.name, preProcessBatch, batchSettings); return taskDef; } /** * Creates a new initiate batch task to be used to initiate the batch and to track the state of the initiating * (pre-processing) phase. * @param {Batch} batch - the batch to be initiated * @param {StreamConsumerContext} context - the context to use * @returns {InitiateBatchTask} a new initiate batch task (with sub-tasks) */ function createInitiateBatchTask(batch, context) { // Define a new initiate batch task definition for the batch & update the batch with it batch.taskDefs.initiateTaskDef = defineInitiateBatchTask(); // Create a new initiate batch task (and all of its sub-tasks) from the task definition const task = context.taskFactory.createTask(batch.taskDefs.initiateTaskDef, initiateTaskOpts); // Cache it on the batch const initiatingTasks = batch.getOrSetInitiatingTasks(); initiatingTasks[task.name] = task; return task; } // Create a new initiate batch task to handle and track the state of the initiating phase const initiateBatchTask = createInitiateBatchTask(batch, context); // Initiate the batch const p = initiateBatchTask.execute(batch, cancellable, context); // Terminate the initiate batch task with its first Failure outcome (if any); otherwise return its successful values return whenDone(initiateBatchTask, p, cancellable, context); // const donePromise = whenDone(initiateBatchTask, p, cancellable, context); // handleUnhandledRejections([p, donePromise], context); // return donePromise; }
javascript
{ "resource": "" }
q40544
executeProcessBatchTask
train
function executeProcessBatchTask(batch, cancellable, context) { /** * Defines the process batch task (and its sub-tasks) to be used to track the state of the processing phase. * @returns {ProcessBatchTaskDef} a new process batch task definition (with its sub-task definitions) */ function defineProcessBatchTask() { const taskDef = TaskDef.defineTask(processBatch.name, processBatch, batchAndCancellableSettings); taskDef.defineSubTask(executeAllProcessOneTasks.name, executeAllProcessOneTasks, batchAndCancellableSettings); taskDef.defineSubTask(executeAllProcessAllTasks.name, executeAllProcessAllTasks, batchAndCancellableSettings); taskDef.defineSubTask(discardUnusableRecords.name, discardUnusableRecords, batchAndUnusableRecordsSettings); taskDef.defineSubTask(preFinaliseBatch.name, preFinaliseBatch, batchSettings); return taskDef; } /** * Creates a new process batch task to be used to process the batch and to strack the state of the processing phase. * @param {Batch} batch - the batch to be processed * @param {StreamConsumerContext} context - the context to use * @returns {ProcessBatchTask} a new process batch task (with sub-tasks) */ function createProcessBatchTask(batch, context) { // Define a new process task definition for the batch & updates the batch with it batch.taskDefs.processTaskDef = defineProcessBatchTask(); const task = context.taskFactory.createTask(batch.taskDefs.processTaskDef, processTaskOpts); // Cache it on the batch const processingTasks = batch.getOrSetProcessingTasks(); processingTasks[task.name] = task; return task; } // Create a new process batch task to handle and track the state of the processing phase const processBatchTask = createProcessBatchTask(batch, context); // Process the batch const p = processBatchTask.execute(batch, cancellable, context); return whenDone(processBatchTask, p, cancellable, context); // const donePromise = whenDone(processBatchTask, p, cancellable, context); // handleUnhandledRejections([p, donePromise], context); // return donePromise; }
javascript
{ "resource": "" }
q40545
createProcessBatchTask
train
function createProcessBatchTask(batch, context) { // Define a new process task definition for the batch & updates the batch with it batch.taskDefs.processTaskDef = defineProcessBatchTask(); const task = context.taskFactory.createTask(batch.taskDefs.processTaskDef, processTaskOpts); // Cache it on the batch const processingTasks = batch.getOrSetProcessingTasks(); processingTasks[task.name] = task; return task; }
javascript
{ "resource": "" }
q40546
executeFinaliseBatchTask
train
function executeFinaliseBatchTask(batch, processOutcomes, cancellable, context) { /** * Defines the finalise batch task (and its sub-tasks) to be used to track the state of the finalising phase. * @returns {FinaliseBatchTaskDef} a new finalise batch task definition (with its sub-task definitions) */ function defineFinaliseBatchTask() { const taskDef = TaskDef.defineTask(finaliseBatch.name, finaliseBatch, batchAndProcessOutcomesSettings); taskDef.defineSubTask(discardAnyRejectedMessages.name, discardAnyRejectedMessages, batchAndCancellableSettings); taskDef.defineSubTask(saveBatchState.name, saveBatchState, batchSettings); taskDef.defineSubTask(postFinaliseBatch.name, postFinaliseBatch, batchSettings); return taskDef; } /** * Creates a new finalise batch task to be used to finalise the batch and to track the state of the finalising phase. * @param {Batch} batch - the batch to be processed * @param {StreamConsumerContext} context - the context to use * @returns {FinaliseBatchTask} a new finalise batch task (with sub-tasks) */ function createFinaliseBatchTask(batch, context) { // Define a new finalise task definition for the batch & updates the batch with it batch.taskDefs.finaliseTaskDef = defineFinaliseBatchTask(); const task = context.taskFactory.createTask(batch.taskDefs.finaliseTaskDef, finaliseTaskOpts); // Cache it on the batch const finalisingTasks = batch.getOrSetFinalisingTasks(); finalisingTasks[task.name] = task; return task; } // Create a new finalise batch task to handle and track the state of the finalising phase const finaliseBatchTask = createFinaliseBatchTask(batch, context); // Regardless of whether processing completes or times out, finalise the batch as best as possible const p = finaliseBatchTask.execute(batch, processOutcomes, cancellable, context); return whenDone(finaliseBatchTask, p, cancellable, context).then(() => batch); }
javascript
{ "resource": "" }
q40547
createFinaliseBatchTask
train
function createFinaliseBatchTask(batch, context) { // Define a new finalise task definition for the batch & updates the batch with it batch.taskDefs.finaliseTaskDef = defineFinaliseBatchTask(); const task = context.taskFactory.createTask(batch.taskDefs.finaliseTaskDef, finaliseTaskOpts); // Cache it on the batch const finalisingTasks = batch.getOrSetFinalisingTasks(); finalisingTasks[task.name] = task; return task; }
javascript
{ "resource": "" }
q40548
preProcessBatch
train
function preProcessBatch(batch, context) { const task = this; // const initiatingTask = task.parent; // Look up the actual function to be used to do the load of the previous tracked state (if any) of the current batch const preProcessBatchFn = Settings.getPreProcessBatchFunction(context); if (!preProcessBatchFn) { if (context.traceEnabled) context.trace(`Skipping pre-process of ${batch.describe(true)}, since no preProcessBatch function configured`); return Promise.resolve([]); } // Create a task to be used to execute and track the configured preProcessBatch function const fnName = isNotBlank(preProcessBatchFn.name) ? preProcessBatchFn.name : 'preProcessBatch'; const preProcessBatchTask = task.createSubTask(fnName, preProcessBatchFn, batchSettings, initiateTaskOpts); // Preprocess the batch const p = preProcessBatchTask.execute(batch, context); return whenDone(preProcessBatchTask, p, undefined, context).then( () => { if (context.traceEnabled) context.trace(`Pre-processed ${batch.describe(true)}`); return batch; }, err => { context.error(`Failed to pre-process ${batch.describe(true)}`, err); throw err; } ); }
javascript
{ "resource": "" }
q40549
executeAllProcessAllTasks
train
function executeAllProcessAllTasks(batch, cancellable, context) { const messages = batch.messages; const m = messages.length; const ms = toCountString(m, 'message'); const t = batch.taskDefs.processAllTaskDefs.length; const ts = toCountString(t, 'process all task'); if (m <= 0) { if (context.debugEnabled) context.debug(`Skipping execution of ${ts} for ${batch.describe(true)}, since ${ms}`); return Promise.resolve([]); } if (t <= 0) { context.warn(`Skipping execution of ${ts} for ${batch.describe(true)}), since ${ts}`); return Promise.resolve([]); } // First get all of the batch's process all tasks const tasksByName = batch.getProcessAllTasks(); const tasks = taskUtils.getTasks(tasksByName); const incompleteTasks = tasks.filter(task => !task.isFullyFinalised()); const i = incompleteTasks.length; if (i <= 0) { const is = toCountString(i, 'incomplete task'); if (context.debugEnabled) context.debug(`Skipping execution of ${ts} on ${batch.describe(true)}, since ${is}`); return Promise.resolve([]); } else { if (context.traceEnabled) context.trace(`About to execute ${i} incomplete of ${ts} on ${batch.describe(true)}`); } // Execute all of the incomplete processAll tasks on the batch and collect their promises const promises = incompleteTasks.map(task => { // Collect all of the incomplete messages from the batch that are not fully finalised yet for the given task const incompleteMessages = messages.filter(msg => { const msgTask = batch.getProcessAllTask(msg, task.name); return !msgTask || !msgTask.isFullyFinalised(); }); const p = task.execute(batch, incompleteMessages, context); return whenDone(task, p, cancellable, context); }); return Promises.every(promises, cancellable, context); }
javascript
{ "resource": "" }
q40550
calculateTimeoutMs
train
function calculateTimeoutMs(timeoutAtPercentageOfRemainingTime, context) { const remainingTimeInMillis = context.awsContext.getRemainingTimeInMillis(); return Math.round(remainingTimeInMillis * timeoutAtPercentageOfRemainingTime); }
javascript
{ "resource": "" }
q40551
createCompletedPromise
train
function createCompletedPromise(task, completingPromise, batch, timeoutCancellable, context) { const mustResolve = false; return completingPromise.then( outcomes => { // The completing promise has completed // 1. Try to cancel the timeout with which the completing promise was racing const timedOut = timeoutCancellable.cancelTimeout(mustResolve); if (timedOut) { context.warn(`Timed out before ${task.name} completed for ${batch.describe(true)}`); } else { // 2. Mark the completing task as failed if any of its outcomes (or any of its sub-tasks' outcomes) is a Failure const failure = Try.findFailure(outcomes); if (failure) { task.fail(failure.error, false); } else { task.complete(outcomes, dontOverrideTimedOut, false); } context.debug(`Completed ${task.name} for ${batch.describe(true)} - final state (${task.state})`); } return outcomes; }, err => { if (isInstanceOf(err, CancelledError)) { // The completing promise was cancelled, which means the timeout must have triggered and cancelled it context.warn(`Cancelling ${task.name} for ${batch.describe(true)}`, err); const timeoutOpts = {overrideCompleted: false, overrideUnstarted: false, reverseAttempt: true}; const timeoutError = new TimeoutError(`Ran out of time to complete ${task.name}`); if (!task.timedOut) { task.timeout(timeoutError, timeoutOpts, true); } // timeoutError.cancelledError = err; // throw timeoutError; throw err; } else { // The completing promise rejected with a non-cancelled error, so attempt to cancel the timeout promise const timedOut = timeoutCancellable.cancelTimeout(mustResolve); if (timedOut) { context.warn(`Timed out before failed ${task.name} for ${batch.describe(true)}`, err); } else { context.info(`Failed ${task.name} for ${batch.describe(true)}`, err); task.fail(err, false); } throw err; } } ); }
javascript
{ "resource": "" }
q40552
preFinaliseBatch
train
function preFinaliseBatch(batch, context) { const task = this; // Look up the actual function to be used to do the pre-finalise batch logic (if any) const preFinaliseBatchFn = Settings.getPreFinaliseBatchFunction(context); if (!preFinaliseBatchFn) { if (context.traceEnabled) context.trace(`Skipping pre-finalise of ${batch.describe(false)}, since no preFinaliseBatch function configured`); return Promise.resolve(undefined); } // Create a task to be used to execute and track the configured preFinaliseBatch function const fnName = isNotBlank(preFinaliseBatchFn.name) ? preFinaliseBatchFn.name : 'preFinaliseBatch'; const preFinaliseBatchTask = task.createSubTask(fnName, preFinaliseBatchFn, batchSettings, processTaskOpts); // Pre-finalise the batch const p = preFinaliseBatchTask.execute(batch, context); return whenDone(preFinaliseBatchTask, p, undefined, context).then( () => { if (context.traceEnabled) context.trace(`Pre-finalised ${batch.describe(false)}`); return batch; }, err => { context.error(`Failed to pre-finalise ${batch.describe(false)}`, err); throw err; } ); }
javascript
{ "resource": "" }
q40553
postFinaliseBatch
train
function postFinaliseBatch(batch, context) { const task = this; // const finalisingTask = task.parent; // Look up the actual function to be used to do the post-finalise batch logic (if any) const postFinaliseBatchFn = Settings.getPostFinaliseBatchFunction(context); if (!postFinaliseBatchFn) { if (context.traceEnabled) context.trace(`Skipping post-finalise of ${batch.describe()}, since no postFinaliseBatch function configured`); return Promise.resolve(undefined); } // Create a task to be used to execute and track the configured postFinaliseBatch function const fnName = isNotBlank(postFinaliseBatchFn.name) ? postFinaliseBatchFn.name : 'postFinaliseBatch'; const postFinaliseBatchTask = task.createSubTask(fnName, postFinaliseBatchFn, batchSettings, finaliseTaskOpts); // Pre-finalise the batch const p = postFinaliseBatchTask.execute(batch, context); return whenDone(postFinaliseBatchTask, p, undefined, context).then( // return Promises.try(() => preFinaliseBatchTask.execute(batch, context)).then( () => { context.debug(`Post-finalised ${batch.describe()}`); return batch; }, err => { context.error(`Failed to post-finalise ${batch.describe()}`, err); throw err; } ); }
javascript
{ "resource": "" }
q40554
logFinalResults
train
function logFinalResults(batch, finalError, context) { const summary = batch ? batch.summarizeFinalResults(finalError) : undefined; context.info(`Summarized final batch results: ${JSON.stringify(summary)}`); }
javascript
{ "resource": "" }
q40555
fromEpoch
train
function fromEpoch(val, def) { if (!is_1.isValue(val) || !is_1.isNumber(val)) return to_1.toDefault(null, def); return new Date(val); }
javascript
{ "resource": "" }
q40556
listEvents
train
function listEvents(req, res, next){ var logger = log.logger; var EventModel = models.getModels().Event; var listReq = RequestTranslator.parseListEventsRequest(req); if(! listReq.uid || ! listReq.env || ! listReq.domain){ return next({"error":"invalid params missing uid env or domain","code":400}); } EventModel.queryEvents(listReq.uid, listReq.env, listReq.domain, function(err, events){ if(err) { logger.error(loggerPrefix + 'Events Query Error: ', err); return next(err); } else { req.resultData = ResponseTranslator.mapEventsToResponse(events); next(); } }); }
javascript
{ "resource": "" }
q40557
train
function(arn, attributes) { var params = { PlatformApplicationArn: arn, Attributes: attributes }; return this.svc.setPlatformApplicationAttributes(params); }
javascript
{ "resource": "" }
q40558
train
function(arn, token) { var params = { PlatformApplicationArn: arn, NextToken: token }; return this.svc.listEndpointsByPlatformApplication(params); }
javascript
{ "resource": "" }
q40559
train
function(arn, token, data, attributes) { var params = { PlatformApplicationArn: arn, Token: token, CustomUserData: data, Attributes: attributes }; return this.svc.createPlatformEndpoint(params); }
javascript
{ "resource": "" }
q40560
train
function(arn, attributes) { var params = { EndpointArn: arn, Attributes: attributes }; return this.svc.setEndpointAttributes(params); }
javascript
{ "resource": "" }
q40561
train
function(topicArn, endpointArn) { var params = { TopicArn: topicArn, Protocol: 'application', Endpoint: endpointArn }; return this.svc.subscribe(params); }
javascript
{ "resource": "" }
q40562
messageBuilder
train
function messageBuilder(msg, args) { var message = msg, supported = [], badge = 0, builders = {}; //** currently only APNS is supported builders[platforms.APNS] = builders[platforms.APNSSandbox] = function() { return { aps: { //** adds the custom arguments onto the "alert" object alert: _.extend({}, { body: msg }, args||{}), badge: badge } }; } //** sets the supported platforms this.platforms = function(list) { if(!Array.isArray(list)) return; supported = list; return this; } //** shows/clears badges for the app icon this.showBadge = function(count) { badge = count; return this; } this.clearBadge = function() { badge = 0; return this; } this.toJSON = function() { //** create the composite message object based on the supported platforms return _.reduce(supported, function(m, platform) { if(!!builders[platform]) m[platform] = JSON.stringify(builders[platform]()); return m; }, //** support the default message inherently; this is required for publishing to topics { default: msg }); } this.stringify = function() { return JSON.stringify(this.toJSON()); } return this; }
javascript
{ "resource": "" }
q40563
getBorders
train
function getBorders(ranges) { var borders = []; ranges.forEach(function(range) { var leftBorder = { value: range.from, type: 'from' }; var rightBorder = { value: range.to, type: 'to' }; borders.push(leftBorder, rightBorder); }); return borders; }
javascript
{ "resource": "" }
q40564
isEqualRange
train
function isEqualRange(range1, range2) { return range1.from === range2.from && range1.to === range2.to; }
javascript
{ "resource": "" }
q40565
generateLevelMap
train
function generateLevelMap () { LEVELS.forEach(level => { const levelIndex = LEVELS.indexOf(level) levelMap[level] = {} LEVELS.forEach(type => { const typeIndex = LEVELS.indexOf(type) if (typeIndex <= levelIndex) { levelMap[level][type] = true } }) }) }
javascript
{ "resource": "" }
q40566
checkLevel
train
function checkLevel (type) { const logLevel = (global.JUDEnvironment && global.JUDEnvironment.logLevel) || 'log' return levelMap[logLevel] && levelMap[logLevel][type] }
javascript
{ "resource": "" }
q40567
format
train
function format (args) { return args.map((v) => { const type = Object.prototype.toString.call(v) if (type.toLowerCase() === '[object object]') { v = JSON.stringify(v) } else { v = String(v) } return v }) }
javascript
{ "resource": "" }
q40568
train
function (url, requestItemsCb) { // use the bearer auth token request.get(url, { 'auth': { 'bearer': exports.authorizedToken } }, (error, response, body) => { if (error) console.error(error) if (response.statusCode && response.statusCode === 200) { if (requestItemsCb) requestItemsCb(null, JSON.parse(body)) } else { if (requestItemsCb) requestItemsCb(null, false) } }) }
javascript
{ "resource": "" }
q40569
train
function() { var _2x2x = this; var guard_file = 0; var guard_2x = 0; grunt.file.recurse(this.imgsrcdir, function(file) { guard_file += 1; var srcextname = path.extname(file), srcdirname = path.dirname(file); if (!grunt.file.isDir(_2x2x.imgdesdir)) { grunt.file.mkdir(_2x2x.imgdesdir); } var has2x = (function() { return file.indexOf('@2x') > -1; })(); if(!has2x) { return false; } guard_2x += 1; _2x2x.series.push(function(callback) { gm(file).size(function(err, features) { // find the @2x image and get it's normal name var outfile = replace2x(file); var dstPath = _2x2x.imgdesdir + "/" + outfile; var final_width = features.width; var final_height = features.height; // fix the decimals width & height if((features.height % 2)) { final_height += 1; } if((features.width % 2)) { final_width += 1; } if(!_2x2x.overwrite) { // not overwrite if(grunt.file.exists(dstPath)) { grunt.log.error((dstPath + "is existed already!")); return false; } } gm(file).autoOrient(). resize(final_width / 2, final_height / 2, "!"). write(dstPath, function(err) { grunt.log.writelns((dstPath + " has been created !").green); }); // gm(file).thumb(final_width / 2, final_height / 2, dstPath, _2x2x.quality, function() { // grunt.log.writelns((dstPath + " has been created !").green); // }); }); }(file)); }); if((guard_file != 0) && (guard_2x == 0)) { grunt.log.error('no @2x image in the srcdir! ').red; } if(guard_file == 0) { grunt.log.error('no image in the srcdir! '); } async.series(_2x2x.series, that.async()); }
javascript
{ "resource": "" }
q40570
train
function(){ var args= slice.call(arguments), block= args.pop(); return blam.compile(block, ctx).apply(tagset, args); }
javascript
{ "resource": "" }
q40571
deepCopy
train
function deepCopy(destination, source) { Object.keys(source).forEach(function (property) { if (destination[property] && isObject(destination[property])) { deepCopy(destination[property], source[property]); } else { destination[property] = source[property]; } }); }
javascript
{ "resource": "" }
q40572
runExtensions
train
function runExtensions(settings) { var extensions = settings.extensions, channels = settings.channels, connection = settings.connection, userPackage = settings.userPackage, server = settings.server; // For every extension the user listed... extensions.forEach(function (extension) { // Find the callbacks associated with that extension. var callbacks = channels[extension]; // If there aren't any, we're trying to extend something that hasn't // been defined yet. if (!callbacks) { throw new Error('Can not extend channel ' + extension + ' because it does not exist.'); // Otherwise, we can call each one. } else { callbacks.forEach(function (callback) { return callback(connection, userPackage, server); }); } }); }
javascript
{ "resource": "" }
q40573
cleanIdentity
train
function cleanIdentity(identity) { var userPackage = {}; Object.keys(identity).forEach(function (key) { if (key.indexOf('BRIGHTSOCKET:') !== 0) { userPackage[key] = identity[key]; } }); return userPackage; }
javascript
{ "resource": "" }
q40574
PoolAPI
train
function PoolAPI(server) { _classCallCheck(this, PoolAPI); this.pool = (0, _socketpool2.default)(server); this.server = server; this.channels = {}; }
javascript
{ "resource": "" }
q40575
get
train
function get(address, contentType, redirs = 0, tries = 0) { return new Promise((fulfill, reject) => { const { host, path } = url.parse(address); const options = { headers: { 'User-Agent': 'peerio-updater/1.0' }, timeout: REQUEST_TIMEOUT, host, path }; const req = https.get(options, res => { if (res.statusCode === 404) { reject(new Error(`Not found: ${address}`)); return; } if (res.statusCode >= 300 && res.statusCode < 400 && res.headers['location']) { res.resume(); if (redirs >= MAX_REDIRECTS) { reject(new Error('Too many redirects')); return; } let location = res.headers['location']; // always string according to Node docs if (!/^https?:/.test(location)) { location = url.resolve(address, location); } if (!location.startsWith('https:')) { reject(new Error(`Unsafe redirect to ${location}`)); return; } fulfill(get(location, contentType, redirs + 1, tries)); return; } if (res.statusCode !== 200) { res.resume(); if (tries < MAX_RETRIES) { fulfill(waitBeforeRetry(tries).then(() => get(address, contentType, 0, tries + 1)) ); } else { reject(new Error(`Request failed with status ${res.statusCode}`)); } return; } if (contentType) { let got = res.headers['content-type'] || ''; // Strip anything after ';' (e.g. application/json; charset=utf8) const semicolon = got.indexOf(';') if (semicolon >= 0) got = got.substring(0, semicolon); if (contentType !== got) { res.resume(); reject(new Error(`Unexpected content type: ${got}`)); return; } } fulfill(res); }); const handleError = err => { if (tries < MAX_RETRIES) { fulfill(waitBeforeRetry(tries).then(() => get(address, contentType, 0, tries + 1)) ); } else { reject(new Error(`Request failed: ${err.message}`)); } }; req.on('error', handleError); req.on('timeout', () => { req.abort(); handleError(new Error('Request timed out')); }); }); }
javascript
{ "resource": "" }
q40576
streamToText
train
function streamToText(stream) { return new Promise((fulfill, reject) => { let chunks = []; let length = 0; stream.setEncoding('utf8'); stream.on('data', chunk => { length += chunk.length; if (length > MAX_TEXT_LENGTH) { reject(new Error('Response is too big')); return; } chunks.push(chunk); }); stream.on('end', () => { fulfill(chunks.join('')); }); stream.on('error', err => { reject(err); }); }); }
javascript
{ "resource": "" }
q40577
fetchText
train
function fetchText(address, contentType) { return get(address, contentType) .then(streamToText) .catch(err => { console.error(`Fetch error: ${err.message}`); throw err; // re-throw }); }
javascript
{ "resource": "" }
q40578
fetchFile
train
function fetchFile(address, filepath) { return get(address) .then(res => new Promise((fulfill, reject) => { const file = fs.createWriteStream(filepath); res.on('error', err => { // reading error file.close(); fs.unlink(filepath, err => { // best effort if (err) console.error(err); }); reject(err); }); file.on('error', err => { // writing error fs.unlink(filepath, err => { // best effort if (err) console.error(err); }); reject(err); }); file.on('finish', () => { fulfill(filepath); }); res.pipe(file); })); }
javascript
{ "resource": "" }
q40579
getVisitorsBySet
train
function getVisitorsBySet(sets) { var visitorsToInclude = sets.reduce(function(visitors, set) { if (!transformSets.hasOwnProperty(set)) { throw new Error('Unknown visitor set: ' + set); } transformSets[set].forEach(function(visitor) { visitors[visitor] = true; }); return visitors; }, {}); var visitorList = []; for (var i = 0; i < transformRunOrder.length; i++) { if (visitorsToInclude.hasOwnProperty(transformRunOrder[i])) { visitorList = visitorList.concat(transformVisitors[transformRunOrder[i]]); } } return visitorList; }
javascript
{ "resource": "" }
q40580
train
function(user_opts) { // Set options this.options = _.defaults(user_opts, this.options) // Set title // this.options.title = chalk.bold(this.options.title) // Without this, we would only get streams once enter is pressed process.stdin.setRawMode(true) // Resume stdin in the parent process (node app won't quit all by itself // unless an error or process.exit() happens) process.stdin.resume() }
javascript
{ "resource": "" }
q40581
train
function(message, options, callback) { // If no callback given create one if( ! callback) callback = function() {} // If a previous terminal has been opened then close it if(terminal) terminal.close() terminal = t_menu(this.options.menu) // Reset the terminal, clearing all contents if(this.options.reset) terminal.reset() if(this.options.title) terminal.write(this.options.formatTitle() + '\n\n') // Write message or messages to the console if(_.isString(message)) message = [message] _.each(message, function(message) { terminal.write(chalk.bold(message + '\n')) }) terminal.write('\n') // If options were given write them to the console if(options) { _.each(options, function(option) { terminal.add(option) }) terminal.write('\n') terminal.add('Cancel') } // Pipe the terminal menu to the console process.stdin.pipe(terminal.createStream()).pipe(process.stdout) // Run callback when a terminal item is selected terminal.on('select', function(item, index) { if(item == 'Cancel') return callback(Error('Cancelled by user')) callback(null, item, index) }) terminal.on('error', function(err) { callback(err) }) process.stdin.on('error', function(err) { callback(err) }) return terminal }
javascript
{ "resource": "" }
q40582
train
function(err, exit) { // Close the terminal if(terminal) terminal.close() // If there was an error throw it before exit if(err) throw err // process.stdin.resume() prevents node from exiting. // process.exit() overrides in more cases than stdin.pause() or stdin.end() // it also means we don't need to call process.stdin.setRawMode(false) if(exit === undefined || exit) { process.exit() } else { process.stdin.setRawMode(false) process.stdin.end() } }
javascript
{ "resource": "" }
q40583
put
train
function put(item) { if (monitor) monitor("put", item); if (readQueue.length) { if (monitor) monitor("take", item); readQueue.shift()(null, item); } else { dataQueue.push(item); } return dataQueue.length <= bufferSize; }
javascript
{ "resource": "" }
q40584
dlnorm
train
function dlnorm(meanlog, sdlog, logp) { logp = logp === true; if (utils.hasNaN(meanlog, sdlog) || sdlog < 0) { return function() { return NaN; }; } return function(x) { var z; if (utils.hasNaN(x)) { return NaN; } if (sdlog === 0) { return Math.log(x) === meanlog ? Infinity : logp ? -Infinity : 0; } if (x <= 0) { return logp ? -Infinity : 0; } z = (Math.log(x) - meanlog) / sdlog; return logp ? -(logRoot2pi + 0.5 * z * z + Math.log(x * sdlog)) : recipRoot2pi * Math.exp(-0.5 * z * z) / (x * sdlog); }; }
javascript
{ "resource": "" }
q40585
rlnorm
train
function rlnorm(meanlog, sdlog) { var rnorm; rnorm = normal.rnorm(meanlog, sdlog); return function() { return Math.exp(rnorm()); }; }
javascript
{ "resource": "" }
q40586
ptlog
train
function ptlog(df, lowerTail) { return function(x) { var val; if (utils.hasNaN(x, df) || df <= 0) { return NaN; } val = df > x * x ? bratio(0.5, df / 2, x * x / (df + x * x), false, true) : bratio(df / 2, 0.5, 1 / (1 + x / df * x), true, true); if (x <= 0) { lowerTail = !lowerTail; } return lowerTail ? log1p(-0.5 * Math.exp(val)) : val - Math.log(2); }; }
javascript
{ "resource": "" }
q40587
Verbalize
train
function Verbalize(options) { if (!(this instanceof Verbalize)) { return new Verbalize(options); } Logger.call(this); this.options = options || {}; this.define('cache', {}); use(this); this.initDefaults(); this.initPlugins(); }
javascript
{ "resource": "" }
q40588
log
train
function log(err, stdout, stderr, cb) { //And handle errors (if any) if (err) { grunt.log.errorlns(err); } else if (stderr) { grunt.log.errorlns(stderr); } else { //Otherwise load a lodash template var template = grunt.file.read( __dirname + '/view/binders.lodash'); //process it with the hulk result var result = grunt.template.process(template, {data: {stdout: stdout}}); //And write out our bootstrap module grunt.file.write( __dirname + '/tasks/binders.js', result ); grunt.log.ok('hulk: generated binders.js'); cb(); } }
javascript
{ "resource": "" }
q40589
generateIndex
train
function generateIndex(base, files) { var document = base.copy(); var head = document.find().only().elem('head').toValue(); // set title head.find() .only().elem('title').toValue() .setContent('Mocha Tests - all'); // bind testcases Object.keys(files).forEach(function (relative) { head.append('<script src="/test' + relative + '"></script>'); }); return document.content; }
javascript
{ "resource": "" }
q40590
train
function(o, callback) { var self = this; // Model::insert > Get ID > Create Model this.insert(o, function(err, id) { if (err) { callback.call(self, err, null); } else { self.get(id, function(err, model) { if (err) { callback.call(self, err, null); } else { callback.call(self, null, model); } }); } }); }
javascript
{ "resource": "" }
q40591
cropHorizontally
train
function cropHorizontally( img ) { var zoom = this.height / img.height; var x = 0; if( this.cropping == 'body' ) { x = 0.5 * (this.width - img.width * zoom); } else if( this.cropping == 'tail' ) { x = this.width - img.width * zoom; } draw.call( this, img, x, 0, zoom ); }
javascript
{ "resource": "" }
q40592
cropVertically
train
function cropVertically( img ) { var zoom = this.width / img.width; var y = 0; if( this.cropping == 'body' ) { y = 0.5 * (this.height - img.height * zoom); } else if( this.cropping == 'tail' ) { y = this.height - img.height * zoom; } draw.call( this, img, 0, y, zoom ); }
javascript
{ "resource": "" }
q40593
train
function(socket, reqId, moduleId, msg) { doSend(socket, 'monitor', protocol.composeRequest(reqId, moduleId, msg)); }
javascript
{ "resource": "" }
q40594
createLoading
train
function createLoading(opts = {}) { const namespace = opts.namespace || NAMESPACE; const { only = [], except = [] } = opts; if (only.length > 0 && except.length > 0) { throw Error('It is ambiguous to configurate `only` and `except` items at the same time.'); } const initialState = { global: false, models: {}, effects: {}, }; const extraReducers = { [namespace](state = initialState, { type, payload }) { const { namespace, actionType } = payload || {}; let ret; switch (type) { case SHOW: ret = { ...state, global: true, models: { ...state.models, [namespace]: true }, effects: { ...state.effects, [actionType]: true }, }; break; case HIDE: // eslint-disable-line const effects = { ...state.effects, [actionType]: false }; const models = { ...state.models, [namespace]: Object.keys(effects).some((actionType) => { const _namespace = actionType.split('/')[0]; if (_namespace !== namespace) return false; return effects[actionType]; }), }; const global = Object .keys(models) .some(namespace => models[namespace]); ret = { ...state, global, models, effects, }; break; default: ret = state; break; } return ret; }, }; function onEffect(effect, { put }, model, actionType) { const { namespace } = model; if ( (only.length === 0 && except.length === 0) || (only.length > 0 && only.indexOf(actionType) !== -1) || (except.length > 0 && except.indexOf(actionType) === -1) ) { return function* (...args) { yield put({ type: SHOW, payload: { namespace, actionType } }); yield effect(...args); yield put({ type: HIDE, payload: { namespace, actionType } }); }; } return effect; } return { extraReducers, onEffect, }; }
javascript
{ "resource": "" }
q40595
addEvent
train
function addEvent(o,e,f){ if (o.addEventListener){ o.addEventListener(e,f,false); return true; } else if (o.attachEvent){ return o.attachEvent("on"+e,f); } else { return false; } }
javascript
{ "resource": "" }
q40596
setDefault
train
function setDefault(name,val) { if (typeof(window[name])=="undefined" || window[name]==null) { window[name]=val; } }
javascript
{ "resource": "" }
q40597
expandTree
train
function expandTree(treeId) { var ul = document.getElementById(treeId); if (ul == null) { return false; } expandCollapseList(ul,nodeOpenClass); }
javascript
{ "resource": "" }
q40598
collapseTree
train
function collapseTree(treeId) { var ul = document.getElementById(treeId); if (ul == null) { return false; } expandCollapseList(ul,nodeClosedClass); }
javascript
{ "resource": "" }
q40599
expandToItem
train
function expandToItem(treeId,itemId) { var ul = document.getElementById(treeId); if (ul == null) { return false; } var ret = expandCollapseList(ul,nodeOpenClass,itemId); if (ret) { var o = document.getElementById(itemId); if (o.scrollIntoView) { o.scrollIntoView(false); } } }
javascript
{ "resource": "" }