_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q24100
isKeepalive
train
function isKeepalive(req) { var conn = req.headers.connection; if (typeof(conn) === 'undefined' || conn === null) conn = ''; conn = conn.trim().toLowerCase(); if (/\bclose\b/i.test(conn)) return false; if (/\bkeep-alive\b/i.test(conn)) return true; // No Connection header. Default to keepalive for 1.1, non for 1.0. if (req.httpVersionMajor < 1 || req.httpVersionMinor < 1) { return false; } else { return true; } }
javascript
{ "resource": "" }
q24101
read_p
train
function read_p(path, schemaPath) { return Q.nfcall(fs.readFile, path, 'utf8') .then(function(cdata) { return Q.nfcall(fs.readFile, schemaPath, 'utf8') .then(function(sdata) { return schema.applySchema(parse(cdata, path), parse(sdata, schemaPath)); }); }); }
javascript
{ "resource": "" }
q24102
MultiplexChannel
train
function MultiplexChannel(id, conn, properties) { events.EventEmitter.call(this); this.$id = id; // The channel id this.$conn = conn; // The underlying SockJS connection _.extend(this, properties); // Apply extra properties to this object this.readyState = this.$conn.readyState; assert(this.readyState === 1); // copied from the (definitely active) conn }
javascript
{ "resource": "" }
q24103
createServers
train
function createServers(conf) { var seenKeys = map.create(); var servers = _.map(conf.search('server'), function(serverNode) { var listenNode = serverNode.getOne('listen'); if (!listenNode) throwForNode(serverNode, new Error('Required "listen" directive is missing')); var port = serverNode.getValues('listen').port; if (typeof port === 'undefined') port = 80; if (port <= 0) throwForNode(listenNode, new Error('Invalid port number')); var host = serverNode.getValues('listen').host || '::'; if (host === '*') host = '::'; if (!iputil.isValid(host)) { throwForNode(listenNode, new Error('Invalid IP address "' + host + '"')); } if (iputil.hasZone(host)) { throwForNode(listenNode, new Error(`Invalid IP address "${host}"--zone IDs are not currently supported`)) } var serverNames = serverNode.getValues('server_name').names; // Read all locations. Use post-order traversal so that nested locs // get priority over their parents. var locations = _.chain(serverNode.search('location', false, true)) .map(createLocation) .compact() .value(); // We get the templateDir at the server level so that a global or server- // wide templateDir can be attached to the request directly. We may need // this if a page gets returns without a matching AppSpec (like a 404). var templateDir = serverNode.getValues('template_dir').dir; _.each(serverNames || [''], function(serverName) { var key = host + ':' + port; if (serverName !== '') key += '(' + serverName + ')'; if (seenKeys[key]) throwForNode(listenNode, new Error(key + ' combination conflicts with earlier server definition')); seenKeys[key] = true; }); return new ServerRouter(port, host, serverNames, locations, templateDir); }); return servers; }
javascript
{ "resource": "" }
q24104
createLocation
train
function createLocation(locNode) { // TODO: Include ancestor locations in path var path = locNode.values.path; var terminalLocation = !locNode.getOne('location', false); var node = locNode.getOne(/^site_dir|user_dirs|app_dir|user_apps|redirect$/); if (!node) { // No directives. Only allow this if child locations exist. if (terminalLocation) throwForNode(locNode, new Error('location directive must contain (or inherit) one of site_dir, user_apps, app_dir, or redirect')); else return null; } var settings = map.create(); var gaid = locNode.getValues('google_analytics_id').gaid; if (gaid) settings.gaTrackingId = gaid; var logAsUser = locNode.getValues('log_as_user').enabled; settings.logAsUser = logAsUser; // Add the templateDir to the AppSpec, if we have one. var templateDir = locNode.getValues('template_dir').dir; if (templateDir){ settings.templateDir = templateDir; } settings = configRouterUtil.parseApplication(settings, locNode, true); switch (node.name) { case 'site_dir': return createSiteDir(locNode, node, settings); case 'app_dir': return createAppDir(locNode, node, settings); case 'user_apps': return createUserApps(locNode, node, settings); case 'user_dirs': return createUserApps(locNode, node, settings, true); case 'redirect': return createRedirect(locNode, node, settings); default: throwForNode(locNode, new Error('Node name ' + node.name + ' was not expected here')); } }
javascript
{ "resource": "" }
q24105
forEachPromise_p
train
function forEachPromise_p(array, iterator, accept, defaultValue) { var deferred = Q.defer(); var i = 0; function tryNext() { if (i >= array.length) { // We've reached the end of the list--give up deferred.resolve(defaultValue); } else { try { // Try the next item in the list iterator(array[i++]) .then( function(result) { // If the promise returns a result, see if it is acceptable; if // so, we're done, otherwise move on to the next item in the list if (accept(result)) { deferred.resolve(result); } else { tryNext(); } }, function(err) { deferred.reject(err); } ); } catch(ex) { deferred.reject(ex); } } } tryNext(); return deferred.promise; }
javascript
{ "resource": "" }
q24106
fapply
train
function fapply(func, object, args) { try { return Q.resolve(func.apply(object, args)); } catch(err) { return Q.reject(err); } }
javascript
{ "resource": "" }
q24107
map_p
train
function map_p(collection, func_p) { if (collection.length === 0) return Q.resolve([]); var results = []; var lastFunc = Q.resolve(true); _.each(collection, function(el, index) { lastFunc = lastFunc.then(function() { return func_p(collection[index]) .then(function(result) { results[index] = result; return results; }); }); }); return lastFunc; }
javascript
{ "resource": "" }
q24108
findConfig_p
train
function findConfig_p(appDir){ var filePath = path.join(appDir, ".shiny_app.conf"); return fsutil.safeStat_p(filePath) .then(function(stat){ if (stat && stat.isFile()){ return (filePath); } throw new Error('Invalid app configuration file.'); }); }
javascript
{ "resource": "" }
q24109
sendClientAlertMessage
train
function sendClientAlertMessage(ws, alert) { var msg = JSON.stringify({ custom: { alert: alert } }); ws.write(msg); }
javascript
{ "resource": "" }
q24110
error404
train
function error404(req, res, templateDir) { sendPage(res, 404, 'Page not found', { template: 'error-404', templateDir: templateDir, vars: { message: "Sorry, but the page you requested doesn't exist." } }); }
javascript
{ "resource": "" }
q24111
errorAppOverloaded
train
function errorAppOverloaded(req, res, templateDir) { sendPage(res, 503, 'Too Many Users', { template: 'error-503-users', templateDir: templateDir, vars: { message: "Sorry, but this application has exceeded its quota of concurrent users. Please try again later." } }); }
javascript
{ "resource": "" }
q24112
ping
train
function ping(req, res) { if (url.parse(req.url).pathname == '/ping') { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('OK'); return true; } return false; }
javascript
{ "resource": "" }
q24113
compact
train
function compact(x) { function shouldDrop(key) { return typeof(x[key]) === 'undefined' || x[key] === null; } return _.omit(x, _.filter(_.keys(x), shouldDrop)) }
javascript
{ "resource": "" }
q24114
AnonymousObserver
train
function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; }
javascript
{ "resource": "" }
q24115
arrayIndexOfComparer
train
function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; }
javascript
{ "resource": "" }
q24116
VirtualTimeScheduler
train
function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this); }
javascript
{ "resource": "" }
q24117
HistoricalScheduler
train
function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; __super__.call(this, clock, cmp); }
javascript
{ "resource": "" }
q24118
train
function (ticks, value) { return typeof value === 'function' ? new Recorded(ticks, new OnNextPredicate(value)) : new Recorded(ticks, Notification.createOnNext(value)); }
javascript
{ "resource": "" }
q24119
train
function (ticks, error) { return typeof error === 'function' ? new Recorded(ticks, new OnErrorPredicate(error)) : new Recorded(ticks, Notification.createOnError(error)); }
javascript
{ "resource": "" }
q24120
AsyncSubject
train
function AsyncSubject() { __super__.call(this); this.isDisposed = false; this.isStopped = false; this.hasValue = false; this.observers = []; this.hasError = false; }
javascript
{ "resource": "" }
q24121
exit
train
function exit() { myFingerprintSensor = null; fingerprint_lib.cleanUp(); fingerprint_lib = null; console.log("Exiting"); process.exit(0); }
javascript
{ "resource": "" }
q24122
start
train
function start() { if (motor) { // configure it, for this example, we'll assume 200 steps per rev motor.configStepper(200); motor.setStepperSteps(100); // start it going at 10 RPM motor.enableStepper(mdObj.MD.STEP_DIR_CW, 10); } }
javascript
{ "resource": "" }
q24123
periodicActivity
train
function periodicActivity() { //Read & Scale Gyro/Accel Data var xgyro = imu.gyroScale(imu.regRead(0x04)); var ygyro = imu.gyroScale(imu.regRead(0x06)); var zgyro = imu.gyroScale(imu.regRead(0x08)); var xaccl = imu.accelScale(imu.regRead(0x0A)); var yaccl = imu.accelScale(imu.regRead(0x0C)); var zaccl = imu.accelScale(imu.regRead(0x0E)); //Display Scaled Data on the Console Log console.log('XGYRO: ' + xgyro); console.log('YGYRO: ' + ygyro); console.log('ZGYRO: ' + zgyro); console.log('XACCL: ' + xaccl); console.log('YACCL: ' + yaccl); console.log('ZACCL: ' + zaccl); console.log(' '); setTimeout(periodicActivity,200); //call the indicated function after 0.2 seconds (200 milliseconds) }
javascript
{ "resource": "" }
q24124
readSensorValue
train
function readSensorValue() { if ( touch.isPressed() ) { console.log(touch.name() + " is pressed"); } else { console.log(touch.name() + " is not pressed"); } }
javascript
{ "resource": "" }
q24125
outputData
train
function outputData() { sensor.update(); var floatData = sensor.getEulerAngles(); console.log("Euler: Heading: " + floatData.get(0) + " Roll: " + floatData.get(1) + " Pitch: " + floatData.get(2) + " degrees"); floatData = sensor.getQuaternions(); console.log("Quaternion: W: " + floatData.get(0) + " X:" + floatData.get(1) + " Y: " + floatData.get(2) + " Z: " + floatData.get(3)); floatData = sensor.getLinearAcceleration(); console.log("Linear Acceleration: X: " + floatData.get(0) + " Y: " + floatData.get(1) + " Z: " + floatData.get(2) + " m/s^2"); floatData = sensor.getGravityVectors(); console.log("Gravity Vector: X: " + floatData.get(0) + " Y: " + floatData.get(1) + " Z: " + floatData.get(2) + " m/s^2"); console.log(""); }
javascript
{ "resource": "" }
q24126
update
train
function update(){ now = new Date(); var time = now.getHours().toString() + ("0" + now.getMinutes().toString()).slice(-2); display.writeString(time); display.setColon(colon = !colon); }
javascript
{ "resource": "" }
q24127
rotateScreen
train
function rotateScreen(r) { lcd.setRotation(r); lcd.fillRect(0, 0, 5, 5, ili9341.ILI9341_WHITE); if (r < 4) { r++; setTimeout(function() { rotateScreen(r); }, 1000); } }
javascript
{ "resource": "" }
q24128
train
function (callback) { return this._request({ path: this._extension }, function (err, body, res) { return err ? callback(err) : callback(null, body.networks, res); }); }
javascript
{ "resource": "" }
q24129
train
function (network, callback) { var networkId = (typeof network === 'object') ? network.id : network; return this._request({ path: urlJoin(this._extension, networkId) }, function (err, body) { return err ? callback(err) : callback(null, body.network); }); }
javascript
{ "resource": "" }
q24130
train
function (options, properties, callback) { return this._request({ method: 'POST', path: this._extension, body: { network: _.pick(options, properties) } }, function (err, body) { return err ? callback(err) : callback(null, body.network); }); }
javascript
{ "resource": "" }
q24131
train
function (network, callback) { var networkId = (typeof network === 'object') ? network.id : network; return this._request({ path: urlJoin(this._extension, 'add'), method: 'POST', body: { id: networkId } }, function (err) { return callback(err); }); }
javascript
{ "resource": "" }
q24132
handleServerResponse
train
function handleServerResponse(err, server) { if (err) { console.dir(err); return; } console.log('SERVER CREATED: ' + server.name + ', waiting for active status'); // Wait for status: ACTIVE on our server, and then callback server.setWait({ status: server.STATUS.running }, 5000, function (err) { if (err) { console.dir(err); return; } console.log('SERVER INFO'); console.log(server.name); console.log(server.status); console.log(server.id); console.log('Make sure you DELETE server: ' + server.id + ' in order to not accrue billing charges'); }); }
javascript
{ "resource": "" }
q24133
SharedKeyTable
train
function SharedKeyTable(storageAccount, storageAccessKey) { this.storageAccount = storageAccount; this.storageAccessKey = storageAccessKey; this.signer = new HmacSha256Sign(storageAccessKey); }
javascript
{ "resource": "" }
q24134
train
function(loadBalancer, callback) { var self = this, loadBalancerId = loadBalancer instanceof lb.LoadBalancer ? loadBalancer.id : loadBalancer; self._request({ path: urlJoin(_urlPrefix, loadBalancerId) }, function (err, body) { if (err) { return callback(err); } else if (!body || !body.loadBalancer) { return callback(new Error('Unexpected empty response')); } else { return callback(null, new lb.LoadBalancer(self, body.loadBalancer)); } }); }
javascript
{ "resource": "" }
q24135
train
function(details, callback) { var self = this, createOptions = { path: _urlPrefix, method: 'POST', body: { name: details.name, nodes: details.nodes || [], protocol: details.protocol ? details.protocol.name : '', port: details.protocol ? details.protocol.port : '', virtualIps: details.virtualIps } }; createOptions.body = _.extend(createOptions.body, _.pick(details, ['accessList', 'algorithm', 'connectionLogging', 'connectionThrottle', 'healthMonitor', 'metadata', 'timeout', 'sessionPersistence'])); var validationErrors = validateLbInputs(createOptions.body); if (validationErrors) { return callback(new Error('Errors validating inputs for createLoadBalancer', validationErrors)); } self._request(createOptions, function(err, body) { return err ? callback(err) : callback(err, new lb.LoadBalancer(self, body.loadBalancer)); }); }
javascript
{ "resource": "" }
q24136
train
function (loadBalancer, callback) { if (!(loadBalancer instanceof lb.LoadBalancer)) { throw new Error('Missing required argument: loadBalancer'); } var self = this, updateOptions = { path: urlJoin(_urlPrefix, loadBalancer.id), method: 'PUT', body: {} }; updateOptions.body.loadBalancer = _.pick(loadBalancer, ['name', 'protocol', 'port', 'timeout', 'algorithm', 'httpsRedirect', 'halfClosed']); self._request(updateOptions, function (err) { callback(err); }); }
javascript
{ "resource": "" }
q24137
train
function(loadBalancer, details, callback) { var self = this, loadBalancerId = loadBalancer instanceof lb.LoadBalancer ? loadBalancer.id : loadBalancer; if (!details || !details.type) { throw new Error('Details is a required option for loadBalancer health monitors'); } var requestOptions = { path: urlJoin(_urlPrefix, loadBalancerId, 'healthmonitor'), method: 'PUT' }; if (details.type === 'CONNECT') { requestOptions.body = { attemptsBeforeDeactivation: details.attemptsBeforeDeactivation, type: details.type, delay: details.delay, timeout: details.timeout }; } else if (details.type === 'HTTP' || details.type === 'HTTPS') { requestOptions.body = { attemptsBeforeDeactivation: details.attemptsBeforeDeactivation, type: details.type, delay: details.delay, timeout: details.timeout, bodyRegex: details.bodyRegex, path: details.path, statusRegex: details.statusRegex }; if (details.hostHeader) { requestOptions.body.hostHeader = details.hostHeader; } } else { throw new Error('Unsupported health monitor type'); } self._request(requestOptions, function (err) { return callback(err); }); }
javascript
{ "resource": "" }
q24138
train
function (loadBalancer, type, callback) { var self = this, loadBalancerId = loadBalancer instanceof lb.LoadBalancer ? loadBalancer.id : loadBalancer; if (!type || (type !== 'HTTP_COOKIE' && type !== 'SOURCE_IP')) { throw new Error('Please provide a valid session persistence type'); } self._request({ path: urlJoin(_urlPrefix, loadBalancerId, 'sessionpersistence'), method: 'PUT', body: { sessionPersistence: { persistenceType: type } } }, function (err) { return callback(err); }); }
javascript
{ "resource": "" }
q24139
train
function (loadBalancer, details, callback) { var self = this, loadBalancerId = loadBalancer instanceof lb.LoadBalancer ? loadBalancer.id : loadBalancer; var options = _.pick(details, ['maxConnectionRate', 'maxConnections', 'minConnections', 'rateInterval']); self._request({ path: urlJoin(_urlPrefix, loadBalancerId, 'connectionthrottle'), method: 'PUT', body: { connectionThrottle: options } }, function (err) { return callback(err); }); }
javascript
{ "resource": "" }
q24140
train
function (startTime, endTime, options, callback) { var self = this; if (typeof options === 'function') { callback = options; options = {}; } var requestOpts = { path: urlJoin(_urlPrefix, 'billable'), qs: { startTime: typeof startTime === 'Date' ? startTime.toISOString() : startTime, endTime: typeof endTime === 'Date' ? endTime.toISOString() : endTime } }; requestOpts.qs = _.extend(requestOpts.qs, _.pick(options, ['offset', 'limit'])); self._request(requestOpts, function (err, body, res) { return callback(err, body.loadBalancers.map(function (loadBalancer) { return new lb.LoadBalancer(self, loadBalancer); }), res); }); }
javascript
{ "resource": "" }
q24141
train
function (startTime, endTime, callback) { var self = this; self._request({ path: urlJoin(_urlPrefix, 'usage'), qs: { startTime: typeof startTime === 'Date' ? startTime.toISOString() : startTime, endTime: typeof endTime === 'Date' ? endTime.toISOString() : endTime } }, function (err, body) { return callback(err, body); }); }
javascript
{ "resource": "" }
q24142
train
function (callback) { var self = this; self._request({ path: urlJoin(_urlPrefix, 'alloweddomains') }, function (err, body) { return callback(err, body.allowedDomains); }); }
javascript
{ "resource": "" }
q24143
SharedKey
train
function SharedKey(storageAccount, storageAccessKey) { this.storageAccount = storageAccount; this.storageAccessKey = storageAccessKey; this.signer = new HmacSha256Sign(storageAccessKey); }
javascript
{ "resource": "" }
q24144
train
function (loadBalancer, callback) { var self = this, loadBalancerId = loadBalancer instanceof lb.LoadBalancer ? loadBalancer.id : loadBalancer; self._request({ path: urlJoin(_urlPrefix, loadBalancerId, 'nodes') }, function (err, body, res) { if (err) { return callback(err); } else if (!body || !body.nodes) { return callback(new Error('Unexpected empty response')); } else { return callback(null, body.nodes.map(function (node) { return new lb.Node(self, _.extend(node, { loadBalancerId: loadBalancerId })); }), res); } }); }
javascript
{ "resource": "" }
q24145
train
function(loadBalancer, nodes, callback) { var self = this, loadBalancerId = loadBalancer instanceof lb.LoadBalancer ? loadBalancer.id : loadBalancer; if (!Array.isArray(nodes)) { nodes = [ nodes ]; } var postOptions = { path: urlJoin(_urlPrefix, loadBalancerId, 'nodes'), method: 'POST', body: { nodes: [] } }; postOptions.body.nodes = _.map(nodes, function(node) { return _.pick(node, ['address', 'port', 'condition', 'type', 'weight']); }); self._request(postOptions, function (err, body, res) { if (err) { return callback(err); } else if (!body || !body.nodes) { return callback(new Error('Unexpected empty response')); } else { return callback(null, body.nodes.map(function (node) { return new lb.Node(self, _.extend(node, { loadBalancerId: loadBalancerId })); }), res); } }); }
javascript
{ "resource": "" }
q24146
train
function(loadBalancer, node, callback) { var self = this, loadBalancerId = loadBalancer instanceof lb.LoadBalancer ? loadBalancer.id : loadBalancer; if (!(node instanceof lb.Node) && (typeof node !== 'object')) { throw new Error('node is a required argument and must be an object'); } self._request({ path: urlJoin(_urlPrefix, loadBalancerId, 'nodes', node.id), method: 'PUT', body: { node: _.pick(node, ['condition', 'type', 'weight']) } }, function (err) { callback(err); }); }
javascript
{ "resource": "" }
q24147
train
function (loadBalancer, node, callback) { var self = this, loadBalancerId = loadBalancer instanceof lb.LoadBalancer ? loadBalancer.id : loadBalancer, nodeId = node instanceof lb.Node ? node.id : node; self._request({ path: urlJoin(_urlPrefix, loadBalancerId, 'nodes', nodeId), method: 'DELETE' }, function (err) { callback(err); }); }
javascript
{ "resource": "" }
q24148
train
function (loadBalancer, nodes, callback) { var self = this, loadBalancerId = loadBalancer instanceof lb.LoadBalancer ? loadBalancer.id : loadBalancer; // check for valid inputs if (!nodes || nodes.length === 0 || !Array.isArray(nodes)) { throw new Error('nodes must be an array of Node or nodeId'); } // support passing either the javascript object or an array of ids var list = nodes.map(function (item) { return (typeof item === 'object') ? item.id : item; }); self._request({ path: urlJoin(_urlPrefix, loadBalancerId, 'nodes', '?id=' + list.join('&id=')), method: 'DELETE' }, function (err) { callback(err); }); }
javascript
{ "resource": "" }
q24149
train
function (loadBalancer, callback) { var self = this, loadBalancerId = loadBalancer instanceof lb.LoadBalancer ? loadBalancer.id : loadBalancer; self._request({ path: urlJoin(_urlPrefix, loadBalancerId, 'nodes', 'events') }, function (err, body) { return err ? callback(err) : callback(err, body.nodeServiceEvents); }); }
javascript
{ "resource": "" }
q24150
encodeAddressName
train
function encodeAddressName(name) { if (!/^[\w ']*$/.test(name)) { if (/^[\x20-\x7e]*$/.test(name)) { return JSON.stringify(name); } else { return (0, _emailjsMimeCodec.mimeWordEncode)(name, 'Q', 52); } } return name; }
javascript
{ "resource": "" }
q24151
parseFetchValue
train
function parseFetchValue (key, value) { if (!value) { return null } if (!Array.isArray(value)) { switch (key) { case 'uid': case 'rfc822.size': return Number(value.value) || 0 case 'modseq': // do not cast 64 bit uint to a number return value.value || '0' } return value.value } switch (key) { case 'flags': case 'x-gm-labels': value = [].concat(value).map((flag) => (flag.value || '')) break case 'envelope': value = parseENVELOPE([].concat(value || [])) break case 'bodystructure': value = parseBODYSTRUCTURE([].concat(value || [])) break case 'modseq': value = (value.shift() || {}).value || '0' break } return value }
javascript
{ "resource": "" }
q24152
buildFETCHCommand
train
function buildFETCHCommand(sequence, items, options) { let command = { command: options.byUid ? 'UID FETCH' : 'FETCH', attributes: [{ type: 'SEQUENCE', value: sequence }] }; if (options.valueAsString !== undefined) { command.valueAsString = options.valueAsString; } let query = []; items.forEach(item => { item = item.toUpperCase().trim(); if (/^\w+$/.test(item)) { // alphanum strings can be used directly query.push({ type: 'ATOM', value: item }); } else if (item) { try { // parse the value as a fake command, use only the attributes block const cmd = (0, _emailjsImapHandler.parser)((0, _common.toTypedArray)('* Z ' + item)); query = query.concat(cmd.attributes || []); } catch (e) { // if parse failed, use the original string as one entity query.push({ type: 'ATOM', value: item }); } } }); if (query.length === 1) { query = query.pop(); } command.attributes.push(query); if (options.changedSince) { command.attributes.push([{ type: 'ATOM', value: 'CHANGEDSINCE' }, { type: 'ATOM', value: options.changedSince }]); } return command; }
javascript
{ "resource": "" }
q24153
buildXOAuth2Token
train
function buildXOAuth2Token(user = '', token) { let authData = [`user=${user}`, `auth=Bearer ${token}`, '', '']; return (0, _emailjsBase.encode)(authData.join('\x01')); }
javascript
{ "resource": "" }
q24154
buildSTORECommand
train
function buildSTORECommand(sequence, action = '', flags = [], options = {}) { let command = { command: options.byUid ? 'UID STORE' : 'STORE', attributes: [{ type: 'sequence', value: sequence }] }; command.attributes.push({ type: 'atom', value: action.toUpperCase() + (options.silent ? '.SILENT' : '') }); command.attributes.push(flags.map(flag => { return { type: 'atom', value: flag }; })); return command; }
javascript
{ "resource": "" }
q24155
shallowEqual
train
function shallowEqual(objA, objB, options = {}) { if (is(objA, objB)) { return true; } if ((typeof objA === 'undefined' ? 'undefined' : _typeof(objA)) !== 'object' || objA === null || (typeof objB === 'undefined' ? 'undefined' : _typeof(objB)) !== 'object' || objB === null) { return false; } if(objA instanceof Date && objB instanceof Date) { return objA === objB; } const keysA = Object.keys(objA); const keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } const { omitKeys, deepKeys, } = options; // Test for A's keys different from B. for (let i = 0; i < keysA.length; i++) { // if key is an omitted key, skip comparison if (omitKeys && omitKeys.length && ~omitKeys.indexOf(keysA[i])) continue; if (deepKeys && deepKeys.length && ~deepKeys.indexOf(keysA[i])) { const result = shallowEqual(objA[keysA[i]], objB[keysA[i]]); if (!result) return false; } else if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; }
javascript
{ "resource": "" }
q24156
rewriteFonts
train
function rewriteFonts () { const style = path.join(target, 'css', 'style.css') const css = fs.readFileSync(style) .toString() .replace(/@import url\(.*?Roboto.*?\);/, `@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,600|Source+Code+Pro:400,600');`) .replace(/Roboto/g, 'Open Sans') fs.writeFileSync(style, ` ${css} code { font-family: 'Source Code Pro', monospace; } pre > code { padding: 0.75em 1em; line-height: 1.5em; } ul, ol { margin-bottom: 15px; } hr { border: 0; height: 2px; background: #f5f5f5; margin: 15px 0; } blockquote { border-left: 3px solid #eee; padding-left: 0.75em; margin-bottom: 15px; color: #999; font-size: 0.9em; } `) }
javascript
{ "resource": "" }
q24157
runExec
train
function runExec(container) { var options = { Cmd: ['bash', '-c', 'echo test $VAR'], Env: ['VAR=ttslkfjsdalkfj'], AttachStdout: true, AttachStderr: true }; container.exec(options, function(err, exec) { if (err) return; exec.start(function(err, stream) { if (err) return; container.modem.demuxStream(stream, process.stdout, process.stderr); exec.inspect(function(err, data) { if (err) return; console.log(data); }); }); }); }
javascript
{ "resource": "" }
q24158
train
function(modem, name, remote) { this.modem = modem; this.name = name; this.remote = remote || name; }
javascript
{ "resource": "" }
q24159
containerLogs
train
function containerLogs(container) { // create a single stream for stdin and stdout var logStream = new stream.PassThrough(); logStream.on('data', function(chunk){ console.log(chunk.toString('utf8')); }); container.logs({ follow: true, stdout: true, stderr: true }, function(err, stream){ if(err) { return logger.error(err.message); } container.modem.demuxStream(stream, logStream, logStream); stream.on('end', function(){ logStream.end('!stop!'); }); setTimeout(function() { stream.destroy(); }, 2000); }); }
javascript
{ "resource": "" }
q24160
_getPathFromPowerShell
train
function _getPathFromPowerShell () { return new Promise(resolve => { const psArgs = 'Get-Command npm | Select-Object -ExpandProperty Definition' const args = [ '-NoProfile', '-NoLogo', psArgs ] const child = spawn('powershell.exe', args) let stdout = [] let stderr = [] child.stdout.on('data', (data) => { debug(`PowerShell: Stdout received: ${data.toString()}`) stdout.push(data.toString()) }) child.stderr.on('data', (data) => { debug(`PowerShell: Stderr received: ${data.toString()}`) stderr.push(data.toString()) }) child.on('exit', () => { const cmdPath = (stdout[0] && stdout[0].trim) ? stdout[0].trim() : null if (stderr.length === 0 && cmdPath && cmdPath.slice(cmdPath.length - 7) === 'npm.cmd') { // We're probably installed in a location like C:\Program Files\nodejs\npm.cmd, // meaning that we should not use the global prefix installation location const npmPath = cmdPath.slice(0, cmdPath.length - 8) debug(`PowerShell: _getPathFromPowerShell() resolving with: ${npmPath}`) resolve(npmPath) } else { resolve(null) } }) child.stdin.end() }) }
javascript
{ "resource": "" }
q24161
_getPath
train
function _getPath () { return Promise.all([_getPathFromPowerShell(), _getPathFromNpm()]) .then((results) => { const fromNpm = results[1] || '' const fromPowershell = results[0] || '' // Quickly check if there's an npm folder in there const fromPowershellPath = path.join(fromPowershell, 'node_modules', 'npm') const fromNpmPath = path.join(fromNpm, 'node_modules', 'npm') const isFromPowershell = utils.isPathAccessible(fromPowershellPath) const isFromNpm = utils.isPathAccessible(fromNpmPath) // Found in... // Powershell: -> return powershell path // npm: -> return npm path // nowhere: -> return powershell path if (isFromPowershell) { return { path: fromPowershell, message: strings.npmFoundIn(fromPowershell, fromNpm, fromPowershell) } } else if (isFromNpm) { return { path: fromNpm, message: strings.npmFoundIn(fromPowershell, fromNpm, fromNpm) } } else { return { path: fromPowershell, message: strings.npmNotFoundGuessing(fromPowershell, fromNpm, fromPowershell) } } }) }
javascript
{ "resource": "" }
q24162
runUpgrade
train
function runUpgrade (version, npmPath) { return new Promise((resolve, reject) => { const scriptPath = path.resolve(__dirname, '../powershell/upgrade-npm.ps1') const psArgs = npmPath === null ? `& {& '${scriptPath}' -version '${version}' }` : `& {& '${scriptPath}' -version '${version}' -NodePath '${npmPath}' }` const args = [ '-ExecutionPolicy', 'Bypass', '-NoProfile', '-NoLogo', psArgs ] if (process.env.DEBUG) { args.push('-debug') } let stdout = [] let stderr = [] let child try { child = spawn('powershell.exe', args) } catch (error) { return reject(error) } child.stdout.on('data', (data) => { debug('PowerShell: Stdout received: ' + data.toString()) stdout.push(data.toString()) }) child.stderr.on('data', (data) => { debug('PowerShell: Stderr received: ' + data.toString()) stderr.push(data.toString()) }) child.on('exit', () => resolve({ stderr, stdout })) child.stdin.end() }) }
javascript
{ "resource": "" }
q24163
runSimpleUpgrade
train
function runSimpleUpgrade (version) { return new Promise((resolve) => { let npmCommand = (version) ? `npm install -g npm@${version}` : 'npm install -g npm' let stdout = [] let stderr = [] let child try { child = spawn('powershell.exe', [ '-NoProfile', '-NoLogo', npmCommand ]) } catch (error) { // This is dirty, but the best way for us to try/catch right now resolve({ error }) } child.stdout.on('data', (data) => stdout.push(data.toString())) child.stderr.on('data', (data) => stderr.push(data.toString())) child.on('exit', () => resolve({ stderr, stdout })) child.stdin.end() }) }
javascript
{ "resource": "" }
q24164
exit
train
function exit (status, ...messages) { if (messages) { messages.forEach(message => console.log(message)) } process.exit(status) }
javascript
{ "resource": "" }
q24165
checkExecutionPolicy
train
function checkExecutionPolicy () { return new Promise((resolve, reject) => { let output = [] let child try { debug('Powershell: Attempting to spawn PowerShell child') child = spawn('powershell.exe', ['-NoProfile', '-NoLogo', 'Get-ExecutionPolicy']) } catch (error) { debug('Powershell: Could not spawn PowerShell child') reject(error) } child.stdout.on('data', (data) => { debug('PowerShell: Stdout received: ' + data.toString()) output.push(data.toString()) }) child.stderr.on('data', (data) => { debug('PowerShell: Stderr received: ' + data.toString()) output.push(data.toString()) }) child.on('exit', () => { const linesHit = output.filter((line) => line.includes('Unrestricted') || line.includes('RemoteSigned') || line.includes('Bypass')) const unrestricted = (linesHit.length > 0) if (!unrestricted) { debug('PowerShell: Resolving restricted (false)') resolve(false) } else { debug('PowerShell: Resolving unrestricted (true)') resolve(true) } }) child.stdin.end() }) }
javascript
{ "resource": "" }
q24166
isPathAccessible
train
function isPathAccessible (filePath) { try { fs.accessSync(filePath) debug(`Utils: isPathAccessible(): ${filePath} exists`) return true } catch (err) { debug(`Utils: isPathAccessible(): ${filePath} does not exist`) return false } }
javascript
{ "resource": "" }
q24167
getAvailableNPMVersions
train
function getAvailableNPMVersions () { return new Promise((resolve, reject) => { exec('npm view npm versions --json', (err, stdout) => { if (err) { let error = 'We could not show latest available versions. Try running this script again ' error += 'with the version you want to install (npm-windows-upgrade --npm-version 3.0.0)' return reject(error) } resolve(JSON.parse(stdout)) }) }) }
javascript
{ "resource": "" }
q24168
_getWindowsVersion
train
function _getWindowsVersion () { return new Promise((resolve, reject) => { const command = 'systeminfo | findstr /B /C:"OS Name" /C:"OS Version"' exec(command, (error, stdout) => { if (error) { reject(error) } else { resolve(stdout) } }) }) }
javascript
{ "resource": "" }
q24169
getVersions
train
async function getVersions () { let versions = process.versions let prettyVersions = [] versions.os = process.platform + ' ' + process.arch for (let variable in versions) { if (versions.hasOwnProperty(variable)) { prettyVersions.push(`${variable}: ${versions[variable]}`) } } try { const windowsVersion = await _getWindowsVersion() prettyVersions.push(windowsVersion.replace(/ +/g, ' ')) } catch (error) { // Do nothing, we're okay with this failing. // Most common reason is we're not on an english // Windows. } return prettyVersions.join(' | ') }
javascript
{ "resource": "" }
q24170
train
function (hostEl, targetEl, positionStr, appendToBody) { var positionStrParts = positionStr.split('-'); var pos0 = positionStrParts[0], pos1 = positionStrParts[1] || 'center'; var hostElPos, targetElWidth, targetElHeight, targetElPos; hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl); targetElWidth = targetEl.prop('offsetWidth'); targetElHeight = targetEl.prop('offsetHeight'); var shiftWidth = { center: function () { return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2; }, left: function () { return hostElPos.left; }, right: function () { return hostElPos.left + hostElPos.width; } }; var shiftHeight = { center: function () { return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2; }, top: function () { return hostElPos.top; }, bottom: function () { return hostElPos.top + hostElPos.height; } }; switch (pos0) { case 'right': targetElPos = { top: shiftHeight[pos1](), left: shiftWidth[pos0]() }; break; case 'left': targetElPos = { top: shiftHeight[pos1](), left: hostElPos.left - targetElWidth }; break; case 'bottom': targetElPos = { top: shiftHeight[pos0](), left: shiftWidth[pos1]() }; break; default: targetElPos = { top: hostElPos.top - targetElHeight, left: shiftWidth[pos1]() }; break; } return targetElPos; }
javascript
{ "resource": "" }
q24171
snake_case
train
function snake_case(name){ var regexp = /[A-Z]/g; var separator = '-'; return name.replace(regexp, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); }
javascript
{ "resource": "" }
q24172
computeLinesAndColumns
train
function computeLinesAndColumns(tokenizer, source) { var sourceLength = source.length; var start = firstCharOffset(source); var lines = tokenizer.lines; var line = tokenizer.startLine; var columns = tokenizer.columns; var column = tokenizer.startColumn; if (lines === null || lines.length < sourceLength + 1) { lines = new SafeUint32Array(Math.max(sourceLength + 1024, MIN_BUFFER_SIZE)); columns = new SafeUint32Array(lines.length); } for (var i = start; i < sourceLength; i++) { var code = source.charCodeAt(i); lines[i] = line; columns[i] = column++; if (code === N || code === R || code === F) { if (code === R && i + 1 < sourceLength && source.charCodeAt(i + 1) === N) { i++; lines[i] = line; columns[i] = column; } line++; column = 1; } } lines[i] = line; columns[i] = column; tokenizer.linesAnsColumnsComputed = true; tokenizer.lines = lines; tokenizer.columns = columns; }
javascript
{ "resource": "" }
q24173
readPreferencesFromCfg
train
function readPreferencesFromCfg(cfg) { try { var value = cfg.getPreferenceValue('ShowSplashScreen'); if(typeof value != 'undefined') { showSplashScreen = value === 'true'; } splashScreenDelay = cfg.getPreferenceValue('SplashScreenDelay') || splashScreenDelay; splashScreenDelay = parseInt(splashScreenDelay, 10); imageSrc = cfg.getPreferenceValue('SplashScreen') || imageSrc; bgColor = cfg.getPreferenceValue('SplashScreenBackgroundColor') || bgColor; splashImageWidth = cfg.getPreferenceValue('SplashScreenWidth') || splashImageWidth; splashImageHeight = cfg.getPreferenceValue('SplashScreenHeight') || splashImageHeight; autoHideSplashScreen = cfg.getPreferenceValue('AutoHideSplashScreen') || autoHideSplashScreen; autoHideSplashScreen = (autoHideSplashScreen === true || autoHideSplashScreen.toLowerCase() === 'true'); } catch(e) { var msg = '[Browser][SplashScreen] Error occurred on loading preferences from config.xml: ' + JSON.stringify(e); console.error(msg); } }
javascript
{ "resource": "" }
q24174
resolveRegistration
train
function resolveRegistration(owner, ...args) { if (owner.resolveRegistration) { return owner.resolveRegistration(...args); } else if (owner.__container__) { return owner.__container__.lookupFactory(...args); } else { return owner.container.lookupFactory(...args); } }
javascript
{ "resource": "" }
q24175
createPretender
train
function createPretender(server) { return new Pretender(function() { this.passthroughRequest = function(verb, path, request) { if (server.shouldLog()) { console.log(`Passthrough request: ${verb.toUpperCase()} ${request.url}`); } }; this.handledRequest = function(verb, path, request) { if (server.shouldLog()) { console.groupCollapsed( `Mirage: [${request.status}] ${verb.toUpperCase()} ${request.url}` ); let { requestBody, responseText } = request; let loggedRequest, loggedResponse; try { loggedRequest = JSON.parse(requestBody); } catch(e) { loggedRequest = requestBody; } try { loggedResponse = JSON.parse(responseText); } catch(e) { loggedResponse = responseText; } console.log({ request: loggedRequest, response: loggedResponse, raw: request }); console.groupEnd(); } }; this.unhandledRequest = function(verb, path) { path = decodeURI(path); assert( `Your Ember app tried to ${verb} '${path}', but there was no route defined to handle this request. Define a route that matches this path in your mirage/config.js file. Did you forget to add your namespace?` ); }; }, { trackRequests: server.shouldTrackRequests() }); }
javascript
{ "resource": "" }
q24176
isOption
train
function isOption(option) { if (!option || typeof option !== 'object') { return false; } let allOptions = Object.keys(defaultRouteOptions); let optionKeys = Object.keys(option); for (let i = 0; i < optionKeys.length; i++) { let key = optionKeys[i]; if (allOptions.indexOf(key) > -1) { return true; } } return false; }
javascript
{ "resource": "" }
q24177
extractRouteArguments
train
function extractRouteArguments(args) { let [ lastArg ] = args.splice(-1); if (isOption(lastArg)) { lastArg = _assign({}, defaultRouteOptions, lastArg); } else { args.push(lastArg); lastArg = defaultRouteOptions; } let t = 2 - args.length; while (t-- > 0) { args.push(undefined); } args.push(lastArg); return args; }
javascript
{ "resource": "" }
q24178
superstruct
train
function superstruct(config = {}) { const types = { ...Types, ...(config.types || {}), } /** * Create a `kind` struct with `schema`, `defaults` and `options`. * * @param {Any} schema * @param {Any} defaults * @param {Object} options * @return {Function} */ function struct(schema, defaults, options = {}) { if (isStruct(schema)) { schema = schema.schema } const kind = Kinds.any(schema, defaults, { ...options, types }) function Struct(data) { if (this instanceof Struct) { if (process.env.NODE_ENV !== 'production') { throw new Error( 'The `Struct` creation function should not be used with the `new` keyword.' ) } else { throw new Error('Invalid `new` keyword!') } } return Struct.assert(data) } Object.defineProperty(Struct, IS_STRUCT, { value: true }) Object.defineProperty(Struct, KIND, { value: kind }) Struct.kind = kind.name Struct.type = kind.type Struct.schema = schema Struct.defaults = defaults Struct.options = options Struct.assert = value => { const [error, result] = kind.validate(value) if (error) { throw new StructError(error) } return result } Struct.test = value => { const [error] = kind.validate(value) return !error } Struct.validate = value => { const [error, result] = kind.validate(value) if (error) { return [new StructError(error)] } return [undefined, result] } return Struct } /** * Mix in a factory for each specific kind of struct. */ Object.keys(Kinds).forEach(name => { const kind = Kinds[name] struct[name] = (schema, defaults, options) => { const type = kind(schema, defaults, { ...options, types }) const s = struct(type, defaults, options) return s } }) /** * Return the struct factory. */ return struct }
javascript
{ "resource": "" }
q24179
train
function( element, method ) { return $(element).data("msg-" + method.toLowerCase()) || (element.attributes && $(element).attr("data-msg-" + method.toLowerCase())); }
javascript
{ "resource": "" }
q24180
train
function(element, method) { if (!$.metadata) return; var meta = this.settings.meta ? $(element).metadata()[this.settings.meta] : $(element).metadata(); return meta && meta.messages && meta.messages[method]; }
javascript
{ "resource": "" }
q24181
getModules
train
function getModules(directory, logger, local) { logger(`Getting modules @ ${directory.path}`); if (directory.barrel) { // If theres a barrel then use that as it *should* contain descendant modules. logger(`Found existing barrel @ ${directory.barrel.path}`); return [directory.barrel]; } const files = [].concat(directory.files); if (!local) { directory.directories.forEach((childDirectory) => { // Recurse. files.push(...getModules(childDirectory, logger, local)); }); } // Only return files that look like TypeScript modules. return files.filter((file) => file.name.match(utilities_1.isTypeScriptFile)); }
javascript
{ "resource": "" }
q24182
buildBarrel
train
function buildBarrel(directory, builder, quoteCharacter, semicolonCharacter, barrelName, logger, baseUrl, local, include, exclude) { logger(`Building barrel @ ${directory.path}`); const content = builder(directory, modules_1.loadDirectoryModules(directory, logger, include, exclude, local), quoteCharacter, semicolonCharacter, logger, baseUrl); const destination = path_1.default.join(directory.path, barrelName); if (content.length === 0) { // Skip empty barrels. return; } // Add the header const contentWithHeader = header_1.addHeaderPrefix(content); fs_1.default.writeFileSync(destination, contentWithHeader); // Update the file tree model with the new barrel. if (!directory.files.some((file) => file.name === barrelName)) { const convertedPath = utilities_1.convertPathSeparator(destination); const barrel = { name: barrelName, path: convertedPath }; logger(`Updating model barrel @ ${convertedPath}`); directory.files.push(barrel); directory.barrel = barrel; } }
javascript
{ "resource": "" }
q24183
buildImportPath
train
function buildImportPath(directory, target, baseUrl) { // If the base URL option is set then imports should be relative to there. const startLocation = baseUrl ? baseUrl : directory.path; const relativePath = path_1.default.relative(startLocation, target.path); // Get the route and ensure it's relative let directoryPath = path_1.default.dirname(relativePath); if (directoryPath !== ".") { directoryPath = `.${path_1.default.sep}${directoryPath}`; } // Strip off the .ts or .tsx from the file name. const fileName = getBasename(relativePath); // Build the final path string. Use posix-style seperators. const location = `${directoryPath}${path_1.default.sep}${fileName}`; const convertedLocation = utilities_1.convertPathSeparator(location); return stripThisDirectory(convertedLocation, baseUrl); }
javascript
{ "resource": "" }
q24184
getBasename
train
function getBasename(relativePath) { const mayBeSuffix = [".ts", ".tsx", ".d.ts"]; let mayBePath = relativePath; mayBeSuffix.map(suffix => { const tmpPath = path_1.default.basename(relativePath, suffix); if (tmpPath.length < mayBePath.length) { mayBePath = tmpPath; } }); // Return whichever path is shorter. If they're the same length then nothing was stripped. return mayBePath; }
javascript
{ "resource": "" }
q24185
getDestinations
train
function getDestinations(rootTree, locationOption, barrelName, logger) { let destinations; switch (locationOption) { case "top": default: destinations = [rootTree]; break; case "below": destinations = rootTree.directories; break; case "all": destinations = []; fileTree_1.walkTree(rootTree, (directory) => { destinations.push(directory); }); break; case "replace": destinations = []; fileTree_1.walkTree(rootTree, (directory) => { if (directory.files.some((location) => location.name === barrelName)) { destinations.push(directory); } }); break; case "branch": destinations = []; fileTree_1.walkTree(rootTree, (directory) => { if (directory.directories.length > 0) { destinations.push(directory); } }); break; } // Sort by length. This means barrels will be created deepest first. destinations = destinations.sort((a, b) => { return b.path.length - a.path.length; }); logger("Destinations:"); destinations.forEach(destination => logger(destination.path)); return destinations; }
javascript
{ "resource": "" }
q24186
buildTree
train
function buildTree(directory, barrelName, logger) { logger(`Building directory tree for ${utilities_1.convertPathSeparator(directory)}`); const names = fs_1.default.readdirSync(directory); const result = { directories: [], files: [], name: path_1.default.basename(directory), path: utilities_1.convertPathSeparator(directory) }; names.forEach((name) => { const fullPath = path_1.default.join(directory, name); if (fs_1.default.statSync(fullPath).isDirectory()) { result.directories.push(buildTree(fullPath, barrelName, logger)); } else { const convertedPath = utilities_1.convertPathSeparator(fullPath); const file = { name, path: convertedPath }; result.files.push(file); if (file.name === barrelName) { logger(`Found existing barrel @ ${convertedPath}`); result.barrel = file; } } }); return result; }
javascript
{ "resource": "" }
q24187
walkTree
train
function walkTree(directory, callback) { callback(directory); directory.directories.forEach(childDirectory => walkTree(childDirectory, callback)); }
javascript
{ "resource": "" }
q24188
train
function(server, model, options) { // TODO: generate multiple DELETE routes at /RESOURCE and at // TODO: /RESOURCE/{ownerId}/ASSOCIATION that take a list of Id's as a payload try { validationHelper.validateModel(model, logger) let collectionName = model.collectionDisplayName || model.modelName let Log = logger.bind(chalk.blue(collectionName)) options = options || {} if (model.routeOptions.allowRead !== false) { this.generateListEndpoint(server, model, options, Log) this.generateFindEndpoint(server, model, options, Log) } if (model.routeOptions.allowCreate !== false) { this.generateCreateEndpoint(server, model, options, Log) } if (model.routeOptions.allowUpdate !== false) { this.generateUpdateEndpoint(server, model, options, Log) } if (model.routeOptions.allowDelete !== false) { this.generateDeleteOneEndpoint(server, model, options, Log) this.generateDeleteManyEndpoint(server, model, options, Log) } if (model.routeOptions.associations) { for (let associationName in model.routeOptions.associations) { let association = model.routeOptions.associations[associationName] if ( association.type === 'MANY_MANY' || association.type === 'ONE_MANY' || association.type === '_MANY' ) { if (association.allowAdd !== false) { this.generateAssociationAddOneEndpoint( server, model, association, options, Log ) this.generateAssociationAddManyEndpoint( server, model, association, options, Log ) } if (association.allowRemove !== false) { this.generateAssociationRemoveOneEndpoint( server, model, association, options, Log ) this.generateAssociationRemoveManyEndpoint( server, model, association, options, Log ) } if (association.allowRead !== false) { this.generateAssociationGetAllEndpoint( server, model, association, options, Log ) } } } } if (model.routeOptions && model.routeOptions.extraEndpoints) { for (let extraEndpointIndex in model.routeOptions.extraEndpoints) { let extraEndpointFunction = model.routeOptions.extraEndpoints[extraEndpointIndex] extraEndpointFunction(server, model, options, Log) } } } catch (error) { logger.error('Error:', error) throw error } }
javascript
{ "resource": "" }
q24189
_list
train
function _list(model, query, Log) { let request = { query: query } return _listHandler(model, request, Log) }
javascript
{ "resource": "" }
q24190
_find
train
function _find(model, _id, query, Log) { let request = { params: { _id: _id }, query: query } return _findHandler(model, _id, request, Log) }
javascript
{ "resource": "" }
q24191
_findHandler
train
async function _findHandler(model, _id, request, Log) { try { let query = Object.assign({}, request.query) try { if ( model.routeOptions && model.routeOptions.find && model.routeOptions.find.pre ) { query = await model.routeOptions.find.pre(_id, query, request, Log) } } catch (err) { handleError(err, 'There was a preprocessing error.', Boom.badRequest, Log) } let flatten = false if (query.$flatten) { flatten = true } delete query.$flatten let mongooseQuery = model.findOne({ _id: _id }) mongooseQuery = QueryHelper.createMongooseQuery( model, query, mongooseQuery, Log ).lean() let result = await mongooseQuery.exec() if (result) { let data = result try { if ( model.routeOptions && model.routeOptions.find && model.routeOptions.find.post ) { data = await model.routeOptions.find.post(request, result, Log) } } catch (err) { handleError( err, 'There was a postprocessing error.', Boom.badRequest, Log ) } if (model.routeOptions) { let associations = model.routeOptions.associations for (let associationKey in associations) { let association = associations[associationKey] if (association.type === 'ONE_MANY' && data[associationKey]) { // EXPL: we have to manually populate the return value for virtual (e.g. ONE_MANY) associations result[associationKey] = data[associationKey] } if (association.type === 'MANY_MANY' && flatten === true) { // EXPL: remove additional fields and return a flattened array if (result[associationKey]) { result[associationKey] = result[associationKey].map(object => { object = object[association.model] return object }) } } } } if (config.enableSoftDelete && config.filterDeletedEmbeds) { // EXPL: remove soft deleted documents from populated properties filterDeletedEmbeds(result, {}, '', 0, Log) } Log.log('Result: %s', JSON.stringify(result)) return result } else { throw Boom.notFound('No resource was found with that id.') } } catch (err) { handleError(err, null, null, Log) } }
javascript
{ "resource": "" }
q24192
_create
train
function _create(model, payload, Log) { let request = { payload: payload } return _createHandler(model, request, Log) }
javascript
{ "resource": "" }
q24193
_update
train
function _update(model, _id, payload, Log) { let request = { params: { _id: _id }, payload: payload } return _updateHandler(model, _id, request, Log) }
javascript
{ "resource": "" }
q24194
_updateHandler
train
async function _updateHandler(model, _id, request, Log) { let payload = Object.assign({}, request.payload) try { try { if ( model.routeOptions && model.routeOptions.update && model.routeOptions.update.pre ) { payload = await model.routeOptions.update.pre( _id, payload, request, Log ) } } catch (err) { handleError( err, 'There was a preprocessing error updating the resource.', Boom.badRequest, Log ) } if (config.enableUpdatedAt) { payload.updatedAt = new Date() } let result try { result = await model.findByIdAndUpdate(_id, payload, { runValidators: config.enableMongooseRunValidators }) } catch (err) { Log.error(err) if (err.code === 11000) { throw Boom.conflict('There was a duplicate key error.') } else { throw Boom.badImplementation( 'There was an error updating the resource.' ) } } if (result) { let attributes = QueryHelper.createAttributesFilter({}, model, Log) result = await model.findOne({ _id: result._id }, attributes).lean() try { if ( model.routeOptions && model.routeOptions.update && model.routeOptions.update.post ) { result = await model.routeOptions.update.post(request, result, Log) } } catch (err) { handleError( err, 'There was a postprocessing error updating the resource.', Boom.badRequest, Log ) } return result } else { throw Boom.notFound('No resource was found with that id.') } } catch (err) { handleError(err, null, null, Log) } }
javascript
{ "resource": "" }
q24195
_deleteOne
train
function _deleteOne(model, _id, hardDelete, Log) { let request = { params: { _id: _id } } return _deleteOneHandler(model, _id, hardDelete, request, Log) }
javascript
{ "resource": "" }
q24196
_deleteOneHandler
train
async function _deleteOneHandler(model, _id, hardDelete, request, Log) { try { try { if ( model.routeOptions && model.routeOptions.delete && model.routeOptions.delete.pre ) { await model.routeOptions.delete.pre(_id, hardDelete, request, Log) } } catch (err) { handleError( err, 'There was a preprocessing error deleting the resource.', Boom.badRequest, Log ) } let deleted try { if (config.enableSoftDelete && !hardDelete) { let payload = { isDeleted: true } if (config.enableDeletedAt) { payload.deletedAt = new Date() } if (config.enableDeletedBy && config.enableSoftDelete) { let deletedBy = request.payload.deletedBy || request.payload[0].deletedBy if (deletedBy) { payload.deletedBy = deletedBy } } deleted = await model.findByIdAndUpdate(_id, payload, { new: true, runValidators: config.enableMongooseRunValidators }) } else { deleted = await model.findByIdAndRemove(_id) } } catch (err) { handleError( err, 'There was an error deleting the resource.', Boom.badImplementation, Log ) } // TODO: clean up associations/set rules for ON DELETE CASCADE/etc. if (deleted) { // TODO: add eventLogs try { if ( model.routeOptions && model.routeOptions.delete && model.routeOptions.delete.post ) { await model.routeOptions.delete.post( hardDelete, deleted, request, Log ) } } catch (err) { handleError( err, 'There was a postprocessing error deleting the resource.', Boom.badRequest, Log ) } return true } else { throw Boom.notFound('No resource was found with that id.') } } catch (err) { handleError(err, null, null, Log) } }
javascript
{ "resource": "" }
q24197
_deleteMany
train
function _deleteMany(model, payload, Log) { let request = { payload: payload } return _deleteManyHandler(model, request, Log) }
javascript
{ "resource": "" }
q24198
_deleteManyHandler
train
async function _deleteManyHandler(model, request, Log) { try { // EXPL: make a copy of the payload so that request.payload remains unchanged let payload = request.payload.map(item => { return _.isObject(item) ? _.assignIn({}, item) : item }) let promises = [] for (let arg of payload) { if (JoiMongooseHelper.isObjectId(arg)) { promises.push(_deleteOneHandler(model, arg, false, request, Log)) } else { promises.push( _deleteOneHandler(model, arg._id, arg.hardDelete, request, Log) ) } } await Promise.all(promises) return true } catch (err) { handleError(err, null, null, Log) } }
javascript
{ "resource": "" }
q24199
_addOne
train
function _addOne( ownerModel, ownerId, childModel, childId, associationName, payload, Log ) { let request = { params: { ownerId: ownerId, childId: childId }, payload: payload } return _addOneHandler( ownerModel, ownerId, childModel, childId, associationName, request, Log ) }
javascript
{ "resource": "" }