_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q36500 | flock | train | function flock(boids) {
const averageVelocity = velocity.clone();
const averagePosition = Vec2.get();
let inSightCount = 0;
for (let i = 0; i < boids.length; i++) {
const b = boids[i];
if (b !== boid && inSight(b)) {
averageVelocity.add(b.velocity);
averagePosition.add(b.position);
if (position.distanceSq(b.position) < minDistanceSq) {
flee(b.position);
}
inSightCount++;
}
}
if (inSightCount > 0) {
averageVelocity.divideBy(inSightCount);
averagePosition.divideBy(inSightCount);
seek(averagePosition);
steeringForce.add(averageVelocity.subtract(velocity));
}
averageVelocity.dispose();
averagePosition.dispose();
return boid;
} | javascript | {
"resource": ""
} |
q36501 | getEntityNameKeyMap | train | function getEntityNameKeyMap(structure) {
const result = {};
for (const kk in structure) {
const vv = structure[kk];
if (typeof vv === 'string') {
if (types.isMap(vv)) {
const info = types.getTypeInfo(vv);
const entityName = info.entity;
if (_entityNameType[entityName]) throw new Error(`Duplicate entity ${entityName}`);
_entityNameType[entityName] = vv;
result[entityName] = kk;
delete structure[kk];
}
}
}
return result;
} | javascript | {
"resource": ""
} |
q36502 | wrapProcess | train | function wrapProcess (tmpIn, tmpOut, processProvider) {
return createStream(tmpIn, tmpOut, function (input, output, callback) {
var _this = this
var process = processProvider.call(this, tmpIn, tmpOut)
process.on('error', function (error) {
callback(error)
})
if (!tmpIn) {
input.pipe(process.stdin).on('error', function (error) {
if (error.code === 'ECONNRESET' && error.syscall === 'read') {
// This can happen if the process closes stdin before all data has been read
// e.g. in ps.spawn("exiftool", ["-s3", "-MimeType", "-fast","-"]);
// This is not necessarily an error, since the output is still valid
_this.emit('input-closed', error)
} else if (error.code === 'EPIPE' && error.syscall === 'write') {
// This also can happen if the process closes stdin before all data has been read
// e.g. in ps.spawn("head", ["-2"]);
// This is not necessarily an error, since the output is still valid
_this.emit('input-closed', error)
} else {
// This "emit" causes test cases to fail
// it is most likely a followup-error of an error that is already
// emitted
// _this.emit("error", error);
}
})
}
if (!tmpOut) {
process.stdout.pipe(output)
}
process.on('exit', function (code, signal) {
_this.emit('exit', code, signal)
callback(null)
})
})
} | javascript | {
"resource": ""
} |
q36503 | parseString | train | function parseString (string, tmpIn, tmpOut) {
var resultIn = null
var resultOut = null
var resultString = string.replace(placeHolderRegex, function (match) {
switch (match) {
case IN:
resultIn = resultIn || tmpIn
return resultIn
case OUT:
resultOut = resultOut || tmpOut
return resultOut
/* istanbul ignore next */
default:
throw new Error("Found '" + match + "'. Placeholder regex not consistent: " + JSON.stringify({
IN: IN,
OUT: OUT,
match: match
}))
}
})
return {
in: resultIn,
out: resultOut,
string: resultString
}
} | javascript | {
"resource": ""
} |
q36504 | cleanJoin | train | function cleanJoin(req) {
if(!isAbsoluteURL(req.url) && req.baseURL) {
const parsedBase = url.parse(req.baseURL, true);
const parsed = url.parse(req.url, true);
return {
protocol: parsedBase.protocol,
host: parsedBase.hostname,
port: parsedBase.port,
path: URLJoin(parsedBase.pathname, parsed.pathname),
query: mergeObjects(req._query, parsedBase.query, parsed.query)
};
} else {
const parsed = url.parse(req.url, true);
return {
protocol: parsed.protocol,
host: parsed.hostname,
port: parsed.port,
path: parsed.pathname,
query: mergeObjects(req._query, parsed.query)
};
}
} | javascript | {
"resource": ""
} |
q36505 | load | train | function load () {
const str = fs.readFileSync(settingsFile, 'utf8')
if (str) {
const settings = JSON.parse(str)
this.settings = settings.livereload
this.paths = getPaths(settings)
.map(p => path.normalize(this.root + '/' + p))
.map(p => makeGlob(p))
}
} | javascript | {
"resource": ""
} |
q36506 | init | train | function init (root, storage) {
// calling path
const calling = path.dirname(getCallingScript())
// root path
root = !root || root === '.' || root === './'
? root = calling
: path.isAbsolute(root)
? root
: path.normalize(calling + root)
sketchpad.root = root.replace(/\/*$/, '/')
// settings path
const settingsFolder = path.normalize(sketchpad.root + (storage || 'storage') + '/sketchpad/')
settingsFile = settingsFolder + 'settings.json'
// check for settings
if (!fs.existsSync(settingsFolder)) {
return error('Folder "' +settingsFolder+ '" not found')
}
if (!fs.existsSync(settingsFile)) {
return error('File "settings.json" not found in "' +settingsFolder+ '"')
}
// load settings
sketchpad.load()
return this
} | javascript | {
"resource": ""
} |
q36507 | getOwnNameFallBack | train | function getOwnNameFallBack(names, dest) {
if (!names[dest]) return dest
else return names[dest][dest] || dest
} | javascript | {
"resource": ""
} |
q36508 | train | function (tag, text, index) {
var re = wp.shortcode.regexp(tag)
var match
var result
re.lastIndex = index || 0
match = re.exec(text)
if (!match) {
return
}
// If we matched an escaped shortcode, try again.
if (match[1] === '[' && match[7] === ']') {
return wp.shortcode.next(tag, text, re.lastIndex)
}
result = {
index: match.index,
content: match[0],
shortcode: wp.shortcode.fromMatch(match)
}
// If we matched a leading `[`, strip it from the match
// and increment the index accordingly.
if (match[1]) {
result.content = result.content.slice(1)
result.index++
}
// If we matched a trailing `]`, strip it from the match.
if (match[7]) {
result.content = result.content.slice(0, -1)
}
return result
} | javascript | {
"resource": ""
} | |
q36509 | train | function (match) {
var type
if (match[4]) {
type = 'self-closing'
} else if (match[6]) {
type = 'closed'
} else {
type = 'single'
}
return new Shortcode({
tag: match[2],
attrs: match[3],
type: type,
content: match[5]
})
} | javascript | {
"resource": ""
} | |
q36510 | train | function () {
var text = '[' + this.tag
_.each(this.attrs.numeric, function (value) {
if (/\s/.test(value)) {
text += ' "' + value + '"'
} else {
text += ' ' + value
}
})
_.each(this.attrs.named, function (value, name) {
text += ' ' + name + '="' + value + '"'
})
// If the tag is marked as `single` or `self-closing`, close the
// tag and ignore any additional content.
if (this.type === 'single') {
return text + ']'
} else if (this.type === 'self-closing') {
return text + ' /]'
}
// Complete the opening tag.
text += ']'
if (this.content) {
text += this.content
}
// Add the closing tag.
return text + '[/' + this.tag + ']'
} | javascript | {
"resource": ""
} | |
q36511 | checkArguments | train | function checkArguments (argz) {
if (!argz.args.length) {
return error('first argument cant be function')
}
if (isEmptyFunction(argz.cb.toString())) {
return error('should have `callback` (non empty callback)')
}
if (typeOf(argz.args[0]) !== 'string') {
return type('expect `cmd` be string', argz.cb)
}
if (typeOf(argz.args[1]) === 'object') {
argz.args[2] = argz.args[1]
argz.args[1] = []
}
if (typeOf(argz.args[2]) !== 'object') {
argz.args[2] = {}
}
return {
cmd: argz.args[0],
args: argz.args[1],
opts: argz.args[2],
callback: argz.cb
}
} | javascript | {
"resource": ""
} |
q36512 | buildSpawn | train | function buildSpawn (cmd, args, opts, callback) {
var proc = spawn(cmd, args, opts)
var buffer = new Buffer('')
var cmdError = {}
cmd = cmd + ' ' + args.join(' ')
if (proc.stdout) {
proc.stdout.on('data', function indexOnData (data) {
buffer = Buffer.concat([buffer, data])
})
}
proc
.on('error', function spawnOnError (err) {
cmdError = new CommandError({
command: cmd,
message: err.message ? err.message : undefined,
stack: err.stack ? err.stack : undefined,
buffer: buffer ? buffer : undefined,
status: err.status ? err.status : 1
})
})
.on('close', function spawnOnClose (code) {
if (code === 0) {
callback(null, buffer.toString().trim(), code, buffer)
return
}
cmdError = new CommandError({
command: cmd,
message: cmdError.message ? cmdError.message : undefined,
stack: cmdError.stack ? cmdError.stack : undefined,
buffer: cmdError.buffer ? cmdError.buffer : buffer,
status: cmdError.status ? cmdError.status : code
})
callback(cmdError, undefined, code, undefined)
})
return proc
} | javascript | {
"resource": ""
} |
q36513 | CommandError | train | function CommandError (err) {
this.name = 'CommandError'
this.command = err.command
this.message = err.message
this.stack = err.stack
this.buffer = err.buffer
this.status = err.status
Error.captureStackTrace(this, CommandError)
} | javascript | {
"resource": ""
} |
q36514 | router | train | function router(req, resp, next) {
const routerPath = req.routePath || '';
const beforeRunMiddleware = (route) => {
const match = matchRoute(routerPath, req, route);
if (!match) return false;
const { params, path: matchPath } = match;
if (options.params) req.params = { ...options.params, ...params };
else req.params = params;
// dynamically set req.routePath for the route
req.routePath = routerPath + matchPath;
return true;
};
const routeStack = compose(router.routes, { beforeRunMiddleware });
return routeStack.call(this, req, resp, () => {
req.routePath = routerPath;// restore routePath
return next && next();
});
} | javascript | {
"resource": ""
} |
q36515 | eventPromise | train | function eventPromise (emitter, eventName) {
return new Promise((resolve, reject) => {
emitter.on(eventName, (...args) => {
return resolve(args)
})
})
} | javascript | {
"resource": ""
} |
q36516 | status | train | function status() {
var tasks = [],
cwd = process.cwd();
findRepos(function(err, repos) {
if (err) return console.log(err);
repos.forEach(function(repo) {
tasks.push(function(done) {
repo.status(function(err, status) {
if (err) return done(err);
if (argv.b) {
repo.branch(function(err, head) {
if (err) return done(err);
done(null, {status: status, head: head});
});
}
else {
done(null, {status: status});
}
});
});
});
async.series(tasks, function(err, results) {
if (err) return console.log(err);
var row,
col,
res,
file,
head = [],
table,
symbol;
head.push('Repo');
if (argv.b) {
head.push('Branch');
}
head.push('Status');
table = new Table({
head: head,
style: {
compact: true,
'padding-left': 1,
'padding-right': 1,
head: ['white', 'bold']
}
});
results.forEach(function(res) {
var row = [];
row.push(res.status.repo.path.replace(cwd + '/', ''));
if (argv.b) {
row.push(res.head.name);
}
row.push(res.status.clean ? 'Clean'.green : 'Changed'.red);
table.push(row);
if (argv.v) {
for (var name in res.status.files) {
row = [];
row.push('');
if (argv.b) {
row.push('');
}
switch (res.status.files[name].type) {
case 'A':
symbol = '+'.green; break;
case 'D':
symbol = '-'.red; break;
case 'M':
symbol = '*'.yellow; break;
default:
symbol = '~'.grey; break;
}
row.push(' ' + symbol + ' ' + name);
table.push(row);
}
}
});
console.log(table.toString());
});
});
} | javascript | {
"resource": ""
} |
q36517 | pull | train | function pull() {
var tasks = [],
cwd = process.cwd();
findRepos(function(err, repos) {
if (err) return console.log(err);
repos.forEach(function(repo) {
tasks.push(function(done) {
repo.status(function(err, status) {
var name = status.repo.path.replace(cwd + '/', '');
if (!status.clean) {
console.log('Skipped '.red + name.bold + ' (not clean)'.grey);
done();
}
else {
console.log('Pulling '.green + name.bold);
process.chdir(status.repo.path);
exec('git fetch', function(err, stdout, stderr) {
if (err) return done(stderr);
if (stdout && argv.v) console.log(indent(stdout));
exec('git rebase', function(err, stdout, stderr) {
if (err) return done(stderr);
if (stdout && argv.v) console.log(indent(stdout));
done(null);
});
});
}
});
});
});
async.series(tasks, function(err, results) {
if (err) {
console.log('Error:'.red);
console.log(err);
}
else {
console.log('Done!');
}
});
});
} | javascript | {
"resource": ""
} |
q36518 | indent | train | function indent(str, prefix) {
prefix = prefix || ' ';
var lines = str.split("\n");
lines.forEach(function(line, i) {
lines[i] = prefix + line;
});
return lines.join("\n");
} | javascript | {
"resource": ""
} |
q36519 | findRepos | train | function findRepos(callback) {
var cwd = process.cwd(),
tasks = [];
fs.readdir(cwd, function(err, files) {
if (err) return callback(err);
var repos = [];
files.forEach(function(file) {
if (fs.existsSync(path.join(cwd, file, '.git'))) {
repos.push(path.join(cwd, file));
}
});
if (repos.length === 0) {
return callback(new Error('No repositories found'));
}
repos.forEach(function(dir) {
tasks.push(function(done) {
done(err, git(dir));
});
});
async.series(tasks, function(err, results) {
callback(err, results);
});
});
} | javascript | {
"resource": ""
} |
q36520 | Iterator | train | function Iterator(iterator) {
if (Array.isArray(iterator) || typeof iterator == "string")
return Iterator.iterate(iterator);
iterator = Object(iterator);
if (!(this instanceof Iterator))
return new Iterator(iterator);
this.next = this.send =
iterator.send || iterator.next || iterator;
if (
Object.prototype.toString.call(this.next) !=
"[object Function]"
)
throw new TypeError();
} | javascript | {
"resource": ""
} |
q36521 | traverse | train | function traverse(_promise){
var c = _promise._chain,
s = _promise._state,
v = _promise._value,
o = _promise._opaque,
t, p, h, r;
while((t = c.shift())){
p = t[0];
h = t[s];
if(typeof h === 'function') {
try {
r = h(v,o);
p.resolve(r,o);
} catch(e) {
p.reject(e);
}
} else {
p._promise._state = s;
p._promise._value = v;
p._promise._opaque = o;
task(traverse,[p._promise]);
}
}
} | javascript | {
"resource": ""
} |
q36522 | cart | train | function cart(xs, ys)
{
// nothing on the left
if(!xs || xs.length === 0)
return ys.map(function(y){
return [[],y]
});
// nothing on the right
if(!ys || ys.length === 0)
return xs.map(function(x){
return [x,[]]
});
return Combinatorics.cartesianProduct(x, y).toArray();
} | javascript | {
"resource": ""
} |
q36523 | train | function(obj, iterator, context) {
if (!obj) return
else if (obj.forEach) obj.forEach(iterator)
else if (obj.length == +obj.length) {
for (var i = 0; i < obj.length; i++) iterator.call(context, obj[i], i)
} else {
for (var key in obj) iterator.call(context, obj[key], key)
}
} | javascript | {
"resource": ""
} | |
q36524 | train | function(context, handlers/*, params*/ ) {
var args = this.slice(arguments)
args.shift()
args.shift()
this.each(handlers, function(handler) {
if (handler) handler.apply(context, args)
})
} | javascript | {
"resource": ""
} | |
q36525 | train | function(array) {
// return Array.prototype.slice.call(array)
var i = array.length
var a = new Array(i)
while(i) {
i --
a[i] = array[i]
}
return a
} | javascript | {
"resource": ""
} | |
q36526 | train | function(obj, extObj) {
this.each(extObj, function(value, key) {
if (extObj.hasOwnProperty(key)) obj[key] = value
})
return obj
} | javascript | {
"resource": ""
} | |
q36527 | train | function (f, proto) {
function Ctor() {}
Ctor.prototype = proto
f.prototype = new Ctor()
f.prototype.constructor = Ctor
return f
} | javascript | {
"resource": ""
} | |
q36528 | inspect | train | function inspect(callback) {
return function (filename) {
var chunks = [];
function transform(chunk, encoding, done) {
/* jshint validthis:true */
chunks.push(chunk);
this.push(chunk);
done();
}
function flush(done) {
callback(filename, chunks.join(''), done);
if (callback.length < 3) {
done();
}
}
return through(transform, flush);
}
} | javascript | {
"resource": ""
} |
q36529 | getKeyColumn | train | function getKeyColumn(propDesc, keyPropContainer) {
if (propDesc.keyColumn)
return propDesc.keyColumn;
const keyPropDesc = keyPropContainer.getPropertyDesc(
propDesc.keyPropertyName);
return keyPropDesc.column;
} | javascript | {
"resource": ""
} |
q36530 | makeSelector | train | function makeSelector(sql, markup) {
return {
sql: (sql instanceof Translatable ? sql.translate.bind(sql) : sql),
markup: markup
};
} | javascript | {
"resource": ""
} |
q36531 | makeOrderElement | train | function makeOrderElement(sql) {
return {
sql: (sql instanceof Translatable ? sql.translate.bind(sql) : sql)
};
} | javascript | {
"resource": ""
} |
q36532 | buildQueryTree | train | function buildQueryTree(
dbDriver, recordTypes, propsTree, anchorNode, clauses, singleAxis) {
// get and validate top records specification data
const recordTypeDesc = recordTypes.getRecordTypeDesc(
propsTree.desc.refTarget);
const topIdPropName = recordTypeDesc.idPropertyName;
const topIdColumn = recordTypeDesc.getPropertyDesc(topIdPropName).column;
// create top query tree node
const topNode = (
anchorNode ?
anchorNode.createChildNode(
propsTree, recordTypeDesc.table, topIdColumn,
false, false,
topIdColumn, topIdColumn) :
new QueryTreeNode(
dbDriver, recordTypes, new Map(), new Map(), new Map(),
singleAxis, propsTree, true, recordTypeDesc.table, 'z',
topIdColumn)
);
topNode.rootPropNode = propsTree;
// add top record id property to have it in front of the select list
const idPropSql = topNode.tableAlias + '.' + topIdColumn;
topNode.addSelect(makeSelector(idPropSql, topIdPropName));
topNode.addPropSql(topIdPropName, idPropSql);
topNode.addPropValueColumn(
topIdPropName, topNode.table, topNode.tableAlias, topIdColumn);
// add the rest of selected properties
if (propsTree.hasChildren()) {
const topMarkupCtx = {
prefix: '',
nextChildMarkupDisc: 'a'.charCodeAt(0)
};
for (let p of propsTree.children)
if (!p.desc.isId()) // already included
topNode.addProperty(p, clauses, topMarkupCtx);
}
// return the query tree
return topNode;
} | javascript | {
"resource": ""
} |
q36533 | long | train | function long(nodes, context, recur, wrap) {
context.write(WRAPPERS[wrap].left);
for (var i = 0; i < nodes.length; i++) {
recur(nodes[i]);
if (nodes[i + 1]) {
context.write(', ');}}
context.write(WRAPPERS[wrap].right);} | javascript | {
"resource": ""
} |
q36534 | short | train | function short(nodes, context, recur, wrap) {
context.write(WRAPPERS[wrap].left);
context.indentIn();
context.write('\n');
for (var i = 0; i < nodes.length; i++) {
context.write(context.getIndent());
recur(nodes[i]);
if (nodes[i + 1]) {
context.write(',\n');}}
context.indentOut();
context.write('\n', context.getIndent(), WRAPPERS[wrap].right);} | javascript | {
"resource": ""
} |
q36535 | MultiserverWorker | train | function MultiserverWorker(servers, func_name, callback, options) {
var that = this;
options = options || {};
Multiserver.call(this, servers, function(server, index) {
return new gearman.Worker(func_name, function(payload, worker) {
that._debug('received job from', that._serverString(index));
return callback(payload, worker);
}, {
host: server.host,
port: server.port,
debug: options.debug || false
});
}, Multiserver.component_prefix(options.component_name) + 'worker');
} | javascript | {
"resource": ""
} |
q36536 | exec | train | function exec() {
var actions = {
commands: {
init: { action: _init },
gen: { action: _gen },
watch: { action: _watch },
drift: { action: _watch },
clean: { action: _clean }
}
};
bag.command(__dirname, actions);
} | javascript | {
"resource": ""
} |
q36537 | pluck | train | function pluck(data) {
//
// Either map as array or return object through single map.
//
if (Array.isArray(data)) return data.map(map);
return map(data);
/**
* Recursive mapping function.
*
* @param {Object} d Collection, Model or plain object.
* @returns {Object} plucked object
* @api private
*/
function map(d) {
if (isModel(d)) return pluck(d.attributes);
for (var key in d) {
if (isCollection(d[key])) {
d[key] = pluck(d[key].models);
}
if (isModel(d[key])) {
//
// Delete MongoDB ObjectIDs. The stored state of the model is ambigious
// as the referenced model could have different values in its own
// collection. Hence doing recursive storage should be limited as much
// as possible, since duplicate data will be stored.
//
d[key] = pluck(d[key].attributes);
delete d[key]._id;
}
}
return d;
}
} | javascript | {
"resource": ""
} |
q36538 | map | train | function map(d) {
if (isModel(d)) return pluck(d.attributes);
for (var key in d) {
if (isCollection(d[key])) {
d[key] = pluck(d[key].models);
}
if (isModel(d[key])) {
//
// Delete MongoDB ObjectIDs. The stored state of the model is ambigious
// as the referenced model could have different values in its own
// collection. Hence doing recursive storage should be limited as much
// as possible, since duplicate data will be stored.
//
d[key] = pluck(d[key].attributes);
delete d[key]._id;
}
}
return d;
} | javascript | {
"resource": ""
} |
q36539 | persist | train | function persist(client, next) {
var single = isModel(item)
, data;
switch (method) {
case 'create':
data = single ? [ item.clone() ] : item.clone().models;
client.insert(pluck(data), config, function inserted(error, results) {
if (error) return next(error);
//
// Set the _stored property for each model to true.
//
results.forEach(function each(model) {
if (single) return item.stored = model._id;
item.id(model._id).stored = model._id;
});
next(null, results);
});
break;
case 'read':
//
// Models will be read by Model _id if no query was passed or if
// the Model already exists in the database. This would otherwise
// result in data ambiguity.
//
query = query || {};
if (single && item.id) query._id = item.id;
//
// No query and Model has no ObjectId reference, return early.
//
if (single && !Object.keys(query).length) return next(null, null);
//
// Read the documents from the MongoDB database and process
// the results, depending on the item being a Model or Collection.
//
client.find(query, config).toArray(function found(error, results) {
if (error) return next(error);
if (single) results = results[0];
//
// If the item is a model, parse first. After merge the results
// of the read operation in the current item.
//
if (single && options.parse) results = item.parse(results, options);
item.set(results);
next(null, results);
});
break;
case 'update':
case 'patch':
data = single ? [ item ] : item.models;
async.reduce(data, 0, function loopModels(memo, model, fn) {
model = model.clone();
var update = { $set: pluck(model) };
if (config.upsert) update = pluck(model);
client.update({ _id: model.id }, update, config, function updated(error, results) {
if (error) return next(error);
model.stored = model.id;
fn(null, memo + results);
});
}, next);
break;
case 'delete':
data = single ? [ item ] : item.models;
async.reduce(data, 0, function loopModels(memo, model, fn) {
client.remove({ _id: model.id }, config, function updated(error, results) {
if (error) return fn(error);
//
// Update the stored state properties to false.
//
model.stored = false;
fn(null, memo + results);
});
}, next);
break;
}
} | javascript | {
"resource": ""
} |
q36540 | after | train | function after(results, next) {
item.trigger('after:' + method, function done(error) {
next(error, results);
});
} | javascript | {
"resource": ""
} |
q36541 | createRecord | train | function createRecord(fvs, options) {
options || (options = {});
const model = this;
const row = {};
if (fvs) {
for (const kk in fvs) {
row[kk] = fvs[kk];
}
}
const r = constructRecord(model, row, Object.keys(model.def.fields), true);
getDefaultOnCreate(r, null, options.createdBy);
return r;
} | javascript | {
"resource": ""
} |
q36542 | readDirSync | train | function readDirSync (dir, allFiles = []) {
const files = fs.readdirSync(dir).map(f => join(dir, f))
allFiles.push(...files)
files.forEach(f => {
fs.statSync(f).isDirectory() && readDirSync(f, allFiles)
})
return allFiles
} | javascript | {
"resource": ""
} |
q36543 | getData | train | function getData (allFiles = [], config) {
const files = allFiles.reduce((memo, iteratee) => {
const filePath = path.parse(iteratee)
if (config.include.includes(filePath.ext) && !config.exclude.includes(filePath.base)) {
const newFile = {
file: iteratee.replace(config.content, ''),
dir: filePath.dir.replace(config.content, ''),
name: filePath.name,
base: filePath.base,
ext: filePath.ext,
}
if (filePath.ext === '.md') {
const file = fs.readFileSync(iteratee, { encoding: 'utf8' })
const frontMatter = fm(file)
newFile.attr = frontMatter.attributes
newFile.body = frontMatter.body
} else if (filePath.ext === '.png') {
const image = new PNG.load(iteratee)
newFile.width = image.width
newFile.height = image.height
}
memo.push(newFile)
}
return memo
}, [])
return files
} | javascript | {
"resource": ""
} |
q36544 | translate | train | function translate (content, contentTypes) {
let output = {}
content.forEach(each => {
const base = path.parse(each.file).base
if (base === 'index.md') {
const type = each.dir.split('/').pop()
const contentTypeTranslation = contentTypes.find(contentType => contentType[type])
if (contentTypeTranslation && contentTypeTranslation[type]) {
output[type] = contentTypeTranslation[type](content, type)
}
}
})
return output
} | javascript | {
"resource": ""
} |
q36545 | write | train | function write (filename, content) {
const json = JSON.stringify(content, (key, value) => value === undefined ? null : value)
fs.writeFileSync(filename, json)
return json
} | javascript | {
"resource": ""
} |
q36546 | parse | train | function parse(html, script, filePath){
var m, index = 0;//the index in the html string
while(m = reDelim.exec(html)) {
addLiteral(script, html.slice(index, m.index));//string
addCode(script, m, filePath);
index = m.index + m[0].length;
}
addLiteral(script, html.slice(index));
script.push('\n}return __r.join("");');
script = script.join('');
return script;
} | javascript | {
"resource": ""
} |
q36547 | addLiteral | train | function addLiteral(script, str){
if(!str) return;
str = str.replace(/\\|'/g, '\\$&');// escape '
var m, index = 0;
while(m = reNewline.exec(str)){
var nl = m[0];
var es = nl==='\r\n'? '\\r\\n':'\\n';
script.push("__p('" + str.slice(index, m.index) + es + "');\n");
index = m.index + nl.length;
}
var last = str.slice(index);
if(last) script.push("__p('" + last + "');");
} | javascript | {
"resource": ""
} |
q36548 | addCode | train | function addCode(script, match, filePath) {
var leftDeli = match[1], code = match[2];
if(leftDeli==='<@' || leftDeli==='<!--@='){
script.push('__p(escape(' + code + '));');
}
else if(leftDeli==='<@|' || leftDeli==='<!--@|'){//no escape
script.push('__p(' + code + ');');
}
else{//<!--@ -->
script.push(code);
//possible single-line comment check
var lastLine = code.split('\n').slice(-1)[0];
if(lastLine.indexOf('//')>=0){
/*eslint-disable no-console*/
if(!filePath) console.warn('detect a possible single-line comment: %s', lastLine);
else console.warn('detect a possible single-line comment in file %s: %s', filePath, lastLine);
/*eslint-enable no-console*/
}
if(code.slice(-1)!==';') script.push(';');
}
} | javascript | {
"resource": ""
} |
q36549 | defaultName | train | function defaultName (folder, data) {
if (data.name) return data.name
return path.basename(folder).replace(/^node[_-]?|[-\.]?js$/g, '')
} | javascript | {
"resource": ""
} |
q36550 | DriverOperationError | train | function DriverOperationError(code,description) {
this.code = code;
this.description = description;
console.log('in DriverOperationError',code,description);
} | javascript | {
"resource": ""
} |
q36551 | train | function(me, deviceType, connectionType) {
if (!self.hasOpenAll) {
throw new DriverInterfaceError(
'openAll is not loaded. Use ListAll and Open functions instead.'
);
}
if (deviceType === undefined || connectionType === undefined) {
throw 'Insufficient parameters for OpenAll - DeviceType and ConnectionType required';
}
me.numOpened = new ref.alloc('int', 0);
me.aHandles = new Buffer(ARCH_INT_NUM_BYTES * LJM_LIST_ALL_SIZE);
me.aHandles.fill(0);
me.numErrors = new ref.alloc('int', 0);
me.errorHandle = new ref.alloc('int', 0);
me.errors = new Buffer(ARCH_POINTER_SIZE);
me.errors.fill(0);
me.devType = driver_const.deviceTypes[deviceType];
me.deviceType = deviceType;
me.connType = driver_const.connectionTypes[connectionType];
me.connectionType = connectionType;
} | javascript | {
"resource": ""
} | |
q36552 | done | train | function done() {
// get the next route from the stack
route = stack.pop()
var callback
// if the stack is not empty yet, i.e., if this is not
// the last route part, the callback standard callback is provided
if (stack.length) {
callback = done
}
// otherwise a slightly modified callback is provided
else {
callback = function() {
done.end()
}
callback.redirect = done.redirect
callback.render = function() {
res.render.apply(res, [req.app._currentRoute].concat(Array.prototype.slice.call(arguments), finalize))
}
}
// exectue the route part
route.execute(req.app, req, res, callback)
} | javascript | {
"resource": ""
} |
q36553 | Ejector | train | function Ejector(conf) {
component.Component.call(this, 'ejector', conf);
var that = this;
this._dbconn = conf.dbconn;
this.registerGearman(conf.servers, {
worker: {
func_name: 'delayedJobDone',
func: function(payload, worker) {
var task = JSON.parse(payload.toString());
that._info('Received a task with id:', task.id);
that.eject(task, worker);
}
}
});
} | javascript | {
"resource": ""
} |
q36554 | getRandomItem | train | function getRandomItem(list) {
if (!list)
return null;
if (list.length === 0)
return list[0];
const randomIndex = random(1, list.length) - 1;
return list[randomIndex];
} | javascript | {
"resource": ""
} |
q36555 | _loadRecursive | train | function _loadRecursive(container, map, accum = {}) {
return Bluebird.reduce(Object.keys(map), (memo, key) => {
const path = map[key];
if (typeof path === 'string') {
return container._load(path)
.then((mod) => {
set(memo, key, mod);
return memo;
});
}
return _loadRecursive(container, path)
.then((mods) => {
set(memo, key, mods);
return memo;
});
}, accum);
} | javascript | {
"resource": ""
} |
q36556 | _recursiveDeps | train | function _recursiveDeps(graph, name, deps) {
return Object.keys(deps).forEach((key) => {
const dep = deps[key];
if (PLUGIN.test(dep)) {
return;
}
if (typeof dep === 'string') {
if (!graph.hasNode(dep)) {
graph.addNode(dep);
}
graph.addDependency(name, dep);
} else if (typeof dep === 'object') {
_recursiveDeps(graph, name, deps[key]);
}
});
} | javascript | {
"resource": ""
} |
q36557 | profile | train | function profile(excludeRegex) {
var categories = [];
return {
forCategory: forCategory,
toArray : toArray,
toString : toString
};
function toArray() {
return categories;
}
function toString() {
return categories
.map(String)
.filter(Boolean)
.join('\n');
}
/**
* Create a category for analysis.
* @param {string} [label] Optional category label
* @param {{forCategory:function, start:function, stop:function, report:function, toString:function}} A new instance
*/
function forCategory(label) {
var eventsByFilename = {},
isUsed = false,
self = {
forCategory: forCategory,
start : start,
stop : stop,
report : report,
toString : toString
};
label = label || ('category-' + String.fromCharCode(65 + categories.length));
categories.push(self);
return self;
/**
* Start a segment delineated by the given key.
* @param {string} key A key to delineate a segment
* @returns {function} A transform that causes a start event when the file is completed streaming
*/
function start(key) {
return createEventTransform(key);
}
/**
* Stop the currently delineated segment.
* @returns {function} A transform that causes a stop event when the file is completed streaming
*/
function stop() {
return createEventTransform(null);
}
/**
* Create a transform that pushes time-stamped events data to the current filename.
* @param {*} data The event data
* @returns {function} A browserify transform that captures events on file contents complete
*/
function createEventTransform(data) {
return inspect(onComplete);
function onComplete(filename) {
isUsed = true;
var now = Date.now();
var events = eventsByFilename[filename] = eventsByFilename[filename] || [];
events.push(now, data);
}
}
/**
* Create a json report of time verses key verses filename.
*/
function report() {
return Object.keys(eventsByFilename)
.filter(testIncluded)
.reduce(reduceFilenames, {});
function testIncluded(filename) {
return !excludeRegex || !excludeRegex.test(filename);
}
function reduceFilenames(reduced, filename) {
var totalsByKey = {},
list = eventsByFilename[filename],
lastKey = null,
lastTime = NaN;
// events consist of time,key pairs
for (var i = 0; i < list.length; i += 2) {
var time = list[i],
key = list[i + 1];
if (lastKey) {
var initial = totalsByKey[key] || 0,
delta = ((time - lastTime) / 1000) || 0;
totalsByKey[lastKey] = initial + delta;
}
lastKey = key;
lastTime = time;
}
// total at the end to guarantee consistency
var total = 0;
for (var key in totalsByKey) {
total += totalsByKey[key];
}
totalsByKey.total = total;
// store by the short filename
var short = path.relative(process.cwd(), filename);
reduced[short] = totalsByKey;
return reduced;
}
}
/**
* A string representation of the report, sorted by longest time.
*/
function toString() {
var json = report(),
filenames = Object.keys(json),
longestFilename = filenames.reduce(reduceFilenamesToLength, 0),
columnOrder = orderColumns(),
headerRow = [label].concat(columnOrder).map(leftJustify).join(' '),
delimiter = (new Array(headerRow.length + 1)).join('-');
if (isUsed) {
return [delimiter, headerRow, delimiter]
.concat(rows())
.concat(delimiter)
.filter(Boolean)
.join('\n');
} else {
return '';
}
/**
* Establish the column names, in order, left justified (for the maximum length).
*/
function orderColumns() {
var keyTotals = filenames.reduce(reduceFilenamesToKeyTotal, {});
return sort(keyTotals);
function reduceFilenamesToKeyTotal(reduced, filename) {
var item = json[filename];
return Object.keys(item)
.reduce(reducePropToLength.bind(item), reduced);
}
}
/**
* Map each filename to a data row, in decreasing time order.
*/
function rows() {
var fileTotals = filenames.reduce(reducePropToLength.bind(json), {}),
fileOrder = sort(fileTotals);
return fileOrder.map(rowForFile);
function rowForFile(filename) {
var data = json[filename];
// console.log(JSON.stringify(data, null, 2));
return [filename]
.concat(columnOrder
.map(dataForColumn)
.map(formatFloat))
.map(leftJustify)
.join(' ');
function dataForColumn(column) {
return data[column];
}
function formatFloat(number) {
var padding = '000',
warning = ((number > 99) ? '>' : ' '),
integer = (padding + Math.min(99, Math.floor(number))).slice(-2),
fraction = (padding + Math.round(1000 * number)).slice(-3);
return warning + integer + '.' + fraction;
}
}
}
function reduceFilenamesToLength(reduced, filename) {
return Math.max(filename.length, reduced);
}
function leftJustify(name, i) {
var length = i ? Math.max(7, columnOrder[i - 1].length) : longestFilename;
var padding = (new Array(length + 1)).join(' ');
return (name + padding).slice(0, length);
}
function reducePropToLength(reduced, key) {
var value = (typeof this[key] === 'object') ? this[key].total : this[key];
reduced[key] = (reduced[key] || 0) + value;
return reduced;
}
function sort(object) {
return Object.keys(object)
.reduce(createObjects.bind(object), [])
.sort(sortTimeDescending)
.map(getColumnName);
function createObjects(reduced, field) {
reduced.push({
name: field,
time: Math.round(this[field] * 1000) / 1000 // millisecond precision
});
return reduced;
}
function sortTimeDescending(a, b) {
return b.time - a.time;
}
function getColumnName(object) {
return object.name;
}
}
}
}
} | javascript | {
"resource": ""
} |
q36558 | createEventTransform | train | function createEventTransform(data) {
return inspect(onComplete);
function onComplete(filename) {
isUsed = true;
var now = Date.now();
var events = eventsByFilename[filename] = eventsByFilename[filename] || [];
events.push(now, data);
}
} | javascript | {
"resource": ""
} |
q36559 | report | train | function report() {
return Object.keys(eventsByFilename)
.filter(testIncluded)
.reduce(reduceFilenames, {});
function testIncluded(filename) {
return !excludeRegex || !excludeRegex.test(filename);
}
function reduceFilenames(reduced, filename) {
var totalsByKey = {},
list = eventsByFilename[filename],
lastKey = null,
lastTime = NaN;
// events consist of time,key pairs
for (var i = 0; i < list.length; i += 2) {
var time = list[i],
key = list[i + 1];
if (lastKey) {
var initial = totalsByKey[key] || 0,
delta = ((time - lastTime) / 1000) || 0;
totalsByKey[lastKey] = initial + delta;
}
lastKey = key;
lastTime = time;
}
// total at the end to guarantee consistency
var total = 0;
for (var key in totalsByKey) {
total += totalsByKey[key];
}
totalsByKey.total = total;
// store by the short filename
var short = path.relative(process.cwd(), filename);
reduced[short] = totalsByKey;
return reduced;
}
} | javascript | {
"resource": ""
} |
q36560 | rows | train | function rows() {
var fileTotals = filenames.reduce(reducePropToLength.bind(json), {}),
fileOrder = sort(fileTotals);
return fileOrder.map(rowForFile);
function rowForFile(filename) {
var data = json[filename];
// console.log(JSON.stringify(data, null, 2));
return [filename]
.concat(columnOrder
.map(dataForColumn)
.map(formatFloat))
.map(leftJustify)
.join(' ');
function dataForColumn(column) {
return data[column];
}
function formatFloat(number) {
var padding = '000',
warning = ((number > 99) ? '>' : ' '),
integer = (padding + Math.min(99, Math.floor(number))).slice(-2),
fraction = (padding + Math.round(1000 * number)).slice(-3);
return warning + integer + '.' + fraction;
}
}
} | javascript | {
"resource": ""
} |
q36561 | train | function (data) {
// Add property to hold internal values
Object.defineProperty(this, '_', {
enumerable: false,
configurable: false,
writable: false,
value: {
dt: this._clone(data),
ev: {},
df: {},
sp: false,
ct: 0
}
});
// Assign keys
for (var key in this._.dt) {
this._addProperty(key);
}
} | javascript | {
"resource": ""
} | |
q36562 | Application | train | function Application (configDir, appConfigFileName) {
/**
* The DXL client to use for communication with the fabric.
* @private
* @type {external.DxlClient}
* @name Application#_dxlClient
*/
this._dxlClient = null
/**
* The directory containing the application configuration files.
* @private
* @type {String}
* @name Application#_configDir
*/
this._configDir = configDir
/**
* Full path to the file used to configure the DXL client.
* @private
* @type {String}
* @name Application#_dxlClientConfigPath
*/
this._dxlClientConfigPath = path.join(configDir, DXL_CLIENT_CONFIG_FILE)
/**
* Full path to the application-specifie configuration file.
* @private
* @type {String}
* @name Application#_appConfigPath
*/
this._appConfigPath = path.join(configDir, appConfigFileName)
/**
* Whether or not the application is currently running.
* @private
* @type {boolean}
* @name Application#_running
*/
this._running = false
/**
* Loads the configuration settings from the application-specific
* configuration file
* @private
*/
this._loadConfiguration = function () {
var configData
try {
configData = fs.readFileSync(this._appConfigPath, 'utf-8')
} catch (err) {
throw new Error('Unable to read configuration file: ' + err.message)
}
var parsedConfig
try {
parsedConfig = ini.parse(configData)
} catch (err) {
throw new Error('Unable to parse config file: ' + err.message)
}
this.onLoadConfiguration(parsedConfig)
}
/**
* Attempts to connect to the DXL fabric.
* @private
* @param {Function} [callback=null] - Callback function which should be
* invoked after the client has been connected.
*/
this._dxlConnect = function (callback) {
var that = this
var config = Config.createDxlConfigFromFile(this._dxlClientConfigPath)
this._dxlClient = new Client(config)
this._dxlClient.connect(function () {
that.onRegisterEventHandlers()
that.onRegisterServices()
that.onDxlConnect()
if (callback) {
callback()
}
})
}
} | javascript | {
"resource": ""
} |
q36563 | transform | train | function transform(filepath, options) {
// Normalize options
options = extend({
match: /bower_components.*\.html$/
}, options || {})
if(!(options.match instanceof RegExp)) {
options.match = RegExp.apply(null, Array.isArray(options.match) ? options.match : [options.match])
}
// Shim polymer.js
if(/polymer\/polymer\.js$/.test(filepath)) {
return fixpolymer();
}
// Transform only source that vulcanize can handle
if(!options.match.test(filepath) || !/\.html$/.test(filepath)) {
return through();
}
// Bufferize and polymerize
var src = '';
return through(
function(chunk) { src += chunk.toString() },
function() {
this.queue(polymerize(src, filepath, options))
this.queue(null)
}
);
} | javascript | {
"resource": ""
} |
q36564 | include | train | function include(partial, cb) {
cb((params.partials && params.partials[partial]) ?
params.partials[partial] :
'[error] partial ' + partial + ' does not exist');
} | javascript | {
"resource": ""
} |
q36565 | title | train | function title(cb) {
cb((params.sitemap && params.sitemap[page]) ?
params.sitemap[page].title :
'[error] page ' + page + ' does not have any sitemap title');
} | javascript | {
"resource": ""
} |
q36566 | train | function (value, encoding) {
encoding = (typeof encoding === 'undefined') ? 'utf8' : encoding
if (Buffer.isBuffer(value)) {
value = value.toString(encoding)
}
return value
} | javascript | {
"resource": ""
} | |
q36567 | train | function (message, encoding) {
return module.exports.jsonToObject(
module.exports.decodePayload(message, encoding))
} | javascript | {
"resource": ""
} | |
q36568 | train | function (value, encoding) {
encoding = (typeof encoding === 'undefined') ? 'utf8' : encoding
var returnValue = value
if (!Buffer.isBuffer(returnValue)) {
if (value === null) {
returnValue = ''
} else if (typeof value === 'object') {
returnValue = module.exports.objectToJson(value)
} else if (typeof value !== 'string') {
returnValue = '' + value
}
returnValue = Buffer.from(returnValue, encoding)
}
return returnValue
} | javascript | {
"resource": ""
} | |
q36569 | train | function (message, value, encoding) {
message.payload = module.exports.encode(value, encoding)
} | javascript | {
"resource": ""
} | |
q36570 | train | function (obj, prettyPrint) {
return prettyPrint ? JSON.stringify(obj,
Object.keys(findUniqueKeys(
obj, {}, [])).sort(), 4) : JSON.stringify(obj)
} | javascript | {
"resource": ""
} | |
q36571 | plugin | train | function plugin(derby) {
// Wrap createBackend in order to be able to listen to derby-ar RPC calls
// But only do it once (e.g. if we have many apps, we need to ensure we only wrap it once since otherwise we'll destroy the wrapping)
if(derby.__createBackend) return;
derby.__createBackend = derby.createBackend;
derby.createBackend = function () {
// Create backend using regular createBackend method
var backend = this.__createBackend.apply(this, arguments);
backend.rpc.on('derby-ar', function (data, cb) {
var path = data.path;
var method = data.method;
var args = data.args || [];
var model = backend.createModel();
var $scoped = model.scope(data.path);
args.push(cb);
$scoped[method].apply($scoped, args);
});
return backend;
};
} | javascript | {
"resource": ""
} |
q36572 | removeModuleAlias | train | function removeModuleAlias(moduleName, folder, replacement = './') {
return __awaiter(this, void 0, void 0, function* () {
fs.readdirSync(folder).forEach(child => {
if (fs.statSync(folder + '/' + child).isDirectory()) {
removeModuleAlias(moduleName, folder + '/' + child, './.' + replacement);
}
else {
fs.writeFileSync(folder + '/' + child, fs
.readFileSync(folder + '/' + child, 'utf8')
.split(`require("${moduleName}/`)
.join(`require("${replacement}`)
.split(`require("./../`)
.join(`require("../`)
.split(`require('${moduleName}/`)
.join(`require('${replacement}`)
.split(`require('./../`)
.join(`require('../`)
.split(`from '${moduleName}/`)
.join(`from '${replacement}`)
.split(`from './../`)
.join(`from '../`)
.split(`module":"${moduleName}/`)
.join(`module":"${replacement}`)
.split(`module":"./../`)
.join(`module":"../`));
}
});
return Promise.resolve();
});
} | javascript | {
"resource": ""
} |
q36573 | packageFilter | train | function packageFilter(pkg, root) {
pkg.main = pkg.glslify || (
path.extname(pkg.main || '') !== '.js' &&
pkg.main
) || 'index.glsl'
return pkg
} | javascript | {
"resource": ""
} |
q36574 | train | function (obj) {
var fns = {},
i;
for (i in obj) {
fns[i] = hogan.compile( obj[i] );
}
return fns;
} | javascript | {
"resource": ""
} | |
q36575 | diffObjects | train | function diffObjects(container, pathPrefix, objOld, objNew, patchSpec) {
// keep track of processed properties
const unrecognizedPropNames = new Set(Object.keys(objNew));
// diff main properties
diffObjectProps(
container, pathPrefix,
objOld, objNew,
unrecognizedPropNames, patchSpec);
// check if polymorphic object and check the subtype properties
if (container.isPolymorphObject()) {
// type property is recognized
unrecognizedPropNames.delete(container.typePropertyName);
// match the subtype
const subtype = objOld[container.typePropertyName];
if (objNew[container.typePropertyName] !== subtype)
throw new common.X2SyntaxError(
'Polymorphic object type does not match.');
// go over the subtype properties
const subtypeDesc = container.getPropertyDesc(subtype);
diffObjectProps(
subtypeDesc.nestedProperties, `${pathPrefix}${subtype}:`,
objOld, objNew,
unrecognizedPropNames, patchSpec);
}
// any unrecognized properties?
if (unrecognizedPropNames.size > 0)
throw new common.X2SyntaxError(
`Unrecognized properties for ${container.recordTypeName}` +
` at ${pathPrefix}:` + Array.from(unrecognizedPropNames).join(', '));
} | javascript | {
"resource": ""
} |
q36576 | diffMaps | train | function diffMaps(propDesc, propPath, mapOld, mapNew, patchSpec) {
const objects = (propDesc.scalarValueType === 'object');
const keysToRemove = new Set(Object.keys(mapOld));
for (let key of Object.keys(mapNew)) {
const valOld = mapOld[key];
const valNew = mapNew[key];
if ((valNew === undefined) || (valNew === null)) {
if ((valOld === undefined) || (valOld === null))
keysToRemove.delete(key);
continue;
}
keysToRemove.delete(key);
if ((valOld === undefined) || (valOld === null)) {
patchSpec.push({
op: 'add',
path: `${propPath}/${ptrSafe(key)}`,
value: valNew
});
} else if (objects) {
diffObjects(
propDesc.nestedProperties,
`${propPath}/${ptrSafe(key)}/`,
valOld, valNew, patchSpec);
} else if (valNew !== valOld) {
patchSpec.push({
op: 'replace',
path: `${propPath}/${ptrSafe(key)}`,
value: valNew
});
}
}
for (let key of keysToRemove)
patchSpec.push({
op: 'remove',
path: `${propPath}/${ptrSafe(key)}`
});
} | javascript | {
"resource": ""
} |
q36577 | deserializeValue | train | function deserializeValue(value) {
var num
try {
return value ?
value == 'true' || value == true ||
(value == 'false' || value == false ? false :
value == 'null' ? null :
!/^0/.test(value) && !isNaN(num = Number(value)) ? num :
/^[\[\{]/.test(value) ? JSON.parse(value) :
value)
: value
} catch (e) {
return value
}
} | javascript | {
"resource": ""
} |
q36578 | remove | train | function remove(item, list) {
var i = list.indexOf(item);
if (~i) list.splice(i, 1);
} | javascript | {
"resource": ""
} |
q36579 | train | function(element, options)
{
// Make sure the transform property is an object
if(typeof element.transform != "object")
{
element.transform = {};
}
// If we have an object of options
if(typeof options[0] == "object")
{
// Loop through object properties and save their values
var keys = Object.keys(options[0]);
keys.forEach(function(property)
{
element.transform[property] = options[0][property];
});
}
// Otherwise, loop through all of the options to find values
else
{
var property = options[0];
var args = [];
for(var i = 1, l = options.length; i < l; i++)
{
args.push(options[i]);
}
element.transform[property] = args;
}
} | javascript | {
"resource": ""
} | |
q36580 | train | function(element)
{
// Loop through all saved transform functions to generate the style text
var funcs = Object.keys(element.transform);
var style = [];
funcs.forEach(function(func)
{
var args = element.transform[func];
// If we have an array of arguments, join them with commas
if(Array.isArray(args))
{
args = args.join(', ');
}
style.push(func + "("+args+") ");
});
// Update the element
element.style['transform'] = style.join(" ");
element.style['-webkit-transform'] = style.join(" ");
} | javascript | {
"resource": ""
} | |
q36581 | findModulePath | train | function findModulePath(filename_rootfile, filename, options = DEFAULT_OPTIONS) {
/**
* . 相对路径
* . 绝对路径
*/
const ext = path.extname(filename);
if (ext && exports.extensions.indexOf(ext) === -1) {
return null;
}
if (path.dirname(filename_rootfile) !== filename_rootfile) {
filename_rootfile = path.dirname(filename_rootfile);
}
const storeKey = storePathKey(filename_rootfile, filename);
const storeKeyVal = store.get(storeKey);
const { baseUrl = DEFAULT_OPTIONS.baseUrl } = options;
if (storeKeyVal) {
return storeKeyVal === "null" ? null : storeKeyVal;
}
// save result path and return pathname
const storeAndReturn = (rpath) => {
store.set(storeKey, String(rpath));
return rpath;
};
const roots = baseUrl.concat(filename_rootfile);
let r = null;
roots.some(baseRoot => {
if (ext) {
const namepath = genPath(baseRoot, filename);
r = namepath;
return !!namepath;
}
let namepath2 = null;
exports.extensions.some(extname => {
namepath2 = genPath(baseRoot, `${filename}${extname}`);
if (!namepath2) {
namepath2 = genPath(baseRoot, `${filename}/index${extname}`);
}
return !!namepath2;
});
if (namepath2) {
r = namepath2;
return true;
}
return false;
});
return storeAndReturn(r);
} | javascript | {
"resource": ""
} |
q36582 | MultiserverClient | train | function MultiserverClient(servers, options) {
options = options || {};
Multiserver.call(this, servers, function(server) {
return new gearman.Client({
host: server.host,
port: server.port,
debug: options.debug || false
});
}, Multiserver.component_prefix(options.component_name) + 'client');
this._rr_index = -1; // round robin index
} | javascript | {
"resource": ""
} |
q36583 | dump | train | function dump(gcore, coredump) {
gcore = gcore || 'gcore';
coredump = coredump || `${process.cwd()}/core.${process.pid}`;
return DumpProcess.dumpProcess(gcore, coredump);
} | javascript | {
"resource": ""
} |
q36584 | installMutations | train | function installMutations(modules, enclosingFolder) {
makeFolderLibraryIfNotExist(enclosingFolder);
if (modules.length === 0) {
return new Promise(resolve => resolve({}));
}
return npm.install(modules, {
cwd: pathToMutations(enclosingFolder),
save: true
});
} | javascript | {
"resource": ""
} |
q36585 | loadMutations | train | function loadMutations(enclosingFolder) {
const here = jetpack.cwd(pathToMutations(enclosingFolder));
const pkg = here.read(PACKAGE_JSON, "json");
errorIf(
!pkg,
`There doesn't seem to be a package.json file.
Did you create one at the enclosing folder?
FYI: installMutations creates one for you if you don't have one. `
);
const node_modules_path = here.dir(NODE_MODULES).cwd();
return new Promise((resolve, reject) => {
// Load in mutations from dependencies
const mutations = loadMutationsFromDependencies(
pkg.dependencies,
node_modules_path
);
resolve(mutations);
});
} | javascript | {
"resource": ""
} |
q36586 | next | train | function next() {
var fns = activeQueue.shift();
if ( !fns ) {
return;
}
ret = ret.then(
typeof fns[0] === 'function' ? fns[0].bind(self) : fns[0],
typeof fns[1] === 'function' ? fns[1].bind(self) : fns[1]
);
next();
} | javascript | {
"resource": ""
} |
q36587 | isInstalled | train | function isInstalled(dep) {
if (_.has(exceptions, dep)) return exceptions[dep];
return installedDeps.has(dep);
} | javascript | {
"resource": ""
} |
q36588 | resolveDependencyPlugins | train | function resolveDependencyPlugins(deps) {
return deps
.filter(dep => isInstalled(dep) && isInstalled(`eslint-plugin-${dep}`))
.map(dep => `./lib/plugin-conf/${dep}.js`);
} | javascript | {
"resource": ""
} |
q36589 | mutate | train | function mutate(Component, title, api = {}) {
class Mutated extends React.Component {
constructor(props, context) {
super(props);
this.ToRender = Component;
const mutations = context.mutations;
if (!mutations || !mutations[title]) {
return;
}
// Convert old style mutations to new style mutations
if (!Array.isArray(mutations[title])) {
mutations[title] = [mutations[title]];
}
// Apply all mutations to the component
for (let mut of mutations[title]) {
this.ToRender = mut(this.ToRender, api);
}
}
render() {
const ToRender = this.ToRender;
return <ToRender {...this.props} />;
}
}
Mutated.contextTypes = {
mutations: PropTypes.object
};
return Mutated;
} | javascript | {
"resource": ""
} |
q36590 | run | train | function run(collector, commands, keys, params, options, callback)
{
// either keys is array or commands
var prefix, key, cmd = (keys || commands).shift();
// done here
if (!cmd)
{
return callback(null, collector);
}
// transform object into a command
if (keys)
{
key = cmd;
cmd = commands[key];
}
// update placeholders
cmd = parse(cmd, params);
// if loop over parameters terminated early
// do not proceed further
if (!cmd)
{
callback(new Error('Parameters should be a primitive value.'));
return;
}
// populate command prefix
prefix = parse(options.cmdPrefix || '', params);
if (prefix)
{
cmd = prefix + ' ' + cmd;
}
execute(collector, cmd, options, function(error, output)
{
// store the output, if present
if (output)
{
collector.push((key ? key + ': ' : '') + output);
}
// do not proceed further if error
if (error)
{
// do not pass collector back if it a regular error
callback(error, error.terminated ? collector : undefined);
return;
}
// rinse, repeat
run(collector, commands, keys, params, options, callback);
});
} | javascript | {
"resource": ""
} |
q36591 | constructor | train | function constructor(attributes, options) {
var hooks = []
, local = {};
options = options || {};
//
// Set the database name and/or urlRoot if provided in the options.
//
if (options.database) this.database = options.database;
if (options.urlRoot) this.urlRoot = options.urlRoot;
//
// Copy attributes to a new object and provide a MongoDB OfbjectID.
//
attributes = attributes || {};
for (var key in attributes) local[key] = attributes[key];
//
// If the provided `_id` is an ObjectID assume the model is stored.
// If it is not an ObjectID, remove it from the provided data.
// MongoDB will provide an ObjectID by default.
//
if ('_id' in local) try {
local._id = new ObjectID(local._id);
} catch (error) { delete local._id; }
//
// Define restricted non-enumerated properties.
//
predefine(this, fossa);
//
// Check for presence of before/after hooks and setup.
//
if (this.before) hooks.push('before');
if (this.after) hooks.push('after');
this.setup(hooks);
//
// Call original Backbone Model constructor.
//
backbone.Model.call(this, local, options);
} | javascript | {
"resource": ""
} |
q36592 | save | train | function save() {
var defer = new Defer
, xhr = backbone.Model.prototype.save.apply(this, arguments);
if (xhr) return xhr;
defer.next(new Error('Could not validate model'));
return defer;
} | javascript | {
"resource": ""
} |
q36593 | train | function(namespacedEvent, callback) {
var event, namespace, _ref;
_ref = namespacedEvent.split("."), event = _ref[0], namespace = _ref[1];
if (namespace) {
callback.__PIXIE || (callback.__PIXIE = {});
callback.__PIXIE[namespace] = true;
}
eventCallbacks[event] || (eventCallbacks[event] = []);
eventCallbacks[event].push(callback);
return this;
} | javascript | {
"resource": ""
} | |
q36594 | train | function(namespacedEvent, callback) {
var callbacks, event, key, namespace, _ref;
_ref = namespacedEvent.split("."), event = _ref[0], namespace = _ref[1];
if (event) {
eventCallbacks[event] || (eventCallbacks[event] = []);
if (namespace) {
eventCallbacks[event] = eventCallbacks.select(function(callback) {
var _ref2;
return !(((_ref2 = callback.__PIXIE) != null ? _ref2[namespace] : void 0) != null);
});
} else {
if (callback) {
eventCallbacks[event].remove(callback);
} else {
eventCallbacks[event] = [];
}
}
} else if (namespace) {
for (key in eventCallbacks) {
callbacks = eventCallbacks[key];
eventCallbacks[key] = callbacks.select(function(callback) {
var _ref2;
return !(((_ref2 = callback.__PIXIE) != null ? _ref2[namespace] : void 0) != null);
});
}
}
return this;
} | javascript | {
"resource": ""
} | |
q36595 | train | function() {
var callbacks, event, parameters;
event = arguments[0], parameters = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
callbacks = eventCallbacks[event];
if (callbacks && callbacks.length) {
self = this;
return callbacks.each(function(callback) {
return callback.apply(self, parameters);
});
}
} | javascript | {
"resource": ""
} | |
q36596 | train | function() {
var attrNames;
attrNames = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return attrNames.each(function(attrName) {
return self[attrName] = function() {
return I[attrName];
};
});
} | javascript | {
"resource": ""
} | |
q36597 | train | function() {
var Module, key, moduleName, modules, value, _i, _len;
modules = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
for (_i = 0, _len = modules.length; _i < _len; _i++) {
Module = modules[_i];
if (typeof Module.isString === "function" ? Module.isString() : void 0) {
moduleName = Module;
Module = Module.constantize();
} else if (moduleName = Module._name) {} else {
for (key in root) {
value = root[key];
if (value === Module) Module._name = moduleName = key;
}
}
if (moduleName) {
if (!I.includedModules.include(moduleName)) {
I.includedModules.push(moduleName);
self.extend(Module(I, self));
}
} else {
warn("Unable to discover name for module: ", Module, "\nSerialization issues may occur.");
self.extend(Module(I, self));
}
}
return self;
} | javascript | {
"resource": ""
} | |
q36598 | train | function (route, options) {
var opts = options || {};
opts.dest = opts.dest || './docs';
opts.destname = opts.destname || false;
route = route || './*.js';
mkdirp( opts.dest, function (err) {
if (err) {
console.error(err);
} else {
// options is optional
glob( route, function (err, files) {
var f;
if (err) {
throw err;
}
for (f in files) {
renderFile( files[f], opts );
}
});
}
});
} | javascript | {
"resource": ""
} | |
q36599 | hash | train | function hash(input, algo, type){
// string or buffer input ? => keep it
if (typeof input !== 'string' && !(input instanceof Buffer)){
input = JSON.stringify(input);
}
// create hash algo
var sum = _crypto.createHash(algo);
// set content
sum.update(input);
// binary output ?
if (type && type.toLowerCase().trim() == 'binary'){
// calculate hashsum
return sum.digest();
// base 64 urlsafe ?
}else if (type==='base64-urlsafe'){
return base64urlsafe(sum.digest('base64'));
// string output
}else{
// calculate hashsum
return sum.digest(type);
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.