_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q36700
reverse
train
function reverse(param) { var ret = new buffer.Buffer(param.length); for (var i = 0; i < param.length; i++) { ret[i] = param[param.length - i - 1]; } return ret; }
javascript
{ "resource": "" }
q36701
transformAllFiles
train
function transformAllFiles(transform, flush) { var files = []; return through.obj( function(file, enc, cb) { if (file.isStream()) { this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Streams are not supported!')); return cb(); } if (file.isBuffer()) { if (transform) transform.call(this, file, enc); } files.push(file); cb(); }, function(cb) { if (flush) files = flush.call(this, files); for (var i = 0; i < files.length; ++i) { this.push(files[i]); } cb(); } ); }
javascript
{ "resource": "" }
q36702
exec
train
function exec(cmd, args = [], silent = false) { return __awaiter(this, void 0, void 0, function* () { const response = []; return new Promise((resolve, reject) => { const exe = child_process_1.spawn(cmd, args, { env: process.env }); exe.stdout.on('data', data => { response.push(data.toString()); if (!silent) { console.log(data.toString()); } }); exe.stderr.on('data', data => { if (!silent) { console.error(data.toString()); } }); exe.on('exit', code => { if (code === 0) { return resolve(response); } else { if (!silent) { console.error('Problem executing ' + cmd); } return reject(); } }); }); }); }
javascript
{ "resource": "" }
q36703
DbEntity
train
function DbEntity(table, entity, opts, pool, logger){ LOGGER = logger; this.pool = pool; this.table = table; this.entity = entity; if(_.isNil(opts)||_.isNil(opts.plural)){ if(_.endsWith(entity,'y')){ this.plural = entity.substr(0, entity.lastIndexOf('y')) + 'ies'; } else if (_.endsWith(entity,'s')) { this.plural = entity.substr(0, entity.lastIndexOf('s')) + 'es'; } else { this.plural = entity + 's'; } } else { this.plural = opts.plural; } this.options = (opts || { created_timestamp_column: 'created', updated_timestamp_column: 'updated', version_number_column: 'version', log_category: 'db' }); if(logger && LOGGER.info){ LOGGER = logger; } else { //use winston LOGGER = {error: console.log, warn: console.log, info: function(){}, debug: function(){}, silly: function(){} } } this.metadata = null;//initialized to empty. }
javascript
{ "resource": "" }
q36704
_transformToSafeValue
train
function _transformToSafeValue(input, column){ var out = input; var datatype = column.sql_type; var nullable = column.nullable; if( input === '' ){ //empty string. if(datatype==='datetime'|| datatype==='timestamp' ||_.startsWith(datatype, 'int') || _.startsWith(datatype, 'num') || _.startsWith(datatype, 'dec')){ if(nullable){ out = null; } else { throw new Error(column.column + ' is not permitted to be empty.') } } } else if( !_.isNil(input) ) { //not null, not undefined if(datatype==='datetime'|| datatype==='timestamp'){ out = moment(input).format('YYYY-MM-DD HH:mm:ss'); } } return out; }
javascript
{ "resource": "" }
q36705
fulfill
train
function fulfill(promise, value) { if (promise.state !== PENDING) return; promise.value = value; promise.state = FULFILLED; return resolve(promise); }
javascript
{ "resource": "" }
q36706
reject
train
function reject(promise, reason) { if (promise.state !== PENDING) return; promise.reason = reason; promise.state = REJECTED; return resolve(promise); }
javascript
{ "resource": "" }
q36707
execute
train
function execute(collector, cmd, options, callback) { collector._process = exec(cmd, options, function(err, stdout, stderr) { var cmdPrefix = '' , child = collector._process ; // normalize stdout = (stdout || '').trim(); stderr = (stderr || '').trim(); // clean up finished process reference delete collector._process; if (err) { // clean up shell errors err.message = (err.message || '').trim(); err.stdout = stdout; err.stderr = stderr; // make it uniform across node versions (and platforms as side effect) // looking at you node@6.3+ if (err.cmd && (cmdPrefix = err.cmd.replace(cmd, '')) != err.cmd) { err.cmd = cmd; err.message = err.message.replace(cmdPrefix, ''); } // check if process has been willingly terminated if (child._executioner_killRequested && err.killed) { // mark job as properly terminated err.terminated = true; // it happen as supposed, so output might matter callback(err, stdout); return; } // just an error, no output matters callback(err); return; } // everything is good callback(null, stdout); }); }
javascript
{ "resource": "" }
q36708
getHeatmap
train
function getHeatmap(tracks) { var heatmap = []; _.each(tracks, function(track) { var idxStart = Math.floor(track.startTime / HEATMAP_SEGMENT), idxEnd = Math.ceil(track.endTime / HEATMAP_SEGMENT); idxEnd = Math.min(MAX_HEATMAP_LEN, idxEnd); /* Protection - sometimes we have buggy tracks which end in Infinity */ for (var i=idxStart; i<idxEnd; i++) { if (i<0) continue; if (! heatmap[i]) heatmap[i] = 0; USE_BOOLEAN ? heatmap[i] = 1 : heatmap[i]++; } }); /* Heatmap: Fill in the blanks */ for (var i = 0; i!=heatmap.length; i++) if (! heatmap[i]) heatmap[i] = 0; return heatmap; }
javascript
{ "resource": "" }
q36709
WithName
train
function WithName(name, Base) { let BaseClass = Base || Therror; return class extends BaseClass { constructor(err, msg, prop) { super(err, msg, prop); this.name = name; } }; }
javascript
{ "resource": "" }
q36710
sitemap
train
function sitemap(app) { let html return (req, res) => { if(!html) html = view(parseRoutes(app)) res.set({ 'Content-Type': 'text/html', 'Content-Length': html.length }) res.send(html) } }
javascript
{ "resource": "" }
q36711
getTouchById
train
function getTouchById(touches, id) { if (touches != null && id != null) { for (var i = 0; i < touches.length; i++) { if (touches[i].identifier === id) { return touches[i]; } } } return null; }
javascript
{ "resource": "" }
q36712
PointerEvent
train
function PointerEvent(options) { var _this = this; _classCallCheck(this, PointerEvent); this.startHandlers = {}; this.lastHandlerId = 0; this.curPointerClass = null; this.curTouchId = null; this.lastPointerXY = { clientX: 0, clientY: 0 }; this.lastTouchTime = 0; // Options this.options = { // Default preventDefault: true, stopPropagation: true }; if (options) { ['preventDefault', 'stopPropagation'].forEach(function (option) { if (typeof options[option] === 'boolean') { _this.options[option] = options[option]; } }); } }
javascript
{ "resource": "" }
q36713
findSatisfying
train
function findSatisfying (pkg, name, range, mustHave, reg) { if (mustHave) return null return semver.maxSatisfying ( Object.keys(reg[name] || {}) .concat(Object.keys(Object.getPrototypeOf(reg[name] || {}))) , range ) }
javascript
{ "resource": "" }
q36714
withConfig
train
function withConfig(fn) { return (source, options={}) => { options.type = 'dom'; options.client = options.client || rp; return fn(source, options); } }
javascript
{ "resource": "" }
q36715
getNextId
train
function getNextId() { var dataIds = Object.keys(idIndexData) dataIds.sort(function (a, b) { return b - a }) if (dataIds && dataIds[0]) { var id = _.parseInt(dataIds[0]) + 1 return id } else { return 1 } }
javascript
{ "resource": "" }
q36716
del
train
function del(id, callback) { callback = callback || emptyFn if (typeof callback !== 'function') { throw new TypeError('callback must be a function or empty') } if (!idIndexData[id]) { return callback(new Error('No object found with \'' + options.idProperty + '\' = \'' + id + '\'')) } self.emit('delete', id) delete idIndexData[id] // Work around for dynamic property var find = {} find[options.idProperty] = id data.splice(_.findIndex(data, find), 1) saveFile('afterDelete', id, callback) }
javascript
{ "resource": "" }
q36717
devices
train
function devices (port, paths) { paths = paths || {} var actualPath = defaults(paths, defaultPaths) var device = isNaN(port) ? motor() : sensor() if (device.prefix === motor().prefix) { port = port.toUpperCase() } if (device.available[device.prefix + port]) { return path.join(device.path, device.available[device.prefix + port]) } else { throw new Error('no device in port ' + port) } function motor () { motorCache = isEmpty(motorCache) ? getPaths(actualPath.motor) : motorCache return { path: actualPath.motor, available: motorCache, prefix: 'out' } } function sensor () { sensorCache = isEmpty(sensorCache) ? getPaths(actualPath.sensor) : sensorCache return { path: actualPath.sensor, available: sensorCache, prefix: 'in' } } }
javascript
{ "resource": "" }
q36718
SetArr
train
function SetArr() { let arr = {} let set = { size: 0, clear() { set.size = 0 }, add(item) { let index = arr.indexOf(item) if (index !== -1) return arr arr.push(item) set.size = arr.length return set }, delete(item) { let index = arr.indexOf(item) if (index === -1) return false arr.splice(index, 1) set.size = arr.length return true }, [Symbol.iterator]: () => arr[Symbol.iterator]() } return set }
javascript
{ "resource": "" }
q36719
Autocrat
train
function Autocrat(options) { this.options = parseOptions(this, options); /** * A namespace to host members related to observing state/Autocrat activity * * @name surveillance * @namespace */ surveillance.serveAutocrat(this); this.surveillance = surveillance; /** * Has a dual nature as both an array and a namespace. The array members are * plugins, which are essentially mixins for the Autocrat singleton. * The namespace is used a general storage for plugin related methods and * information * * @name constitution * @namespace */ constitution.serveAutocrat(this); Ward.serveAutocrat(this); this.Ward = Ward; Advisor.serveAutocrat(this); this.Advisor = Advisor; Governor.serveAutocrat(this); this.Governor = Governor; Domain.serveAutocrat(this); this.Domain = Domain; Law.serveAutocrat(this); this.Law = Law; }
javascript
{ "resource": "" }
q36720
getTransformPropertyName
train
function getTransformPropertyName(globalObj, forceRefresh = false) { if (storedTransformPropertyName_ === undefined || forceRefresh) { const el = globalObj.document.createElement('div'); const transformPropertyName = ('transform' in el.style ? 'transform' : 'webkitTransform'); storedTransformPropertyName_ = transformPropertyName; } return storedTransformPropertyName_; }
javascript
{ "resource": "" }
q36721
updateDepsTo
train
function updateDepsTo (arg, cb) { asyncMap(arg._others, function (o, cb) { updateOtherVersionDeps(o, arg, cb) }, cb) }
javascript
{ "resource": "" }
q36722
createDependencyLinks
train
function createDependencyLinks (dep, pkg, cb) { var depdir = path.join(npm.dir, dep.name, dep.version) , depsOn = path.join( depdir , "dependson" , pkg.name+"@"+pkg.version ) , deps = path.join(depdir, "node_modules", pkg.name) , targetRoot = path.join(npm.dir, pkg.name, pkg.version) , dependentLink = path.join( npm.dir , pkg.name , pkg.version , "dependents" , dep.name + "@" + dep.version ) asyncMap ( [ [ link, targetRoot, depsOn ] , [ link, depdir, dependentLink ] , [ linkBins, pkg, path.join(depdir, "dep-bin"), false ] , [ linkModules, pkg, deps ] ] , function (c, cb) { c.shift().apply(null, c.concat(cb)) } , cb ) }
javascript
{ "resource": "" }
q36723
defer
train
function defer(timeout) { var resolve, reject; var promise = new Promise(function() { resolve = arguments[0]; reject = arguments[1]; setTimeout(reject, timeout, "Timeout"); }); return { resolve: resolve, reject: reject, promise: promise, timestamp:new Date().getTime() }; }
javascript
{ "resource": "" }
q36724
oneShot
train
function oneShot(callback) { var done = false; return function (err) { if (!done) { done = true; return callback.apply(this, arguments); } if (err) console.error(err.stack); } }
javascript
{ "resource": "" }
q36725
makeFile
train
function makeFile(idx) { var file = new Vinyl({ path: `source-file-${idx}.hbs`, contents: new Buffer(`this is source-file-${idx}`) }); file.data = { categories: pickCategories(), tags: pickTags() }; return file; }
javascript
{ "resource": "" }
q36726
pickTags
train
function pickTags() { var picked = []; var max = Math.floor(Math.random() * maxTags); while(picked.length < max) { var tag = pickTag(); if (picked.indexOf(tag) === -1) { picked.push(tag); } } return picked; }
javascript
{ "resource": "" }
q36727
pickCategories
train
function pickCategories() { var picked = []; var max = Math.floor(Math.random() * maxCategories); while(picked.length < max) { var category = pickCategory(); if (picked.indexOf(category) === -1) { picked.push(category); } } return picked; }
javascript
{ "resource": "" }
q36728
Injector
train
function Injector(conf) { component.Component.call(this, 'injector', conf); var that = this; this._default_controller = defaults.controllerfuncname(conf); this._dbconn = conf.dbconn; this.registerGearman(conf.servers, { worker: { func_name: 'submitJobDelayed', func: function(payload, worker) { var task; try { task = JSON.parse(payload); } catch (err) { that._err('Error:', err.message); worker.done(that.component_name + ': ' + err.message); return; } that._info('Received a task for', (task.controller || that._default_controller) + '/' + task.func_name); // TODO: Properly abstract date handling into lib/gearsloth.js and handle // invalid dates etc. if ('at' in task) { task.at = new Date(task.at); if (isNaN(task.at.getTime())) { worker.done(that.component_name + ': invalid date format.'); return; } } if ('after' in task && isNaN(task.after)) { worker.done(that.component_name + ': invalid \'after\' format.'); return; } if (! ('func_name' in task)) { worker.done(that.component_name + ': no function name (func_name) defined in task.'); return; } that.inject(task, worker); } } }); }
javascript
{ "resource": "" }
q36729
getData
train
function getData(callArgs, req, res, next) { debug("getData called"); if (callArgs.useStub) readStub(callArgs, req, res, next); else callApi(callArgs, req, res, next); }
javascript
{ "resource": "" }
q36730
GlobalDefine
train
function GlobalDefine(options) { var globalDefine; if (!(this instanceof GlobalDefine)) { globalDefine = new GlobalDefine(options); return globalDefine.amdefineWorkaround(globalDefine.getCallerModule()); } this.basePath = options.basePath || process.cwd(); this.paths = options.paths || paths; this.pathsKeys = Object.keys(this.paths).sort(sortPaths); this.blackList = options.blackList || blackList; this.whiteList = options.whiteList || whiteList; this.disableCache = options.disableCache || disableCache; this.aliasRequire = options.aliasRequire || aliasRequire; // if flag provided override default value this.exposeAmdefine = ('exposeAmdefine' in options) ? options.exposeAmdefine : exposeAmdefine; // construct basePath regexp this.basePathRegexp = new RegExp(('^' + this.basePath + '/').replace('/', '\\/')); // propagate upstream to allow global-define on sibling branches this.propagateUpstream(this.getCallerModule(), options.forceUpstream); // being a little bit brutal // for things that go around normal module loading process // like `istanbul`, that reads (`fs.readFileSync(filename, 'utf8')`) // and runs `module._compile(code, filename);` compilation step // skipping loading extensions. // But do it only once, no need to step on itself if (options.invasiveMode && Module.prototype._compile._id != module.id) { originalModuleCompile = Module.prototype._compile; Module.prototype._compile = customModuleCompile; Module.prototype._compile._id = module.id; } }
javascript
{ "resource": "" }
q36731
propagateUpstream
train
function propagateUpstream(parentModule, shouldPropagate) { // do not step on another global-define instance if (parentModule._globalDefine) return; // keep reference to the define instance parentModule._globalDefine = this; if (shouldPropagate && parentModule.parent) { this.propagateUpstream(parentModule.parent, shouldPropagate); } }
javascript
{ "resource": "" }
q36732
checkPath
train
function checkPath(id) { var i; for (i = 0; i < this.pathsKeys.length; i++) { if (id.indexOf(this.pathsKeys[i]) == 0) { if (this.paths[this.pathsKeys[i]] == 'empty:') { id = 'empty:'; } else { id = id.replace(this.pathsKeys[i], this.paths[this.pathsKeys[i]]); } break; } } return id; }
javascript
{ "resource": "" }
q36733
isBlacklisted
train
function isBlacklisted(moduleId) { var i; // strip basePath moduleId = moduleId.replace(this.basePathRegexp, ''); for (i = 0; i < this.blackList.length; i++) { if (minimatch(moduleId, this.blackList[i])) { return true; } } return false; }
javascript
{ "resource": "" }
q36734
isWhitelisted
train
function isWhitelisted(moduleId) { var i; // check if its empty if (!this.whiteList.length) { return true; } // strip basePath moduleId = moduleId.replace(this.basePathRegexp, ''); for (i = 0; i < this.whiteList.length; i++) { if (minimatch(moduleId, this.whiteList[i])) { return true; } } return false; }
javascript
{ "resource": "" }
q36735
customModuleCompile
train
function customModuleCompile(content, filename) { var moduleExceptions, parentDefine = global.define; if (!this._globalDefine) { setGlobalDefine(this); } moduleExceptions = originalModuleCompile.call(this, content, filename); global.define = parentDefine; return moduleExceptions; }
javascript
{ "resource": "" }
q36736
setGlobalDefine
train
function setGlobalDefine(requiredModule) { // pass globalDefine instance from parent to child module if (requiredModule.parent && requiredModule.parent._globalDefine) { // inherited instance requiredModule._globalDefine = requiredModule.parent._globalDefine; } // create global define specific to the module // but only if its whitelisted and not blacklisted if (requiredModule._globalDefine && requiredModule._globalDefine.isWhitelisted(requiredModule.id) && !requiredModule._globalDefine.isBlacklisted(requiredModule.id)) { global.define = requiredModule._globalDefine.amdefineWorkaround(requiredModule); // run required paths through alias substituion if (requiredModule._globalDefine.aliasRequire) { requiredModule._originalRequire = requiredModule.require; requiredModule.require = function(modulePath) { return requiredModule._originalRequire.call(this, requiredModule._globalDefine.checkPath(modulePath)); } } } else { // reset global define delete global.define; } }
javascript
{ "resource": "" }
q36737
filesToPacks
train
function filesToPacks(files) { return files.map(function(id) { return { id: id, source: readFile(id), mtime: readMTime(id) }; }); }
javascript
{ "resource": "" }
q36738
updatePacks
train
function updatePacks(packs) { var didUpdate = false; var updated = packs.map(function(pack) { var mtime_ = readMTime(pack.id); if (pack.mtime !== mtime_) { didUpdate = true; return { id: pack.id, source: readFile(pack.id), mtime: mtime_ }; } else { return pack; } }); return didUpdate ? updated : packs; }
javascript
{ "resource": "" }
q36739
stitch
train
function stitch(name, packs) { var content = ';(function(require){\n'; packs.forEach(function(pack) { content += removeSourceMaps(pack.source); if (content[content.length-1] !== '\n') content += '\n'; }); content += '\nreturn require;}());\n'; return content; }
javascript
{ "resource": "" }
q36740
VKOAuth2
train
function VKOAuth2(appId, appSecret, redirectURL, fullSettings) { this._appId = appId; this._appSecret = appSecret; this._redirectURL = redirectURL; fullSettings = fullSettings || {}; this._vkOpts = fullSettings.settings || {}; this._apiVersion = this._vkOpts.version || '5.41'; this._dialogOptions = this._vkOpts.dialog || {}; this._fields = fullSettings.fieldMap ? _.values(fullSettings.fieldMap) : []; this._fields = _.unique(this._fields.concat(['uid', 'first_name', 'last_name', 'screen_name'])); this._authURL = 'https://oauth.vk.com/authorize'; this._accessTokenURI = 'https://oauth.vk.com/access_token'; this._profileURI = 'https://api.vk.com/method/users.get'; }
javascript
{ "resource": "" }
q36741
score
train
function score(data, candidate) { var result = 0; /* Scoring calculations here */ //Last Name if (!data.name.last || !candidate.name.last) { result = result + 0; } else if (data.name.last.toUpperCase() === candidate.name.last.toUpperCase()) { result = result + 9.58; } else if (data.name.last.toUpperCase().substring(0, 3) === candidate.name.last.toUpperCase().substring(0, 3)) { result = result + 5.18; } else if (data.name.last.toUpperCase().substring(0, 3) !== candidate.name.last.toUpperCase().substring(0, 3)) { result = result - 3.62; } //First Name if (!data.name.first || !candidate.name.first) { result = result + 0; } else if (data.name.first.toUpperCase() === candidate.name.first.toUpperCase()) { result = result + 6.69; } else if (data.name.first.toUpperCase().substring(0, 3) === candidate.name.first.toUpperCase().substring(0, 3)) { result = result + 3.37; } else if (data.name.first.toUpperCase().substring(0, 3) !== candidate.name.first.toUpperCase().substring(0, 3)) { result = result - 3.27; } //Middle Initial if (!data.name.middle || !candidate.name.middle) { result = result + 0; } else if (data.name.middle.toUpperCase().substring(0, 1) === candidate.name.middle.toUpperCase().substring(0, 1)) { result = result + 3.65; } //DOB if (!data.dob || !candidate.dob) { result = result + 0; } else if (data.dob.substring(0, 10) === candidate.dob.substring(0, 10)) { result = result + 6.22; } //Initials result = result + 0; return result; }
javascript
{ "resource": "" }
q36742
train
function() { var deferred = q.defer(); setTimeout(function() { console.log("Async Action 1 Completed"); deferred.resolve(); }, 1000); return deferred.promise; }
javascript
{ "resource": "" }
q36743
createRootReducer
train
function createRootReducer (model, name) { const handlers = {} const initialState = model.state // auto-generated reducers if (isNotNullObject(initialState)) { for (const key of Object.keys(initialState)) { handlers[addSetPrefix(name)(key)] = (state, action) => includeKey(action, 'payload') ? { ...state, [key]: action.payload } : state } } // reducer for updating multiple field of the state in one action // or replace the state directly handlers[addPrefix(name)('merge')] = (state, action) => { if (!includeKey(action, 'payload')) { return state } const payload = action.payload if (isNotArrayObject(state)) { // if (includeNewKeys(state, payload)) { // return pureMerge(state, payload) // } else { // return { ...state, ...payload } // } return pureMerge(state, payload) } else { return payload } } // user defined reducers for (const r of Object.keys(model.reducers || {})) { const reducer = model.reducers[r] let finalReducer if (typeof reducer === 'function') { finalReducer = (state, action) => reducer(state, action) } else { finalReducer = (state) => state } // notice the reducer override occurs here handlers[addPrefix(name)(r)] = finalReducer } return (state = initialState, action) => (handlers[action.type] ? handlers[action.type](state, action) : state) }
javascript
{ "resource": "" }
q36744
getNamespace
train
function getNamespace (path, relative) { // ignore parent path let final = '' if (relative) { const s = path.split('/') final = s[s.length - 1] } else { final = path.startsWith('./') ? path.slice(2) : path } // remove '.js' return final.slice(0, final.length - 3) }
javascript
{ "resource": "" }
q36745
readModels
train
function readModels (dir, relative) { const fs = require('fs') const path = require('path') // eslint-disable-next-line no-eval const evalRequire = eval('require') const list = [] function readRecursively (dir, root, list) { fs.readdirSync(dir).forEach(file => { const filePath = path.join(dir, file) if (fs.statSync(filePath).isDirectory()) { // walk through readRecursively(filePath, root, list) } else { // only '*.js' file will be added as model if (file.match(/^(\.\/)?([\w]+\/)*([\w]+\.js)$/)) { // bundler like webpack will complain about using dynamic require // See https://github.com/webpack/webpack/issues/196 // use `eval` trick to avoid this let model = evalRequire(filePath) // handling es6 module if (model.__esModule) { model = model.default } // get relative path of the root path const pathNS = path.join(path.relative(root, dir), file) list.push(checkNS(model) ? model : {namespace: getNamespace(pathNS, relative), ...model}) } } }) } const p = path.resolve(__dirname, dir) readRecursively(p, p, list) return list }
javascript
{ "resource": "" }
q36746
transformHtmlEntities
train
function transformHtmlEntities() { return function(method, request, next) { next(function(response, next) { response.body = utils.deHtmlEntities(response.body); next(); }) }; }
javascript
{ "resource": "" }
q36747
run
train
function run(cmd){ var proc = require('child_process'), done = grunt.task.current.async(); // Tells Grunt that an async task is complete proc.exec(cmd, function(error, stdout, stderr){ if(stderr){ grunt.log.writeln('ERROR: ' + stderr).error(); } grunt.log.writeln(stdout); done(error); } ); }
javascript
{ "resource": "" }
q36748
up
train
function up(){ console.log(grunt.target); var key = (grunt.option('name') || ""), label = ( key || "EMPTY"), cmd = (migrateBinPath + " up " + key).trim(); grunt.log.write('Running migration "UP" [' + label + ']...').ok(); run(cmd); }
javascript
{ "resource": "" }
q36749
down
train
function down(){ var key = (grunt.option('name') || ""), label = ( key || "EMPTY"), cmd = (migrateBinPath + " down " + key).trim(); grunt.log.write('Running migration "DOWN" [' + label + ']...').ok(); run(cmd); }
javascript
{ "resource": "" }
q36750
create
train
function create(){ var cmd = (migrateBinPath + " create " + grunt.option('name')).trim(); grunt.log.write('Creating a new migration named "' + grunt.option('name') + '"...').ok(); run(cmd); }
javascript
{ "resource": "" }
q36751
train
function(entity) { // Bind to start event right away. var boundStart = entity.start.bind(entity); this.on('start', boundStart); // Bind to preloadComplete, but only once. var boundPreloadComplete = entity.preloadComplete.bind(entity); this.once('preloadComplete', boundPreloadComplete); // Only bind to update after preloadComplete event. var boundUpdate = entity.update.bind(entity); this.once('preloadComplete', function() { this.on('update', boundUpdate); }.bind(this)); entity.on('destroy', function() { this.removeListener('start', boundStart); this.removeListener('preloadComplete', boundPreloadComplete); this.removeListener('update', boundUpdate); }.bind(this)); this.emit('entityAdded', entity); }
javascript
{ "resource": "" }
q36752
saveOpts
train
function saveOpts(apiOpts) { if (apiOpts.url && apiOpts.url.toLowerCase().indexOf('password') >= 0) { var idx = apiOpts.url.indexOf('?'); apiOpts.url = apiOpts.url.substring(0, idx); } storage.set('lastApiCall', (JSON.stringify(apiOpts) || '').substring(0, 250)); }
javascript
{ "resource": "" }
q36753
send
train
function send(url, method, options, resourceName) { var deferred = $q.defer(); var key, val, paramArray = []; url = config.apiBase + url; options = options || {}; // separate out data if it exists var data = options.data; delete options.data; // attempt to add id to the url if it exists if (url.indexOf('{_id}') >= 0) { if (options._id) { url = url.replace('{_id}', options._id); delete options._id; } else if (data && data._id) { url = url.replace('{_id}', data._id); } } else if (method === 'GET' && options._id) { url += '/' + options._id; delete options._id; } var showErr = options.showErr !== false; delete options.showErr; // add params to the URL options.lang = options.lang || config.lang; for (key in options) { if (options.hasOwnProperty(key) && options[key]) { val = options[key]; val = angular.isObject(val) ? JSON.stringify(val) : val; paramArray.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); } } // add params to URL if (paramArray.length) { url += '?' + paramArray.join('&'); } // set up the api options var apiOpts = { method: method, url: url }; // if the jwt exists, add it to the request var jwt = storage.get('jwt'); if (jwt && jwt !== 'null') { // hack fix; someone setting localStorage to 'null' apiOpts.headers = { Authorization: jwt }; } // add data to api options if available if (data) { apiOpts.data = data; } // emit events for start and end so realtime services can stop syncing for post eventBus.emit(resourceName + '.' + method.toLowerCase() + '.start'); // finally make the http call $http(apiOpts) .then(function (respData) { respData = respData || {}; saveOpts(apiOpts); deferred.resolve(respData.data); //deferred.resolve(respData.data || respData); }) .catch(function (err) { // if (status > 450 && status < 499) { // eventBus.emit('error.' + status, err); // return; // } saveOpts(apiOpts); // var isTimeout = !status || status === -1; // if (!err && isTimeout) { // err = new Error('Cannot access back end'); // } if (!err) { err = new Error('error httpCode ' + status + ' headers ' + JSON.stringify(headers) + ' conf ' + JSON.stringify(conf)); } if (showErr) { eventBus.emit('error.api', err); } log.error(err, { apiOpts: apiOpts, status: status, headers: headers }); deferred.reject(err); }) .finally(function () { eventBus.emit(resourceName + '.' + method.toLowerCase() + '.end'); }); return deferred.promise; }
javascript
{ "resource": "" }
q36754
extendsFrom
train
function extendsFrom(TestedClass, RootClass, enforceClasses = false) { if (!TestedClass || !RootClass) { return false; } if (TestedClass === RootClass) { return true; } TestedClass = TestedClass.constructor && typeof TestedClass !== 'function' ? TestedClass.constructor : TestedClass; RootClass = RootClass.constructor && typeof RootClass !== 'function' ? RootClass.constructor : RootClass; let ParentClass = TestedClass; if (parseInt(process.version.substring(1)) < 6) { throw new Error(` Reflect must be implemented in the JavaScript engine. This cannot be polyfilled and as such, if process.version is less than 6 an error will be thrown. Please try an alternate means of doing what you desire. `); } if (enforceClasses) { if (!isClass(TestedClass) && !isClass(RootClass)) { throw new Error(` When using extendsFrom() with enforceClasses true, each Function argument supplied must pass the isClass() method testing. See the function isClass to learn more about these requirements. `); } } if (!TestedClass || !RootClass) { return false; } if (TestedClass === RootClass) { return true; } do { ParentClass = (0, _getPrototypeOf2.default)(ParentClass); if (ParentClass === RootClass) { return true; } } while (ParentClass); return false; }
javascript
{ "resource": "" }
q36755
rgeom
train
function rgeom(prob) { var scale; if (prob <= 0 || prob > 1) { return function() { return NaN; }; } scale = prob / (1 - prob); return function() { return rpois(rexp(scale)())(); }; }
javascript
{ "resource": "" }
q36756
GraphicsRenderer
train
function GraphicsRenderer(renderer) { ObjectRenderer.call(this, renderer); this.graphicsDataPool = []; this.primitiveShader = null; this.complexPrimitiveShader = null; }
javascript
{ "resource": "" }
q36757
ensureCodeBehind
train
function ensureCodeBehind(code_behind) { if (typeof code_behind === 'undefined') throw "Missing mandatory global variable CODE_BEHIND!"; var i, funcName; for (i = 1; i < arguments.length; i++) { funcName = arguments[i]; if (typeof code_behind[funcName] !== 'function') throw "Expected CODE_BEHIND." + funcName + " to be a function!"; } }
javascript
{ "resource": "" }
q36758
defVal
train
function defVal(target, args, defaultValues) { var key, val; for (key in defaultValues) { val = defaultValues[key]; if (typeof args[key] === 'undefined') { target[key] = val; } else { target[key] = args[key]; } } }
javascript
{ "resource": "" }
q36759
generate
train
function generate(allows) { return function (req, res, next) { req.route.allows = allows; next(); }; }
javascript
{ "resource": "" }
q36760
train
function (plugin, settings) { plugin.ext('onPostHandler', (request, reply) => { let response = request.response; // if the reply is a view add settings data into template system if (response.variety === 'view') { // Added to fix bug that cannot yet be reproduced in test - REVIEW /* $lab:coverage:off$ */ if (!response.source.context) { response.source.context = {}; } /* $lab:coverage:on$ */ // append tags from document request to JSON request if (request.query.tags) { settings.jsonPath = appendQueryString(settings.jsonPath, 'tags', request.query.tags); } else { settings.jsonPath = appendQueryString(settings.jsonPath, null, null); } const prefixedSettings = Hoek.clone(settings); if (plugin.realm.modifiers.route.prefix) { ['jsonPath', 'swaggerUIPath'].forEach((setting) => { prefixedSettings[setting] = plugin.realm.modifiers.route.prefix + prefixedSettings[setting]; }); } const prefix = findAPIKeyPrefix(settings); if (prefix) { prefixedSettings.keyPrefix = prefix; } prefixedSettings.stringified = JSON.stringify(prefixedSettings); response.source.context.hapiSwagger = prefixedSettings; } return reply.continue(); }); }
javascript
{ "resource": "" }
q36761
train
function (url, qsName, qsValue) { let urlObj = Url.parse(url); if (qsName && qsValue) { urlObj.query = Querystring.parse(qsName + '=' + qsValue); urlObj.search = '?' + encodeURIComponent(qsName) + '=' + encodeURIComponent(qsValue); } else { urlObj.search = ''; } return urlObj.format(urlObj); }
javascript
{ "resource": "" }
q36762
train
function (settings) { let out = ''; if (settings.securityDefinitions) { Object.keys(settings.securityDefinitions).forEach((key) => { if (settings.securityDefinitions[key]['x-keyPrefix']) { out = settings.securityDefinitions[key]['x-keyPrefix']; } }); } return out; }
javascript
{ "resource": "" }
q36763
render_path
train
function render_path(path, params) { params = params || {}; return ARRAY( is.array(path) ? path : [path] ).map(function(p) { return p.replace(/:([a-z0-9A-Z\_]+)/g, function(match, key) { if(params[key] === undefined) { return ':'+key; } return ''+fix_object_ids(params[key]); }); }).valueOf(); }
javascript
{ "resource": "" }
q36764
ResourceView
train
function ResourceView(opts) { var view = this; var compute_keys; if(opts && opts.compute_keys) { compute_keys = opts.compute_keys; } var element_keys; if(opts && opts.element_keys) { element_keys = opts.element_keys; } var collection_keys; if(opts && opts.collection_keys) { collection_keys = opts.collection_keys; } var element_post; if(opts && opts.element_post) { element_post = opts.element_post; } var collection_post; if(opts && opts.collection_post) { collection_post = opts.collection_post; } opts = copy(opts || {}); debug.assert(opts).is('object'); debug.assert(opts.path).is('string'); view.opts = {}; view.opts.keys = opts.keys || ['$id', '$type', '$ref']; view.opts.path = opts.path; view.opts.elementPath = opts.elementPath; view.Type = opts.Type; if(is.obj(compute_keys)) { view.compute_keys = compute_keys; } if(is.obj(element_keys)) { view.element_keys = element_keys; } if(is.obj(collection_keys)) { view.collection_keys = collection_keys; } if(is.func(element_post)) { view.element_post = element_post; } if(is.func(collection_post)) { view.collection_post = collection_post; } //debug.log("view.opts = ", view.opts); }
javascript
{ "resource": "" }
q36765
flatten
train
function flatten(list) { return list.reduce(function (acc, item) { if (Array.isArray(item)) { return acc.concat(flatten(item)); } else { return acc.concat(item); } }, []); }
javascript
{ "resource": "" }
q36766
getFile
train
function getFile(group) { while (group) { if (group.file) return group.file group = group.parent } }
javascript
{ "resource": "" }
q36767
getContext
train
function getContext(i) { if (context) { return context } else { const path = getCallsite(i || 2).getFileName() const file = files[path] if (file) return file.group throw Error(`Test module was not loaded properly: "${path}"`) } }
javascript
{ "resource": "" }
q36768
makeHumaniseWare
train
function makeHumaniseWare ({ apiKey, incomingWebhookUrl, logger, getHandoffFromUpdate }) { if (!apiKey || !incomingWebhookUrl) { throw new Error('botmaster-humanise-ware requires at least both of apiKey and incomingWebhookUrl parameters to be defined') } const HUMANISE_URL = incomingWebhookUrl if (!logger) { logger = { log: debug, debug: debug, info: debug, verbose: debug, warn: debug, error: debug } } logger.info(`sending updates to humanise on: ${HUMANISE_URL}`) const incoming = { type: 'incoming', name: 'humanise-wrapped-incoming-ware', controller: async (bot, update) => { bot.sendIsTypingMessageTo(update.sender.id, {ignoreMiddleware: true}).catch(err => logger.error(err)) // a few refinements for messenger specific messages before sending to humanise // will be deprecated in the future if (bot.type === 'messenger') { convertPostbacks(bot, update) convertRefs(bot, update) convertMessengerThumbsup(bot, update) } // updates with no messages are currently not supported. Also, // not sending back messages that come from a potential humanise bot // as would just be re-sending to platform that just sent it if (!update.message || bot.type === 'humanise') { const debugMessage = !update.message ? 'Got an update with no message, not sending it to humanise' : 'Got a user update from humanise, not sending it back to them' logger.verbose(debugMessage) return } // humanise takes in only objects that would be accepted on the various platforms const userInfo = await bot.getUserInfo(update.sender.id) if (getHandoffFromUpdate) { const handoffReason = await getHandoffFromUpdate(update) if (handoffReason) { const handoffTag = `<handoff>${handoffReason}</handoff>` update.message.text ? update.message.text += handoffTag : update.message.text = handoffTag } } const objectToSend = { apiKey, update, senderType: 'user', userInfo } const requestOptions = { method: 'POST', uri: HUMANISE_URL, json: objectToSend } const debugMessage = 'About to send update to humanise' logger.debug(debugMessage) await request(requestOptions) update.senderUserInfo = userInfo } } const outgoing = { type: 'outgoing', name: 'humanise-wrapped-outgoing-ware', controller: async (bot, update, message) => { // skip if there is no message if (!message.message) { return } let userInfo if (update.sender.id === message.recipient.id) { userInfo = update.senderUserInfo } else { // this should never be the case if it is something like an // an automated answer from an AI userInfo = bot.getUserInfo(message.recipient.id) } const objectToSend = { apiKey, update: message, senderType: 'bot', userInfo } const requestOptions = { method: 'POST', uri: HUMANISE_URL, json: objectToSend } await request(requestOptions) // don't send anything. Your webhook should now be doing that return 'cancel' } } const humaniseWare = { incoming, outgoing } return humaniseWare }
javascript
{ "resource": "" }
q36769
checkPort
train
function checkPort(basePort, callback){ return deasync(function(basePort, callback) { portfinder.basePort = basePort; portfinder.getPort(function (err, port) { callback(null, port); }); })(basePort); }
javascript
{ "resource": "" }
q36770
inBlackList
train
function inBlackList(port, additionalPorts) { const blacklist = [4200].concat(additionalPorts || []); return blacklist.indexOf(port) === -1 ? false : true; }
javascript
{ "resource": "" }
q36771
Index
train
function Index(keySize, block) { var reader = new SbonReader(block.buffer); this.level = reader.readUint8(); // Number of keys in this index. this.keyCount = reader.readInt32(); // The blocks that the keys point to. There will be one extra block in the // beginning of this list that points to the block to go to if the key being // searched for is left of the first key in this index. this.blockIds = new Int32Array(this.keyCount + 1); this.blockIds[0] = reader.readInt32(); this.keys = []; // Load all key/block reference pairs. for (var i = 1; i <= this.keyCount; i++) { this.keys.push(reader.readByteString(keySize)); this.blockIds[i] = reader.readInt32(); } }
javascript
{ "resource": "" }
q36772
train
function(className, array) { var len = array.length; for (var i = 0; i < len; i++) { if (array[i].indexOf(className) > -1) { return i; } } return -1; }
javascript
{ "resource": "" }
q36773
train
function(className) { for (var i = 0; i < databaseLen; i++) { if (database["field" + i].regExp.test(className)) { return i; } } return -1; }
javascript
{ "resource": "" }
q36774
train
function(array) { // Run Functions regLoop(); // Functions var addOutputValue = function(objectField, value, property, addon) { var index = objectField.unit.indexOf(property), indexInDatabase, unit; if (addon === "responsive") { indexInDatabase = checkClassExist(property, responsiveArray); if (indexInDatabase === -1) { unit = objectField.unit[index + 1]; responsiveArray.push([property, unit, value]); // If array exist } else if (responsiveArray[indexInDatabase].indexOf(value) === -1) { responsiveArray[indexInDatabase].push(value); } var typedata = checkType(value); if (typedata !== -1) { var field = "field" + typedata; if (!database[field].output) { database[field].output = []; } // grunt.log.writeln(typedata + " " + field + " " + value); } return value; // if (indexInDatabase === -1) { // console.log("Create new responsive: " + property, unit, value); // unit = objectField.unit[index + 1]; // responsiveArray.push([property, unit, value]); // // If array exist // } else if (responsiveArray[indexInDatabase].indexOf(value) === -1) { // console.log("Add value to database " + value); // responsiveArray[indexInDatabase].push(value); // } // console.log("Create new responsive: " + property, unit, value); // return value; } else { indexInDatabase = checkClassExist(property, objectField.output); if (indexInDatabase === -1) { unit = objectField.unit[index + 1]; objectField.output.push([property, unit, value]); // If array exist } else if (objectField.output[indexInDatabase].indexOf(value) === -1) { objectField.output[indexInDatabase].push(value); } } }; var classProcess = function(name) { var typedata = checkType(name); if (typedata !== -1) { var field = "field" + typedata; if (!database[field].output) { database[field].output = []; } var checkInField = database[field], indexDash = name.indexOf(checkInField.gap), property = name.slice(0, indexDash), value = name.slice(indexDash + 1, name.length), addon = false; if (!database[field].output) { database[field].output = []; } // Check if have addon property - "responsive" if (database[field].addon === "responsive") { addon = addOutputValue(database[field], value, property, "responsive"); } // If don't have addon property else { addon = addOutputValue(database[field], value, property); } if (addon) { classProcess(addon); } } else { return false; } }; // Variables var output = [], len = array.length; // Loop for (var i = 0; i < len; i++) { classProcess(array[i]); } return output; }
javascript
{ "resource": "" }
q36775
entry
train
function entry(name = '') { return path.normalize(path.join(sourceDir, config.entriesDir, name ? `${name}.js` : '')); }
javascript
{ "resource": "" }
q36776
train
function(name, factory, object) { var that = this; var objects = this._resolveObjects(name, factory, object); _.each(objects, function(factoryObjects, factory) { _.each(factoryObjects, function(object, name) { that._setObjectCreator([name], that._createObjectCreator(factory, object)); }); }); return this; }
javascript
{ "resource": "" }
q36777
train
function(name) { this._checkObject(name); if (!this._hasObject([name])) { this._setObject([name], this._getObjectCreator([name]).call())._removeObjectCreator([name]); } return this._getObject([name]); }
javascript
{ "resource": "" }
q36778
train
function(name) { this._checkObject(name); return (this._hasObject([name]) && this._removeObject([name])) || (this._hasObjectCreator([name]) && this._removeObjectCreator([name])); }
javascript
{ "resource": "" }
q36779
train
function(name, factory) { if (_.isUndefined(factory)) { factory = name; name = undefined; } if (factory && factory.__clazz && factory.__clazz.__isSubclazzOf('/InjectorJS/Factories/Abstract')) { return this.__setPropertyValue(['factory', factory.getName()], factory); } var fields = _.isString(name) ? name.split('.') : name || []; return this.__setPropertyValue(['factory'].concat(fields), factory); }
javascript
{ "resource": "" }
q36780
train
function(factory) { var factoryName = _.isString(factory) ? factory : factory.getName(); return this.__hasPropertyValue(['factory', factoryName]); }
javascript
{ "resource": "" }
q36781
train
function(name, factory, object) { var that = this; var objects = {}; var defaultFactory = this.getDefaultFactory().getName(); if (_.isObject(name)) { objects = name; } else { if (_.isUndefined(object)) { object = factory; factory = undefined; } if (_.isUndefined(factory)) { factory = defaultFactory; } objects[factory] = {}; objects[factory][name] = object; } _.each(objects, function(factoryObjects, factory) { if (!that.hasFactory(factory)) { if (!(defaultFactory in objects)) { objects[defaultFactory] = {}; } objects[defaultFactory][factory] = factoryObjects; delete objects[factory]; } }); return objects; }
javascript
{ "resource": "" }
q36782
train
function(factoryName, object) { if (_.isUndefined(object)) { object = factoryName; factoryName = undefined; } var that = this; return function() { var factory = !_.isUndefined(factoryName) ? that.getFactory(factoryName) : that.getDefaultFactory(); var params = _.isFunction(object) ? object.call(that) : object; return _.isFunction(factory) ? factory(params) : factory.create(params); } }
javascript
{ "resource": "" }
q36783
train
function(value, metaData, name, object) { name = name || 'unknown'; object = object || this; var that = this; var processors = this.getProcessor(); _.each(metaData, function(data, option) { if (!(option in processors)) { return; } value = processors[option].call(that, value, data, name, object); }); return value; }
javascript
{ "resource": "" }
q36784
train
function(params) { var that = this; var paramsDefinition = this.getParamsDefinition(); var parameterProcessor = this.getParameterProcessor(); _.each(params, function(value, param) { if (!(param in paramsDefinition)) { throw new Error('Parameter "' + param + '" does not defined!'); } params[param] = parameterProcessor.process(value, paramsDefinition[param], param, that); }); return params; }
javascript
{ "resource": "" }
q36785
train
function(params) { var clazz = this.getClazz(); return clazz(params.name, params.parent, params.deps) }
javascript
{ "resource": "" }
q36786
train
function(params) { // Create '_createService' function for this purpose for parameters applying to clazz constructor. var service = this._createService(params.class, params.init); _.each(params.call, function(params, method) { service[method].apply(service, params); }); return service; }
javascript
{ "resource": "" }
q36787
train
function(collection, options, cb) { this.store().setItem( options.indexKey, JSON.stringify([]), function(err, res) { cb(err, [], res); } ); }
javascript
{ "resource": "" }
q36788
train
function(collection, options, cb) { var ids = []; var keys = _.isFunction(collection.url) ? collection.url() : collection.url; keys += options.keys; debug('findKeys', keys); this.store().getItem(keys, function(err, data) { if (data) ids.push(keys); cb(null, ids); }); }
javascript
{ "resource": "" }
q36789
Cell
train
function Cell(north, east, south, west) { this._north = north; this._east = east; this._south = south; this._west = west; }
javascript
{ "resource": "" }
q36790
Maze
train
function Maze(width, height) { if (width < 0 || height < 0) throw new Error('invalid size: ' + width + 'x' + height); this._width = width; this._height = height; this._blockWidth = ((width+1)+15) >> 4; this._grid = new Array(this._blockWidth * (height + 1)); for (var i = 0; i < this._blockWidth * (height + 1); i ++) this._grid[i] = 0; }
javascript
{ "resource": "" }
q36791
dropEnvironmentDatabase
train
function dropEnvironmentDatabase(domain, env, next) { _getEnvironmentDatabase({ domain: domain, environment: env }, function (err, found) { if (err) { return next(common.buildErrorObject({ err: err, msg: 'Failed to get environment', httpCode: 500 })); } if (!found) { log.logger.info("no environment db for " + env + " moving on"); return next(); } found.dropDb(config.getConfig(), function dropped(err) { if (err) { log.logger.error('Failed to delete model'); return next(common.buildErrorObject({ err: err, msg: 'Failed to drop environment db', httpCode: 500 })); } found.remove(next); }); }); }
javascript
{ "resource": "" }
q36792
getOrCreateEnvironmentDatabase
train
function getOrCreateEnvironmentDatabase(req, res, next){ var models = mbaas.getModels(); log.logger.debug('process getOrCreateEnvironmentDatabase request', req.originalUrl , req.body, req.method, req.params); var domain = req.params.domain; var env = req.params.environment; log.logger.debug('process db create request', {domain: domain, env: env} ); _getEnvironmentDatabase({ domain: domain, environment: env }, function(err, found){ if(err){ return next(common.buildErrorObject({ err: err, msg: 'Failed to get mbaas instance', httpCode: 500 })); } log.logger.debug('process db create request AFTER', {domain: domain, env: env} ); if(found){ req.mongoUrl = common.formatDbUri(found.dbConf); return next(); } else { // because of the composite unique index on the collection, only the first creation call will succeed. // NB the req.params should have the mongo.host and mongo.port set !! var cfg = config.getConfig(); models.Mbaas.createModel(domain, env, cfg, function(err, created){ if(err){ return next(common.buildErrorObject({ err: err, msg: 'Failed to create mbaas instance', httpCode: 500 })); } created.createDb(cfg, function(err, dbConf){ if(err){ log.logger.error('Failed to create db, delete model'); created.remove(function(removeErr){ if(removeErr){ log.logger.error(removeErr, 'Failed to remove model'); } return next(common.buildErrorObject({ err: err, msg: 'Failed to create db for domain ' + domain + ' and env ' + env, httpCode: 500 })); }); } else { req.mongoUrl = common.formatDbUri(dbConf); next(); } }); }); } }); }
javascript
{ "resource": "" }
q36793
getEnvironmentDatabase
train
function getEnvironmentDatabase(req, res, next){ log.logger.debug('process getEnvironmentDatabase request', req.originalUrl ); _getEnvironmentDatabase({ domain: req.params.domain, environment: req.params.environment }, function(err, envDb){ if(err){ log.logger.error('Failed to get mbaas instance', err); return next(common.buildErrorObject({ err: err, msg: 'Failed to get mbaas instance', httpCode: 500 })); } if(!envDb){ log.logger.error("No Environment Database Found", err); return next(common.buildErrorObject({ err: new Error("No Environment Database Found"), httpCode: 400 })); } req.mongoUrl = common.formatDbUri(envDb.dbConf); log.logger.debug("Found Environment Database", req.mongoUrl); return next(); }); }
javascript
{ "resource": "" }
q36794
getMedia
train
function getMedia (hostname) { const patterns = { abc: /abc\.es/, ara: /ara\.cat/, elconfidencial: /elconfidencial\.com/, eldiario: /eldiario\.es/, elespanol: /elespanol\.com/, elmundo: /elmundo\.es/, elpais: /elpais\.com/, elperiodico: /elperiodico\.com/, esdiario: /esdiario\.com/, europapress: /europapress\.es/, huffingtonpost: /huffingtonpost\.es/, lainformacion: /lainformacion\.com/, larazon: /larazon\.es/, lavanguardia: /lavanguardia\.com/, lavozdegalicia: /lavozdegalicia\.es/, libertaddigital: /libertaddigital\.com/, okdiario: /okdiario\.com/, publico: /publico\.es/ } for (const id in patterns) { if (patterns[id].test(hostname)) { return id } } return null }
javascript
{ "resource": "" }
q36795
delta
train
function delta(a) { return lgamma(a) - (a - 0.5) * Math.log(a) + a - 0.5 * Math.log(2 * Math.PI); }
javascript
{ "resource": "" }
q36796
findx0SmallA
train
function findx0SmallA(a, p, q) { var B, u, temp; B = q * gamma(a); if (B > 0.6 || B >= 0.45 && a >= 0.3) { // use 21 u = B * q > 1e-8 ? Math.pow(p * gamma(a + 1), 1 / a) : Math.exp(-q / a - eulerGamma); return u / (1 - u / (a + 1)); } if (a < 0.3 && B >= 0.35 && B <= 0.6) { // use 22 temp = Math.exp(-eulerGamma - B); u = temp * Math.exp(temp); return temp * Math.exp(u); } temp = -Math.log(B); u = temp - (1 - a) * Math.log(temp); if (B >= 0.15) { // use 23, with temp for y and u for v return temp - (1 - a) * Math.log(u) - Math.log(1 + (1 - a) / (1 + u)); } if (B > 0.01) { // use 24, with temp for y and u for v return temp - (1 - a) * Math.log(u) - Math.log( (u * u + 2 * (3 - a) * u + (2 - a) * (3 - a)) / (u * u + (5 - a) * u + 2)); } // use 25, where c1 + ... + c5/y^4 is treated as a polynomial in y^-1 // using u for c1, temp for y return findx0TinyB(a, temp); }
javascript
{ "resource": "" }
q36797
f
train
function f(x, n) { return Math.exp((logpg + x - Math.log(series(snTerm(x), n + 1))) / a); }
javascript
{ "resource": "" }
q36798
step
train
function step(x, a, p, q) { var temp, w; temp = p <= 0.5 ? gratio(a)(x) - p : q - gratioc(a)(x); temp /= r(a, x); w = (a - 1 - x) / 2; if (Math.max(Math.abs(temp), Math.abs(w * temp)) <= 0.1) { return x * (1 - (temp + w * temp * temp)); } return x * (1 - temp); }
javascript
{ "resource": "" }
q36799
decojs
train
function decojs(str) { var i , curChar, nextChar, lastNoSpaceChar , inString = false , inComment = false , inRegex = false , onlyComment = false , newStr = '' , curLine = '' , keepLineFeed = false // Keep a line feed after comment , stringOpenWith ; for (i = 0; i < str.length; ++i) { curChar = str.charAt(i); nextChar = str.charAt(i + 1); curLine = curLine + '' + curChar; // In string switcher if ( !inRegex && !inComment && (curChar === '"' || curChar === "'") && ( (str.charAt(i - 1) !== '\\') || (str.charAt(i - 2) + str.charAt(i - 1) == '\\\\') ) ) { if(inString && (curChar === stringOpenWith)) { inString = false; stringOpenWith = null; } else if(!inString) { inString = true; stringOpenWith = curChar; } } // In regex switcher if((!inComment && !inString) && (curChar === '/')) { if(inRegex // Not escaped ... /myregexp\/...../ && (str.charAt(i - 1) !== '\\') // Or escape char, previously escaped /myregexp\\/ || ((str.charAt(i - 1) === '\\') && (str.charAt(i - 2) === '\\'))) { inRegex = false; } else { if(~['=',',','('].indexOf(lastNoSpaceChar)) { inRegex = true; } } } if(!~['', ' '].indexOf(curChar)) { lastNoSpaceChar = curChar; } // we are not inside of a string or a regex if (!inString && !inRegex) { // Reset current line: if(curChar == '\n') { curLine = ''; if(inComment === 2) { keepLineFeed = true; } } // singleline comment start if (!inComment && curChar + nextChar === '/'+'/') { ++i; inComment = 1; keepLineFeed = (curLine.slice(0,-1).trim() != ''); // singleline comment end } else if (inComment === 1 && curChar === '\n') { inComment = false; curChar = keepLineFeed ? '\n' : ''; // multiline comment start } else if (!inComment && curChar + nextChar === '/'+'*') { ++i; inComment = 2; curChar = ''; // multiline comment end } else if (inComment === 2 && curChar + nextChar === '*'+'/') { ++i; inComment = false; curChar = keepLineFeed ? '\n' : ''; } if (inComment === 2 && curChar === '\n') { curChar = ''; } else if (inComment) { curChar = ''; } } newStr += curChar; } return newStr; }
javascript
{ "resource": "" }