_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| 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;
|
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) ===
|
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');
|
javascript
|
{
"resource": ""
}
|
q2503
|
indent
|
train
|
function indent(str, indent) {
if (typeof indent === 'number') {
var indent_str = '';
while (indent_str.length < indent) indent_str += ' ';
indent
|
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)+"";
|
javascript
|
{
"resource": ""
}
|
q2505
|
escapestr
|
train
|
function escapestr(s) {
return s.replace(/\\/g, '\\\\')
.replace(/'/g, '\\\'')
.replace(/"/g, '\\"')
|
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
|
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));
|
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 => {
|
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];
}
}
|
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;
|
javascript
|
{
"resource": ""
}
|
|
q2511
|
train
|
function (arguments) {
var argData = ArgumentHelpers.prepareCallback(arguments);
var callback = argData.callback;
var args = argData.arguments;
|
javascript
|
{
"resource": ""
}
|
|
q2512
|
train
|
function (functionName, arguments) {
var self = this;
var args = self._getArgs(arguments);
var callback = self._getCallback(arguments);
|
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);
}
}
|
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 ||
|
javascript
|
{
"resource": ""
}
|
|
q2515
|
train
|
function (bodySchemaModels, defName) {
for (var i in bodySchemaModels) {
if (bodySchemaModels[i]["name"] == defName) {
|
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);
}
}
|
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) {
|
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) {
|
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)) {
|
javascript
|
{
"resource": ""
}
|
|
q2520
|
name
|
train
|
function name(fp, options) {
var opts = options || {};
if (typeof opts.namespace === 'function') {
return opts.namespace(fp,
|
javascript
|
{
"resource": ""
}
|
q2521
|
read
|
train
|
function read(fp, opts) {
if (opts && opts.read) {
return opts.read(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 = '.'
|
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
|
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
|
javascript
|
{
"resource": ""
}
|
q2525
|
assertObject
|
train
|
function assertObject(attr, data) {
if (data === null || data === undefined) {
return null;
}
|
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) {
|
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
|
javascript
|
{
"resource": ""
}
|
q2528
|
assertString
|
train
|
function assertString(attr, data) {
if (data === null || data === undefined) {
return null;
}
if (typeof data !== 'string') {
throw new
|
javascript
|
{
"resource": ""
}
|
q2529
|
train
|
function (values, model, type) {
var deferred = Q.defer();
var modelData = {data: model};
ModelValidator.validate(values, modelData,
|
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] = {};
|
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;
}
}
|
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');
|
javascript
|
{
"resource": ""
}
|
|
q2533
|
train
|
function (initFunction) {
if (_.isFunction(initFunction)) {
Logger.info("Run init function");
_customInitFuncton = initFunction;
return initFunction(appHttp)
.then(function () {
|
javascript
|
{
"resource": ""
}
|
|
q2534
|
train
|
function () {
//set logger
if (!module.parent) {
appHttp.use(morgan({format: 'dev'}));
|
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"];
|
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:
|
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
|
javascript
|
{
"resource": ""
}
|
|
q2538
|
train
|
function () {
const crons = _.get(Shared, 'runtimeArgs.cron') || _.get(Shared, 'runtimeArgs.crons');
if (crons) {
const cronTasks = crons.replace(/\s/g, '').split(',');
|
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) {
|
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: {}
},
{
|
javascript
|
{
"resource": ""
}
|
q2541
|
loadFromFile
|
train
|
function loadFromFile(filename) {
var cfg = {}
Object.assign(
cfg,
|
javascript
|
{
"resource": ""
}
|
q2542
|
saveToFile
|
train
|
function saveToFile(filename, cfg) {
// Use 'wx' flag to fails if filename exists
|
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)
|
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
|
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) {
|
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);
|
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
|
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
|
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)) {
|
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) {
|
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)){
|
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
|
javascript
|
{
"resource": ""
}
|
q2553
|
train
|
function () {
return ServerHeartbeatModel.find({
status: _statusActive
}).then(function (cursor) {
return Q.ninvoke(cursor, 'toArray').then(function (servers) {
var 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();
|
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] +=
|
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 || {};
|
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) {
|
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) {
|
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)
|
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;
|
javascript
|
{
"resource": ""
}
|
q2561
|
train
|
function(e, s)
{
var parens = [];
e.tree.push(parens);
|
javascript
|
{
"resource": ""
}
|
|
q2562
|
train
|
function(done) {
return {
success: function(res) {
|
javascript
|
{
"resource": ""
}
|
|
q2563
|
add
|
train
|
function add(base, addend) {
if (util.isDate(base)) {
return new Date(base.getTime() + interval(addend));
|
javascript
|
{
"resource": ""
}
|
q2564
|
renderSass
|
train
|
function renderSass(options) {
return new Promise((resolve, reject) => {
try {
// using synchronous rendering because
|
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
|
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
|
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
|
javascript
|
{
"resource": ""
}
|
q2568
|
getChangelog
|
train
|
function getChangelog(log) {
var data = {
date: moment().format('YYYY-MM-DD'),
|
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 {
|
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])) {
|
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 {
|
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];
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2573
|
train
|
function (req, res, next) {
if (!req.miajs.controllerDebugInfo) {
req.miajs.controllerDebugInfo = {};
}
if (controller.name && controller.version) {
|
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)
|
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: {
|
javascript
|
{
"resource": ""
}
|
|
q2576
|
train
|
function (range) {
var coeff = 1000 * 60 * range;
|
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({
|
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);
|
javascript
|
{
"resource": ""
}
|
|
q2579
|
train
|
function(e, win) {
var event = $.event.get(e, win);
var wheel = $.event.getWheel(event);
|
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];
}
}
|
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);
}
|
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; })) {
|
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);
//
//
|
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
|
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) {
|
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,
|
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;
|
javascript
|
{
"resource": ""
}
|
q2588
|
validatePropertyType
|
train
|
function validatePropertyType(property, type, recursive) {
return type && (
(recursive && typeof property === 'object') ||
(type === 'string' && typeof property === 'string') ||
(type ===
|
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) {
|
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;
|
javascript
|
{
"resource": ""
}
|
q2591
|
skip
|
train
|
function skip(ignoreRouteUrls) {
return function ignoreUrl(req) {
|
javascript
|
{
"resource": ""
}
|
q2592
|
omit
|
train
|
function omit(req, blacklist) {
return
|
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) => {
|
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;
|
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
|
javascript
|
{
"resource": ""
}
|
|
q2596
|
train
|
function (note, number) {
var letter = note.letter;
var index = scale.indexOf(note.letter);
var newIndex =
|
javascript
|
{
"resource": ""
}
|
|
q2597
|
train
|
function (letter1, letter2) {
var index1 = scale.indexOf(letter1);
var index2 = scale.indexOf(letter2);
var distance =
|
javascript
|
{
"resource": ""
}
|
|
q2598
|
train
|
function (int) {
var map = interval.isPerfect(int.number) ? perfectOffsets
|
javascript
|
{
"resource": ""
}
|
|
q2599
|
train
|
function (number, halfSteps) {
var diatonicHalfSteps = getDiatonicHalfSteps(number);
var halfStepOffset = halfSteps - diatonicHalfSteps;
// Handle various abnormalities
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.