_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 is the full matched string
result[values[i]] = current[i + 1];
}
return result;
} | 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_ENUM(enumName, enumSpec);
}, docs);
docs = _.reduce(specjs.CLASSES, function(memo, classSpec, parentClass) {
return _.reduce(classSpec.methods, function(memo, methodSpec, methodName) {
return memo += GENERATE_METHOD(methodName, methodSpec, parentClass);
}, memo);
}, docs);
return docs;
} | 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" :
var numPings = data.timestamps.length;
//Ping a minimum of number of times, before calculating the latency
if (numPings < MAX_PINGS){
ping(data);
}
else if (numPings == MAX_PINGS){
//Calculate this connections average latency and send it to the client
data.latency = calculateLatency(data.timestamps);
console.log(data.latency);
ping(data);
//If we haven't initialized yet, add this connection to the server zone
if (!initialized){
serverZone.add(connection);
initialized = true;
}
}
break;
case "PlayerUpdate":
//Set the player update id to the connection id to prevent clients from updating other players
data.id = connection.id;
serverZone.updatePlayer(data);
break;
default:
console.warn("Unexpected Schema Type Received: "+type);
break;
}
} | 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.consumer.on('data', onData.bind(this));
this.consumer.on('end', onEnd.bind(this));
// consume the stream
stream.setEncoding('utf8');
stream.pipe(this.consumer);
// yum-yum!
} | 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)
.then(function () {
return initServices(container);
})
.then(function () {
return ctx;
});
} | 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.type + '.reactor'];
var matchesCriteria = objUtils.matchesCriteria(payload.data, reactData.criteria);
var fieldMissing = reactData.onFieldChange && reactData.onFieldChange.length &&
_.isEmpty(fakeblock.filter.getFieldsFromObj(inputData, reactData.onFieldChange));
if (!reactor) {
log.info('reactHandler does not exist: ' + JSON.stringify(reactData));
}
if (!reactor || !matchesCriteria || fieldMissing) {
//deferred.resolve();
return;
}
Q.fcall(function () {
reactor.react({
caller: payload.caller,
inputData: inputData,
data: payload.data,
context: payload.context,
reactData: reactData,
resourceName: eventData.name.resource,
methodName: eventData.name.method
});
}).catch(log.error);
});
};
} | 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 });
}
});
// most reactors will be through the resource reactor definitions
_.each(resources, function (resource) { // loop through all the resources
_.each(resource.reactors, function (reactData) { // loop through reactors
if (isBatch && reactData.type === 'audit') { // don't do anything if audit for batch
return; // since audit not needed for batch
}
var eventTriggers = { // events that will trigger this propgation
resources: [resource.name],
adapters: reactData.trigger.adapters,
methods: reactData.trigger.methods
};
// add the event handler
eventBus.addHandlers(eventTriggers, reactHandler(reactData));
});
});
} | 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(adapters, function (adapter) {
if (adapter.init) {
calls.push(adapter.init);
}
});
}
return chainPromises(calls, config)
.then(function (returnConfig) {
if (returnConfig) {
return returnConfig;
}
else {
throw new Error('An adapter in the chain is not returning the config.');
}
});
} | 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([args]));
} else {
app.log("Executed [%s] on %d workers", id, done);
app.removeListener('worker_message', workerMessage);
}
}
app.on('worker_message', workerMessage = function(msg) {
if (isMessageForMe(msg) && msg[3] === 'done') {
nextWorker()
}
});
nextWorker();
} | 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);
var id = path
.replace(this.mvcpath + 'views/', '')
.replace('/partials/', '/')
.replace(/\/+/g, '_')
.replace(/[_\-]+/g, '_')
.replace(/^_+/g, '');
// Note: the layout_ prefix needs to be removed from the name because
// the slash from the path has been replaced with an underscore.
id = id.slice(0, id.indexOf('.')).toLowerCase().replace(layoutPrefix, '');
// Normalize views to remove duplicate chunks within the filename
// For example: dashboard/dashboard-test will be accessed as {{> dashboard_test}}
// The added benefit of this method is that it will remove all duplicate subsequent
// occurrences of the same chunk, regardless.
id = id.split('_').reduce(function(prev, current) {
if (prev[0] !== current) prev.unshift(current);
return prev;
}, []).reverse().join('_');
func.id = id;
this.views.partials[id] = func;
} else {
throw new Error(util.format("Unable to render %s: engine not loaded", this.relPath(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, Ctor, i=0; i < files.length; i++) {
file = files[i];
key = file.replace(this.regex.jsFile, '');
className = file.replace(this.regex.jsFile, '');
Ctor = protos.require(cpath + className, true); // Don't use module cache (allow reloading)
Ctor = createControllerFunction.call(this, Ctor);
instance = new Ctor(this);
instance.className = instance.constructor.name;
this.controllers[key.replace(/_controller$/, '')] = instance;
}
this.controller = this.controllers.main;
this.emit('controllers_loaded', this.controllers);
} | 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 = handlersPath + '/' + dirname;
var stat = fs.statSync(dir);
if (stat.isDirectory(dir)) {
var handlers = self.handlers[dirname] = {};
fileModule.walkSync(dir, function(dirPath, dirs, files) {
for (var path,hkey,callback,file,i=0; i < files.length; i++) {
file = files[i];
path = dirPath + '/' + file;
hkey = self.relPath(path, pathModule.basename(self.mvcpath) + '/handlers/' + dirname);
if (jsFile.test(file)) {
callback = protos.require(path, true); // Don't use module cache (allow reloading)
if (callback instanceof Function) {
handlers[hkey] = callback;
} else {
throw new Error(util.format("Expected a function for handler: %s/%s", dirname, file));
}
}
}
});
}
});
}
this.emit('handlers_loaded', self.handlers); // Emit regardless
} | 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 defaults.
var config = (fs.existsSync(configFile)) ? require(configFile) : protos.require('skeleton/config.js');
var baseConfig = (mainPos !== -1) ? require(this.path + '/config/base.js') : {};
_.extend(config, baseConfig);
// Extend with config files
for (var file,key,cfg,i=0; i < files.length; i++) {
if (i==mainPos) continue;
file = files[i];
key = file.replace(jsExt, '');
cfg = require(this.path + '/config/' + file);
if (typeof config[key] == 'object') _.extend(config[key], cfg);
else config[key] = cfg;
}
// Return merged configuration object
return config;
} | 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.config.watchInterval || 100});
watcher.on('change', function() {
self.debug("Regeneraging view partial", self.relPath(path));
callback.call(self, path);
});
watcher.on('unlink', function() {
self.log(util.format("Stopped watching partial '%s' (renamed)", self.relPath(path)));
watcher.close();
});
watcher.on('error', function(err) {
self.log(util.format("Stopped watching partial '%s' (error)", self.relPath(path)));
self.log(err.stack);
watcher.close();
});
}
} | 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; }
for (y in cfg) {
if (typeof cfg[y] == 'object') {
if (typeof drivers[x] == 'undefined') drivers[x] = {};
drivers[x][y] = [x, cfg[y]];
} else {
drivers[x] = [x, cfg];
break;
}
}
}
} | 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] == 'object') {
if (typeof storages[x] == 'undefined') storages[x] = {};
storages[x][y] = [x, cfg[y]];
} else {
storages[x] = [x, cfg];
break;
}
}
}
} | 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 cache (allow reloading)
_.extend(this.api, methods);
}, this);
}
this.emit('api_loaded', this.api);
} | 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];
evt = file.replace(jsFile, '');
loadedHooks.push(evt);
cb = protos.require(hooksPath + '/' + file, true);
if (cb instanceof Function) {
if (RELOADING) {
var origCb = this.hooks[evt];
if (origCb instanceof Function) {
// Hook was added previously
if (events[evt] instanceof Array) {
idx = events[evt].indexOf(origCb);
if (idx >= 0) {
// If old function is in events array, replace it
events[evt][idx] = this.hooks[evt] = cb;
} else {
// Otherwise, append to events array (add a new event handler)
events[evt].push(cb);
this.hooks[evt] = cb;
}
} else if (events[evt] instanceof Function) {
if (events[evt] === origCb) {
// If evt has only one callback, replace it
events[evt] = this.hooks[evt] = cb;
} else {
// Otherwise, create an array with the old and new events
events[evt] = [origCb, cb];
}
} // No else clause is needed here, it's either Function or Array
} else {
// This is a new event handler
this.hooks[evt] = cb;
this.on(evt, cb);
}
} else {
// Add the event handler normally
this.hooks[evt] = cb;
this.on(evt, cb);
}
}
}
}
// Remove any inexisting hooks
for (evt in this.hooks) {
if (loadedHooks.indexOf(evt) === -1) {
app.removeListener(evt, this.hooks[evt]);
delete this.hooks[evt];
}
}
} | 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 = ['className', 'extensions'];
for (engine in protos.engines) {
instance = new protos.engines[engine]();
instance.className = instance.constructor.name;
protos.util.onlySetEnumerable(instance, engineProps);
this.engines[engine] = instance;
}
// Register engine extensions
for (var key in this.engines) {
engine = this.engines[key];
exts = exts.concat(engine.extensions);
for (var i=0; i < engine.extensions.length; i++) {
key = engine.extensions[i];
this.enginesByExtension[key] = engine;
}
}
// Set default view extension if not set
if (typeof this.config.viewExtensions.html == 'undefined') {
this.config.viewExtensions.html = 'ejs';
}
// Override engine extensions (from config)
var ext, extOverrides = this.config.viewExtensions;
for (ext in extOverrides) {
if (exts.indexOf(ext) == -1) exts.push(ext); // Register extension on `exts`
engine = this.engines[extOverrides[ext]]; // Get engine object
if (engine) {
engine.extensions.push(ext); // Add ext to engine extensions
this.enginesByExtension[ext] = engine; // Override engine extension
} else {
this.debug(util.format("Ignoring '%s' extension: the '%s' engine is not loaded"), ext, extOverrides[ext]);
}
}
// Set default template engine
this.defaultEngine = (this.engines.ejs || this.engines[loadedEngines[0]]);
// Add the engines regular expression
this.engineRegex = new RegExp('^(' + Object.keys(this.engines).join('|').replace(/\-/, '\\-') + ')$');
}
// Generate template file regex from registered template extensions
this.regex.templateFile = new RegExp('\\.(' + exts.join('|') + ')$');
this.templateExtensions = exts;
this.emit('engines_loaded', this.engines); // Emit regardless
} | 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 = engine.renderPartial(path);
func.engine = engine;
func.ext = ext;
this.templates[tpl] = func;
} else {
throw new Error(util.format("Unable to render %s: engine not loaded", this.relPath(path)));
}
} | 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 RegExp('\\.(' + exts.join('|') + ')$');
var layoutPath = this.mvcpath + 'views/' + this.paths.layout;
var viewsPath = this.mvcpath + 'views';
var partialPaths = [];
if (fs.existsSync(viewsPath)) {
fileModule.walkSync(viewsPath, function(dirPath, dirs, files) {
for (var path,file,i=0; i < files.length; i++) {
file = files[i];
path = dirPath + "/" + file;
if (partialRegex.test(path)) {
// Only build valid partial views
partialPaths.push(path);
buildPartialView.call(self, path);
watchPartial.call(self, path, buildPartialView);
} else if (templateRegex.test(file)) {
// Build partial views for everything inside app.paths.layout
if (path.indexOf(layoutPath) === 0) {
partialPaths.push(path);
buildPartialView.call(self, path);
watchPartial.call(self, path, buildPartialView);
}
// Only add valid templates to view associations
self.views.pathAsoc[self.relPath(path.replace(self.regex.templateFile, ''))] = path;
}
}
});
}
// Add Builtin Partials
var Helper = protos.lib.helper;
var builtinHelper = new Helper();
for (var m in builtinHelper) {
if (builtinHelper[m] instanceof Function) {
this.registerViewHelper(m, builtinHelper[m], builtinHelper);
}
}
// Helper Partials
Object.keys(this.helpers).forEach(function(alias) {
var m, method, hkey, helper = self.helpers[alias];
for (m in helper) {
if (helper[m] instanceof Function) {
method = helper[m];
hkey = (alias == 'main')
? util.format('%s', m)
: util.format('%s_%s', alias, m);
self.registerViewHelper(hkey, method, helper);
}
}
});
// Event when view partials are loaded
this.emit('view_partials_loaded', this.views.partials);
// Set shortcode context
// NOTE: Automatically resets on hot code loading, so it's good.
var shortcodeContext = this.__shortcodeContext = {};
// Only add shortcode filter to context if enabled on config
if (this.config.shortcodeFilter) {
// Register shortcodes from partials
var shortcode = self.shortcode;
var partials = self.views.partials;
Object.keys(this.views.partials).forEach(function(partial) {
if (partial[0] === '$') {
shortcodeContext[partial.replace(/^\$/, '#')] = self.views.partials[partial];
} else {
shortcodeContext[partial] = function(buf, params, locals) {
if (buf) params.content = buf; // Provide wrapped content in params.content
params.__proto__ = locals; // Set locals as prototype of params
return partials[partial].call(null, params); // Provide params to partial, which is passed as locals
}
}
});
this.addFilter('context', function(buf, locals) {
buf = this.shortcode.parse(buf, locals, shortcodeContext);
return buf;
});
}
// Event when view shortcodes are loaded
this.emit('view_shortcodes_loaded', shortcodeContext);
} | 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 alias = protos.lib.controller.prototype.getAlias(func.name),
srcFile = this.mvcpath + 'controllers/' + alias + '.js';
try {
source = fs.readFileSync(srcFile, 'utf-8');
} catch(e){
source = fs.readFileSync(srcFile.replace(/\.js$/, '_controller.js'), 'utf-8');
}
// Detect pre & post function code
var si = source.indexOf(funcSrc),
preFuncSrc = source.slice(0, si).trim(),
postFuncSrc = source.slice(si + funcSrc.length).trim();
// Controller code
var template = Handlebars.compile('\n\
with (locals) {\n\n\
function {{{name}}}(app) {\n\
this.filters = this.filters["{{{name}}}"] || [];\n\
}\n\n\
require("util").inherits({{{name}}}, protos.lib.controller);\n\n\
protos.extend({{{name}}}, protos.lib.controller);\n\n\
{{{name}}}.filter = {{{name}}}.prototype.filter;\n\
{{{name}}}.handler = {{{name}}}.prototype.handler;\n\n\
var __funKeys__ = Object.keys({{{name}}});\n\
\n\
(function() { \n\
{{{preFuncSrc}}}\n\n\
with(this) {\n\n\
{{{code}}}\n\
}\n\n\
{{{postFuncSrc}}}\n\n\
}).call({{{name}}});\n\n\
for (var key in {{{name}}}) {\n\
if (__funKeys__.indexOf(key) === -1) { \n\
{{{name}}}.prototype[key] = {{{name}}}[key];\n\
delete {{{name}}}[key];\n\
}\n\
}\n\
\n\
if (!{{{name}}}.prototype.authRequired) {\n\
{{{name}}}.prototype.authRequired = protos.lib.controller.prototype.authRequired;\n\
} else {\n\
{{{name}}}.prototype.authRequired = true; \n\
}\n\n\
return {{{name}}};\n\n\
}');
var fnCode = template({
name: func.name,
code: code,
preFuncSrc: preFuncSrc,
postFuncSrc: postFuncSrc,
});
// console.exit(fnCode);
/*jshint evil:true */
compile = new Function('locals', fnCode);
newFunc = compile({
app: this,
protos: protos,
module: {},
require: require,
console: console,
__dirname: this.mvcpath + 'controllers',
__filename: srcFile,
process: process
});
return newFunc;
} | 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 a - b;
});
var index = (length - 1) * k;
var lower = Math.floor(index);
var upper = lower + 1;
var weight = index % 1;
if (upper >= length) {
return array[lower];
}
return array[lower] * (1 - weight) + array[upper] * weight;
} | 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(no[key])) {
oo[key] = no[key]
}
} else {
// Plain assign
oo[key] = no[key]
}
}
return oo
}
return _merge(oldCopy, newObject)
} | 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('\n');
} | 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 + '`?',
value: 'nothing',
choices: [{
key: 'n',
name: 'do not overwrite',
value: 'skip'
}, {
key: 'y',
name: 'overwrite',
value: 'write'
}, {
key: 'a',
name: 'overwrite this and all others',
value: 'force'
}, {
key: 'x',
name: 'abort',
value: 'abort'
}, {
key: 'd',
name: 'diff comparison between the current and new:',
value: 'diff'
}]
};
prompt([questions], function (answers) {
var msg = answers.action;
switch(answers.action) {
case 'skip':
cb(answers.action);
process.exit(0);
case 'abort':
msg = utils.red(utils.error) + ' Aborted. No action was taken.';
if (!opts.silent) console.log(msg);
cb(answers.action);
process.exit(0);
case 'diff':
var existing = opts.existing || fs.readFileSync(fp, 'utf8');
if (lazy.isBinary(existing) && typeof opts.binaryDiff === 'function') {
opts.binaryDiff(existing, file.contents);
} else {
stringDiff(existing, file.contents.toString());
}
return ask(file, opts, cb);
case 'force':
opts.force = true;
break;
case 'write':
msg = utils.green(utils.success) + ' file written to';
opts.force = true;
break;
default: {
msg = utils.red(utils.error) + utils.red(' Aborted.') + ' No action was taken.';
if (!opts.silent) console.log(msg);
cb(answers.action);
process.exit(0);
}
}
var rel = path.relative(process.cwd(), fp);
var filepath = utils[answers.action](rel);
if (!opts.silent) {
console.log(msg, filepath);
}
return cb(answers.action);
});
} | 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 (letter === separator) {
result.push(token);
token = '';
} else {
token += letter;
}
});
if (token.length > 0) {
result.push(token);
}
return result;
} | 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);
}
return acc;
}, []);
} | 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){
if (err) return handleError(null, err, 'cannot open mongodb connection', cb);
var targetDb = db.db(dbName);
targetDb.authenticate(admin, admin_pass, {'authSource': 'admin'}, function(err) {
if (err) return handleError(db, err, 'can not authenticate admin user', cb);
// update for mongodb3.2 - need to remove user first
targetDb.removeUser(dbUser, function(err) {
if(err){
log.logger.error(err, 'failed to remove user');
}
// add user to database
targetDb.addUser(dbUser, dbUserPass, function(err, user) {
if (err) return handleError(db, err, 'can not add user', cb);
log.logger.trace({user: user, database: dbName}, 'mongo added new user');
db.close();
return cb();
});
});
});
});
} | 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(null, err, 'cannot open mongodb connection', cb);
var dbToDrop = dbObj.db(dbName);
dbToDrop.authenticate(admin, admin_pass, {'authSource': 'admin'}, function(err){
if(err) return handleError(dbObj, err, 'can not authenticate admin user', cb);
dbToDrop.removeUser(dbUser, function(err){
if(err){
log.logger.error(err, 'failed to remove user');
}
dbToDrop.dropDatabase(function(err){
if(err) return handleError(dbObj, err, 'failed to drop database', cb);
dbObj.close();
return cb();
});
});
});
});
} | 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 inputArg) &&
('call' in inputArg) &&
('apply' in inputArg) &&
('length' in inputArg) &&
typeof inputArg.length === 'number') {
isFn = true;
}
}
return isFn;
} | 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) {
flags = pReplace.call(flags + options.add, clipDups, '');
}
if (options.remove) {
// Would need to escape `options.remove` if this was public
flags = pReplace.call(flags, new CRegExp('[' + options.remove + ']+', 'g'), '');
}
return new CRegExp(regExpArg.source, flags);
} | 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(s, times / 2);
val = half + half;
}
return val;
} | 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;
} else {
typex = typeof left[0];
typey = typeof right[0];
if (typex === 'undefined' && typey === 'undefined') {
val = +0;
} else if (typex === 'undefined') {
val = 1;
} else if (typey === 'undefined') {
val = -1;
}
}
return val;
} | 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 (comparison(left[0], right[0]) <= 0) {
if ($hasOwn(left, 0)) {
result[next] = left[0];
}
pShift.call(left);
} else {
if ($hasOwn(right, 0)) {
result[next] = right[0];
}
pShift.call(right);
}
} else if (sComp <= 0) {
if ($hasOwn(left, 0)) {
result[next] = left[0];
}
pShift.call(left);
} else {
if ($hasOwn(right, 0)) {
result[next] = right[0];
}
pShift.call(right);
}
next += 1;
}
while (left.length) {
if ($hasOwn(left, 0)) {
result[next] = left[0];
}
pShift.call(left);
next += 1;
}
while (right.length) {
if ($hasOwn(right, 0)) {
result[next] = right[0];
}
pShift.call(right);
next += 1;
}
return result;
} | 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);
back = $slice(array, middle);
val = merge(mergeSort(front, comparefn), mergeSort(back, comparefn), comparefn);
}
return val;
} | 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 converting file %s", file);
var data = files[file];
return function(cb) {
var NormalizedRho = null;
if (_.isPlainObject(options.blockCompiler)) {
NormalizedRho = options.blockCompiler;
} else if (_.isFunction(options.blockCompiler)) {
NormalizedRho = options.blockCompiler(files, file, data);
} else {
NormalizedRho = require("rho").BlockCompiler;
}
var html = (new NormalizedRho()).toHtml(data.contents.toString());
data.contents = new Buffer(html);
cb(null, html);
};
});
async.parallel(convertFns, function(err) {
if (err) {
debug("A file failed to compile: %s", err);
done(new Error());
}
_.forEach(tbConvertedFiles, function(file) {
var contents = files[file];
var extension = path.extname(file);
var fileNameWoExt = path.basename(file, extension);
var dirname = path.dirname(file);
var renamedFile = path.join(dirname, fileNameWoExt + "." + options.extension);
files[renamedFile] = contents;
delete files[file];
});
done();
});
};
} | 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: palette.base02,
base3: palette.base03
});
} | 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} ${majorVersion} ChangeLog\n`,
`All changes commited to this repository will be documented in this file. It adheres to [Semantic Versioning](http://semver.org/).\n`,
'<details>',
`<summary>List of tags released on the ${majorVersion} range</summary>\n`
];
tagsList[majorVersion].forEach(info => {
link = `${info.tag}-${info.date}`;
logIndex.push(`- [${info.tag}](#${link.replace(/\./g, '')})`);
logDetailed.push(
`\n## [${info.tag}](${repoUrl}/tree/${info.tag}), ${info.date}\n` +
`- [Release notes](${repoUrl}/releases/tag/${info.tag})\n` +
`- [Full changelog](${repoUrl}/compare/${prevTagHolder}...${info.tag})\n`
);
prevTagHolder = info.tag;
});
logContent.push(logIndex.reverse().join('\n'), '\n</details>\n\n', logDetailed.reverse().join('\n'));
writeLogFiles.push(promiseWriteFile(`changelog/CHANGELOG-${majorVersion.toUpperCase()}.md`, logContent.join('\n')));
});
return Promise.all(writeLogFiles);
} | 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(!this[cmd]) continue;
// must re-define the command method
// so it is not shared across client instances
method = this[cmd] = this[cmd].bind(this);
function subcommand(cmd, sub) {
var args = [].slice.call(arguments, 1), cb;
if(typeof args[args.length - 1] === 'function') {
cb = args.pop();
}
this.execute(cmd, args, cb);
return this;
}
for(sub in SubCommand[cmd]) {
method[sub] = subcommand.bind(this, cmd, sub);
}
}
this.socket = socket;
this.socket.on('connect', this._connect.bind(this));
this.socket.on('data', this._data.bind(this));
this.socket.on('error', this._error.bind(this));
this.socket.on('close', this._close.bind(this));
this.tcp = (this.socket instanceof Socket);
// using a tcp socket connection
if(this.tcp) {
this.encoder = new Encoder(
{return_buffers: options.buffers});
this.encoder.pipe(this.socket);
this.decoder = new Decoder(
{
simple: options.simple,
return_buffers: options.buffers,
raw: options.raw
});
this.decoder.on('reply', this._reply.bind(this))
}
} | 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 process
}else{
this.socket.write(arr);
}
} | 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 = apiOrBuilder.registry;
instanceName = apiOrBuilder.instanceName;
} else {
api = apiOrBuilder;
}
if (_.isFunction(api)) {
api = api();
}
if (!registry && _.isFunction(api.registry)) {
registry = api.registry();
}
if (!registry) {
// print errors here
return;
}
_.forEach(registry, (value, key) => {
if (_.isArray(value)) {
_.forEach(value, item => buildRoute(router, api, key, item, pathPrefix, instanceName));
} else {
buildRoute(router, api, key, value, pathPrefix, instanceName);
}
});
} | 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._id;
al.enabled = alert.alertEnabled;
return al;
});
}
// Return the response
return res;
} | 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 notification.toJSON();
});
}
// Return the response
return res;
} | 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 = event.details ? event.details.message || " " : " ";
ev.category = event.eventClass;
ev.severity = event.eventLevel;
ev.guid = event._id;
ev.eventDetails = ev.details ||{};
return ev;
});
}
// Return the response
return res;
} | 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 = "";
if (virtualPath !== "/" && uri.indexOf(virtualPath) === 0) {
uri = uri.substr(virtualPath.length, uri.length - virtualPath.length);
}
uri = (physicalPath || "") + uri;
filename = fs.combine(process.cwd(), uri).replace(/\%20/gmi, ' ');
if (cache[filename]) {
console.log("\u001b[32mLoaded from Cache '" + filename + "\u001b[39m'");
if (cache[filename] === 404) {
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("Content not found");
res.end();
} else {
if (req.headers["If-Modified-Since"] === cache[filename].since) {
res.writeHead(304, {
'Content-Type': mime.lookup(filename),
'Last-Modified': cache[filename].since,
//'If-Modified-Since': cache[filename].since,
"Cache-Control": "max-age=31536000"
});
res.end();
} else {
res.writeHead(200, {
'Content-Type': mime.lookup(filename),
//'If-Modified-Since': cache[filename].since,
'Last-Modified': cache[filename].since,
"Cache-Control": "max-age=31536000"
});
res.write(cache[filename].data, "binary");
res.end();
}
}
return;
}
if (filename) {
fs.readFile(filename, "binary", synchronizer.register("file"));
}
synchronizer.onfinish(function (err, data) {
if (err) {
if (paths.length > 0) {
processRequest(paths);
} else if (next) {
next();
} else {
console.log("\u001b[31mStatic file not found '" + filename + "'\u001b[39m");
cache[filename] = 404;
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("Content not found");
res.end();
}
return;
}
console.error("\u001b[31mLoaded static file '" + filename + "'\u001b[39m");
cache[filename] = {
data: data.file,
since: new Date().toGMTString()
};
res.writeHead(200, {
'Content-Type': mime.lookup(filename),
//'If-Modified-Since': cache[filename].since,
'Last-Modified': cache[filename].since,
"Cache-Control": "max-age=31536000"
});
res.write(data.file, "binary");
res.end();
if (!settings.cacheEnabled) { cache[filename] = undefined; }
});
}
processRequest(paths);
};
} | 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";
}
}
return message;
} | 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.length; i++) {
codePart = codeParts[i];
codeParts[i] = codePart.substring(0, 1).toUpperCase() + codePart.substring(1);
}
str = codeParts.join('');
});
return str;
} | 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);
const packageFile = path.resolve(PACKAGES_PATH, packageName, 'index.js');
fs.writeFileSync(packageFile, generatedData);
})
.then(
() => console.log(`Finished building ${name} config to ./packages/${packageName}`),
error => console.log(error),
);
} | 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, 1,
1, 1,
1, 0,
0, 1]);
/**
* An array of vertices
*
* @member {Float32Array}
*/
this.vertices = vertices || new Float32Array([0, 0,
100, 0,
100, 100,
0, 100]);
/*
* @member {Uint16Array} An array containing the indices of the vertices
*/
// TODO auto generate this based on draw mode!
this.indices = indices || new Uint16Array([0, 1, 2, 3]);
/**
* Whether the Mesh is dirty or not
*
* @member {boolean}
*/
this.dirty = true;
/**
* The blend mode to be applied to the sprite. Set to blendModes.NORMAL to remove any blend mode.
*
* @member {number}
* @default CONST.BLEND_MODES.NORMAL;
*/
this.blendMode = core.BLEND_MODES.NORMAL;
/**
* Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other.
*
* @member {number}
*/
this.canvasPadding = 0;
/**
* The way the Mesh should be drawn, can be any of the Mesh.DRAW_MODES consts
*
* @member {number}
*/
this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH;
} | 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;
selector = undefined;
}
var wait = undefined;
this.on(eventNames, selector, /** @function
* @param {...*} args */function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var _this = this;
if (!throttle) {
clearTimeout(wait);
wait = null;
}
if (!wait) {
wait = setTimeout(function () {
wait = null;
listener.apply(_this, args);
}, delay);
}
});
} | 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(userInfo.securityEvents, (secEvt) => {
if (secEvt.eventType === 'password_reset_requested') {
delete secEvt.data.resetCode;
}
});
return cb(null, userInfo, curVersion);
});
} | 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 || safeExec('git rev-parse HEAD').stdout.trim();
echo(`Deploying commit ${commitSHA}...`);
echo('Loging in to docker registry...');
const loginCmd = safeExec('aws ecr get-login', { silent: true }).stdout;
safeExec(loginCmd);
echo('Building docker image...');
safeExec(`docker build -t ${containerName} .`);
echo('Uploading docker image...');
safeExec(`docker tag ${containerName} ${containerRepository}:${commitSHA}`);
safeExec(`docker tag ${containerName} ${containerRepository}:latest`);
safeExec(`docker push ${containerRepository}`);
echo('Updating service...');
const ecs = new AWS.ECS();
ecs.describeServices({
cluster: clusterName,
services: [serviceName],
}).promise()
.then((data) => {
const taskDefinition = data.services[0].taskDefinition;
return ecs.describeTaskDefinition({
taskDefinition,
}).promise();
})
.then((data) => {
const { taskDefinition } = data;
return ecs.registerTaskDefinition({
containerDefinitions: taskDefinition.containerDefinitions.map(def => {
const newImage = `${def.image.split(':')[0]}:${commitSHA}`;
return Object.assign({}, def, { image: newImage });
}),
family: taskDefinition.family,
networkMode: taskDefinition.networkMode,
taskRoleArn: taskDefinition.taskRoleArn,
volumes: taskDefinition.volumes,
}).promise();
})
.then((data) => {
echo(`Created new revision ${data.taskDefinition.revision}.`);
return ecs.updateService({
service: serviceName,
cluster: clusterName,
taskDefinition: data.taskDefinition.taskDefinitionArn,
}).promise();
})
.then(() => {
echo('Service updated successfully.');
})
.catch((err) => {
echo(err);
exit(1);
});
} | 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', 'Invalid size supplied');
assert(typeof this._options.hash === 'string', 'Invalid hash alg supplied');
this.hash = crypto.createHash(this._options.hash);
this.bytes = 0;
ReadableStream.call(this);
} | 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 {
cycles[test.name] = await measure(test, bench)
} catch (e) {
config.onError(e)
}
}
// all done!
config.onFinish(cycles)
bench.done(cycles)
} | 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, // number of samples
time: null, // elapsed time (including delays)
stats: null,
}
let n = 0
let t = process.hrtime()
let warmups = -1
// synchronous test
if (run.length == 0) {
let start
while (true) {
bench.before.forEach(call)
if (test.before) test.before()
start = process.hrtime()
run()
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
onSample(samples[n - 1], cycle)
if (minTime <= clock(t) && minSamples <= n) {
break // all done!
}
}
// wait then repeat
await wait(delay)
}
}
// asynchronous test
else {
let start
const next = function() {
bench.before.forEach(call)
if (test.before) test.before()
start = process.hrtime()
run(done)
}
// called by the test function for every sample
const done = 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
onSample(samples[n - 1], cycle)
if (minTime <= clock(t) && minSamples <= n) {
return cycle.done() // all done!
}
}
// wait then repeat
wait(delay).then(next)
}
defer(cycle) // wrap cycle with a promise
next() // get the first sample
// wait for samples
await cycle.promise
}
const time = clock(t)
const stats = analyze(samples)
cycle.hz = 1000 / stats.mean
cycle.size = n
cycle.time = time
cycle.stats = stats
onCycle(cycle, bench.config)
} | 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
onSample(samples[n - 1], cycle)
if (minTime <= clock(t) && minSamples <= n) {
return cycle.done() // all done!
}
}
// wait then repeat
wait(delay).then(next)
} | 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} ${hz} ops/sec ${rme}`)
} | 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.position = 0;
}
if(buffer != null && !(buffer instanceof Number)) {
// Only accept Buffer, Uint8Array or Arrays
if(typeof buffer == 'string') {
// Different ways of writing the length of the string for the different types
if(typeof Buffer != 'undefined') {
this.buffer = new Buffer(buffer);
} else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) {
this.buffer = writeStringToArray(buffer);
} else {
throw new Error("only String, Buffer, Uint8Array or Array accepted");
}
} else {
this.buffer = buffer;
}
this.position = buffer.length;
} else {
if(typeof Buffer != 'undefined') {
this.buffer = new Buffer(Binary.BUFFER_SIZE);
} else if(typeof Uint8Array != 'undefined'){
this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE));
} else {
this.buffer = new Array(Binary.BUFFER_SIZE);
}
// Set position to start of buffer
this.position = 0;
}
} | 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 + '"';
}
//Check if is necessary add the comma
if(set !== '')
{
//Add the comma
set = set + ' , ';
}
//Add the key=value
set = set + key + '=' + value;
}
//Return
return set;
} | 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,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1] },
}
);
} | 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) * (i - j) / w / w);
result[i] += wd * d[j];
s += wd;
}
result[i] /= s;
}
return result;
} | 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];
}
namespace = typeof namespace === 'string' ? namespace.toString().toLowerCase() : '';
controller = controller.pluralize().capitalize();
var crtRoot = './../app/controllers/';
['', 'es', 'ses'].forEach(function (prf) {
var ctlFile = crtRoot + namespace + controller + prf + 'Controller';
if (fileExists(path.resolve(__dirname, ctlFile) + '.js')) {
responseHandler = require(ctlFile)[action];
}
});
} catch (e) {
// console.log( 'Error Route Action: ' + action );
console.log(e);
}
if (!responseHandler) console.log('Bridge not found for ' + namespace + controller + '#' + action);
return responseHandler || function (req, res) {
res.send('Bridge not found for ' + namespace + controller + '#' + action);
};
} | 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',
'update': 'PUT /:id',
'show': 'GET /:id',
'destroyall': 'DELETE /'
},
availableRoutesSingleton =
{
'show': 'GET /show',
'create': 'POST /',
'new': 'GET /new',
'edit': 'GET /edit',
'destroy': 'DELETE /',
'update': 'PUT /',
'destroyall': 'DELETE /'
};
if (params.singleton) {
availableRoutes = availableRoutesSingleton;
}
// 1. only
if (params.only) {
if (typeof params.only === 'string') {
params.only = [params.only];
}
params.only.forEach(function (action) {
if (action in availableRoutes) {
activeRoutes[action] = availableRoutes[action];
}
});
}
// 2. except
else if (params.except) {
if (typeof params.except === 'string') {
params.except = [params.except];
}
for (var action1 in availableRoutes) {
if (params.except.indexOf(action1) === -1) {
activeRoutes[action1] = availableRoutes[action1];
}
}
}
// 3. all
else {
for (var action2 in availableRoutes) {
activeRoutes[action2] = availableRoutes[action2];
}
}
return activeRoutes;
} | 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') {
ipc.root.emit('error', new TypeError("No callback specified"));
return;
}
// send request to remote
ipc.send('call', [name, args], function (sucess, content) {
if (sucess) {
callback.apply({
error: null
}, content);
} else {
callback.apply({
error: helpers.object2error(content)
}, []);
}
});
} | 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, '');
if (latestVer !== packageJson.version) {
const osType = os.type();
const sudo = (osType === 'Linux' || osType === 'Darwin') ? 'sudo ' : '';
latestVerStr = `Latest version on npm: ${col.warning(latestVer).bold}
Run "${col.warning(`${sudo}npm install -g ${pkgName}@latest`)}" to upgrade.`;
} else {
latestVerStr = `${col.success('up-to-date!')}`;
}
}
return `${packageJson.version}\n${latestVerStr}`;
} | 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 => _.sortBy(arr, 'helpPriority'));
const sortedGroups = _.sortBy(sorted, grp => grp[0].helpPriority);
const longestCmd = _.max(_.map(Commands, cmd => cmd.name.length));
const commandListStr = _.map(sortedGroups, (helpGroup) => {
const groupName = _.first(helpGroup).helpGroup;
return _.flatten([
`\n * ${col.primary(groupName)}`,
_.map(helpGroup, (cmd) => {
const cmdName = _.padEnd(cmd.name, longestCmd);
return ` ${col.bold(cmdName)} ${cmd.desc}`;
}),
]).join('\n');
}).join('\n');
return `\
${header}
${commandListStr}
Use ${col.bold(`${execName} <command> -h`)} for command-specific help.`;
} | 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 = _.map(cmdSpec.argSpec, (argDef) => {
const dashify = flag => (flag.length === 1 ? `-${col.primary(flag)}` : `--${col.primary(flag)}`);
const lhs = _.map(argDef.flags, dashify).join(', ');
const rhs = argDef.desc || '';
return [lhs, rhs, argDef];
});
const firstColWidth = _.max(
_.map(usageTableRows, row => stripAnsi(row[0]).length)) + 1;
const body = _.map(usageTableRows, (row) => {
const rhsLines = row[1].split(/\n/mg);
const firstRhsLine = rhsLines[0];
rhsLines.splice(0, 1);
const lhsSpacer = new Array((firstColWidth - stripAnsi(row[0]).length) + 1).join(' ');
const paddedLhs = `${lhsSpacer}${row[0]}`;
const firstLine = `${paddedLhs}: ${firstRhsLine}`;
const skipLeft = new Array(firstColWidth + 1).join(' ');
const paddedRhs = rhsLines.length ? _.map(rhsLines, line => `${skipLeft}${line}`).join('\n') : '';
const argDef = row[2];
let curVal = _.find(argDef.flags, flag => (flag in args ? args[flag] : null));
if (!curVal) curVal = argDef.defVal || argDef.default || '';
if (curVal) {
curVal = `${skipLeft} ${col.dim('Current:')} "${col.primary(curVal)}"`;
}
return _.filter([
firstLine,
paddedRhs,
curVal,
]).join('\n');
}).join('\n\n');
return `\
${header}
${body}
`;
} | 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 = _.fromPairs(_.map(_.flatten(_.map(argSpec, 'flags')), (flagAlias) => {
return [flagAlias, true];
}));
//
// Make sure all provided flags are specified in the argSpec.
//
_.forEach(args, (argVal, argKey) => {
if (argKey === '_') return; // ignore positional arguments
if (!(argKey in allAliases)) {
const d = argKey.length === 1 ? '-' : '--';
throw new Error(
`Unknown command-line option "${col.bold(d + argKey)}" specified ` +
`for command "${col.bold(cmdName)}".`);
}
});
//
// Handle boolean flags specified as string values on the command line.
//
args = _.mapValues(args, (flagVal) => {
if (_.isString(flagVal)) {
if (flagVal === 'true') {
return true;
}
if (flagVal === 'false') {
return false;
}
}
return flagVal;
});
//
// For each flag in the argSpec, see if any alias of the flag is
// present in `args`. If it is, then assign that value to *all*
// aliases of the flag. If it is not present, then assign the
// default value. Throw on unspecified required flags.
//
const finalFlags = {};
_.forEach(argSpec, (aspec, idx) => {
// Find the first alias of this flag that is specified in args, if at all.
const foundAlias = _.find(aspec.flags, (flagAlias) => {
return flagAlias && (flagAlias in args);
});
let assignValue = foundAlias ? args[foundAlias] : (aspec.defVal || aspec.default);
// If defVal is an object, then we need to execute a function to get the
// default value.
if (_.isObject(assignValue)) {
assert(
_.isFunction(assignValue.fn),
`Argspec entry ${idx} has an invalid 'defVal'/'default' property.`);
assignValue = assignValue.fn.call(argSpec);
}
if (!_.isUndefined(assignValue)) {
// Assign value to all aliases of flag.
_.forEach(aspec.flags, (flagAlias) => {
finalFlags[flagAlias] = assignValue;
});
}
});
// Copy positional arguments to finalFlags.
finalFlags._ = args._;
return finalFlags;
} | 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)};
};
}
// shorthand -- scalars match _id
if (LocalCollection._selectorIsId(selector)) {
self._selector = {_id: selector};
self._recordPathUsed('_id');
return function (doc) {
return {result: EJSON.equals(doc._id, selector)};
};
}
// protect against dangerous selectors. falsey and {_id: falsey} are both
// likely programmer error, and not what you want, particularly for
// destructive operations.
if (!selector || (('_id' in selector) && !selector._id)) {
self._isSimple = false;
return nothingMatcher;
}
// Top level can't be an array or true or binary.
if (typeof(selector) === 'boolean' || isArray(selector) ||
EJSON.isBinary(selector))
throw new Error("Invalid selector: " + selector);
self._selector = EJSON.clone(selector);
return compileDocumentSelector(selector, self, {isRoot: true});
} | 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 (typeof v === "function")
return 13;
if (_.isDate(v))
return 9;
if (EJSON.isBinary(v))
return 5;
if (v instanceof LocalCollection._ObjectID)
return 7;
return 3; // object
// XXX support some/all of these:
// 14, symbol
// 15, javascript code with scope
// 16, 18: 32-bit/64-bit integer
// 17, timestamp
// 255, minkey
// 127, maxkey
} | 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) {
++negatives;
} else {
dst[0] = '';
}
} else if (part !== '.' && (dsti === 0 || keepBlanks || part !== '')) {
dst[dsti++] = part;
}
}
if (negatives) {
dst[--negatives] = dst[dsti-1];
dsti = negatives + 1;
while (negatives--) { dst[negatives] = '..'; }
}
dst.length = dsti;
return dst;
} | 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) === '/') {
url = u + normalizeArray(url.split('/')).join('/');
} else {
path += ((path.charAt(path.length-1) === '/') ? '' : '/../') + url;
url = u + normalizeArray(path.split('/')).join('/');
}
}
return url;
} | 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]);
}
}
const ps = {};
ps.time = time;
ps.serverId = param.serverId;
ps.serverType = ps.serverId.split('-')[0];
ps.pid = param.pid;
const pid = ps.pid;
ps.cpuAvg = outValueArray[1];
ps.memAvg = outValueArray[2];
ps.vsz = outValueArray[3];
ps.rss = outValueArray[4];
outValueArray = [];
if (process.platform === 'darwin') {
ps.usr = 0;
ps.sys = 0;
ps.gue = 0;
cb(null, ps);
return;
}
exec(`pidstat -p ${pid}`, (err, output) => {
if (err) {
console.error('the command pidstat failed! ', err.stack);
return;
}
const _outArray = output.toString().replace(/^\s+|\s+$/g, '').split(/\s+/);
for (let i = 0; i < _outArray.length; i++) {
if ((!isNaN(_outArray[i]))) {
outValueArray.push(_outArray[i]);
}
}
ps.usr = outValueArray[1];
ps.sys = outValueArray[2];
ps.gue = outValueArray[3];
cb(null, ps);
});
} | javascript | {
"resource": ""
} |
q38399 | slice | train | function slice(toToken) {
if (has(toToken) && !isLast(toToken)) {
_tokens = _tokens.slice(0, _tokens.lastIndexOf(toToken) + 1);
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.