_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q38800 | train | function() {
var self = this;
var children = self._children;
var prev = self.state.childrenLoadingStatus;
var isLoading = false;
for (var k in children) {
if (children[k]) {
isLoading = true;
break;
}
}
if (prev === isLoading) return;
self.setState({childrenLoadingStatus: isLoading});
} | javascript | {
"resource": ""
} | |
q38801 | train | function(isLoaded) {
var self = this;
var isLoading = !isLoaded;
var state = self.state;
var prev = state.loadingStatus;
isLoading = isLoading || false;
state.loadingStatus = isLoading;
self._notifyParentLoadingStatus(prev, !self.isLoaded());
} | javascript | {
"resource": ""
} | |
q38802 | createScheduleStatusUpdate | train | function createScheduleStatusUpdate() {
var isChanging = false;
var shouldUpdate = false;
function update(self, fn) {
raf(function() {
if (self.isMounted()) fn();
isChanging = false;
if (shouldUpdate) update(self, fn);
shouldUpdate = false;
});
}
return function _scheduleStatusUpdate(fn) {
if (isChanging) return shouldUpdate = true;
var self = this;
isChanging = true;
update(self, fn || self._updateChildrenLoadingStatus);
};
} | javascript | {
"resource": ""
} |
q38803 | train | function(chunk){
if(printOutput){
if (chunk.indexOf(options.matchString) !== -1) {
child_process.stdout.removeListener('data', detachIfStarted);
printOutput = false;
done();
}
}
} | javascript | {
"resource": ""
} | |
q38804 | getClassIndex | train | function getClassIndex(element, className) {
assertType(element, Node, false, 'Invalid element specified');
assertType(className, 'string', false, `Invalid class name: ${className}`);
let classList = element.className.split(' ');
return classList.indexOf(className);
} | javascript | {
"resource": ""
} |
q38805 | registerModuleEventListener | train | function registerModuleEventListener (name, module, meta) {
if (name !== 'globalEvent') {
module['addEventListener'] = function (evt, callbackId, options) {
return addEventListener.call(this, name, evt, callbackId, options)
}
module['removeAllEventListeners'] = function (evt) {
return removeAllEventListeners.call(this, name, evt)
}
; [{
name: 'addEventListener',
args: ['string', 'function', 'object']
}, {
name: 'removeAllEventListeners',
args: ['string']
}].forEach(info => meta[name].push(info))
}
} | javascript | {
"resource": ""
} |
q38806 | declaration | train | function declaration(obj) {
const
{error, value} = joi.validate(obj, declarationSchema);
if (error) {
throw new TypeError(`Invalid declaration object: ${error.message}`);
}
return value;
} | javascript | {
"resource": ""
} |
q38807 | getname | train | function getname(req, res) {
res.send(null, req.conn.client.name);
} | javascript | {
"resource": ""
} |
q38808 | setname | train | function setname(req, res) {
req.conn.client.name = req.args[0];
res.send(null, Constants.OK);
} | javascript | {
"resource": ""
} |
q38809 | list | train | function list(req, res) {
var s = '';
this.state.connections.forEach(function(conn) {
s += conn.toString();
})
res.send(null, s);
} | javascript | {
"resource": ""
} |
q38810 | pause | train | function pause(req, res) {
res.send(null, Constants.OK);
this.state.pause(req.args[0]);
} | javascript | {
"resource": ""
} |
q38811 | kill | train | function kill(req, res) {
// TODO: implement filters
var conn;
// single ip:port
if(req.args.length === 1) {
conn = req.args[0];
// shouldn't get here, however there is a possible
// race condition whereby the target connection quits
// between validate and execute
if(!conn) return res.send(null, null);
// suicide
if(conn.id === req.conn.id) {
conn.write(Constants.OK, function onWrite() {
conn.close();
})
// killing another connection
}else{
//console.dir('closing another connection...');
conn.close(function onClose() {
res.send(null, Constants.OK);
})
}
}
} | javascript | {
"resource": ""
} |
q38812 | validate | train | function validate(cmd, args, info) {
AbstractCommand.prototype.validate.apply(this, arguments);
var sub = info.command.sub
, cmd = ('' + sub.cmd)
, args = sub.args
, timeout
, conn;
if(cmd === Constants.SUBCOMMAND.client.pause.name) {
timeout = parseInt('' + args[0]);
// redis returns: 'timeout is' ...
// but we are not creating another error just yet!
if(isNaN(timeout)) {
throw IntegerRange;
}
args[0] = timeout;
}else if(cmd === Constants.SUBCOMMAND.client.kill.name) {
// kill by ip:port
if(args.length === 1) {
conn = this.state.getByAddr('' + args[0]);
if(!conn) {
throw NoSuchClient;
}
//console.dir('found kill connection');
args[0] = conn;
}
}else if(cmd === Constants.SUBCOMMAND.client.setname.name) {
// redis appears to allow every thing but whitespace
if(/\s+/.test(args[0])) {
throw ClientName;
}
}
} | javascript | {
"resource": ""
} |
q38813 | checkInbox | train | function checkInbox(uri, cert) {
console.log('checking inbox for:', uri, cert)
shell.ls([null, null, uri, cert], function(err, ret) {
if (err) {
console.error(err)
} else {
console.log(ret)
}
})
} | javascript | {
"resource": ""
} |
q38814 | MongooseStore | train | function MongooseStore(session, mongooseModel) {
var
self = this;
if(!session || !session.Store) {
throw 'express-session was not passed in constructor.';
}
if(!mongooseModel || !mongooseModel.findById) {
throw 'Mongoose Model was not passed in constructor.';
}
var Store = session.Store;
/**
* MongooseStore session store constructor
*/
function MStore(config) {
var
me = this,
// define our options for this store instance
opts = _.extend({}, defaults, config),
// default (un)serializer using JSON
serializer = JSON.stringify,
unserializer = JSON.parse;
// call superclass method
Store.call(me, opts);
var
defExpireTime = opts.defaultExpirationTime,
propSid = opts.propertySessionId,
propData = opts.propertyData,
propLastActive = opts.propertyLastActivity;
// creates/updates a query to search for a certain property
function _applyProp(property, value, obj) {
obj = obj || {};
obj[property] = value;
return obj;
}
// checks a session document's expiration date to see if it's still valid
function _checkExpiration(session) {
return !session[propLastActive] || new Date < (session[propLastActive].getTime() + defExpireTime);
}
_.extend(me, {
// get session data by session id:
get: function (sid, callback) {
var cb = callback || _.noop;
// ensureIndex is already called on start-up
mongooseModel.findOne(_applyProp(propSid, sid), function(err, doc) {
if(err || !doc) { // exit immediately
cb(err, null);
return;
}
if(_checkExpiration(doc) && doc[propData] !== undefined) { // we're still valid:
cb(null, unserializer(doc[propData]));
}
else { // needs clean-up
me.destroy(sid, cb);
}
});
},
// set session data by session id:
set: function (sid, session, callback) {
var rec = {};
// apply our properties:
_applyProp(propSid, sid, rec);
_applyProp(propData, serializer(session), rec);
// opportunity to do:
_applyProp(propLastActive, new Date(), rec);
mongooseModel.findOneAndUpdate(_applyProp(propSid, sid), rec, {upsert: true}, function(err){
(callback||_.noop)(err);
});
},
// destroy session by session id:
destroy: function (sid, callback) {
mongooseModel.findOneAndRemove(_applyProp(propSid, sid), function(err) {
(callback||_.noop)(err);
});
},
// get the number of total sessions:
length: function (callback) {
mongooseModel.count({}, callback||_.noop);
},
// clear all stored sessions:
clear: function (callback) {
mongooseModel.remove({}, callback||_.noop);
}
});
return me;
}
// inherit by default from connect memory store:
util.inherits(MStore, Store);
// return preconfigured mongoose store:
return MStore;
} | javascript | {
"resource": ""
} |
q38815 | web | train | function web(){
this.router = routers
this.data = {}
this.data.portStruct = this.data.portStruct || {}
this.data.routers = {}
this.data.isClearRequires = this.data.isClearRequires || this.isProductionMode
this.data.consoleAll = this.data.consoleAll
this.data.consoleNonProductionErrors = true
return this
} | javascript | {
"resource": ""
} |
q38816 | helpers | train | function helpers (options) {
extend(helpers, Options.prototype);
var opts = extend({}, options);
helpers.option('dir', opts.dir || 'test');
helpers.option('fixtures', helpers.options.dir + '/fixtures');
helpers.option('actual', helpers.options.dir + '/actual');
helpers.config(opts);
return helpers;
} | javascript | {
"resource": ""
} |
q38817 | NachosConfig | train | function NachosConfig() {
var defaults = {
packages: nachosHome('packages'),
server: 'http://nachosjs.herokuapp.com',
defaults: {
shell: 'shell',
exts: {}
},
startup: []
};
debug('creating new settings file with these defaults: %j', defaults);
SettingsFile.call(this, 'nachos', {
globalDefaults: defaults
});
} | javascript | {
"resource": ""
} |
q38818 | train | function () {
var data = this.data,
labelDistance = this.options.dataLabels.distance,
leftSide,
sign,
point,
i = data.length,
x,
y;
// In the original pie label anticollision logic, the slots are distributed
// from one labelDistance above to one labelDistance below the pie. In funnels
// we don't want this.
this.center[2] -= 2 * labelDistance;
// Set the label position array for each point.
while (i--) {
point = data[i];
leftSide = point.half;
sign = leftSide ? 1 : -1;
y = point.plotY;
x = this.getX(y, leftSide);
// set the anchor point for data labels
point.labelPos = [
0, // first break of connector
y, // a/a
x + (labelDistance - 5) * sign, // second break, right outside point shape
y, // a/a
x + labelDistance * sign, // landing point for connector
y, // a/a
leftSide ? 'right' : 'left', // alignment
0 // center angle
];
}
seriesTypes.pie.prototype.drawDataLabels.call(this);
} | javascript | {
"resource": ""
} | |
q38819 | addPluginsToScope | train | function addPluginsToScope(scope) {
var name;
for (name in plugins) {
if (plugins.hasOwnProperty(name)) {
scope[name] = plugins[name];
}
}
} | javascript | {
"resource": ""
} |
q38820 | registerPlugin | train | function registerPlugin(name, obj) {
if (name && name.length && obj) {
plugins[name] = obj;
}
} | javascript | {
"resource": ""
} |
q38821 | init | train | function init() {
// ex. jif(true, div('blah'))
registerPlugin('jif', function jif(condition, elem) {
if (utils.isArray(elem)) {
elem = runtime.naked(elem, null);
}
return condition ? elem : null;
});
// ex. jeach({}, function (item) {})
registerPlugin('jeach', function jeach(items, cb) {
if (!items || !cb) { return null; }
var ret = [];
for (var i = 0, len = items.length; i < len; ++i) {
ret.push(cb(items[i]));
}
return ret;
});
} | javascript | {
"resource": ""
} |
q38822 | InternalCursor | train | function InternalCursor(parent, key) {
debug.assert(parent).is('object');
debug.assert(key).is('defined');
this.cursors = [{'parent':parent, 'key':key}];
} | javascript | {
"resource": ""
} |
q38823 | connect_cb | train | function connect_cb(err, db) {
if (err) {
next(err);
} else {
if (db && db instanceof sqlite) { // Sqlite only
app.db = db;
// Use the query escaping facilities of mysql
app.db.escape = SqliteString.escape;
app.db.escapeId = SqliteString.escapeId;
app.db.format = SqliteString.format;
// Wrap exec with a signature similar to mysql's
// prepared queries
app.db.query = function(sql, values, callback) {
// prepare the statement
if (typeof values == 'function') {
callback = values;
} else {
sql = app.db.format(sql, values);
}
// Log some info
console.log('SQL query:', sql);
// execute the statement
app.db.exec(sql, callback);
};
app.db.end = function() {};
} else { // MySql only
app.db.format = MySqlString.format;
// Wrap qyery with some logging some logging
var _query = app.db.query;
app.db.query = function(sql, values, callback) {
var _sql = sql;
// prepare the statement (just for logging)
if (typeof values != 'function')
_sql = app.db.format(sql, values);
// Log some info
console.log('SQL query:', _sql);
// execute the statement
return _query.call(this, sql, values, callback);
};
}
next();
}
} | javascript | {
"resource": ""
} |
q38824 | train | function (user) {
if (user.id)
return {_id: user.id};
else if (user.username)
return {username: user.username};
else if (user.email)
return {"emails.address": user.email};
throw new Error("shouldn't happen (validation missed something)");
} | javascript | {
"resource": ""
} | |
q38825 | train | function (options) {
// Unknown keys allowed, because a onCreateUserHook can take arbitrary
// options.
check(options, Match.ObjectIncluding({
username: Match.Optional(String),
email: Match.Optional(String),
password: Match.Optional(String),
srp: Match.Optional(SRP.matchVerifier)
}));
var username = options.username;
var email = options.email;
if (!username && !email)
throw new Meteor.Error(400, "Need to set a username or email");
// Raw password. The meteor client doesn't send this, but a DDP
// client that didn't implement SRP could send this. This should
// only be done over SSL.
if (options.password) {
if (options.srp)
throw new Meteor.Error(400, "Don't pass both password and srp in options");
options.srp = SRP.generateVerifier(options.password);
}
var user = {services: {}};
if (options.srp)
user.services.password = {srp: options.srp}; // XXX validate verifier
if (username)
user.username = username;
if (email)
user.emails = [{address: email, verified: false}];
return Accounts.insertUserDoc(options, user);
} | javascript | {
"resource": ""
} | |
q38826 | setMessages | train | function setMessages() {
var messages = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
__messages = _extends({}, __messages, messages);
} | javascript | {
"resource": ""
} |
q38827 | whichStream | train | async function whichStream(config) {
const {
source,
destination,
} = config
let { readable, writable } = config
if (!(source || readable))
throw new Error('Please give either a source or readable.')
if (!(destination || writable))
throw new Error('Please give either a destination or writable.')
if (source && !readable) readable = createReadStream(source)
if (destination == '-') {
readable.pipe(process.stdout)
} else if (destination) {
await handleWriteStream(destination, readable, source)
} else if (writable instanceof Writable) {
readable.pipe(writable)
await new Promise((r, j) => {
writable.on('error', j)
writable.on('finish', r)
})
}
} | javascript | {
"resource": ""
} |
q38828 | search | train | function search(stream, needle) {
var ss = new streamsearch(needle),
push = ss.push.bind(ss);
ss.maxMatches = 1;
var defered = defer();
stream.on("data", push);
stream.once("finish", function(){
defered.reject("No stub found in stream")
});
var pos = 0;
ss.on("info", function(isMatch, data, start, end){
if(data)
pos += end - start;
if(!isMatch)
return;
stream.removeListener("data", push);
defered.resolve(pos);
});
return defered;
} | javascript | {
"resource": ""
} |
q38829 | Plugin | train | function Plugin(server) {
this.server = server;
this.config = server.config;
//Check if we have the right config
this.checkConfiguration();
this.settings = this.config.githubAuth;
//Init if not present
if (typeof this.server.passport === "undefined")
this.initGithubAuth();
else
this.passport = this.server.passport;
} | javascript | {
"resource": ""
} |
q38830 | take | train | async function take(key) {
const previousLocks = LOCKS_MAP.get(key) || [];
let locksLength = previousLocks.length;
log('debug', `Taking the lock on ${key} (queue length was ${locksLength})`);
let release;
const newLock = {
releasePromise: new Promise(async (resolve, reject) => {
release = resolve;
if (LOCK_TIMEOUT !== Infinity) {
await delay.create(LOCK_TIMEOUT);
reject(new YError('E_LOCK_TIMEOUT'));
}
}),
release,
};
previousLocks.push(newLock);
locksLength++;
if (locksLength > 1) {
await previousLocks[locksLength - 1].releasePromise;
} else {
LOCKS_MAP.set(key, previousLocks);
}
} | javascript | {
"resource": ""
} |
q38831 | release | train | async function release(key) {
const previousLocks = LOCKS_MAP.get(key) || [];
const locksLength = previousLocks.length;
log(
'debug',
`Releasing the lock on ${key} (queue length was ${locksLength})`,
);
previousLocks.pop().release();
} | javascript | {
"resource": ""
} |
q38832 | service | train | function service(root, cb) {
var registryPath = config.registryPath || path.join(root, 'registry');
fs.mkdir(registryPath, function(err) {
if (err && err.code !== 'EEXIST') {
logger.error(err);
return cb(err);
}
// swallow errors, it may exists
var server = registry({
dir: registryPath
});
server.on('error', function(err) {
logger.error(err);
});
server.listen(config.registryPort, function(err) {
logger.info({
port: config.registryPort,
path: registryPath
}, 'registry started');
if (typeof err === 'string') {
// err will contains the ip
// TODO remove me as https://github.com/mafintosh/root/issues/12 get fixes
err = null;
}
if (cb) {
cb(err, server);
}
});
});
} | javascript | {
"resource": ""
} |
q38833 | Class | train | function Class(prop, superClass) {
var ClassType = function() {
function F(args) {
for (var name in ClassType.__prop) {
var val = ClassType.__prop[name];
this[name] = isObject(val) ? extend({}, val) : val;
}
if (isFunction(this.__construct)) {
this.__construct.apply(this, [].slice.call(args));
}
return this;
}
F.prototype = ClassType.prototype;
F.constructor = ClassType;
return new F(arguments);
};
ClassType.extend = function(prop) {
if (isFunction(prop)) {
prop = prop();
}
if (isObject(prop)) {
for (var name in prop) {
var val = prop[name];
if (name === 'parent') {
throw new Error("'parent' method must not be override wrote.");
}
if (isFunction(val)) {
ClassType.prototype[name] = val;
} else {
ClassType.__prop[name] = isObject(val) ? extend({}, val) : val;
}
}
}
return this;
};
ClassType.inherits = function(superClass) {
inherits(ClassType, superClass);
extend(ClassType.__prop, superClass.__prop);
return this;
};
ClassType.prototype.parent = function(methodName, args) {
var super_ = this.constructor.super_;
if (!isFunction(this[methodName]) || !isFunction(super_.prototype[methodName])) {
throw new Error("parent has not method '" + methodName + "'.");
}
if (arguments.length === 1) {
args = [];
} else if (!isArray(args)) {
args = [].slice.call(arguments, 1);
}
while ((this[methodName] === super_.prototype[methodName]) && super_.super_) {
super_ = super_.super_;
}
var method = super_.prototype[methodName];
delete super_.prototype[methodName];
var retResult = method.apply(this, args);
super_.prototype[methodName] = method;
return retResult;
};
ClassType.__prop = {};
if (superClass === true && isFunction(prop)) {
superClass = prop;
prop = undefined;
}
if (isFunction(superClass)) {
ClassType.inherits(superClass);
}
if (prop) {
ClassType.extend(prop);
}
return ClassType;
} | javascript | {
"resource": ""
} |
q38834 | accept | train | function accept(req, res, cb) {
var u = url.parse(req.url, true),
path = u.pathname
if(/^\/api\/?$/.test(path)) {
messageInit({cb:(cb || nop), req:req, res:res, path:path, query:u.query, u:u})
return;
}
if(req.method == "OPTIONS") {
res.writeHead(200, {
"Access-Control-Allow-Origin": "*", // to support cross-domain script execution of our api
"Access-Control-Max-Age": "0",
})
res.end()
return;
}
www(req, res) // everything else handled by paperboy
} | javascript | {
"resource": ""
} |
q38835 | train | function (data) {
var self = this;
self._heap = _.map(data, function (o) {
return { id: o.id, value: o.value };
});
_.each(data, function (o, i) {
self._heapIdx.set(o.id, i);
});
if (! data.length)
return;
// start from the first non-leaf - the parent of the last leaf
for (var i = parentIdx(data.length - 1); i >= 0; i--)
self._downHeap(i);
} | javascript | {
"resource": ""
} | |
q38836 | train | function (iterator) {
var self = this;
_.each(self._heap, function (obj) {
return iterator(obj.value, obj.id);
});
} | javascript | {
"resource": ""
} | |
q38837 | matchAndIssueAlertEmails | train | function matchAndIssueAlertEmails(eventDetails, alerts){
underscore.each(alerts, function(alert) {
if (shouldTriggerAlert(eventDetails, alert)){
issueAlertEmail(eventDetails, alert);
}
});
} | javascript | {
"resource": ""
} |
q38838 | shouldTriggerAlert | train | function shouldTriggerAlert(eventDetails, alert){
if (alert.alertEnabled){
// Event Message Criteria
var msgEventName = eventDetails.eventType;
var msgEventCategory = eventDetails.eventClass;
var msgEventSeverity = eventDetails.eventLevel;
// Saved Alert Criteria
var alertEventNames = alert.eventNames;
var alertEventCategories = alert.eventCategories;
var alertEventSeverities = alert.eventSeverities;
// Test results
var matchOnAlertEventName = alertEventNames.indexOf(msgEventName) > -1;
var matchOnAlertEventCategory = alertEventCategories.indexOf(msgEventCategory) > -1;
var matchOnAlertSeverity = alertEventSeverities.indexOf(msgEventSeverity) > -1;
// if we match on the above, grab the emails from the Alert and send email (where is template???) and save Notification to Mongo (what is the record format????)
if (matchOnAlertEventName && matchOnAlertEventCategory && matchOnAlertSeverity) {
logger.logger.trace(loggerPrefix +'Match found. Sending emails to: ', alert.emails);
return true;
} else {
logger.logger.trace(loggerPrefix +'No Match found. No emails to send');
return false;
}
} else {
return false;
}
} | javascript | {
"resource": ""
} |
q38839 | handler | train | function handler (eventDetails){
var Alert = models.getModels().Alert;
logger.logger.trace(loggerPrefix +'Processing Alerts for Event: ', eventDetails);
Alert.queryAlerts(eventDetails.uid, eventDetails.env, eventDetails.domain, function(err, alerts){
if(err) {
logger.logger.warn({ error:err }, loggerPrefix +'Failed to query Alerts for uid and env', uid, env);
} else {
if(alerts && alerts.length > 0){
logger.logger.trace(loggerPrefix +'Found ['+ alerts.length +'] Alerts. Matching and send emails', alerts);
matchAndIssueAlertEmails(eventDetails, alerts);
} else {
logger.logger.trace(loggerPrefix +'No Alerts for event. No emails to send.');
}
}
});
} | javascript | {
"resource": ""
} |
q38840 | columnToSQL | train | function columnToSQL(col) {
var sql = "`" + col.name + "` ";
sql += nrutil.typeToSQL(col.type);
if (col['additional']) {
sql += ' ' + col['additional'];
}
if (!col['allow_null']) {
sql += " NOT NULL";
}
if (col['default_value'] !== undefined) {
var def = col['default_value']
sql += " DEFAULT " + nrutil.serialize(def);
}
if (col.type == 'primary_key') {
sql += " PRIMARY KEY AUTO_INCREMENT";
}
return sql;
} | javascript | {
"resource": ""
} |
q38841 | train | function(name, newname) {
var act = new NobleMachine(function() {
act.toNext(db.query("SHOW COLUMNS FROM `" + tablename + "`;"));
});
act.next(function(result) {
var sql = "ALTER TABLE `" + tablename + "` CHANGE `" + name + "` `" + newname + "`";
result.forEach(function(coldatum) {
if (coldatum['Field'] == name) {
sql += " " + coldatum['Type'];
if (coldatum['Null'] == 'NO') {
sql += " NOT NULL";
}
if (coldatum['Key'] == 'PRI') {
sql += " PRIMARY KEY";
}
sql += coldatum['Extra'];
if (coldatum['Default'] != 'NULL') {
sql += " DEFAULT " + coldatum['Default'];
}
}
});
sql += ";";
act.toNext(db.query(sql));
});
me.act.next(act);
} | javascript | {
"resource": ""
} | |
q38842 | train | function() {
var me = {};
var db = common.config.database;
me.act = new NobleMachine();
return _.extend(me, {
create_table: function(name, definer) {
var t = new TableDefinition(name, 'create', definer);
me.act.next(t.act);
},
change_table: function(name, definer) {
var t = new TableDefinition(name, 'alter', definer);
me.act.next(t.act);
},
drop_table: function(name) {
me.act.next(db.query(" DROP TABLE `" + name + "`;"));
},
rename_table: function(name, newname) {
me.act.next(db.query(" ALTER TABLE `" + name + "` RENAME `" + newname + "`"));
},
});
} | javascript | {
"resource": ""
} | |
q38843 | helpPlugin | train | function helpPlugin() {
return function(app) {
// style to turn `[ ]` strings into
// colored strings with backticks
app.style('codify', function(msg) {
var re = /\[([^\]]*\[?[^\]]*\]?[^[]*)\]/g;
return msg.replace(re, function(str, code) {
return this.red('`' + code + '`');
}.bind(this));
});
// style and format a single help command
app.style('helpCommand', function(command) {
var msg = '';
msg += this.bold(command.name.substr(0, 1).toUpperCase() +
command.name.substr(1) + ': ');
msg += this.bold(command.description);
return msg;
});
// style and format an array of help commands
app.style('helpCommands', function(commands) {
return commands
.map(this.helpCommand)
.join('\n\n');
});
// style and format a single example
app.style('helpExample', function(example) {
var msg = '';
msg += ' ' + this.gray('# ' + example.description) + '\n';
msg += ' ' + this.white('$ ' + example.command);
return msg;
});
// style and format an array of examples
app.style('helpExamples', function(examples) {
return examples
.map(this.helpExample)
.join('\n\n');
});
// style and format a single option
app.style('helpOption', function(option) {
var msg = '';
msg += ' ' + (option.flag ? this.bold(option.flag) : ' ');
msg += ' ' + this.bold(option.name);
msg += ' ' + this.bold(this.codify(option.description));
return msg;
});
// style and format an array of options
app.style('helpOptions', function(options) {
return options
.map(this.helpOption)
.join('\n');
});
// style and formation a help text object using
// other styles to break up responibilities
app.emitter('help', function(help) {
var msg = '\n';
msg += this.bold('Usage: ') + this.cyan(help.usage) + '\n\n';
msg += this.helpCommands(help.commands);
if (help.examples && help.examples.length) {
msg += this.bold('Examples:\n\n');
msg += this.helpExamples(help.examples);
}
if (help.options && help.options.length) {
msg += this.bold('Options:\n\n');
msg += this.helpOptions(help.options);
}
return msg + '\n';
});
};
} | javascript | {
"resource": ""
} |
q38844 | removeDoubles | train | function removeDoubles( arrInput ) {
const
arrOutput = [],
map = {};
arrInput.forEach( function forEachItem( itm ) {
if ( itm in map ) return;
map[ itm ] = 1;
arrOutput.push( itm );
} );
return arrOutput;
} | javascript | {
"resource": ""
} |
q38845 | cleanDir | train | function cleanDir( path, _preserveGit ) {
const
preserveGit = typeof _preserveGit !== 'undefined' ? _preserveGit : false,
fullPath = Path.resolve( path );
// If the pah does not exist, everything is fine!
if ( !FS.existsSync( fullPath ) ) return;
if ( preserveGit ) {
/*
* We must delete the content of this folder but preserve `.git`.
* The `www` dir, for instance, can be used as a `gh-pages` branch.
*/
const files = FS.readdirSync( path );
files.forEach( function forEachFile( filename ) {
if ( filename === '.git' ) return;
const
filepath = Path.join( path, filename ),
stat = FS.statSync( filepath );
if ( stat.isDirectory() ) {
if ( filepath !== '.' && filepath !== '..' ) PathUtils.rmdir( filepath );
} else FS.unlinkSync( filepath );
} );
} else {
// Brutal clean: remove dir and recreate it.
PathUtils.rmdir( path );
PathUtils.mkdir( path );
}
} | javascript | {
"resource": ""
} |
q38846 | isNewerThan | train | function isNewerThan( inputs, target ) {
if ( !FS.existsSync( target ) ) return true;
const files = Array.isArray( inputs ) ? inputs : [ inputs ],
statTarget = FS.statSync( target ),
targetTime = statTarget.mtime;
for ( const file of files ) {
if ( !FS.existsSync( file ) ) continue;
const stat = FS.statSync( file );
if ( stat.mtime > targetTime ) {
return true;
}
}
return false;
} | javascript | {
"resource": ""
} |
q38847 | addData | train | function addData(a)
{
if(isObject(a.event.value) || isArray(a.event.value))
{
if(!isObservable(a.event.value))
{
a.preventDefault();
var local = a.event.local,
str = local.__kbscopeString+(local.__kbscopeString.length !== 0 ? '.' : '')+a.key,
builder = (isObject(a.event.value) ? KObject : KArray)(local.__kbname,local,str);
overwrite(builder).parseData(a.event.value);
if(local[a.key] === undefined)
{
local.add(a.key,builder);
}
else if(isArray(local))
{
local.splice(a.key,0,builder);
}
else if(isObject(local))
{
local.set(a.key,builder);
}
}
}
} | javascript | {
"resource": ""
} |
q38848 | SyntaxUnit | train | function SyntaxUnit(text, line, col){
/**
* The column of text on which the unit resides.
* @type int
* @property col
*/
this.col = col;
/**
* The line of text on which the unit resides.
* @type int
* @property line
*/
this.line = line;
/**
* The text representation of the unit.
* @type String
* @property text
*/
this.text = text;
} | javascript | {
"resource": ""
} |
q38849 | train | function(type, listener){
if (this._handlers[type] instanceof Array){
var handlers = this._handlers[type];
for (var i=0, len=handlers.length; i < len; i++){
if (handlers[i] === listener){
handlers.splice(i, 1);
break;
}
}
}
} | javascript | {
"resource": ""
} | |
q38850 | train | function(receiver, supplier){
for (var prop in supplier){
if (supplier.hasOwnProperty(prop)){
receiver[prop] = supplier[prop];
}
}
return receiver;
} | javascript | {
"resource": ""
} | |
q38851 | train | function (expected, actual, message) {
YUITest.Assert._increment();
if (expected !== actual) {
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Values should be the same."), expected, actual);
}
} | javascript | {
"resource": ""
} | |
q38852 | train | function (actual, message) {
YUITest.Assert._increment();
if (true !== actual) {
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Value should be true."), true, actual);
}
} | javascript | {
"resource": ""
} | |
q38853 | train | function (actual, message) {
YUITest.Assert._increment();
if (actual !== null) {
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Value should be null."), null, actual);
}
} | javascript | {
"resource": ""
} | |
q38854 | train | function (actual, message) {
YUITest.Assert._increment();
if (typeof actual != "undefined") {
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Value should be undefined."), undefined, actual);
}
} | javascript | {
"resource": ""
} | |
q38855 | train | function (actual, message) {
YUITest.Assert._increment();
if (typeof actual != "boolean"){
throw new YUITest.UnexpectedValue(YUITest.Assert._formatMessage(message, "Value should be a Boolean."), actual);
}
} | javascript | {
"resource": ""
} | |
q38856 | train | function (expectedType, actualValue, message){
YUITest.Assert._increment();
if (typeof actualValue != expectedType){
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Value should be of type " + expectedType + "."), expectedType, typeof actualValue);
}
} | javascript | {
"resource": ""
} | |
q38857 | train | function (needle, haystack,
message) {
YUITest.Assert._increment();
if (this._indexOf(haystack, needle) == -1){
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value " + needle + " (" + (typeof needle) + ") not found in array [" + haystack + "]."));
}
} | javascript | {
"resource": ""
} | |
q38858 | train | function (needles, haystack,
message) {
YUITest.Assert._increment();
for (var i=0; i < needles.length; i++){
if (this._indexOf(haystack, needles[i]) > -1){
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value found in array [" + haystack + "]."));
}
}
} | javascript | {
"resource": ""
} | |
q38859 | train | function (matcher, haystack,
message) {
YUITest.Assert._increment();
//check for valid matcher
if (typeof matcher != "function"){
throw new TypeError("ArrayAssert.doesNotContainMatch(): First argument must be a function.");
}
if (this._some(haystack, matcher)){
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value found in array [" + haystack + "]."));
}
} | javascript | {
"resource": ""
} | |
q38860 | train | function (expected, actual,
message) {
YUITest.Assert._increment();
//first check array length
if (expected.length != actual.length){
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Array should have a length of " + expected.length + " but has a length of " + actual.length));
}
//begin checking values
for (var i=0; i < expected.length; i++){
if (expected[i] != actual[i]){
throw new YUITest.Assert.ComparisonFailure(YUITest.Assert._formatMessage(message, "Values in position " + i + " are not equal."), expected[i], actual[i]);
}
}
} | javascript | {
"resource": ""
} | |
q38861 | train | function (actual, message) {
YUITest.Assert._increment();
if (actual.length > 0){
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Array should be empty."));
}
} | javascript | {
"resource": ""
} | |
q38862 | train | function (needle, haystack, index, message) {
//try to find the value in the array
for (var i=haystack.length; i >= 0; i--){
if (haystack[i] === needle){
if (index != i){
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value exists at index " + i + " but should be at index " + index + "."));
}
return;
}
}
//if it makes it here, it wasn't found at all
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value doesn't exist in array."));
} | javascript | {
"resource": ""
} | |
q38863 | train | function(expected, actual, message) {
YUITest.Assert._increment();
for (var name in expected){
if (expected.hasOwnProperty(name)){
if (expected[name] != actual[name]){
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Values should be equal for property " + name), expected[name], actual[name]);
}
}
}
} | javascript | {
"resource": ""
} | |
q38864 | train | function (object, message) {
YUITest.Assert._increment();
var count = 0,
name;
for (name in object){
if (object.hasOwnProperty(name)){
count++;
}
}
if (count !== 0){
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Object owns " + count + " properties but should own none."));
}
} | javascript | {
"resource": ""
} | |
q38865 | train | function (propertyName, object, message) {
YUITest.Assert._increment();
if (!(propertyName in object)){
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Property '" + propertyName + "' not found on object."));
}
} | javascript | {
"resource": ""
} | |
q38866 | train | function (properties, object, message) {
YUITest.Assert._increment();
for (var i=0; i < properties.length; i++){
if (!(properties[i] in object)){
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Property '" + properties[i] + "' not found on object."));
}
}
} | javascript | {
"resource": ""
} | |
q38867 | train | function (expected, actual, message){
YUITest.Assert._increment();
if (expected instanceof Date && actual instanceof Date){
var msg = "";
//check years first
if (expected.getFullYear() != actual.getFullYear()){
msg = "Years should be equal.";
}
//now check months
if (expected.getMonth() != actual.getMonth()){
msg = "Months should be equal.";
}
//last, check the day of the month
if (expected.getDate() != actual.getDate()){
msg = "Days of month should be equal.";
}
if (msg.length){
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, msg), expected, actual);
}
} else {
throw new TypeError("YUITest.DateAssert.datesAreEqual(): Expected and actual values must be Date objects.");
}
} | javascript | {
"resource": ""
} | |
q38868 | train | function (expected, actual, message){
YUITest.Assert._increment();
if (expected instanceof Date && actual instanceof Date){
var msg = "";
//check hours first
if (expected.getHours() != actual.getHours()){
msg = "Hours should be equal.";
}
//now check minutes
if (expected.getMinutes() != actual.getMinutes()){
msg = "Minutes should be equal.";
}
//last, check the seconds
if (expected.getSeconds() != actual.getSeconds()){
msg = "Seconds should be equal.";
}
if (msg.length){
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, msg), expected, actual);
}
} else {
throw new TypeError("YUITest.DateAssert.timesAreEqual(): Expected and actual values must be Date objects.");
}
} | javascript | {
"resource": ""
} | |
q38869 | train | function (segment, delay){
var actualDelay = (typeof segment == "number" ? segment : delay);
actualDelay = (typeof actualDelay == "number" ? actualDelay : 10000);
if (typeof segment == "function"){
throw new YUITest.Wait(segment, actualDelay);
} else {
throw new YUITest.Wait(function(){
YUITest.Assert.fail("Timeout: wait() called but resume() never called.");
}, actualDelay);
}
} | javascript | {
"resource": ""
} | |
q38870 | train | function (testObject) {
if (testObject instanceof YUITest.TestSuite || testObject instanceof YUITest.TestCase) {
this.items.push(testObject);
}
return this;
} | javascript | {
"resource": ""
} | |
q38871 | train | function(results) {
function serializeToXML(results){
var xml = "<" + results.type + " name=\"" + xmlEscape(results.name) + "\"";
if (typeof(results.duration)=="number"){
xml += " duration=\"" + results.duration + "\"";
}
if (results.type == "test"){
xml += " result=\"" + results.result + "\" message=\"" + xmlEscape(results.message) + "\">";
} else {
xml += " passed=\"" + results.passed + "\" failed=\"" + results.failed + "\" ignored=\"" + results.ignored + "\" total=\"" + results.total + "\">";
for (var prop in results){
if (results.hasOwnProperty(prop)){
if (results[prop] && typeof results[prop] == "object" && !(results[prop] instanceof Array)){
xml += serializeToXML(results[prop]);
}
}
}
}
xml += "</" + results.type + ">";
return xml;
}
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + serializeToXML(results);
} | javascript | {
"resource": ""
} | |
q38872 | train | function() {
if (this._form){
this._form.parentNode.removeChild(this._form);
this._form = null;
}
if (this._iframe){
this._iframe.parentNode.removeChild(this._iframe);
this._iframe = null;
}
this._fields = null;
} | javascript | {
"resource": ""
} | |
q38873 | train | function(results){
//if the form hasn't been created yet, create it
if (!this._form){
this._form = document.createElement("form");
this._form.method = "post";
this._form.style.visibility = "hidden";
this._form.style.position = "absolute";
this._form.style.top = 0;
document.body.appendChild(this._form);
//IE won't let you assign a name using the DOM, must do it the hacky way
try {
this._iframe = document.createElement("<iframe name=\"yuiTestTarget\" />");
} catch (ex){
this._iframe = document.createElement("iframe");
this._iframe.name = "yuiTestTarget";
}
this._iframe.src = "javascript:false";
this._iframe.style.visibility = "hidden";
this._iframe.style.position = "absolute";
this._iframe.style.top = 0;
document.body.appendChild(this._iframe);
this._form.target = "yuiTestTarget";
}
//set the form's action
this._form.action = this.url;
//remove any existing fields
while(this._form.hasChildNodes()){
this._form.removeChild(this._form.lastChild);
}
//create default fields
this._fields.results = this.format(results);
this._fields.useragent = navigator.userAgent;
this._fields.timestamp = (new Date()).toLocaleString();
//add fields to the form
for (var prop in this._fields){
var value = this._fields[prop];
if (this._fields.hasOwnProperty(prop) && (typeof value != "function")){
var input = document.createElement("input");
input.type = "hidden";
input.name = prop;
input.value = value;
this._form.appendChild(input);
}
}
//remove default fields
delete this._fields.results;
delete this._fields.useragent;
delete this._fields.timestamp;
if (arguments[1] !== false){
this._form.submit();
}
} | javascript | {
"resource": ""
} | |
q38874 | train | function (page, results){
var r = this._results;
r.passed += results.passed;
r.failed += results.failed;
r.ignored += results.ignored;
r.total += results.total;
r.duration += results.duration;
if (results.failed){
r.failedPages.push(page);
} else {
r.passedPages.push(page);
}
results.name = page;
results.type = "page";
r[page] = results;
} | javascript | {
"resource": ""
} | |
q38875 | train | function () /*:Void*/ {
//set the current page
this._curPage = this._pages.shift();
this.fire(this.TEST_PAGE_BEGIN_EVENT, this._curPage);
//load the frame - destroy history in case there are other iframes that
//need testing
this._frame.location.replace(this._curPage);
} | javascript | {
"resource": ""
} | |
q38876 | train | function () /*:Void*/ {
if (!this._initialized) {
/**
* Fires when loading a test page
* @event testpagebegin
* @param curPage {string} the page being loaded
* @static
*/
/**
* Fires when a test page is complete
* @event testpagecomplete
* @param obj {page: string, results: object} the name of the
* page that was loaded, and the test suite results
* @static
*/
/**
* Fires when the test manager starts running all test pages
* @event testmanagerbegin
* @static
*/
/**
* Fires when the test manager finishes running all test pages. External
* test runners should subscribe to this event in order to get the
* aggregated test results.
* @event testmanagercomplete
* @param obj { pages_passed: int, pages_failed: int, tests_passed: int
* tests_failed: int, passed: string[], failed: string[],
* page_results: {} }
* @static
*/
//create iframe if not already available
if (!this._frame){
var frame /*:HTMLElement*/ = document.createElement("iframe");
frame.style.visibility = "hidden";
frame.style.position = "absolute";
document.body.appendChild(frame);
this._frame = frame.contentWindow || frame.contentDocument.parentWindow;
}
this._initialized = true;
}
// reset the results cache
this._results = {
passed: 0,
failed: 0,
ignored: 0,
total: 0,
type: "report",
name: "YUI Test Results",
duration: 0,
failedPages:[],
passedPages:[]
/*
// number of pages that pass
pages_passed: 0,
// number of pages that fail
pages_failed: 0,
// total number of tests passed
tests_passed: 0,
// total number of tests failed
tests_failed: 0,
// array of pages that passed
passed: [],
// array of pages that failed
failed: [],
// map of full results for each page
page_results: {}*/
};
this.fire(this.TEST_MANAGER_BEGIN_EVENT, null);
this._run();
} | javascript | {
"resource": ""
} | |
q38877 | train | function (parentNode, testSuite) {
//add the test suite
var node = parentNode.appendChild(testSuite);
//iterate over the items in the master suite
for (var i=0; i < testSuite.items.length; i++){
if (testSuite.items[i] instanceof YUITest.TestSuite) {
this._addTestSuiteToTestTree(node, testSuite.items[i]);
} else if (testSuite.items[i] instanceof YUITest.TestCase) {
this._addTestCaseToTestTree(node, testSuite.items[i]);
}
}
} | javascript | {
"resource": ""
} | |
q38878 | train | function () {
this._root = new TestNode(this.masterSuite);
//this._cur = this._root;
//iterate over the items in the master suite
for (var i=0; i < this.masterSuite.items.length; i++){
if (this.masterSuite.items[i] instanceof YUITest.TestSuite) {
this._addTestSuiteToTestTree(this._root, this.masterSuite.items[i]);
} else if (this.masterSuite.items[i] instanceof YUITest.TestCase) {
this._addTestCaseToTestTree(this._root, this.masterSuite.items[i]);
}
}
} | javascript | {
"resource": ""
} | |
q38879 | train | function () {
//flag to indicate if the TestRunner should wait before continuing
var shouldWait = false;
//get the next test node
var node = this._next();
if (node !== null) {
//set flag to say the testrunner is running
this._running = true;
//eliminate last results
this._lastResult = null;
var testObject = node.testObject;
//figure out what to do
if (typeof testObject == "object" && testObject !== null){
if (testObject instanceof YUITest.TestSuite){
this.fire({ type: this.TEST_SUITE_BEGIN_EVENT, testSuite: testObject });
node._start = new Date();
this._execNonTestMethod(node, "setUp" ,false);
} else if (testObject instanceof YUITest.TestCase){
this.fire({ type: this.TEST_CASE_BEGIN_EVENT, testCase: testObject });
node._start = new Date();
//regular or async init
/*try {
if (testObject["async:init"]){
testObject["async:init"](this._context);
return;
} else {
testObject.init(this._context);
}
} catch (ex){
node.results.errors++;
this.fire({ type: this.ERROR_EVENT, error: ex, testCase: testObject, methodName: "init" });
}*/
if(this._execNonTestMethod(node, "init", true)){
return;
}
}
//some environments don't support setTimeout
if (typeof setTimeout != "undefined"){
setTimeout(function(){
YUITest.TestRunner._run();
}, 0);
} else {
this._run();
}
} else {
this._runTest(node);
}
}
} | javascript | {
"resource": ""
} | |
q38880 | train | function (node) {
//get relevant information
var testName = node.testObject,
testCase = node.parent.testObject,
test = testCase[testName],
//get the "should" test cases
shouldIgnore = testName.indexOf("ignore:") === 0 ||
!inGroups(testCase.groups, this._groups) ||
(testCase._should.ignore || {})[testName]; //deprecated
//figure out if the test should be ignored or not
if (shouldIgnore){
//update results
node.parent.results[testName] = {
result: "ignore",
message: "Test ignored",
type: "test",
name: testName.indexOf("ignore:") === 0 ? testName.substring(7) : testName
};
node.parent.results.ignored++;
node.parent.results.total++;
this.fire({ type: this.TEST_IGNORE_EVENT, testCase: testCase, testName: testName });
//some environments don't support setTimeout
if (typeof setTimeout != "undefined"){
setTimeout(function(){
YUITest.TestRunner._run();
}, 0);
} else {
this._run();
}
} else {
//mark the start time
node._start = new Date();
//run the setup
this._execNonTestMethod(node.parent, "setUp", false);
//now call the body of the test
this._resumeTest(test);
}
} | javascript | {
"resource": ""
} | |
q38881 | train | function (options) {
options = options || {};
//pointer to runner to avoid scope issues
var runner = YUITest.TestRunner,
oldMode = options.oldMode;
//if there's only one suite on the masterSuite, move it up
if (!oldMode && this.masterSuite.items.length == 1 && this.masterSuite.items[0] instanceof YUITest.TestSuite){
this.masterSuite = this.masterSuite.items[0];
}
//determine if there are any groups to filter on
runner._groups = (options.groups instanceof Array) ? "," + options.groups.join(",") + "," : "";
//initialize the runner
runner._buildTestTree();
runner._context = {};
runner._root._start = new Date();
//fire the begin event
runner.fire(runner.BEGIN_EVENT);
//begin the testing
runner._run();
} | javascript | {
"resource": ""
} | |
q38882 | train | function(filename, options) {
var input = readFile(filename),
result = CSSLint.verify(input, gatherRules(options)),
formatId = options.format || "text",
messages = result.messages || [],
exitCode = 0;
if (!input) {
print("csslint: Could not read file data in " + filename + ". Is the file empty?");
exitCode = 1;
} else {
print(CSSLint.getFormatter(formatId).formatResults(result, filename, formatId));
if (messages.length > 0 && pluckByType(messages, 'error').length > 0) {
exitCode = 1;
}
}
return exitCode;
} | javascript | {
"resource": ""
} | |
q38883 | compact | train | function compact(source) {
if (!source) return null;
if (isArray(source))
return compactArray(source);
if (typeof source == 'object')
return compactObject(source);
return source;
} | javascript | {
"resource": ""
} |
q38884 | compactArray | train | function compactArray(source) {
return source.reduce(function(result, value){
if (value != void 0)
result.push(value);
return result;
}, []);
} | javascript | {
"resource": ""
} |
q38885 | compactObject | train | function compactObject(source) {
var result = {}, key;
for (key in source) {
var value = source[key];
if (value != void 0)
result[key] = value;
}
return result;
} | javascript | {
"resource": ""
} |
q38886 | qsort | train | function qsort(array, l, r, func) {
if(l < r) {
var i = l, j = r;
var x = array[l];
while(i < j) {
while(i < j && func(x, array[j])) j--;
array[i] = array[j];
while(i < j && func(array[i], x)) i++;
array[j] = array[i];
}
array[i] = x;
qsort(array, l, i - 1, func);
qsort(array, i + 1, r, func);
}
} | javascript | {
"resource": ""
} |
q38887 | validateLibOpts | train | function validateLibOpts(libOptsRaw) {
_chai.assert.ok(libOptsRaw, 'libOpts definition is required');
var libName = libOptsRaw.libName;
var validateContext = libOptsRaw.validateContext;
var configureAppContext = libOptsRaw.configureAppContext;
var configureInitialState = libOptsRaw.configureInitialState;
(0, _chai.assert)(typeof libName === 'string', 'libName must be a string');
(0, _chai.assert)(libName.length > 0, 'libName must not be empty');
_chai.assert.ok(validateContext, 'validateContext must exist');
(0, _chai.assert)(typeof validateContext === 'function', 'validateContext must be a function');
_chai.assert.ok(configureAppContext, 'configureAppContext must exist');
(0, _chai.assert)(typeof configureAppContext === 'function', 'configureAppContext must be a function');
_chai.assert.ok(configureInitialState, 'configureInitialState must exist');
(0, _chai.assert)(typeof configureInitialState === 'function', 'configureInitialState must be a function');
} | javascript | {
"resource": ""
} |
q38888 | validateAppOpts | train | function validateAppOpts(appOptsRaw) {
_chai.assert.ok(appOptsRaw, 'appOpts are required');
var appName = appOptsRaw.appName;
(0, _chai.assert)(typeof appName === 'string', 'appName opt must be a string');
(0, _chai.assert)(appName.length > 0, 'appName opt must not be empty');
} | javascript | {
"resource": ""
} |
q38889 | monitorArray | train | function monitorArray(a, emit) {
['copyWithin', 'fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift']
.forEach(function(key) {
var original = a[key];
a[key] = function() {
var result = original.apply(a, arguments);
emit();
return result;
};
});
return a;
} | javascript | {
"resource": ""
} |
q38890 | inherit | train | function inherit(options, destination, source, key) {
var define, override, path;
if (key in destination) {
if (isObject(destination[key]) && isObject(source[key])) {
// live up to the name and merge the sub objects
Object.keys(source[key]).forEach(function(k) {
inherit(options, destination[key], source[key], k);
});
}
return;
}
options.path.push(key);
define = {enumerable: true};
if (isObject(source[key])) {
override = combine(options, [source[key]]);
}
else if (source[key] instanceof Array) {
override = monitorArray(source[key], function() {
options.emitter.emit('change', path, source[key], source[key]);
});
}
if (isTrue(options, 'live')) {
path = options.path.join('.');
define.get = function() {
return override || source[key];
};
define.set = function(value) {
if (isTrue(options, 'locked') || value === destination[key]) {
return;
}
if (isObject(value)) {
options.path = path.split('.');
value = combine(options, [value, source[key]]);
}
override = null;
options.emitter.emit('change', path, value, source[key]);
source[key] = value;
};
}
else {
define.value = override || source[key];
define.writable = !isTrue(options, 'locked');
}
Object.defineProperty(destination, key, define);
options.path.pop();
} | javascript | {
"resource": ""
} |
q38891 | promisedRequire | train | function promisedRequire (name, retries=0) {
if (Array.isArray(name)) {
return Promise.all(name.map((n) => {
return promisedRequire(n);
}));
}
return new Promise(function (resolve, reject) {
global.requirejs([name], (result) => {
resolve(result);
}, (err) => {
var failedId = err.requireModules && err.requireModules[0];
if (failedId === name) {
global.requirejs.undef(name);
let query = `script[data-requirecontext][data-requiremodule="${name}"]`;
let script = document.querySelector(query);
if (script) {
script.parentNode.removeChild(script);
}
if (retries < 1) {
reject(err);
} else {
retries -= 1;
promisedRequire(name, retries).then(resolve, reject);
}
}
});
});
} | javascript | {
"resource": ""
} |
q38892 | train | function (key) {
const value = db.get(key);
if (!value) {
db.set(key, {
frozen: true
});
return;
}
db.set(key, {
intent: value.intent,
message: value.message,
editor: value.editor,
time: value.time,
frozen: true
});
return true;
} | javascript | {
"resource": ""
} | |
q38893 | pluginTarget | train | function pluginTarget(obj)
{
obj.__plugins = {};
/**
* Adds a plugin to an object
*
* @param pluginName {string} The events that should be listed.
* @param ctor {Object} ?? @alvin
*/
obj.registerPlugin = function (pluginName, ctor)
{
obj.__plugins[pluginName] = ctor;
};
/**
* Instantiates all the plugins of this object
*
*/
obj.prototype.initPlugins = function ()
{
this.plugins = this.plugins || {};
for (var o in obj.__plugins)
{
this.plugins[o] = new (obj.__plugins[o])(this);
}
};
/**
* Removes all the plugins of this object
*
*/
obj.prototype.destroyPlugins = function ()
{
for (var o in this.plugins)
{
this.plugins[o].destroy();
this.plugins[o] = null;
}
this.plugins = null;
};
} | javascript | {
"resource": ""
} |
q38894 | train | function(){
canvas = document.getElementById("canvas");
canvas.width = Zone.prototype.WIDTH;
canvas.height = Zone.prototype.HEIGHT;
frameCount = 0;
if (GameView.isRunning()){
run();
}
//Add a listener on our global gameData object, to know when our game starts/stops
gameData.on("change:isRunning", function(model, value){
value ? run() : reset();
});
} | javascript | {
"resource": ""
} | |
q38895 | angleDiff | train | function angleDiff(angle1, angle2){
var deltaAngle = angle1-angle2;
while (deltaAngle < -Math.PI) deltaAngle += (2*Math.PI);
while (deltaAngle > Math.PI) deltaAngle -= (2*Math.PI);
return Math.abs(deltaAngle);
} | javascript | {
"resource": ""
} |
q38896 | train | function(object, constraints, property) {
var that = this;
object.__addSetter(property, this.SETTER_NAME, this.SETTER_WEIGHT, function(value, fields) {
return that.apply(value, constraints, property, fields, this);
});
} | javascript | {
"resource": ""
} | |
q38897 | train | function(value, constraints, property, fields, object) {
_.each(constraints, function(constraint, name) {
if (!constraint.call(object, value, fields, property)) {
throw new Error('Constraint "' + name + '" was failed!');
}
});
return value;
} | javascript | {
"resource": ""
} | |
q38898 | normalizeUrl | train | function normalizeUrl(url) {
if (!IS_ABSOLUTE.test(url)) {
return (0, _normalizeUrl2['default'])(url).replace('http://', '');
} else {
return (0, _normalizeUrl2['default'])(url);
}
} | javascript | {
"resource": ""
} |
q38899 | _isFile | train | function _isFile (file, callback) {
if ("undefined" === typeof file) {
throw new ReferenceError("missing \"file\" argument");
}
else if ("string" !== typeof file) {
throw new TypeError("\"file\" argument is not a string");
}
else if ("" === file.trim()) {
throw new Error("\"file\" argument is empty");
}
else if ("undefined" === typeof callback) {
throw new ReferenceError("missing \"callback\" argument");
}
else if ("function" !== typeof callback) {
throw new TypeError("\"callback\" argument is not a function");
}
else {
lstat(file, (err, stats) => {
return callback(null, Boolean(!err && stats.isFile()));
});
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.