_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q2500
|
train
|
function(sourceOrProgram, filename) {
if (!(this instanceof MetaScript)) {
__version = Array.prototype.join.call(arguments, '.');
return;
}
// Whether constructing from a meta program or, otherwise, a source
var isProgram = (sourceOrProgram+="").substring(0, 11) === 'MetaScript(';
/**
* Original source.
* @type {?string}
*/
this.source = isProgram ? null : sourceOrProgram;
/**
* Original source file name.
* @type {string}
*/
this.filename = filename || "main";
/**
* The compiled meta program's source.
* @type {string}
*/
this.program = isProgram ? sourceOrProgram : MetaScript.compile(sourceOrProgram);
}
|
javascript
|
{
"resource": ""
}
|
|
q2501
|
evaluate
|
train
|
function evaluate(expr) {
if (expr.substring(0, 2) === '==') {
return 'write(JSON.stringify('+expr.substring(2).trim()+'));\n';
} else if (expr.substring(0, 1) === '=') {
return 'write('+expr.substring(1).trim()+');\n';
} else if (expr.substring(0, 3) === '...') {
expr = '//...\n'+expr.substring(3).trim()+'\n//.';
}
if (expr !== '') {
return expr+'\n';
}
return '';
}
|
javascript
|
{
"resource": ""
}
|
q2502
|
append
|
train
|
function append(source) {
if (s === '') return;
var index = 0,
expr = /\n/g,
s,
match;
while (match = expr.exec(source)) {
s = source.substring(index, match.index+1);
if (s !== '') out.push(' write(\''+escapestr(s)+'\');\n');
index = match.index+1;
}
s = source.substring(index, source.length);
if (s !== '') out.push(' write(\''+escapestr(s)+'\');\n');
}
|
javascript
|
{
"resource": ""
}
|
q2503
|
indent
|
train
|
function indent(str, indent) {
if (typeof indent === 'number') {
var indent_str = '';
while (indent_str.length < indent) indent_str += ' ';
indent = indent_str;
}
var lines = str.split(/\n/);
for (var i=0; i<lines.length; i++) {
if (lines[i].trim() !== '')
lines[i] = indent + lines[i];
}
return lines.join("\n");
}
|
javascript
|
{
"resource": ""
}
|
q2504
|
include
|
train
|
function include(filename, absolute) {
filename = absolute
? filename
: __dirname + '/' + filename;
var _program = __program, // Previous meta program
_source = __source, // Previous source
_filename = __filename, // Previous source file
_dirname = __dirname, // Previous source directory
_indent = __; // Previous indentation level
var files;
if (/(?:^|[^\\])\*/.test(filename)) {
files = require("glob").sync(filename, { cwd : __dirname, nosort: true });
files.sort(naturalCompare); // Sort these naturally (e.g. int8 < int16)
} else {
files = [filename];
}
files.forEach(function(file) {
var source = require("fs").readFileSync(file)+"";
__program = MetaScript.compile(indent(source, __));
__source = source;
__filename = file;
__dirname = dirname(__filename);
__runProgram();
__program = _program;
__source = _source;
__filename = _filename;
__dirname = _dirname;
__ = _indent;
});
}
|
javascript
|
{
"resource": ""
}
|
q2505
|
escapestr
|
train
|
function escapestr(s) {
return s.replace(/\\/g, '\\\\')
.replace(/'/g, '\\\'')
.replace(/"/g, '\\"')
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n');
}
|
javascript
|
{
"resource": ""
}
|
q2506
|
__err2code
|
train
|
function __err2code(program, err) {
if (typeof err.stack !== 'string')
return indent(program, 4);
var match = /<anonymous>:(\d+):(\d+)\)/.exec(err.stack);
if (!match) {
return indent(program, 4);
}
var line = parseInt(match[1], 10)-1,
start = line - 3,
end = line + 4,
lines = program.split("\n");
if (start < 0) start = 0;
if (end > lines.length) end = lines.length;
var code = [];
start = 0; end = lines.length;
while (start < end) {
code.push(start === line ? "--> "+lines[start] : " "+lines[start]);
start++;
}
return indent(code.join('\n'), 4);
}
|
javascript
|
{
"resource": ""
}
|
q2507
|
train
|
function(callback) {
bootstrap(behaviour, (bootstrapErr, bootstrapRes) => {
if (bootstrapErr) api.emit("error", bootstrapErr);
if (bootstrapRes && bootstrapRes.virgin) {
bootstrapRes.connection.on("error", (err) => api.emit("error", err));
bootstrapRes.connection.on("close", (why) => api.emit("error", why));
api.emit("connected");
bootstrapRes.pubChannel.on("error", (err) => api.emit("error", err));
bootstrapRes.subChannel.on("error", (err) => api.emit("error", err));
bootstrapRes.pubChannel.assertExchange(behaviour.exchange, "topic");
}
callback(bootstrapErr, bootstrapRes);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2508
|
mkdirSync
|
train
|
function mkdirSync(dirPath) {
// Get relative path to output
const relativePath = dirPath.replace(`${CWD}${pathSep}`, '');
const dirs = relativePath.split(pathSep);
let currentDir = CWD;
// Check if each dir exists, and if not, create it
dirs.forEach(dir => {
currentDir = path.resolve(currentDir, dir);
if(!fs.existsSync(currentDir)) {
fs.mkdirSync(currentDir);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q2509
|
train
|
function (values, options, callback) {
var deferred = Q.defer();
var args = ArgumentHelpers.prepareArguments(options, callback)
, wrapper = {};
options = args.options;
callback = Qext.makeNodeResolver(deferred, args.callback);
//Check for mongo's another possible syntax with '$' operators, e.g. '$set', '$setOnInsert' and set wrapper
values = values || {};
for (var element in values) {
if (element.match(/\$/i)) {
wrapper[element] = values[element];
options.flat = options.flat != undefined ? options.flat : true
}
}
// If nothing to wrap just validate values
if (_.isEmpty(wrapper)) {
ModelValidator.validate(values, this.prototype, options, function (err, validatedValues) {
callback(err, validatedValues);
});
}
else {
// If wrapping elements like $set, $inc etc found, validate each and rewrite to values
values = {};
var errors = {};
var wrapperOptions = {};
for (var wrapperElem in wrapper) {
wrapperOptions = _.clone(options);
if (options && options.partial && _.isObject(options.partial)) {
if (options.partial[wrapperElem] !== undefined) {
wrapperOptions['partial'] = options.partial[wrapperElem];
}
}
if (options && options.validate && _.isObject(options.validate)) {
if (options.validate[wrapperElem] !== undefined) {
wrapperOptions['validate'] = options.validate[wrapperElem];
}
}
if (options.validate && options.validate[wrapperElem] === false) {
values[wrapperElem] = wrapper[wrapperElem];
}
else {
ModelValidator.validate(wrapper[wrapperElem], this.prototype, wrapperOptions, function (err, validatedValues) {
if (err) {
errors = err;
}
values[wrapperElem] = validatedValues;
});
}
}
if (_.isEmpty(errors)) {
errors = null;
}
callback(errors, values);
}
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q2510
|
train
|
function (callback) {
var self = this;
var deferred = Q.defer();
callback = Qext.makeNodeResolver(deferred, callback);
var breakExec = {};
Async.waterfall([
function (next) {
if (!self.collectionName) {
next({
name: 'InternalError',
err: "collectionName property is not set for model " + self.identity
});
} else {
var dbName = self.dbName || Shared.config("environment.defaultMongoDatabase");
var db = self.db(dbName);
if (db) {
next(null, db);
}
else {
next({
name: 'InternalError',
err: "No connection to database " + self.identity
});
}
}
},
function (db, next) {
if (!db || _.isEmpty(db)) {
Logger.error("No db connection");
next("No db connection");
}
else {
//try to get exiting collection
db.collection(self.collectionName, {strict: true}, function (err, collection) {
if (!err) {
//collection exists already
self._collection = collection;
//do not apply indexes to exiting collection, since this operation is time consuming
next(breakExec, collection);
}
else {
var collectionOptions = self.collectionOptions || {};
db.createCollection(self.collectionName, collectionOptions, function (err, collection) {
if (!err) {
next(null, collection);
}
else {
db.collection(self.collectionName, {strict: true}, function (err, collection) {
if (!err) {
//collection exists already
self._collection = collection;
//do not apply indexes to exiting collection, since this operation is time consuming
next(breakExec, collection);
}
else {
Logger.error(err);
next(err);
}
});
}
});
}
});
}
},
function (collection, next) {
//store new collection
self._collection = collection;
if (_skipDatabaseIndexingOnNewCollections()) {
return next(null, collection);
}
//apply all indexes on collection
self.ensureAllIndexes(function (err) {
next(err, collection);
});
},
function (collection, next) {
//return collection
next(null, collection);
}
], function (err, collection) {
if (!err || err === breakExec) {
callback(null, collection);
}
else {
callback(err);
}
});
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q2511
|
train
|
function (arguments) {
var argData = ArgumentHelpers.prepareCallback(arguments);
var callback = argData.callback;
var args = argData.arguments;
if (callback) {
args.pop();
}
return args;
}
|
javascript
|
{
"resource": ""
}
|
|
q2512
|
train
|
function (functionName, arguments) {
var self = this;
var args = self._getArgs(arguments);
var callback = self._getCallback(arguments);
return self._generic(functionName, args)
.nodeify(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q2513
|
train
|
function (args) {
var shardKey = this.prototype.shardKey;
var query = !_.isUndefined(args[0]) ? args[0] : {};
var options = !_.isUndefined(args[1]) ? args[1] : {};
var ignoreShardKey = MemberHelpers.getPathPropertyValue(options, 'ignoreShardKey') ? true : false;
var missingFields = [];
if (!_.isUndefined(shardKey) && !_.isUndefined(query) && !ignoreShardKey) {
for (let shardKeyField in shardKey) {
if (!query.hasOwnProperty(shardKeyField)) {
missingFields.push(shardKeyField);
}
}
}
return new Q.Promise(function (resolve, reject) {
if (!_.isEmpty(missingFields)) {
return reject("Query doesn't contain the shard key or parts of it. Missing fields: " + missingFields.join(', '));
}
return resolve();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2514
|
train
|
function(event) {
if (typeof event.touches != 'undefined' && event.touches.length > 0) {
var c = {
x: event.touches[0].pageX,
y: event.touches[0].pageY
};
} else {
var c = {
x: (event.pageX || (event.clientX + document.body.scrollLeft)),
y: (event.pageY || (event.clientY + document.body.scrollTop))
};
}
return c;
}
|
javascript
|
{
"resource": ""
}
|
|
q2515
|
train
|
function (bodySchemaModels, defName) {
for (var i in bodySchemaModels) {
if (bodySchemaModels[i]["name"] == defName) {
return bodySchemaModels[i];
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q2516
|
train
|
function (values, schema) {
var publicList = find(schema, 'public')
, arrElem;
for (var value in values) {
if (publicList[value]) {
if (_.isArray(publicList[value])) {
for (var thisArrayElem in publicList[value]) {
if (!_.isArray(values[value])) {
// Delete values due to it should be an array defined in schema
delete(values[value]);
}
else {
for (var thisValue in values[value]) {
values[value][thisValue] = unsetPublicSet(values[value][thisValue], publicList[value][thisArrayElem]);
if (_.isEmpty(values[value][thisValue])) {
(values[value]).splice(thisValue);
}
}
if (_.isEmpty(values[value])) {
delete(values[value]);
}
}
}
}
else {
if (publicList[value].public) {
if (publicList[value].public == false || (publicList[value].public.hasOwnProperty('set') && publicList[value].public.set != true)) {
delete(values[value]);
}
}
}
}
}
return values;
}
|
javascript
|
{
"resource": ""
}
|
|
q2517
|
train
|
function (values, schema, options) {
var virtualList = find(schema, 'virtual');
//Set default value for virtual if not exists in values
if (options && options.query === true) {
}
else {
for (var virtual in virtualList) {
if (_.isArray(virtualList[virtual])) {
for (var thisVirtual in virtualList[virtual]) {
if (_.isArray(values[virtual])) {
for (var thisValue in values[virtual]) {
setVirtuals(values[virtual][thisValue], virtualList[virtual][thisVirtual], options);
}
}
}
}
else {
if (values[virtual] === undefined && virtualList[virtual] && virtualList[virtual].hasOwnProperty('default') && options && options.partial !== true) {
values[virtual] = (virtualList[virtual]).default;
}
}
}
}
for (var value in values) {
if (virtualList[value] && virtualList[value].virtual) {
var setFunction = virtualList[value].virtual;
//Check for setter and getter
if (virtualList[value].virtual.set) {
setFunction = virtualList[value].virtual.set;
}
//Check conditions and apply virtual
rulesMatch(value, values[value], setFunction, null, function (err, data) {
if (!err) {
if (_.isFunction(setFunction)) {
var virtualResult = setFunction(values[value]);
if (_.isObject(virtualResult) && !_.isEmpty(virtualResult)) {
//Check if virtual values does not exists in given values list. Do not overwrite given
for (var vValue in virtualResult) {
{
if (vValue == 'this') {
virtualResult[value] = virtualResult[vValue];
delete(virtualResult[vValue]);
}
else {
// Prevent overwrite of given values
if (values[vValue] !== undefined) {
delete(virtualResult[vValue]);
}
}
}
}
values = _.assign(values, virtualResult);
}
}
}
});
}
}
return values;
}
|
javascript
|
{
"resource": ""
}
|
|
q2518
|
train
|
function (model, filter, value) {
if (!_.isString(filter)) {
return null;
}
if (model.data) {
var list = findKeys(model.data, filter)
, values = [];
for (var res in list) {
if (value === undefined || list[res][filter] === value) {
values.push(res);
}
}
}
//return _.isEmpty(values) ? undefined : values;
//Changed to return empty array instead of 'undefined'. Do not change back, otherwise some functions working with arrays do not work properly.
return values;
}
|
javascript
|
{
"resource": ""
}
|
|
q2519
|
train
|
function (schema) {
var extendList = find(schema, 'extend');
for (var extendElem in extendList) {
if (extendList[extendElem] && extendList[extendElem].extend && _.isFunction(extendList[extendElem].extend)) {
schema[extendElem] = extendList[extendElem].extend();
}
}
return schema;
}
|
javascript
|
{
"resource": ""
}
|
|
q2520
|
name
|
train
|
function name(fp, options) {
var opts = options || {};
if (typeof opts.namespace === 'function') {
return opts.namespace(fp, opts);
}
if (typeof opts.namespace === false) {
return fp;
}
var ext = path.extname(fp);
return path.basename(fp, ext);
}
|
javascript
|
{
"resource": ""
}
|
q2521
|
read
|
train
|
function read(fp, opts) {
if (opts && opts.read) {
return opts.read(fp, opts);
}
return readData.call(this, fp, opts);
}
|
javascript
|
{
"resource": ""
}
|
q2522
|
readData
|
train
|
function readData(fp, options) {
// shallow clone options
var opts = utils.extend({}, options);
// get the loader for this file.
var ext = opts.lang || path.extname(fp);
if (ext && ext.charAt(0) !== '.') {
ext = '.' + ext;
}
if (!this.dataLoaders.hasOwnProperty(ext)) {
return this.dataLoader('read')(fp, opts);
}
return this.dataLoader(ext)(fp, opts);
}
|
javascript
|
{
"resource": ""
}
|
q2523
|
train
|
function() {
if (common.inlinescripts.length > 0) {
var script_text = '';
for (var i = 0; i < common.inlinescripts.length; i++) {
if (!common.inlinescripts[i] || typeof common.inlinescripts[i] == 'undefined')
continue;
else
script_text += common.inlinescripts[i] + '\n';
}
try {
eval(script_text);
} catch(e) {
batch.callback(script_text);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2524
|
saveObjectToJSON
|
train
|
function saveObjectToJSON(filePath, data) {
try {
data = JSON.stringify(data, null, 2);
writeFileSync(filePath, data, { encoding: 'utf8' });
return true;
} catch(ex) {
console.warn('Unable to save class JSON');
return false;
}
// NOTE: ASYNC REQUIRES PROMISIFYING ALL OPERATIONS
// fs.writeFile(filePath, data, err => {
// if (err) { console.warn(`Unable to save ${filePath}`); }
// });
}
|
javascript
|
{
"resource": ""
}
|
q2525
|
assertObject
|
train
|
function assertObject(attr, data) {
if (data === null || data === undefined) {
return null;
}
if (typeof data !== 'object' || Array.isArray(data)) {
throw new ParseError(`Attribute ${attr} must be of type "object"`);
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q2526
|
assertArray
|
train
|
function assertArray(attr, data, type) {
if (data === null || data === undefined) {
return [];
}
if (!Array.isArray(data)) {
throw new ParseError(`Attribute ${attr} must be of type "array"`);
}
const clone = [];
for (const d of data) {
if (d !== undefined && d !== null) {
if (typeof d !== type) {
throw new ParseError(`Attribute ${attr} must contain only values of type "${type}"`);
}
clone.push(d);
}
}
return clone;
}
|
javascript
|
{
"resource": ""
}
|
q2527
|
assertUniTypeObject
|
train
|
function assertUniTypeObject(attr, data, type) {
data = assertObject(attr, data);
if (data === null) {
return null;
}
Object.keys(data).forEach(key => {
if (type === undefined) {
type = typeof data[key];
}
type = type.toLowerCase();
let msg = `Attribute ${attr} must be of type "object" and have all its properties of type ${type}.`
+ `\nExpected "${attr}.${key}" to be of type "${type}", but go "${typeof data[key]}".`;
switch (type) {
case 'array':
if (!Array.isArray(data[key])) {
throw new ParseError(msg);
}
break;
default:
if (typeof data[key] !== type) {
throw new ParseError(msg);
}
break;
}
});
return data;
}
|
javascript
|
{
"resource": ""
}
|
q2528
|
assertString
|
train
|
function assertString(attr, data) {
if (data === null || data === undefined) {
return null;
}
if (typeof data !== 'string') {
throw new ParseError(`Attribute ${attr} must be of type "string"`);
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q2529
|
train
|
function (values, model, type) {
var deferred = Q.defer();
var modelData = {data: model};
ModelValidator.validate(values, modelData, function (err, data) {
deferred.resolve({data: data, err: err, type: type});
});
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q2530
|
train
|
function (req, controller) {
var parameters = [];
if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.header) {
parameters.push(_checkValues(req.headers, controller.conditions.parameters.header, "header"))
}
if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.query) {
parameters.push(_checkValues(req.query, controller.conditions.parameters.query, "query"))
}
if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.body) {
parameters.push(_checkValues(req.body, controller.conditions.parameters.body, "body"))
}
if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.path) {
parameters.push(_checkValues(req.params, controller.conditions.parameters.path, "path"))
}
return Q.all(parameters).then(function (results) {
var validatedData = [];
var errors = [];
results.forEach(function (result) {
if (result.data) {
if (!validatedData[result.type]) {
validatedData[result.type] = {};
}
validatedData[result.type] = result.data;
}
// Collect validation errors
if (result.err && result.err.err && result.err.name == "ValidationError") {
var resultErrors = result.err.err;
resultErrors.forEach(function (error) {
error.in = result.type;
errors.push(error);
});
}
});
return Q({
validatedData: {
name: controller.name,
version: controller.version,
method: controller.method,
function: controller.function,
data: validatedData
},
errors: errors
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2531
|
train
|
function (req, res, next) {
var hostId = req.miajs.route.hostId;
var url = req.miajs.route.url;
var prefix = req.miajs.route.prefix;
var method = req.miajs.route.method;
var group = req.miajs.route.group;
var version = req.miajs.route.version;
var registeredServices = Shared.registeredServices();
var errors = [];
var routeFound = false;
req.miajs = req.miajs || {};
//console.log('checkPreconditions: url: ' + url + ', method: ' + method + ', body: ' + JSON.stringify(req.body));
for (var index in registeredServices) {
if (registeredServices[index].group == group
&& registeredServices[index].hostId == hostId
&& registeredServices[index].version == version
&& registeredServices[index].prefix == prefix
&& registeredServices[index].method == method
&& registeredServices[index].url == url
) {
routeFound = true;
if (registeredServices[index].preconditions) {
var service = registeredServices[index];
var preconditionsList = service.preconditions;
var qfunctions = [];
for (var cIndex in preconditionsList) {
qfunctions.push(_checkControllerConditions(req, preconditionsList[cIndex]));
}
Q.all(qfunctions).then(function (results) {
req.miajs.commonValidatedParameters = [];
results.forEach(function (result) {
if (result) {
if (result.validatedData) {
req.miajs.commonValidatedParameters.push(result.validatedData);
}
var controllerErrors = result.errors;
controllerErrors.forEach(function (error) {
var inList = false;
// Check for error duplicates
for (var eIndex in errors) {
if (errors[eIndex].code == error.code && errors[eIndex].id == error.id && errors[eIndex].in == error.in) {
inList = true;
}
}
if (inList == false) {
errors.push(error);
}
});
}
});
}).then(function () {
if (!_.isEmpty(errors)) {
next({'status': 400, err: errors})
return;
}
else {
next();
return;
}
}).catch(function (err) {
next({'status': 400, err: err});
return;
});
}
else {
next();
return;
}
}
}
if (routeFound == false) {
Logger.error('Can not find controller file in preconditionsCheck to perform parameter validation. Request canceled due to security reasons');
next({status: 500});
return;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2532
|
train
|
function () {
Shared.initialize('/config', process.argv[2]);
Shared.setAppHttp(appHttp);
Shared.setAppHttps(appHttps);
Shared.setExpress(express);
// Init memcached
var memcached = Shared.memcached();
// Init redis cache
var redis = Shared.redis(true);
//Enable gzip compression
appHttp.use(compression());
appHttp.disable('x-powered-by');
appHttps.use(compression());
appHttps.disable('x-powered-by');
var env = Shared.config("environment");
var maxLag = env.maxLag;
if (maxLag) {
toobusy.maxLag(maxLag);
}
appHttp.use(function (req, res, next) {
if (maxLag && toobusy()) {
Logger.error("Server is busy, rejected request");
res.status(503).send("I'm busy right now, sorry.");
} else {
next();
}
});
appHttps.use(function (req, res, next) {
if (maxLag && toobusy()) {
Logger.error("Server is busy, rejected request");
res.status(503).send("I'm busy right now, sorry.");
} else {
next();
}
});
return Q();
}
|
javascript
|
{
"resource": ""
}
|
|
q2533
|
train
|
function (initFunction) {
if (_.isFunction(initFunction)) {
Logger.info("Run init function");
_customInitFuncton = initFunction;
return initFunction(appHttp)
.then(function () {
return initFunction(appHttps);
});
}
return Q();
}
|
javascript
|
{
"resource": ""
}
|
|
q2534
|
train
|
function () {
//set logger
if (!module.parent) {
appHttp.use(morgan({format: 'dev'}));
appHttps.use(morgan({format: 'dev'}));
}
return Q();
}
|
javascript
|
{
"resource": ""
}
|
|
q2535
|
train
|
function (host, reInit) {
if (_.isEmpty(host.id) || !_.isString(host.id)) {
throw new Error("Host configuration is invalid. Host id is missing or not a string");
}
if (_.isEmpty(host.host)) {
throw new Error("Host configuration is invalid. Host is missing");
}
if (_.isString(host.host)) {
host.host = [host.host];
}
if (!_.isArray(host.host)) {
throw new Error("Host configuration is invalid. Host should be array or string");
}
var router = new express.Router();
if (reInit === false) {
// Check if host is already defined. Use same router instance to merge routes
for (var index in _vhosts) {
for (var vh in _vhosts[index]["host"]) {
if (_vhosts[index]["host"][vh] == host.host) {
router = _vhosts[index]["router"];
}
}
}
}
_vhosts[host.id] = {
host: host.host,
router: router,
http: !host.listener ? true : host.listener && host.listener.http || null,
https: !host.listener ? true : host.listener && host.listener.https || null
};
_applyRouterConfig(_vhosts[host.id]["router"]);
_customInitFuncton(_vhosts[host.id]["router"]);
}
|
javascript
|
{
"resource": ""
}
|
|
q2536
|
train
|
function (reInit = false) {
//load routes
var environment = Shared.config("environment");
var hosts = environment.hosts;
if (hosts) {
if (!_.isArray(hosts)) {
hosts = [hosts];
}
for (var host in hosts) {
_parseHosts(hosts[host], reInit);
}
}
_vhosts["*"] = {
host: '*',
router: new express.Router()
};
_applyRouterConfig(_vhosts["*"]["router"]);
_customInitFuncton(_vhosts["*"]["router"]);
return RoutesHandler.initializeRoutes(_vhosts, reInit === false);
}
|
javascript
|
{
"resource": ""
}
|
|
q2537
|
train
|
function () {
const cronJobsToStart = _getNamesOfCronJobsToStart();
if (!cronJobsToStart && _shouldStartCrons() && Shared.isDbConnectionAvailable() === true) {
return CronJobManagerJob.startListening().then(function () {
Logger.tag('Cron').info('Cron Job Manager is started. Starting all available cron jobs');
return Q();
}, function (err) {
Logger.tag('Cron').error('Error starting Cron Job Manager ');
return Q.reject(err);
});
} else if (cronJobsToStart && _shouldStartCrons()) {
Logger.tag('Cron').info('Starting specific cron jobs "' + cronJobsToStart.join(', ') + '"');
try {
const cronJobs = Shared.cronModules(cronJobsToStart);
let promises = [];
for (let cron of cronJobs) {
// Set force run config
cron.forceRun = true;
promises.push(cron.worker(cron, cron));
}
return Q.all(promises)
.then(() => process.exit())
.catch(() => process.exit(1));
} catch (err) {
process.exit(1);
}
} else {
Logger.tag('Cron').warn('Cron Manager is disabled for this environment.');
return Q();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2538
|
train
|
function () {
const crons = _.get(Shared, 'runtimeArgs.cron') || _.get(Shared, 'runtimeArgs.crons');
if (crons) {
const cronTasks = crons.replace(/\s/g, '').split(',');
return cronTasks.length > 0 ? cronTasks : undefined;
}
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
|
q2539
|
setResponsive
|
train
|
function setResponsive(name) {
if (name) {
setResponsiveComponents.call(this, name);
} else {
_utils2["default"].forEach(Object.keys(this._component), (function (name) {
setResponsiveComponents.call(this, name);
}).bind(this));
}
if (_utils2["default"].isUndefined(name)) {
_utils2["default"].forEach(this._matchMedias._orders, (function (query) {
if (this._matchMedias[query].matches) {
_utils2["default"].forIn(this._responsiveStyles[query], (function (style, key) {
if (!this._styles[key]) {
this._styles[key] = {};
}
this[key] = _utils2["default"].merge(this._styles[key], (0, _reactPrefixer2["default"])(style));
}).bind(this));
}
}).bind(this));
}
}
|
javascript
|
{
"resource": ""
}
|
q2540
|
loadDefault
|
train
|
function loadDefault() {
return {
port: 8000,
host: '127.0.0.1',
root: './',
logFormat: 'combined',
middlewares: [
{
name: 'cors',
cfg: {
origin: true
}
},
{
name: 'morgan',
cfg: {}
},
{
name: 'serveStatic',
cfg: {}
},
{
name: 'serveIndex',
cfg: {
icons: true
}
}
]
}
}
|
javascript
|
{
"resource": ""
}
|
q2541
|
loadFromFile
|
train
|
function loadFromFile(filename) {
var cfg = {}
Object.assign(
cfg,
loadDefault(),
JSON.parse(fs.readFileSync(filename))
)
return cfg
}
|
javascript
|
{
"resource": ""
}
|
q2542
|
saveToFile
|
train
|
function saveToFile(filename, cfg) {
// Use 'wx' flag to fails if filename exists
fs.writeFileSync(filename, JSON.stringify(cfg, null, 2), {flag: 'wx'})
}
|
javascript
|
{
"resource": ""
}
|
q2543
|
loadFromOptions
|
train
|
function loadFromOptions(opts) {
var defCfg = loadDefault()
var cfg = opts.config ? loadFromFile(opts.config) : loadDefault()
// Command line config override file loaded config
for (var k in opts) {
defCfg.hasOwnProperty(k) && (defCfg[k] !== opts[k] && (cfg[k] = opts[k]))
}
return cfg
}
|
javascript
|
{
"resource": ""
}
|
q2544
|
train
|
function (options, iterationInfo) {
var files;
var modules = {};
var result = {};
// remember the starting directory
try {
files = fs.readdirSync(iterationInfo.dirName);
} catch (e) {
if (options.optional)
return {};
else
throw new Error('Directory not found: ' + iterationInfo.dirName);
}
// iterate through files in the current directory
files.forEach(function (fileName) {
iterationInfo.dirName = iterationInfo.initialDirName + '/' + fileName + '/' + options.moduleDir;
iterationInfo.projectDir = iterationInfo.initialDirName + '/' + fileName;
result = _.assign(doInterations(options, iterationInfo), result);
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q2545
|
train
|
function (options, iterationInfo, modules) {
// filename filter
if (options.fileNameFilter) {
var match = iterationInfo.fileName.match(options.fileNameFilter);
if (!match) {
return;
}
}
// Filter spec.js files
var match = iterationInfo.fileName.match(/.spec.js/i);
if (match) {
return;
}
// relative path filter
if (options.relativePathFilter) {
var pathMatch = iterationInfo.relativeFullPath.match(options.relativePathFilter);
if (!pathMatch)
return;
}
//load module
loadModule(modules, options, iterationInfo);
}
|
javascript
|
{
"resource": ""
}
|
|
q2546
|
train
|
function (modules, options, iterationInfo) {
// load module into memory (unless `dontLoad` is true)
var module = true;
//default is options.dontLoad === false
if (options.dontLoad !== true) {
//if module is to be loaded
module = require(iterationInfo.absoluteFullPath);
// If a module is found but was loaded as 'undefined', don't include it (since it's probably unusable)
if (typeof module === 'undefined') {
throw new Error('Invalid module:' + iterationInfo.absoluteFullPath);
}
var identity;
//var name;
var version;
if (options.useVersions === true) {
if (module.version) {
version = module.version;
}
else {
version = '1.0';
}
}
if (module.identity) {
identity = module.identity;
//name = identity;
}
else {
identity = generateIdentity(options, iterationInfo);
//name = identity;
}
//consider default options.injectIdentity === true
if (options.injectIdentity !== false) {
module.fileName = iterationInfo.fileName;
module.projectDir = iterationInfo.projectDir;
module.relativePath = iterationInfo.relativePath;
module.relativeFullPath = iterationInfo.relativeFullPath;
module.absolutePath = iterationInfo.absolutePath;
module.absoluteFullPath = iterationInfo.absoluteFullPath;
module.identity = identity;
//module.name = name;
if (options.useVersions === true) {
module.version = version;
}
}
else {
identity = generateIdentity(options, iterationInfo);
}
//check if identity is unique within the collection and add to dictionary
if (options.useVersions === true) {
if (modules[identity] && modules[identity][version]) {
var anotherModule = modules[identity][version];
throw new Error("Identity '" + identity + "' with version '" + version + "' is already registered by module at '" + anotherModule.absoluteFullPath + "'");
}
modules[identity] = modules[identity] || {};
modules[identity][version] = module;
}
else {
var anotherModule = modules[identity];
if (anotherModule) {
throw new Error("Identity '" + identity + "' is already registered by module at '" + anotherModule.absoluteFullPath + "'");
}
modules[identity] = module;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2547
|
train
|
function (options, iterationInfo) {
// Use the identity for the key name
var identity;
if (options.mode === 'list') {
identity = iterationInfo.relativeFullPath;
//identity = identity.toLowerCase();
//find and replace all containments of '/', ':' and '\' within the string
identity = identity.replace(/\/|\\|:/g, '');
}
else if (options.mode === 'tree') {
identity = iterationInfo.fileName;
//identity = identity.toLowerCase();
}
else
throw new Error('Unknown mode');
//remove extention
identity = identity.substr(0, identity.lastIndexOf('.')) || identity;
return identity;
}
|
javascript
|
{
"resource": ""
}
|
|
q2548
|
train
|
function (options, iterationInfo, modules) {
// Ignore explicitly excluded directories
if (options.excludeDirs) {
var match = iterationInfo.fileName.match(options.excludeDirs);
if (match)
return;
}
// Recursively call requireAll on each child directory
var subIterationInfo = _.clone(iterationInfo);
++subIterationInfo.depth;
subIterationInfo.dirName = iterationInfo.absoluteFullPath;
//process subtree recursively
var subTreeResult = doInterations(options, subIterationInfo);
//omit empty dirs
if (_.isEmpty(subTreeResult))
return;
//add to the list or to the subtree
if (options.mode === 'list') {
//check uniqueness
_.forEach(subTreeResult, function (value, index) {
if (options.useVersions === true) {
modules[index] = modules[index] || {};
_.forEach(value, function (versionValue, versionIndex) {
if (modules[index][versionIndex])
throw new Error("Identity '" + index + "' with version '" + versionIndex + "' is already registered by module at '" + modules[index][versionIndex].absoluteFullPath + "'");
modules[index][versionIndex] = versionValue;
});
}
else {
if (modules[index])
throw new Error("Identity '" + index + "' is already registered by module at '" + modules[index].absoluteFullPath + "'");
modules[index] = value;
}
})
}
else if (options.mode === 'tree') {
if (options.markDirectories !== false) {
subTreeResult.isDirectory = true;
}
var identity = generateIdentity(options, iterationInfo);
modules[identity] = subTreeResult;
}
else
throw new Error('Unknown mode');
}
|
javascript
|
{
"resource": ""
}
|
|
q2549
|
train
|
function (level, message, tag, data) {
var env = Shared.config('environment');
var levels = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'];
var logLevelConfig = env.logLevel || "info";
if (logLevelConfig == "none") {
return;
}
var logLevel = levels.indexOf(logLevelConfig) >= 0 ? logLevelConfig : 'info';
// Set default error logging
if (_.isObject(message) && _.isEmpty(data)) {
if (message.message && _.isString(message.message)) {
data = message.stack || "";
message = message.message;
}
else {
data = message;
message = null;
}
}
//Output
if (levels.indexOf(level) <= levels.indexOf(logLevel)) {
var logString = "";
if (env.logFormat === 'json') {
logString = JSON.stringify({
timestamp: new Date().toISOString(),
level,
tag,
message,
data,
hostname: Shared.getCurrentHostId(),
pid: process.pid,
mode: env.mode
});
} else {
if (_.isObject(data)) {
data = Util.inspect(data, {showHidden: false, depth: null});
}
logString += new Date().toISOString() + ' ';
logString += '[' + level + ']';
logString += tag == "default" ? "" : ' [' + tag + ']';
logString += !_.isString(message) ? "" : ': ' + message;
logString += data ? ' --> ' + data : "";
}
if (["error", "fatal"].indexOf(level) >= 0) {
_outputLog("error", logString);
} else if (level == "warn") {
_outputLog("warn", logString);
} else {
_outputLog("info", logString);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2550
|
train
|
function (obj, tag) {
tag = _.isArray(tag) ? tag.join(',') : tag;
tag = !_.isEmpty(tag) ? tag.toLowerCase() : 'default';
obj.trace = function (message, data) {
_logEvent("trace", message, tag, data);
};
obj.debug = function (message, data) {
_logEvent("debug", message, tag, data);
};
obj.info = function (message, data) {
_logEvent("info", message, tag, data);
};
obj.warn = function (message, data) {
_logEvent("warn", message, tag, data);
};
obj.error = function (message, data) {
_logEvent("error", message, tag, data);
};
obj.fatal = function (message, data) {
_logEvent("fatal", message, tag, data);
};
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q2551
|
expandField
|
train
|
function expandField(input, grunt){
var get = pointer(input);
return function(memo, fin, fout){
if(_.isString(fin)){
var match = fin.match(re.PATH_POINT);
// matched ...with a `$.` ...but not with a `\`
if(match && match[3] === '$.' && !match[1]){
// field name, starts with an unescaped `$`, treat as JSON Path
memo[fout] = jsonPath(input, match[2]);
}else if(match && match[3] === '/' && !match[1]){
// field name, treat as a JSON pointer
memo[fout] = get(match[2]);
}else{
memo[fout] = input[match[2]];
}
}else if(_.isFunction(fin)){
// call a function
memo[fout] = fin(input);
}else if(_.isArray(fin)){
// pick out the values
memo[fout] = _.map(fin, function(value){
return expandField(input)({}, value, "dummy")["dummy"];
});
}else if(_.isObject(fin)){
// build up an object of something else
memo[fout] = _.reduce(fin, expandField(input, grunt), {});
}else if(_.isNull(fin)){
// copy the value
memo[fout] = input[fout];
}else{
grunt.fail.warn('Could not map `' + JSON.stringify(fin) + '` to `' +
JSON.stringify(fout) + '`');
}
return memo;
};
}
|
javascript
|
{
"resource": ""
}
|
q2552
|
action_handler
|
train
|
async function action_handler(req, h) {
const data = req.payload
const json = 'string' === typeof data ? tu.parseJSON(data) : data
if (json instanceof Error) {
throw json
}
const seneca = prepare_seneca(req, json)
const msg = tu.internalize_msg(seneca, json)
return await new Promise(resolve => {
var out = null
for (var i = 0; i < modify_action.length; i++) {
out = modify_action[i].call(seneca, msg, req)
if (out) {
return resolve(out)
}
}
seneca.act(msg, function(err, out, meta) {
if (err && !options.debug) {
err.stack = null
}
resolve(tu.externalize_reply(this, err, out, meta))
})
})
}
|
javascript
|
{
"resource": ""
}
|
q2553
|
train
|
function () {
return ServerHeartbeatModel.find({
status: _statusActive
}).then(function (cursor) {
return Q.ninvoke(cursor, 'toArray').then(function (servers) {
var serverIds = [];
servers.map(function (value) {
serverIds.push(value._id);
});
return _removeAllJobsOfUnknownServer(serverIds);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2554
|
train
|
function( input, chunk, context ){
// return given input if there is no dust reference to resolve
var output = input;
// dust compiles a string to function, if there are references
if( typeof input === "function"){
if( ( typeof input.isReference !== "undefined" ) && ( input.isReference === true ) ){ // just a plain function, not a dust `body` function
output = input();
} else {
output = '';
chunk.tap(function(data){
output += data;
return '';
}).render(input, context).untap();
if( output === '' ){
output = false;
}
}
}
return output;
}
|
javascript
|
{
"resource": ""
}
|
|
q2555
|
compactBuffers
|
train
|
function compactBuffers(context, node) {
var out = [node[0]], memo;
for (var i=1, len=node.length; i<len; i++) {
var res = dust.filterNode(context, node[i]);
if (res) {
if (res[0] === 'buffer') {
if (memo) {
memo[1] += res[1];
} else {
memo = res;
out.push(res);
}
} else {
memo = null;
out.push(res);
}
}
}
return out;
}
|
javascript
|
{
"resource": ""
}
|
q2556
|
thisModule
|
train
|
function thisModule() {
var self = this;
/**
* Generate random hash value
* @returns {*}
*/
self.getClientIP = function (req) {
req = req || {};
req.connection = req.connection || {};
req.socket = req.socket || {};
req.client = req.client || {};
var ipString = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.client.remoteAddress || req.ip || "";
var ips = ipString.split(",");
if (ips.length > 0) {
return ips[0];
}
else {
return;
}
};
return self;
}
|
javascript
|
{
"resource": ""
}
|
q2557
|
train
|
function (el, cls) {
cls = getString(cls);
if (!cls) return;
if (Array.isArray(cls)) {
cls.forEach(function(c) {
dom.addClass(el, c);
});
} else if (el.classList) {
el.classList.add(cls);
} else {
if (!hasClass(el, cls)) {
if (el.classList) {
el.classList.add(cls);
} else {
el.className += ' ' + cls;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2558
|
train
|
function(name, container, args, events) {
/* handling for any default values if args are not specified */
var mergeDefaults = function(args, defaults) {
var args = args || {};
if (typeof defaults == 'object') {
for (var key in defaults) {
if (elation.utils.isNull(args[key])) {
args[key] = defaults[key];
}
}
}
return args;
};
var realname = name;
if (elation.utils.isObject(name)) {
// Simple syntax just takes an object with all arguments
args = name;
realname = elation.utils.any(args.id, args.name, null);
container = (!elation.utils.isNull(args.container) ? args.container : null);
events = (!elation.utils.isNull(args.events) ? args.events : null);
}
// If no args were passed in, we're probably being used as the base for another
// component's prototype, so there's no need to go through full init
if (elation.utils.isNull(realname) && !container && !args) {
var obj = new component.base(type);
// apply default args
obj.args = mergeDefaults(obj.args, elation.utils.clone(obj.defaults));
return obj;
}
// If no name was passed, use the current object count as a name instead ("anonymous" components)
if (elation.utils.isNull(realname) || realname === "") {
realname = component.objcount;
}
if (!component.obj[realname] && !elation.utils.isEmpty(args)) {
component.obj[realname] = obj = new component.base(type);
component.objcount++;
//}
// TODO - I think combining this logic would let us use components without needing HTML elements for the container
//if (component.obj[realname] && container !== undefined) {
component.obj[realname].componentinit(type, realname, container, args, events);
/*
if (component.extendclass) {
component.obj[realname].initSuperClass(component.extendclass);
}
*/
// fix handling for append component infinite recursion issue
if (args.append instanceof elation.component.base)
args.append = args.append.container;
if (args.before instanceof elation.component.base)
args.before = args.before.container;
// apply default args
try {
if (typeof obj.defaults == 'object')
args = mergeDefaults(args, elation.utils.clone(obj.defaults));
var parentclass = component.extendclass;
// recursively apply inherited defaults
while (parentclass) {
if (typeof parentclass.defaults == 'object')
elation.utils.merge(mergeDefaults(args, elation.utils.clone(parentclass.defaults)),args);
parentclass = parentclass.extendclass;
}
} catch (e) {
console.log('-!- Error merging component args', e.msg);
}
if (typeof obj.init == 'function') {
obj.init(realname, container, args, events);
}
}
return component.obj[realname];
}
|
javascript
|
{
"resource": ""
}
|
|
q2559
|
train
|
function(description) {
// Look for triple backtick code blocks flagged as `glimmer`;
// define end of block as triple backticks followed by a newline
let matches = description.match(/(```glimmer)(.|\n)*?```/gi);
if (matches && matches.length) {
matches.map(codeBlock => {
let blockEnd = codeBlock.length + description.indexOf(codeBlock);
let plainCode = codeBlock.replace(/(```glimmer|```)/gi, '');
description = `${description.slice(0, (blockEnd))}${plainCode}${ description.slice(blockEnd)}`;
});
}
return description;
}
|
javascript
|
{
"resource": ""
}
|
|
q2560
|
obMerge
|
train
|
function obMerge(prefix, ob1, ob2 /*, ...*/)
{
for (var i=2; i<arguments.length; ++i)
{
for (var nm in arguments[i])
{
if (arguments[i].hasOwnProperty(nm) || typeof arguments[i][nm] == 'function')
{
if (typeof(arguments[i][nm]) == 'object' && arguments[i][nm] != null)
{
ob1[prefix+nm] = (arguments[i][nm] instanceof Array) ? new Array : new Object;
obMerge('', ob1[prefix+nm], arguments[i][nm]);
}
else
{
ob1[prefix+nm] = arguments[i][nm];
}
}
}
}
return ob1;
}
|
javascript
|
{
"resource": ""
}
|
q2561
|
train
|
function(e, s)
{
var parens = [];
e.tree.push(parens);
parens.parent = e.tree;
e.tree = parens;
}
|
javascript
|
{
"resource": ""
}
|
|
q2562
|
train
|
function(done) {
return {
success: function(res) {
done(null, res);
},
error: function(res, err) {
done(err);
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q2563
|
add
|
train
|
function add(base, addend) {
if (util.isDate(base)) {
return new Date(base.getTime() + interval(addend));
}
return interval(base) + interval(addend);
}
|
javascript
|
{
"resource": ""
}
|
q2564
|
renderSass
|
train
|
function renderSass(options) {
return new Promise((resolve, reject) => {
try {
// using synchronous rendering because it is faster
let result = sass.renderSync(options);
result.css = fixEOF(result.css);
resolve(result);
} catch(err) {
reject(err);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q2565
|
train
|
function(obj) {
if (obj.anchor) {
// obj is a plane or line
var P = this.elements.slice();
var C = obj.pointClosestTo(P).elements;
return Vector.create([C[0] + (C[0] - P[0]), C[1] + (C[1] - P[1]), C[2] + (C[2] - (P[2] || 0))]);
} else {
// obj is a point
var Q = obj.elements || obj;
if (this.elements.length != Q.length) { return null; }
return this.map(function(x, i) { return Q[i-1] + (Q[i-1] - x); });
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2566
|
train
|
function(obj) {
if (obj.normal) {
// obj is a plane
var A = this.anchor.elements, D = this.direction.elements;
var A1 = A[0], A2 = A[1], A3 = A[2], D1 = D[0], D2 = D[1], D3 = D[2];
var newA = this.anchor.reflectionIn(obj).elements;
// Add the line's direction vector to its anchor, then mirror that in the plane
var AD1 = A1 + D1, AD2 = A2 + D2, AD3 = A3 + D3;
var Q = obj.pointClosestTo([AD1, AD2, AD3]).elements;
var newD = [Q[0] + (Q[0] - AD1) - newA[0], Q[1] + (Q[1] - AD2) - newA[1], Q[2] + (Q[2] - AD3) - newA[2]];
return Line.create(newA, newD);
} else if (obj.direction) {
// obj is a line - reflection obtained by rotating PI radians about obj
return this.rotate(Math.PI, obj);
} else {
// obj is a point - just reflect the line's anchor in it
var P = obj.elements || obj;
return Line.create(this.anchor.reflectionIn([P[0], P[1], (P[2] || 0)]), this.direction);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2567
|
getChanges
|
train
|
function getChanges(log, regex) {
var changes = [];
var match;
while ((match = regex.exec(log))) {
var change = '';
for (var i = 1, len = match.length; i < len; i++) {
change += match[i];
}
changes.push(change.trim());
}
return changes;
}
|
javascript
|
{
"resource": ""
}
|
q2568
|
getChangelog
|
train
|
function getChangelog(log) {
var data = {
date: moment().format('YYYY-MM-DD'),
features: getChanges(log, options.featureRegex),
fixes: getChanges(log, options.fixRegex)
};
return template(data);
}
|
javascript
|
{
"resource": ""
}
|
q2569
|
writeChangelog
|
train
|
function writeChangelog(changelog) {
var fileContents = null;
var firstLineFile = null;
var firstLineFileHeader = null;
var regex = null;
if (options.insertType && grunt.file.exists(options.dest)) {
fileContents = grunt.file.read(options.dest);
firstLineFile = fileContents.split('\n')[0];
grunt.log.debug('firstLineFile = ' + firstLineFile);
switch (options.insertType) {
case 'prepend':
changelog = changelog + '\n' + fileContents;
break;
case 'append':
changelog = fileContents + '\n' + changelog;
break;
default:
grunt.fatal('"' + options.insertType + '" is not a valid insertType. Please use "append" or "prepend".');
return false;
}
}
if (options.fileHeader) {
firstLineFileHeader = options.fileHeader.split('\n')[0];
grunt.log.debug('firstLineFileHeader = ' + firstLineFileHeader);
if (options.insertType === 'prepend') {
if (firstLineFile !== firstLineFileHeader) {
changelog = options.fileHeader + '\n\n' + changelog;
} else {
regex = new RegExp(options.fileHeader+'\n\n','m');
changelog = options.fileHeader + '\n\n' + changelog.replace(regex, '');
}
// insertType === 'append' || undefined
} else {
if (firstLineFile !== firstLineFileHeader) {
changelog = options.fileHeader + '\n\n' + changelog;
}
}
}
grunt.file.write(options.dest, changelog);
// Log the results.
grunt.log.ok(changelog);
grunt.log.writeln();
grunt.log.writeln('Changelog created at '+ options.dest.toString().cyan + '.');
}
|
javascript
|
{
"resource": ""
}
|
q2570
|
train
|
function (preconditions) {
var errorCodesList = {
"500": ["InternalServerError"],
"400": [
"UnexpectedDefaultValue",
"UnexpectedType",
"MinLengthUnderachieved",
"MaxLengthExceeded",
"MinValueUnderachived",
"MaxValueExceeded",
"ValueNotAllowed",
"PatternMismatch",
"MissingRequiredParameter"],
"429": ["RateLimitExceeded"],
};
for (var index in preconditions) {
if (preconditions[index].conditions && preconditions[index].conditions.responses) {
for (var code in preconditions[index].conditions.responses) {
if (errorCodesList[code]) {
if (_.isArray(preconditions[index].conditions.responses[code])) {
for (var ecode in preconditions[index].conditions.responses[code]) {
if (_.indexOf(errorCodesList[code], preconditions[index].conditions.responses[code][ecode]) == -1) {
errorCodesList[code].push(preconditions[index].conditions.responses[code][ecode]);
}
}
}
else {
if (_.indexOf(errorCodesList[code], preconditions[index].conditions.responses[code]) == -1) {
errorCodesList[code].push(preconditions[index].conditions.responses[code]);
}
}
}
else {
if (_.isArray(preconditions[index].conditions.responses[code])) {
errorCodesList[code] = _.clone(preconditions[index].conditions.responses[code]);
}
else {
errorCodesList[code] = [_.clone(preconditions[index].conditions.responses[code])];
}
}
}
}
}
return errorCodesList;
}
|
javascript
|
{
"resource": ""
}
|
|
q2571
|
train
|
function (attr, attrName) {
if (_.isObject(attr) && !_.isDate(attr) && !_.isBoolean(attr) && !_.isString(attr) && !_.isNumber(attr) && !_.isFunction(attr) && !_.isRegExp(attr) && !_.isArray(attr)) {
//attr = _removeAttributes();
for (var aIndex in attr) {
attr[aIndex] = _removeAttributes(attr[aIndex], aIndex);
}
return attr;
}
else {
if (_.indexOf(allowedAttributes, attrName) != -1) {
if (_.isFunction(attr)) {
attr = _functionName(attr);
}
return attr;
}
else {
return;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2572
|
train
|
function (parametersList, parameters, section) {
if (parameters[section]) {
for (var name in parameters[section]) {
var addCondition = parameters[section][name];
if (parametersList[section] && parametersList[section][name]) {
// Merge parameters attributes
for (var attr in addCondition) {
if (_.has(parametersList, [section, name, attr]) === false) {
// Attribute does not exists -> add to list
parametersList[section][name][attr] = addCondition[attr];
} else {
// Attribute already exists compare values
if (_.isFunction(addCondition[attr])) {
addCondition[attr] = _functionName(addCondition[attr]);
}
if (JSON.stringify(parametersList[section][name][attr]) != JSON.stringify(addCondition[attr])) {
throw new Error("Precondition conflict: " + preconditions[index].name + ' -> ' + preconditions[index].version + ' -> ' + preconditions[index].method + ' -> ' + attr + ':' + addCondition[attr] + ' -> already defined in previous controller and value is mismatching');
}
else {
parametersList[section][name][attr] = addCondition[attr];
}
}
}
} else {
parametersList[section] = parametersList[section] ? parametersList[section] : {};
parametersList[section][name] = addCondition;
}
// Filter parameter attributes by allowedAttributes
var validatedParameterAttributes = {};
if (_.has(parametersList, [section, name])) {
for (var attr in parametersList[section][name]) {
validatedParameterAttributes[attr] = _removeAttributes(parametersList[section][name][attr], attr);
}
}
if (!_.isEmpty(validatedParameterAttributes)) {
parametersList[section][name] = validatedParameterAttributes;
}
}
}
return parametersList;
}
|
javascript
|
{
"resource": ""
}
|
|
q2573
|
train
|
function (req, res, next) {
if (!req.miajs.controllerDebugInfo) {
req.miajs.controllerDebugInfo = {};
}
if (controller.name && controller.version) {
req.miajs.controllerDebugInfo[controller.name + '_' + controller.version] = {'runtime': Date.now() - req.miajs.controllerStart};
}
next();
}
|
javascript
|
{
"resource": ""
}
|
|
q2574
|
train
|
function (routeConfig, methodValue) {
var rateLimits = [];
var environment = Shared.config("environment");
var globalRateLimit = environment.rateLimit;
if (globalRateLimit) {
if (globalRateLimit.interval && _.isNumber(globalRateLimit.interval) && parseInt(globalRateLimit.interval) > 0 && globalRateLimit.maxRequests && _.isNumber(globalRateLimit.maxRequests) && parseInt(globalRateLimit.maxRequests) > 0) {
rateLimits.push(globalRateLimit);
}
else {
throw new Error('Global rate limit config invalid' + ". Provide parameters 'interval' and 'maxRequests' with Int value");
}
}
if (routeConfig && routeConfig.rateLimit) {
if (routeConfig.rateLimit.interval && _.isNumber(routeConfig.rateLimit.interval) && parseInt(routeConfig.rateLimit.interval) > 0 && routeConfig.rateLimit.maxRequests && _.isNumber(routeConfig.rateLimit.maxRequests) && parseInt(routeConfig.rateLimit.maxRequests) > 0) {
rateLimits.push(routeConfig.rateLimit);
}
else {
throw new Error('Rate limit config invalid for route file ' + routeConfig.prefix + ". Provide parameters 'interval' and 'maxRequests' with Int value");
}
}
if (methodValue && methodValue.rateLimit) {
if (methodValue.rateLimit.interval && _.isNumber(methodValue.rateLimit.interval) && parseInt(methodValue.rateLimit.interval) > 0 && methodValue.rateLimit.maxRequests && _.isNumber(methodValue.rateLimit.maxRequests) && parseInt(methodValue.rateLimit.maxRequests) > 0) {
rateLimits.push(methodValue.rateLimit);
}
else {
throw new Error('Rate limit config invalid for route ' + methodValue.identity + ' in route file ' + routeConfig.prefix + ". Provide parameters 'interval' and 'maxRequests' with Int value");
}
}
if (!_.isEmpty(rateLimits) && !Shared.memcached()) {
throw new Error("Rate limits set but memcached not configured. Provide settings for memcached in environment config file");
}
return rateLimits;
}
|
javascript
|
{
"resource": ""
}
|
|
q2575
|
train
|
function (req, res, next) {
var ip = IPAddressHelper.getClientIP(req)
, route = req.miajs.route
, key = ip + route.path + route.method;
if (_.isEmpty(route.rateLimits)) {
next();
return;
}
RateLimiter.checkRateLimitsByKey(key, route.rateLimits).then(function (rateLimiterResult) {
if (rateLimiterResult.remaining == -1) {
_logInfo("Rate limit of " + rateLimiterResult.limit + "req/" + rateLimiterResult.timeInterval + "min requests exceeded " + route.requestmethod.toUpperCase() + " " + route.url + " for " + ip);
res.header("X-Rate-Limit-Limit", rateLimiterResult.limit);
res.header("X-Rate-Limit-Remaining", 0);
res.header("X-Rate-Limit-Reset", rateLimiterResult.timeTillReset);
next(new MiaError({
status: 429,
err: {
'code': 'RateLimitExceeded',
'msg': Translator('system', 'RateLimitExceeded')
}
}));
}
else {
res.header("X-Rate-Limit-Limit", rateLimiterResult.limit);
res.header("X-Rate-Limit-Remaining", rateLimiterResult.remaining);
res.header("X-Rate-Limit-Reset", rateLimiterResult.timeTillReset);
next();
}
}).catch(function () {
next();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2576
|
train
|
function (range) {
var coeff = 1000 * 60 * range;
return new Date(Math.ceil(new Date(Date.now()).getTime() / coeff) * coeff).getTime() / 1000;
}
|
javascript
|
{
"resource": ""
}
|
|
q2577
|
train
|
function (key, timeInterval, limit) {
//Validate rate limiter settings
if (!_.isNumber(timeInterval) || parseInt(timeInterval) <= 0 || !_.isNumber(limit) || parseInt(limit) <= 0) {
return Q.reject();
}
var cacheKey = Encryption.md5("MiaJSRateLimit" + key + _calculateCurrentTimeInterval(timeInterval));
return _validateRateLimit(cacheKey, timeInterval, limit).then(function (value) {
return Q({
limit: limit,
remaining: limit - value,
timeInterval: timeInterval,
timeTillReset: _getTimeLeftTillReset(timeInterval)
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2578
|
train
|
function (key, intervalSize, limit) {
var deferred = Q.defer()
, memcached = Shared.memcached();
if (!memcached) {
deferred.reject();
}
else {
//Get current rate for ip
memcached.get(key, function (err, value) {
if (err) {
//Allow access as failover
Logger.warn("Rate limit set but memcached error, allow access without limit", err);
deferred.reject();
}
else if (_.isUndefined(value)) {
memcached.set(key, 1, 60 * intervalSize, function (err) {
if (err) {
Logger.warn("Rate limit set but memcached error, allow access without limit", err);
}
});
deferred.resolve(1);
}
else {
//Do not increase rate counter if exceeded anyway
if (value < limit) {
// Increase rate counter by 1
memcached.incr(key, 1, function (err) {
if (err) {
Logger.warn("Rate limit set but memcached error, allow access without limit", err);
}
});
}
deferred.resolve(value + 1);
}
});
}
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q2579
|
train
|
function(e, win) {
var event = $.event.get(e, win);
var wheel = $.event.getWheel(event);
that.handleEvent('MouseWheel', e, win, wheel);
}
|
javascript
|
{
"resource": ""
}
|
|
q2580
|
$E
|
train
|
function $E(tag, props) {
var elem = document.createElement(tag);
for(var p in props) {
if(typeof props[p] == "object") {
$.extend(elem[p], props[p]);
} else {
elem[p] = props[p];
}
}
if (tag == "canvas" && !supportsCanvas && G_vmlCanvasManager) {
elem = G_vmlCanvasManager.initElement(document.body.appendChild(elem));
}
return elem;
}
|
javascript
|
{
"resource": ""
}
|
q2581
|
getNodesToHide
|
train
|
function getNodesToHide(node) {
node = node || this.clickedNode;
if(!this.config.constrained) {
return [];
}
var Geom = this.geom;
var graph = this.graph;
var canvas = this.canvas;
var level = node._depth, nodeArray = [];
graph.eachNode(function(n) {
if(n.exist && !n.selected) {
if(n.isDescendantOf(node.id)) {
if(n._depth <= level) nodeArray.push(n);
} else {
nodeArray.push(n);
}
}
});
var leafLevel = Geom.getRightLevelToShow(node, canvas);
node.eachLevel(leafLevel, leafLevel, function(n) {
if(n.exist && !n.selected) nodeArray.push(n);
});
for (var i = 0; i < nodesInPath.length; i++) {
var n = this.graph.getNode(nodesInPath[i]);
if(!n.isDescendantOf(node.id)) {
nodeArray.push(n);
}
}
return nodeArray;
}
|
javascript
|
{
"resource": ""
}
|
q2582
|
getNodesToShow
|
train
|
function getNodesToShow(node) {
var nodeArray = [], config = this.config;
node = node || this.clickedNode;
this.clickedNode.eachLevel(0, config.levelsToShow, function(n) {
if(config.multitree && !('$orn' in n.data)
&& n.anySubnode(function(ch){ return ch.exist && !ch.drawn; })) {
nodeArray.push(n);
} else if(n.drawn && !n.anySubnode("drawn")) {
nodeArray.push(n);
}
});
return nodeArray;
}
|
javascript
|
{
"resource": ""
}
|
q2583
|
SubStream
|
train
|
function SubStream(stream, name, options) {
if (!(this instanceof SubStream)) return new SubStream(stream, name, options);
options = options || {};
this.readyState = stream.readyState; // Copy the current readyState.
this.stream = stream; // The underlaying stream.
this.name = name; // The stream namespace/name.
this.primus = options.primus; // Primus reference.
//
// Register the SubStream on the socket.
//
if (!stream.streams) stream.streams = {};
if (!stream.streams[name]) stream.streams[name] = this;
Stream.call(this);
//
// No need to continue with the execution if we don't have any events that
// need to be proxied.
//
if (!options.proxy) return;
for (var i = 0, l = options.proxy.length, event; i < l; i++) {
event = options.proxy[i];
this.stream.on(event, this.emits(event));
}
}
|
javascript
|
{
"resource": ""
}
|
q2584
|
fallBack
|
train
|
function fallBack () {
var programFilesVar = "ProgramFiles";
if (arch === "(64)") {
console.warn("You are using 32-bit version of Firefox on 64-bit versions of the Windows.\nSome features may not work correctly in this version. You should upgrade Firefox to the latest 64-bit version now!")
programFilesVar = "ProgramFiles(x86)";
}
resolve(path.join(process.env[programFilesVar], appName, "firefox.exe"));
}
|
javascript
|
{
"resource": ""
}
|
q2585
|
listen
|
train
|
function listen(event, spark) {
if ('end' === event) return function end() {
if (!spark.streams) return;
for (var stream in spark.streams) {
stream = spark.streams[stream];
if (stream.end) stream.end();
}
};
if ('readyStateChange' === event) return function change(reason) {
if (!spark.streams) return;
for (var stream in spark.streams) {
stream = spark.streams[stream];
stream.readyState = spark.readyState;
if (stream.emit) emit.call(stream, event, reason);
}
};
return function proxy() {
if (!spark.streams) return;
var args = Array.prototype.slice.call(arguments, 0);
for (var stream in spark.streams) {
if (stream.emit) emit.call(stream, [event].concat(args));
}
};
}
|
javascript
|
{
"resource": ""
}
|
q2586
|
createLoggerStream
|
train
|
function createLoggerStream(name, level, logglyConfig) {
const streams = [process.stdout];
if (logglyConfig.enabled) {
const logglyStream = new LogglyStream({
token: logglyConfig.token,
subdomain: logglyConfig.subdomain,
name,
environment: logglyConfig.environment,
});
streams.push(logglyStream);
}
return new UnionStream({ streams });
}
|
javascript
|
{
"resource": ""
}
|
q2587
|
confChanged
|
train
|
function confChanged(current, proposed) {
if (stringify(current.conf) !== stringify(proposed.conf)) {
if (current.version >= proposed.version) {
const e = new Error('Schema change, but no version increment.');
e.current = current;
e.proposed = proposed;
throw e;
}
return true;
} else {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q2588
|
validatePropertyType
|
train
|
function validatePropertyType(property, type, recursive) {
return type && (
(recursive && typeof property === 'object') ||
(type === 'string' && typeof property === 'string') ||
(type === 'number' && typeof property === 'number') ||
(type === 'uuid' && isUuid(property)) ||
(type === 'uuidList' && isUuidList(property))
);
}
|
javascript
|
{
"resource": ""
}
|
q2589
|
parseObject
|
train
|
function parseObject(obj, { name, path, subPaths, type, recursive = true, ...args }) {
let property = get(obj, path);
if (property === null || !validatePropertyType(property, type, recursive)) {
return [];
}
if (type === 'uuidList' && isUuidList(property)) {
return [{ [name]: property.split(',') }];
}
if (recursive && typeof property === 'object') {
const propertyName = isNil(name) ? '' : name;
const nextPaths = subPaths || Object.keys(property);
return flatten(nextPaths
.map(subPath => parseObject(obj, {
name: `${propertyName}${subPath}`,
path: `${path}.${subPath}`,
recursive: false,
type,
...args,
})));
}
if (args.filterPattern) {
property = typeof property === 'string' ? get(property.match(args.filterPattern), '[1]') : null;
}
if (args.hideUUID) {
property = typeof property === 'string' ? property.replace(
RegExp('[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}', 'g'),
'{uuid}',
) : null;
}
return property === null ? [] : [{ [name]: property }];
}
|
javascript
|
{
"resource": ""
}
|
q2590
|
Entry
|
train
|
function Entry(name, hash, status, mode, deed, registrationDate, value, highestBid) {
// TODO: improve Entry constructor so that unknown names can be handled via getEntry
this.name = name;
this.hash = hash;
this.status = status;
this.mode = mode;
this.deed = deed;
this.registrationDate = registrationDate;
this.value = value;
this.highestBid = highestBid;
}
|
javascript
|
{
"resource": ""
}
|
q2591
|
skip
|
train
|
function skip(ignoreRouteUrls) {
return function ignoreUrl(req) {
const url = req.originalUrl || req.url;
return ignoreRouteUrls.includes(url);
};
}
|
javascript
|
{
"resource": ""
}
|
q2592
|
omit
|
train
|
function omit(req, blacklist) {
return omitBy(req, (value, key) => blacklist.includes(key));
}
|
javascript
|
{
"resource": ""
}
|
q2593
|
morganMiddleware
|
train
|
function morganMiddleware(req, res, next) {
const { ignoreRouteUrls, includeReqHeaders, omitReqProperties } = getConfig('logger');
const { format } = getConfig('logger.morgan');
// define custom tokens
morgan.token('operation-hash', request => get(request, 'body.extensions.persistentQuery.sha256Hash'));
morgan.token('operation-name', request => get(request, 'body.operationName'));
morgan.token('user-id', request => get(request, 'locals.user.id'));
morgan.token('company-id', request => get(request, 'locals.user.companyId'));
morgan.token('message', request => request.name || '-');
morgan.token('request-id', request => request.id);
morgan.token('request-headers', (request) => {
const headers = includeReqHeaders === true
? omit(request.headers, omitReqProperties) : {};
return JSON.stringify(headers);
});
const logger = getContainer('logger');
const formatFormat = json(format);
const options = {
stream: asStream(logger),
skip: skip(ignoreRouteUrls),
};
return morgan(formatFormat, options)(req, res, next);
}
|
javascript
|
{
"resource": ""
}
|
q2594
|
getConfig
|
train
|
function getConfig(config) {
// Read a RESTBase configuration from a (optional) path argument, an (optional) CONFIG
// env var, or from /etc/restbase/config.yaml
var conf;
if (config) {
conf = config;
} else if (process.env.CONFIG) {
conf = process.env.CONFIG;
} else {
conf = '/etc/restbase/config.yaml';
}
var confObj = yaml.safeLoad(fs.readFileSync(conf));
return confObj.default_project['x-modules'][0].options.table;
}
|
javascript
|
{
"resource": ""
}
|
q2595
|
train
|
function (name) {
var octave = null;
name = prepareNoteName(name);
// Extract octave number if given
if (/\d$/.test(name)) {
octave = parseInt(name.slice(-1));
name = name.slice(0, -1);
}
// Throw an error for an invalid note name
if (!(/^[A-Ga-g](bb|##|[b#n])?$/).test(name)) {
throw new Error('Invalid note name: ' + name);
}
return {
letter: name[0].toUpperCase(),
acc: name.slice(1) || 'n',
octave: octave
};
}
|
javascript
|
{
"resource": ""
}
|
|
q2596
|
train
|
function (note, number) {
var letter = note.letter;
var index = scale.indexOf(note.letter);
var newIndex = mod(index + number - 1, scale.length);
assert(index > -1);
assert(newIndex > -1 && newIndex < scale.length);
return scale[newIndex];
}
|
javascript
|
{
"resource": ""
}
|
|
q2597
|
train
|
function (letter1, letter2) {
var index1 = scale.indexOf(letter1);
var index2 = scale.indexOf(letter2);
var distance = mod(index2 - index1, scale.length) + 1;
assert(index1 > -1);
assert(index2 > -1);
assert(distance > 0 && distance <= scale.length);
return distance;
}
|
javascript
|
{
"resource": ""
}
|
|
q2598
|
train
|
function (int) {
var map = interval.isPerfect(int.number) ? perfectOffsets : majorOffsets;
var key = _.invert(map)[int.quality];
return parseInt(key, 10);
}
|
javascript
|
{
"resource": ""
}
|
|
q2599
|
train
|
function (number, halfSteps) {
var diatonicHalfSteps = getDiatonicHalfSteps(number);
var halfStepOffset = halfSteps - diatonicHalfSteps;
// Handle various abnormalities
if (halfStepOffset === 11) halfStepOffset = -1;
if (halfStepOffset === -11) halfStepOffset = 1;
return halfStepOffset;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.