_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q29500 | defaults | train | function defaults(name, selfie, opts) {
return millisecond(
name in opts ? opts[name] : (name in selfie ? selfie[name] : Recovery[name])
);
} | javascript | {
"resource": ""
} |
q29501 | Recovery | train | function Recovery(options) {
var recovery = this;
if (!(recovery instanceof Recovery)) return new Recovery(options);
options = options || {};
recovery.attempt = null; // Stores the current reconnect attempt.
recovery._fn = null; // Stores the callback.
recovery['reconnect timeout'] = defaults('reconnect timeout', recovery, options);
recovery.retries = defaults('retries', recovery, options);
recovery.factor = defaults('factor', recovery, options);
recovery.max = defaults('max', recovery, options);
recovery.min = defaults('min', recovery, options);
recovery.timers = new Tick(recovery);
} | javascript | {
"resource": ""
} |
q29502 | URL | train | function URL(address, location, parser) {
if (!(this instanceof URL)) {
return new URL(address, location, parser);
}
var relative = relativere.test(address)
, parse, instruction, index, key
, type = typeof location
, url = this
, i = 0;
//
// The following if statements allows this module two have compatibility with
// 2 different API:
//
// 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
// where the boolean indicates that the query string should also be parsed.
//
// 2. The `URL` interface of the browser which accepts a URL, object as
// arguments. The supplied object will be used as default values / fall-back
// for relative paths.
//
if ('object' !== type && 'string' !== type) {
parser = location;
location = null;
}
if (parser && 'function' !== typeof parser) {
parser = qs.parse;
}
location = lolcation(location);
for (; i < instructions.length; i++) {
instruction = instructions[i];
parse = instruction[0];
key = instruction[1];
if (parse !== parse) {
url[key] = address;
} else if ('string' === typeof parse) {
if (~(index = address.indexOf(parse))) {
if ('number' === typeof instruction[2]) {
url[key] = address.slice(0, index);
address = address.slice(index + instruction[2]);
} else {
url[key] = address.slice(index);
address = address.slice(0, index);
}
}
} else if (index = parse.exec(address)) {
url[key] = index[1];
address = address.slice(0, address.length - index[0].length);
}
url[key] = url[key] || (instruction[3] || ('port' === key && relative) ? location[key] || '' : '');
//
// Hostname, host and protocol should be lowercased so they can be used to
// create a proper `origin`.
//
if (instruction[4]) {
url[key] = url[key].toLowerCase();
}
}
//
// Also parse the supplied query string in to an object. If we're supplied
// with a custom parser as function use that instead of the default build-in
// parser.
//
if (parser) url.query = parser(url.query);
//
// We should not add port numbers if they are already the default port number
// for a given protocol. As the host also contains the port number we're going
// override it with the hostname which contains no port number.
//
if (!required(url.port, url.protocol)) {
url.host = url.hostname;
url.port = '';
}
//
// Parse down the `auth` for the username and password.
//
url.username = url.password = '';
if (url.auth) {
instruction = url.auth.split(':');
url.username = instruction[0] || '';
url.password = instruction[1] || '';
}
//
// The href is just the compiled result.
//
url.href = url.toString();
} | javascript | {
"resource": ""
} |
q29503 | Primus | train | function Primus(url, options) {
if (!(this instanceof Primus)) return new Primus(url, options);
if ('function' !== typeof this.client) {
var message = 'The client library has not been compiled correctly, ' +
'see https://github.com/primus/primus#client-library for more details';
return this.critical(new Error(message));
}
if ('object' === typeof url) {
options = url;
url = options.url || options.uri || defaultUrl;
} else {
options = options || {};
}
var primus = this;
// The maximum number of messages that can be placed in queue.
options.queueSize = 'queueSize' in options ? options.queueSize : Infinity;
// Connection timeout duration.
options.timeout = 'timeout' in options ? options.timeout : 10e3;
// Stores the back off configuration.
options.reconnect = 'reconnect' in options ? options.reconnect : {};
// Heartbeat ping interval.
options.ping = 'ping' in options ? options.ping : 25000;
// Heartbeat pong response timeout.
options.pong = 'pong' in options ? options.pong : 10e3;
// Reconnect strategies.
options.strategy = 'strategy' in options ? options.strategy : [];
// Custom transport options.
options.transport = 'transport' in options ? options.transport : {};
primus.buffer = []; // Stores premature send data.
primus.writable = true; // Silly stream compatibility.
primus.readable = true; // Silly stream compatibility.
primus.url = primus.parse(url || defaultUrl); // Parse the URL to a readable format.
primus.readyState = Primus.CLOSED; // The readyState of the connection.
primus.options = options; // Reference to the supplied options.
primus.timers = new TickTock(this); // Contains all our timers.
primus.socket = null; // Reference to the internal connection.
primus.latency = 0; // Latency between messages.
primus.stamps = 0; // Counter to make timestamps unique.
primus.disconnect = false; // Did we receive a disconnect packet?
primus.transport = options.transport; // Transport options.
primus.transformers = { // Message transformers.
outgoing: [],
incoming: []
};
//
// Create our reconnection instance.
//
primus.recovery = new Recovery(options.reconnect);
//
// Parse the reconnection strategy. It can have the following strategies:
//
// - timeout: Reconnect when we have a network timeout.
// - disconnect: Reconnect when we have an unexpected disconnect.
// - online: Reconnect when we're back online.
//
if ('string' === typeof options.strategy) {
options.strategy = options.strategy.split(/\s?\,\s?/g);
}
if (false === options.strategy) {
//
// Strategies are disabled, but we still need an empty array to join it in
// to nothing.
//
options.strategy = [];
} else if (!options.strategy.length) {
options.strategy.push('disconnect', 'online');
//
// Timeout based reconnection should only be enabled conditionally. When
// authorization is enabled it could trigger.
//
if (!this.authorization) options.strategy.push('timeout');
}
options.strategy = options.strategy.join(',').toLowerCase();
//
// Force the use of WebSockets, even when we've detected some potential
// broken WebSocket implementation.
//
if ('websockets' in options) {
primus.AVOID_WEBSOCKETS = !options.websockets;
}
//
// Force or disable the use of NETWORK events as leading client side
// disconnection detection.
//
if ('network' in options) {
primus.NETWORK_EVENTS = options.network;
}
//
// Check if the user wants to manually initialise a connection. If they don't,
// we want to do it after a really small timeout so we give the users enough
// time to listen for `error` events etc.
//
if (!options.manual) primus.timers.setTimeout('open', function open() {
primus.timers.clear('open');
primus.open();
}, 0);
primus.initialise(options);
} | javascript | {
"resource": ""
} |
q29504 | pong | train | function pong() {
primus.timers.clear('pong');
//
// The network events already captured the offline event.
//
if (!primus.online) return;
primus.online = false;
primus.emit('offline');
primus.emit('incoming::end');
} | javascript | {
"resource": ""
} |
q29505 | ping | train | function ping() {
var value = +new Date();
primus.timers.clear('ping');
primus._write('primus::ping::'+ value);
primus.emit('outgoing::ping', value);
primus.timers.setTimeout('pong', pong, primus.options.pong);
} | javascript | {
"resource": ""
} |
q29506 | train | function (name, separator) {
var fullName, sep = separator || "/";
if (name.indexOf(sep) >= 0) {
fullName = name; //already got fully-qualified (theoretically)
} else if (name.indexOf("Service") >= 0) {
fullName = "Schema" + sep + "services" + sep + name; //just got the service class name
} else {
fullName = "Schema" + sep + "services" + sep + name + "Service"; //just got the service "object" name
}
logger.debug("Service util created full name [" + fullName + "] from [" + name + "]");
return fullName;
} | javascript | {
"resource": ""
} | |
q29507 | train | function (plugins, func) {
var idx, plugin = null;
// iterate to process in reverse order without side-effects.
for (idx = 1; idx <= plugins.length; idx += 1) {
plugin = plugins[plugins.length - idx];
func(plugin);
if (plugin.stopProcessing) {
break;
}
}
} | javascript | {
"resource": ""
} | |
q29508 | bundleThrough | train | function bundleThrough(options) {
options = options || {}
var browserifyShouldCreateSourcemaps = options.debug || options.sourcemaps
var bundleTransform = through(function (file, enc, callback) {
var bundler = browserify(file.path, assign({}, options, {debug: browserifyShouldCreateSourcemaps}))
if (options.buffer === false) {
// if `buffer` option is `false` then `file.contents` is a stream
return callback(null, createNewFileByContents(file, bundler.bundle().on('error', callback)))
}
bundler.bundle(function (err, data) {
if (err) { return callback(err) }
callback(null, createNewFileByContents(file, data))
})
})
if (options.sourcemaps !== true) {
return bundleTransform
}
return duplexify.obj(bundleTransform, bundleTransform.pipe(sourcemaps.init({loadMaps: true})))
} | javascript | {
"resource": ""
} |
q29509 | createNewFileByContents | train | function createNewFileByContents(file, newContents) {
var newFile = file.clone()
newFile.contents = newContents
return newFile
} | javascript | {
"resource": ""
} |
q29510 | fetchStyle | train | function fetchStyle(id) {
for (var i = 0; i < styles.length; i++)
if (styles[i].id === id) return styles[i];
} | javascript | {
"resource": ""
} |
q29511 | sendFile | train | function sendFile(imagePath) {
response.set(headers);
response.download(imagePath, request.query.filename);
} | javascript | {
"resource": ""
} |
q29512 | Pipeline | train | function Pipeline(actionFactory, pipe) {
assert.func(actionFactory, 'actionFactory');
assert.optionalArrayOfFunc(pipe, 'pipe');
let middleware = (pipe || []).slice();
let logger;
let module = {
/** Clone the middleware pipeline */
clone: () => {
return Pipeline(actionFactory, middleware);
},
/** Use a segment */
use: (segment) => {
middleware.push(segment);
return module;
},
/** Pass this logger to middleware functions */
useLogger: (theLogger) => {
logger = theLogger;
return module;
},
/**
* Prepare pipeline for execution, with an optional head middleware
* @param {Function} head - the function to execute at the beginning of the pipeline
* @returns {Function} a function to execute the middleware pipeline
*/
prepare: (head) => {
assert.optionalFunc(head, 'head');
let pipe = middleware.slice();
let actions = actionFactory();
if (head){
head(actions);
}
return (message, options) => {
return new Promise((resolve, reject) => {
function executeSegment(){
var segment;
if (pipe.length){
segment = pipe.shift();
segment(message, actions, logger, options);
}
else {
resolve();
}
}
actions.on('error', reject);
actions.on('next', executeSegment);
actions.on('finished', reject);
executeSegment();
});
};
}
};
return module;
} | javascript | {
"resource": ""
} |
q29513 | getMinifiedJSFiles | train | function getMinifiedJSFiles(files) {
var minifiedFiles = [];
files.forEach(function(path) {
minifiedFiles.push('<%- project.uglify %>/' + path.replace('.js', '.min.js').replace('/<%= originalPluginName %>/', ''));
});
return minifiedFiles;
} | javascript | {
"resource": ""
} |
q29514 | _createStreamPointer | train | function _createStreamPointer(self, stream, serializer) {
let id = uuid();
let readable = typeof stream.read === 'function';
let type = readable ? 'readable' : 'writable';
let pointer = `boscar:${type}:${id}`;
self.streams.set(id, stream);
if (readable) {
_bindReadable(pointer, stream, serializer);
}
return pointer;
} | javascript | {
"resource": ""
} |
q29515 | _bindReadable | train | function _bindReadable(pointer, stream, serializer) {
stream.on('data', (data) => {
serializer.write(jsonrpc.notification(pointer, [data]));
});
stream.on('end', () => {
serializer.write(jsonrpc.notification(pointer, [null]));
});
stream.on('error', () => {
serializer.write(jsonrpc.notification(pointer, [null]));
});
} | javascript | {
"resource": ""
} |
q29516 | round | train | function round (value, rules) {
let unit = 1.0, roundOp = Math.round;
if (rules) {
roundOp = Math[rules.type === 'top' ? 'floor' : 'ceil'];
if ('object' === typeof rules.grow) {
unit = rules.grow[rules.type] || 1.0;
}
}
return roundOp(value / unit) * unit;
} | javascript | {
"resource": ""
} |
q29517 | Monitor | train | function Monitor (opt) {
opt = opt || {};
this.prefix = opt.prefix || process.env.MONITOR_PREFIX || null;
this.host = opt.host || process.env.DATADOG_HOST;
this.port = opt.port || process.env.DATADOG_PORT;
this.interval = opt.interval || process.env.MONITOR_INTERVAL;
if (this.host && this.port) {
this.client = new StatsD(this.host, this.port);
this.socketsMonitor = new SocketsMonitor(this);
}
} | javascript | {
"resource": ""
} |
q29518 | eslint | train | function eslint(options) {
if (typeof options === 'boolean') {
options = { fail: options }
}
options = { ...new ESLintOptions(), ...options }
return new Promise((resolve, reject) => {
const args = generateArguments(options)
const child = spawn('node', args, { stdio: options.stdio, cwd: path.resolve(options.appRootPath || getRootPath()) })
function handleError(error) {
if (options.fail === false) {
resolve(false)
} else {
reject(cleanupError(error))
}
}
child.on('error', handleError)
child.on('exit', error => {
if (error) {
handleError(error)
} else {
resolve(true)
}
})
})
} | javascript | {
"resource": ""
} |
q29519 | serializeArray | train | function serializeArray( array, indent = INDENT, pad = 0, space ) {
const elements = array
.map( element => serialize( element, indent, pad + indent, space ) );
return '[' + serializeList( elements, indent, pad, space ) + ']';
} | javascript | {
"resource": ""
} |
q29520 | serializeObject | train | function serializeObject( object, indent = INDENT, pad = 0, space ) {
const properties = Object.keys( object )
.map( key => serializeKey( key ) + ': ' +
serialize( object[ key ], indent, pad + indent, space ) );
return '{' + serializeList( properties, indent, pad, space ) + '}';
} | javascript | {
"resource": ""
} |
q29521 | serializeList | train | function serializeList( elements, indent = INDENT, pad = 0, space ) {
if( elements.length === 0 ) {
return '';
}
const length = elements.reduce( ( sum, e ) => sum + e.length + 2, pad );
const multiline = elements.some( element => /\n/.test( element ) );
const compact = length < LIST_LENGTH && !multiline;
const leader = compact ? ' ' : `\n${spaces( pad + indent, space )}`;
const trailer = compact ? ' ' : `\n${spaces( pad, space )}`;
const separator = `,${leader}`;
const body = elements.join( separator );
return `${leader}${body}${trailer}`;
} | javascript | {
"resource": ""
} |
q29522 | serializeKey | train | function serializeKey( name ) {
const identifier = /^[A-Za-z$_][A-Za-z0-9$_]*$/.test( name );
const keyword = [
'if', 'else',
'switch', 'case', 'default',
'try', 'catch', 'finally',
'function', 'return',
'var', 'let', 'const'
].indexOf( name ) >= 0;
return ( identifier && !keyword ) ? name : `"${name}"`;
} | javascript | {
"resource": ""
} |
q29523 | serializeValue | train | function serializeValue( value, indent, pad, space ) {
return leftpad( JSON.stringify( value, null, indent ), pad, space );
} | javascript | {
"resource": ""
} |
q29524 | leftpad | train | function leftpad( string, pad, space ) {
return string.split( '\n' ).join( `\n${spaces( pad, space )}` );
} | javascript | {
"resource": ""
} |
q29525 | Router | train | function Router(req, res, next) {
const server = this;
const state = {
method: req.method.toUpperCase(),
params: {},
routes: routes.concat(),
routeUnhandled: true,
server: server,
};
run(state, req, res, err => {
req.params = {};
if (state.routeUnhandled) req.log('unhandled', 'Router had no matching paths');
next(err);
});
} | javascript | {
"resource": ""
} |
q29526 | train | function(_name){
var _cookie = document.cookie,
_search = '\\b'+_name+'=',
_index1 = _cookie.search(_search);
if (_index1<0) return '';
_index1 += _search.length-2;
var _index2 = _cookie.indexOf(';',_index1);
if (_index2<0) _index2 = _cookie.length;
return _cookie.substring(_index1,_index2)||'';
} | javascript | {
"resource": ""
} | |
q29527 | add | train | function add(item) {
var newEnd = (end + 1) % BUF_SIZE;
if(end >= 0 && newEnd === begin) {
throw Error('Buffer overflow: Buffer exceeded max size: ' + BUF_SIZE);
}
buffer[newEnd] = item;
end = newEnd;
} | javascript | {
"resource": ""
} |
q29528 | next | train | function next() {
var next;
if (end < 0) { // Buffer is empty
return null;
}
next = buffer[begin];
delete buffer[begin];
if (begin === end) { // Last element
initBuffer();
} else {
begin = (begin + 1) % BUF_SIZE;
}
return next;
} | javascript | {
"resource": ""
} |
q29529 | dispatchWorkItems | train | function dispatchWorkItems() {
var i,
workItem;
if (!buffer.isEmpty()) {
i = workerJobCount.indexOf(0);
if(i >= 0) { //Free worker found
workItem = buffer.next();
// Send task to worker
workerExec(i, workItem);
//Check for more free workers
dispatchWorkItems();
}
}
} | javascript | {
"resource": ""
} |
q29530 | handleArrayResult | train | function handleArrayResult(m, workerIdx) {
var job = jobs[m.context.jobID],
partition = m.context.partition,
subResult = m.result,
result = [],
i;
job.result[partition] = subResult;
// Increase callback count.
job.cbCount++;
// When all workers are finished return result
if(job.cbCount === workers.length) {
for (i = 0; i < job.result.length; i++) {
result = result.concat(job.result[i]);
};
// Cle
job.cb(null, result);
}
// Worker is finished.
workerJobCount[workerIdx]--;
dispatchWorkItems();
} | javascript | {
"resource": ""
} |
q29531 | handleExecResult | train | function handleExecResult(m, workerIdx) {
var job = jobs[m.context.jobID];
job.cb(m.err, m.result);
// Worker is finished.
workerJobCount[workerIdx]--;
dispatchWorkItems();
} | javascript | {
"resource": ""
} |
q29532 | handleMessage | train | function handleMessage(m, workerIdx) {
var job = jobs[m.context.jobID];
switch(job.type) {
case 'func':
handleArrayResult(m, workerIdx);
break;
case 'exec':
handleExecResult(m, workerIdx);
break;
default:
throw Error('Invalid job type: ' + job.type);
}
} | javascript | {
"resource": ""
} |
q29533 | executeParallel | train | function executeParallel(op, arr, iter, cb) {
var chunkSize = Math.floor(arr.length / numCPUs),
worker,
iterStr,
task,
offset,
i;
// Lazy initialization
init();
// Check params
if (!cb) {
throw Error('Expected callback');
}
if (arr == null) {
cb(null, []);
return;
}
if (!Array.isArray(arr)) {
cb(Error('Expected array'));
return;
}
if (typeof iter !== 'function') {
cb(Error('Expected iterator function'));
return;
}
if (!isValidOP(op)) {
cb(Error('Expected valid operation but got ' + op));
return;
}
iterStr = iter.toString(); //Serialize iter
for (i = 0; i < workers.length; i++) {
worker = workers[i];
offset = chunkSize * i;
task = {
type: 'func',
op: op,
data: (i === workers.length - 1 ? arr.slice(offset) : arr.slice(offset, offset + chunkSize)), // Partition arr
iter: iterStr,
context: {
partition: i,
jobID: jobID
}
};
// Send task to worker
// worker.send(task);
buffer.add(task);
}
dispatchWorkItems();
// Store job
jobs[jobID] = {
type: 'func',
result: [],
cbCount: 0,
cb: cb
};
// Increase jobID
jobID++;
} | javascript | {
"resource": ""
} |
q29534 | merge | train | function merge(arrays, comp) {
var mid,
a1, i1,
a2, i2,
result;
if (arrays.length === 1) {
return arrays[0];
} else if (arrays.length === 2) {
// merge two arrays
a1 = arrays[0];
a2 = arrays[1];
i1 = i2 = 0;
result = [];
while(i1 < a1.length && i2 < a2.length) {
if (comp(a2[i2], a1[i1]) > 0) {
result.push(a1[i1]);
i1++;
} else {
result.push(a2[i2]);
i2++;
}
}
while(i1 < a1.length) {
result.push(a1[i1]);
i1++;
}
while(i2 < a2.length) {
result.push(a2[i2]);
i2++;
}
return result;
} else {
mid = Math.floor(arrays.length / 2);
return merge([
merge(arrays.slice(0, mid), comp),
merge(arrays.slice(mid), comp)
], comp);
}
} | javascript | {
"resource": ""
} |
q29535 | defaultComp | train | function defaultComp(a,b) {
var as = '' + a,
bs = '' + b;
if (as < bs) {
return -1;
} else if (as > bs) {
return 1;
} else {
return 0;
}
} | javascript | {
"resource": ""
} |
q29536 | constructSortingFunction | train | function constructSortingFunction(comp) {
var funcStr = 'function(arr) { return arr.sort(%comp%); };',
func;
funcStr = funcStr.replace('%comp%', comp.toString());
// Eval is evil but necessary in this case
eval('func = '+ funcStr);
return func;
} | javascript | {
"resource": ""
} |
q29537 | mergeResults | train | function mergeResults(newResults) {
if (newResults.definitions)
results.definitions = utilApi.joinArray(results.definitions, newResults.definitions);
if (newResults.dependencies)
results.dependencies = utilApi.joinArray(results.dependencies, newResults.dependencies);
if (newResults.module)
results.module = newResults.module;
} | javascript | {
"resource": ""
} |
q29538 | findScript | train | function findScript(scripts, property, value) {
for (var i = 0; i < scripts.length; i++) {
if ((Object.prototype.toString.call(scripts[i][property]) === '[object Array]' &&
scripts[i][property].indexOf(value) > -1) ||
(scripts[i][property] === value)
) {
return scripts[i];
}
}
return null;
} | javascript | {
"resource": ""
} |
q29539 | findLongestDependencyChains | train | function findLongestDependencyChains(scripts, script, modulesToIgnore) {
var chains = [];
if (!script) script = scripts[0];
// Avoid circular dependencies
if (modulesToIgnore && script.module && modulesToIgnore.indexOf(script.module) !== -1) return chains;
// Get script dependencies
if (script.dependencies && script.dependencies.length) {
var longestChainLength;
// Find dependency chains of the script
script.dependencies.forEach(function(dependency) {
var definitionScript = findScript(scripts, 'definitions', dependency);
if (definitionScript)
chains = chains.concat(findLongestDependencyChains(scripts, definitionScript, script.definitions));
});
if (chains.length > 0) {
// Keep the longest chain(s)
chains.sort(function(chain1, chain2) {
// -1 : chain1 before chain2
// 0 : nothing change
// 1 : chain1 after chain2
if (chain1.length > chain2.length)
return -1;
else if (chain1.length < chain2.length)
return 1;
else return 0;
});
longestChainLength = chains[0].length;
chains = chains.filter(function(chain) {
if (chain.length === longestChainLength) {
chain.push(script.path);
return true;
}
return false;
});
return chains;
}
}
chains.push([script.path]);
return chains;
} | javascript | {
"resource": ""
} |
q29540 | buildTree | train | function buildTree(scripts) {
var chains = [];
var tree = {
children: []
};
var currentTreeNode = tree;
// Get the longest dependency chain for each script with the highest dependency
// as the first element of the chain
scripts.forEach(function(script) {
chains = chains.concat(findLongestDependencyChains(scripts, script));
});
// Sort chains by length with longest chains first
chains.sort(function(chain1, chain2) {
// -1 : chain1 before chain2
// 0 : nothing change
// 1 : chain1 after chain2
if (chain1.length > chain2.length)
return -1;
else if (chain1.length < chain2.length)
return 1;
else return 0;
});
// Add each chain to the tree
chains.forEach(function(chain) {
// Add each element of the chain as a child of its parent
chain.forEach(function(scriptPath) {
var currentScript = findScript(scripts, 'path', scriptPath);
var alreadyExists = false;
if (!currentTreeNode.children)
currentTreeNode.children = [];
// Check if current script does not exist in node children
for (var i = 0; i < currentTreeNode.children.length; i++) {
if (currentTreeNode.children[i].path === currentScript.path) {
alreadyExists = true;
break;
}
}
// Add script to the tree
if (!alreadyExists)
currentTreeNode.children.push(currentScript);
currentTreeNode = currentScript;
});
currentTreeNode = tree;
});
return tree;
} | javascript | {
"resource": ""
} |
q29541 | train | function(list, name) {
if (Object.prototype.toString.call(list) === '[object Array]' && Object.prototype.toString.call(name) === '[object String]') {
for (var i = 0; i < list.length; i++) {
if (list[i] === name) {
return true;
}
}
}
return false;
} | javascript | {
"resource": ""
} | |
q29542 | isInstanceOf | train | function isInstanceOf(cls) {
var i, l, bases = this.constructor._meta.bases;
for (i = 0, l = bases.length; i < l; i += 1) {
if (bases[i] === cls) {
return true;
}
}
return this instanceof cls;
} | javascript | {
"resource": ""
} |
q29543 | safeMixin | train | function safeMixin(target, source) {
var name, t;
// add props adding metadata for incoming functions skipping a constructor
for (name in source) {
t = source[name];
if ((t !== op[name] || !(name in op)) && name !== cname) {
if (opts.call(t) === "[object Function]") {
// non-trivial function method => attach its name
t.nom = name;
}
target[name] = t;
}
}
return target;
} | javascript | {
"resource": ""
} |
q29544 | toLink | train | function toLink( data ) {
if ( data && typeof data === 'object' ) {
if ( data.constructor.name === 'ObjectID' || data.constructor.name === 'ObjectId' ) {
return { _id: data } ;
}
data._id = toObjectId( data._id ) ;
}
else if ( typeof data === 'string' ) {
try {
data = { _id: mongodb.ObjectID( data ) } ;
}
catch ( error ) {}
}
return data ;
} | javascript | {
"resource": ""
} |
q29545 | quote | train | function quote(s) {
if (typeof(s) === 'string') {
return "'" + s.replace(/'/g, "''") + "'";
} else if (s instanceof Array) {
return _.map(s, quote).join(', ');
}
return s;
} | javascript | {
"resource": ""
} |
q29546 | ToJSON | train | function ToJSON(jsonName) {
if (jsonName === 'result') jsonName = 'default';
let args = Array.prototype.slice.call(arguments);
if (typeof jsonName === 'undefined') {
jsonName = 'default';
} else if (typeof jsonName === 'string') {
args.splice(0, 1); //remove the name.
}
let jsonFn = modelObj.jsons[jsonName],
result = this.dataValues;
if (typeof jsonFn === 'undefined' && jsonName !== 'default') { // silent fallback
if (typeof modelObj.jsons['default'] === 'function') {
result = modelObj.jsons['default'].apply(this, args);
}
} else {
if (typeof modelObj.jsons[jsonName] === 'function') {
result = modelObj.jsons[jsonName].apply(this, args);
} else {
result = this.dataValues;
}
}
if (result === this) {
result = this.dataValues;
}
if (typeof result === 'object' && result != null) {
for (let i = 0; i < modelObj.privateAttributes.length; i++) {
if (typeof result[modelObj.privateAttributes[i]] !== 'undefined') {
delete result[modelObj.privateAttributes[i]];
}
}
}
return result;
} | javascript | {
"resource": ""
} |
q29547 | switchPersonStr | train | function switchPersonStr( str ) {
var switchPersonStrVerb = {} ;
return str.replace( /\s+|(i|you|he|she|it|we|they)\s+(\S+)(?=\s)/gi , ( match , pronoun , verb ) => {
if ( ! pronoun ) { return match ; }
var person = null , plural = null , switchedPronoun = null ;
pronoun = pronoun.toLowerCase() ;
verb = verb.toLowerCase() ;
switch ( pronoun ) {
case 'he' :
case 'she' :
case 'it' :
case 'they' :
return match ;
case 'i' : person = 1 ; plural = false ; switchedPronoun = 'you' ; break ;
case 'you' : person = 2 ; switchedPronoun = 'I' ; break ;
case 'we' : person = 1 ; plural = true ; switchedPronoun = 'you' ; break ;
}
if ( ! switchPersonStrVerb[ verb ] ) {
// Damned! We don't know that verb!
return switchedPronoun + ' ' + verb ;
}
return switchedPronoun + ' ' + switchPersonStrVerb[ verb ] ;
} ) ;
} | javascript | {
"resource": ""
} |
q29548 | on | train | function on(eventNamesOrPatterns, handler) {
if (!eventNamesOrPatterns) {
throw new Error('Must pass at least one event name or matching RegEx');
}
assert.func(handler, 'handler');
if (!Array.isArray(eventNamesOrPatterns)) {
eventNamesOrPatterns = [eventNamesOrPatterns];
}
for (let i = 0; i < eventNamesOrPatterns.length; i++) {
buckets.push({
pattern: ensureRegExp(eventNamesOrPatterns[i]),
handler: handler
});
}
} | javascript | {
"resource": ""
} |
q29549 | once | train | function once(eventNamesOrPatterns, handler) {
if (!eventNamesOrPatterns) {
throw new Error('Must pass at least one event name or matching RegEx');
}
assert.func(handler, 'handler');
if (!Array.isArray(eventNamesOrPatterns)) {
eventNamesOrPatterns = [eventNamesOrPatterns];
}
let deferred = DeferredPromise();
for (let i = 0; i < eventNamesOrPatterns.length; i++) {
buckets.push({
pattern: ensureRegExp(eventNamesOrPatterns[i]),
handler: handler,
once: deferred
});
}
return deferred.promise;
} | javascript | {
"resource": ""
} |
q29550 | setupHealth | train | function setupHealth(expressRouter, baseURI, dependenciesDef, logger) {
if (typeof (dependenciesDef) === 'string') {
if (!dependenciesDef.startsWith('/')) {
dependenciesDef = `${process.cwd()}/${dependenciesDef}`;
}
if (!fs.existsSync(dependenciesDef)) {
throw new Error(`Health dependencies file doesn't exists -> ${dependenciesDef}`);
}
if (!dependenciesDef.endsWith('.yml') || !dependenciesDef.endsWith('.yaml')) {
throw new Error(`Health dependencies file is not a YAML file -> ${dependenciesDef}`);
}
dependenciesDef = jsYaml.load(fs.readFileSync(dependenciesDef));
}
expressRouter.get(`/${baseURI}/health`, setupHealthHandler(dependenciesDef, logger));
logger.info(`RIK_HEALTH: Setup a Healthcheck endpoint at '/${baseURI}/health'`);
} | javascript | {
"resource": ""
} |
q29551 | train | function(_id){
var _input = _e._$get(_id);
_cache[_id] = 2;
if (!!_input.value) return;
_e._$setStyle(
_e._$wrapInline(_input,_ropt),
'display','none'
);
} | javascript | {
"resource": ""
} | |
q29552 | train | function(_input,_clazz){
var _id = _e._$id(_input),
_label = _e._$wrapInline(_input,{
tag:'label',
clazz:_clazz,
nid:_ropt.nid
});
_label.htmlFor = _id;
var _text = _e._$attr(_input,'placeholder')||'';
_label.innerText = _text=='null'?'':_text;
var _height = _input.offsetHeight+'px';
_e._$style(_label,{
left:0,
// width:_input.offsetWidth+'px',
// height:_height,lineHeight:_height,
display:!_input.value?'':'none'
});
} | javascript | {
"resource": ""
} | |
q29553 | inc | train | function inc(importance) {
var git = require('gulp-git'),
bump = require('gulp-bump'),
filter = require('gulp-filter'),
tag_version = require('gulp-tag-version');
// get all the files to bump version in
return gulp.src(['./package.json', './bower.json'])
// bump the version number in those files
.pipe(bump({type: importance}))
// save it back to filesystem
.pipe(gulp.dest('./'))
// commit the changed version number
.pipe(git.commit('bumps package version'))
// read only one file to get the version number
.pipe(filter('package.json'))
// **tag it in the repository**
.pipe(tag_version());
} | javascript | {
"resource": ""
} |
q29554 | Binder | train | function Binder(topology, logger) {
assert.object(topology, 'connectionInfo');
assert.object(logger, 'logger');
/**
* Ensures the topology is created for a route
* @private
* @param {Object} route - the route
* @returns {Promise} a promise that is fulfilled with the resulting topology names after the topology has been created
*/
const createTopology = (route) => {
logger.silly(`Asserting topology for route ${route.name}`);
return route.pattern.createTopology(topology, route.serviceDomainName, route.appName, route.name);
};
/**
* Bind a publishing route to a consuming route
*
* @public
* @method
* @param {Object} publishingRoute - exchange route (required)
* @param {Object} consumingRoute - consuming route (required)
* @param {Object} options - binding configuration (required)
* @param {String} options.pattern - routing pattern (ex: "#")
* @returns {Promise} a promise that is fulfilled when the bind is finished
*/
const bind = (publishingRoute, consumingRoute, options) => {
let exchangeName;
let queueName;
return createTopology(publishingRoute)
.then((topologyNames) => {
exchangeName = topologyNames.exchangeName;
return createTopology(consumingRoute);
}).then((topologyNames) => {
queueName = topologyNames.queueName;
logger.info('Binding "' + exchangeName + '" to "' + queueName + '" with pattern "' + options.pattern + '"');
return topology.createBinding({
source: exchangeName,
target: queueName,
queue: true,
keys: [options.pattern]
});
});
};
return { bind: bind };
} | javascript | {
"resource": ""
} |
q29555 | train | function() {
$._.$.log && $._.$.log.debug('Cron ' + spec.name + ' waking up');
var cb0 = function(err) {
if (err) {
$._.$.log && $._.$.log.debug('pulser_cron ' +
myUtils.errToPrettyStr(err));
} else {
$._.$.log && $._.$.log.debug('security pulsing done.');
}
};
if ($._.$.security && $._.$.security.__ca_pulse__) {
$._.$.security.__ca_pulse__(cb0);
}
} | javascript | {
"resource": ""
} | |
q29556 | resolveExtensions | train | function resolveExtensions(schema) {
var xprops, props;
xprops = getExtendedProperties(schema, []);
//unwind the property stack so that the earliest gets inheritance link
schema.properties = schema.properties || {};
function copyprop(item) { //util to get around jslint complaints about doing this directly in loop
schema.properties[item.key] = item.val;
}
while (xprops.length > 0) {
props = xprops.pop();
props.forEach(copyprop);
}
} | javascript | {
"resource": ""
} |
q29557 | resolveExtendedParameters | train | function resolveExtendedParameters(obj) {
// assume all references are resolved, just copy parameters down the
// inheritence chain. If I am derived check base first.
if (obj["extends"]) {
resolveExtendedParameters(obj["extends"]);
obj.parameters = obj.parameters || [];
obj.parameters = obj.parameters.concat(obj["extends"].parameters);
}
} | javascript | {
"resource": ""
} |
q29558 | resolveProperties | train | function resolveProperties(schema) {
logger.debug("Resolving sub-properties for " + schema.id);
// resolve inherited global parameters
resolveExtendedParameters(schema);
Object.keys(schema.services || {}).forEach(function (key) {
var value = schema.services[key];
//value.target = value.target ? schema.target + value.target : schema.target; //TODO: should this build concat paths? that is currently handled in getServiceUrl function
value.returns = value.returns || schema.returns;
value.transport = value.transport || schema.transport;
value.contentType = value.contentType || schema.contentType;
value.envelope = value.envelope || schema.envelope || "URL";
value.description = value.description || "";
if (value.returns) {
resolveExtensions(value.returns);
}
if (value.parameters) {
value.parameters.forEach(function (item) {
item.envelope = item.envelope || value.envelope;
item.description = item.description || "";
});
}
var ext = value["extends"];
if (ext) {
//resolution hasn't been completed or extends object isn't proper JSONSchema
if (!ext.id) {
throw new Error("Parent schema for method [" + key + "] in schema " + schema.id + " is invalid.");
}
//TODO: resolveExtensions for params object properties? not really needed yet (the name is fine for now...)
if (!value.parameters) {
value.parameters = ext.parameters;
} else {
value.parameters = value.parameters.concat(ext.parameters);
}
}
});
if (!schema.tag) {
schema.tag = {};
}
schema.tag.resolved = true;
schema.resolvedProperties = true;
} | javascript | {
"resource": ""
} |
q29559 | train | function () {
var names = [];
Object.keys(this.smd.services || {}).forEach(function (serviceName) {
names.push(serviceName);
});
return names;
} | javascript | {
"resource": ""
} | |
q29560 | train | function () {
var services = [], smdServices = this.smd.services;
Object.keys(smdServices || []).forEach(function (serviceName) {
services.push(smdServices[serviceName]);
});
return services;
} | javascript | {
"resource": ""
} | |
q29561 | train | function (methodName) {
var names = [], params = this.getParameters(methodName);
params.forEach(function (param) {
names.push(param.name);
});
return names;
} | javascript | {
"resource": ""
} | |
q29562 | train | function (methodName) {
var parameters = this.smd.parameters || [];
parameters = parameters.concat(this.smd.services[methodName].parameters || []);
return parameters;
} | javascript | {
"resource": ""
} | |
q29563 | train | function (methodName, argName) {
var required = this.findParameter(methodName, argName).required;
//default is false, so if "required" is undefined, return false anyway
if (required) {
return true;
}
return false;
} | javascript | {
"resource": ""
} | |
q29564 | train | function (methodName, args) {
var service = this.smd.services[methodName],
basePath = this.getRootPath(),
url,
parameters = this.enumerateParameters(service);
//if no service target, it sits at the root
url = basePath + (service.target ? "/" + service.target : "");
//replace path params where required
url = this.replacePathParamsInUrl(url, parameters.PATH, args);
//add any query params
url = this.addQueryParamsToUrl(url, parameters.URL, args);
return url;
} | javascript | {
"resource": ""
} | |
q29565 | train | function (methodName) {
var params = this.getParameters(methodName),
ret;
params.forEach(function (param) {
if (param && (param.envelope === 'JSON' ||
param.envelope === 'ENTITY')) {
ret = param;
}
});
return ret;
} | javascript | {
"resource": ""
} | |
q29566 | train | function (methodName) {
var smd = this.smd,
method = smd.services[methodName],
payloadName = (method && method.payload) || smd.payload;
return payloadName;
} | javascript | {
"resource": ""
} | |
q29567 | train | function (methodName) {
var response = this.getResponseSchema(methodName),
payloadName = this.getResponsePayloadName(methodName),
isList = false;
if (response.type !== "null") {
if ((payloadName && response.properties[payloadName] && response.properties[payloadName].type === "array") ||
(response.type && response.type === "array")) {
isList = true;
}
}
return isList;
} | javascript | {
"resource": ""
} | |
q29568 | defaultAssets | train | function defaultAssets( { name, category, descriptor } ) {
switch( category ) {
case 'themes':
return {
assetUrls: [ descriptor.styleSource || 'css/theme.css' ]
};
case 'layouts':
case 'widgets':
case 'controls':
return {
assetsForTheme: [ descriptor.templateSource || `${name}.html` ],
assetUrlsForTheme: [ descriptor.styleSource || `css/${name}.css` ]
};
default:
return {};
}
} | javascript | {
"resource": ""
} |
q29569 | buildAssets | train | function buildAssets( artifact, themes = [] ) {
const { descriptor } = artifact;
const {
assets,
assetUrls,
assetsForTheme,
assetUrlsForTheme
} = extendAssets( descriptor, defaultAssets( artifact ) );
return Promise.all( [
assetResolver
.resolveAssets( artifact, [ ...assets, ...assetUrls ] )
.then( requireAssets( requireFile, assets, assetUrls ) ),
themes.length <= 0 ? {} : assetResolver
.resolveThemedAssets( artifact, themes, [ ...assetsForTheme, ...assetUrlsForTheme ] )
.then( requireAssets( requireFile, assetsForTheme, assetUrlsForTheme ) )
.then( assets => ( { [ themes[ 0 ].name ]: assets } ) )
] ).then( merge );
} | javascript | {
"resource": ""
} |
q29570 | train | function() {
var cb = function(err, meta) {
if (err) {
var error =
new Error('BUG: __external_ca_touch__ ' +
'should not return app error');
error['err'] = err;
that.close(error);
} else {
addMethods(meta);
addBackchannel();
timeout = startTimeout();
if (listeners.open) {
listeners.open();
}
}
};
if (firstTime) {
firstTime = false;
queues.rpc.remoteInvoke(webSocket, '__external_ca_touch__', [],
[cb]);
} else {
retry();
}
} | javascript | {
"resource": ""
} | |
q29571 | replaceSpecialChars | train | function replaceSpecialChars(item) {
if (!j79.isString(item)) {
return item;
}
var result = item;
var specialChars = Object.keys(SPECIAL_CHARS_MAP);
for (var index in specialChars) {
result = replaceSpecialChar(result, specialChars[index]);
}
return result;
} | javascript | {
"resource": ""
} |
q29572 | validateClassConfig | train | function validateClassConfig(obj) {
/** If configuration is not plain object, throw error */
if ( typeof obj != `object` || obj.constructor.name != `Object` )
throw new Error(`ezobjects.validateClassConfig(): Invalid table configuration argument, must be plain object.`);
/** If configuration has missing or invalid 'className' configuration, throw error */
if ( typeof obj.className !== 'string' || !obj.className.match(/^[A-Za-z_0-9$]+$/) )
throw new Error(`ezobjects.validateClassConfig(): Configuration has missing or invalid 'className', must be string containing characters 'A-Za-z_0-9$'.`);
/** Add properties array if one wasn't set */
if ( !obj.properties )
obj.properties = [];
/** Make sure properties is array */
if ( obj.properties && ( typeof obj.properties != 'object' || obj.properties.constructor.name != 'Array' ) )
throw new Error(`ezobjects.validateClassConfig(): Invalid properties configuration, properties not array.`);
/** Loop through any properties and validate them */
obj.properties.forEach((property) => {
property.className = obj.className;
validatePropertyConfig(property);
});
} | javascript | {
"resource": ""
} |
q29573 | train | function(req, res) {
return function(err) {
err = err || new Error('wsFinalHandler error');
err.msg = req.body;
var code = json_rpc.ERROR_CODES.methodNotFound;
var error = json_rpc.newSysError(req.body, code,
'Method not found', err);
var response = JSON.stringify(json_rpc.reply(error));
$._.$.log && $._.$.log.trace(response);
res.send(response);
};
} | javascript | {
"resource": ""
} | |
q29574 | init | train | function init (router) {
router.use((err, req, res, next) => {
res._headers = res._headers || {}
next(err)
})
} | javascript | {
"resource": ""
} |
q29575 | staticViews | train | function staticViews (router, options) {
if (!options) {
return
}
Object.keys(options).filter(urlPath => options[urlPath]).forEach((urlPath) => {
const filePath = options[urlPath]
router.get(urlPath, (req, res) => {
res.render(filePath)
})
})
} | javascript | {
"resource": ""
} |
q29576 | train | function (name, pointcutOrPlugin) {
var method, matchstr;
matchstr = (pointcutOrPlugin && (pointcutOrPlugin.pointcut || pointcutOrPlugin.pattern)) || pointcutOrPlugin;
if ((pointcutOrPlugin && pointcutOrPlugin.pointcut) || typeof (pointcutOrPlugin) === 'string') {
method = this.matchPointcut;
} else {
method = this.matchPattern;
}
return method(name, matchstr);
} | javascript | {
"resource": ""
} | |
q29577 | train | function (name, pointcut) {
var regexString,
regex,
ret;
pointcut = pointcut || "*.*";
regexString = pointcut.replace(/\./g, "\\.").replace(/\*/g, ".*");
logger.debug("pointcut is: " + pointcut);
//adds word boundaries at either the beginning, end, or both depending on the index of "*" (if any)
//If "*" is not in the string then word boundaries should be added by default
if (pointcut.indexOf("*") !== 0) {
regexString = "\\b" + regexString;
}
if (pointcut.lastIndexOf("*") !== pointcut.length - 1) {
regexString += "\\b";
}
logger.debug("regexString is: " + regexString);
regex = new RegExp(regexString);
logger.debug("PluginMatcher match testing [" + name + "] against regex [" + regexString + "]");
ret = regex.exec(name);
return ret !== null;
} | javascript | {
"resource": ""
} | |
q29578 | train | function (serviceName, methodNames, type, plugins) {
var newPlugins = [];
if (plugins && plugins.length > 0) {
plugins.forEach(function (plugin) {
var match = this.matchingMethodNames(serviceName, methodNames, plugin);
if (match.length && plugin.type === type) {
logger.debug("adding " + plugin.name + " to service only list");
newPlugins.push(plugin);
} else {
logger.debug("not adding " + plugin.name + " to service only list");
}
}, this);
}
return newPlugins;
} | javascript | {
"resource": ""
} | |
q29579 | train | function (serviceName, methodNames, pointCut) {
var fullName, ret = [];
methodNames.forEach(function (name) {
fullName = serviceName + "." + name;
var match = this.match(fullName, pointCut);
if (match) {
ret.push(name);
}
}, this);
return ret;
} | javascript | {
"resource": ""
} | |
q29580 | train | function (serviceName, methodName, factoryPlugins, servicePlugins, invokePlugins) {
var ret = util.mixin({}, this.defaults), that = this;
Object.keys(ret).forEach(function (key) {
var pf = that.list(serviceName, methodName, key, factoryPlugins),
ps = that.list(serviceName, methodName, key, servicePlugins),
pi = that.list(serviceName, methodName, key, invokePlugins);
ret[key] = [].concat((pf || []), (ps || []), (pi || []));
});
return ret;
} | javascript | {
"resource": ""
} | |
q29581 | onWhichEvent | train | function onWhichEvent(sense, name, nbFinger) {
var prefix = 'Short';
if (sense.hasPaused) prefix = 'Long';
var onEventName = 'on' + prefix + name + nbFinger;
if (a4p.isDefined(sense[onEventName]) && (sense[onEventName] != null)) {
return onEventName;
}
if (sense.options.prefixPriority) {
// the 'Short'/'Long' prefix has priority over the number of fingers : sense-long-tap before sense-tap-2
onEventName = 'on' + prefix + name;
if (a4p.isDefined(sense[onEventName]) && (sense[onEventName] != null)) {
return onEventName;
}
onEventName = 'on' + name + nbFinger;
if (a4p.isDefined(sense[onEventName]) && (sense[onEventName] != null)) {
return onEventName;
}
} else {
// the number of fingers has priority over the 'Short'/'Long' prefix : sense-tap-2 before sense-long-tap
onEventName = 'on' + name + nbFinger;
if (a4p.isDefined(sense[onEventName]) && (sense[onEventName] != null)) {
return onEventName;
}
onEventName = 'on' + prefix + name;
if (a4p.isDefined(sense[onEventName]) && (sense[onEventName] != null)) {
return onEventName;
}
}
onEventName = 'on' + name;
if (a4p.isDefined(sense[onEventName]) && (sense[onEventName] != null)) {
return onEventName;
}
return '';
} | javascript | {
"resource": ""
} |
q29582 | clearDrops | train | function clearDrops(sense) {
sense.dropsStarted = [];
sense.dropOver = null;
sense.dropEvt = {
dataType: 'text/plain',
dataTransfer: ''
};
} | javascript | {
"resource": ""
} |
q29583 | AccessError | train | function AccessError(message) {
Error.captureStackTrace(this, this.constructor);
Object.defineProperties(this, {
/**
* Error message.
*
* @property message
* @type String
* @final
*/
message: {value: message, writable: true},
/**
* Error name.
*
* @property name
* @type String
* @final
*/
name: {value: 'AccessError', writable: true}
});
} | javascript | {
"resource": ""
} |
q29584 | through | train | function through(transform) {
var th = new Transform({objectMode: true})
th._transform = transform
return th
} | javascript | {
"resource": ""
} |
q29585 | read | train | function read(uri) {
"use strict";
var parsedUrl = url.parse(uri, false, true);
var makeRequest = parsedUrl.protocol === 'https:' ? https.request.bind(https) : http.request.bind(http);
var serverPort = parsedUrl.port ? parsedUrl.port : parsedUrl.protocol === 'https:' ? 443 : 80;
var agent = parsedUrl.protocol === 'https:' ? httpsAgent : httpAgent;
var options = {
host: parsedUrl.host,
path: parsedUrl.path,
agent: agent,
port: serverPort,
method: 'GET',
headers: {'Content-Type': 'application/json'}
};
return new Promise(function (resolve, reject) {
var req = makeRequest(options, function (response) {
var data = '';
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
resolve({
status: response.statusCode,
data: data
});
});
});
req.on('error', reject);
req.end();
});
} | javascript | {
"resource": ""
} |
q29586 | download | train | function download(uri, dest, progressCallback) {
"use strict";
progressCallback = progressCallback || function() {};
var parsedUrl = url.parse(uri, false, true);
var makeRequest = parsedUrl.protocol === 'https:' ? https.request.bind(https) : http.request.bind(http);
var serverPort = parsedUrl.port ? parsedUrl.port : parsedUrl.protocol === 'https:' ? 443 : 80;
var agent = parsedUrl.protocol === 'https:' ? httpsAgent : httpAgent;
var file = fs.createWriteStream(dest);
var options = {
host: parsedUrl.host,
path: parsedUrl.path,
agent: agent,
port: serverPort,
method: 'GET'
};
return new Promise(function (resolve, reject) {
var req = makeRequest(options, function (response) {
var size = response.headers['content-length'];
var progress = 0;
response.on('data', function(chunk) {
progress += chunk.length;
progressCallback(size, progress);
});
response.pipe(file);
file.on('finish', function() {
resolve({
status: response.statusCode
});
});
});
req.on('error', function(error) {
file.end();
rimraf.sync(dest);
reject(error);
});
req.end();
});
} | javascript | {
"resource": ""
} |
q29587 | writeStream | train | async function writeStream (filename, contents) {
await new Promise((resolve, reject) => {
contents.pipe(fs.createWriteStream(filename))
.on('finish', function () {
resolve(filename)
})
.on('error', /* istanbul ignore next */ function (err) {
reject(err)
})
})
return filename
} | javascript | {
"resource": ""
} |
q29588 | downloadFile | train | function downloadFile(cb) {
if(task.file_path) {
// Download the file
var stream = fs.createWriteStream(path);
// Store error if statusCode !== 200
var err;
stream.on("finish", function() {
cb(err);
});
var urlToDownload = url.parse(task.file_path, false, true);
// deny queries to ElasticSearch and other vulnerable services
if(task.config.forbiddenPorts && task.config.forbiddenPorts.indexOf(urlToDownload.port) !== -1) {
stream.end();
return fs.unlink(path, function() {
cb(new Error('Trying to access forbidden port: ' + urlToDownload.port));
});
}
var req = request(urlToDownload.protocol + "//" + urlToDownload.host)
.get(urlToDownload.path);
// Warning, Black magic.
// Streaming and checking for status code is no easy task...
// Hours spent optimizing: 22
req.end(function() {}).req.once('response', function(res) {
if(res.statusCode !== 200) {
if(res.statusCode === 410) {
err = new Error('410 Gone');
err.skip = true;
}
else {
err = new Error('Error downloading file, got status ' + res.statusCode);
}
stream.end();
this.abort();
}
});
req.pipe(stream);
}
else {
cb(null);
}
} | javascript | {
"resource": ""
} |
q29589 | train | function (payload, plugins, ioArgs) {
var writePayload = payload || "", intermediate, that = this;
// Very simiplistic payload type coercion
if (this.requestPayloadName && !payload[this.requestPayloadName]) {
payload = {};
payload[this.requestPayloadName] = writePayload;
}
// Allow request plugins to execute
util.executePluginChain(plugins.request, function (plugin) {
intermediate = plugin.fn.call(plugin.scope || plugin, payload, that, ioArgs);
payload = intermediate || payload;
});
writePayload = (this.requestPayloadName && payload[this.requestPayloadName]) || payload;
// Allow write plugins to execute
util.executePluginChain(plugins.write, function (plugin) {
if (util.isArray(writePayload)) {
writePayload.forEach(function (item, idx) {
intermediate = plugin.fn.call(plugin.scope || plugin, item, that);
writePayload[idx] = intermediate || writePayload[idx];
}, that);
} else {
intermediate = plugin.fn.call(plugin.scope || plugin, writePayload, that);
writePayload = intermediate || writePayload;
}
});
if (this.requestPayloadName) {
payload[this.requestPayloadName] = writePayload;
} else {
payload = writePayload;
}
return payload;
} | javascript | {
"resource": ""
} | |
q29590 | train | function (statusCode, data, plugins, ioArgs) {
var isList = this.reader.isListResponse(this.name),
//TODO: "any" is JSONSchema default if no type is defined. this should come through a model though so we aren't tacking it on everywhere
returnType = this.reader.getResponseSchema(this.name).type || "any", //this could fail if there is no "returns" block on the method
payload,
that = this,
intermediate,
successfulResponsePattern = '(2|3)\\d\\d';
//only auto-process responses if not JSONSchema "null" primitive type
if (returnType && returnType !== "null") {
if (typeof (data) === "object") {
//first we apply any global response plugins to the raw data
//warning: if the plugin doesn't write it back out with the correct payload name,
//it will cause an issue below
util.executePluginChain(plugins.response, function (plugin) {
// filter plugins on statusPattern
var statusPattern = plugin.statusPattern || successfulResponsePattern,
regex = new RegExp(statusPattern);
if (regex.test(statusCode)) {
intermediate = plugin.fn.call(plugin.scope || plugin, data, that, ioArgs);
data = intermediate || data;
}
});
}
payload = data;
if (this.responsePayloadName && data && data[this.responsePayloadName]) {
payload = data[this.responsePayloadName];
logger.debug("Extracting payload for [" + this.name + "] from [" + this.payloadName + "] property", payload);
}
//apply any read plugins supplied, after receiving the server results
util.executePluginChain(plugins.read, function (plugin) {
// filter plugins on statusPattern
var statusPattern = plugin.statusPattern || successfulResponsePattern,
regex = new RegExp(statusPattern);
if (regex.test(statusCode)) {
if (isList) {
payload.some(function (item, idx) {
intermediate = plugin.fn.call(plugin.scope || plugin, item, that);
payload[idx] = intermediate || payload[idx];
}, that);
} else {
intermediate = plugin.fn.call(plugin.scope || plugin, payload, that);
payload = intermediate || payload;
}
}
});
}
this.data = payload; //hold on to a copy for future use (could be undefined of course)
return payload;
} | javascript | {
"resource": ""
} | |
q29591 | HouseholdAddresses | train | function HouseholdAddresses (f1, householdID) {
if (!householdID) {
throw new Error('HouseholdAddresses requires a household ID!')
}
Addresses.call(this, f1, {
path: '/Households/' + householdID + '/Addresses'
})
} | javascript | {
"resource": ""
} |
q29592 | train | function(v,node){
var format = this.__dataset(node,'format')||'yyyy-MM-dd';
return !v||(!isNaN(this.__doParseDate(v)) && _u._$format(this.__doParseDate(v),format) == v);
} | javascript | {
"resource": ""
} | |
q29593 | train | function(_node){
var _type = _node.type,
_novalue = !_node.value,
_nocheck = (_type=='checkbox'||
_type=='radio')&&!_node.checked;
if (_nocheck||_novalue) return -1;
} | javascript | {
"resource": ""
} | |
q29594 | train | function(_node,_options){
var _reg = this.__treg[_options.type],
_val = _node.value.trim(),
_tested = !!_reg.test&&!_reg.test(_val),
_funced = _u._$isFunction(_reg)&&!_reg.call(this,_val,_node);
if (_tested||_funced) return -2;
} | javascript | {
"resource": ""
} | |
q29595 | train | function(_node,_options){
var _number = this.__number(
_node.value,
_options.type,
_options.time
);
if (isNaN(_number)||
_number<_options.min)
return -6;
} | javascript | {
"resource": ""
} | |
q29596 | train | function(_value,_node){
// for multiple select
if (!!_node.multiple){
var _map;
if (!_u._$isArray(_value)){
_map[_value] = _value;
}else{
_map = _u._$array2object(_value);
}
_u._$forEach(
_node.options,function(_option){
_option.selected = _map[_option.value]!=null;
}
);
}else{
_node.value = _getValue(_value);
}
} | javascript | {
"resource": ""
} | |
q29597 | train | function(_value,_node){
if (_reg0.test(_node.type||'')){
// radio/checkbox
_node.checked = _value==_node.value;
}else if(_node.tagName=='SELECT'){
// for select node
_doSetSelect(_value,_node);
}else{
// other
_node.value = _getValue(_value);
}
} | javascript | {
"resource": ""
} | |
q29598 | train | function(callbackUUID, result) {
var callback = apiListeners[callbackUUID];
if (callback) {
if ( !(result && result instanceof Array )) {
if(window.console && console.error){
console.error('received result is not an array.', result);
}
}
callback.apply(this, result);
delete apiListeners[callbackUUID];
}
} | javascript | {
"resource": ""
} | |
q29599 | train | function(options, callback, errorCallback){
if(typeof options == 'function'){
callback = options;
options = {};
}
UT.Expression._callAPI(
'document.textInput',
[options.value || null, options.max || null, options.multiline || false],
callback
);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.