_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q56400
promisifyWithTimeout
train
function promisifyWithTimeout(yieldable, name, timeout) { return new Promise((resolve, reject) => { const timeoutId = setTimeout(() => reject(new Error(`Yieldable timeout in ${name}`)), timeout); co(yieldable) .then((...args) => { clearTimeout(timeoutId); resolve(...args); }) .catch((...args) => { clearTimeout(timeoutId); reject(...args); }); }); }
javascript
{ "resource": "" }
q56401
_wait
train
function _wait(eventName, timeout = 1000) { return new Promise((resolve, reject) => { let timeoutId = null; timeoutId = setTimeout(() => { timeoutId = null; reject(new Error(`event ${eventName} didn't occur after ${timeout}ms`)); }, timeout); emitter.once(eventName, () => { if (timeoutId !== null) { clearTimeout(timeoutId); resolve(); } }); }); }
javascript
{ "resource": "" }
q56402
_closeOnSignal
train
function _closeOnSignal(signal) { process.on(signal, onSignal); /** * @returns {void} */ function onSignal() { logger.info({ workerName: configuration.workerName, signal }, '[worker#listen] Received exit signal, stopping workers...'); workers.close(true); } }
javascript
{ "resource": "" }
q56403
_getMessageConsumer
train
function _getMessageConsumer(channel, handle, validate, routingKey) { return function* _consumeMessage(message) { try { logger.debug({ message, routingKey }, '[worker#listen] received message'); const content = _parseMessage(message); if (!content) return channel.ack(message); const validatedContent = _validateMessage(validate, content); if (_.isError(validatedContent)) return channel.ack(message); const handleSuccess = yield _handleMessage( handle, validatedContent || content, message.fields ); if (!handleSuccess) return channel.nack(message); return channel.ack(message); } catch (err) { logger.error({ err, routingKey }, '[worker#listen] failed to ack/nack'); return null; } }; }
javascript
{ "resource": "" }
q56404
_parseMessage
train
function _parseMessage(message) { try { const contentString = message && message.content && message.content.toString(); return JSON.parse(contentString); } catch (err) { _emit(TASK_FAILED); logger.warn( { err, message, options: configWithoutFuncs }, '[worker#listen] Content is not a valid JSON' ); return null; } }
javascript
{ "resource": "" }
q56405
_validateMessage
train
function _validateMessage(validate, message) { const { workerName } = configuration; try { return validate(message); } catch (err) { _emit(TASK_FAILED); logger.warn( { err, message, options: configWithoutFuncs, workerName }, '[worker#listen] Message validation failed' ); return err; } }
javascript
{ "resource": "" }
q56406
_subscribeToConnectionEvents
train
function _subscribeToConnectionEvents(connection, workerName) { connection.on('close', errCode => { logger.info({ workerName, errCode }, '[AMQP] Connection closing, exiting'); // The workerConnection isn't working anymore... workerConnection = null; workers.close(); }); connection.on('error', err => { logger.error({ err, workerName }, '[AMQP] Connection closing because of an error'); }); connection.on('blocked', reason => { logger.warn({ reason, workerName }, '[AMQP] Connection blocked'); }); }
javascript
{ "resource": "" }
q56407
_subscribeToChannelEvents
train
function _subscribeToChannelEvents(channel, { exchangeName, queueName, channelPrefetch, workerName }) { channel.on('error', err => { logger.error( { err, exchangeName, queueName, channelPrefetch, workerName }, '[AMQP] channel error' ); }); channel.on('close', () => { logger.info( { exchangeName, queueName, channelPrefetch, workerName }, '[AMQP] channel closed' ); // Remove this channel because is closed workerChannels.delete(channel); workers.close(); }); }
javascript
{ "resource": "" }
q56408
train
function (callback) { var self = this; async.parallel([ function (callback) { async.each(self.dispatcher.tree.getCollections(), function (col, callback) { if (col.noReplay) { return callback(null); } col.repository.clear(callback); }, callback); }, function (callback) { self.store.clear(callback); } ], callback); }
javascript
{ "resource": "" }
q56409
train
function (revisionMap, callback) { var self = this; var ids = _.keys(revisionMap); async.each(ids, function (id, callback) { self.store.get(id, function (err, rev) { if (err) { return callback(err); } self.store.set(id, revisionMap[id] + 1, rev, callback); }); }, callback); }
javascript
{ "resource": "" }
q56410
train
function (evts, callback) { this.replayStreamed(function (replay, done) { evts.forEach(function (evt) { replay(evt); }); done(callback); }); }
javascript
{ "resource": "" }
q56411
train
function() { if (!this._startupSchedule || !this._shutdownSchedule) { return true; } var lastStartup = later.schedule(this._startupSchedule).prev().getTime(); var lastShutdown = later.schedule(this._shutdownSchedule).prev().getTime(); return lastStartup > lastShutdown; }
javascript
{ "resource": "" }
q56412
train
function(message) { this._resetRestartTimeout(this.get('heartbeatTimeout')); if (!this._lastHeart) { this._isStartingUp = false; this._firstHeart = Date.now(); logger.info('App started.'); if (this.get('postLaunchCommand')) { spawn(this.get('postLaunchCommand'), null, null, function(err, output) { console.log(err, output); }); } if (this._startupCallback) { this._startupCallback(); this._startupCallback = null; } } this._lastHeart = Date.now(); this.trigger('heart'); }
javascript
{ "resource": "" }
q56413
train
function(time) { clearTimeout(this._restartTimeout); if (!time) { return; } if (!this._isShuttingDown) { this._restartTimeout = setTimeout(_.bind(this._onRestartTimeout, this), time * 1000); } }
javascript
{ "resource": "" }
q56414
train
function() { var that = this; // Save a screenshot. if ($$logging.get('screenshots').enabled) { var filename = $$logging.get('screenshots').filename.replace('{date}', moment().format('YYYYMMDDhhmmss')); logger.info('Saving screenshot to ' + filename); var winCmd = path.join(__dirname, '../tools', 'nircmd.exe'); var winArgs = ['savescreenshotfull', filename]; var macCmd = '/usr/sbin/screencapture'; var macArgs = ['-x', '-t', 'jpg', '-C', filename]; var cmd = process.platform === 'win32' ? winCmd : macCmd; var args = process.platform === 'win32' ? winArgs : macArgs; var screenshot = child_process.spawn(cmd, args); screenshot.on('close', function(code, signal) { logger.info('Screenshot saved, restarting.'); restart(); }); } else { restart(); } function restart() { var restartCount = that.get('restartCount'); restartCount++; var logList = 'App went away: ' + restartCount + ' times\n\n'; _.each($$logging.get('logCache'), function(log) { logList += log.time + ' ' + log.level + ': ' + log.msg + '\n'; }); logger.error(logList); that.trigger('crash'); if (restartCount >= that.get('restartMachineAfter')) { logger.info('Already restarted app ' + that.get('restartMachineAfter') + ' times, rebooting machine.'); that.restartMachine(); return; } that.set('restartCount', restartCount); that._isStartingUp = false; that._isShuttingDown = false; that.restartApp(); } }
javascript
{ "resource": "" }
q56415
train
function(callback) { if (this._isShuttingDown || this._isStartingUp) { return; } this._isShuttingDown = true; // See if the app is running. if (!this.processId() && !this.sideProcessId()) { this._isShuttingDown = false; // Nope, not running. if (callback) { callback(); } return; } // Kill the app. clearTimeout(this._restartTimeout); this._appProcess.kill(); if (this._sideProcess) { this._sideProcess.kill(); } // Check on an interval to see if it's dead. var check = setInterval(_.bind(function() { if (this.processId() || this.sideProcessId()) { return; } clearInterval(check); logger.info('App shut down by force.'); this._isShuttingDown = false; if (callback) { callback(); } }, this), 250); }
javascript
{ "resource": "" }
q56416
train
function(force, callback) { // Don't start if we're waiting for it to finish starting already. var should = !this._isStartingUp; // Don't start if we're outside the schedule, unless requested by the console. should = should && (this._shouldBeRunning() || force === true); // Don't start if it's already running. should = should && !this.processId(); // Don't start if there's no start command. should = should && this.get('launchCommand'); if (!should) { return; } if (this.get('startupTimeout')) { this._isStartingUp = true; } if (this.processId()) { // It's already running. this._isStartingUp = false; if (callback) { callback(true); } return; } this._lastHeart = null; this._firstHeart = null; this._startupCallback = callback; var parts = this._parseCommand(this.get('launchCommand')); // Start the app. logger.info('App starting up.'); this._appProcess = child_process.spawn(parts[0], parts.slice(1), { cwd: path.dirname(parts[0]) }) .on('exit', _.bind(function() { this._appProcess = null; }, this)) .on('error', _.bind(function(err) { logger.error('Application could not be started. Is the launchCommand path correct?'); this._appProcess = null; }, this)); this._resetRestartTimeout(this.get('startupTimeout')); if (!this.get('sideCommand')) { return; } // Start the side process. parts = this._parseCommand(this.get('sideCommand')); this._sideProcess = child_process.spawn(parts[0], parts.slice(1), { cwd: path.dirname(parts[0]) }).on('exit', _.bind(function() { this._sideProcess = null; }, this)); }
javascript
{ "resource": "" }
q56417
train
function() { if (this._isShuttingDown) { return; } this._isShuttingDown = true; // Restart but wait a bit to log things. // -R - restart // -C - shutdown message // -T 0 - shutdown now // -F - don't wait for anything to shut down gracefully var winCmd = 'shutdown -R -T 0 -F -C "ampm restart"'; var macCmd = 'shutdown -r now'; var cmd = process.platform === 'win32' ? winCmd : macCmd; setTimeout(child_process.exec(cmd), 3000); }
javascript
{ "resource": "" }
q56418
train
function (collection) { if (!collection || !_.isObject(collection)) { var err = new Error('Please pass a valid collection!'); debug(err); throw err; } this.collection = collection; }
javascript
{ "resource": "" }
q56419
train
function (evt, callback) { if (this.id && dotty.exists(evt, this.id)) { debug('found viewmodel id in event'); return callback(null, dotty.get(evt, this.id)); } if (this.getNewIdForThisEventExtender) { debug('[' + this.name + '] found eventextender id getter in event'); return this.getNewIdForThisEventExtender(evt, callback); } debug('not found viewmodel id in event, generate new id'); this.collection.getNewId(callback); }
javascript
{ "resource": "" }
q56420
train
function (fn) { if (!fn || !_.isFunction(fn)) { var err = new Error('Please pass a valid function!'); debug(err); throw err; } if (fn.length === 2) { this.getNewIdForThisEventExtender = fn; return this; } this.getNewIdForThisEventExtender = function (evt, callback) { callback(null, fn(evt)); }; return this; }
javascript
{ "resource": "" }
q56421
train
function(compiler){ bindCallbackMethod(compiler, "compilation", this, this.addDependencyFactories); bindCallbackMethod(compiler.parser, "expression window.angular", this, this.addAngularVariable); bindCallbackMethod(compiler.parser, "expression angular", this, this.addAngularVariable); bindCallbackMethod(compiler.parser, "call angular.module", this, this.parseModuleCall); bindCallbackMethod(compiler.resolvers.normal, "module-module", this, this.resolveModule); }
javascript
{ "resource": "" }
q56422
train
function (repository) { if (!repository || !_.isObject(repository)) { var err = new Error('Please pass a valid repository!'); debug(err); throw err; } var extendObject = { collectionName: this.name, indexes: this.indexes, }; if (repository.repositoryType && this.repositorySettings[repository.repositoryType]) { extendObject.repositorySettings = {}; extendObject.repositorySettings[repository.repositoryType] = this.repositorySettings[repository.repositoryType]; } this.repository = repository.extend(extendObject); }
javascript
{ "resource": "" }
q56423
train
function (viewBuilder) { if (!viewBuilder || !_.isObject(viewBuilder)) { var err = new Error('Please inject a valid view builder object!'); debug(err); throw err; } if (viewBuilder.payload === null || viewBuilder.payload === undefined) { viewBuilder.payload = this.defaultPayload; } if (this.viewBuilders.indexOf(viewBuilder) < 0) { viewBuilder.useCollection(this); this.viewBuilders.push(viewBuilder); } }
javascript
{ "resource": "" }
q56424
train
function (eventExtender) { if (!eventExtender || !_.isObject(eventExtender)) { var err = new Error('Please inject a valid event extender object!'); debug(err); throw err; } if (this.eventExtenders.indexOf(eventExtender) < 0) { eventExtender.useCollection(this); this.eventExtenders.push(eventExtender); } }
javascript
{ "resource": "" }
q56425
train
function (preEventExtender) { if (!preEventExtender || !_.isObject(preEventExtender)) { var err = new Error('Please inject a valid event extender object!'); debug(err); throw err; } if (this.preEventExtenders.indexOf(preEventExtender) < 0) { preEventExtender.useCollection(this); this.preEventExtenders.push(preEventExtender); } }
javascript
{ "resource": "" }
q56426
train
function (query) { if (!query || !_.isObject(query)) { return this.viewBuilders; } query.name = query.name || ''; query.version = query.version || 0; query.aggregate = query.aggregate || null; query.context = query.context || null; var found = _.filter(this.viewBuilders, function (vB) { return vB.name === query.name && (vB.version === query.version || vB.version === -1) && (vB.aggregate === query.aggregate) && (vB.context === query.context); }); if (found.length !== 0) { return found; } found = _.filter(this.viewBuilders, function (vB) { return vB.name === query.name && (vB.version === query.version || vB.version === -1) && (vB.aggregate === query.aggregate) && (vB.context === query.context || !query.context); }); if (found.length !== 0) { return found; } found = _.filter(this.viewBuilders, function (vB) { return vB.name === query.name && (vB.version === query.version || vB.version === -1) && (vB.aggregate === query.aggregate || !query.aggregate) && (vB.context === query.context || !query.context); }); if (found.length !== 0) { return found; } return _.filter(this.viewBuilders, function (vB) { return vB.name === '' && (vB.version === query.version || vB.version === -1) && (vB.aggregate === query.aggregate || !query.aggregate) && (vB.context === query.context || !query.context); }); }
javascript
{ "resource": "" }
q56427
train
function (query) { if (!query || !_.isObject(query)) { var err = new Error('Please pass a valid query object!'); debug(err); throw err; } query.name = query.name || ''; query.version = query.version || 0; query.aggregate = query.aggregate || null; query.context = query.context || null; var found = _.find(this.eventExtenders, function (evExt) { return evExt.name === query.name && (evExt.version === query.version || evExt.version === -1) && (evExt.aggregate === query.aggregate) && (evExt.context === query.context); }); if (found) { return found; } found = _.find(this.eventExtenders, function (evExt) { return evExt.name === query.name && (evExt.version === query.version || evExt.version === -1) && (evExt.aggregate === query.aggregate || !query.aggregate || !evExt.aggregate) && (evExt.context === query.context); }); if (found) { return found; } found = _.find(this.eventExtenders, function (evExt) { return evExt.name === query.name && (evExt.version === query.version || evExt.version === -1) && (evExt.aggregate === query.aggregate || !query.aggregate || !evExt.aggregate) && (evExt.context === query.context || !query.context || !evExt.context); }); if (found) { return found; } return _.find(this.eventExtenders, function (evExt) { return evExt.name === '' && (evExt.version === query.version || evExt.version === -1) && (evExt.aggregate === query.aggregate || !query.aggregate || !evExt.aggregate) && (evExt.context === query.context || !query.context || !evExt.context); }); }
javascript
{ "resource": "" }
q56428
train
function (callback) { this.repository.getNewId(function(err, newId) { if (err) { debug(err); return callback(err); } callback(null, newId); }); }
javascript
{ "resource": "" }
q56429
train
function (vm, callback) { if (this.isReplaying) { vm.actionOnCommitForReplay = vm.actionOnCommit; // Clone the values to be sure no reference mistakes happen! if (vm.attributes) { var flatAttr = flatten(vm.attributes); var undefines = []; _.each(flatAttr, function (v, k) { if (v === undefined) { undefines.push(k); } }); vm.attributes = vm.toJSON(); _.each(undefines, function (k) { vm.set(k, undefined); }); } this.replayingVms[vm.id] = vm; if (vm.actionOnCommit === 'delete') { delete this.replayingVms[vm.id]; if (!this.replayingVmsToDelete[vm.id]) this.replayingVmsToDelete[vm.id] = vm; } if (vm.actionOnCommit === 'create') { vm.actionOnCommit = 'update'; } return callback(null); } this.repository.commit(vm, callback); }
javascript
{ "resource": "" }
q56430
train
function (id, callback) { if (this.isReplaying) { if (this.replayingVms[id]) { return callback(null, this.replayingVms[id]); } if (this.replayingVmsToDelete[id]) { var vm = new viewmodel.ViewModel({ id: id }, this.repository); var clonedInitValues = _.cloneDeep(this.modelInitValues); for (var prop in clonedInitValues) { if (!vm.has(prop)) { vm.set(prop, clonedInitValues[prop]); } } this.replayingVms[vm.id] = vm; return callback(null, this.replayingVms[id]); } } var self = this; this.repository.get(id, function(err, vm) { if (err) { debug(err); return callback(err); } if (!vm) { err = new Error('No vm object returned!'); debug(err); return callback(err); } var clonedInitValues = _.cloneDeep(self.modelInitValues); for (var prop in clonedInitValues) { if (!vm.has(prop)) { vm.set(prop, clonedInitValues[prop]); } } if (self.isReplaying) { if (!self.replayingVms[vm.id]) { self.replayingVms[vm.id] = vm; } return callback(null, self.replayingVms[vm.id]); } callback(null, vm); }); }
javascript
{ "resource": "" }
q56431
train
function (id, callback) { this.loadViewModel(id, function (err, vm) { if (err) { return callback(err); } if (!vm || vm.actionOnCommit === 'create') { return callback(null, null); } callback(null, vm); }); }
javascript
{ "resource": "" }
q56432
train
function (callback) { if (!this.isReplaying) { var err = new Error('Not in replay mode!'); debug(err); return callback(err); } var replVms = _.values(this.replayingVms); var replVmsToDelete = _.values(this.replayingVmsToDelete); var self = this; function commit (vm, callback) { if (!vm.actionOnCommitForReplay) { return callback(null); } vm.actionOnCommit = vm.actionOnCommitForReplay; delete vm.actionOnCommitForReplay; self.repository.commit(vm, function (err) { if (err) { debug(err); debug(vm); } callback(err); }); } function prepareVmsForBulkCommit (vms) { return _.map(_.filter(vms, function(vm) { return vm.actionOnCommitForReplay }), function (vm) { vm.actionOnCommit = vm.actionOnCommitForReplay; delete vm.actionOnCommitForReplay; return vm; }) } function bulkCommit (vms, callback) { if (vms.length === 0) return callback(null); self.repository.bulkCommit(prepareVmsForBulkCommit(vms), function (err) { if (err) { debug(err); } callback(err); }); } async.series([ function (callback) { if (self.repository.bulkCommit) { return bulkCommit(replVmsToDelete, callback); } async.each(replVmsToDelete, commit, callback); }, function (callback) { if (self.repository.bulkCommit) { return bulkCommit(replVms, callback); } async.each(replVms, commit, callback); } ], function (err) { if (err) { debug(err); } self.replayingVms = {}; self.replayingVmsToDelete = {}; self.isReplaying = false; callback(err); }); }
javascript
{ "resource": "" }
q56433
train
function(name, data, testFunction){ if(!_.isString(name)){ throw new Error('String expected for parameter name'); } if(!_.isArray(data)){ throw new Error('Array expected for parameter data'); } if(!_.isFunction(testFunction)){ throw new Error('Function expected for parameter testFunction'); } this._name = name; this._testFunction = testFunction; this._res = []; this._data = data; this._itr = 0; }
javascript
{ "resource": "" }
q56434
train
function(callback){ for(this._itr; this._itr < this._data.length; this._itr++) { this._testFunction.call(this, this._itr); } callback.call(this, this._res); }
javascript
{ "resource": "" }
q56435
train
function(s){ if (s.substr(0, 2) === '02' || s.substr(0, 2) === '03' || s.substr(0, 2) === '04' || s.substr(0, 2) === '07' || s.substr(0, 2) === '08') return true; return (s.substr(0, 2) === '61') || (s.substr(0, 4) === '0061'); }
javascript
{ "resource": "" }
q56436
train
function(n){ // Examine international prefix if(n.substr(0,2) === '61'){ return n.length === 11; } // Examine international prefix if(n.substr(0,4) === '0061'){ return n.length === 13; } // Examine number of digits return n.length === 10; }
javascript
{ "resource": "" }
q56437
train
function() { try { this.set(fs.existsSync(this._stateFile) ? JSON.parse(fs.readFileSync(this._stateFile)) : {}); } catch (e) {} }
javascript
{ "resource": "" }
q56438
train
function(key, value, callback) { if (this.get(key) == value) { return; } this.set(key, value); clearTimeout(this._saveTimeout); this._saveTimeout = setTimeout(_.bind(function() { fs.writeFile(this._stateFile, JSON.stringify(this.attributes, null, '\t'), _.bind(function() { logger.info(key + ' saved to ' + path.join(process.cwd(), this._stateFile)); while (this._callbacks && this._callbacks.length) { this._callbacks.shift()(); } }, this)); }, this), 1000); if (callback) { if (!this._callbacks) { this._callbacks = []; } this._callbacks.push(callback); } }
javascript
{ "resource": "" }
q56439
train
function(transport, message, info) { var e = message[0].replace('/', ''); var data = null; if (message[1]) { try { data = JSON.parse(message[1]); } catch (e) { logger.warn('OSC messages should be JSON'); } } transport.emit(e, data); }
javascript
{ "resource": "" }
q56440
train
function (evt, vm) { var notification = {}; // event if (!!this.definitions.notification.meta && !!this.definitions.event.meta) { dotty.put(notification, this.definitions.notification.meta, _.cloneDeep(dotty.get(evt, this.definitions.event.meta))); } if (!!this.definitions.notification.eventId && !!this.definitions.event.id) { dotty.put(notification, this.definitions.notification.eventId, dotty.get(evt, this.definitions.event.id)); } if (!!this.definitions.notification.event && !!this.definitions.event.name) { dotty.put(notification, this.definitions.notification.event, dotty.get(evt, this.definitions.event.name)); } if (!!this.definitions.notification.aggregateId && !!this.definitions.event.aggregateId) { dotty.put(notification, this.definitions.notification.aggregateId, dotty.get(evt, this.definitions.event.aggregateId)); } if (!!this.definitions.notification.aggregate && !!this.definitions.event.aggregate) { dotty.put(notification, this.definitions.notification.aggregate, dotty.get(evt, this.definitions.event.aggregate)); } if (!!this.definitions.notification.context && !!this.definitions.event.context) { dotty.put(notification, this.definitions.notification.context, dotty.get(evt, this.definitions.event.context)); } if (!!this.definitions.notification.revision && !!this.definitions.event.revision) { dotty.put(notification, this.definitions.notification.revision, dotty.get(evt, this.definitions.event.revision)); } dotty.put(notification, this.definitions.notification.correlationId, dotty.get(evt, this.definitions.event.correlationId)); // vm dotty.put(notification, this.definitions.notification.payload, vm.toJSON()); dotty.put(notification, this.definitions.notification.collection, this.collection.name); dotty.put(notification, this.definitions.notification.action, vm.actionOnCommit); return notification; }
javascript
{ "resource": "" }
q56441
train
function (evt, query, callback) { var self = this; this.findViewModels(query, function (err, vms) { if (err) { debug(err); return callback(err); } async.map(vms, function (vm, callback) { self.handleOne(vm, evt, function (err, notification) { if (err) { debug(err); return callback(err); } callback(null, notification); }); }, function (err, notifications) { if (err) { debug(err); return callback(err); } notifications = _.filter(notifications, function (n) { return !!n; }); callback(null, notifications); }); }); }
javascript
{ "resource": "" }
q56442
train
function (evt, callback) { var self = this; this.executeDenormFnForEach(evt, function (err, res) { if (err) { debug(err); return callback(err); } async.each(res, function (item, callback) { if (item.id) { return callback(null); } self.collection.getNewId(function (err, newId) { if (err) { return callback(err); } item.id = newId; callback(null); }); }, function (err) { if (err) { debug(err); return callback(err); } async.map(res, function (item, callback) { self.loadViewModel(item.id, function (err, vm) { if (err) { return callback(err); } self.handleOne(vm, evt, item, function (err, notification) { if (err) { return callback(err); } callback(null, notification); }); }); }, function (err, notis) { if (err) { debug(err); return callback(err); } callback(null, notis); }); }); }); }
javascript
{ "resource": "" }
q56443
train
function (evt, callback) { var self = this; function denorm() { if (self.executeDenormFnForEach) { return self.denormalizeForEach(evt, callback); } if (self.query) { return self.handleQuery(evt, self.query, callback); } if (!self.query && self.getQueryForThisViewBuilder) { self.getQueryForThisViewBuilder(evt, function (err, query) { if (err) { debug(err); return callback(err); } self.handleQuery(evt, query, callback); }); return; } self.extractId(evt, function (err, id) { if (err) { debug(err); return callback(err); } self.loadViewModel(id, function (err, vm) { if (err) { debug(err); return callback(err); } if (vm.actionOnCommit === 'create' && !self.autoCreate) { return callback(null, []); } self.handleOne(vm, evt, function (err, notification) { if (err) { debug(err); return callback(err); } var notis = []; if (notification) { notis.push(notification); } callback(null, notis); }); }); }); } // if (this.shouldHandleRequestsOnlyEvent) { this.shouldHandleEvent(evt, function (err, doHandle) { if (err) { return callback(err); } if (!doHandle) { return callback(null, []); } denorm(); }); // } else { // denorm(); // } }
javascript
{ "resource": "" }
q56444
train
function (fn) { if (!fn || !_.isFunction(fn)) { var err = new Error('Please pass a valid function!'); debug(err); throw err; } if (fn.length === 2) { this.getQueryForThisViewBuilder = fn; return this; } this.getQueryForThisViewBuilder = function (evt, callback) { callback(null, fn(evt)); }; var unwrappedFn = this.getQueryForThisViewBuilder; this.getQueryForThisViewBuilder = function (evt, clb) { var wrappedCallback = function () { try { clb.apply(this, _.toArray(arguments)); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; try { unwrappedFn.call(this, evt, wrappedCallback); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; return this; }
javascript
{ "resource": "" }
q56445
train
function (fn) { if (!fn || !_.isFunction(fn)) { var err = new Error('Please pass a valid function!'); debug(err); throw err; } if (fn.length === 3) { this.handleAfterCommit = fn; return this; } this.handleAfterCommit = function (evt, vm, callback) { callback(null, fn(evt, vm)); }; var unwrappedHandleAfterCommit = this.handleAfterCommit; this.handleAfterCommit = function (evt, vm, clb) { var wrappedCallback = function () { try { clb.apply(this, _.toArray(arguments)); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; try { unwrappedHandleAfterCommit.call(this, evt, vm, wrappedCallback); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; return this; }
javascript
{ "resource": "" }
q56446
train
function () { return (f.L() ? dayTableLeap[f.n()] : dayTableCommon[f.n()]) + f.j() - 1; }
javascript
{ "resource": "" }
q56447
train
function () { var unixTime = jsdate.getTime() / 1000; var secondsPassedToday = unixTime % 86400 + 3600; // since it's based off of UTC+1 if (secondsPassedToday < 0) { secondsPassedToday += 86400; } var beats = ((secondsPassedToday) / 86.4) % 1000; if (unixTime < 0) { return Math.ceil(beats); } return Math.floor(beats); }
javascript
{ "resource": "" }
q56448
train
function() { BaseModel.prototype.initialize.apply(this); $$persistence.on('heart', this._onHeart, this); this._updateStats(); this._updateCpuWin(); this._updateMemoryWin(); this._updateMemoryCpuMac(); $$network.transports.socketToConsole.sockets.on('connection', _.bind(this._onConnection, this)); }
javascript
{ "resource": "" }
q56449
train
function(user) { var config = _.cloneDeep($$config); var network = _.cloneDeep($$network.attributes); delete network.config; var persistence = _.cloneDeep($$persistence.attributes); delete persistence.config; var logging = _.cloneDeep($$logging.attributes); delete logging.config; delete logging.logCache; delete logging.eventCache; var permissions = user ? $$config.permissions[user] : null; return _.merge(_.cloneDeep($$config), { network: network, persistence: persistence, logging: logging, permissions: permissions }); }
javascript
{ "resource": "" }
q56450
train
function(socket) { var username = null; var permissions = null; if (socket.handshake.headers.authorization) { username = socket.handshake.headers.authorization.match(/username="([^"]+)"/)[1]; permissions = $$config.permissions ? $$config.permissions[username] : null; } // Responds to requests for appState updates, but throttle it to _updateConsoleRate. var updateConsole = _.bind(this._updateConsole, this); socket.on('appStateRequest', _.bind(function() { clearTimeout(this._updateConsoleTimeout); this._updateConsoleTimeout = setTimeout(updateConsole, this._updateConsoleRate); }, this)); socket.on('start', _.bind(function() { if (permissions && !permissions.app) { return; } logger.info('Startup requested from console.'); $$serverState.saveState('runApp', true); $$persistence.startApp(true); }, this)); socket.on('restart-app', _.bind(function() { if (permissions && !permissions.app) { return; } logger.info('Restart requested from console.'); $$serverState.saveState('runApp', true); $$persistence.restartApp(true); }, this)); socket.on('shutdown-app', _.bind(function() { if (permissions && !permissions.app) { return; } logger.info('Shutdown requested from console.'); $$serverState.saveState('runApp', false); $$persistence.shutdownApp(); }, this)); socket.on('restart-pc', _.bind(function() { if (permissions && !permissions.computer) { return; } logger.info('Reboot requested from console.'); $$persistence.restartMachine(); }, this)); socket.on('shutdown-pc', _.bind(function() { if (permissions && !permissions.computer) { return; } logger.info('Shutdown requested from console.'); $$persistence.shutdownMachine(); }, this)); socket.on('switchConfig', _.bind(function(config) { $$serverState.saveState('configFile', config, $$persistence.restartServer); }, this)); $$network.transports.socketToConsole.sockets.emit('config', this.fullConfig(username), this.get('configs')); }
javascript
{ "resource": "" }
q56451
train
function() { var message = _.clone(this.attributes); message.restartCount = $$persistence.get('restartCount'); message.logs = $$logging.get('logCache'); message.events = $$logging.get('eventCache'); $$network.transports.socketToConsole.sockets.emit('appState', message); }
javascript
{ "resource": "" }
q56452
train
function() { var fpsHistory = this.get('fps'); if (!fpsHistory) { fpsHistory = []; this.set({ fps: fpsHistory, }); } // Update FPS. if (this._tickSum) { var fps = 1000 / (this._tickSum / this._maxTicks); fps *= 100; fps = Math.round(fps); fps /= 100; fpsHistory.push(fps); while (fpsHistory.length > this._statHistory) { fpsHistory.shift(); } var avg = 0; fpsHistory.filter(function(f) { return f !== null; }).forEach(function(f) { avg += f; }); avg /= fpsHistory.length; this.set({ avgFps: Math.round(avg) }); } if ($$persistence.processId()) { // Update the uptime. var wasRunning = this.get('isRunning'); if (!wasRunning) { this._startupTime = Date.now(); } this.set('uptime', Date.now() - this._startupTime); this.set('isRunning', true); } else { // Not running, so reset everything. this.set({ isRunning: false, fps: null, memory: null, uptime: 0 }); } clearTimeout(this._updateStatsTimeout); this._updateStatsTimeout = setTimeout(_.bind(this._updateStats, this), this._updateStatsRate); }
javascript
{ "resource": "" }
q56453
train
function() { if (process.platform !== 'win32') { return; } var id = $$persistence.processId(); if (id) { child_process.exec('tasklist /FI "PID eq ' + id + '" /FO LIST', _.bind(function(error, stdout, stderror) { /* // tasklist.exe output looks like this: Image Name: Client.exe PID: 12008 Session Name: Console Session#: 1 Mem Usage: 39,384 K */ stdout = stdout.toString(); var match = XRegExp.exec(stdout, XRegExp('[\\d,]+\\sK')); if (!match) { return; } match = match[0]; // "39,384 K" match = match.replace(',', '').replace(' K', ''); // "39384" var memory = parseInt(match) * 1024; // 40329216 this._memoryFrame(memory); clearTimeout(this._updateMemoryWinTimeout); this._updateMemoryWinTimeout = setTimeout(_.bind(this._updateMemoryWin, this), this._updateStatsRate); $$persistence.checkMemory(memory); }, this)); } else { clearTimeout(this._updateMemoryWinTimeout); this._updateMemoryWinTimeout = setTimeout(_.bind(this._updateMemoryWin, this), this._updateStatsRate); } }
javascript
{ "resource": "" }
q56454
train
function() { if (process.platform !== 'darwin') { return; } // top is running in logging mode, spewing process info to stdout every second. this._topConsole = child_process.spawn('/usr/bin/top', ['-l', '0', '-stats', 'pid,cpu,mem,command']); this._topConsole.stdout.on('data', _.bind(function(stdout) { var id = $$persistence.processId(); if (!id) { return; } // Find the line with the process id that matches what we're watching. stdout = stdout.toString(); var lines = stdout.split('\n'); var line = lines.filter(function(line) { return line.indexOf(id) === 0; })[0]; if (!line) { return; } var parts = line.split(/\s+/g); // Add to the CPU history. var cpu = parseFloat(parts[1]); this._cpuFrame(cpu); // Add to the memory history. var memory = parts[2]; var unit = 1; if (memory.indexOf('K') !== -1) { unit = 1024; } else if (memory.indexOf('M') !== -1) { unit = 1024 * 1024; } else if (memory.indexOf('G') !== -1) { unit = 1024 * 1024 * 1024; } memory = memory.replace(/[\D]/g, ''); memory = parseInt(memory) * unit; this._memoryFrame(memory); }, this)); }
javascript
{ "resource": "" }
q56455
train
function(cpu) { if (!isNaN(cpu)) { var cpuHistory = this.get('cpu'); if (!cpuHistory) { cpuHistory = []; this.set('cpu', cpuHistory); } cpuHistory.push(cpu); while (cpuHistory.length > this._statHistory) { cpuHistory.shift(); } var avg = 0; cpuHistory.filter(function(f) { return f !== null; }).forEach(function(f) { avg += f; }); avg /= cpuHistory.length; this.set({ avgCpu: Math.round(avg) }); } }
javascript
{ "resource": "" }
q56456
train
function(memory) { var memoryHistory = this.get('memory'); if (!memoryHistory) { memoryHistory = []; this.set({ memory: memoryHistory }); } memoryHistory.push(memory); while (memoryHistory.length > this._statHistory) { memoryHistory.shift(); } var avg = 0; memoryHistory.filter(function(f) { return f !== null; }).forEach(function(f) { avg += f; }); avg /= memoryHistory.length; this.set({ avgMemory: Math.round(avg) }); }
javascript
{ "resource": "" }
q56457
train
function(message) { if (!this._tickList) { this._tickList = []; while (this._tickList.length < this._maxTicks) { this._tickList.push(0); } } if (!this._lastHeart) { this._lastHeart = Date.now(); this._lastFpsUpdate = this._lastHeart; return; } var newHeart = Date.now(); var newTick = newHeart - this._lastHeart; this._lastHeart = newHeart; this._tickSum -= this._tickList[this._tickIndex]; this._tickSum += newTick; this._tickList[this._tickIndex] = newTick; if (++this._tickIndex == this._maxTicks) { this._tickIndex = 0; } }
javascript
{ "resource": "" }
q56458
train
function(text, countryCode, useGooglePhoneLib){ const that = this, resultsFormatted = []; return new Promise(function(resolve, reject){ const data = utils.formatString(text); let countryRules; if(_.isString(countryCode)){ countryCode = countryCode.toUpperCase(); } if(countryCode === 'AU'){ countryRules = new locale.AU(data); } if(countryCode === 'US'){ countryRules = new locale.US(data); } if(!countryRules){ return reject('Unsupported county code "' + countryCode + '". Supported codes are "AU" (Australia) and "US" (United States)'); } async.map(countryRules.getRules(), function(rule, cb){ rule.run(function(result){ cb(null, result); }); }, function(err, results){ results = _.flatten(results || []); if(useGooglePhoneLib === true){ _.each(results, function(n){ resultsFormatted.push( that.formati18n(n, countryCode) ) }); return resolve(resultsFormatted); } resolve(results); }); }); }
javascript
{ "resource": "" }
q56459
train
function(n, countryCode){ const number = phoneUtil.parse(n, countryCode), isPossibleNumber = phoneUtil.isPossibleNumber(number), res = { input: n, countryCode: countryCode, isPossibleNumber: isPossibleNumber, isPossibleNumberWithReason: phoneUtil.isPossibleNumberWithReason(number) }; if(isPossibleNumber){ res.isPossibleNumber = true; res.isNumberValid = phoneUtil.isValidNumber(number); res.countryCode = countryCode; res.formatted = phoneUtil.formatInOriginalFormat(number, countryCode); res.national = phoneUtil.format(number, PNF.NATIONAL); res.international = phoneUtil.format(number, PNF.INTERNATIONAL) } switch (phoneUtil.isPossibleNumberWithReason(number)){ case PNV.IS_POSSIBLE: res.isPossibleNumberWithReason = 'IS_POSSIBLE'; break; case PNV.INVALID_COUNTRY_CODE: res.isPossibleNumberWithReason = 'INVALID_COUNTRY_CODE'; break; case PNV.TOO_SHORT: res.isPossibleNumberWithReason = 'TOO_SHORT'; break; case PNV.TOO_LONG: res.isPossibleNumberWithReason = 'TOO_LONG'; break; } return res; }
javascript
{ "resource": "" }
q56460
train
function (evt) { if (!evt || !_.isObject(evt)) { var err = new Error('Please pass a valid event!'); debug(err); throw err; } var name = dotty.get(evt, this.definition.name) || ''; var version = 0; if (dotty.exists(evt, this.definition.version)) { version = dotty.get(evt, this.definition.version); } else { debug('no version found, handling as version: 0'); } var aggregate = null; if (dotty.exists(evt, this.definition.aggregate)) { aggregate = dotty.get(evt, this.definition.aggregate); } else { debug('no aggregate found'); } var context = null; if (dotty.exists(evt, this.definition.context)) { context = dotty.get(evt, this.definition.context); } else { debug('no context found'); } return { name: name, version: version, aggregate: aggregate, context: context }; }
javascript
{ "resource": "" }
q56461
train
function (callback) { var self = this; var warnings = null; async.series([ // load domain files... function (callback) { debug('load denormalizer files..'); self.structureLoader(self.options.denormalizerPath, function (err, tree, warns) { if (err) { return callback(err); } warnings = warns; self.tree = attachLookupFunctions(tree); callback(null); }); }, // prepare infrastructure... function (callback) { debug('prepare infrastructure...'); async.parallel([ // prepare repository... function (callback) { debug('prepare repository...'); self.repository.on('connect', function () { self.emit('connect'); }); self.repository.on('disconnect', function () { self.emit('disconnect'); }); self.repository.connect(callback); }, // prepare revisionGuard... function (callback) { debug('prepare revisionGuard...'); self.revisionGuardStore.on('connect', function () { self.emit('connect'); }); self.revisionGuardStore.on('disconnect', function () { self.emit('disconnect'); }); self.revisionGuardStore.connect(callback); } ], callback); }, // inject all needed dependencies... function (callback) { debug('inject all needed dependencies...'); self.revisionGuard = new RevisionGuard(self.revisionGuardStore, self.options.revisionGuard); self.revisionGuard.onEventMissing(function (info, evt) { self.onEventMissingHandle(info, evt); }); self.eventDispatcher = new EventDispatcher(self.tree, self.definitions.event); self.tree.defineOptions(self.options) .defineEvent(self.definitions.event) .defineNotification(self.definitions.notification) .idGenerator(self.getNewId) .useRepository(self.repository); self.revisionGuard.defineEvent(self.definitions.event); self.replayHandler = new ReplayHandler(self.eventDispatcher, self.revisionGuardStore, self.definitions.event, self.options); callback(null); } ], function (err) { if (err) { debug(err); } if (callback) { callback(err, warnings); } }); }
javascript
{ "resource": "" }
q56462
train
function (callback) { debug('prepare repository...'); self.repository.on('connect', function () { self.emit('connect'); }); self.repository.on('disconnect', function () { self.emit('disconnect'); }); self.repository.connect(callback); }
javascript
{ "resource": "" }
q56463
train
function (callback) { debug('prepare revisionGuard...'); self.revisionGuardStore.on('connect', function () { self.emit('connect'); }); self.revisionGuardStore.on('disconnect', function () { self.emit('disconnect'); }); self.revisionGuardStore.connect(callback); }
javascript
{ "resource": "" }
q56464
train
function (evt, callback) { var self = this; var extendedEvent = evt; this.extendEventHandle(evt, function (err, extEvt) { if (err) { debug(err); } extendedEvent = extEvt || extendedEvent; var eventExtender = self.tree.getEventExtender(self.eventDispatcher.getTargetInformation(evt)); if (!eventExtender) { return callback(err, extendedEvent); } eventExtender.extend(extendedEvent, function (err, extEvt) { if (err) { debug(err); } extendedEvent = extEvt || extendedEvent; callback(err, extendedEvent); }); }); }
javascript
{ "resource": "" }
q56465
train
function (evt, callback) { var self = this; var extendedEvent = evt; var eventExtender = self.tree.getPreEventExtender(self.eventDispatcher.getTargetInformation(evt)); if (!eventExtender) { return callback(null, extendedEvent); } eventExtender.extend(extendedEvent, function (err, extEvt) { if (err) { debug(err); } extendedEvent = extEvt || extendedEvent; callback(err, extendedEvent); }); }
javascript
{ "resource": "" }
q56466
train
function (evt, callback) { if (!evt || !_.isObject(evt)) { var err = new Error('Please pass a valid event!'); debug(err); throw err; } var res = false; var self = this; var evtName = dotty.get(evt, this.definitions.event.name); var evtPayload = dotty.get(evt, this.definitions.event.payload); if (evtName === this.options.commandRejectedEventName && evtPayload && evtPayload.reason && evtPayload.reason.name === 'AggregateDestroyedError') { res = true; var info = { aggregateId: evtPayload.reason.aggregateId, aggregateRevision: evtPayload.reason.aggregateRevision, aggregate: !!this.definitions.event.aggregate ? dotty.get(evt, this.definitions.event.aggregate) : undefined, context: !!this.definitions.event.context ? dotty.get(evt, this.definitions.event.context) : undefined }; if (!this.definitions.event.revision || !dotty.exists(evt, this.definitions.event.revision) || !evtPayload.reason.aggregateId || (typeof evtPayload.reason.aggregateId !== 'string' && typeof evtPayload.reason.aggregateId !== 'number')) { this.onEventMissingHandle(info, evt); if (callback) { callback(null, evt, []); } return res; } this.revisionGuardStore.get(evtPayload.reason.aggregateId, function (err, rev) { if (err) { debug(err); if (callback) { callback([err]) } return; } debug('revision in store is "' + rev + '" but domain says: "' + evtPayload.reason.aggregateRevision + '"') if (rev - 1 < evtPayload.reason.aggregateRevision) { info.guardRevision = rev; self.onEventMissingHandle(info, evt); } else if (rev - 1 > evtPayload.reason.aggregateRevision) { debug('strange: revision in store greater than revision in domain, replay?') } if (callback) { callback(null, evt, []); } }); return res; } return res; }
javascript
{ "resource": "" }
q56467
train
function (evt, callback) { if (!evt || !_.isObject(evt) || !dotty.exists(evt, this.definitions.event.name)) { var err = new Error('Please pass a valid event!'); debug(err); if (callback) callback([err]); return; } var self = this; if (this.isCommandRejected(evt, callback)) { return; } var workWithRevisionGuard = false; if (!!this.definitions.event.revision && dotty.exists(evt, this.definitions.event.revision) && !!this.definitions.event.aggregateId && dotty.exists(evt, this.definitions.event.aggregateId)) { workWithRevisionGuard = true; } if (dotty.get(evt, this.definitions.event.name) === this.options.commandRejectedEventName) { workWithRevisionGuard = false; } if (!workWithRevisionGuard) { return this.dispatch(evt, callback); } this.revisionGuard.guard(evt, function (err, done) { if (err) { debug(err); if (callback) { try { callback([err]); } catch (e) { debug(e); process.emit('uncaughtException', e); } } return; } self.dispatch(evt, function (errs, extendedEvt, notifications) { if (errs) { debug(errs); if (callback) { try { callback(errs, extendedEvt, notifications); } catch (e) { debug(e); process.emit('uncaughtException', e); } } return; } done(function (err) { if (err) { if (!errs) { errs = [err]; } else if (_.isArray(errs)) { errs.unshift(err); } debug(err); } if (callback) { try { callback(errs, extendedEvt, notifications); } catch (e) { debug(e); process.emit('uncaughtException', e); } } }); }); }); }
javascript
{ "resource": "" }
q56468
train
function(attributes) { if (!attributes) attributes = {}; this.eClass = attributes.eClass; this.values = {}; // stores function for eOperations. attributes._ && (this._ = attributes._); // Initialize values according to the eClass features. initValues(this); setValues(this, attributes); initOperations(this); return this; }
javascript
{ "resource": "" }
q56469
train
function(name) { if (!this.has(name)) return false; var eClass = this.eClass; if (!eClass) return false; var value = this.get(name); if (value instanceof EList) { return value.size() > 0; } else { return value !== null && typeof value !== 'undefined'; } }
javascript
{ "resource": "" }
q56470
train
function(attrs, options) { var attr, key, val, eve; if (attrs === null) return this; if (attrs.eClass) { attrs = attrs.get('name'); } // Handle attrs is a hash or attrs is // property and options the value to be set. if (!_.isObject(attrs)) { key = attrs; (attrs = {})[key] = options; } var eResource = this.eResource(); for (attr in attrs) { val = attrs[attr]; if (typeof val !== 'undefined' && this.has(attr)) { if (this.isSet(attr)) { this.unset(attr); } var feature = getEStructuralFeature(this.eClass, attr), isContainment = feature.get('containment'); var settingContainmentAttribute = (attr === 'containment') && (typeof(val) === 'string') && (this.eClass.values.name === 'EReference'); if (settingContainmentAttribute) { // Convert string 'true' to boolean true val = (val.toLowerCase() === 'true'); } this.values[attr] = val; if (isContainment) { val.eContainingFeature = feature; val.eContainer = this; } eve = 'change:' + attr; this.trigger('change ' + eve, attr); if (eResource) eResource.trigger('change', this); } } return this; }
javascript
{ "resource": "" }
q56471
train
function(attrs, options) { var attr, key, eve; if (attrs === null) return this; if (attrs.eClass) { attrs = attrs.get('name'); } // Handle attrs is a hash or attrs is // property and options the value to be set. if (!_.isObject(attrs)) { key = attrs; (attrs = {})[key] = undefined; } var eResource = this.eResource(); for (attr in attrs) { if (this.has(attr) && this.isSet(attr)) { // unset var feature = getEStructuralFeature(this.eClass, attr), isContainment = Boolean(feature.get('containment')) === true; var value = this.values[attr]; if (isContainment) { value.eContainingFeature = undefined; value.eContainer = undefined; } this.values[attr] = undefined; eve = 'unset:' + attr; this.trigger('unset ' + eve, attr); if (eResource) eResource.trigger('change', this); } } return this; }
javascript
{ "resource": "" }
q56472
train
function(feature) { if (!feature) return null; var featureName = feature.eClass ? feature.get('name') : feature; if (!_.has(this.values, featureName) && this.has(featureName)) { initValue(this, getEStructuralFeature(this.eClass, featureName)); } var value = this.values[featureName]; if (typeof value === 'function') { return value.apply(this); } else { return value; } }
javascript
{ "resource": "" }
q56473
train
function(type) { if (!type || !this.eClass) return false; var typeName = type.eClass ? type.get('name') : type; return this.eClass.get('name') === typeName; }
javascript
{ "resource": "" }
q56474
train
function(type) { if(!type || !this.eClass) return false; if (this.isTypeOf(type)) return true; var typeName = type.eClass ? type.get('name') : type, superTypes = this.eClass.get('eAllSuperTypes'); return _.any(superTypes, function(eSuper) { return eSuper.get('name') === typeName; }); }
javascript
{ "resource": "" }
q56475
train
function() { if (!this.eClass) return []; if (_.isUndefined(this.__updateContents)) { this.__updateContents = true; var resource = this.eResource(); if (resource) { var me = this; resource.on('add remove', function() { me.__updateContents = true; }) } } if (this.__updateContents) { var eAllFeatures = this.eClass.get('eAllStructuralFeatures'); var eContainments = _.filter(eAllFeatures, function(feature) { return feature.isTypeOf('EReference') && feature.get('containment') && this.isSet(feature.get('name')); }, this); var value = null; this.__eContents = _.flatten(_.map(eContainments, function(c) { value = this.get(c.get('name')); return value ? (value.array ? value.array() : value) : []; }, this)); this.__updateContents = false; } return this.__eContents; }
javascript
{ "resource": "" }
q56476
train
function() { var eContainer = this.eContainer, eClass = this.eClass, iD = eClass.get('eIDAttribute'), eFeature, contents, fragment; // Must be at least contain in a Resource or EObject. if (!eContainer) return null; // Use ID has fragment if (iD) return this.get(iD.get('name')); if (this._id) return this._id; // ModelElement uses names except for roots if (this.isKindOf('EModelElement')) { if (!eContainer) { return '/'; } else if (eContainer.isKindOf('Resource')) { contents = eContainer.get('contents'); return contents.size() > 1 ? '/' + contents.indexOf(this) : '/'; } else { return eContainer.fragment() + '/' + this.get('name'); } } // Default fragments if (eContainer.isKindOf('Resource')) { contents = eContainer.get('contents'); fragment = contents.size() > 1 ? '/' + contents.indexOf(this) : '/'; } else { eFeature = this.eContainingFeature; if (eFeature) { fragment = eContainer.fragment() + '/@' + eFeature.get('name'); if (eFeature.get('upperBound') !== 1) { fragment += '.' + eContainer.get(eFeature.get('name')).indexOf(this); } } } return fragment; }
javascript
{ "resource": "" }
q56477
train
function(eObject) { if (!eObject || !eObject instanceof EObject) return this; if (this._isContainment) { eObject.eContainingFeature = this._feature; eObject.eContainer = this._owner; } this._size++; this._internal.push(eObject); var eResource = this._owner.eResource(), eve = 'add'; if (this._feature) eve += ':' + this._feature.get('name'); this._owner.trigger(eve, eObject); if (eResource) eResource.trigger('add', this); return this; }
javascript
{ "resource": "" }
q56478
train
function(eObject) { var eve = 'remove', eResource = this._owner.eResource(); this._internal = _.without(this._internal, eObject); this._size = this._size - 1; if (this._feature) eve += ':' + this._feature.get('name'); this._owner.trigger(eve, eObject); if (eResource) eResource.trigger('remove', this); return this; }
javascript
{ "resource": "" }
q56479
searchForComment
train
function searchForComment(node) { if(node.type == 'comment') { commentNodes.push(node); } if(!_(node.children).isUndefined()) { _.each(node.children, searchForComment); } }
javascript
{ "resource": "" }
q56480
removeStyleProperties
train
function removeStyleProperties(styles, properties) { _(styles).each(function(value, key) { if(_(properties).include(key)) { delete styles[key] } }); return styles; }
javascript
{ "resource": "" }
q56481
buildIndex
train
function buildIndex(model) { var index = {}, contents = model.get('contents').array(); if (contents.length) { var build = function(object, idx) { var eContents = object.eContents(); index[idx] = object; _.each(eContents, function(e) { build(e, e.fragment()); }); }; var root, iD; if (contents.length === 1) { root = contents[0]; if (root._id) { build(root, root._id); } else { iD = root.eClass.get('eIDAttribute') || null; if (iD) { build(root, root.get(iD.get('name'))); } else { build(root, '/'); } } } else { for (var i = 0; i < contents.length; i++) { root = contents[i]; if (root._id) { build(root, root._id); } else { iD = root.eClass.get('eIDAttribute') || null; if (iD) { build(root, root.get(iD.get('name'))); } else { build(root, '/' + i); } } } } } return index; }
javascript
{ "resource": "" }
q56482
strArray
train
function strArray(array) { if (Array.isArray(array)) { array = array.filter(isString); return array.length ? array : null; } return isString(array) ? [array] : null; }
javascript
{ "resource": "" }
q56483
firstOf
train
function firstOf(items, evaluate) { return new Promise((accept, reject) => { (function next(i) { if (i >= items.length) { accept(null); return; } setImmediate(() => evaluate(items[i], (err, value) => { if (err) reject(err); else if (value) accept(value); else next(i + 1); })); })(0); }); }
javascript
{ "resource": "" }
q56484
resolve
train
function resolve(importee, imports) { return firstOf(imports, ({root, extension}, done) => { const file = path.join(root, importee + extension); fs.stat(file, (err, stats) => { if (!err && stats.isFile()) done(null, file); else done(null, null); }); }); }
javascript
{ "resource": "" }
q56485
rotate
train
function rotate(out, a, angle) { var c = Math.cos(angle), s = Math.sin(angle) var x = a[0], y = a[1] out[0] = x * c - y * s out[1] = x * s + y * c return out }
javascript
{ "resource": "" }
q56486
addPackageFile
train
function addPackageFile (devDependency = false, extraOptions = null) { var packageJSON = { name: 'app', description: 'Vue Build Application', version: '0.1.0', dependencies: { 'vue-build': '^' + require('../package').version } } if (devDependency) { packageJSON.devDependencies = { 'vue-build': packageJSON.dependencies['vue-build'] } delete packageJSON.dependencies['vue-build'] } if (extraOptions) { packageJSON = Object.assign({}, packageJSON, extraOptions) } fs.writeFileSync( path.join(projectRoot, 'package.json'), JSON.stringify(packageJSON, null, 2) ) }
javascript
{ "resource": "" }
q56487
getMessages
train
function getMessages(result) { let messages = []; if (result.messages) { messages = messages.concat(result.messages); } if (result.schemaValidationMessages) { messages = messages.concat( result.schemaValidationMessages.map((m) => `${m.level}: ${m.message}`) ); } return messages; }
javascript
{ "resource": "" }
q56488
divide
train
function divide(out, a, b) { out[0] = a[0] / b[0] out[1] = a[1] / b[1] return out }
javascript
{ "resource": "" }
q56489
train
function (args, config, logger, helper) { console.log(chalk.blue('Running server on http://localhost:' + port + '.....PID:' + process.pid)) var express = require('express') var expressApp = express() // require server path and pass express expressApp to it require(pathToServer)(expressApp) expressApp.listen(port) }
javascript
{ "resource": "" }
q56490
train
function (appServer) { appServer.use(function (req, res, next) { if (process.env.ENVIRONMENT === 'development') { // Lets not console log for status polling or webpack hot module reloading if ( !req.url.includes('/status') && !req.url.includes('/__webpack_hmr') ) { console.log('Using middleware for ' + req.url) } } next() }) // Add webpack hot middleware to use for error overlay // Quiet is set to true because well let WebpackDevServer handle console logging appServer.use(webpackHotMiddleware(compiler)) // If there is a server.js file load it and pass appServer to it if (pathToServer) { require(pathToServer)(appServer) } }
javascript
{ "resource": "" }
q56491
fromValues
train
function fromValues(x, y) { var out = new Float32Array(2) out[0] = x out[1] = y return out }
javascript
{ "resource": "" }
q56492
limit
train
function limit(out, a, max) { var mSq = a[0] * a[0] + a[1] * a[1]; if (mSq > max * max) { var n = Math.sqrt(mSq); out[0] = a[0] / n * max; out[1] = a[1] / n * max; } else { out[0] = a[0]; out[1] = a[1]; } return out; }
javascript
{ "resource": "" }
q56493
combineHeaders
train
function combineHeaders(...args) { const combinedLower = {}; const combined = {}; args.reverse(); args.forEach((headers) => { if (headers) { Object.keys(headers).forEach((name) => { const nameLower = name.toLowerCase(); if (!hasOwnProperty.call(combinedLower, nameLower)) { combinedLower[nameLower] = true; combined[name] = headers[name]; } }); } }); return combined; }
javascript
{ "resource": "" }
q56494
flushData
train
function flushData() { if (currentCharacters) { currentElement.appendChild( doc.createTextNode(currentCharacters)); currentCharacters = ''; } else if (currentCdata) { currentElement.appendChild( doc.createCDATASection(currentCdata)); currentCdata = ''; } }
javascript
{ "resource": "" }
q56495
Mutt
train
function Mutt(schema, options = {}, debug = false) { if (debug) { this.config.setSetting("debug", true) } if (schema === undefined) { throw new Error("You must specify a Schema!") } // Setup a new form instance if called directly return new MuttForm(schema, options) }
javascript
{ "resource": "" }
q56496
initApi
train
function initApi(Mutt) { // Setup the config const config = new MuttConfig() Mutt.config = config // Setup plugin interface Mutt.use = function(plugins) { if (!Array.isArray(plugins)) { plugins = [plugins] } for (const plugin of plugins) { Mutt.config.use(plugin) } } // Setup Utilities Mutt.logger = logger Mutt.mixin = mixin // Add in hooks for fields, widgets & validators Mutt.fields = fields Mutt.widgets = widgets Mutt.validators = validators Mutt.serializers = serializers }
javascript
{ "resource": "" }
q56497
configure
train
function configure(loggers, logDir) { var msgLogger; var logLevel; logLevel = winston.level; // ServerNode. loggers.add('servernode', { console: { level: logLevel, colorize: true }, file: { level: logLevel, timestamp: true, filename: path.join(logDir, 'servernode.log'), maxsize: 1000000, maxFiles: 10 } }); // Channel. loggers.add('channel', { console: { level: logLevel, colorize: true, }, file: { level: logLevel, timestamp: true, filename: path.join(logDir, 'channels.log'), maxsize: 1000000, maxFiles: 10 } }); // Messages. // Make custom levels and only File transports for messages. msgLogger = loggers.add('messages'); msgLogger.remove(winston.transports.Console); msgLogger.add(winston.transports.File, { timestamp: true, maxsize: 1000000, filename: path.join(logDir, 'messages.log') }); // Do not change, or logging might be affected. // Logger.js hardcodes the values for speed. msgLogger.setLevels({ // Log none. none: 0, // All DATA msgs. data: 1, // All SET and DATA msgs. set: 3, // All SET, GET and DATA msgs. get: 5, // All SETUP, SET, GET and DATA msgs. setup: 7, // All messages, but **not** PLAYER_UPDATE, SERVERCOMMAND and ALERT. game: 9, // All messages. all: 11 }); // Set default logging level for messages. msgLogger.level = 'all'; // Clients. loggers.add('clients', { console: { level: logLevel, colorize: true, }, file: { level: 'silly', timestamp: true, filename: path.join(logDir, 'clients.log') } }); return true; }
javascript
{ "resource": "" }
q56498
generalLike
train
function generalLike(d, value, comparator, sensitive) { var regex; RegExp.escape = function(str) { return str.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; regex = RegExp.escape(value); regex = regex.replace(/%/g, '.*').replace(/_/g, '.'); regex = new RegExp('^' + regex + '$', sensitive); if ('object' === typeof d) { return function(elem) { var i, len; len = d.length; for (i = 0; i < len; i++) { if ('undefined' !== typeof elem[d[i]]) { if (regex.test(elem[d[i]])) { return elem; } } } }; } else if (d === '*') { return function(elem) { var d; for (d in elem) { if ('undefined' !== typeof elem[d]) { if (regex.test(elem[d])) { return elem; } } } }; } else { return function(elem) { if ('undefined' !== typeof elem[d]) { if (regex.test(elem[d])) { return elem; } } }; } }
javascript
{ "resource": "" }
q56499
logSecureParseError
train
function logSecureParseError(text, e) { var error; text = text || 'generic error while parsing a game message.'; error = (e) ? text + ": " + e : text; this.node.err('Socket.secureParse: ' + error); return false; }
javascript
{ "resource": "" }