_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q60900
|
hilbertIndexInverse
|
validation
|
function hilbertIndexInverse(dim, index, options) { // :: Int -> Int -> [Int, Int, ..]
options = options || {}
var entry = options.entry || 0,
direction = options.direction || 0,
m = curvePrecision(index, dim),
p = Array.apply(null, new Array(dim)).map(Number.prototype.valueOf, 0)
for (var i = m - 1; i >= 0; i--) {
var mask = 1 << (i * dim), bits = 0, code
for (var k = dim - 1; k >= 0; k--) {
if (index & (mask << k)) {
bits |= (1 << k)
}
}
code = grayInverseTransform(entry, direction, grayCode(bits), dim)
for (var k = 0; k < dim; k++) {
if (code & (1 << k)) {
p[k] |= (1 << i)
}
}
entry = entry ^ bitwise.rotateLeft(entrySequence(bits), dim, 0, direction + 1)
direction = (direction + directionSequence(bits, dim) + 1) % dim
}
return p
}
|
javascript
|
{
"resource": ""
}
|
q60901
|
getConsoleReporterOpts
|
validation
|
function getConsoleReporterOpts(opts) {
opts = opts || {};
opts.print = function () {
grunt.log.write.apply(this, arguments);
};
// checking this here for the old name `verbose` (now alias).
opts.verbosity = opts.verbosity === undefined
? opts.verbose
: opts.verbosity;
return opts;
}
|
javascript
|
{
"resource": ""
}
|
q60902
|
_taskFatalHandler_
|
validation
|
function _taskFatalHandler_(e) {
var err = e ? (e.stack || e.message || e) : 'Unknown Error';
grunt.fatal(err, grunt.fail.code.TASK_FAILURE);
}
|
javascript
|
{
"resource": ""
}
|
q60903
|
validation
|
function(options, cb) {
// if no sassDir or files are not identify, error.
if (!options.sassDir) {
grunt.log.error('compass-multiple needs sassDir for searching scss files.');
cb(false);
}
// search scss files.(Additional Implementation)
if (options.sassFiles) {
var pathes = options.sassFiles;
var pathesCount = pathes.length;
var currentCount = 0;
var files = [];
for (var i = 0; i < pathes.length; i++) {
glob(pathes[i], function(error, tmpFiles) {
if (error) {
console.log('error: ', error);
cb(false);
}
files = files.concat(tmpFiles);
currentCount++;
if (pathesCount === currentCount) {
// compass compile.
grunt.log.writeln('pathes: ', files);
compileFiles(options, files, cb);
}
});
}
} else { // use sassDir
var searchPath = options.sassDir + '/**/*.scss';
glob(searchPath, function(error, files) {
if (error) {
console.log('error: ', error);
cb(false);
}
// compass compile.
compileFiles(options, files, cb);
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60904
|
pageRange
|
validation
|
function pageRange(selected, numPages, num) {
let selectedPos = Math.ceil(num / 2);
let start = (selected < selectedPos) ? 1
: selected - selectedPos + 1;
let len = (numPages < start + num - 1) ? numPages - start + 1
: num;
return Array
.apply(null, Array(len))
.map((u, i) => start + i);
}
|
javascript
|
{
"resource": ""
}
|
q60905
|
showTasks
|
validation
|
function showTasks(tasks) {
const taskList = Object.keys(tasks);
if (taskList.length) {
taskList.forEach((task) => {
process.stdout.write(`Task Name: '${task}'`);
if (tasks[task].description) {
process.stdout.write(` - Description: ${tasks[task].description}`);
}
process.stdout.write('\n');
});
} else {
process.stdout.write('No tasks available.\n');
}
}
|
javascript
|
{
"resource": ""
}
|
q60906
|
sh
|
validation
|
function sh(cmd, exitOnError, cb) {
const child = exec(cmd, {
encoding: 'utf8',
timeout: 1000 * 60 * 2, // 2 min; just want to make sure nothing gets detached forever.
});
let stdout = '';
child.stdout.on('data', (data) => {
stdout += data;
process.stdout.write(data);
});
child.stderr.on('data', (data) => {
process.stdout.write(data);
});
child.on('close', (code) => {
if (code > 0) {
if (exitOnError) {
if (typeof cb === 'function') {
cb(new Error(`Error with code ${code} after running: ${cmd}`));
} else {
process.stdout.write(`Error with code ${code} after running: ${cmd} \n`);
process.exit(code);
}
} else {
notifier.notify({
title: cmd,
message: stdout,
sound: true,
});
}
}
if (typeof cb === 'function') cb();
});
}
|
javascript
|
{
"resource": ""
}
|
q60907
|
readYamlFile
|
validation
|
function readYamlFile(file, cb) {
fs.readFile(file, 'utf8', (err, data) => {
if (err) throw err;
cb(yaml.safeLoad(data));
});
}
|
javascript
|
{
"resource": ""
}
|
q60908
|
writeYamlFile
|
validation
|
function writeYamlFile(file, data, cb) {
fs.writeFile(file, yaml.safeDump(data), () => {
if (cb) cb();
});
}
|
javascript
|
{
"resource": ""
}
|
q60909
|
middleware
|
validation
|
function middleware(file, options) {
var matcher = new RegExp("\\.(?:"+ middleware.extensions.join("|")+")$")
if (!matcher.test(file)) return through();
var input = '';
var write = function (buffer) {
input += buffer;
}
var end = function () {
this.queue(createModule(input, options));
this.queue(null);
}
return through(write, end);
}
|
javascript
|
{
"resource": ""
}
|
q60910
|
createModule
|
validation
|
function createModule(body, options) {
body = middleware.sanitize(body)
if (String(options.parameterize) !== 'false') {
body = middleware.parameterise(body)
}
if (options.module === "es6" || options.module === "es2015") {
var module = 'export default ' + body + ';\n';
}
else {
var module = 'module.exports = ' + body + ';\n';
}
return module
}
|
javascript
|
{
"resource": ""
}
|
q60911
|
validation
|
function(schema,definition) {
return _.reduce(schema, function(memo, field) {
// console.log('definition normalize');console.log(definition);
// Marshal mysql DESCRIBE to waterline collection semantics
var attrName = field.COLUMN_NAME.toLowerCase();
/*Comme oracle n'est pas sensible à la casse, la liste des colonnes retournées est differentes de celle enregistrée dans le schema,
ce qui pose des problèmes à waterline*/
Object.keys(definition).forEach(function (key){
if(attrName === key.toLowerCase()) attrName = key;
});
var type = field.DATA_TYPE;
// Remove (n) column-size indicators
type = type.replace(/\([0-9]+\)$/, '');
memo[attrName] = {
type: type
// defaultsTo: '',
//autoIncrement: field.Extra === 'auto_increment'
};
if (field.primaryKey) {
memo[attrName].primaryKey = field.primaryKey;
}
if (field.unique) {
memo[attrName].unique = field.unique;
}
if (field.indexed) {
memo[attrName].indexed = field.indexed;
}
return memo;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
|
q60912
|
validation
|
function(collectionName, values, key) {
return sql.build(collectionName, values, sql.prepareValue, ', ', key);
}
|
javascript
|
{
"resource": ""
}
|
|
q60913
|
validation
|
function(collectionName, where, key, parentKey) {
return sql.build(collectionName, where, sql.predicate, ' AND ', undefined, parentKey);
}
|
javascript
|
{
"resource": ""
}
|
|
q60914
|
validation
|
function(collectionName, criterion, key, parentKey) {
var queryPart = '';
if (parentKey) {
return sql.prepareCriterion(collectionName, criterion, key, parentKey);
}
// OR
if (key.toLowerCase() === 'or') {
queryPart = sql.build(collectionName, criterion, sql.where, ' OR ');
return ' ( ' + queryPart + ' ) ';
}
// AND
else if (key.toLowerCase() === 'and') {
queryPart = sql.build(collectionName, criterion, sql.where, ' AND ');
return ' ( ' + queryPart + ' ) ';
}
// IN
else if (_.isArray(criterion)) {
queryPart = sql.prepareAttribute(collectionName, null, key) + " IN (" + sql.values(collectionName, criterion, key) + ")";
return queryPart;
}
// LIKE
else if (key.toLowerCase() === 'like') {
return sql.build(collectionName, criterion, function(collectionName, value, attrName) {
var attrStr = sql.prepareAttribute(collectionName, value, attrName);
attrStr = attrStr.replace(/'/g, '"');
// TODO: Handle regexp criterias
if (_.isRegExp(value)) {
throw new Error('RegExp LIKE criterias not supported by the MySQLAdapter yet. Please contribute @ http://github.com/balderdashy/sails-mysql');
}
var valueStr = sql.prepareValue(collectionName, value, attrName);
// Handle escaped percent (%) signs [encoded as %%%]
valueStr = valueStr.replace(/%%%/g, '\\%');
var condition = (attrStr + " LIKE " + valueStr);
//condition = condition.replace(/'/g, '"');
return condition;
}, ' AND ');
}
// NOT
else if (key.toLowerCase() === 'not') {
throw new Error('NOT not supported yet!');
}
// Basic criteria item
else {
return sql.prepareCriterion(collectionName, criterion, key);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60915
|
sqlTypeCast
|
validation
|
function sqlTypeCast(type, attrName) {
type = type && type.toLowerCase();
switch (type) {
case 'string':
return 'VARCHAR2(255)';
case 'text':
case 'array':
case 'json':
return 'VARCHAR2(255)';
case 'boolean':
return 'NUMBER(1) CHECK("' + attrName + '" IN (0,1))';
case 'int':
case 'integer':
return 'NUMBER';
case 'float':
case 'double':
return 'FLOAT';
case 'date':
return 'DATE';
case 'datetime':
return 'TIMESTAMP';
case 'binary':
return 'BLOB';
default:
console.error("Unregistered type given: " + type);
return "TEXT";
}
}
|
javascript
|
{
"resource": ""
}
|
q60916
|
validSubAttrCriteria
|
validation
|
function validSubAttrCriteria(c) {
return _.isObject(c) && (
!_.isUndefined(c.not) || !_.isUndefined(c.greaterThan) || !_.isUndefined(c.lessThan) ||
!_.isUndefined(c.greaterThanOrEqual) || !_.isUndefined(c.lessThanOrEqual) || !_.isUndefined(c['<']) ||
!_.isUndefined(c['<=']) || !_.isUndefined(c['!']) || !_.isUndefined(c['>']) || !_.isUndefined(c['>=']) ||
!_.isUndefined(c.startsWith) || !_.isUndefined(c.endsWith) || !_.isUndefined(c.contains) || !_.isUndefined(c.like));
}
|
javascript
|
{
"resource": ""
}
|
q60917
|
processIconTemplate
|
validation
|
function processIconTemplate(srcFile, destFile, data, cb) {
fs.readFile(srcFile, 'utf8', (err, srcFileContents) => {
if (err) throw err;
const result = template(srcFileContents, {
// Use custom template delimiters of `{{` and `}}`.
interpolate: /{{([\s\S]+?)}}/g,
// Use custom evaluate delimiters of `{%` and `%}`.
evaluate: /{%([\s\S]+?)%}/g,
})(data);
fs.writeFile(destFile, result, cb);
});
}
|
javascript
|
{
"resource": ""
}
|
q60918
|
icons
|
validation
|
function icons(done) {
const stream = gulp.src(config.src)
.pipe(iconfont({
fontName: config.iconName,
appendUniconde: true,
formats: config.formats,
timestamp: config.useTimestamp ? getTimestamp() : 0,
autohint: config.autohint,
normalize: config.normalize,
}));
// write icons to disk
stream.pipe(gulp.dest(config.dest));
// reload browser
core.events.emit('reload');
if (config.templates.enabled && config.templates.sets.length) {
stream.on('glyphs', (glyphs) => {
// console.log(glyphs);
const iconData = {
glyphs: glyphs.map(glyph => ({ // returns the object
name: glyph.name,
content: glyph.unicode[0].toString(16).toUpperCase(),
})),
fontName: config.iconName,
fontPath: config.fontPathPrefix,
classNamePrefix: config.classNamePrefix,
};
Promise.all(config.templates.sets.map(set => new Promise((resolve, reject) => {
processIconTemplate(set.src, set.dest, iconData, (err) => {
if (err) reject();
resolve();
});
}))).then(() => done());
});
} else {
done();
}
}
|
javascript
|
{
"resource": ""
}
|
q60919
|
injectData
|
validation
|
function injectData(tokenValue, options, key) {
var data;
if (~options.contentType.indexOf('application/json')) {
data = options.data ? JSON.parse(options.data) : {};
data[key] = tokenValue;
options.data = JSON.stringify(data);
} else {
options.data += options.data ? '&' : '';
options.data += key + '=' + tokenValue;
}
}
|
javascript
|
{
"resource": ""
}
|
q60920
|
injectQuery
|
validation
|
function injectQuery(tokenValue, options, param) {
options.url += ~options.url.indexOf('?') ? '&' : '?';
options.url += param + '=' + tokenValue;
}
|
javascript
|
{
"resource": ""
}
|
q60921
|
homedir
|
validation
|
function homedir(username) {
return username ? path.resolve(path.dirname(home), username) : home;
}
|
javascript
|
{
"resource": ""
}
|
q60922
|
validation
|
function (conn, cb) {
if (LOG_DEBUG) {
console.log("BEGIN tearDown");
}
if (typeof conn == 'function') {
cb = conn;
conn = null;
}
if (!conn) {
connections = {};
return cb();
}
if (!connections[conn])
return cb();
delete connections[conn];
cb();
}
|
javascript
|
{
"resource": ""
}
|
|
q60923
|
validation
|
function (connectionName, table, query, data, cb) {
var connectionObject = connections[connectionName];
if (LOG_DEBUG) {
console.log("BEGIN query");
}
if (_.isFunction(data)) {
cb = data;
data = null;
}
// Run query
if (!data)
data = {};
connectionObject.pool.getConnection(
function (err, connection)
{
if (err) {
return handleQueryError(err, 'query');;
}
if (LOG_QUERIES) {
console.log('Executing query: ' + query);
}
connection.execute(query, data, {outFormat: oracledb.OBJECT}, function (err, result) {
if (err) {
doRelease(connection);
return cb(err, result);
}
return castClobs(result, function (err, result) {
if (err) {
doRelease(connection);
return cb(err, result);
}
if (LOG_QUERIES) {
console.log("Length: " + result.rows.length);
}
doRelease(connection);
return cb(err, result);
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60924
|
dropTable
|
validation
|
function dropTable(item, next) {
// Build Query
var query = 'DROP TABLE ' + utils.escapeName(item) + '';
// Run Query
connectionObject.pool.getConnection(function (err, connection) {
if (LOG_QUERIES) {
console.log('Executing query: ' + query);
}
connection.execute(query, {}, function (err, result) {
doRelease(connection);
next(null, result);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q60925
|
validation
|
function (connectionName, table, attrName, attrDef, cb) {
var connectionObject = connections[connectionName];
if (LOG_DEBUG) {
console.log("BEGIN addAttribute");
}
// Escape Table Name
table = utils.escapeName(table);
// Setup a Schema Definition
var attrs = {};
attrs[attrName] = attrDef;
var _schema = utils.buildSchema(attrs);
// Build Query
var query = 'ALTER TABLE ' + table + ' ADD COLUMN ' + _schema;
// Run Query
connectionObject.pool.getConnection(
function (err, connection)
{
if (err) {
handleQueryError(err, 'addAttribute');
return;
}
if (LOG_QUERIES) {
console.log('Executing query: ' + query);
}
connection.execute(query, {}, {outFormat: oracledb.OBJECT}, function __ADD_ATTRIBUTE__(err, result) {
/* Release the connection back to the connection pool */
doRelease(connection);
if (err)
return cb(handleQueryError(err, 'addAttribute'));
cb(null, result.rows);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60926
|
validation
|
function(connectionName, table, options, data, cb) {
if (LOG_DEBUG) {
console.log("BEGIN update");
}
//LIMIT in a oracle UPDATE command is not valid
if (hop(options, 'limit')) {
return cb(new Error('Your \'LIMIT ' + options.limit + '\' is not allowed in the Oracle DB UPDATE query.'));
}
var connectionObject = connections[connectionName];
var collection = connectionObject.collections[table];
var _schema = connectionObject.schema;
var processor = new Processor(_schema);
// Mixin WL Next connection overrides to sqlOptions
var overrides = connectionOverrides[connectionName] || {};
var _options = _.cloneDeep(sqlOptions);
if (hop(overrides, 'wlNext')) {
_options.wlNext = overrides.wlNext;
}
var sequel = new Sequel(_schema, _options);
var query;
// Build a query for the specific query strategy
try {
query = sequel.update(table, options, data);
} catch (e) {
return cb(e);
}
query.query = query.query.replace('RETURNING *', '');
query.query = query.query.replace( /\$/g, ':');
query.query = query.query.replace(' AS ', " ");
var keys = Object.keys(data);
var j = 1;
for (j; j < keys.length + 1; j++) {
query.query = query.query.replace(":" + j, ":" + keys[j - 1]);
}
var keysoptions = Object.keys(options.where);
var oraOptions = {where: {}};
for(var k=0; k <keysoptions.length; k++){
oraOptions.where[ "where"+keysoptions[k] ] = options.where[ keysoptions[k] ];
data["where"+keysoptions[k]] = options.where[ keysoptions[k] ];
}
var keysoptions = Object.keys(oraOptions.where);
for (var z = keys.length; z < keys.length + keysoptions.length + 1; z++) {
query.query = query.query.replace(":" + z, ":" + keysoptions[z - 1 - keys.length]);
}
// Run Query
connectionObject.pool.getConnection(
function (err, connection)
{
if (err) {
handleQueryError(err, 'create');
return;
}
if (LOG_QUERIES) {
console.log('Executing query: ' + query.query);
}
connection.execute(query.query, data, {/*outFormat: oracledb.OBJECT, */autoCommit: false}, function __CREATE__(err, result) {
if (err) {
// Release the connection back to the connection pool
return connection.rollback(function(rollerr) {
doRelease(connection);
return cb(handleQueryError(err, 'update'));
});
}
// Build a query for the specific query strategy
try {
var _seqQuery = sequel.find(table, options);
} catch (e) {
return cb(handleQueryError(e, 'update'));
}
var findQuery = _seqQuery.query[0];
findQuery = findQuery.split( /\$/g).join(":");
findQuery = findQuery.split(" AS ").join(" ");
var keysOptionsSelect = Object.keys(oraOptions.where);
for (var z = 1; z < keysOptionsSelect.length + 1; z++) {
findQuery = findQuery.replace(":" + z, ":" + keysOptionsSelect[z-1]);
}
connection.execute(findQuery, oraOptions.where, {outFormat: oracledb.OBJECT}, function __CREATE_SELECT__(err, result){
if (err){
// Release the connection back to the connection pool
return connection.rollback(function(rollerr) {
doRelease(connection);
return cb(handleQueryError(err, 'update_select'));
});
}
// Cast special values
var values = [];
result.rows.forEach(function (row) {
values.push(processor.cast(table, _.omit(row, 'LINE_NUMBER')));
});
connection.commit(function (err){
// Release the connection back to the connection pool
doRelease(connection);
if (err){
return cb(handleQueryError(err, 'update_commit'));
}
cb(null, values);
});
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60927
|
validation
|
function(connectionName, table, options, cb) {
if (LOG_DEBUG) {
console.log("BEGIN destroy");
}
var connectionObject = connections[connectionName];
var collection = connectionObject.collections[table];
var _schema = connectionObject.schema;
// Mixin WL Next connection overrides to sqlOptions
var overrides = connectionOverrides[connectionName] || {};
var _options = _.cloneDeep(sqlOptions);
if (hop(overrides, 'wlNext')) {
_options.wlNext = overrides.wlNext;
}
var sequel = new Sequel(_schema, _options);
var query;
// Build a query for the specific query strategy
try {
query = sequel.destroy(table, options);
} catch (e) {
return cb(e);
}
query.query = query.query.replace('RETURNING *', '');
query.query = query.query.replace( /\$/g, ':');
query.query = query.query.replace(" AS ", " ");
// Run Query
connectionObject.pool.getConnection(
function (err, connection)
{
if (err) {
handleQueryError(err, 'destroy');
return;
}
if (LOG_QUERIES) {
console.log('Executing query: ' + query.query);
console.log('Data for query: ' + JSON.stringify(query.values));
}
connection.execute(query.query, query.values, {autoCommit: true, outFormat: oracledb.OBJECT}, function __DELETE__(err, result) {
if (err) {
/* Release the connection back to the connection pool */
doRelease(connection);
return cb(handleQueryError(err, 'destroy'));
}
/* Release the connection back to the connection pool */
doRelease(connection);
cb(null, result.rows);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60928
|
printError
|
validation
|
function printError (message) {
arrayify(message).forEach(function (msg) {
console.error(ansi.format(msg, 'red'))
})
}
|
javascript
|
{
"resource": ""
}
|
q60929
|
printOutput
|
validation
|
function printOutput (message) {
process.stdout.on('error', err => {
if (err.code === 'EPIPE') {
/* no big deal */
}
})
arrayify(message).forEach(function (msg) {
console.log(ansi.format(msg))
})
}
|
javascript
|
{
"resource": ""
}
|
q60930
|
halt
|
validation
|
function halt (err, options) {
options = Object.assign({ exitCode: 1 }, options)
if (err) {
if (err.code === 'EPIPE') {
process.exit(0) /* no big deal */
} else {
const t = require('typical')
printError(t.isString(err) ? err : options.stack ? err.stack : err.message, options)
}
}
process.exit(options.exitCode)
}
|
javascript
|
{
"resource": ""
}
|
q60931
|
getCli
|
validation
|
function getCli (definitions, usageSections, argv) {
const commandLineArgs = require('command-line-args')
const commandLineUsage = require('command-line-usage')
const usage = usageSections ? commandLineUsage(usageSections) : ''
const options = commandLineArgs(definitions, argv)
return { options, usage }
}
|
javascript
|
{
"resource": ""
}
|
q60932
|
CompositeError
|
validation
|
function CompositeError(message, innerErrors) {
this.message = message;
this.name = 'CompositeError';
this.innerErrors = normalizeInnerErrors(innerErrors);
Error.captureStackTrace(this, this.constructor);
this.originalStackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack');
// Override the stack property
Object.defineProperty(this, 'stack', {
get: function() { return this.formatStackTraces(); }
});
}
|
javascript
|
{
"resource": ""
}
|
q60933
|
handleRequest
|
validation
|
function handleRequest(req, res) {
var self = this;
var config = self.app.config;
// if request is type POST|config.transport.method and on /exec|config.transport.path url then parse the data and handle it
if (req.url.indexOf(config.transport.path) !== -1 && req.method.toLowerCase() === config.transport.method.toLowerCase() ) {
return self.app.exec(req.body, function(err, out) {
if (err) {
return handleError.call(self, err, req, res);
}
sendResponse(res, out || null, { statusCode: 200 });
});
}
// default action for the rest of requests
sendResponse(res, { message: 'To call an action use '+config.transport.path }, { statusCode: 200 });
}
|
javascript
|
{
"resource": ""
}
|
q60934
|
killPosix
|
validation
|
function killPosix() {
getDescendentProcessInfo(this.pid, (err, descendent) => {
if (err) {
return
}
descendent.forEach(({PID: pid}) => {
try {
process.kill(pid)
} catch (_err) {
// ignore.
}
})
})
}
|
javascript
|
{
"resource": ""
}
|
q60935
|
TreeWalker
|
validation
|
function TreeWalker(ast, recv) {
var self = this;
this.ast = ast;
this.recv = recv;
this.stack =
[{traverse: ast, parent: undefined, name: undefined},
{fun: function () {
if (self.hasProp(self.recv, 'finished') &&
Function === self.recv.finished.constructor) {
return self.recv.finished();
}
}}];
this.current = undefined;
}
|
javascript
|
{
"resource": ""
}
|
q60936
|
validation
|
function () {
self.log("enumerate");
var result = [], keys, i, name, desc;
stm.recordRead(self);
keys = handler.getPropertyNames();
for (i = 0; i < keys.length; i += 1) {
name = keys[i];
desc = handler.getPropertyDescriptor(name);
if (undefined !== desc && desc.enumerable) {
result.push(name);
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q60937
|
validation
|
function (obj, meta) {
var val, parentId;
if (undefined === obj || util.isPrimitive(obj)) {
return {proxied: obj, raw: obj};
}
val = this.proxiedToTVar.get(obj);
if (undefined === val) {
val = this.objToTVar.get(obj);
if (undefined === val) {
this.tVarCount += 1;
val = new TVar(this.tVarCount, obj, this);
this.proxiedToTVar.set(val.proxied, val);
this.objToTVar.set(obj, val);
this.idToTVar[val.id] = val;
this.recordCreation(val, meta);
return val;
} else {
// found it in the cache
return val;
}
} else {
// obj was already proxied
return val;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60938
|
ContractInstance
|
validation
|
function ContractInstance(config) {
_classCallCheck(this, ContractInstance);
this._config = config;
this._contract = config.contract;
this._web3 = this._contract._web3;
this._address = config.address;
this._inst = this.contract._contract.at(this._address);
/*
Logger is same as parent contract one, except that address is prepended
to all log output.
*/
this._logger = {};
for (var logMethod in DUMMY_LOGGER) {
this._logger[logMethod] = function (logMethod, self) {
return function () {
self.contract.logger[logMethod].apply(self.contract.logger, ['[' + self.address + ']: '].concat(Array.from(arguments)));
};
}(logMethod, this);
}
}
|
javascript
|
{
"resource": ""
}
|
q60939
|
Transaction
|
validation
|
function Transaction(config) {
_classCallCheck(this, Transaction);
this._web3 = config.parent._web3;
this._logger = config.parent._logger;
this._hash = config.hash;
}
|
javascript
|
{
"resource": ""
}
|
q60940
|
spawnCommandWithKill
|
validation
|
function spawnCommandWithKill(...args) {
const child = spawnCommand(...args)
child.kill = kill.bind(child)
return child
}
|
javascript
|
{
"resource": ""
}
|
q60941
|
applyFormat
|
validation
|
function applyFormat(method, args, string) {
// Parse a string like "1, 2, false, 'test'"
var m, pos = 0;
while ((m = string.substring(pos).match(argsExp))) {
// number
args.push(m[2] ? +m[2]
// boolean
: (m[1] ? m[1] === 'true'
// string
: m[4].replace(quotesExp[m[3]], m[3])));
pos += m[0].length;
}
return method.apply(null, args);
}
|
javascript
|
{
"resource": ""
}
|
q60942
|
FormatError
|
validation
|
function FormatError(func, msg, value) {
this.name = 'FormatError';
this.message = new Formatter()(msg, value);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, func);
}
}
|
javascript
|
{
"resource": ""
}
|
q60943
|
chooseDataSource
|
validation
|
function chooseDataSource(dataSource) {
if (dataSource === 'json') {
return function(file) {
return JSON.parse(file.contents.toString());
};
} else if (dataSource === 'vinyl') {
return function(file) {
file[bodyAttribute] = file.contents.toString();
return file;
};
} else if (dataSource === 'data') {
return function(file) {
var data = file.data;
data[bodyAttribute] = file.contents.toString();
return data;
};
} else if (typeof dataSource === 'function') {
return dataSource;
} else {
throw pluginError('Unknown dataSource');
}
}
|
javascript
|
{
"resource": ""
}
|
q60944
|
templatesFromStream
|
validation
|
function templatesFromStream(templateStream) {
var firstTemplate = null;
templateStream.on('data', function(file) {
var relpath = file.relative;
var deferred;
if (registry.hasOwnProperty(relpath)) {
deferred = registry[relpath];
} else {
deferred = registry[relpath] = new Deferred();
}
try {
if (!file.isBuffer()) {
throw pluginError('Template source must be buffer');
}
var template = compile({
data: file.contents.toString(),
name: file.path,
path: file.path
});
deferred.resolve(template);
if (firstTemplate === null) {
firstTemplate = template;
} else {
firstTemplate = false;
theOnlyTemplate.reject(pluginError('Multiple templates given, must select one'));
}
} catch(err) {
deferred.reject(err);
}
}).on('end', function() {
if (firstTemplate)
theOnlyTemplate.resolve(firstTemplate);
else
theOnlyTemplate.reject(pluginError('No templates in template stream'));
noMoreTemplates();
}).on('error', function(err) {
templateStreamError = err;
noMoreTemplates();
});
}
|
javascript
|
{
"resource": ""
}
|
q60945
|
noMoreTemplates
|
validation
|
function noMoreTemplates() {
registryComplete = true;
// Reject all unresolved promises
Object.keys(registry).forEach(function(templateName) {
registry[templateName].reject(noSuchTemplate(templateName));
});
theOnlyTemplate.reject(noSuchTemplate('<default>'));
}
|
javascript
|
{
"resource": ""
}
|
q60946
|
templateFromFile
|
validation
|
function templateFromFile(path) {
// template source is a file name
forcedTemplateName = 'singleton';
if (cache.hasOwnProperty(templateSrc)) {
registry.singleton = cache[templateSrc];
return;
}
// Have to read this template for the first time
var deferred = cache[templateSrc] = registry.singleton = new Deferred();
fs.readFile(templateSrc, 'utf-8', function(err, data) {
try {
if (err) throw err;
var template = compile({
data: data,
name: templateSrc,
path: templateSrc
});
deferred.resolve(template);
} catch (err2) {
// delete cache[templateSrc]; // Should we do this?
deferred.reject(err2);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q60947
|
processFile
|
validation
|
function processFile(file, cb) {
var data = dataSource(file);
return pickTemplate(
forcedTemplateName
|| getTemplateName(data)
|| defaultTemplateName)
.then(function(template) {
file.path = replaceExt(file.path, '.html');
data._file= file;
data._target = {
path: file.path,
relative: replaceExt(file.relative, '.html'),
};
// data = dataParser(data);
var result = template.render(data);
file.contents = new Buffer(result, 'utf-8');
return file;
});
}
|
javascript
|
{
"resource": ""
}
|
q60948
|
pickTemplate
|
validation
|
function pickTemplate(templateName) {
if (templateName === THE_ONLY_TEMPLATE)
return theOnlyTemplate.promise;
if (registry.hasOwnProperty(templateName))
return registry[templateName].promise;
if (registryComplete)
throw noSuchTemplate(templateName);
return (registry[templateName] = new Deferred()).promise;
}
|
javascript
|
{
"resource": ""
}
|
q60949
|
getTemplateName
|
validation
|
function getTemplateName(data) {
for (var i = 0; i < templateAttribute.length; ++i) {
if (!data) return null;
data = data[templateAttribute[i]];
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q60950
|
deepSet
|
validation
|
function deepSet(obj, path) {
var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var define = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : !1;
if (!(0, _object.isObject)(obj)) throw new TypeError('Deepget is only supported for objects');
var parts = interpolatePath(path);
// Build any unknown paths and set cursor
for (var i = 0; i < parts.length - 1; i++) {
// If this part is an empty string, just continue
if (parts[i] === '') continue;
if (!obj[parts[i]]) obj[parts[i]] = {};
// Set cursor
obj = obj[parts[i]];
// If not an array continue
if (!(0, _array.isArray)(obj)) continue;
// If an array and i is not the last index ... set the object to be the index on the array
if (i < parts.length - 2) {
obj = obj[parts[i + 1]];
i++;
}
}
// Set the actual value on the cursor
define ? Object.defineProperty(obj, parts[parts.length - 1], value) : obj[parts[parts.length - 1]] = value;
return !0;
}
|
javascript
|
{
"resource": ""
}
|
q60951
|
deepGet
|
validation
|
function deepGet(obj, path) {
var get_parent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : !1;
if (!(0, _object.isObject)(obj)) throw new TypeError('Deepget is only supported for objects');
var parts = interpolatePath(path);
// Return obj if no parts were passed or if only 1 part and get_parent is true
if (parts.length === 0 || parts.length === 1 && get_parent) return obj;
// Cut last part if get_parent
if (get_parent) parts.pop();
var cursor = obj;
while (parts.length > 0) {
cursor = (0, _array.isArray)(cursor) ? cursor[parseInt(parts.shift())] : cursor[parts.shift()];
}
// false | 0 | '' will all negate the ternary, hence we do extra checks here
// to make sure none of them comes back as undefined
return cursor || cursor === !1 || cursor === 0 || cursor === '' ? cursor : undefined;
}
|
javascript
|
{
"resource": ""
}
|
q60952
|
validation
|
function (/*message, channel*/) {
var args = Array.prototype.slice.apply(arguments);
var message = args[0];
var rpcCallbackHandler = function () {};
// Check if event is of type "rpc".
if ('__type' in message && message.__type === 'rpc') {
// After the application executes the "done" handler,
// the result will be trigger back to the "back channel" (rpc response).
// After that step, the "rpc callback" handler will handle the result data.
rpcCallbackHandler = function (err, result) {
self.emit(
message.__backChannel,
{
err: err,
result: result
}
);
};
}
// Append our extended rpc callback handler
args = [].concat(args, [rpcCallbackHandler]);
// Call original handler with extended args
handler.apply(null, args);
}
|
javascript
|
{
"resource": ""
}
|
|
q60953
|
toPercentage
|
validation
|
function toPercentage(val) {
var precision = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var min = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var max = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;
if (!isNumber(val) || isNumericalNaN(val)) {
throw new TypeError('Value should be numeric');
}
if (!isNumber(min) || isNumericalNaN(min)) {
throw new TypeError('Value should be numeric');
}
if (!isNumber(max) || isNumericalNaN(max)) {
throw new TypeError('Value should be numeric');
}
return round((val - min) / (max - min) * 100, precision);
}
|
javascript
|
{
"resource": ""
}
|
q60954
|
round
|
validation
|
function round(val) {
var precision = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
if (!isNumber(val) || isNumericalNaN(val)) {
throw new TypeError('Value should be numeric');
}
if (precision === !1 || precision < 1) {
return Math.round(val);
}
var exp = Math.pow(10, Math.round(precision));
return Math.round(val * exp) / exp;
}
|
javascript
|
{
"resource": ""
}
|
q60955
|
randomBetween
|
validation
|
function randomBetween() {
var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10;
if (!isNumber(min) || isNumericalNaN(min)) {
throw new TypeError('Min should be numeric');
}
if (!isNumber(max) || isNumericalNaN(max)) {
throw new TypeError('Max should be numeric');
}
return Math.random() * max + min;
}
|
javascript
|
{
"resource": ""
}
|
q60956
|
Flow
|
validation
|
function Flow(limit) {
this.limit = limit;
Object.defineProperty(this, "futureStack_", {
enumerable: false,
writable: true,
value: []
});
Object.defineProperty(this, "runningNum_", {
enumerable: false,
writable: true,
value: 0
});
}
|
javascript
|
{
"resource": ""
}
|
q60957
|
Future
|
validation
|
function Future(f, args) {
var self = this;
function run() {
args[args.length] = function cb() {
switch (arguments.length) {
case 0:
self.result = null;
break;
case 1:
if (arguments[0] instanceof Error) {
self.err = arguments[0];
} else {
self.result = arguments[0];
}
break;
default:
self.err = arguments[0];
if (arguments.length === 2) {
self.result = arguments[1];
} else {
self.result = Array.prototype.slice.call(arguments, 1);
}
break;
}
if (self.flow_) self.flow_.futureFinished();
var caller = self.caller;
if (caller) caller.run();
};
args.length++;
f.apply(undefined, args);
}
this.run = run;
var flow = Fiber.current.flow;
if (flow) {
Object.defineProperty(this, "flow_", {
enumerable: false,
writable: true,
value: flow
});
flow.registerFuture(this);
} else {
run();
}
}
|
javascript
|
{
"resource": ""
}
|
q60958
|
hashish
|
validation
|
function hashish() {
var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Math.floor(Math.random() * 100);
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var base = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 36;
return _createHash(id, _createSalts(n, base), base);
}
|
javascript
|
{
"resource": ""
}
|
q60959
|
indexOfMatch
|
validation
|
function indexOfMatch(string, regex, index) {
const str = index !== null ? string.substring(index) : string;
const matches = str.match(regex);
return matches ? str.indexOf(matches[0]) + index : -1;
}
|
javascript
|
{
"resource": ""
}
|
q60960
|
lastIndexOfMatch
|
validation
|
function lastIndexOfMatch(string, regex, index) {
const str = index !== null ? string.substring(0, index) : string;
const matches = str.match(regex);
return matches ? str.lastIndexOf(matches[matches.length - 1]) : -1;
}
|
javascript
|
{
"resource": ""
}
|
q60961
|
splitLines
|
validation
|
function splitLines(string, index) {
const str = index ? string.substring(index) : string;
return str.split(/\r\n|\r|\n/);
}
|
javascript
|
{
"resource": ""
}
|
q60962
|
inlineHandler
|
validation
|
function inlineHandler(string, selectionRange, symbol) {
let newString = string;
const newSelectionRange = [...selectionRange];
// insertSymbols determines whether to add the symbol to either end of the selected text
// Stat with assuming we will insert them (we will remove as necessary)
const insertSymbols = [symbol, symbol];
const symbolLength = symbol.length;
const relevantPart = string.substring(selectionRange[0] - symbolLength, selectionRange[1] + symbolLength).trim();
// First check that the symbol is in the string at all
if (relevantPart.includes(symbol)) {
// If it is, for each index in the selection range...
newSelectionRange.forEach((selectionIndex, j) => {
const isStartingIndex = j === 0;
const isEndingIndex = j === 1;
// If the symbol immediately precedes the selection index...
if (newString.lastIndexOf(symbol, selectionIndex) === selectionIndex - symbolLength) {
// First trim it
newString = newString.substring(0, selectionIndex - symbolLength) + newString.substring(selectionIndex);
// Then adjust the selection range,
// If this is the starting index in the range, we will have to adjust both
// starting and ending indices
if (isStartingIndex) {
newSelectionRange[0] -= symbolLength;
newSelectionRange[1] -= symbolLength;
}
if (isEndingIndex && !insertSymbols[0]) {
newSelectionRange[1] -= symbol.length;
}
// Finally, disallow the symbol at this end of the selection
insertSymbols[j] = '';
}
// If the symbol immediately follows the selection index...
if (newString.indexOf(symbol, selectionIndex) === selectionIndex) {
// Trim it
newString = newString.substring(0, selectionIndex) + newString.substring(selectionIndex + symbolLength);
// Then adjust the selection range,
// If this is the starting index in the range...
if (isStartingIndex) {
// If the starting and ending indices are NOT the same (selection length > 0)
// Adjust the ending selection down
if (newSelectionRange[0] !== newSelectionRange[1]) {
newSelectionRange[1] -= symbolLength;
}
// If the starting and ending indices are the same (selection length = 0)
// Adjust the starting selection down
if (newSelectionRange[0] === newSelectionRange[1]) {
newSelectionRange[0] -= symbolLength;
}
}
// If this is the ending index and the range
// AND we're inserting the symbol at the starting index,
// Adjust the ending selection up
if (isEndingIndex && insertSymbols[0]) {
newSelectionRange[1] += symbolLength;
}
// Finally, disallow the symbol at this end of the selection
insertSymbols[j] = '';
}
});
}
// Put it all together
const value = newString.substring(0, newSelectionRange[0]) + insertSymbols[0] + newString.substring(newSelectionRange[0], newSelectionRange[1]) + insertSymbols[1] + newString.substring(newSelectionRange[1]);
return {
value,
range: [newSelectionRange[0] + insertSymbols[0].length, newSelectionRange[1] + insertSymbols[1].length]
};
}
|
javascript
|
{
"resource": ""
}
|
q60963
|
insertHandler
|
validation
|
function insertHandler(string, selectionRange, snippet) {
const start = selectionRange[0];
const end = selectionRange[1];
const value = string.substring(0, start) + snippet + string.substring(end, string.length);
return { value, range: [start, start + snippet.length] };
}
|
javascript
|
{
"resource": ""
}
|
q60964
|
markymark
|
validation
|
function markymark(container = document.getElementsByTagName('marky-mark')) {
if (container instanceof HTMLElement) {
return initializer(container);
}
if (!(container instanceof Array) && !(container instanceof HTMLCollection) && !(container instanceof NodeList)) {
throw new TypeError('argument should be an HTMLElement, Array, HTMLCollection');
}
return Array.from(container).map(initializer);
}
|
javascript
|
{
"resource": ""
}
|
q60965
|
toJavascript
|
validation
|
function toJavascript(data, mergeInto) {
var result = mergeInto || {}
var keys = Object.keys(data)
for (var i = 0; i < keys.length; i++) {
var p = keys[i]
result[p] = toJsValue(data[p])
}
return result
}
|
javascript
|
{
"resource": ""
}
|
q60966
|
toDDB
|
validation
|
function toDDB(data, mergeInto) {
var result = mergeInto || {}
var keys = Object.keys(data)
for (var i = 0; i < keys.length; i++) {
var p = keys[i]
result[p] = toDDBValue(data[p])
}
return result
}
|
javascript
|
{
"resource": ""
}
|
q60967
|
deepClone
|
validation
|
function deepClone(obj) {
if (obj == null || typeof obj !== 'object') {
return obj;
}
var cloned = obj.constructor();
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
cloned[key] = deepClone(obj[key]);
}
}
return cloned;
}
|
javascript
|
{
"resource": ""
}
|
q60968
|
deepMerge
|
validation
|
function deepMerge(one, another) {
if (another == null || typeof another !== 'object') {
return another;
}
if(one == null && typeof another === 'object') {
if(Array.isArray(another)) {
one = [];
} else {
one = {};
}
}
var cloned = deepClone(another);
for (var key in cloned) {
if (cloned.hasOwnProperty(key)) {
one[key] = deepMerge(one[key], another[key]);
}
}
return one;
}
|
javascript
|
{
"resource": ""
}
|
q60969
|
contentsToDisplay
|
validation
|
function contentsToDisplay(req, res, scsId, scId = 0, cb) {
var zlSiteContentIn = app.models.zlSiteContentIn;
var Role = app.models.Role;
var compMod = require('./helpers/component-from-model')(app);
// emit that content was requested
if (res.locals.emiter.emit(`fetching content ${scsId}`, cb)) {
// if a package listen, it is responsible for callback
// also enable using scsId that is not in db to not cause error
return;
}
var { themeData } = res.locals;
// first, make sure they are allowed to view page
// get role permission for page
let filter = {fields: {scsPermission: true, zlSiteId: true}};
app.models.zlSiteContentSet.findById(scsId, filter, (err, scs) => {
if (err || !scs) return cb(`page does not exist`);
let ctx = app.locals.authCtx(req, res);
Role.isInRole(scs.scsPermission, ctx, (err, isInRole) => {
if (isInRole) {
// filter for model search
let filter = {
fields: {scId: true},
include: {
relation: 'zlSiteContent',
scope: {
where: {scStatus: 'publish', zlSiteId: res.locals.zlSite.zsId},
},
},
where: {scsId: scsId},
};
zlSiteContentIn.find(filter, (err, data) => {
// to keep list of promises
var promises = [];
// functions in component-from-model may need to make promises
compMod.promises = promises;
_.forEach(data, function(val, key) {
if (!val || !val.zlSiteContent) return data.splice(key, 1);
// converts from loopback object to json
val = val.toJSON().zlSiteContent;
if ('page content' === val.scType) {
// overide data to this value
data = val.scContent;
// iterate list of page content
if (_.isArray(data)) {
_.forEach(data, function(subVal, subKey) {
// make sure there is a scId
subVal.scId = (subVal.scId)?subVal.scId:`pg${scsId}-cont${subKey}`;
prepContent(req, res, data, subVal, subKey, promises,
compMod, scsId, cb);
});
}
// end here since only 1 active content list is used
return false;
} else {
// other type (like 'post' but not yet used anywhere)
data[key] = val.scContent;
prepContent(req, res, data, val.scContent, key, promises,
compMod, scsId, cb);
}
});
// emit that content loaded; allowing other sources to populate further
res.locals.emiter.emit(`loaded content ${scsId}`, data, promises);
// when all promise met, callback
Promise.all(promises).then(values => {
cb(null, data);
});
});
} else cb('Page Authorization failed');
});
});
compMod.themeData = themeData;
}
|
javascript
|
{
"resource": ""
}
|
q60970
|
vhostof
|
validation
|
function vhostof (req, regexp, subsite) {
var host = req.headers.host
var hostname = hostnameof(req)
if (!hostname) {
return
}
var match = regexp.exec(hostname)
if (!match) {
return
}
if (subsite && 'IS_ROUTE' != subsite && !_.startsWith(req.path, subsite+'/', 1)
&& (req.get('X-Base-Url-Path') != subsite)) {
return
}
var obj = Object.create(null)
obj.host = host
obj.hostname = hostname
obj.length = match.length - 1
for (var i = 1; i < match.length; i++) {
obj[i - 1] = match[i]
}
return obj
}
|
javascript
|
{
"resource": ""
}
|
q60971
|
setPackagesState
|
validation
|
function setPackagesState(app, dependencies, cb) {
var zealPacks = {};
let promises = [];
_.forEach(dependencies, function(val, key) {
buildPackagesList(app, zealPacks, val, key, promises);
});
/* app.debug('Installed themes: %O', app.locals.themes);
app.debug('Installed apps: %O', app.locals.apps); */
Promise.all(promises).then(() => {
app.emit('zealder packages loaded');
// if callback passed
if (cb) cb(zealPacks);
});
}
|
javascript
|
{
"resource": ""
}
|
q60972
|
loadModels
|
validation
|
function loadModels(app, datasource, src, cb = null) {
const ds = app.dataSources[datasource];
let promises = [], modelsNames = [];
let files = fs.readdirSync(src);
if (files) {
files.forEach(file => {
// load model for all model json files
if (file.endsWith('.json')) {
promises.push( new Promise((resolve, reject) => {
fs.readFile(`${src}/${file}`, 'utf8', (fileErr, data) => {
if (fileErr) app.error(`Failed reading %s because: %s`, file, fileErr);
else {
let mJson = JSON.parse(data);
let model = loopback.createModel(mJson);
app.model(model, {dataSource: datasource});
modelsNames.push(mJson.name);
resolve();
}
});
}));
}
});
}
Promise.all(promises).then(() => {
// process addl model js
if (files) {
files.forEach(file => {
if (file.endsWith('.js')) {
require(`${src}/${file}`)(app);
}
});
/**
* NOTE: UNCOMMENT TO UPDATE DB ON PRODUCTION ALTHOUGH THAT SHOULD BE
* AVOIDED BECAUSE IT RECREATE TABLE STRUCTURE AND REMOVES INDEXES, while
* TRYING TO REBUILD STRUCTURE/INDEX IT CAN LEAVE SOME OUT ON LARGE DB AND
* CREATE OPTIMIZATION NIGHTMARE
*/
//if ('build' === process.env.WORK && !_.isEmpty(modelsNames)) {
if ('development' === process.env.NODE_ENV && !_.isEmpty(modelsNames)) {
ds.autoupdate(modelsNames);
}
}
if (cb) cb();
});
}
|
javascript
|
{
"resource": ""
}
|
q60973
|
makeEntity
|
validation
|
function makeEntity(req, res, all, top, data, path = '', promises) {
var Role = app.models.Role;
const { zlSite } = res.locals;
const zsBaseUrlPath = (zlSite.zsBaseUrlPath) ? `/${zlSite.zsBaseUrlPath}/` : '/'
_.forEach(_.filter(all, ['scsParent', top]), function(val) {
val = val.toJSON();
/* check if have children
NOTE: since children loads first, they will return even if parent
permission is denied, so must assign children correct permission/role */
if (_.find(all, ['scsParent', val.scsId])) {
data = makeEntity(req, res, all, val.scsId, data, path+val.scsSlug+'/', promises);
}
let loadThisEntity = () => {
data[val.scsId] = val;
// placeholder for content id list
data[val.scsId]['contents'] = [];
// set page path
data[val.scsId]['path'] = `${path}${val.scsSlug}`;
data[val.scsId]['realPath'] = `${zsBaseUrlPath}${data[val.scsId]['path']}`;
}
// make sure they have correct permission
// verify that they have permission to this page
let ctx = app.locals.authCtx(req, res);
return promises.push( new Promise((resolve, reject) => {
Role.isInRole(val.scsPermission, ctx, (err, isInRole) => {
if (isInRole) {
loadThisEntity();
}
resolve();
});
}));
// if we reach here, I guess we can load page
loadThisEntity();
});
return data;
}
|
javascript
|
{
"resource": ""
}
|
q60974
|
buildAllRoles
|
validation
|
function buildAllRoles(all, roles) {
all.push(...roles);
_.forEach(roles, function(role) {
// check if have inherits
if (ROLE_INHERIT[role]) {
all = buildAllRoles(all, ROLE_INHERIT[role]);
}
});
return all;
}
|
javascript
|
{
"resource": ""
}
|
q60975
|
makeScreenCap
|
validation
|
function makeScreenCap(zsId, url, req) {
const zlSite = app.models.zlSite;
// make screen capture (skip if is screencap request during screencap building)
if (!req.get('X-Phantom-Js')) {
let siteScreenCap = '';
let cap = spawn(`${path.join(__dirname, "helpers/phantomjs")}`, [
'--ignore-ssl-errors=true',
path.join(__dirname, "helpers/siteScreenCap.js"),
url,
req.accessToken.id
]);
cap.stdout.on('data', data => {
siteScreenCap += data;
});
cap.on('close', (code) => {
if (0 == code) {
// screencap successful
app.locals.cdn.upload(
'site',
zsId,
'screenCap.png',
new Buffer(siteScreenCap, 'base64'),
{ContentType: 'image/png'},
(err, data) => {
if (err) console.error(err);
if (!err && data) {
let screenCap = `${data.url}?v=${new Date().valueOf()}`;
// push image url to all current users who can edit the site
_.delay(()=> {
app.io.in(`authSite-${zsId}`).emit(events.SCREEN_CAP_UPDATED, zsId, screenCap)
}, 3000);
// save image url to db
zlSite.findById(zsId, (err, site) => {
if (site) {
let zsInternalConfig = Object.assign(
{},
site.zsInternalConfig,
{ScreenCap: screenCap}
);
site.updateAttribute('zsInternalConfig', zsInternalConfig);
}
})
}
}
);
}
else {
console.error(`Error: ${siteScreenCap}`);
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q60976
|
curry
|
validation
|
function curry(fn) {
return function resolver() {
for (var _len = arguments.length, resolverArgs = Array(_len), _key = 0; _key < _len; _key++) {
resolverArgs[_key] = arguments[_key];
}
return function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var nextArgs = resolverArgs.concat(args.length ? args : null);
var next = nextArgs.length >= fn.length ? fn : resolver;
return next.apply(undefined, toConsumableArray(nextArgs));
};
}();
}
|
javascript
|
{
"resource": ""
}
|
q60977
|
resetLocalOrResetUTC
|
validation
|
function resetLocalOrResetUTC(increment, date, utc) {
var _incrementHandlers;
var incrementHandlers = (_incrementHandlers = {}, defineProperty(_incrementHandlers, SECOND, function (date) {
return new Date(date['set' + utc + 'Seconds'](date['get' + utc + 'Seconds'](), 0));
}), defineProperty(_incrementHandlers, MINUTE, function (date) {
return new Date(date['set' + utc + 'Minutes'](date['get' + utc + 'Minutes'](), 0, 0));
}), defineProperty(_incrementHandlers, HOUR, function (date) {
return new Date(date['set' + utc + 'Hours'](date['get' + utc + 'Hours'](), 0, 0, 0));
}), defineProperty(_incrementHandlers, DATE, function (date) {
date['set' + utc + 'Date'](date['get' + utc + 'Date']());
date['set' + utc + 'Hours'](0, 0, 0, 0);
return new Date(date);
}), defineProperty(_incrementHandlers, WEEK, function (date) {
date['set' + utc + 'Date'](date['get' + utc + 'Date']() - date['get' + utc + 'Day']());
date['set' + utc + 'Hours'](0, 0, 0, 0);
return new Date(date);
}), defineProperty(_incrementHandlers, MONTH, function (date) {
date['set' + utc + 'Month'](date['get' + utc + 'Month'](), 1);
date['set' + utc + 'Hours'](0, 0, 0, 0);
return new Date(date);
}), defineProperty(_incrementHandlers, YEAR, function (date) {
date['set' + utc + 'FullYear'](date['get' + utc + 'FullYear'](), 0, 1);
date['set' + utc + 'Hours'](0, 0, 0, 0);
return new Date(date);
}), _incrementHandlers);
return incrementHandlers[increment](date);
}
|
javascript
|
{
"resource": ""
}
|
q60978
|
getInheritTheme
|
validation
|
function getInheritTheme(theme, tree = {}) {
if (!app.locals.themes[theme]) {
// this theme is not installed
app.error('requested theme:%s but it is not installed', theme);
return tree;
}
// add the one been requested
tree[theme] = {};
// get inheritance
var config = app.locals.themes[theme].zealderConfig;
if (config && config.themeDependency && !tree[config.themeDependency]) {
tree = getInheritTheme(config.themeDependency, tree);
}
return tree;
}
|
javascript
|
{
"resource": ""
}
|
q60979
|
cache
|
validation
|
function cache(app) {
if (app.locals.config.cacheDb && 'redis' === app.locals.config.cacheDb.connector) {
// use redis for cache
let redis = require("redis").createClient(app.locals.config.cacheDb);
redis.on("error", function (err) {
app.error(err);
});
// clear existing cache on startup
redis.del('zlSites', 'themeTrees', 'themesConfig');
return {
// for getting data
get: function () {
if (3 == arguments.length) {
// hash request
redis.hget(arguments[0], arguments[1], arguments[2]);
}
else if (2 == arguments.length) {
// key request
redis.get(arguments[0], arguments[1]);
}
},
// for setting data
set: function () {
if (4 == arguments.length) {
// hash request
redis.hset(arguments[0], arguments[1], arguments[2], arguments[3]);
}
else if (3 == arguments.length) {
// key request
redis.set(arguments[0], arguments[1], arguments[2]);
}
},
// for setting volatile data with an expiration date
setvol: function () {
if (4 == arguments.length) {
// key request
redis.set(arguments[0], arguments[1], () => {
redis.expire(arguments[0], arguments[2], arguments[3]);
});
}
},
// for deleting data
del: function () {
if (3 == arguments.length) {
// hash request
redis.hdel(arguments[0], arguments[1], arguments[2]);
}
else if (2 == arguments.length) {
// key request
redis.del(arguments[0], arguments[1]);
}
}
}
}
else {
// not using cache
app.error('No config.cacheDb provided. This may affect performance.');
let e = function() { arguments[arguments.length-1](); }
return { get: e, set: e, setvol: e, del: e }
}
}
|
javascript
|
{
"resource": ""
}
|
q60980
|
validation
|
function () {
if (3 == arguments.length) {
// hash request
redis.hget(arguments[0], arguments[1], arguments[2]);
}
else if (2 == arguments.length) {
// key request
redis.get(arguments[0], arguments[1]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60981
|
validation
|
function () {
if (4 == arguments.length) {
// hash request
redis.hset(arguments[0], arguments[1], arguments[2], arguments[3]);
}
else if (3 == arguments.length) {
// key request
redis.set(arguments[0], arguments[1], arguments[2]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60982
|
validation
|
function () {
if (4 == arguments.length) {
// key request
redis.set(arguments[0], arguments[1], () => {
redis.expire(arguments[0], arguments[2], arguments[3]);
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60983
|
validation
|
function () {
if (3 == arguments.length) {
// hash request
redis.hdel(arguments[0], arguments[1], arguments[2]);
}
else if (2 == arguments.length) {
// key request
redis.del(arguments[0], arguments[1]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60984
|
bypass
|
validation
|
function bypass(req, conditions = {files: 1, api: 1}) {
if (conditions.files) {
// bypass all files request
let regexp = /\w+\.\w+$/i;
if (req.path.match(regexp)) {
return true;
}
}
if (conditions.api) {
// bypass api request
let regexp = /^\/api\//i;
if (req.path.match(regexp)) {
return true;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q60985
|
authCtx
|
validation
|
function authCtx(req, res) {
let ctx = {
accessToken: null,
remotingContext: { req: req, res: res }
}
// populate accessToken
if (req && req.accessToken) ctx.accessToken = req.accessToken;
return ctx;
}
|
javascript
|
{
"resource": ""
}
|
q60986
|
mailCommon
|
validation
|
function mailCommon(type, data, req, res) {
const { zlSite } = res.locals;
if ('form-notice' === type) {
if (data.text) {
data.text += `\nReferred By: ${req.cookies.referer}\n\n`+
`-----------------------------------------------------------`+
`\nThis message was triggered by a website user's request.\n`+
`From IP: ${req.ip}\nFrom Url: ${req.get('Referrer')}\n\n`+
`This message was sent from a ${process.env.ZEAL_NETWORK_NAME} powered `+
`Website. Login to your account to view more details.`
}
}
// make from name use site name (but auth email address so it will relay)
data.from = `"${zlSite.zsName}" ${process.env.ZEAL_NETWORK_EMAIL}`;
if (zlSite.zsInternalConfig && zlSite.zsInternalConfig.displayEmail) {
data.replyTo = `"${zlSite.zsName}" ${zlSite.zsInternalConfig.displayEmail}`;
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q60987
|
recaptchaVerify
|
validation
|
function recaptchaVerify(req, res, action = 'form_submit', cb, token = '', threshold = 0.3) {
const { zlSite } = res.locals;
if (zlSite.user) {
// signed in user don't need to verify
cb();
}
else {
if (!token && 'POST' === req.method) {
token = req.body.recaptcha;
}
if (!token) {
cb('Token is required.');
}
else {
request.post({
url: 'https://www.google.com/recaptcha/api/siteverify',
json: true,
form: {
secret: req.app.locals.reCAPTCHAsecret,
response: token,
remoteip: req.ip
}
}, function (error, response, body) {
if (error) {
req.app.error(error);
// no error of user fault so allow action
cb();
}
else if (body && body.success) {
if (body.hostname !== req.hostname) {
cb(`site: ${req.hostname} did not match recaptcha from ${body.hostname}`);
}
else if (body.score < threshold) cb('score below threshold');
else if (action !== body.action) {
cb(`action: ${action} did not match recaptcha action: ${body.action}`);
}
else cb();
}
else cb('unknown error occurred');
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q60988
|
copyFileFrom
|
validation
|
function copyFileFrom(file, to_dir){
var sys = require("sys");
var fs = require('fs');
var file_name = filenameFromPath(file);
if (file_name == ".DS_Store") {
return;
}
sys.pump(fs.createReadStream(file), fs.createWriteStream(to_dir),function(){
console.log("Copied file: " + file);
console.log("To new destination: " + to_dir + "\n");
});
}
|
javascript
|
{
"resource": ""
}
|
q60989
|
realDestinationPath
|
validation
|
function realDestinationPath(file, from_dir, to_dir)
{
var length = from_dir.length;
var from_dir_path = file.substring(length, file.length);
return to_dir + from_dir_path;
}
|
javascript
|
{
"resource": ""
}
|
q60990
|
removeFileAtPath
|
validation
|
function removeFileAtPath(file, to_dir){
var fs = require('fs');
var file_name = filenameFromPath(file);
var file_at_dest_dir = to_dir + file_name;
fs.unlink(file_at_dest_dir);
console.log("Removed file at directory: " + file_at_dest_dir);
}
|
javascript
|
{
"resource": ""
}
|
q60991
|
base
|
validation
|
function base(args, ctor) {
var plain = false;
// class instance constructor
function clas() {
// we can't simply use a plain new clas() here
// since we might get called unbound from a child class
// or as a constructor
// therefore we must use the correct 'this' in that case
if (this !== global) {
plain ? (plain = false) : ctor.apply(this, arguments);
return this;
} else {
// Case of missing new keyword, a bit hackish but still
// better than adding another prototype layer
return (plain = true) && clas.apply(new clas(), arguments);
}
}
// closures copies of the base properties
var properties = {};
// constructor for sub classes e.g. Foo.init(barInstance, ...);
clas.init = bind(ctor);
// extend method of this class, needed to get access to the 'properties'
// object of other classes
clas.extend = function(obj) {
if (is('Function', obj)) {
// Extend the class that wants to inherit
if (obj.hasOwnProperty('extend')) {
return obj.extend(properties);
}
} else {
for(var i in obj) {
if (obj.hasOwnProperty(i)) {
extend(clas, properties, obj, i);
}
}
}
return clas;
};
// Extend and inherit
var i = is('Function', ctor) && ctor.hasOwnProperty('init') ? 0 : 1;
for(var l = args.length; i < l; i++) {
if (is('Object', args[i])) {
clas.extend(args[i]);
} else {
// We're inheriting, so we need access to the other class's
// 'properties' object, therefore, call that class which then
// calls the extend method of this class and passes its
// 'properties' object
args[i].extend(clas);
}
}
return clas;
}
|
javascript
|
{
"resource": ""
}
|
q60992
|
clas
|
validation
|
function clas() {
// we can't simply use a plain new clas() here
// since we might get called unbound from a child class
// or as a constructor
// therefore we must use the correct 'this' in that case
if (this !== global) {
plain ? (plain = false) : ctor.apply(this, arguments);
return this;
} else {
// Case of missing new keyword, a bit hackish but still
// better than adding another prototype layer
return (plain = true) && clas.apply(new clas(), arguments);
}
}
|
javascript
|
{
"resource": ""
}
|
q60993
|
sizeIt
|
validation
|
function sizeIt(gridSize, sizeEle, sizeScreen = 'xs') {
// determine outer size
let outerSize = _getOuterSize(gridSize, sizeScreen);
// subtract outer from this size
let size = sizeEle * grid/outerSize;
if (size > grid) size = grid;
else if (size < 1) size = 1;
return Math.round(size);
}
|
javascript
|
{
"resource": ""
}
|
q60994
|
_getOuterSize
|
validation
|
function _getOuterSize(gridSize, sizeScreen) {
if ('lg' === sizeScreen) {
if (gridSize && gridSize.lg) {
return gridSize.lg;
}
else if (gridSize && gridSize.md) {
return gridSize.md;
}
else if (gridSize && gridSize.sm) {
return gridSize.sm;
}
else if (gridSize && gridSize.xs) {
return gridSize.xs;
}
}
else if ('md' === sizeScreen) {
if (gridSize && gridSize.md) {
return gridSize.md;
}
else if (gridSize && gridSize.sm) {
return gridSize.sm;
}
else if (gridSize && gridSize.xs) {
return gridSize.xs;
}
}
else if ('sm' === sizeScreen) {
if (gridSize && gridSize.sm) {
return gridSize.sm;
}
else if (gridSize && gridSize.xs) {
return gridSize.xs;
}
}
else if ('xs' === sizeScreen) {
if (gridSize && gridSize.xs) {
return gridSize.xs;
}
}
// default
return grid;
}
|
javascript
|
{
"resource": ""
}
|
q60995
|
RecursiveConcat
|
validation
|
function RecursiveConcat(options) {
this.concat = null;
this.currentCountDirectories = 0;
this.currentCountFiles = 0;
this.currentFolder = null;
this.newFileGenerated = null;
this.newFinalFile = "";
this.options = options;
this.walkCounter=0;
this.stream = new Transform({objectMode: true});
this.stream._transform = function(chunk, encoding, callback){
var fullPath = null,
file = {},
relative = chunk.relative;
file.base = chunk.base;
file.contents = chunk.contents;
file.extname = Path.extname(relative);
file.basename = Path.basename(relative, file.extname);
file.dirname = Path.dirname(relative);
file.newDirname = utils.fixDirName(file.dirname);
fullPath = file.newDirname + file.basename + file.extname;
file.path = Path.join(chunk.base, fullPath);
if (!file.relative) {
file.relative = relative;
}
callback(null, self.walk(file));
};
var self = this;
return this.stream;
}
|
javascript
|
{
"resource": ""
}
|
q60996
|
check_role_authorization
|
validation
|
function check_role_authorization(req, res, next) {
if (!req.hasOwnProperty("user") || !req.user.hasOwnProperty('authorized_roles') ||
!(req.user.authorized_roles instanceof Array) || req.user.authorized_roles.length === 0){
running_debug("Unhautorized: Invalid role or path not configured");
var err = new Error("Unhautorized: Invalid role or path not configured");
err.status = 401;
return next(err);
}
running_debug("Authorized roles: " + req.user.authorized_roles);
return next();
}
|
javascript
|
{
"resource": ""
}
|
q60997
|
InSicht
|
validation
|
function InSicht() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, InSicht);
this.options = Object.assign({}, defaults, options);
this.init();
}
|
javascript
|
{
"resource": ""
}
|
q60998
|
userFromToken
|
validation
|
function userFromToken(req, cb) {
const { accessToken } = req;
app.models.zlUser.findById(accessToken.userId, (err, usr) => {
if (!err && usr) {
cb(null, usr);
}
else cb(err);
});
}
|
javascript
|
{
"resource": ""
}
|
q60999
|
render
|
validation
|
function render(rawCode, idPre) {
var codeArr = {};
// get js that is a src ref
// TODO: need to check for `async` OR `defer` prop
var re = /<script[^>]* src\s*=\s*'*"*([^'"]+)[^>]*>.*<\/script>/gi;
var HeaderCode = re.exec(rawCode);
if (HeaderCode) {
_.forEach(HeaderCode, function(code, key) {
if (0 === key) return;
codeArr[`${idPre}-src-${key}`] = code;
});
}
// get js that is code
re = /<script[^>]*>([^]+)<\/script>/gi;
HeaderCode = re.exec(rawCode);
if (HeaderCode) {
_.forEach(HeaderCode, function(code, key) {
if (0 === key) return;
codeArr[`${idPre}-js-${key}`] = {code: code};
});
}
return codeArr;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.