_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q38500 | train | function(id, callback) {
var url = '/resources/' + ProcessrUtil.encodeURIComponent(id);
return processr._request('GET', url, null, callback);
} | javascript | {
"resource": ""
} | |
q38501 | onReadystatechange | train | function onReadystatechange(e) {
if (!(e instanceof Event)) {
throw new TypeError('Invalid event was given');
}
if (document.readyState == 'interactive') {
makeReady.call(this);
}
if (document.readyState == 'complete') {
makeLoaded.call(this);
}
} | javascript | {
"resource": ""
} |
q38502 | check | train | function check() {
var el,
i;
// Return early if no elements need to be checked
if (!elements.length) {
return;
}
for (i = 0; i < elements.length; i++) {
el = elements[i];
if (el.isVisible(options.padding)) {
if (live) {
el.classList.remove(query);
} else {
elements.splice(i, 1);
}
i--;
callback(el);
// If delay_callback is true,
// wait until the next check to call another item
if (options.delay_callback) {
req();
break;
}
}
}
// Stop all future checks if no elements are left and it's not live
if (!live && !elements.length) {
document.removeEventListener('wheel', req);
document.removeEventListener('click', req);
document.removeEventListener('scroll', req);
that.removeListener('rendered', req);
clearInterval(intervalId);
queue.destroy();
}
} | javascript | {
"resource": ""
} |
q38503 | train | function(clazz, metaData) {
this.applyEvents(clazz, metaData.clazz_events || {});
this.applyEvents(clazz.prototype, metaData.events || {});
} | javascript | {
"resource": ""
} | |
q38504 | train | function(object, events) {
if (!object.__isInterfaceImplemented('events')) {
object.__implementInterface('events', this.interface);
}
object.__initEvents();
_.each(events, function(eventListeners, eventName) {
_.each(eventListeners, function(listener, listenerName) {
object.__addEventListener(eventName, listenerName, listener);
});
});
} | javascript | {
"resource": ""
} | |
q38505 | train | function(event /* params */) {
var listeners;
var that = this;
var params = _.toArray(arguments).slice(1);
listeners = this.__getEventListeners(event);
_.each(listeners, function(listener) {
listener.apply(that, params);
});
listeners = this.__getEventListeners('event.emit');
_.each(listeners, function(listener) {
listener.call(that, event, params);
});
return this;
} | javascript | {
"resource": ""
} | |
q38506 | train | function(event, name, callback) {
if (this.__hasEventListener(event, name)) {
throw new Error('Event listener for event "' + event + '" with name "' + name + '" already exist!');
}
if (!(event in this.__events)) {
this.__events[event] = {};
}
this.__events[event][name] = callback;
return this;
} | javascript | {
"resource": ""
} | |
q38507 | train | function(event, name) {
var that = this;
if (!(event in that.__events)) {
that.__events[event] = {};
}
if (!_.isUndefined(name)) {
if (!that.__hasEventListener(event, name)) {
throw new Error('There is no "' + event + (name ? '"::"' + name : '') + '" event callback!');
}
that.__events[event][name] = undefined;
}
else {
_.each(that.__getEventListeners(event), function(listener, name) {
that.__events[event][name] = undefined;
});
}
return that;
} | javascript | {
"resource": ""
} | |
q38508 | train | function(event, name) {
var eventListeners = this.__getEventListeners(event);
if (!(name in eventListeners)) {
throw new Error('Event listener for event "' + event + '" with name "' + name + '" does not exist!');
}
return eventListeners[event][name];
} | javascript | {
"resource": ""
} | |
q38509 | train | function(event) {
var events = this.__collectAllPropertyValues.apply(this, ['__events', 2].concat(event || []));
_.each(events, function(eventsListeners) {
_.each(eventsListeners, function(listener, listenerName) {
if (_.isUndefined(listener)) {
delete eventsListeners[listenerName];
}
})
});
return event ? events[event] || {} : events;
} | javascript | {
"resource": ""
} | |
q38510 | ScriptManager | train | function ScriptManager() {
// child process
this.ps = null;
// script execution limit in milliseconds
this._limit = 5000;
// flag determining if a script is busy executing
this._busy = false;
// flag determining if script execution issued
// any write commands
this._written = false;
// currently executing script name
this._script = null;
// injected reference to the command handlers
this._commands = {};
// script limit timeout listener
this.onTimeout = this.onTimeout.bind(this);
} | javascript | {
"resource": ""
} |
q38511 | load | train | function load(req, res, source) {
this.spawn();
this.reply(req, res);
this.ps.send({event: 'load', source: source});
} | javascript | {
"resource": ""
} |
q38512 | eval | train | function eval(req, res, source, args) {
this.spawn();
this.reply(req, res, this._limit);
// need to coerce buffers for the moment
args = args.map(function(a) {
if(a instanceof Buffer) return a.toString();
return a;
})
this.ps.send({event: 'eval', source: source, args: args});
} | javascript | {
"resource": ""
} |
q38513 | evalsha | train | function evalsha(req, res, sha, args) {
this.spawn();
this.reply(req, res, this._limit);
// need to coerce buffers for the moment
args = args.map(function(a) {
if(a instanceof Buffer) return a.toString();
return a;
})
this.ps.send({event: 'evalsha', sha: sha, args: args});
} | javascript | {
"resource": ""
} |
q38514 | flush | train | function flush(req, res) {
this.spawn();
this.reply(req, res);
this.ps.send({event: 'flush'});
} | javascript | {
"resource": ""
} |
q38515 | kill | train | function kill(req, res) {
if(!this._busy || !this.ps) return res.send(NotBusy);
if(this._busy && this._written) return res.send(Unkillable);
this.ps.removeAllListeners();
this._busy = false;
this._written = false;
function onClose() {
res.send(null, Constants.OK);
// re-spawn for next execution
//this.spawn();
}
this.ps.once('close', onClose.bind(this))
process.kill(this.ps.pid, 'SIGQUIT');
this.emit('kill');
} | javascript | {
"resource": ""
} |
q38516 | train | function() {
var firstName = Math.round((firstNames.length - 1) * randomFunc());
var lastName = Math.round((lastNames.length - 1) * randomFunc());
var pets = Math.round(10 * randomFunc());
var birthyear = 1900 + Math.round(randomFunc() * 114);
var birthmonth = Math.round(randomFunc() * 11);
var birthday = Math.round(randomFunc() * 29);
var birthstate = Math.round(randomFunc() * 49);
var residencestate = Math.round(randomFunc() * 49);
var travel = randomFunc() * 1000;
var income = randomFunc() * 100000;
var employed = Math.round(randomFunc());
var person = {
last_name: lastNames[lastName],
//jshint ignore:line
first_name: firstNames[firstName],
//jshint ignore:line
pets: pets,
birthDate: birthyear + '-' + months[birthmonth] + '-' + days[birthday],
birthState: states[birthstate],
residenceState: states[residencestate],
employed: employed === 1,
income: income,
travel: travel
};
return person;
} | javascript | {
"resource": ""
} | |
q38517 | HTTPParser | train | function HTTPParser(channelContext, context) {
_classCallCheck(this, HTTPParser);
if (channelContext) {
this._channelContext = channelContext;
channelContext[SERVER.Capabilities][HTTP.CAPABILITY].incoming = [];
channelContext[SERVER.Capabilities][HTTP.CAPABILITY].currentIncoming = null;
}
this.context = context || this._createNewRequest();
this.context[HTTP.SkipBody] = false;
this.context[HTTP.ShouldKeepAlive] = true;
this.context[IOPA.Trailers] = [];
this._state = 'HTTP_LINE';
this._upgrade = false;
this._line = '';
this._isChunked = false;
this._connection = '';
this._headerSize = 0;
this._contentLength = null;
// this._currentChunk;
// this._offset;
// this._end;
} | javascript | {
"resource": ""
} |
q38518 | write | train | async function write(path, data) {
if (!path) throw new Error('No path is given.')
const er = erotic(true)
const ws = createWriteStream(path)
await new Promise((r, j) => {
ws
.on('error', (e) => {
const err = er(e)
j(err)
})
.on('close', r)
.end(data)
})
} | javascript | {
"resource": ""
} |
q38519 | validate | train | function validate(cmd, args, info) {
AbstractCommand.prototype.validate.apply(this, arguments);
var i
, num;
if((args.length - 1) % 2 !== 0) {
throw new CommandArgLength(cmd);
}
for(i = 1;i < args.length;i += 2) {
num = parseFloat('' + args[i]);
if(isNaN(num)) {
throw InvalidFloat;
}
args[i] = num;
}
} | javascript | {
"resource": ""
} |
q38520 | distinctElements | train | function distinctElements(a1,a2){
var ret = a1.slice();
a2.forEach(function(a2item){
if(ret.indexOf(a2item)<0){
ret.push(a2item);
}
});
return ret;
} | javascript | {
"resource": ""
} |
q38521 | stringToRegexp | train | function stringToRegexp (path, keys, options) {
var tokens = parse(path)
var re = tokensToRegExp(tokens, options)
// Attach keys back to the regexp.
for (var i = 0; i < tokens.length; i++) {
if (typeof tokens[i] !== 'string') {
keys.push(tokens[i])
}
}
return attachKeys(re, keys)
} | javascript | {
"resource": ""
} |
q38522 | looseEqual | train | function looseEqual (a, b) {
/* eslint-disable eqeqeq */
return a == b || (
isObject(a) && isObject(b)
? JSON.stringify(a) === JSON.stringify(b)
: false
)
/* eslint-enable eqeqeq */
} | javascript | {
"resource": ""
} |
q38523 | mergeData | train | function mergeData (to, from) {
var key, toVal, fromVal;
for (key in from) {
toVal = to[key];
fromVal = from[key];
if (!hasOwn(to, key)) {
set(to, key, fromVal);
} else if (isObject(toVal) && isObject(fromVal)) {
mergeData(toVal, fromVal);
}
}
return to
} | javascript | {
"resource": ""
} |
q38524 | normalizeComponents | train | function normalizeComponents (options) {
if (options.components) {
var components = options.components;
var def;
for (var key in components) {
var lower = key.toLowerCase();
if (isBuiltInTag(lower) || config.isReservedTag(lower)) {
"development" !== 'production' && warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + key
);
continue
}
def = components[key];
if (isPlainObject(def)) {
components[key] = Vue$3.extend(def);
}
}
}
} | javascript | {
"resource": ""
} |
q38525 | updateDOMListeners | train | function updateDOMListeners (oldVnode, vnode) {
if (!oldVnode.data.on && !vnode.data.on) {
return
}
var on = vnode.data.on || {};
var oldOn = oldVnode.data.on || {};
var add = vnode.elm._v_add || (vnode.elm._v_add = function (event, handler, capture) {
vnode.elm.addEventListener(event, handler, capture);
});
var remove = vnode.elm._v_remove || (vnode.elm._v_remove = function (event, handler) {
vnode.elm.removeEventListener(event, handler);
});
updateListeners(on, oldOn, add, remove, vnode.context);
} | javascript | {
"resource": ""
} |
q38526 | removeClass | train | function removeClass (el, cls) {
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); });
} else {
el.classList.remove(cls);
}
} else {
var cur = ' ' + el.getAttribute('class') + ' ';
var tar = ' ' + cls + ' ';
while (cur.indexOf(tar) >= 0) {
cur = cur.replace(tar, ' ');
}
el.setAttribute('class', cur.trim());
}
} | javascript | {
"resource": ""
} |
q38527 | Printr | train | function Printr(options) {
options = options || {};
options.out = options.out || process.stdout;
options.err = options.err || process.stderr;
options.prefix = options.prefix || '';
this.options = options;
} | javascript | {
"resource": ""
} |
q38528 | train | function (key, obj) {
//Split key
var p = key.split('.');
//Loop and save object state
for (var i = 0, len = p.length; i < len - 1; i++) {
obj = obj[p[i]];
}
//Return object value
return obj[p[len - 1]];
} | javascript | {
"resource": ""
} | |
q38529 | train | function () {
//Init Var
var length = 0;
//Loop filenames
$.each(config.data, function () {
length++;
});
//If value of length is equal to filenames length,
// return true, if not, return false
if (length === config.filenames.length) {
return true;
} else {
return false;
}
} | javascript | {
"resource": ""
} | |
q38530 | train | function (key) {
var string = key.split('.');
string.shift(0);
var value = string.join('.');
return value;
} | javascript | {
"resource": ""
} | |
q38531 | DependenciesNotResolvedError | train | function DependenciesNotResolvedError(dependencies){
superError.call(
this,
'DependenciesNotResolvedError',
util.format('Dependencies cannot be resolved: %s', dependencies.join(','))
);
this.dependencies = dependencies;
} | javascript | {
"resource": ""
} |
q38532 | PathNotFoundError | train | function PathNotFoundError(path, sympath){
superError.call(
this,
'PathNotFoundError',
util.format('Path was not found in the tree: %s', sympath)
);
this.arrayPath = path;
this.sympath = sympath;
} | javascript | {
"resource": ""
} |
q38533 | CannotBuildDependencyGraphError | train | function CannotBuildDependencyGraphError(nestedError){
this.name = 'CannotBuildDependencyGraphError';
this.message = nestedError.message;
this.stack = nestedError.stack;
this.nestedError = nestedError;
} | javascript | {
"resource": ""
} |
q38534 | JavaScriptFileLoadError | train | function JavaScriptFileLoadError(file, nestedError){
nestedError = nestedError || null;
var message = (nestedError)?
util.format('"%s" failed to load as JavaScript; VM error: %s', file, nestedError.toString()) :
util.format('"%s" failed to load as JavaScript.', file);
superError.call(this, 'JavaScriptFileLoadError', message);
this.fsPath = file;
this.nestedError = nestedError;
} | javascript | {
"resource": ""
} |
q38535 | HttpRequestError | train | function HttpRequestError(nestedError, status, body){
nestedError = nestedError || null;
status = status || -1;
body = body || null;
superError.call(
this,
'HttpRequestError',
util.format('An error [%s] occurred requesting content from an HTTP source: %s', status, nestedError || body)
);
this.status = status;
this.body = body;
this.nestedError = nestedError;
} | javascript | {
"resource": ""
} |
q38536 | CannotParseTreeError | train | function CannotParseTreeError(errors){
superError.call(
this,
'CannotParseTreeError',
util.format('Could not parse the tree for metadata; errors: %s', JSON.stringify(errors))
);
this.errors = errors;
} | javascript | {
"resource": ""
} |
q38537 | prepend | train | function prepend (value, string) {
if (
value === null || value === undefined || value === '' ||
string === null || string === undefined
) {
return value
}
return string + value
} | javascript | {
"resource": ""
} |
q38538 | enable | train | function enable(options, cb) {
options = options || {};
var travis = new Travis({
version: '2.0.0',
// user-agent needs to start with "Travis"
// https://github.com/travis-ci/travis-ci/issues/5649
headers: {'user-agent': 'Travis: jonschlinkert/enable-travis'}
});
travis.auth.github.post({
github_token: options.GITHUB_OAUTH_TOKEN
}, function(err, res) {
if (err) return cb(err);
travis.authenticate({
access_token: res.access_token
}, function(err) {
if (err) return cb(err);
var segs = options.repo.split('/');
travis.repos(segs[0], segs[1]).get(function(err, res) {
if (err) return cb(err);
travis.hooks(res.repo && res.repo.id).put({
hook: {active: true}
}, function(err, content) {
if (err) return cb(err);
cb(null, content);
});
});
});
});
} | javascript | {
"resource": ""
} |
q38539 | ColorStepFilter | train | function ColorStepFilter()
{
core.AbstractFilter.call(this,
// vertex shader
null,
// fragment shader
fs.readFileSync(__dirname + '/colorStep.frag', 'utf8'),
// custom uniforms
{
step: { type: '1f', value: 5 }
}
);
} | javascript | {
"resource": ""
} |
q38540 | train | function(config, onload, onprogress, onerror) {
var character = new THREE.MD2Character();
character.onLoadComplete = function() {
if (onload) onload( character );
};
character.loadParts( config );
} | javascript | {
"resource": ""
} | |
q38541 | PostgreSQL | train | function PostgreSQL(config) {
var self = this;
config = protos.extend({
host: 'localhost',
port: 5432
}, config);
this.className = this.constructor.name;
this.config = config;
// Set client
this.client = new Client(config);
// Connect client
this.client.connect();
// Assign storage
if (typeof config.storage == 'string') {
this.storage = app.getResource('storages/' + config.storage);
} else if (config.storage instanceof protos.lib.storage) {
this.storage = config.storage;
}
// Set db
this.db = config.database;
// Only set important properties enumerable
protos.util.onlySetEnumerable(this, ['className', 'db']);
} | javascript | {
"resource": ""
} |
q38542 | init | train | function init(options) {
var fs = require('fs');
var path = require('path');
var rootdir = path.dirname(require.main);
var options = options || {
config: require(path.join(rootdir, 'config.json')),
root: rootdir,
callback: function (noop) {}
};
var def = {};
function ModulePaths (moduledir) {
this.moduledir = moduledir;
}
ModulePaths.prototype.then = function (accept, reject) {
var moduledir = this.moduledir;
fs.readdir(moduledir, function (err, files) {
if (err) reject(err);
files.forEach(function (file) {
var name = path.basename(file, '.js');
def[name] = path.join(moduledir, name);
});
accept();
});
};
var pubpath = new ModulePaths(path.join(path.dirname(module.filename), '..', 'public', 'js'));
var prvpath = new ModulePaths(path.join(path.dirname(module.filename), '..', 'private', 'js'));
Promise.all([pubpath, prvpath])
.then(function () {
var requirejs = require('requirejs');
requirejs.config({
baseUrl: path.join(rootdir),
paths: def
});
requirejs(['loader_factory'], function (LoaderFactory) {
var fs = require('fs');
var config = options.config;
config.paths.push(path.dirname(pubpath.moduledir));
var loader = 'loader_express';
var db = 'db_mongo';
if (config.loader) loader = config.loader;
if (config.db) db = config.db;
new LoaderFactory().create(loader, db, function (loader) {
loader.init(config, options.callback);
});
});
})
.catch(function (err) {
console.error('err:', err);
});
} | javascript | {
"resource": ""
} |
q38543 | Button | train | function Button (hardware, callback) {
var self = this;
// Set hardware connection of the object
self.hardware = hardware;
// Object properties
self.delay = 100;
self.pressed = false;
// Begin listening for events
self.hardware.on('fall', function () {
self._press();
});
self.hardware.on('rise', function () {
self._release();
});
// Make sure the events get emitted, even if late
setInterval(function () {
if(!self.hardware.read()) {
self._press();
} else {
self._release();
}
}, self.delay);
// Emit the ready event when everything is set up
setImmediate(function emitReady() {
self.emit('ready');
});
// Call the callback with object
if (callback) {
callback(null, self);
}
} | javascript | {
"resource": ""
} |
q38544 | formatOptionStrings | train | function formatOptionStrings(options, width) {
var totalWidth = (width < process.stdout.columns) ? width : process.stdout.columns;
var paddingWidth = cliOptions.largestOptionLength() + 6;
var stringWidth = totalWidth - paddingWidth;
if (stringWidth <= 0) {
return;
}
var paddingString = '\n' + (new Array(paddingWidth - 3)).join(' ');
for (var i = 0; i < options.length; i++) {
var option = options[i];
// Separate description by width taking words into consideration
var description = option.description;
var splitDescription = [];
while (description) {
if (description.length <= stringWidth) {
splitDescription.push(description);
description = '';
continue;
}
var lastSpaceI = description.lastIndexOf(' ', stringWidth);
if (lastSpaceI < 0) {
splitDescription.push(description);
description = "";
break;
}
var stringChunk = description.substring(0, lastSpaceI);
description = description.substring(lastSpaceI + 1);
splitDescription.push(stringChunk);
}
// Reconstruct description with correct padding
option.description = splitDescription.join(paddingString);
}
} | javascript | {
"resource": ""
} |
q38545 | setupCliObject | train | function setupCliObject(argv) {
// Set cli options
cliOptions
.version(packageJson.version)
.usage('[options] <component_path ...>')
.option('-v, --verbose',
'Be verbose during tests. (cannot be used with --quiet or --silent)')
.option('-q, --quiet',
'Display only the final outcome.')
.option('-s, --silent',
'Suppress all output.')
.option('-r, --recursive',
'Recurse into local and external dependencies.')
.option('-d, --dep-paths <paths>',
'Colon separated list of paths to external dependencies. (default: "./components")')
.option('-w, --warn-paths <paths>',
'Colon separated list of paths where component errors will be converted to warnings. (supports minimatch globbing)')
.option('-i, --ignore-paths <paths>',
'Colon separated list of paths component-hint should ignore. (supports minimatch globbing)')
.option('-l, --lookup-paths <paths>',
'Colon separated list of paths to check for the existence of missing local ' +
'dependencies. This is used to give the user a hint where they can find them.')
.option(' --reporter <path>',
'Path to reporter file to use for output formatting.',
path.join(__dirname, './reporters/default.js'));
// Cleanup option strings and re-format them
formatOptionStrings(cliOptions.options, 100);
// Add additional info at the bottom of our help
cliOptions.on('--help', function () {
var scriptName = path.basename(argv[1]);
process.stdout.write(' Examples:\n');
process.stdout.write('\n');
process.stdout.write(' Check multiple component entry points\n');
process.stdout.write(' $ ' + scriptName + ' /path/to/single/component /path/to/another/component\n');
process.stdout.write('\n');
process.stdout.write(' Check multiple component entry point which exist in the same folder\n');
process.stdout.write(' $ ' + scriptName + ' /path/to/multiple/component/folder/*/\n');
process.stdout.write('\n');
});
// Parse arguments
cliOptions.parse(argv);
} | javascript | {
"resource": ""
} |
q38546 | ensurePathsExist | train | function ensurePathsExist(pathsList, cb) {
async.eachLimit(pathsList, 10, function (pathItem, callback) {
var absolutePath = path.resolve(pathItem);
fs.stat(absolutePath, function (error, stats) {
if (error) {
return callback(new Error('Path does not exist: ' + absolutePath));
}
if (!stats.isDirectory()) {
return callback(new Error('Path is not a directory: ' + absolutePath));
}
return callback();
});
}, cb);
} | javascript | {
"resource": ""
} |
q38547 | createSocket | train | function createSocket(type, receive)
{
try{ // newer
var sock = dgram.createSocket({ type: type, reuseAddr: true }, receive);
}catch(E){ // older
var sock = dgram.createSocket(type, receive);
}
return sock;
} | javascript | {
"resource": ""
} |
q38548 | receive | train | function receive(msg, rinfo){
var packet = lob.decloak(msg);
if(!packet) packet = lob.decode(msg); // accept un-encrypted discovery broadcast hints
if(!packet) return mesh.log.info('dropping invalid packet from',rinfo,msg.toString('hex'));
tp.pipe(false, {type:'udp4',ip:rinfo.address,port:rinfo.port}, function(pipe){
mesh.receive(packet, pipe);
});
} | javascript | {
"resource": ""
} |
q38549 | findById | train | function findById(schemaName, id) {
return new Promise(function(resolve, reject) {
var Model = db.mongoose.model(schemaName);
Model
.findById(id)
.exec(function(error, result) {
if (error) {
reqlog.error('internal server error', error);
reject(error);
} else {
resolve(result || 'notFound');
}
});
});
} | javascript | {
"resource": ""
} |
q38550 | getInstanceNameFromElement | train | function getInstanceNameFromElement(element) {
let nameFromName = getAttribute(element, 'name');
if (nameFromName !== null && nameFromName !== undefined && nameFromName !== '')
return nameFromName;
else
return null;
} | javascript | {
"resource": ""
} |
q38551 | train | function (lines, cb) {
fs.stat(HOSTS, function (err, stat) {
if (err) {
cb(err);
} else {
var s = fs.createWriteStream(HOSTS, { mode: stat.mode });
s.on('close', cb);
s.on('error', cb);
lines.forEach(function (line, lineNum) {
if (Array.isArray(line)) {
line = line[0] + ' ' + line[1];
}
s.write(line + (lineNum === lines.length - 1 ? '' : EOL));
});
s.end();
}
});
} | javascript | {
"resource": ""
} | |
q38552 | getBody | train | function getBody(id, arr) {
var result = []
// heading and location: 'Anomaly 2012-08-11T03:23:49.725Z'
var now = new Date
result.push('Anomaly ' + now.toISOString() + ' ' + haraldutil.getISOPacific(now))
if (id) result.push()
result.push('host:' + os.hostname() +
' app:' + (opts.app || 'unknown') +
' api: ' + (id || 'unknown')) +
' pid: ' + process.pid
// output each provided argument
arr.forEach(function (value, index) {
result.push((index + 1) + ': ' + haraldutil.inspectDeep(value))
})
// a stack trace for the invocation of anomaly
var o = haraldutil.parseTrace(new Error)
if (o && Array.isArray(o.frames)) {
result.push('Anomaly invoked from:')
for (var ix = 2; ix < o.frames.length; ix++) {
var frame = o.frames[ix]
var s = [' ']
if (frame.func) s.push(frame.func)
if (frame.as) s.push('as:', frame.as)
if (frame.file) s.push(frame.file + ':' + frame.line + ':' + frame.column)
if (frame.folder) s.push(frame.folder)
if (frame.source) s.push('source:', frame.source)
result.push(s.join(' '))
}
}
return result.join('\n')
} | javascript | {
"resource": ""
} |
q38553 | sendQueue | train | function sendQueue() {
var subject = ['Anomaly Report']
if (!opts.noSubjectApp && opts.app) subject.push(opts.app)
if (!opts.noSubjectHost) subject.push(os.hostname())
subject = subject.join(' ')
var body
if (skipCounter > 0) { // notify of skipped emails
enqueuedEmails.push('Skipped:' + skipCounter)
skipCounter = 0
}
body = enqueuedEmails.join('\n\n')
enqueuedEmails = []
emailer.send({subject: subject, body: body}) // TODO error handling when haraldops and emailer updated
lastSent = Date.now()
startSilentPeriod()
} | javascript | {
"resource": ""
} |
q38554 | EventEmitter | train | function EventEmitter() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, EventEmitter);
this._events = {};
if (opts.async) this.emit = emitAsync;
} | javascript | {
"resource": ""
} |
q38555 | train | function(method, model, options) {
options = options || {};
var self = this;
var db;
if (!(self instanceof Db)) {
db = model.db || options.db;
debug('using db from model');
} else {
debug('using self as database');
db = self;
}
debug('sync %s %s %s %s',
method,
model.type,
JSON.stringify(model.toJSON(options)),
JSON.stringify(options)
);
var start = Date.now();
function callback(err, res, resp) {
debug('callback ' + err + ' ' + JSON.stringify(res));
var elapsed = Date.now() - start;
var syncInfo = {
method: method,
type: model.type,
elapsed: elapsed,
model: model.toJSON(options),
res: JSON.stringify(res)
};
if (err) {
syncInfo.error = err;
}
if (options && options.where) {
syncInfo.where = _.clone(options.where);
}
if (db.trigger) {
db.trigger('sync_info', syncInfo);
}
if ((err && options.error) || (!err && !res && options.error)) {
var errorMsg = pff('%s (%s) not found', model.type, model.id);
err = err || new errors.NotFoundError(errorMsg);
return options.error(err, resp);
} else if (options.success && res) {
debug('success %s', JSON.stringify(res));
return options.success(res, resp);
}
}
switch (method) {
case 'create':
return db.create(model, options, callback);
case 'update':
return db.update(model, options, callback);
case 'delete':
return db.destroy(model, options, callback);
case 'read':
if (typeof model.get(model.idAttribute) !== 'undefined') {
return db.find(model, options, callback);
}
return db.findAll(model, options, callback);
default:
throw new Error('method ' + method + ' not supported');
}
} | javascript | {
"resource": ""
} | |
q38556 | hook | train | function hook(req, res, next) {
var _end = res.end;
var _write = res.write;
//var _on = res.on;
res.write = function(chunk, encoding) {
// ... other things
// Call the original
_write.call(this, chunk, encoding);
// Note: in some cases, you have to restore the function:
// res.write = _write;
};
res.end = function(chunk, encoding) {
// ... other things
// Call the original
_end.call(this, chunk, encoding);
// Note: in some cases, you have to restore the function:
// res.end = _end;
};
return next();
} | javascript | {
"resource": ""
} |
q38557 | inferEndpoint | train | function inferEndpoint(f, y, lower, e) {
var comp; // comparison of f(e) and f(2*e)
if (e != null) { return e; }
e = lower ? -1 : 1;
comp = f(e) < f(2 * e);
while (f(e) > y !== comp) {
e *= 2;
if (-e > 1e200) {
throw new Error('Binary search: Cannot find ' + (lower ? 'lower' : 'upper') + ' endpoint.');
}
}
return e;
} | javascript | {
"resource": ""
} |
q38558 | getLoggerOptions | train | function getLoggerOptions() {
'use strict';
var defaultOptions = {
logger: {
level: 'info',
silent: false,
exitOnError: true,
logFile: ''
}
};
var loggerOptions = {};
// get the project's options
var projectOptions = getOptions.getProjectOptions();
// merge project options with default options; project options take precedence
var options = getOptions.mergeOptions(defaultOptions, projectOptions);
// check if we're unit testing
if (isTest()) {
options.logger.level = 'warn';
}
// basic transports from options
loggerOptions.transports = [
new winston.transports.Console({
level: options.logger.level,
silent: options.logger.silent,
colorize: true
})
];
// check if we should add a log file
if (options.logger.logFile) {
loggerOptions.transports.push(
new winston.transports.File({
filename: options.logger.logFile,
level: options.logger.level
})
);
}
loggerOptions.exitOnError = options.logger.exitOnError;
return loggerOptions;
} | javascript | {
"resource": ""
} |
q38559 | Rope | train | function Rope(texture, points)
{
Mesh.call(this, texture);
/*
* @member {Array} An array of points that determine the rope
*/
this.points = points;
/*
* @member {Float32Array} An array of vertices used to construct this rope.
*/
this.vertices = new Float32Array(points.length * 4);
/*
* @member {Float32Array} The WebGL Uvs of the rope.
*/
this.uvs = new Float32Array(points.length * 4);
/*
* @member {Float32Array} An array containing the color components
*/
this.colors = new Float32Array(points.length * 2);
/*
* @member {Uint16Array} An array containing the indices of the vertices
*/
this.indices = new Uint16Array(points.length * 2);
this.refresh();
} | javascript | {
"resource": ""
} |
q38560 | train | function(opts) {
var performance = window.performance || window.webkitPerformance || window.msPerformance || window.mozPerformance;
if (performance === undefined) {
//console.log('Unfortunately, your browser does not support the Navigation Timing API');
return;
}
var timing = performance.timing;
var api = {};
opts = opts || {};
if (timing) {
if(opts && !opts.simple) {
for (var k in timing) {
if (timing.hasOwnProperty(k)) {
api[k] = timing[k];
}
}
}
// Time to first paint
if (api.firstPaint === undefined) {
// All times are relative times to the start time within the
// same objects
var firstPaint = 0;
// Chrome
if (window.chrome && window.chrome.loadTimes) {
// Convert to ms
firstPaint = window.chrome.loadTimes().firstPaintTime * 1000;
api.firstPaintTime = firstPaint - (window.chrome.loadTimes().startLoadTime*1000);
}
// IE
else if (typeof window.performance.timing.msFirstPaint === 'number') {
firstPaint = window.performance.timing.msFirstPaint;
api.firstPaintTime = firstPaint - window.performance.timing.navigationStart;
}
// Firefox
// This will use the first times after MozAfterPaint fires
//else if (window.performance.timing.navigationStart && typeof InstallTrigger !== 'undefined') {
// api.firstPaint = window.performance.timing.navigationStart;
// api.firstPaintTime = mozFirstPaintTime - window.performance.timing.navigationStart;
//}
if (opts && !opts.simple) {
api.firstPaint = firstPaint;
}
}
// Total time from start to load
api.loadTime = timing.loadEventEnd - timing.fetchStart;
// Time spent constructing the DOM tree
api.domReadyTime = timing.domComplete - timing.domInteractive;
// Time consumed preparing the new page
api.readyStart = timing.fetchStart - timing.navigationStart;
// Time spent during redirection
api.redirectTime = timing.redirectEnd - timing.redirectStart;
// AppCache
api.appcacheTime = timing.domainLookupStart - timing.fetchStart;
// Time spent unloading documents
api.unloadEventTime = timing.unloadEventEnd - timing.unloadEventStart;
// DNS query time
api.lookupDomainTime = timing.domainLookupEnd - timing.domainLookupStart;
// TCP connection time
api.connectTime = timing.connectEnd - timing.connectStart;
// Time spent during the request
api.requestTime = timing.responseEnd - timing.requestStart;
// Request to completion of the DOM loading
api.initDomTreeTime = timing.domInteractive - timing.responseEnd;
// Load event time
api.loadEventTime = timing.loadEventEnd - timing.loadEventStart;
}
return api;
} | javascript | {
"resource": ""
} | |
q38561 | train | function(cb) {
var self = this
//set mainHtml
mainHtmlCache = fs.readFileSync(config.get('main_path'))
self.emit("STARTUP")
self.httpServer.listen(this.getConfig("port"), Meteor.bindEnvironment(function() {
Log.info('xiami server listeing at ' + self.getConfig('port'))
self.emit('STARTED')
self.isStarted = true
cb && cb()
}))
} | javascript | {
"resource": ""
} | |
q38562 | verifyHash | train | function verifyHash(correctHash, filepath) {
return calculateHash(filepath).then(hash => {
if (hash !== correctHash) {
throw new Error(`Incorrect checksum: expected ${correctHash}, got ${hash}`);
}
return true;
});
} | javascript | {
"resource": ""
} |
q38563 | calculateHash | train | function calculateHash(filepath) {
return new Promise((fulfill, reject) => {
const file = fs.createReadStream(filepath);
const hash = crypto.createHash('sha512');
hash.setEncoding('hex');
file.on('error', err => {
reject(err);
});
file.on('end', () => {
hash.end();
fulfill(hash.read());
});
file.pipe(hash);
});
} | javascript | {
"resource": ""
} |
q38564 | getRoot | train | function getRoot(i, list) {
for (var x = list.height; x > 0; x--) {
var slot = i >> x * _const.B;
while (list.sizes[slot] <= i) {
slot++;
}
if (slot > 0) {
i -= list.sizes[slot - 1];
}
list = list[slot];
}
return list[i];
} | javascript | {
"resource": ""
} |
q38565 | Promise | train | function Promise(fn) {
if (typeof this !== 'object') {
throw new TypeError('Promises must be constructed via new');
}
if (typeof fn !== 'function') {
throw new TypeError('not a function');
}
this._37 = 0;
this._12 = null;
this._59 = [];
if (fn === noop) return;
doResolve(fn, this);
} | javascript | {
"resource": ""
} |
q38566 | host | train | function host(){
var app = leachApp(connect())
for(var x in host.prototype)app[x] = host.prototype[x]
return app
} | javascript | {
"resource": ""
} |
q38567 | relay | train | function relay(evtName) {
sbDriver.on(evtName, (...evtArgs) => {
evtArgs.splice(0, 0, evtName);
console.log(json(evtArgs));
});
} | javascript | {
"resource": ""
} |
q38568 | Text | train | function Text(text, style, resolution)
{
/**
* The canvas element that everything is drawn to
*
* @member {HTMLCanvasElement}
*/
this.canvas = document.createElement('canvas');
/**
* The canvas 2d context that everything is drawn with
* @member {HTMLCanvasElement}
*/
this.context = this.canvas.getContext('2d');
/**
* The resolution of the canvas.
* @member {number}
*/
this.resolution = resolution || CONST.RESOLUTION;
/**
* Private tracker for the current text.
*
* @member {string}
* @private
*/
this._text = null;
/**
* Private tracker for the current style.
*
* @member {object}
* @private
*/
this._style = null;
var texture = Texture.fromCanvas(this.canvas);
texture.trim = new math.Rectangle();
Sprite.call(this, texture);
this.text = text;
this.style = style;
} | javascript | {
"resource": ""
} |
q38569 | getDataRegistry | train | function getDataRegistry(identifier) {
assert(!identifier || (typeof identifier === 'string'), `Invalid identifier specified: ${identifier}`);
if (!window.__private__) window.__private__ = {};
if (window.__private__.dataRegistry === undefined) window.__private__.dataRegistry = {};
if (identifier)
return namespace(identifier, window.__private__.dataRegistry);
else if (identifier === null)
return null
else
return window.__private__.dataRegistry;
} | javascript | {
"resource": ""
} |
q38570 | train | function (el, puzzle) {
var output = '';
// for each row in the puzzle
for (var i = 0, height = puzzle.length; i < height; i++) {
// append a div to represent a row in the puzzle
var row = puzzle[i];
output += '<div class="wordsRow">';
// for each element in that row
for (var j = 0, width = row.length; j < width; j++) {
// append our button with the appropriate class
output += '<button class="puzzleSquare" x="' + j + '" y="' + i + '">';
output += row[j] || ' ';
output += '</button>';
}
// close our div that represents a row
output += '</div>';
}
$(el).html(output);
} | javascript | {
"resource": ""
} | |
q38571 | train | function (target) {
// if the user hasn't started a word yet, just return
if (!startSquare) {
return;
}
// if the new square is actually the previous square, just return
var lastSquare = selectedSquares[selectedSquares.length - 1];
if (lastSquare == target) {
return;
}
// see if the user backed up and correct the selectedSquares state if
// they did
var backTo;
for (var i = 0, len = selectedSquares.length; i < len; i++) {
if (selectedSquares[i] == target) {
backTo = i + 1;
break;
}
}
while (backTo < selectedSquares.length) {
$(selectedSquares[selectedSquares.length - 1]).removeClass('selected');
selectedSquares.splice(backTo, 1);
curWord = curWord.substr(0, curWord.length - 1);
}
// see if this is just a new orientation from the first square
// this is needed to make selecting diagonal words easier
var newOrientation = calcOrientation($(startSquare).attr('x') - 0, $(startSquare).attr('y') - 0, $(target).attr('x') - 0, $(target).attr('y') - 0);
if (newOrientation) {
selectedSquares = [startSquare];
curWord = $(startSquare).text();
if (lastSquare !== startSquare) {
$(lastSquare).removeClass('selected');
lastSquare = startSquare;
}
curOrientation = newOrientation;
}
// see if the move is along the same orientation as the last move
var orientation = calcOrientation($(lastSquare).attr('x') - 0, $(lastSquare).attr('y') - 0, $(target).attr('x') - 0, $(target).attr('y') - 0);
// if the new square isn't along a valid orientation, just ignore it.
// this makes selecting diagonal words less frustrating
if (!orientation) {
return;
}
// finally, if there was no previous orientation or this move is along
// the same orientation as the last move then play the move
if (!curOrientation || curOrientation === orientation) {
curOrientation = orientation;
playTurn(target);
}
} | javascript | {
"resource": ""
} | |
q38572 | train | function (square) {
// make sure we are still forming a valid word
for (var i = 0, len = wordList.length; i < len; i++) {
if (wordList[i].indexOf(curWord + $(square).text()) === 0) {
$(square).addClass('selected');
selectedSquares.push(square);
curWord += $(square).text();
break;
}
}
} | javascript | {
"resource": ""
} | |
q38573 | train | function (e) {
// see if we formed a valid word
for (var i = 0, len = wordList.length; i < len; i++) {
if (wordList[i] === curWord) {
var selected = $('.selected');
selected.addClass('found');
wordList.splice(i, 1);
var color = e.data.colorHash.hex(curWord);
$('.' + curWord).addClass('wordFound');
for (var selectedIndex = 0, selectedLength = selected.length; selectedIndex < selectedLength; selectedIndex++) {
var current = $(selected[selectedIndex]), style = current.attr("style"), hasBC = style != undefined && style.search("background-color") != -1;
if (hasBC) {
current.css("border", "4px solid " + color);
}
else {
current.css("background-color", color);
}
}
$(e.data.puzzleEl).trigger("found", curWord);
$(e.data.wordsEl).append("<li class=\"" + curWord + " wordFound\"><i style=\"background-color:" + color + ";\"></i>" + curWord + "</li>");
}
if (wordList.length === 0) {
$('.puzzleSquare').off(".spl").addClass('complete');
$(e.data.puzzleEl).trigger("end");
}
}
// reset the turn
$('.selected').removeClass('selected');
startSquare = null;
selectedSquares = [];
curWord = '';
curOrientation = null;
} | javascript | {
"resource": ""
} | |
q38574 | train | function (x1, y1, x2, y2) {
for (var orientation in wordfind.orientations) {
var nextFn = wordfind.orientations[orientation];
var nextPos = nextFn(x1, y1, 1);
if (nextPos.x === x2 && nextPos.y === y2) {
return orientation;
}
}
return null;
} | javascript | {
"resource": ""
} | |
q38575 | train | function (words, puzzleEl, wordsEl, options, colorHash) {
wordList = words.slice(0).sort();
var puzzle = wordfind.newPuzzle(words, options);
// draw out all of the words
drawPuzzle(puzzleEl, puzzle);
var list = drawWords(wordsEl, wordList);
$('.puzzleSquare').on("mousedown.spl touchstart.spl", { puzzleEl: puzzleEl, colorHash: colorHash }, startTurn)
.on("touchmove.spl", { puzzleEl: puzzleEl, colorHash: colorHash }, touchMove)
.on("mouseup.spl touchend.spl", { puzzleEl: puzzleEl, wordsEl: list, colorHash: colorHash }, endTurn)
.on("mousemove.spl", { puzzleEl: puzzleEl, colorHash: colorHash }, mouseMove);
return puzzle;
} | javascript | {
"resource": ""
} | |
q38576 | train | function (puzzle, words, list, colorHash) {
var solution = wordfind.solve(puzzle, words).found;
for (var i = 0, len = solution.length; i < len; i++) {
var word = solution[i].word, orientation = solution[i].orientation, x = solution[i].x, y = solution[i].y, next = wordfind.orientations[orientation];
if (!$('.' + word).hasClass('wordFound')) {
var color = colorHash.hex(word);
list.append("<li class=\"" + word + "\"><i style=\"background-color:" + color + ";\"></i>" + word + "</li>");
for (var j = 0, size = word.length; j < size; j++) {
var nextPos = next(x, y, j);
//por cada letra de la palabra
//si no tiene bc
//se añade bc
//si tiene bc
//se añade un elemento hijo
//se añade el bc
var selected = $('[x="' + nextPos.x + '"][y="' + nextPos.y + '"]');
for (var selectedIndex = 0, selectedLength = selected.length; selectedIndex < selectedLength; selectedIndex++) {
var current = $(selected[selectedIndex]), childrens = current.find(".puzzleSquare"), item = childrens.length == 0 ? current : childrens.last(), style = item.attr("style"), hasBC = style != undefined && style.indexOf("background-color") - 1;
if (hasBC) {
var subItem = $("<span class='puzzleSquare'>" + item.text() + "</span>")
.css("background-color", color);
item.text("");
item.append(subItem);
}
else {
current.css("background-color", color);
}
}
selected.addClass('solved');
}
$('.' + word).addClass('wordFound');
}
}
$('.puzzleSquare').off(".spl").trigger("end");
} | javascript | {
"resource": ""
} | |
q38577 | initMongo | train | function initMongo(config, callback) {
var self = this;
// Set db
self.db = new Db(config.database, new Server(config.host, config.port, {}), {safe: true});
// Get client
self.db.open(function(err, client) {
if (err) throw err;
else {
self.client = client;
client.collectionNames(function(err, names) {
if (err) throw err;
else {
var name = config.database + '.' + config.collection;
var exists = names.filter(function(col) {
if (col.name == name) return col;
});
// Collection options
var opts = {capped: true, size: config.logSize};
if (config.logLimit != null) opts.max = config.logLimit;
if (exists.length === 0) {
client.createCollection(config.collection, opts, function(err, collection) {
if (err) throw err;
else {
self.collection = collection;
callback.call(self);
}
});
} else {
// Get collection
client.collection(config.collection, function(err, collection) {
if (err) throw err;
else {
self.collection = collection;
// Get collection options » Check if collection has already been capped
collection.options(function(err, options) {
if (err) {
throw err;
} else {
// Check if collection's options match log requirements
var ready = (options.capped === true && options.size === opts.size);
if ('max' in opts) ready = (ready && options.max === opts.max);
if (!ready) {
// Convert collection to capped if it's not match log requirements
var cmd = {"convertToCapped": config.collection, size: opts.size};
if ('max' in opts) cmd.max = opts.max;
client.command(cmd, function(err) {
if (err) throw err;
else {
callback.call(self);
}
});
} else {
callback.call(self);
}
}
});
}
});
}
}
});
}
});
} | javascript | {
"resource": ""
} |
q38578 | checkJSONExpression | train | function checkJSONExpression(expression, json) {
if (! (expression && json)) {
return false;
}
// array expressions never match non-arrays or arrays of a different length.
if (_.isArray(expression) && !(_.isArray(json) && expression.length === json.length)) {
return false;
}
return _.all(expression, function(v, k) {
// check "$" properties
if (k === "$not") return (! checkJSONExpression(v, json));
if (k === "$unordered") {
return v.length === json.length && arrayContains(json, v);
}
if (k === "$contains") {
return arrayContains(json, v);
}
if (k === "$length" ) return(v === json.length);
if (k === "$gt") return (json > v);
if (k === "$gte") return (json >= v);
if (k === "$lt") return (json < v);
if (k === "$lte") return (json <= v);
// check $not-exists
if (! _.has(json, k)) return (v === "$not-exists");
// check rest of "$" values.
if (v === "$exists") return _.has(json, k);
if (v === "$string") return _.isString(json[k]);
if (_.isRegExp(v)) return v.test(json[k]);
if (_.isObject(v)) return checkJSONExpression(v, json[k]);
if (v === "$date") {
try {
new Date(json[k]);
return true;
} catch (e) {
return false;
}
}
if (v === "$int") {
//http://stackoverflow.com/questions/3885817/how-to-check-if-a-number-is-float-or-integer
return (typeof json[k] === 'number' && json[k] % 1 === 0);
}
// check a strict equals
return (v === json[k]);
});
} | javascript | {
"resource": ""
} |
q38579 | POST_FILE | train | function POST_FILE(uri, params, filepath) {
var form = new FormData();
for (var i in params) {
form.append(i, params[i]);
}
let contenttype = 'INVALID';
if(filepath.split('.').pop().toLowerCase() == 'jpg') { contenttype = 'image/jpg' }
if(filepath.split('.').pop().toLowerCase() == 'png') { contenttype = 'image/png' }
if(filepath.split('.').pop().toLowerCase() == 'gif') { contenttype = 'image/gif' }
if(contenttype == 'INVALID') { throw 'Invalid image type.' }
let imageData = fs.readFileSync(filepath);
form.append('image', imageData, {
filename: filepath.split('/').pop(),
filepath: filepath,
contentType: contenttype,
knownLength: imageData.length
});
const requestURL = `${uri}`;
log(`request URL: ${requestURL}`);
return fetch(requestURL, { method: 'POST', compress: compress, body: form, headers: { 'Content-Type': 'multipart/form-data; boundary='+form.getBoundary() } })
.then(function handleRequest(res) {
const status = res.status;
if (status != 200) {
const error = new Error(`Request failed: ${status}`);
error.status = status;
throw error;
}
return res.json();
})
.catch(error => {
log(`error: ${error}`);
throw error;
});
} | javascript | {
"resource": ""
} |
q38580 | POST | train | function POST(uri, params) {
var form = new FormData();
for (var i in params) {
form.append(i, params[i]);
}
const requestURL = `${uri}`;
log(`request URL: ${requestURL}`);
return fetch(requestURL, { method: 'POST', compress: compress, body: form, headers: { 'Content-Type': 'multipart/form-data; boundary='+form.getBoundary() } })
.then(function handleRequest(res) {
const status = res.status;
if (status != 200) {
const error = new Error(`Request failed: ${status}`);
error.status = status;
throw error;
}
return res.json();
})
.catch(error => {
log(`error: ${error}`);
throw error;
});
} | javascript | {
"resource": ""
} |
q38581 | DELETE | train | function DELETE(uri, params) {
const requestURL = `${uri}${url.format({ query: params })}`;
log(`request URL: ${requestURL}`);
return fetch(requestURL, { method: 'DELETE', compress: compress })
.then(function handleRequest(res) {
const statusText = res.statusText;
const status = res.status;
if (status != 200) {
const error = new Error(`Request failed: ${statusText}`);
error.status = status;
throw error;
}
return res.json();
})
.catch(error => {
log(`error: ${error}`);
throw error;
});
} | javascript | {
"resource": ""
} |
q38582 | memoize | train | function memoize(key, val) {
if (cache.hasOwnProperty(key)) {
return cache[key];
}
return (cache[key] = val);
} | javascript | {
"resource": ""
} |
q38583 | castBuffer | train | function castBuffer (val) {
if (Buffer.isBuffer(val)) {
return val
}
val = toJSON(val)
var args = assertArgs([val], {
val: ['string', 'array', 'object', 'number', 'boolean']
})
val = args.val
var str
if (Array.isArray(val)) {
val = val.map(toJSON)
str = JSON.stringify(val)
} else if (isObject(val)) {
val = toJSON(val)
str = JSON.stringify(val)
} else { // val is a string, number, or boolean
str = val + ''
}
return new Buffer(str)
} | javascript | {
"resource": ""
} |
q38584 | train | function (value) {
if(value === undefined) return null;
if(value instanceof Date) {
return value;
}
var date = null, replace, regex, a = 0, length = helpers.date.regex.length;
value = value.toString();
for(a; a < length; a++) {
regex = helpers.date.regex[a];
if(value.match(regex.test)) {
if(regex.replace.indexOf("-") > -1){
replace = value.replace(regex.test, regex.replace).split("-");
date = new Date(parseInt(replace[0]), parseInt(--replace[1]), parseInt(replace[2]));
}
else {
replace = parseInt(value.replace(regex.test, regex.replace));
date = new Date(replace);
}
break;
}
}
return date;
} | javascript | {
"resource": ""
} | |
q38585 | train | function(format, value) {
var date = helpers.date.parse(value);
if(date === false || date === undefined) return false;
var day = date.getDate().toString().replace(/(?=(^\d{1}$))/g, "0");
var month = (date.getMonth() + 1).toString().replace(/(?=(^\d{1}$))/g, "0");
var formatDate = format
.replace(/dd/gi, day)
.replace(/mm/gi, month)
.replace(/yyyy/gi, date.getFullYear());
return formatDate;
} | javascript | {
"resource": ""
} | |
q38586 | saveModelSync | train | function saveModelSync (modelName, modelMetadata, modelDir) {
const buffer = `const Arrow = require('arrow')
var Model = Arrow.Model.extend('${modelName}', ${JSON.stringify(modelMetadata, null, '\t')})
module.exports = Model`
fs.writeFileSync(path.join(modelDir, modelMetadata.name.toLowerCase() + '.js'), buffer)
} | javascript | {
"resource": ""
} |
q38587 | ensureExistsAndClean | train | function ensureExistsAndClean (dir) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir)
} else {
cleanDir(dir)
}
} | javascript | {
"resource": ""
} |
q38588 | executable | train | function executable(value) {
var result;
try {
result = resolve(task.apply(this, arguments));
} catch (e) {
result = reject(e);
}
return result;
} | javascript | {
"resource": ""
} |
q38589 | parallel | train | function parallel(tasks) {
if (tasks == null) return promisen([]);
tasks = Array.prototype.map.call(tasks, wrap);
return all;
function all(value) {
var boundTasks = Array.prototype.map.call(tasks, run.bind(this, value));
return promisen.Promise.all(boundTasks);
}
// apply the first argument only. ignore rest.
function wrap(task) {
return promisen(task);
}
function run(value, func) {
return func.call(this, value);
}
} | javascript | {
"resource": ""
} |
q38590 | IF | train | function IF(condTask, trueTask, falseTask) {
condTask = (condTask != null) ? promisen(condTask) : promisen();
trueTask = (trueTask != null) ? promisen(trueTask) : promisen();
falseTask = (falseTask != null) ? promisen(falseTask) : promisen();
return conditional;
function conditional(value) {
var condFunc = condTask.bind(this, value);
var trueFunc = trueTask.bind(this, value);
var falseFunc = falseTask.bind(this, value);
return condFunc().then(switching);
function switching(condition) {
return condition ? trueFunc() : falseFunc();
}
}
} | javascript | {
"resource": ""
} |
q38591 | WHILE | train | function WHILE(condTask, runTask) {
var runTasks = Array.prototype.slice.call(arguments, 1);
runTasks.push(nextTask);
runTask = waterfall(runTasks);
var whileTask = IF(condTask, runTask);
return whileTask;
function nextTask(value) {
return whileTask.call(this, value);
}
} | javascript | {
"resource": ""
} |
q38592 | eachSeries | train | function eachSeries(arrayTask, iteratorTask) {
if (arrayTask == null) arrayTask = promisen();
iteratorTask = promisen(iteratorTask);
return waterfall([arrayTask, loopTask]);
// composite multiple tasks
function loopTask(arrayResults) {
arrayResults = Array.prototype.map.call(arrayResults, wrap);
return series(arrayResults).call(this);
}
function wrap(value) {
return iterator;
function iterator() {
return iteratorTask.call(this, value);
}
}
} | javascript | {
"resource": ""
} |
q38593 | each | train | function each(arrayTask, iteratorTask) {
if (arrayTask == null) arrayTask = promisen();
iteratorTask = promisen(iteratorTask);
return waterfall([arrayTask, loopTask]);
// composite multiple tasks
function loopTask(arrayResults) {
arrayResults = Array.prototype.map.call(arrayResults, wrap);
return parallel(arrayResults).call(this);
}
// apply the first argument only. ignore rest.
function wrap(value) {
return iterator;
function iterator() {
return iteratorTask.call(this, value);
}
}
} | javascript | {
"resource": ""
} |
q38594 | incr | train | function incr(array) {
return incrTask;
function incrTask() {
if (!array.length) {
Array.prototype.push.call(array, 0 | 0);
}
return resolve(++array[array.length - 1]);
}
} | javascript | {
"resource": ""
} |
q38595 | push | train | function push(array) {
return pushTask;
function pushTask(value) {
Array.prototype.push.call(array, value); // copy
return resolve(value); // through
}
} | javascript | {
"resource": ""
} |
q38596 | pop | train | function pop(array) {
return popTask;
function popTask() {
var value = Array.prototype.pop.call(array);
return resolve(value);
}
} | javascript | {
"resource": ""
} |
q38597 | top | train | function top(array) {
return topTask;
function topTask() {
var value = array[array.length - 1];
return resolve(value);
}
} | javascript | {
"resource": ""
} |
q38598 | wait | train | function wait(msec) {
return waitTask;
function waitTask(value) {
var that = this;
return new promisen.Promise(function(resolve) {
setTimeout(function() {
resolve.call(that, value);
}, msec);
});
}
} | javascript | {
"resource": ""
} |
q38599 | throttle | train | function throttle(task, concurrency, timeout) {
if (!concurrency) concurrency = 1;
task = promisen(task);
var queue = singleTask.queue = [];
var running = singleTask.running = {};
var serial = 0;
return singleTask;
function singleTask(value) {
var that = this;
var args = arguments;
var Promise = promisen.Promise;
var seq = ++serial;
return new Promise(function(resolve, reject) {
queue.push(job);
var timer = timeout && setTimeout(onTimeout, timeout);
next();
function job() {
if (timer) clearTimeout(timer);
running[seq] = true;
task.apply(that, args).then(onResolve, onReject);
}
function onTimeout() {
onReject(new Error("timeout: " + timeout + "ms"));
}
function onResolve(value) {
delete running[seq];
setTimeout(next, 0);
resolve(value);
}
function onReject(value) {
delete running[seq];
setTimeout(next, 0);
reject(value);
}
});
}
function next() {
if (Object.keys(running).length >= concurrency) return;
var job = queue.pop();
if (job) job();
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.