_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q38300
train
function () { let date = new Date(); let result = {}; let regex = /(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d).\d\d\dZ/g; let current = regex.exec(date.toJSON()); if (current === null || current.length < 7) { return null; } for (let i = 0; i < 6; i++) { //The first element ...
javascript
{ "resource": "" }
q38301
generateDocs
train
function generateDocs(specjs) { var docs = GENERATE_MODULE(specjs.MODULE); docs = _.reduce(specjs.METHODS, function(memo, methodSpec, methodName) { return memo += GENERATE_METHOD(methodName, methodSpec); }, docs); docs = _.reduce(specjs.ENUMS, function(memo, enumSpec, enumName) { return memo += GENERATE...
javascript
{ "resource": "" }
q38302
train
function(buffer){ //Deserialize binary data into a JSON object var data = micro.toJSON(buffer); var type = data._type; delete data._type; switch (type) { case "Ping" : ...
javascript
{ "resource": "" }
q38303
train
function(data){ data = data || {timestamps:[]}; data.timestamps.push(new Date().getTime()); send(connection, "Ping", data); }
javascript
{ "resource": "" }
q38304
send
train
function send(conn,schemaName,json,byteLength){ var buffer = micro.toBinary(json, schemaName,byteLength); if (FAKE_LATENCY){ setTimeout(function(){ conn.sendBytes(buffer); },FAKE_LATENCY); }else{ conn.sendBytes(buffer); } }
javascript
{ "resource": "" }
q38305
calculateLatency
train
function calculateLatency(timestamps){ var length = timestamps.length, sumLatency = 0; for (var i = 1; i < length; i++){ sumLatency += (timestamps[i] - timestamps[i-1])/2; } return (sumLatency/(length-1)); }
javascript
{ "resource": "" }
q38306
eat
train
function eat(stream, callback) { if (!stream instanceof Stream) { throw 'eat() accepts Stream only!'; } this.callback = callback; this.consumer = new TapConsumer(); this.report = { pass: false, skip: false, fail: false, total: false, failures: [], text: '' }; // setup events this....
javascript
{ "resource": "" }
q38307
init
train
function init(ctx) { var container = ctx.container; // reactors can be initialized without a promise since just attaching event handlers initReactors(container); // adapters and services may be making database calls, so do with promises return initAdapters(container) ...
javascript
{ "resource": "" }
q38308
reactHandler
train
function reactHandler(reactData) { return function (eventData) { // handler should always be run asynchronously setTimeout(function () { var payload = eventData.payload; var inputData = payload.inputData; var reactor = reactors[reactData.t...
javascript
{ "resource": "" }
q38309
initReactors
train
function initReactors(container) { var isBatch = container === 'batch'; // loop through each reactor and call init if it exists _.each(reactors, function (reactor) { if (reactor.init) { reactor.init({ config: config, pancakes: pancakes }); } }); ...
javascript
{ "resource": "" }
q38310
initAdapters
train
function initAdapters(container) { var calls = []; if (container === 'webserver') { _.each(adapters, function (adapter) { if (adapter.webInit) { calls.push(adapter.webInit); } }); } else { _.each(ad...
javascript
{ "resource": "" }
q38311
train
function() { var args = [].slice.call(arguments, 0); var workerMessage, done = 0; var workerKeys = Object.keys(cluster.workers); var nextWorker = function() { if (workerKeys.length) { done++; cluster.workers[workerKeys.shift()].send(taskMessage.concat([a...
javascript
{ "resource": "" }
q38312
buildPartialView
train
function buildPartialView(path) { var self = this; var layoutPrefix = /^layout_/; var p = pathModule.basename(path); var pos = p.indexOf('.'); var ext = p.slice(pos+1); if (ext in this.enginesByExtension) { var engine = this.enginesByExtension[ext]; var func = engine.renderPartial(path)...
javascript
{ "resource": "" }
q38313
getDriverInstance
train
function getDriverInstance(driver, config) { if (!(driver in protos.drivers)) throw new Error(util.format("The '%s' driver is not loaded. Load it with app.loadDrivers('%s')", driver, driver)); return new protos.drivers[driver](config || {}); }
javascript
{ "resource": "" }
q38314
getStorageInstance
train
function getStorageInstance(storage, config) { if (!(storage in protos.storages)) throw new Error(util.format("The '%s' storage is not loaded. Load it with app.loadStorages('%s')", storage, storage)); return new protos.storages[storage](config || {}); }
javascript
{ "resource": "" }
q38315
loadControllers
train
function loadControllers() { // Note: runs on app context // Get controllers/ var cpath = this.mvcpath + 'controllers/', files = protos.util.getFiles(cpath); // Create controllers and attach to app var controllerCtor = protos.lib.controller; for (var controller, key, file, instance, className, ...
javascript
{ "resource": "" }
q38316
processControllerHandlers
train
function processControllerHandlers() { var self = this; var jsFile = this.regex.jsFile; var handlersPath = this.mvcpath + 'handlers'; var relPath = self.relPath(this.mvcpath) + 'handlers'; if (fs.existsSync(handlersPath)) { fs.readdirSync(handlersPath).forEach(function(dirname) { var dir = h...
javascript
{ "resource": "" }
q38317
parseConfig
train
function parseConfig() { // Get main config var p = this.path + '/config/', files = protos.util.getFiles(p), mainPos = files.indexOf('base.js'), jsExt = protos.regex.jsFile, configFile = this.path + '/config.js'; // If config.js is not present, use the one from skeleton to provide defa...
javascript
{ "resource": "" }
q38318
watchPartial
train
function watchPartial(path, callback) { // Don't watch partials again when reloading if (this.watchPartials && RELOADING === false) { var self = this; self.debug('Watching Partial for changes: %s', self.relPath(path, 'app/views')); var watcher = chokidar.watch(path, {interval: self.confi...
javascript
{ "resource": "" }
q38319
parseDriverConfig
train
function parseDriverConfig() { var cfg, def, x, y, z, config = this.config.drivers, drivers = this.drivers; if (!config) config = this.config.drivers = {}; if (Object.keys(config).length === 0) return; for (x in config) { cfg = config[x]; if (x == 'default') { def = cfg; continue; } ...
javascript
{ "resource": "" }
q38320
parseStorageConfig
train
function parseStorageConfig() { var cfg, x, y, z, config = this.config.storages, storages = this.storages; if (!config) config = this.config.storages = {}; if (Object.keys(config).length === 0) return; for (x in config) { cfg = config[x]; for (y in cfg) { if (typeof cfg[y] == ...
javascript
{ "resource": "" }
q38321
loadAPI
train
function loadAPI() { var apiPath = this.fullPath(this.paths.api); if (fs.existsSync(apiPath) && fs.statSync(apiPath).isDirectory()) { var files = protos.util.ls(apiPath, this.regex.jsFile); files.forEach(function(file) { var methods = protos.require(apiPath + "/" + file, true); // Don't use module cac...
javascript
{ "resource": "" }
q38322
loadHooks
train
function loadHooks() { var events = this._events; var jsFile = /\.js$/i; var hooksPath = this.fullPath('hook'); var loadedHooks = []; if (fs.existsSync(hooksPath)) { var files = protos.util.ls(hooksPath, jsFile); for (var cb,idx,evt,file,len=files.length,i=0; i < len; i++) { file = files[i]; ...
javascript
{ "resource": "" }
q38323
loadEngines
train
function loadEngines() { // Initialize engine properties this.enginesByExtension = {}; // Engine local variables var exts = []; var loadedEngines = this.loadedEngines = Object.keys(protos.engines); if (loadedEngines.length > 0) { // Get view engines var engine, instance, engineProps = ...
javascript
{ "resource": "" }
q38324
buildTemplatePartial
train
function buildTemplatePartial(path) { var tplDir = app.mvcpath + app.paths.templates; var p = path.replace(tplDir, ''); var pos = p.indexOf('.'); var ext = p.slice(pos+1); var tpl = p.slice(0,pos); if (ext in this.enginesByExtension) { var engine = this.enginesByExtension[ext]; var func = e...
javascript
{ "resource": "" }
q38325
setupViewPartials
train
function setupViewPartials() { // Set view path association object this.views.pathAsoc = {}; // Partial & template regexes var self = this; var exts = this.templateExtensions; var partialRegex = new RegExp('\/views\/(.+)\/partials\/[a-zA-Z0-9-_]+\\.(' + exts.join('|') + ')$'); var templateRegex = new ...
javascript
{ "resource": "" }
q38326
createControllerFunction
train
function createControllerFunction(func) { var Handlebars = protos.require('handlebars'); var context, newFunc, compile, source, funcSrc = func.toString(); var code = funcSrc .trim() .replace(/^function\s+(.*?)(\s+)?\{(\s+)?/, '') .replace(/(\s+)?\}$/, ''); // Get source file path var...
javascript
{ "resource": "" }
q38327
percentile
train
function percentile(array, k) { var length = array.length; if (length === 0) { return 0; } if (typeof k !== 'number') { throw new TypeError('k must be a number'); } if (k <= 0) { return array[0]; } if (k >= 1) { return array[length - 1]; } array.sort(function (a, b) { return...
javascript
{ "resource": "" }
q38328
mergeObject
train
function mergeObject (oldObject, newObject) { let oldCopy = Object.assign({}, oldObject) function _merge (oo, no) { for (let key in no) { if (key in oo) { // Follow structure of oo if (oo[key] === Object(oo[key])) { _merge(oo[key], no[key]) } else if (no[key] !== Object(...
javascript
{ "resource": "" }
q38329
connect
train
function connect(mongodbUri, callback) { snapdb.connect(mongodbUri, function(err, client) { if (err) return callback(err); callback(null, client); }); }
javascript
{ "resource": "" }
q38330
findStoresInZip
train
function findStoresInZip(address, callback) { geo.geocode(address, function(err, georesult) { if (err) return callback(err); snapdb.findStoresInZip(georesult.zip5, function(err, stores) { if (err) return callback(err); georesult.stores = stores; return callback(null, georesult); }); }...
javascript
{ "resource": "" }
q38331
sortStoresByDistance
train
function sortStoresByDistance(location, stores) { var i, s; for (i = 0; i < stores.length; i++) { s = stores[i]; s.distance = geo.getDistanceInMiles(location, { lat:s.latitude, lng:s.longitude }); } stores.sort(function(a,b) { return a.distance - b.distance; }); return stores; }
javascript
{ "resource": "" }
q38332
setup
train
function setup(subject) { context.subject = subject; context.subjectType = null; context.subjectConstructor = null; context.isSet = false; }
javascript
{ "resource": "" }
q38333
rejectFields
train
function rejectFields(result, fields) { // If result is an array, then rejection rules are applied to each array entry if (_.isArray(result)) { return _.map(result, (single_entry) => _.omit(single_entry, fields)); } return _.omit(result, fields); }
javascript
{ "resource": "" }
q38334
stringDiff
train
function stringDiff(existing, proposed, method) { method = method || 'diffJson'; lazy.diff[method](existing, proposed).forEach(function (res) { var color = utils.gray; if (res.added) color = utils.green; if (res.removed) color = utils.red; process.stdout.write(color(res.value)); }); console.log(...
javascript
{ "resource": "" }
q38335
ask
train
function ask(file, opts, cb) { if (typeof opts === 'function') { cb = opts; opts = {}; } opts = opts || {}; var prompt = lazy.inquirer.createPromptModule(); var fp = path.relative(process.cwd(), file.path); var questions = { name: 'action', type: 'expand', message: 'Overwrite `' + fp + ...
javascript
{ "resource": "" }
q38336
splitEscaped
train
function splitEscaped(src, separator) { let escapeFlag = false, token = '', result = []; src.split('').forEach(letter => { if (escapeFlag) { token += letter; escapeFlag = false; } else if (letter === '\\') { escapeFlag = true; } else if...
javascript
{ "resource": "" }
q38337
combineMultiLines
train
function combineMultiLines(lines) { return lines.reduce((acc, cur) => { const line = acc[acc.length - 1]; if (acc.length && isLineContinued(line)) { acc[acc.length - 1] = line.replace(/\\$/, ''); acc[acc.length - 1] += cur; } else { acc.push(cur); ...
javascript
{ "resource": "" }
q38338
createDb
train
function createDb(config, dbUser, dbUserPass, dbName, cb) { log.logger.trace({user: dbUser, pwd: dbUserPass, name: dbName}, 'creating new datatbase'); var url = config.mongoUrl; var admin = config.mongo.admin_auth.user; var admin_pass = config.mongo.admin_auth.pass; MongoClient.connect(url, function(err, db)...
javascript
{ "resource": "" }
q38339
dropDb
train
function dropDb(config, dbUser, dbName, cb){ log.logger.trace({user: dbUser, name: dbName}, 'drop database'); var url = config.mongoUrl; var admin = config.mongo.admin_auth.user; var admin_pass = config.mongo.admin_auth.pass; MongoClient.connect(url, function(err, dbObj){ if (err) return handleError(n...
javascript
{ "resource": "" }
q38340
throwIfIsPrimitive
train
function throwIfIsPrimitive(inputArg) { var type = typeof inputArg; if (type === 'undefined' || inputArg === null || type === 'boolean' || type === 'string' || type === 'number') { throw new CTypeError('called on non-object: ' + typeof inputArg); } return inputArg; }
javascript
{ "resource": "" }
q38341
isFunctionBasic
train
function isFunctionBasic(inputArg) { var isFn = toClass(inputArg) === classFunction, type; if (!isFn && inputArg !== null) { type = typeof inputArg; if ((type === 'function' || type === 'object') && ('constructor' in inputA...
javascript
{ "resource": "" }
q38342
copyRegExp
train
function copyRegExp(regExpArg, options) { var flags; if (!isPlainObject(options)) { options = {}; } // Get native flags in use flags = onlyCoercibleToString(pExec.call(getNativeFlags, $toString(regExpArg))[1]); if (options.add) { ...
javascript
{ "resource": "" }
q38343
stringRepeatRep
train
function stringRepeatRep(s, times) { var half, val; if (times < 1) { val = ''; } else if (times % 2) { val = stringRepeatRep(s, times - 1) + s; } else { half = stringRepeatRep...
javascript
{ "resource": "" }
q38344
checkV8StrictBug
train
function checkV8StrictBug(fn) { var hasV8StrictBug = false; if (isStrictMode) { fn.call([1], function () { hasV8StrictBug = this !== null && typeof this === 'object'; }, 'foo'); } return hasV8StrictBug; }
javascript
{ "resource": "" }
q38345
defaultComparison
train
function defaultComparison(left, right) { var leftS = $toString(left), rightS = $toString(right), val = 1; if (leftS === rightS) { val = +0; } else if (leftS < rightS) { val = -1; } return val; }
javascript
{ "resource": "" }
q38346
sortCompare
train
function sortCompare(left, right) { var hasj = $hasOwn(left, 0), hask = $hasOwn(right, 0), typex, typey, val; if (!hasj && !hask) { val = +0; } else if (!hasj) { val = 1; } else if (!hask) { val = -1; ...
javascript
{ "resource": "" }
q38347
merge
train
function merge(left, right, comparison) { var result = [], next = 0, sComp; result.length = left.length + right.length; while (left.length && right.length) { sComp = sortCompare(left, right); if (typeof sComp !== 'number') { if (co...
javascript
{ "resource": "" }
q38348
mergeSort
train
function mergeSort(array, comparefn) { var length = array.length, middle, front, back, val; if (length < 2) { val = $slice(array); } else { middle = ceil(length / 2); front = $slice(array, 0, middle); ...
javascript
{ "resource": "" }
q38349
plugin
train
function plugin(options) { options = normalize(options); return function(files, metalsmith, done) { var tbConvertedFiles = _.filter(Object.keys(files), function(file) { return minimatch(file, options.match); }); var convertFns = _.map(tbConvertedFiles, function(file) { debug("Asyncly conve...
javascript
{ "resource": "" }
q38350
invertPalette
train
function invertPalette(palette) { return _extends({}, palette, { base03: palette.base3, base02: palette.base2, base01: palette.base1, base00: palette.base0, base0: palette.base00, base1: palette.base01, base2: palett...
javascript
{ "resource": "" }
q38351
train
function(url, dest, cb) { var get = request(url); get.on('response', function (res) { res.pipe(fs.createWriteStream(dest)); res.on('end', function () { cb(); }); res.on('error', function (err) { cb(err); }); }); }
javascript
{ "resource": "" }
q38352
changelog
train
function changelog(tagsList, prevTag, repoUrl, repoName) { const writeLogFiles = []; let logIndex; let logDetailed; let logContent; let link; let prevTagHolder = prevTag; Object.keys(tagsList).forEach(majorVersion => { logIndex = []; logDetailed = []; logContent = [ `\n# ${repoName} ${m...
javascript
{ "resource": "" }
q38353
Client
train
function Client(socket, options) { options = options || {}; // hook up subcommand nested properties var cmd, sub, method; for(cmd in SubCommand) { // we have defined the cluster slots subcommand // but the cluster command is not returned in the // command list, ignore this for the moment if(!th...
javascript
{ "resource": "" }
q38354
execute
train
function execute(cmd, args, cb) { if(typeof args === 'function') { cb = args; args = null; } var arr = [cmd].concat(args || []); if(typeof cb === 'function') { this.once('reply', cb); } // sending over tcp if(this.tcp) { this.encoder.write(arr); // connected to a server within this proc...
javascript
{ "resource": "" }
q38355
multi
train
function multi(cb) { // not chainable with a callback if(typeof cb === 'function') { return this.execute(Constants.MAP.multi.name, [], cb); } // chainable instance return new Multi(this); }
javascript
{ "resource": "" }
q38356
_data
train
function _data(data) { if(this.tcp) { this.decoder.write(data); // connected to an in-process server, // emit the reply from the server socket }else{ if(data instanceof Error) { this.emit('reply', data, null); }else{ this.emit('reply', null, data); } } }
javascript
{ "resource": "" }
q38357
create
train
function create(sock, options) { var socket; if(!sock) { sock = {port: PORT, host: HOST}; } if(typeof sock.createConnection === 'function') { socket = sock.createConnection(); }else{ socket = net.createConnection(sock); } return new Client(socket, options); }
javascript
{ "resource": "" }
q38358
buildRoutes
train
function buildRoutes(router, apiOrBuilder) { // if it's a builder function, build it... let pathPrefix = null; let api = null; let registry = null; let instanceName = null; if (_.isObject(apiOrBuilder)) { pathPrefix = apiOrBuilder.path; api = apiOrBuilder.api; registry = ...
javascript
{ "resource": "" }
q38359
mapMongoAlertsToResponseObj
train
function mapMongoAlertsToResponseObj(alerts){ // Base response, regardless of whether we have alerts or not var res = {"list":[],"status":"ok"}; // Filter and add alerts to response if we have them if (alerts){ res.list = _.map(alerts, function(alert){ var al = alert.toJSON(); al.guid = alert....
javascript
{ "resource": "" }
q38360
mapMongoNotificationsToResponseObj
train
function mapMongoNotificationsToResponseObj(notifications){ // Base response, regardless of whether we have alerts or not var res = {"list":[],"status":"ok"}; // Filter and add alerts to response if we have them if (notifications){ res.list = _.map(notifications, function(notification){ return notif...
javascript
{ "resource": "" }
q38361
mapMongoEventsToResponseObj
train
function mapMongoEventsToResponseObj(events){ // Base response, regardless of whether we have alerts or not var res = {"list":[],"status":"ok"}; // Filter and add alerts to response if we have them if (events){ res.list = _.map(events, function(event){ var ev = event.toJSON(); ev.message = ...
javascript
{ "resource": "" }
q38362
createListener
train
function createListener(virtualPath) { return function listener(req, res, next) { var paths = allPaths[virtualPath].slice(); function processRequest(paths) { var physicalPath = paths.pop() , synchronizer = new Synchronizer() , uri = urlParser.parse(req.url).pathname , filename...
javascript
{ "resource": "" }
q38363
train
function(error, verbose) { var message = ""; //Some errors have a base error (in case of ElevatorError for example) while(error) { message += (verbose === true && error.stack) ? error.stack : error.message; error = error.baseError; if(error) { message += "\r\n"...
javascript
{ "resource": "" }
q38364
camelCase
train
function camelCase(str, delim) { var delims = delim || ['_', '.', '-']; if (!_.isArray(delims)) { delims = [delims]; } _.each(delims, function (adelim) { var codeParts = str.split(adelim); var i, codePart; for (i = 1; i < codeParts.lengt...
javascript
{ "resource": "" }
q38365
buildConfig
train
async function buildConfig(file) { const { default: config } = await import(`${CONFIGS_PATH}/${file}`); const { creator, name, packageName } = config; creator .then((data) => { const stringifiedData = JSON.stringify(data); const generatedData = TEMPLATE.replace(/{{ data }}/, stringifiedData); ...
javascript
{ "resource": "" }
q38366
Mesh
train
function Mesh(texture, vertices, uvs, indices, drawMode) { core.Container.call(this); /** * The texture of the Mesh * * @member {Texture} */ this.texture = texture; /** * The Uvs of the Mesh * * @member {Float32Array} */ this.uvs = uvs || new Float32Array([0...
javascript
{ "resource": "" }
q38367
train
function (opts) { this.isAppError = true; this.code = opts.code; this.message = this.msg = opts.msg; this.type = opts.type; this.err = opts.err; this.stack = (new Error(opts.msg)).stack; }
javascript
{ "resource": "" }
q38368
onDelayed
train
function onDelayed(delay, throttle, eventNames, selector, listener) { if (typeof throttle !== 'boolean') { listener = selector; selector = eventNames; eventNames = throttle; throttle = false; } if (typeof selector === 'function') { listener = selector; select...
javascript
{ "resource": "" }
q38369
get
train
function get(ignored, cb) { assert(this.$session); const ugRequest = { userId: this.$session.userId, }; this.syscall('UserManager', 'get', ugRequest, (err, userInfo, curVersion) => { if (err) return cb(err); // Strip security-sensitive information. delete userInfo.hashedPassword; _.forEach(...
javascript
{ "resource": "" }
q38370
safeExec
train
function safeExec(command, options) { const result = exec(command, options); if (result.code !== 0) { exit(result.code); return null; } return result; }
javascript
{ "resource": "" }
q38371
deploy
train
function deploy({ containerName, containerRepository, clusterName, serviceName, accessKeyId, secretAccessKey, region = 'us-west-2', }) { AWS.config.update({ accessKeyId, secretAccessKey, region }); cd('C:\\Users\\janic\\Developer\\pikapik\\th3rdwave-api'); const commitSHA = env.CIRCLE_SHA1 || safeEx...
javascript
{ "resource": "" }
q38372
train
function (src, dest, content, fileObject) { var files = {}; _.each(content, function (v, k) { var file = fileObject.orig.dest + '/' + k + '.json'; files[file] = JSON.stringify(v); }); return files; }
javascript
{ "resource": "" }
q38373
RandomStream
train
function RandomStream(options) { if (!(this instanceof RandomStream)) { return new RandomStream(options); } this._options = merge(Object.create(RandomStream.DEFAULTS), options); assert(typeof this._options.length === 'number', 'Invalid length supplied'); assert(typeof this._options.size === 'number', 'I...
javascript
{ "resource": "" }
q38374
psec
train
function psec(name, run) { const test = { name, run, before: null, after: null } ctx.tests.push(test) ctx.run() return { beforeEach(fn) { test.before = fn return this }, afterEach(fn) { test.after = fn return this }, } }
javascript
{ "resource": "" }
q38375
flush
train
function flush() { if (queue.length) { let bench = queue[0] process.nextTick(() => { run(bench).then(() => { queue.shift() flush() }, console.error) }) } }
javascript
{ "resource": "" }
q38376
run
train
async function run(bench) { let { tests, config } = bench if (tests.length == 0) { throw Error('Benchmark has no test cycles') } // Find the longest test name. config.width = tests.reduce(longest, 0) let cycles = {} for (let i = 0; i < tests.length; i++) { const test = tests[i] try { ...
javascript
{ "resource": "" }
q38377
measure
train
async function measure(test, bench) { let { delay, minTime, minSamples, minWarmups, onCycle, onSample, } = bench.config let { name, run } = test delay *= 1e3 minTime *= 1e3 let samples = [] let cycle = { name, // test name hz: null, // samples per second size: null, /...
javascript
{ "resource": "" }
q38378
train
function() { let sample = clock(start) if (test.after) test.after() bench.after.forEach(call) if (warmups == -1) { warmups = Math.max(minWarmups, sample > 100 ? 1 : sample > 10 ? 5 : 50) } if (warmups > 0) { warmups-- } else { samples[n++] = sample ...
javascript
{ "resource": "" }
q38379
onCycle
train
function onCycle(cycle, opts) { let hz = Math.round(cycle.hz).toLocaleString() let rme = '\xb1' + cycle.stats.rme.toFixed(2) + '%' // add colors hz = color(34) + hz + color(0) rme = color(33) + rme + color(0) const padding = ' '.repeat(opts.width - cycle.name.length) console.log(`${cycle.name}${padding}...
javascript
{ "resource": "" }
q38380
Binary
train
function Binary(buffer, subType) { if(!(this instanceof Binary)) return new Binary(buffer, subType); this._bsontype = 'Binary'; if(buffer instanceof Number) { this.sub_type = buffer; this.position = 0; } else { this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; this...
javascript
{ "resource": "" }
q38381
QueryUpdate
train
function QueryUpdate(data) { //Initialize the set var set = ''; //Get all data for(var key in data) { //Save data value var value = data[key]; //Check the data type if(typeof value === 'string' || value instanceof String) { //Add the quotes value = '"' + value + '"'; } ...
javascript
{ "resource": "" }
q38382
ColorMatrixFilter
train
function ColorMatrixFilter() { core.AbstractFilter.call(this, // vertex shader null, // fragment shader fs.readFileSync(__dirname + '/colorMatrix.frag', 'utf8'), // custom uniforms { m: { type: '1fv', value: [1, 0, 0, 0, 0, ...
javascript
{ "resource": "" }
q38383
smooth
train
function smooth(d, w) { let result = []; for (let i = 0, l = d.length; i < l; ++i) { let mn = Math.max(0, i - 5 * w), mx = Math.min(d.length - 1, i + 5 * w), s = 0.0; result[i] = 0.0; for (let j = mn; j < mx; ++j) { let wd = Math.exp(-0.5 * (i - j) * (...
javascript
{ "resource": "" }
q38384
TrinteBridge
train
function TrinteBridge(namespace, controller, action) { var responseHandler; if (typeof action === 'function') { return action; } try { if (/\//.test(controller)) { var cnts = controller.split('/'); namespace = cnts[0] + '/'; controller = cnts[1]; ...
javascript
{ "resource": "" }
q38385
getActiveRoutes
train
function getActiveRoutes(params) { var activeRoutes = {}, availableRoutes = { 'index': 'GET /', 'create': 'POST /', 'new': 'GET /new', 'edit': 'GET /:id/edit', 'destroy': 'DELETE /:id', ...
javascript
{ "resource": "" }
q38386
train
function(yuiType, c) { var index = yuiType.indexOf(c); if (index != -1) { yuiType = yuiType.substring(0, index); yuiType = yuiType.trim(); } return yuiType; }
javascript
{ "resource": "" }
q38387
request
train
function request(ipc, name, args) { // check online if (!ipc.root.online) { ipc.root.emit('error', new Error("Could not make a request, channel is offline")); return; } // store callback for later var callback = args.pop(); // check that a callback is set if (typeof callback !== 'function') { ...
javascript
{ "resource": "" }
q38388
setEmoji
train
function setEmoji(type,emojiDefault, emojiInfo, emojiError, emojiWarn) { let icon = emojiDefault switch (type) { case 'info': icon = emojiInfo break case 'error': icon = emojiError break case 'warn': icon = emojiWarn break default: } return icon }
javascript
{ "resource": "" }
q38389
ShowVersion
train
function ShowVersion(packageJson) { const pkgName = packageJson.name; let latestVer = spawnSync(`npm show ${pkgName} version`, { shell: true, stdio: ['inherit', 'pipe', 'inherit'], }).stdout; let latestVerStr = ''; if (latestVer) { latestVer = latestVer.toString('utf-8').replace(/\s/gm, ''); ...
javascript
{ "resource": "" }
q38390
GetCommandList
train
function GetCommandList(execName, packageJson, Commands) { const header = `\ ${packageJson.title || packageJson.name || execName} ${packageJson.version} Usage: ${execName} ${col.bold('<command>')} [options] Commands:`; const grouped = _.groupBy(Commands, 'helpGroup'); const sorted = _.mapValues(grouped, arr =...
javascript
{ "resource": "" }
q38391
GetCommandUsage
train
function GetCommandUsage(execName, packageJson, cmdSpec, args) { const argSpec = cmdSpec.argSpec || []; const optStr = argSpec.length ? ' [options]' : ''; const header = `\ Usage: ${execName} ${cmdSpec.name}${optStr} Purpose: ${cmdSpec.desc} Options: ${argSpec.length ? '' : 'none.'}`; const usageTableRows = ...
javascript
{ "resource": "" }
q38392
ParseArguments
train
function ParseArguments(cmd, args) { assert(_.isObject(cmd), 'require an object argument for "cmd".'); assert(_.isObject(args), 'require an object argument for "args".'); const argSpec = cmd.argSpec || []; const cmdName = cmd.name; // // Build a map of all flag aliases. // const allAliases = _.fromPair...
javascript
{ "resource": "" }
q38393
train
function (selector) { var self = this; // you can pass a literal function instead of a selector if (_.isFunction(selector)) { self._isSimple = false; self._selector = selector; self._recordPathUsed(''); return function (doc) { return {result: !!selector.call(doc)}; }; ...
javascript
{ "resource": "" }
q38394
train
function (v) { if (typeof v === "number") return 1; if (typeof v === "string") return 2; if (typeof v === "boolean") return 8; if (isArray(v)) return 4; if (v === null) return 10; if (_.isRegExp(v)) // note that typeof(/x/) === "object" return 11; if...
javascript
{ "resource": "" }
q38395
normalizeArray
train
function normalizeArray (v, keepBlanks) { var L = v.length, dst = new Array(L), dsti = 0, i = 0, part, negatives = 0, isRelative = (L && v[0] !== ''); for (; i<L; ++i) { part = v[i]; if (part === '..') { if (dsti > 1) { --dsti; } else if (isRelative) { ...
javascript
{ "resource": "" }
q38396
normalizeId
train
function normalizeId(id, parentId) { id = id.replace(/\/+$/g, ''); return normalizeArray((parentId ? parentId + '/../' + id : id).split('/')) .join('/'); }
javascript
{ "resource": "" }
q38397
normalizeUrl
train
function normalizeUrl(url, baseLocation) { if (!(/^\w+:/).test(url)) { var u = baseLocation.protocol+'//'+baseLocation.hostname; if (baseLocation.port && baseLocation.port !== 80) { u += ':'+baseLocation.port; } var path = baseLocation.pathname; if (url.charAt(0) === '/') { ...
javascript
{ "resource": "" }
q38398
format
train
function format(param, data, cb) { const time = util.formatTime(new Date()); const outArray = data.toString().replace(/^\s+|\s+$/g, '').split(/\s+/); let outValueArray = []; for (let i = 0; i < outArray.length; i++) { if ((!isNaN(outArray[i]))) { outValueArray.push(outArray[i]); ...
javascript
{ "resource": "" }
q38399
slice
train
function slice(toToken) { if (has(toToken) && !isLast(toToken)) { _tokens = _tokens.slice(0, _tokens.lastIndexOf(toToken) + 1); } }
javascript
{ "resource": "" }