_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q2700
|
train
|
function(callback) {
var errName;
try {
if (self._covered) {
// If coverage is request, we want the testModule to reference the
// code instrumented by istanbul in lib-cov/ instead of any local code in lib/.
// This passage looks for variables assigned to by require('lib/*')
// and sets a value for the variable which is the equivalent module in lib-cov.
var fullModuleName = path.resolve(testModule);
if (!fullModuleName.match(/\.js$/)) {
fullModuleName = fullModuleName + '.js';
}
var requirements = requiredAs(fullModuleName);
// for every requirement in lib/, rewrite to lib-cov/
var newRequirements = underscore.map(requirements, function(req) {
if (req.source.match(/node_modules/) || !req.source.match(/lib\//)) {
return undefined;
}
req.source = path.resolve(path.dirname(fullModuleName), req.source);
req.source = req.source.replace(/lib\//, 'lib-cov/');
return req;
});
exportedFunctions = rewire(fullModuleName);
underscore.each(newRequirements.filter(function(i) { return i; }), function(nr) {
exportedFunctions.__set__(nr.name, require(nr.source));
});
} else {
exportedFunctions = require(testModule);
}
}
catch (err) {
if (err.message.indexOf(testModule) !== -1 &&
err.message.match(/cannot find module/i)) {
errName = 'file_does_not_exist';
}
else {
errName = 'uncaught_exception';
}
test = new Test(errName, null);
test._markAsFailed(err);
self._reportTestResult(test.getResultObject());
callback(err);
return;
}
exportedFunctionsNames = Object.keys(exportedFunctions);
exportedFunctionsNames = exportedFunctionsNames.filter(isValidTestFunctionName);
testsLen = exportedFunctionsNames.length;
initializeFunc = exportedFunctions[constants.TEST_FILE_INITIALIZE_FUNCTION_NAME];
finalizeFunc = exportedFunctions[constants.TEST_FILE_FINALIZE_FUNCTION_NAME];
setUpFunc = exportedFunctions[constants.SETUP_FUNCTION_NAME];
tearDownFunc = exportedFunctions[constants.TEARDOWN_FUNCTION_NAME];
callback();
}
|
javascript
|
{
"resource": ""
}
|
|
q2701
|
train
|
function(callback) {
var queue;
if (exportedFunctionsNames.length === 0) {
callback();
return;
}
function taskFunc(task, callback) {
var setUpFunc = task.setUpFunc, tearDownFunc = task.tearDownFunc;
async.waterfall([
function runSetUp(callback) {
if (!setUpFunc) {
callback();
return;
}
var test = new Test(constants.SETUP_FUNCTION_NAME, setUpFunc,
self._scopeLeaks);
test.run(onTestDone.bind(null, test, callback));
},
function runTest(callback) {
var test = task.test;
self._runningTest = test;
test.run(onTestDone.bind(null, test, callback));
},
function runTearDown(callback) {
if (!tearDownFunc) {
callback();
return;
}
var test = new Test(constants.TEARDOWN_FUNCTION_NAME, tearDownFunc,
self._scopeLeaks);
test.run(onTestDone.bind(null, test, callback));
}
], callback);
}
function onDrain() {
callback();
}
queue = async.queue(taskFunc, self._concurrency);
queue.drain = onDrain;
for (i = 0; i < testsLen; i++) {
testName = exportedFunctionsNames[i];
testFunc = exportedFunctions[testName];
if (!gex(self._pattern).on(testName)) {
continue;
}
test = new Test(testName, testFunc, self._scopeLeaks);
queue.push({'test': test, 'setUpFunc': setUpFunc, 'tearDownFunc': tearDownFunc});
}
if (queue.length() === 0) {
// No test matched the provided pattern
callback();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2702
|
train
|
function (actualArgs, expectedArgs) {
var i;
if (actualArgs.length !== expectedArgs.length) {
return false;
}
for (i = 0; i < expectedArgs.length; i++) {
if (actualArgs[i] !== expectedArgs[i]) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q2703
|
buildDep
|
train
|
function buildDep(file, pkg){
var files = [];
if (file.processed || file.package != pkg)
return files;
file.processed = true;
for (var i = 0, depFile; depFile = file.deps[i++];)
files.push.apply(files, buildDep(depFile, file.package));
files.push(file);
return files;
}
|
javascript
|
{
"resource": ""
}
|
q2704
|
assert
|
train
|
function assert (validator, message) {
message = messageBuilder(message || 'vet/utils/assert error!');
if (isFunction(validator)) {
return function() {
var args = arguments;
if (validator.apply(this, args)) {
return true;
} else {
throw new Error(message.apply(this, args));
}
};
} else if (!validator) {
throw new Error(message.apply(this));
} else {
return true;
}
}
|
javascript
|
{
"resource": ""
}
|
q2705
|
coverage
|
train
|
function coverage(data, type) {
var comparisionFunc;
var n = 0;
function isCovered(val) {
return (val > 0);
}
function isMissed(val) {
return !isCovered(val);
}
if (type === 'covered') {
comparisionFunc = isCovered;
}
else if (type === 'missed') {
comparisionFunc = isMissed;
}
else {
throw new Error('Invalid type: ' + type);
}
var len = Object.keys(data.lines).length;
for (var i = 0; i < len; ++i) {
if (data.lines[i] !== null && comparisionFunc(data.lines[i])) {
++n;
}
}
return n;
}
|
javascript
|
{
"resource": ""
}
|
q2706
|
aggregateCoverage
|
train
|
function aggregateCoverage(files) {
var i, len, file, content, results;
var resultsObj = getEmptyResultObject();
for (i = 0, len = files.length; i < len; i++) {
file = files[i];
content = JSON.parse(fs.readFileSync(file).toString());
resultsObj = populateCoverage(resultsObj, content);
}
return resultsObj;
}
|
javascript
|
{
"resource": ""
}
|
q2707
|
pakoUnzip
|
train
|
async function pakoUnzip(inputData) {
let strm
let pos = 0
let i = 0
const chunks = []
let inflator
do {
const remainingInput = inputData.slice(pos)
inflator = new Inflate()
strm = inflator.strm
inflator.push(remainingInput, Z_SYNC_FLUSH)
if (inflator.err) throw new Error(inflator.msg)
pos += strm.next_in
chunks[i] = Buffer.from(inflator.result)
i += 1
} while (strm.avail_in)
const result = Buffer.concat(chunks)
return result
}
|
javascript
|
{
"resource": ""
}
|
q2708
|
sink
|
train
|
function sink(modulename, level, message, obj) {
term.puts(sprintf('[green]%s[/green]: %s', modulename, message));
}
|
javascript
|
{
"resource": ""
}
|
q2709
|
indexEntry
|
train
|
function indexEntry(entry) {
if (entry.year) entry.year = parseInt(entry.year.toString().split("-")[0]); // first year for series
var n = helpers.simplifyName(entry);
if (!meta[n]) meta[n] = [];
meta[n].push(entry);
byImdb[entry.imdb_id] = entry;
}
|
javascript
|
{
"resource": ""
}
|
q2710
|
File
|
train
|
function File(retries, cdn, options) {
options = options || {};
this.backoff = new Backoff({ min: 100, max: 20000 });
this.mime = options.mime || {};
this.retries = retries || 5;
this.client = cdn.client;
this.cdn = cdn;
}
|
javascript
|
{
"resource": ""
}
|
q2711
|
Field
|
train
|
function Field(type, config) {
if (utils.typeOf(type) === 'object') {
config = type;
type = null;
}
if (!utils.isObject(config)) {
throw new TypeError('expected config to be an object');
}
this.types = type || config.type || config.types || [];
this.types = typeof this.types === 'string'
? this.types.split(/\W/)
: this.types;
if (typeof this.types === 'undefined' || this.types.length === 0) {
throw new TypeError('expected type to be a string or array of JavaScript native types');
}
for (var key in config) {
this[key] = config[key];
}
if (!config.hasOwnProperty('required')) {
this.required = false;
}
if (!config.hasOwnProperty('optional')) {
this.optional = true;
}
if (this.required === true) {
this.optional = false;
}
if (this.optional === false) {
this.required = true;
}
}
|
javascript
|
{
"resource": ""
}
|
q2712
|
train
|
function (obj, other) {
var notIn = {};
for (var key in obj) {
if (other[key] === undefined) {
notIn[key] = true;
}
}
return _.keys(notIn);
}
|
javascript
|
{
"resource": ""
}
|
|
q2713
|
isBetween
|
train
|
function isBetween(lower, upper) {
return function (val) {
return isNumber(val) && val > lower && val < upper;
}
}
|
javascript
|
{
"resource": ""
}
|
q2714
|
DockerProc
|
train
|
function DockerProc(docker, config) {
EventEmitter.call(this);
this.docker = docker;
this._createConfig = config.create;
this._startConfig = config.start;
this.stdout = new streams.PassThrough();
this.stderr = new streams.PassThrough();
}
|
javascript
|
{
"resource": ""
}
|
q2715
|
train
|
function(options) {
options = options || {};
if (!('pull' in options)) options.pull = true;
// no pull means no extra stream processing...
if (!options.pull) return this._run();
return new Promise(function(accept, reject) {
// pull the image (or use on in the cache and output status in stdout)
var pullStream =
utils.pullImageIfMissing(this.docker, this._createConfig.Image);
// pipe the pull stream into stdout but don't end
pullStream.pipe(this.stdout, { end: false });
pullStream.once('error', reject);
pullStream.once('end', function() {
pullStream.removeListener('error', reject);
this._run().then(accept, reject);
}.bind(this));
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q2716
|
train
|
function() {
var that = this;
this.killed = true;
if (this.started) {
this.container.kill();
} else {
this.once('container start', function() {
that.container.kill();
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2717
|
returns
|
train
|
function returns(func, validator, message) {
message = messageBuilder(message || 'vet/utils/returns error!');
return function _returnsInstance() {
var args = arguments;
var result = func.apply(this, arguments);
if (validator(result)) {
return result;
} else {
throw new Error(message.call(this, result));
}
};
}
|
javascript
|
{
"resource": ""
}
|
q2718
|
setupConn
|
train
|
function setupConn(connectCfg, options) {
var conn = amqp.createConnection(connectCfg, options);
conn.on('ready', function() {
debug('received ready event from node-amqp');
var eventName = 'connection';
//Ready event will be emitted when re-connected.
//To keep backward compatible, only emit 'connection' event for the first time
if (_connection) {
eventName = 'reconnect';
}
_connection = conn;
_connection._isClosed = false;
self.emit('ready');
// wrapped in 'nextTick' for unit test friendliness
process.nextTick(function() {
debug('going to emit ' + eventName);
self.emit(eventName);
});
autoSubscribe();
publishCachedMessages();
_rpcReplyQ = null;
_rpcReplyQName = null;
_rpcSubscribed = false;
if (_.size(_rpcCallbacks) > 0) {
debug('found ' + _.size(_rpcCallbacks) + ' callbacks left after reconnect');
//still have callbacks that are waiting for response.However, since we have reconnected, they won't receive the messages
_.each(_rpcCallbacks, function(cb) {
return cb('connection_error');
});
}
_rpcCallbacks = {};
});
conn.on('error', function(err) {
self.emit('error', err);
});
conn.on('close', function() {
if (_connection) {
_connection._isClosed = true;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q2719
|
autoSubscribe
|
train
|
function autoSubscribe() {
//re-add pending subscribers
if (_pendingSubscribers.length > 0) {
async.each(_pendingSubscribers, function(sub, callback) {
debug('Add pending subscriber', sub);
self.subscribeToTopic(sub.exchange, sub.queue, sub.filter, sub.subscriber, sub.opts, function(err) {
if (err) {
debug('Failed to add subscriber, keep it', sub);
} else {
//done, remove the item from the pending subscribers
var idx = _pendingSubscribers.indexOf(sub);
_pendingSubscribers.splice(idx, 1);
debug('pending subsriber added, now there are ' + _pendingSubscribers.length + ' left');
}
return callback();
});
}, function() {
debug('pending subscribers are added');
});
}
}
|
javascript
|
{
"resource": ""
}
|
q2720
|
publishCachedMessages
|
train
|
function publishCachedMessages() {
if (_cachedPublishMessages.length > 0) {
async.each(_cachedPublishMessages, function(message, callback) {
debug('republish message', message);
self.publishTopic(message.exchange, message.topic, message.message, message.options, function(err) {
if (err) {
debug('Failed to republish message', message);
} else {
var idx = _cachedPublishMessages.indexOf(message);
_cachedPublishMessages.splice(idx, 1);
debug('cached publish message re-published, now there are ' + _cachedPublishMessages.length + ' messages left');
}
return callback();
});
}, function() {
debug('cached publish messages processed');
});
}
}
|
javascript
|
{
"resource": ""
}
|
q2721
|
filter_email
|
train
|
function filter_email(value) {
var m = EMAIL_RE.exec(value);
if(m == null) throw OptError('Excpeted an email address.');
return m[1];
}
|
javascript
|
{
"resource": ""
}
|
q2722
|
build_rules
|
train
|
function build_rules(filters, arr) {
var rules = [];
for(var i=0; i<arr.length; i++) {
var r = arr[i], rule
if(!contains_expr(r)) throw OptError('Rule MUST contain an option.');
switch(r.length) {
case 1:
rule = build_rule(filters, r[0]);
break;
case 2:
var expr = LONG_SWITCH_RE.test(r[0]) ? 0 : 1;
var alias = expr == 0 ? -1 : 0;
var desc = alias == -1 ? 1 : -1;
rule = build_rule(filters, r[alias], r[expr], r[desc]);
break;
case 3:
rule = build_rule(filters, r[0], r[1], r[2]);
break;
default:
case 0:
continue;
}
rules.push(rule)
}
return rules;
}
|
javascript
|
{
"resource": ""
}
|
q2723
|
extend
|
train
|
function extend(dest, src) {
var result = dest;
for(var n in src) {
result[n] = src[n];
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q2724
|
spaces
|
train
|
function spaces(arg1, arg2) {
var l, builder = [];
if(arg1.constructor === Number) {
l = arg1;
} else {
if(arg1.length == arg2) return arg1;
l = arg2 - arg1.length;
builder.push(arg1);
}
while(l-- > 0) builder.push(' ');
return builder.join('');
}
|
javascript
|
{
"resource": ""
}
|
q2725
|
train
|
function(value, fn) {
if(value.constructor === Function ) {
this.default_handler = value;
} else if(value.constructor === Number) {
this.on_args[value] = fn;
} else {
this.on_switches[value] = fn;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2726
|
train
|
function(args) {
var result = [], callback;
var rules = build_rules(this.filters, this._rules);
var tokens = args.concat([]);
var token;
while(this._halt == false && (token = tokens.shift())) {
if(LONG_SWITCH_RE.test(token) || SHORT_SWITCH_RE.test(token)) {
var arg = undefined;
// The token is a long or a short switch. Get the corresponding
// rule, filter and handle it. Pass the switch to the default
// handler if no rule matched.
for(var i = 0; i < rules.length; i++) {
var rule = rules[i];
if(rule.long == token || rule.short == token) {
if(rule.filter !== undefined) {
arg = tokens.shift();
if(!LONG_SWITCH_RE.test(arg) && !SHORT_SWITCH_RE.test(arg)) {
try {
arg = rule.filter(arg);
} catch(e) {
throw OptError(token + ': ' + e.toString());
}
} else if(rule.optional_arg) {
tokens.unshift(arg);
} else {
throw OptError('Expected switch argument.');
}
}
callback = this.on_switches[rule.name];
if (!callback) callback = this.on_switches['*'];
if(callback) callback.apply(this, [rule.name, arg]);
break;
}
}
if(i == rules.length) this.default_handler.apply(this, [token]);
} else {
// Did not match long or short switch. Parse the token as a
// normal argument.
callback = this.on_args[result.length];
result.push(token);
if(callback) callback.apply(this, [token]);
}
}
return this._halt ? this.on_halt.apply(this, [tokens]) : result;
}
|
javascript
|
{
"resource": ""
}
|
|
q2727
|
train
|
function() {
var builder = [this.banner, '', this.options_title],
shorts = false, longest = 0, rule;
var rules = build_rules(this.filters, this._rules);
for(var i = 0; i < rules.length; i++) {
rule = rules[i];
// Quick-analyze the options.
if(rule.short) shorts = true;
if(rule.decl.length > longest) longest = rule.decl.length;
}
for(var i = 0; i < rules.length; i++) {
var text = spaces(6);
rule = rules[i];
if(shorts) {
if(rule.short) text = spaces(2) + rule.short + ', ';
}
text += spaces(rule.decl, longest) + spaces(3);
text += rule.desc;
builder.push(text);
}
return builder.join('\n');
}
|
javascript
|
{
"resource": ""
}
|
|
q2728
|
matches
|
train
|
function matches(regex) {
return function(val) {
regex.lastIndex = 0;
return isString(val) && regex.test(val);
};
}
|
javascript
|
{
"resource": ""
}
|
q2729
|
netcdfGcms
|
train
|
function netcdfGcms(data, options = {}) {
let reader = new NetCDFReader(data);
const globalAttributes = reader.globalAttributes;
let instrument_mfr = reader.getDataVariableAsString('instrument_mfr');
let dataset_origin = reader.attributeExists('dataset_origin');
let mass_values = reader.dataVariableExists('mass_values');
let detector_name = reader.getAttribute('detector_name');
let aia_template_revision = reader.attributeExists('aia_template_revision');
let source_file_format = reader.getAttribute('source_file_format');
let ans;
if (mass_values && dataset_origin) {
ans = agilentGCMS(reader);
} else if (
mass_values &&
instrument_mfr &&
instrument_mfr.match(/finnigan/i)
) {
ans = finniganGCMS(reader);
} else if (mass_values && instrument_mfr && instrument_mfr.match(/bruker/i)) {
ans = brukerGCMS(reader);
} else if (
mass_values &&
source_file_format &&
source_file_format.match(/shimadzu/i)
) {
ans = shimadzuGCMS(reader);
} else if (detector_name && detector_name.match(/(dad|tic)/i)) {
// diode array agilent HPLC
ans = agilentHPLC(reader);
} else if (aia_template_revision) {
ans = aiaTemplate(reader);
} else {
throw new TypeError('Unknown file format');
}
if (options.meta) {
ans.meta = addMeta(globalAttributes);
}
if (options.variables) {
ans.variables = addVariables(reader);
}
return ans;
}
|
javascript
|
{
"resource": ""
}
|
q2730
|
getCardId
|
train
|
function getCardId(o) {
return o.master + '#' + o.combination.front.join(',') + '@' + o.combination.back.join(',');
}
|
javascript
|
{
"resource": ""
}
|
q2731
|
addReview
|
train
|
function addReview(reviews, review) {
if (!reviews.length) {
return [review];
}
var i = reviews.length - 1;
for (; i >= 0; i -= 1) {
if (reviews[i].ts <= review.ts) {
break;
}
}
var newReviews = reviews.slice(0);
newReviews.splice(i + 1, 0, review);
return newReviews;
}
|
javascript
|
{
"resource": ""
}
|
q2732
|
searchForArrowCloudLogDir
|
train
|
function searchForArrowCloudLogDir() {
if (isWritable('/ctlog')) {
return '/ctlog';
}
if (process.env.HOME && isWritable(path.join(process.env.HOME, 'ctlog'))) {
return path.join(process.env.HOME, 'ctlog');
}
if (process.env.USERPROFILE && isWritable(path.join(process.env.USERPROFILE, 'ctlog'))) {
return path.join(process.env.USERPROFILE, 'ctlog');
}
if (isWritable('./logs')) {
return path.resolve('./logs');
}
throw new Error('No writable logging directory was found.');
}
|
javascript
|
{
"resource": ""
}
|
q2733
|
isWritable
|
train
|
function isWritable(dir) {
debug('checking if ' + dir + ' is writable');
try {
if (!fs.existsSync(dir)) {
debug(' - it does not exist yet, attempting to create it');
fs.mkdirSync(dir);
}
if (fs.accessSync) {
fs.accessSync(dir, fs.W_OK);
} else {
debug(' - fs.accessSync is not available, falling back to manual write detection');
fs.writeFileSync(path.join(dir, '.foo'), 'foo');
assert.equal(fs.readFileSync(path.join(dir, '.foo'), 'UTF-8'), 'foo');
fs.unlinkSync(path.join(dir, '.foo'));
}
debug(' - yes, it is writable');
return true;
} catch (exc) {
debug(' - no, it is not writable: ', exc);
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q2734
|
getPort
|
train
|
function getPort(req) {
if (req.connection && req.connection.localPort) {
return req.connection.localPort.toString();
}
const host = req.headers && req.headers.host;
let protocolSrc = 80;
if (host && ((host.match(/:/g) || []).length) === 1) {
const possiblePort = host.split(':')[1];
protocolSrc = isNaN(possiblePort) ? protocolSrc : possiblePort;
}
return protocolSrc;
}
|
javascript
|
{
"resource": ""
}
|
q2735
|
getStatus
|
train
|
function getStatus (res) {
let status;
const statusCode = res.statusCode;
if (statusCode) {
status = Math.floor(statusCode / 100) * 100;
}
switch (status) {
case 100:
case 200:
case 300:
return 'success';
default:
return 'failure';
}
}
|
javascript
|
{
"resource": ""
}
|
q2736
|
isWhitelisted
|
train
|
function isWhitelisted(url) {
return options.adiPathFilter.some(function (route) {
return url.substr(0, route.length) === route;
});
}
|
javascript
|
{
"resource": ""
}
|
q2737
|
createDefaultLogger
|
train
|
function createDefaultLogger(options) {
const ConsoleLogger = require('./console'),
consoleLogger = new ConsoleLogger(options),
config = _.mergeWith({
name: 'logger',
streams: [
{
level: options && options.level || 'trace',
type: 'raw',
stream: consoleLogger
}
]
}, options, function (a, b) {
return _.isArray(a) ? a.concat(b) : undefined;
});
consoleLogger.level = bunyan.resolveLevel(options && options.level || 'trace');
// default is to add the problem logger
if (!options || options.problemLogger || options.problemLogger === undefined) {
const ProblemLogger = require('./problem');
config.streams.push({
level: 'trace',
type: 'raw',
stream: new ProblemLogger(options)
});
}
const defaultLogger = bunyan.createLogger(config);
/**
* Set log level
* Backward compatible with Arrow Cloud MVC framework
* @param {Object} nameOrNum log level in string or number
* @return {String}
*/
defaultLogger.setLevel = function (nameOrNum) {
var level = 'trace';
try {
level = bunyan.resolveLevel(nameOrNum);
} catch (e) {} // eslint-disable-line no-empty
consoleLogger.level = level;
return this.level(level);
};
return defaultLogger;
}
|
javascript
|
{
"resource": ""
}
|
q2738
|
train
|
function(apiClient) {
this.apiClient = apiClient || ApiClient.instance;
/**
* Finds a code
* Finds a code
* @param {String} codeId Id of the code
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Code}
*/
this.findCode = function(codeId) {
var postBody = null;
// verify the required parameter 'codeId' is set
if (codeId == undefined || codeId == null) {
throw "Missing the required parameter 'codeId' when calling findCode";
}
var pathParams = {
'codeId': codeId
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var authNames = ['basicAuth'];
var contentTypes = ['application/json;charset=utf-8'];
var accepts = ['application/json;charset=utf-8'];
var returnType = Code;
return this.apiClient.callApi(
'/codes/{codeId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
/**
* Lists codes
* Lists codes
* @param {Object} opts Optional parameters
* @param {Array.<String>} opts.types Filter results by types
* @param {String} opts.search Search codes by free-text query
* @param {String} opts.sortBy define order (NATURAL or SCORE). Default is SCORE
* @param {String} opts.sortDir ASC or DESC. Default is ASC
* @param {Integer} opts.firstResult First result
* @param {Integer} opts.maxResults Max results
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/Code>}
*/
this.listCodes = function(opts) {
opts = opts || {};
var postBody = null;
var pathParams = {
};
var queryParams = {
'types': this.apiClient.buildCollectionParam(opts['types'], 'csv'),
'search': opts['search'],
'sortBy': opts['sortBy'],
'sortDir': opts['sortDir'],
'firstResult': opts['firstResult'],
'maxResults': opts['maxResults']
};
var headerParams = {
};
var formParams = {
};
var authNames = ['basicAuth'];
var contentTypes = ['application/json;charset=utf-8'];
var accepts = ['application/json;charset=utf-8'];
var returnType = [Code];
return this.apiClient.callApi(
'/codes', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2739
|
ConsoleLogger
|
train
|
function ConsoleLogger(options) {
EventEmitter.call(this);
this.options = options || {};
// allow use to customize if they want the label or not
this.prefix = this.options.prefix === undefined ? true : this.options.prefix;
this.showcr = this.options.showcr === undefined ? true : this.options.showcr;
this.showtab = this.options.showtab === undefined ? true : this.options.showtab;
this.colorize = this.options.colorize === undefined ? checkColorize() : this.options.colorize;
this.logPrepend = this.options.logPrepend;
chalk.enabled = !!this.colorize;
// if we are logging from a cluster worker, prepend the process PID
// istanbul ignore if
if (cluster.isWorker) {
if (chalk.enabled) {
this.logPrepend = chalk.black.inverse(String(process.pid)) + grey(' |');
} else {
this.logPrepend = process.pid + ' |';
}
}
this.remapLevels();
}
|
javascript
|
{
"resource": ""
}
|
q2740
|
isLoadNeeded
|
train
|
function isLoadNeeded(newProps, oldProps) {
return !_.isEqual(newProps.formDesign, oldProps.formDesign) || !_.isEqual(newProps.data, oldProps.data);
}
|
javascript
|
{
"resource": ""
}
|
q2741
|
train
|
function(apiClient) {
this.apiClient = apiClient || ApiClient.instance;
/**
* Find organization
* Find organization
* @param {String} organizationId organization id
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Organization}
*/
this.findOrganization = function(organizationId) {
var postBody = null;
// verify the required parameter 'organizationId' is set
if (organizationId == undefined || organizationId == null) {
throw "Missing the required parameter 'organizationId' when calling findOrganization";
}
var pathParams = {
'organizationId': organizationId
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var authNames = ['basicAuth'];
var contentTypes = ['application/json;charset=utf-8'];
var accepts = ['application/json;charset=utf-8'];
var returnType = Organization;
return this.apiClient.callApi(
'/organizations/{organizationId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
/**
* List organizations
* List organizations
* @param {Object} opts Optional parameters
* @param {String} opts.businessName Filter by organization's business name
* @param {String} opts.businessCode Filter by organization's business code
* @param {String} opts.search Search organizations by free-text query
* @param {String} opts.sortBy define order (NATURAL or SCORE). Default is NATURAL
* @param {String} opts.sortDir ASC or DESC. Default is ASC
* @param {Integer} opts.firstResult First result
* @param {Integer} opts.maxResults Max results
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/Organization>}
*/
this.listOrganizations = function(opts) {
opts = opts || {};
var postBody = null;
var pathParams = {
};
var queryParams = {
'businessName': opts['businessName'],
'businessCode': opts['businessCode'],
'search': opts['search'],
'sortBy': opts['sortBy'],
'sortDir': opts['sortDir'],
'firstResult': opts['firstResult'],
'maxResults': opts['maxResults']
};
var headerParams = {
};
var formParams = {
};
var authNames = ['basicAuth'];
var contentTypes = ['application/json;charset=utf-8'];
var accepts = ['application/json;charset=utf-8'];
var returnType = [Organization];
return this.apiClient.callApi(
'/organizations', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2742
|
createLogger
|
train
|
function createLogger(fn) {
return function () {
var args = [],
self = this,
c;
for (c = 0; c < arguments.length; c++) {
args[c] = logger.specialObjectClone(arguments[c]);
}
return fn.apply(self, args);
};
}
|
javascript
|
{
"resource": ""
}
|
q2743
|
train
|
function(apiClient) {
this.apiClient = apiClient || ApiClient.instance;
/**
* Finds organizations page fragment
* Finds single organization page fragment
* @param {String} organizationId Organization id
* @param {String} fragmentId fragment id
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Fragment}
*/
this.findOrganizationFragment = function(organizationId, fragmentId) {
var postBody = null;
// verify the required parameter 'organizationId' is set
if (organizationId == undefined || organizationId == null) {
throw "Missing the required parameter 'organizationId' when calling findOrganizationFragment";
}
// verify the required parameter 'fragmentId' is set
if (fragmentId == undefined || fragmentId == null) {
throw "Missing the required parameter 'fragmentId' when calling findOrganizationFragment";
}
var pathParams = {
'organizationId': organizationId,
'fragmentId': fragmentId
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var authNames = ['basicAuth'];
var contentTypes = ['application/json;charset=utf-8'];
var accepts = ['application/json;charset=utf-8'];
var returnType = Fragment;
return this.apiClient.callApi(
'/organizations/{organizationId}/fragments/{fragmentId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
/**
* Lists organizations page fragments
* Lists organizations page fragments
* @param {String} organizationId Organization id
* @param {Object} opts Optional parameters
* @param {String} opts.slug Filter results by fragment slug
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/Fragment>}
*/
this.listOrganizationFragments = function(organizationId, opts) {
opts = opts || {};
var postBody = null;
// verify the required parameter 'organizationId' is set
if (organizationId == undefined || organizationId == null) {
throw "Missing the required parameter 'organizationId' when calling listOrganizationFragments";
}
var pathParams = {
'organizationId': organizationId
};
var queryParams = {
'slug': opts['slug']
};
var headerParams = {
};
var formParams = {
};
var authNames = ['basicAuth'];
var contentTypes = ['application/json;charset=utf-8'];
var accepts = ['application/json;charset=utf-8'];
var returnType = [Fragment];
return this.apiClient.callApi(
'/organizations/{organizationId}/fragments', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2744
|
train
|
function() {
canReflect.onValue( observation, updater,"notify");
if (observation.hasOwnProperty("_value")) {// can-observation 4.1+
compute.value = observation._value;
} else {// can-observation < 4.1
compute.value = observation.value;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2745
|
train
|
function(apiClient) {
this.apiClient = apiClient || ApiClient.instance;
/**
* Finds a phone service channel by id
* Finds a phone service channel by id
* @param {String} phoneServiceChannelId Phone service channel id
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PhoneServiceChannel}
*/
this.findPhoneServiceChannel = function(phoneServiceChannelId) {
var postBody = null;
// verify the required parameter 'phoneServiceChannelId' is set
if (phoneServiceChannelId == undefined || phoneServiceChannelId == null) {
throw "Missing the required parameter 'phoneServiceChannelId' when calling findPhoneServiceChannel";
}
var pathParams = {
'phoneServiceChannelId': phoneServiceChannelId
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var authNames = ['basicAuth'];
var contentTypes = ['application/json;charset=utf-8'];
var accepts = ['application/json;charset=utf-8'];
var returnType = PhoneServiceChannel;
return this.apiClient.callApi(
'/phoneServiceChannels/{phoneServiceChannelId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
/**
* Lists phone service channels
* Lists phone service channels
* @param {Object} opts Optional parameters
* @param {String} opts.organizationId Organization id
* @param {String} opts.search Search channels by free-text query
* @param {String} opts.sortBy define order (NATURAL or SCORE). Default is NATURAL
* @param {String} opts.sortDir ASC or DESC. Default is ASC
* @param {Integer} opts.firstResult First result
* @param {Integer} opts.maxResults Max results
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/PhoneServiceChannel>}
*/
this.listPhoneServiceChannels = function(opts) {
opts = opts || {};
var postBody = null;
var pathParams = {
};
var queryParams = {
'organizationId': opts['organizationId'],
'search': opts['search'],
'sortBy': opts['sortBy'],
'sortDir': opts['sortDir'],
'firstResult': opts['firstResult'],
'maxResults': opts['maxResults']
};
var headerParams = {
};
var formParams = {
};
var authNames = ['basicAuth'];
var contentTypes = ['application/json;charset=utf-8'];
var accepts = ['application/json;charset=utf-8'];
var returnType = [PhoneServiceChannel];
return this.apiClient.callApi(
'/phoneServiceChannels', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
/**
* Updates a channel
* Updates a service channel
* @param {String} phoneServiceChannelId phone channel id
* @param {module:model/PhoneServiceChannel} payload New phone service data
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PhoneServiceChannel}
*/
this.updatePhoneServiceChannel = function(phoneServiceChannelId, payload) {
var postBody = payload;
// verify the required parameter 'phoneServiceChannelId' is set
if (phoneServiceChannelId == undefined || phoneServiceChannelId == null) {
throw "Missing the required parameter 'phoneServiceChannelId' when calling updatePhoneServiceChannel";
}
// verify the required parameter 'payload' is set
if (payload == undefined || payload == null) {
throw "Missing the required parameter 'payload' when calling updatePhoneServiceChannel";
}
var pathParams = {
'phoneServiceChannelId': phoneServiceChannelId
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var authNames = ['basicAuth'];
var contentTypes = ['application/json;charset=utf-8'];
var accepts = ['application/json;charset=utf-8'];
var returnType = PhoneServiceChannel;
return this.apiClient.callApi(
'/phoneServiceChannels/{phoneServiceChannelId}', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2746
|
ProblemLogger
|
train
|
function ProblemLogger(options) {
options = options || {};
ConsoleLogger.call(this);
const tmpdir = require('os').tmpdir();
this.filename = path.join(tmpdir, 'logger-' + (+new Date()) + '.log');
this.name = options.problemLogName || ((options.name || 'problem') + '.log');
this.stream = fs.createWriteStream(this.filename);
this.write({ level: bunyan.TRACE, msg: util.format('log file opened') });
streams.push(this);
}
|
javascript
|
{
"resource": ""
}
|
q2747
|
closeStreams
|
train
|
function closeStreams(exitCode) {
// default is 0 if not specified
exitCode = exitCode === undefined ? 0 : exitCode;
if (streams.length) {
streams.forEach(function (logger) {
logger.write({ level: bunyan.TRACE, msg: util.format('exited with code %d', exitCode) });
logger.stream.end();
// jscs:disable jsDoc
logger.write = function () {};
});
}
}
|
javascript
|
{
"resource": ""
}
|
q2748
|
train
|
function(l) {
debug('Attaching link ' + l.name + ':' + l.handle + ' after begin received');
if (l.state() !== 'attached' && l.state() !== 'attaching') l.attach();
}
|
javascript
|
{
"resource": ""
}
|
|
q2749
|
role
|
train
|
function role(value) {
if (typeof value === 'boolean')
return value;
if (value !== 'sender' && value !== 'receiver')
throw new errors.EncodingError(value, 'invalid role');
return (value === 'sender') ? false : true;
}
|
javascript
|
{
"resource": ""
}
|
q2750
|
listBuilder
|
train
|
function listBuilder(list, bufb, codec, width) {
if (!Array.isArray(list)) {
throw new errors.EncodingError(list, 'Unsure how to encode non-array as list');
}
if (!width && list.length === 0) {
bufb.appendUInt8(0x45);
return;
}
// Encode all elements into a temp buffer to allow us to front-load appropriate size and count.
var tempBuilder = new Builder();
var _len = list.length;
for (var _i = 0; _i < _len; ++_i) codec.encode(list[_i], tempBuilder);
var tempBuffer = tempBuilder.get();
// Code, size, length, data
if (width === 1 || (tempBuffer.length < 0xFF && list.length < 0xFF && width !== 4)) {
// list8
if (!width) bufb.appendUInt8(0xC0);
bufb.appendUInt8(tempBuffer.length + 1);
bufb.appendUInt8(list.length);
} else {
// list32
if (!width) bufb.appendUInt8(0xD0);
bufb.appendUInt32BE(tempBuffer.length + 4);
bufb.appendUInt32BE(list.length);
}
bufb.appendBuffer(tempBuffer);
}
|
javascript
|
{
"resource": ""
}
|
q2751
|
mapBuilder
|
train
|
function mapBuilder(map, bufb, codec, width) {
if (typeof map !== 'object') {
throw new errors.EncodingError(map, 'Unsure how to encode non-object as map');
}
if (Array.isArray(map)) {
throw new errors.EncodingError(map, 'Unsure how to encode array as map');
}
var keys = Object.keys(map);
if (!width && keys.length === 0) {
bufb.appendUInt8(0xC1);
bufb.appendUInt8(1);
bufb.appendUInt8(0);
return;
}
// Encode all elements into a temp buffer to allow us to front-load appropriate size and count.
var tempBuilder = new Builder();
var _len = keys.length;
for (var _i = 0; _i < _len; ++_i) {
codec.encode(keys[_i], tempBuilder);
codec.encode(map[keys[_i]], tempBuilder);
}
var tempBuffer = tempBuilder.get();
// Code, size, length, data
if (width === 1 || (width !== 4 && tempBuffer.length < 0xFF)) {
// map8
if (!width) bufb.appendUInt8(0xC1);
bufb.appendUInt8(tempBuffer.length + 1);
bufb.appendUInt8(keys.length * 2);
} else {
// map32
if (!width) bufb.appendUInt8(0xD1);
bufb.appendUInt32BE(tempBuffer.length + 4);
bufb.appendUInt32BE(keys.length * 2);
}
bufb.appendBuffer(tempBuffer);
}
|
javascript
|
{
"resource": ""
}
|
q2752
|
assertArguments
|
train
|
function assertArguments(options, argnames) {
if (!argnames) return;
if (!options) throw new TypeError('missing arguments: ' + argnames);
argnames.forEach(function (argname) {
if (!options.hasOwnProperty(argname)) {
throw new TypeError('missing argument: ' + argname);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q2753
|
Sasl
|
train
|
function Sasl(mechanism, handler) {
if (!mechanism || !handler) {
throw new errors.NotImplementedError('Need both the mechanism and the handler');
}
this.mechanism = mechanism;
this.handler = handler;
this.receivedHeader = false;
}
|
javascript
|
{
"resource": ""
}
|
q2754
|
Policy
|
train
|
function Policy(overrides) {
if (!(this instanceof Policy))
return new Policy(overrides);
u.defaults(this, overrides, {
/**
* support subjects in link names with the following characteristics:
* receiver: "amq.topic/news", means a filter on the ReceiverLink will be made
* for messages send with a subject "news"
*
* sender: "amq.topic/news", will automatically set "news" as the subject for
* messages sent on this link, unless the user explicitly overrides
* the subject.
*
* @name Policy#defaultSubjects
* @property {boolean}
*/
defaultSubjects: true,
/**
* Options related to the reconnect behavior of the client. If this value is `null` reconnect
* is effectively disabled
*
* @name Policy#reconnect
* @type {Object|null}
* @property {number|null} [retries] How many times to attempt reconnection
* @property {string} [strategy='fibonacci'] The algorithm used for backoff. Can be `fibonacci` or `exponential`
* @property {boolean} [forever] Whether or not to attempt reconnection forever
*/
reconnect: {
retries: 10,
strategy: 'fibonacci', // || 'exponential'
forever: true
},
/**
* @name Policy#connect
* @type {object}
* @property {object} options Options passed into the open performative on initial connection
* @property {string|function} options.containerId The id of the source container
* @property {string} options.hostname The name of the target host
* @property {number} options.maxFrameSize The largest frame size that the sending peer is able to accept on this connection
* @property {number} options.channelMax The channel-max value is the highest channel number that can be used on the connection
* @property {number} options.idleTimeout The idle timeout required by the sender
* @property {array<string>|null} options.outgoingLocales A list of the locales that the peer supports for sending informational text
* @property {array<string>|null} options.incomingLocales A list of locales that the sending peer permits for incoming informational text
* @property {array<string>|null} options.offeredCapabilities A list of extension capabilities the peer may use if the sender offers them
* @property {array|null} options.desiredCapabilities The desired-capability list defines which extension capabilities the sender may use if the receiver offers them
* @property {object|null} options.properties The properties map contains a set of fields intended to indicate information about the connection and its container
* @property {object} sslOptions Options used to initiate a TLS/SSL connection, with the exception of the following options all options in this object are passed directly to node's [tls.connect](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback) method.
* @property {string|null} sslOptions.keyFile Path to the file containing the private key for the client
* @property {string|null} sslOptions.certFile Path to the file containing the certificate key for the client
* @property {string|null} sslOptions.caFile Path to the file containing the trusted cert for the client
* @property {boolean} sslOptions.rejectUnauthorized
* @property {string|null} saslMechanism Allows the sasl mechanism to be overriden by policy
*/
connect: {
options: {
containerId: containerName(),
hostname: 'localhost',
maxFrameSize: constants.defaultMaxFrameSize,
channelMax: constants.defaultChannelMax,
idleTimeout: constants.defaultIdleTimeout,
outgoingLocales: constants.defaultOutgoingLocales,
incomingLocales: constants.defaultIncomingLocales,
offeredCapabilities: null,
desiredCapabilities: null,
properties: {},
},
sslOptions: {
keyFile: null,
certFile: null,
caFile: null,
rejectUnauthorized: false
},
saslMechanism: null
},
/**
* @name Policy#session
* @type {object}
* @property {object} options Options passed into the `begin` performative on session start
* @property {number} options.nextOutgoingId The transfer-id to assign to the next transfer frame
* @property {number} options.incomingWindow The maximum number of incoming transfer frames that the endpoint can currently receive
* @property {number} options.outgoingWindow The maximum number of outgoing transfer frames that the endpoint can currently send
* @property {function} window A function used to calculate how/when the flow control window should change
* @property {number} windowQuantum Quantum used in predefined window policies
* @property {boolean} enableSessionFlowControl Whether or not session flow control should be performed at all
* @property {object|null} reestablish=null Whether the session should attempt to reestablish when ended by the broker
*/
session: {
options: {
nextOutgoingId: constants.session.defaultOutgoingId,
incomingWindow: constants.session.defaultIncomingWindow,
outgoingWindow: constants.session.defaultOutgoingWindow
},
window: putils.WindowPolicies.RefreshAtHalf,
windowQuantum: constants.session.defaultIncomingWindow,
enableSessionFlowControl: true,
reestablish: null
},
/**
* @name Policy#senderLink
* @type {object}
* @property {object} attach Options passed into the `attach` performative on link attachment
* @property {string|function} attach.name This name uniquely identifies the link from the container of the source to the container of the target node
* @property {string|boolean} attach.role The role being played by the peer
* @property {string|number} attach.sndSettleMode The delivery settlement policy for the sender
* @property {number} attach.maxMessageSize The maximum message size supported by the link endpoint
* @property {number} attach.initialDeliveryCount This must not be null if role is sender, and it is ignored if the role is receiver.
* @property {string} callback Determines when a send should call its callback ('settle', 'sent', 'none')
* @property {function|null} encoder=null The optional encoder used for all outgoing sends
* @property {boolean|null} reattach=null Whether the link should attempt reattach on detach
*/
senderLink: {
attach: {
name: linkName('sender'),
role: constants.linkRole.sender,
sndSettleMode: constants.senderSettleMode.mixed,
maxMessageSize: 0,
initialDeliveryCount: 1
},
callback: putils.SenderCallbackPolicies.OnSettle,
encoder: null,
reattach: null
},
/**
* @name Policy#receiverLink
* @type {object}
* @property {object} attach Options passed into the `attach` performative on link attachment
* @property {string|function} attach.name This name uniquely identifies the link from the container of the source to the container of the target node
* @property {boolean} attach.role The role being played by the peer
* @property {number|string} attach.rcvSettleMode The delivery settlement policy for the receiver
* @property {number} attach.maxMessageSize The maximum message size supported by the link endpoint
* @property {number} attach.initialDeliveryCount This must not be null if role is sender, and it is ignored if the role is receiver.
* @property {function} credit A function that determines when (if ever) to refresh the receiver link's credit
* @property {number} creditQuantum Quantum used in pre-defined credit policy functions
* @property {function|null} decoder=null The optional decoder used for all incoming data
* @property {boolean|null} reattach=null Whether the link should attempt reattach on detach
*/
receiverLink: {
attach: {
name: linkName('receiver'),
role: constants.linkRole.receiver,
rcvSettleMode: constants.receiverSettleMode.autoSettle,
maxMessageSize: 10000, // Arbitrary choice
initialDeliveryCount: 1
},
credit: putils.CreditPolicies.RefreshAtHalf,
creditQuantum: 100,
decoder: null,
reattach: null
},
});
putils.fixDeprecatedLinkOptions(this.senderLink);
putils.fixDeprecatedLinkOptions(this.receiverLink);
return this;
}
|
javascript
|
{
"resource": ""
}
|
q2755
|
train
|
function (onDone) {
// store what to do after connected
// NOTE: may be called repeatedly (if initial attempts fail or disconnect happens)
if (typeof onDone === 'function')
l_onConnect = onDone;
if (l_ip_port === undefined) {
LOG.warn('not init (or already disposed), cannot connect to server');
return;
}
if (l_connector === undefined)
l_connector = new SR.Connector(l_config);
// establish connection
LOG.warn('connecting to: ', l_name);
LOG.warn(l_ip_port, l_name);
l_connector.connect(l_ip_port, function (err, socket) {
if (err) {
// try-again later
LOG.warn('connect failed, try to re-connect in: ' + l_timeoutConnectRetry + 'ms', l_name);
setTimeout(l_connect, l_timeoutConnectRetry);
return;
}
LOG.warn('connection to: ' + socket.host + ':' + socket.port + ' established', l_name);
UTIL.safeCall(l_onConnect);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2756
|
train
|
function (latest_log) {
if (latest_log !== null && latest_log.type !== "SYSTEM_DOWN") {
LOG.warn("server crashed last time", 'handlers.system');
LOG.event("SYSTEM_CRASHED", SR.Settings.SERVER_INFO);
}
LOG.event("SYSTEM_UP", SR.Settings.SERVER_INFO);
}
|
javascript
|
{
"resource": ""
}
|
|
q2757
|
train
|
function () {
if (queue.length > 0) {
if (queue.length % 500 === 0)
LOG.warn('socketio queue: ' + queue.length);
var item = queue.shift();
socket.busy = true;
socket.emit('SRR', item);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2758
|
train
|
function () {
SR.fs.close(l_logs[log_id].fd,
function () {
console.log(l_name + '::l_closeLog::' + SR.Tags.YELLOW + 'LogID=' + log_id + ' closed.' + SR.Tags.ERREND);
delete l_logs[log_id];
onDone(log_id);
}
);
}
|
javascript
|
{
"resource": ""
}
|
|
q2759
|
train
|
function (appID, locationID) {
// check if location exists
if (l_locations.hasOwnProperty(locationID) === false) {
LOG.error('locationID: ' + locationID + ' does not exist', 'addApp');
return;
}
// check if already exists, ignore action if already exists
if (l_apps.hasOwnProperty(appID) === true) {
LOG.error('appID: ' + appID + ' already exists', 'addApp');
return;
}
// insert new app record for this location
l_apps[appID] = {
locationID: locationID,
users: {}
}
// build mapping from location to app
// TODO: (needed? or can simplfiy?)
l_locations[locationID].apps[appID] = l_apps[appID];
}
|
javascript
|
{
"resource": ""
}
|
|
q2760
|
train
|
function (upload) {
if (!upload || !upload.path || !upload.name || !upload.size) {
LOG.error('upload object incomplete:', l_name);
return;
}
// record basic file info
var arr = upload.path.split('/');
var upload_name = arr[arr.length-1];
var filename = (preserve_name ? upload.name : upload_name);
LOG.warn("The file " + upload.name + " was uploaded as: " + filename + ". size: " + upload.size, l_name);
uploaded.push({name: filename, size: upload.size, type: upload.type});
// check if we might need to re-name
// default is to rename (preserve upload file names)
if (preserve_name === false) {
return;
}
var new_name = SR.path.resolve(form.uploadDir, upload.name);
SR.fs.rename(upload.path, new_name, function (err) {
if (err) {
return LOG.error('rename fail: ' + new_name, l_name);
}
LOG.warn("File " + upload_name + " renamed as: " + upload.name + " . size: " + upload.size, l_name);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2761
|
train
|
function (id) {
LOG.warn('server started: ' + server_type, l_name);
// check if we should notify start server request
for (var i=0; i < l_pendingStart.length; i++) {
var task = l_pendingStart[i];
if (task.server_type !== server_type) {
continue;
}
LOG.warn('pending type matched: ' + task.server_type, l_name);
// record server id, check for return
task.servers.push(id);
task.curr++;
// store this process id
if (l_started.hasOwnProperty(server_type) === false)
l_started[server_type] = [];
// NOTE: we currently do not maintain this id, should we?
l_started[server_type].push(id);
// check if all servers of a particular type are started
if (task.curr === task.total) {
UTIL.safeCall(task.onDone, null, task.servers);
// remove this item until app servers have also reported back
l_pendingStart.splice(i, 1);
}
break;
}
// delete log
l_deleteStartedServer({
owner: args.owner,
project: args.project,
name: args.name
});
// log started server
l_getServerInfo({
owner: args.owner,
project: args.project,
name: args.name,
size: args.size
}, 1);
}
|
javascript
|
{
"resource": ""
}
|
|
q2762
|
train
|
function (exec_path, onExec) {
var onFound = function () {
// if file found, execute directly
// store starting path
args.exec_path = exec_path;
LOG.warn('starting ' + size + ' [' + server_type + '] servers', l_name);
// store an entry for the callback when all servers are started as requested
// TODO: if it takes too long to start all app servers, then force return in some interval
l_pendingStart.push({
onDone: onDone,
total: size,
curr: 0,
server_type: server_type,
servers: []
});
start_server();
}
var file_path = SR.path.join(exec_path, args.name, 'frontier.js');
LOG.warn('validate file_path: ' + file_path, l_name);
// verify frontier file exists, if not then we try package.json
SR.fs.stat(file_path, function (err, stats) {
// file not found
if (err) {
file_path = SR.path.join(exec_path, 'package.json');
// remove server name from parameter
args.name = '';
SR.fs.stat(file_path, function (err, stats) {
if (err) {
return onExec('cannot find entry file');
}
onFound();
});
}
onFound();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2763
|
convertApiError
|
train
|
function convertApiError(err) {
if (err.error && err.error.response && err.error.response.text) {
const obj = JSON.parse(err.error.response.text);
if (obj.errors && obj.errors.length) {
err = { message: obj.errors[0].message, error:err.error };
}
}
return err;
}
|
javascript
|
{
"resource": ""
}
|
q2764
|
train
|
function (area, layer) {
// check if layer exists
if (l_layers.hasOwnProperty(layer) === false)
return [];
// get all current subscriptions at this layer
var subs = l_layers[layer];
// prepare list of connection of subscribers matching / covering the area
var connections = [];
// check each subscription to see if it overlaps with the given area
for (var id in subs) {
var subscription = subs[id];
// check for overlaps (distance between the two centers is less than sum of radii)
if (l_dist(subscription, para) <= (subscription.r + para.r))
connections.push(subscription.conn);
}
return connections;
}
|
javascript
|
{
"resource": ""
}
|
|
q2765
|
train
|
function (event) {
// if event is not from socket, no need to queue
// TODO: remove connection-specific code from here
if (event.conn.type !== 'socket')
return true;
var socket = event.conn.connector;
// if no mechanism to store (such as from a bot), just ignore
// TODO: this is not clean
if (typeof socket.queuedEvents === 'undefined')
socket.queuedEvents = {};
var queue_size = Object.keys(socket.queuedEvents).length;
if (queue_size > l_queuedEventsPerSocket) {
LOG.warn('queued event size: ' + queue_size + ' limit exceeded (' + l_queuedEventsPerSocket + ')', l_name);
// DEBUG purpose (print out events queued)
for (var i in socket.queuedEvents)
LOG.sys('queuedEvents[' + i + '] =' + UTIL.stringify(socket.queuedEvents[i].data), l_name);
return false;
}
// store event with the ID to socket's eventlist
socket.queuedEvents[event.id] = event;
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q2766
|
train
|
function (event) {
// check if connection object exists
if (typeof event.conn === 'undefined') {
LOG.error('no connection records, cannot respond to request', l_name);
return false;
}
// if no mechanism to store (such as from a bot), just ignore
// TODO: cleaner approach?
if (event.conn.type !== 'socket' ||
event.conn.connector.queuedEvents === undefined) {
return true;
}
var socket = event.conn.connector;
// check if id exist
if (socket.queuedEvents.hasOwnProperty(event.id) === false) {
LOG.error('event not found. id = ' + event.id, l_name);
LOG.stack();
return false;
}
// remove current event from the socket's event queues
delete socket.queuedEvents[event.id];
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q2767
|
train
|
function (req, res) {
LOG.warn('handle_request');
// attach custom res methods (borrowed from express)
res = UTIL.mixin(res, response);
LOG.sys('HTTP req received, header', 'SR.REST');
LOG.sys(req.headers, 'SR.REST');
var content_type = req.headers['content-type'];
// NOTE: multi-part needs to be handled first, because req.on('data') will not be able to process correctly
if (typeof content_type === 'string' && content_type.startsWith('multipart/form-data; boundary=')) {
LOG.warn('parsing form request...', 'SR.REST');
route(req, res);
return;
}
// temp buffer for incoming request
var data = '';
var JSONobj = undefined;
req.on('data', function (chunk) {
data += chunk;
});
req.on('end', function () {
var JSONobj = undefined;
try {
if (data !== '') {
if (content_type.startsWith('application/x-www-form-urlencoded')) {
JSONobj = qs.parse(data);
} else if (content_type.startsWith('application/json')) {
JSONobj = UTIL.convertJSON(decodeURIComponent(data));
} else if (content_type.startsWith('application/sdp')) {
JSONobj = data;
} else {
var msg = 'content type not known: ' + content_type;
LOG.warn(msg, 'SR.REST');
SR.REST.reply(res, msg);
//res.writeHead(200, {'Content-Type': 'text/plain'});
//res.end(msg);
return;
}
}
} catch (e) {
var msg = 'JSON parsing error for data: ' + data + '\n content_type: ' + content_type;
LOG.error(msg, 'SR.REST');
//res.writeHead(200, {'Content-Type': 'text/plain'});
//res.end(msg);
SR.REST.reply(res, msg);
return;
}
route(req, res, JSONobj);
})
}
|
javascript
|
{
"resource": ""
}
|
|
q2768
|
train
|
function (account, data, conn) {
//if (l_logins.hasOwnProperty(account) === true)
//return false;
// check if user's unique data exists
if (typeof data.data !== 'object') {
LOG.error('data field does not exist, cannot add login data');
return false;
}
LOG.warn('account: ' + account + ' data:', 'addLogin');
LOG.warn(data);
// attach login name to connection
// NOTE: we attach connection object to the data stored in memory (not clean?)
if (conn) {
// NOTE: we use session because this request could come from an HTTP request
// that does not have a persistent connectino record in SR.Conn
SR.Conn.setSessionName(conn, account);
data._conn = conn;
}
l_logins[account] = data;
LOG.warn('user [' + account + '] login success, total count: ' + Object.keys(l_logins).length, 'user');
delete data._conn;
//console.log(data);
// error check: make sure lastStatus field exists
if (data.hasOwnProperty('lastStatus') === false || data.lastStatus === null)
data.lastStatus = {loginCount: 0};
data.lastStatus.loginIP = conn.host;
data.lastStatus.loginCount = data.lastStatus.loginCount + 1;
data.lastStatus.time = conn.time;
SR.DB.updateData(SR.Settings.DB_NAME_ACCOUNT, {account: account}, data,
function () {
},
function () {
});
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q2769
|
train
|
function (error) {
if (error) {
var err = new Error("set custom data for account [" + account + "] fail");
err.name = "setUser Error";
LOG.error('set custom data for account [' + account + '] fail', 'user');
UTIL.safeCall(onDone, err);
}
else {
LOG.warn('set custom data for account [' + account + '] success', 'user');
UTIL.safeCall(onDone, null);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2770
|
train
|
function (uid, token) {
// TODO: check if local account already exists, or replace existing one
// multiple accounts storable for one local server
// NOTE: field name is a variable
// ref: http://stackoverflow.com/questions/11133912/how-to-use-a-variable-as-a-field-name-in-mongodb-native-findandmodify
var field = 'data.accounts.' + server + '.' + uid;
var onUpdated = function (error) {
if (error) {
var err = new Error("ADD_LOCAL_ACCOUNT_FAIL: " + account);
err.name = "addLocal Error";
err.code = 1;
UTIL.safeCall(onDone, err);
}
else {
UTIL.safeCall(onDone, null, {code: 0, msg: 'ADD_LOCAL_ACCOUNT_SUCCESS: ' + account});
}
};
l_updateUser({account: account}, field, token, onUpdated);
}
|
javascript
|
{
"resource": ""
}
|
|
q2771
|
train
|
function (error) {
if (error) {
var err = new Error(error.toString());
err.name = "l_createToken Error";
UTIL.safeCall(onDone, err);
}
else {
LOG.warn('pass_token [' + token + '] stored');
UTIL.safeCall(onDone, null, token);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2772
|
train
|
function (msgtype, event) {
// we only forward for non-SR user-defined events at lobby
if (SR.Settings.SERVER_INFO.type !== 'lobby' || msgtype.startsWith('SR'))
return false;
// check if we're lobby and same-name app servers are available
var list = SR.AppConn.queryAppServers();
LOG.sys('check forward for: ' + msgtype + ' app server size: ' + Object.keys(list).length, l_name);
var minload_id = undefined;
var minload = 10000;
for (var id in list) {
var info = list[id];
if (info.type === 'app' && info.name === SR.Settings.SERVER_INFO.name) {
LOG.warn('found forward target [' + id + '] loading: ' + info.usercount, l_name);
if (info.usercount < minload) {
minload_id = id;
minload = info.usercount;
}
}
}
// an app server with minimal loading is available, relay the event
if (minload_id) {
SR.RPC.relayEvent(minload_id, msgtype, event);
return true;
}
// no need to forward, local execution
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q2773
|
train
|
function (response_type, event) {
LOG.sys('handling event response [' + response_type + ']', l_name);
// go over each registered callback function and see which one responds
for (var i=0; i < l_responders[response_type].length; i++) {
// find the callback with matching client id
// call callback and see whether it has been processed
if (l_responders[response_type][i].cid === event.cid) {
// log incoming message type & IP/port
LOG.sys(SR.Tags.RCV + response_type + ' from ' + event.printSource() + SR.Tags.END, l_name);
// make callback
UTIL.safeCall(l_responders[response_type][i].onResponse, event);
// then remove it
l_responders[response_type].splice(i, 1);
i--;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2774
|
train
|
function (e, req, res, host) {
LOG.error('proxy error for host: ' + host + '. remove from active proxy list:', 'SR.Proxy');
LOG.error(e, 'SR.Proxy');
// remove proxy info from list
delete l_proxies[host];
// notify for proxy failure
UTIL.safeCall(onProxyFail, host);
// send back to client about the proxy error
res.writeHead(502, {
'Content-Type': 'text/plain'
});
res.end('PROXY_ERROR: cannot access proxy: ' + host);
}
|
javascript
|
{
"resource": ""
}
|
|
q2775
|
JobQueue
|
train
|
function JobQueue(para) {
this.queue = [];
this.curr = 0;
this.all_passed = true;
this.timeout = ((typeof para === 'object' && typeof para.timeout === 'number') ? para.timeout : 0);
}
|
javascript
|
{
"resource": ""
}
|
q2776
|
train
|
function () {
if (item.done === false) {
LOG.error('job timeout! please check if the job calls onDone eventually. ' + (item.name ? '[' + item.name + ']' : ''), l_name);
// force this job be done
onJobDone(false);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2777
|
train
|
function (list) {
for (var i=0; i < list.length; i++) {
for (var j=0; j < l_entries.length; j++) {
if (list[i] === l_entries[j]) {
l_entries.splice(j, 1);
break;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2778
|
getInput
|
train
|
function getInput() {
var account = document.getElementById('account').value;
var email = (document.getElementById('email') ? document.getElementById('email').value : '');
var password = document.getElementById('password').value;
return {account: account, email: email, password: password};
}
|
javascript
|
{
"resource": ""
}
|
q2779
|
train
|
function (err, data) {
if (err) {
LOG.warn(err.toString());
}
else {
for (var server in data.accounts) {
LOG.warn('local server: ' + server);
var user_list = data.accounts[server];
for (var uid in user_list) {
var token = user_list[uid];
LOG.warn('local uid: ' + uid + ' token: ' + token);
l_send_remote_login(server, uid, token);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2780
|
train
|
function (server, uid, token) {
try {
// convert uid to number if not already
if (typeof uid === 'string')
uid = parseInt(uid);
}
catch (e) {
LOG.error('uid cannot be parsed as integer...', 'login.send_remote_login');
return false;
}
SR.User.loginLocal(server, uid, token, function (result) {
// NOTE: if local server is not registered, will return 'undefined' as result
if (result) {
// NOTE: result has U and P fields
LOG.warn('local login result for [' + uid + ']: ' + (result.code === 0));
}
else
LOG.warn('local login result for [' + uid + ']: remote server not online');
});
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q2781
|
train
|
function (login_id, session, data) {
// acknowledge as 'logined'
l_loginID[login_id] = data.account;
// init session
session['_account'] = data.account;
// TODO: needs to fix this, should read "groups" from DB
session['_groups'] = data.groups;
session['_permissions'] = data.permissions;
session['lastStatus'] = data.lastStatus;
// TODO: centralize handling of logined users?
//SR.User.addGroup(user_data.account, ['user', 'admin']);
}
|
javascript
|
{
"resource": ""
}
|
|
q2782
|
train
|
function (err, result) {
// if login is successful, we record the user's account in cache
if (err) {
LOG.warn(err.toString());
result = {code: err.code, msg: err.message};
}
else {
if (result.code === 0) {
LOG.warn('login success, result: ');
LOG.warn(result);
var data = {
account: user_data.account,
groups: result.data.groups,
lastStatus: result.data.lastStatus,
permissions: []
}
l_initSession(event.data.login_id, event.session, data);
/*
// todo: read permssion from DB
//event.session['_permissions'] = result.data.permissions;
var xx = [];
var onSuccess = function(dat){
//console.log(dat.permission);
if (dat === null) {
console.log("no permission");
}
else {
for (var i in dat.permission) {
//console.log("pushing: " + dat.permission[i]);
xx.push(dat.permission[i]);
}
}
//event.done("get group", {"status": "success", "data": data});
};
var onFail = function(dat){
//event.done("get group", {"status": "failure", "data": data});
};
for (var i in event.session['_groups']) {
//console.log("getting: " + event.session['_groups'][i]);
SR.DB.getData(groupPermissionDB, {"group": event.session['_groups'][i], part: "group"}, onSuccess, onFail);
}
*/
// TODO: login at once to all local accounts
// NOTE: need to query all local login account name & password, then perform individual logins
l_login_local_accounts(user_data.account);
}
}
//LOG.warn('event before sending login response:');
//LOG.warn(event);
//if (result.data) delete result.data;
// return response regardless success or fail
event.done('SR_LOGIN_RESPONSE', result);
}
|
javascript
|
{
"resource": ""
}
|
|
q2783
|
train
|
function (arg) {
if ( ! arg.allow ){
return;
}
var exist = false;
for (var i in data.allow) {
if (data.allow[i] === arg.allow) {
exist = true;
}
}
if ( exist === false ) {
data.allow[data.allow.length] = arg.allow;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2784
|
Connection
|
train
|
function Connection (type, sender, from) {
// provide default 'from' values
from = from || {};
// connection-specific UUID
this.connID = UTIL.createUUID();
// a project-specific / supplied name (can be account or app name)
this.name = '';
// sender function associated with this connection
this.connector = sender;
// store pointers on how to respond
this.type = type;
// where the connection comes from (default to nothing)
this.host = from.host || '';
this.port = from.port || 0;
// time when this connection is established
this.time = new Date();
// append cookie, if available (this is useful if the event will be relayed to another server to execute,
// cookie can then be preserved
if (from.cookie)
this.cookie = from.cookie;
}
|
javascript
|
{
"resource": ""
}
|
q2785
|
train
|
function () {
// get a event from the front of queue
var tmdata = queue.dequeue();
// whether to keep processing (default is no)
busy = false;
// check if data exists
if (tmdata === undefined) {
return;
}
// handle the event if handler is available
if (handler === null) {
console.log(SR.Tags.ERR + 'handler undefined, cannot process event' + ERREND);
return;
}
switch (handler(tmdata)) {
// if the event is not handled, re-queue it
case false:
queue.enqueue(tmdata);
break;
// return true, keep processing
case true:
break;
/*
// NOTE: we do not pause continuing execution, because it's possible for a event
// to consider it finished, re-activate the queue (which it think it has paused),
// but then the execution runs to the end of handler, and returning a undefine to pause icQueue
// this will thus cause a event to indefinitely pause without any on-going progress.
//
// Currently if the event has returned, we assume it's been processed.
// If not yet, then it's up to the handler to re-enqueue the event (by returning 'false')
// note that it's possible that the previous event is still being processed
// (for example, waiting for DB to return), while the next event starts processing
// so the ordering may not be preserved.
// The assumption we have is that events are relatively independent from each other
// so such out-of-sequence processing may be "okay," as long as handler will properly re-queue the event
// in case it needs to be processed again
//
*/
// did not return anything, pause execution
default:
//console.log(SR.Tags.WARN + 'pause processing event, callee: ' + arguments.callee.name);
return;
break;
}
// keep processing
busy = true;
UTIL.asyncCall(processEvent);
}
|
javascript
|
{
"resource": ""
}
|
|
q2786
|
train
|
function (arr) {
// extract collection name
if (arr && typeof arr._name === 'string') {
var size = arr.length - arr._index;
if (size <= 0)
return false;
LOG.sys('try to store to array [' + arr._name + '], # of elements to store: ' + size, 'SR.Sync');
// TODO: wasteful of space?
// NOTE: only new array entries will be stored to DB
var elements = [];
for (var i=arr._index; i < arr.length; i++)
elements.push(arr[i]);
// update index count (regardless of update success or not?)
arr._index = arr.length;
// TODO: find right way to store
// store away
// NOTE: $each is used here (try to hide it?)
SR.DB.updateArray(SR.Settings.DB_NAME_SYNC, {name: arr._name}, {data: elements},
function (result) {
LOG.sys('update array success: ' + result, 'SR.Sync');
},
function (result) {
LOG.error('update array fail: ' + result, 'SR.Sync');
}
);
return true;
}
else
LOG.error('cannot store to DB, arr_name unavailable', 'SR.Sync');
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q2787
|
train
|
function (arrays, config, onDone) {
var names = [];
// load array's content from DB, if any
SR.DB.getArray(SR.Settings.DB_NAME_SYNC,
function (result) {
// NOTE: if array does not exist it'll return success with an empty array
if (result === null || result.length === 0) {
LOG.warn('no arrays found, cannot load', 'SR.Sync');
}
else {
var array_limit = (typeof config.limit === 'number' ? config.limit : 0);
LOG.sys('arrays exist, try to load (limit: ' + array_limit + ')', 'SR.Sync');
for (var i=0; i < result.length; i++) {
var record = result[i];
var arr = arrays[record.name] = [];
// load data (clone is better?)
var limit = (record.data.length > array_limit ? array_limit : record.data.length);
var start = record.data.length - limit;
for (var j=0; j < limit; j++)
arr[j] = UTIL.clone(record.data[start+j]);
// override array's default behavior
arr.push = l_push;
// store array's name
arr._name = record.name;
// store last stored index (next index to store)
arr._index = j;
LOG.sys('[' + record.name + '] DB record length: ' + record.data.length + ' start: ' + start + ' actual limit: ' + limit + ' _index: ' + arr._index, 'SR.Sync');
l_names[record.name] = arr;
names.push(record.name);
}
}
UTIL.safeCall(onDone, names);
},
function (result) {
UTIL.safeCall(onDone, names);
},
{});
}
|
javascript
|
{
"resource": ""
}
|
|
q2788
|
train
|
function (args, result, func, extra) {
return new SR.promise(function (resolve, reject) {
UTIL.safeCall(func, args, result, function () {
UTIL.safeCall(resolve);
}, extra);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2789
|
train
|
function (args, onDone, extra) {
// if args are not provided then we shift the parameters
if (typeof args === 'function') {
extra = onDone;
onDone = args;
args = {};
}
// TODO: perform argument type check (currently there's none, so internal API calls won't do type checks)
// TODO: move checker to here
var onError = function(err) {
LOG.error('onError '+ err, l_name);
UTIL.safeCall(onDone, err);
}
function onExec() {
// make actual call to user-defined function
// NOTE: we also return values for direct function calls
return UTIL.safeCall(l_list[name], args, function (err, result, unsupported_return) {
if (err) {
LOG.error('[' + name + '] error:', l_name);
LOG.error(err, l_name);
}
if (unsupported_return) {
var errmsg = 'onDone() in SR.API does not support more than one return variable, please return everything inside a result object';
LOG.error(errmsg, l_name);
LOG.stack();
return UTIL.safeCall(onDone, errmsg);
}
// perform post-event actions, if any
if (l_afterActions.hasOwnProperty(name) === false) {
return UTIL.safeCall(onDone, err, result);
}
var posts = l_afterActions[name];
var promise = undefined;
for (var i=0; i < posts.length; i++) {
if (!promise) {
promise = post_action(args, { err: err, result: result }, posts[i], extra);
} else {
promise = promise.then(post_action(args, { err: err, result: result }, posts[i], extra));
}
}
// last action
promise.then(new SR.promise(function (resolve, reject) {
//LOG.warn('everything is done... call original onDone...', l_name);
UTIL.safeCall(onDone, err, result);
resolve();
}));
}, extra);
}
// perform pre-event actions, if any
if (l_beforeActions.hasOwnProperty(name) === false) {
return onExec();
}
const pres = l_beforeActions[name].map((callback) => pre_action(args, callback, extra));
pres.reduce((p, callback) => p.then(() => callback), Promise.resolve())
.then(onExec)
.catch((err) => {
LOG.error(err);
onDone(err);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2790
|
train
|
function (account) {
// check if DB is initialized
if (typeof l_accounts === 'undefined') {
LOG.error('DB module is not loaded, please enable DB module', l_name);
return false;
}
if (l_accounts.hasOwnProperty(account) === false) {
LOG.error('[' + account + '] not found', l_name);
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q2791
|
getUIDCallback
|
train
|
function getUIDCallback (err, uid) {
if (err) {
return onDone('UID_ERROR');
}
var ip = (extra) ? extra.conn.host : "server";
// NOTE: by default a user is a normal user, user 'groups' can later be customized
var reg = {
uid: uid,
account: args.account,
password: l_encryptPass(args.password),
email: args.email,
// verify: {email_verify: false, phone_verify: false},
tokens: {reset: '', pass: {}},
enc_type: l_enc_type,
control: {groups: args.groups || [], permissions: []},
data: args.data || {},
login: {IP: ip, count: 1}
};
// special handling (by default 'admin' account is special and will be part of the 'admin' group by default
if (!args.authWP && reg.account === 'admin') {
reg.control.groups.push('admin');
}
LOG.warn('creating new account [' + args.account + ']...', l_name);
l_accounts.add(reg, function (err) {
if (err) {
return onDone('DB_ERROR', err);
}
// register success
LOG.warn('account register success', l_name);
onDone(null);
});
}
|
javascript
|
{
"resource": ""
}
|
q2792
|
train
|
function (conn) {
LOG.error('AppManager disconnected', 'SR.AppConnector');
if (SR.Settings.APPSERVER_AUTOSHUT === true) {
// shutdown this frontier
l_dispose();
SR.Settings.FRONTIER.dispose();
}
else {
LOG.warn('auto-shutdown is false, attempt to re-connect AppManager in ' + l_timeoutReconnect + ' ms...');
// keep app server alive and try to re-connect if lobby shuts down
setTimeout(l_connect, l_timeoutReconnect);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2793
|
train
|
function () {
LOG.warn('appinfo sent to lobby:');
LOG.warn(l_appinfo);
// notify AppManager we're ready
l_notifyLobby('SR_APP_READY', l_appinfo, 'SR_APP_READY_RES',
function (event) {
if (event.data.op === true)
LOG.sys('SR_APP_READY returns ok', 'l_HandlerPool');
else
LOG.error('SR_APP_READY returns fail', 'l_HandlerPool');
// call onDone if exists (but just once)
if (l_onDone) {
UTIL.safeCall(l_onDone);
l_onDone = undefined;
}
}
);
}
|
javascript
|
{
"resource": ""
}
|
|
q2794
|
train
|
function (ip_port, onDone) {
if (l_appConnector === undefined) {
LOG.warn('appConnector not init, cannot connect');
return;
}
// retrieve from previous connect attempt, also store for later connect attempt
// TODO: will need to change when lobby port becomes not fixed
ip_port = ip_port || l_ip_port;
l_ip_port = ip_port;
// store callback to be called later
// TODO: better approach?
l_onDone = onDone || l_onDone;
l_appConnector.connect(ip_port, function (err, socket) {
if (err) {
LOG.error('connection to manager: ' + ip_port.IP + ':' + ip_port.port + ' fail, try again in ' + l_timeoutReconnect + ' ms');
// TODO: do not keep trying, but rather try to re-connect after being notified by monitor server
setTimeout(l_connect, l_timeoutReconnect);
}
// connection is successful
else {
LOG.warn('connection to manager: ' + ip_port.IP + ':' + ip_port.port + ' established');
l_register();
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2795
|
train
|
function (req) {
var session = l_getSession(req);
if (session.hasOwnProperty('_user')) {
var login = session._user;
login.admin = (session._user.account === 'admin');
return login;
}
LOG.warn('user not yet logined...');
return {control: {groups: [], permissions: []}};
}
|
javascript
|
{
"resource": ""
}
|
|
q2796
|
copyFilesToPack
|
train
|
function copyFilesToPack(grunt, buildPath, filesToPack) {
return function(callback) {
grunt.util.async.forEach(filesToPack, function(fileConfig, callback) {
try {
var filepathDest;
if (detectDestType(grunt, fileConfig.dest) === 'directory') {
var dest = (fileConfig.orig.expand) ? fileConfig.dest : path.join(fileConfig.dest, fileConfig.src);
filepathDest = path.join(buildPath, dest);
} else {
filepathDest = path.join(buildPath, fileConfig.dest);
}
if (grunt.file.isDir(fileConfig.src)) {
if (fileConfig.directory) {
// Copy a whole folder to the destination directory.
grunt.verbose.writeln('Copying folder "' + fileConfig.src + '" to "' + filepathDest + '"');
fs.copyRecursive(fileConfig.src, filepathDest, callback);
} else {
// Create a folder inside the destination directory.
grunt.verbose.writeln('Creating folder "' + filepathDest + '"');
fs.mkdirs(filepathDest, callback);
}
} else {
// Copy a file to the destination directory inside the tmp folder.
if (fileConfig.link) {
grunt.verbose.writeln('Copying symlink "' + fileConfig.src + '->' + fileConfig.link + '" to "' + filepathDest + '"');
//ensure the parent directory exists when making symlinks
fs.mkdirs(getDirName(filepathDest), function(err) {
if (err) throw err;
_fs.symlink(fileConfig.link, filepathDest, 'file', callback);
});
}
else {
grunt.verbose.writeln('Copying file "' + fileConfig.src + '" to "' + filepathDest + '"');
grunt.file.copy(fileConfig.src, filepathDest);
fs.lstat(fileConfig.src, function(err, stat) {
if (err) throw err;
_fs.chmod(filepathDest, stat.mode, callback);
});
}
}
} catch(e) {
callback(e);
}
}, callback);
};
}
|
javascript
|
{
"resource": ""
}
|
q2797
|
writeSpecFile
|
train
|
function writeSpecFile(grunt, options, filesToPack) {
return function(callback) {
try {
var specPath = path.join(options.destination, specFolder);
options.files = filesToPack;
var pkg = grunt.file.readJSON('package.json');
grunt.util._.defaults(options, pkg);
options.specFilepath = path.join(specPath, options.name + '.spec');
spec(options, callback);
} catch(e) {
callback(e);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q2798
|
train
|
function () {
if (l_ip_port === undefined) {
LOG.warn('not init (or already disposed), cannot connect to server');
return;
}
if (l_connector === undefined)
l_connector = new SR.Connector(l_config);
// establish connection
LOG.warn('connecting to: ' + l_ip_port);
l_connector.connect(l_ip_port, function (err, socket) {
if (err) {
// try-again later
LOG.warn('attempt to re-connect in: ' + l_timeoutConnectRetry + 'ms');
setTimeout(l_connect, l_timeoutConnectRetry);
return;
}
LOG.warn('connection to: ' + socket.host + ':' + socket.port + ' established');
l_connector.send('SR_REGISTER_SERVER', l_para, 'SR_REGISTER_SERVER_R', function (res) {
console.log(res.data);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2799
|
train
|
function (res, res_obj) {
// return response if exist, otherwise response might be returned
// AFTER some callback is done handling (i.e., response will be returned within the handler)
if (typeof res_obj === 'string') {
LOG.sys('replying a string: ' + res_obj);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(res_obj);
}
else {
LOG.sys('replying a JSON: ' + JSON.stringify(res_obj));
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(res_obj));
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.