_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| 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);
}
}
|
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,
|
javascript
|
{
"resource": ""
}
|
|
q2702
|
train
|
function (actualArgs, expectedArgs) {
var i;
if (actualArgs.length !== expectedArgs.length) {
return false;
}
for (i = 0; i < expectedArgs.length; i++)
|
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++];)
|
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;
|
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: '
|
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];
|
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
|
javascript
|
{
"resource": ""
}
|
q2708
|
sink
|
train
|
function sink(modulename, level, message, obj) {
|
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
|
javascript
|
{
"resource": ""
}
|
q2710
|
File
|
train
|
function File(retries, cdn, options) {
options = options || {};
this.backoff = new Backoff({ min: 100, max: 20000 });
this.mime =
|
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');
}
|
javascript
|
{
"resource": ""
}
|
q2712
|
train
|
function (obj, other) {
var notIn = {};
for (var key in obj) {
if (other[key] === undefined) {
|
javascript
|
{
"resource": ""
}
|
|
q2713
|
isBetween
|
train
|
function isBetween(lower, upper) {
return function (val) {
|
javascript
|
{
"resource": ""
}
|
q2714
|
DockerProc
|
train
|
function DockerProc(docker, config) {
EventEmitter.call(this);
this.docker = docker;
this._createConfig = config.create;
this._startConfig = config.start;
|
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
|
javascript
|
{
"resource": ""
}
|
|
q2716
|
train
|
function() {
var that = this;
this.killed = true;
if (this.started) {
this.container.kill();
} else {
|
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
|
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;
|
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);
|
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);
|
javascript
|
{
"resource": ""
}
|
q2721
|
filter_email
|
train
|
function filter_email(value) {
var m = EMAIL_RE.exec(value);
|
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 =
|
javascript
|
{
"resource": ""
}
|
q2723
|
extend
|
train
|
function extend(dest, src) {
var result = dest;
|
javascript
|
{
"resource": ""
}
|
q2724
|
spaces
|
train
|
function spaces(arg1, arg2) {
var l, builder = [];
if(arg1.constructor === Number) {
l = arg1;
} else {
|
javascript
|
{
"resource": ""
}
|
q2725
|
train
|
function(value, fn) {
if(value.constructor === Function ) {
this.default_handler = value;
} else if(value.constructor === Number) {
|
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 {
|
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);
|
javascript
|
{
"resource": ""
}
|
|
q2728
|
matches
|
train
|
function matches(regex) {
return function(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
|
javascript
|
{
"resource": ""
}
|
q2730
|
getCardId
|
train
|
function getCardId(o) {
return o.master + '#'
|
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
|
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')))
|
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');
|
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) {
|
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:
|
javascript
|
{
"resource": ""
}
|
q2736
|
isWhitelisted
|
train
|
function isWhitelisted(url) {
return options.adiPathFilter.some(function (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
|
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
|
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 ?
|
javascript
|
{
"resource": ""
}
|
q2740
|
isLoadNeeded
|
train
|
function isLoadNeeded(newProps, oldProps) {
return !_.isEqual(newProps.formDesign, oldProps.formDesign) ||
|
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
|
javascript
|
{
"resource": ""
}
|
|
q2742
|
createLogger
|
train
|
function createLogger(fn) {
return function () {
var args = [],
self = this,
c;
for (c = 0; c < arguments.length; c++) {
|
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
|
javascript
|
{
"resource": ""
}
|
|
q2744
|
train
|
function() {
canReflect.onValue( observation, updater,"notify");
if (observation.hasOwnProperty("_value")) {// can-observation 4.1+
compute.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
);
|
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 =
|
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:
|
javascript
|
{
"resource": ""
}
|
q2748
|
train
|
function(l) {
debug('Attaching link ' + l.name + ':' + l.handle + ' after begin received');
if
|
javascript
|
{
"resource": ""
}
|
|
q2749
|
role
|
train
|
function role(value) {
if (typeof value === 'boolean')
return value;
if (value !== 'sender' && value !== 'receiver')
throw
|
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 ===
|
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 !==
|
javascript
|
{
"resource": ""
}
|
q2752
|
assertArguments
|
train
|
function assertArguments(options, argnames) {
if (!argnames) return;
if (!options) throw new TypeError('missing arguments: ' + argnames);
argnames.forEach(function (argname) {
|
javascript
|
{
"resource": ""
}
|
q2753
|
Sasl
|
train
|
function Sasl(mechanism, handler) {
if (!mechanism || !handler) {
throw new errors.NotImplementedError('Need both the mechanism and the handler');
}
|
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: {
|
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)
|
javascript
|
{
"resource": ""
}
|
|
q2756
|
train
|
function (latest_log) {
if (latest_log !== null && latest_log.type !== "SYSTEM_DOWN") {
LOG.warn("server
|
javascript
|
{
"resource": ""
}
|
|
q2757
|
train
|
function () {
if (queue.length > 0) {
if (queue.length % 500 === 0)
LOG.warn('socketio queue:
|
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.'
|
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;
|
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) {
|
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);
|
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
|
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) {
|
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];
|
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);
|
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'
|
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 +=
|
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
|
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);
|
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
|
javascript
|
{
"resource": ""
}
|
|
q2771
|
train
|
function (error) {
if (error) {
var err = new Error(error.toString());
err.name = "l_createToken Error";
|
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
|
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
|
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,
|
javascript
|
{
"resource": ""
}
|
|
q2775
|
JobQueue
|
train
|
function JobQueue(para) {
this.queue = [];
this.curr = 0;
this.all_passed = true;
this.timeout = ((typeof para === 'object'
|
javascript
|
{
"resource": ""
}
|
q2776
|
train
|
function () {
if (item.done === false) {
LOG.error('job timeout! please check if the job calls onDone eventually. ' + (item.name ? '[' +
|
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]
|
javascript
|
{
"resource": ""
}
|
|
q2778
|
getInput
|
train
|
function getInput() {
var account = document.getElementById('account').value;
var email = (document.getElementById('email') ? document.getElementById('email').value : '');
|
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);
|
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,
|
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
|
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) {
|
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;
}
|
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
|
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
|
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
|
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 =
|
javascript
|
{
"resource": ""
}
|
|
q2788
|
train
|
function (args, result, func, extra) {
return new SR.promise(function (resolve,
|
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 },
|
javascript
|
{
"resource": ""
}
|
|
q2790
|
train
|
function (account) {
// check if DB is initialized
if (typeof l_accounts === 'undefined') {
LOG.error('DB module is not loaded, please
|
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: {}},
|
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
|
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
|
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 +
|
javascript
|
{
"resource": ""
}
|
|
q2795
|
train
|
function (req) {
var session = l_getSession(req);
if (session.hasOwnProperty('_user')) {
var login = session._user;
|
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
|
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);
|
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);
|
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 {
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.