_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...
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, listenerNa...
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); }); ...
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] = {}; ...
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 + ...
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)) { ...
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; // currentl...
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 ...
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(randomFu...
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.cont...
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; ...
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( ...
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,...
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') + ' ';...
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 f...
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, 'Java...
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...
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({ g...
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 stor...
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...
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('ri...
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(paddin...
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, --s...
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.isDirector...
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}, f...
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)) {...
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: '...
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) skipCo...
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,...
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.wri...
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 ' ...
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 opti...
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 * ...
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; ...
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')...
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', () => { ...
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} */ ...
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 n...
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">'; ...
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]; ...
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(squa...
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); ...
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; }...
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);...
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 = word...
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(f...
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(expressio...
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') { contentt...
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; bo...
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; ...
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...
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]; ...
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...
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...
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) { ...
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, wra...
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); ...
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 = argumen...
javascript
{ "resource": "" }