_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q9200
|
train
|
function (eventName, argsArray) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (arguments.length > 1 && (!argsArray || argsArray.length === undefined)) {
throw '"argsArray" must have a length property';
}
}
if (!this.__private || !this.__private.listeners) { return; }
var listenersForEvent = this.__private.listeners[eventName];
if (!listenersForEvent) { return; }
for (var i = 0, n = listenersForEvent.length; i < n; ++i) {
listenersForEvent[i].apply(undefined, argsArray);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9201
|
train
|
function (eventName, callback) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (typeof callback !== 'function') {
throw '"callback" argument must be a function';
}
}
this.__private || Object.defineProperty(this, '__private', { writable: true, value: {}, });
var listeners = this.__private.listeners || (this.__private.listeners = {});
var listenersForEvent = listeners[eventName] || (listeners[eventName] = []);
if (RUNTIME_CHECKS && listenersForEvent.indexOf(callback) !== -1) {
throw 'This listener has already been added (event: ' + eventName + ')';
}
listenersForEvent.push(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q9202
|
train
|
function (eventName, callback) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (arguments.length === 2 && typeof callback !== 'function') {
throw '"callback" argument must be a function'; // Catch a common cause of errors
}
}
// No listeners at all? We are done.
if (!this.__private || !this.__private.listeners) { return; }
var listenersForEvent = this.__private.listeners[eventName];
if (!listenersForEvent) { return; } // No listeners for this event? We are done.
if (callback) {
var pos = listenersForEvent.indexOf(callback);
if (pos === -1) { return; }
listenersForEvent.splice(pos, 1);
} else {
listenersForEvent.length = 0;
}
listenersForEvent.length === 0 && (delete this.__private.listeners[eventName]);
}
|
javascript
|
{
"resource": ""
}
|
|
q9203
|
train
|
function (collection, callback) {
var index,
iterable = collection,
result = iterable;
if (!iterable) {
return result;
}
if (!sofa.Util.objectTypes[typeof iterable]) {
return result;
}
for (index in iterable) {
if (Object.prototype.hasOwnProperty.call(iterable, index)) {
if (callback(iterable[index], index, collection) === false) {
return result;
}
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q9204
|
train
|
function(filepath){
filepath = filepath.replace(pathSepExp,'/'); // Use unix paths regardless. Makes these checks easier
if(filepath &&
(
( // If filepath has the jsIncludeDir, but does not include the node_modules directory under them
filepath.match(expressions.jsIncludeDir)
&& !filepath.match(expressions.jsExcludeDir)
)
// Or the filepath has nothing to do with node_modules, app_modules/vendor
|| !filepath.match(expressions.jsAlwaysIncludeDir)
|| filepath.match(/node_modules(\\|\/)@polymer|node_modules(\\|\/)@webcomponents(\\|\/)shadycss/)
)
) {
// console.log('===================================')
// console.log(filepath)
// console.log('### Transpiling: '+filepath);
return true;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9205
|
train
|
function(config, cb){
// This will tell webpack to create a new chunk
rq.ensure(['INDEX_PATH'],function(rq){
let library = rq('INDEX_PATH');
library = library.default || library; // To preven issues between versions
cb(
// Expected to export an initializing function
library(config)
);
},'NAME');
}
|
javascript
|
{
"resource": ""
}
|
|
q9206
|
getFormat
|
train
|
function getFormat(syntax, options) {
let format = syntaxFormat[syntax];
if (typeof format === 'string') {
format = syntaxFormat[format];
}
return Object.assign({}, format, options && options.format);
}
|
javascript
|
{
"resource": ""
}
|
q9207
|
train
|
function(newRoutes)
{
for(var key in newRoutes)
{
if(routes.hasOwnProperty(key))
{
if(typeof routes[key] == 'Array')
{
routes[key].push(newRoutes[key]);
}
else
{
routes[key] = [routes[key],newRoutes[key]];
}
}
else
{
routes[key] = newRoutes[key];
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9208
|
role_permissions
|
train
|
function role_permissions(roles, callback) {
var permissions = [],
fetch = [];
if (roles) {
// TODO: Here we could do with some caching like Drupal does.
roles.forEach(function (name, rid) {
fetch.push(rid);
});
// Get permissions for the rids.
if (fetch) {
db.query("SELECT rid, permission FROM role_permission WHERE rid IN ($1);", [fetch], function (err, rows) {
if (err) {
callback(err, null);
}
if (rows.length > 0) {
rows.forEach(function (row) {
permissions.push(row.permission);
});
}
callback(null, permissions);
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9209
|
access
|
train
|
function access(permission, account, callback) {
// User #1 has all privileges:
if (account.uid === 1) {
callback(null, true);
return;
}
// If permissions is already loaded, use them.
if (account.permissions) {
callback(null, account.permissions.indexOf(permission) > -1);
return;
}
role_permissions(account.roles, function (err, permissions) {
if (err) {
callback(err);
return;
}
callback(null, permissions.indexOf(permission) > -1);
});
}
|
javascript
|
{
"resource": ""
}
|
q9210
|
session_load
|
train
|
function session_load(sid, callback) {
var rows = [];
db.query("SELECT * FROM sessions WHERE sid = $1;", [sid], function (err, rows) {
if (err) {
callback(err, null);
return;
}
if (rows.length > 0) {
callback(null, rows[0]);
}
else {
callback('Session not found', null);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q9211
|
decode
|
train
|
function decode(object) {
var result = {};
// enumerable properties
for (var key in object) {
var value = object[key];
// nested object
if (value && (typeof value === 'object')) {
// instance
if (value.$class && value.$props) {
result[value] = assign(new classes.getDefinition(value.$class), decode(value.$props));
}
// plain object
else {
result[value] = decode(value);
}
}
// other
else {
result[value] = value;
}
}
// complete
return result;
}
|
javascript
|
{
"resource": ""
}
|
q9212
|
closestPointnd
|
train
|
function closestPointnd(c, positions, x, result) {
var D = numeric.rep([c.length, c.length], 0.0);
var dvec = numeric.rep([c.length], 0.0);
for(var i=0; i<c.length; ++i) {
var pi = positions[c[i]];
dvec[i] = numeric.dot(pi, x);
for(var j=0; j<c.length; ++j) {
var pj = positions[c[j]];
D[i][j] = D[j][i] = numeric.dot(pi, pj);
}
}
var A = numeric.rep([c.length, c.length+2], 0.0);
var b = numeric.rep([c.length+2], 0.0);
b[0] = 1.0-EPSILON;
b[1] = -(1.0+EPSILON);
for(var i=0; i<c.length; ++i) {
A[i][0] = 1;
A[i][1] = -1
A[i][i+2] = 1;
}
for(var attempts=0; attempts<15; ++attempts) {
var fortran_poop = numeric.solveQP(D, dvec, A, b);
if(fortran_poop.message.length > 0) {
//Quadratic form may be singular, perturb and resolve
for(var i=0; i<c.length; ++i) {
D[i][i] += 1e-8;
}
continue;
} else if(isNaN(fortran_poop.value[0])) {
break;
} else {
//Success!
var solution = fortran_poop.solution;
for(var i=0; i<x.length; ++i) {
result[i] = 0.0;
for(var j=0; j<solution.length; ++j) {
result[i] += solution[j] * positions[c[j]][i];
}
}
return 2.0 * fortran_poop.value[0] + numeric.dot(x,x);
}
}
for(var i=0; i<x.length; ++i) {
result[i] = Number.NaN;
}
return Number.NaN;
}
|
javascript
|
{
"resource": ""
}
|
q9213
|
train
|
function (subscriptions, fn, context) {
for (var id in subscriptions) {
for (var property in subscriptions[id]) {
fn.call(context, subscriptions[id][property], property, id);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9214
|
train
|
function (fn, update, container) {
// Alias passed in variables for later access.
this._fn = fn;
this._update = update;
this._container = container;
// Assign every subscription instance a unique id. This helps with linking
// between parent and child subscription instances.
this.cid = 'c' + Utils.uniqueId();
this.children = {};
this.subscriptions = {};
this.unsubscriptions = [];
// Create statically bound function instances for public consumption.
this.boundUpdate = Utils.bind(this.update, this);
this.boundUnsubscription = Utils.bind(this.unsubscription, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q9215
|
train
|
function (fn, create, update) {
var subscriber = new Subscription(fn, update, this);
// Immediately alias the starting value.
subscriber.value = subscriber.execute();
Utils.isFunction(create) && (subscriber.value = create(subscriber.value));
return subscriber;
}
|
javascript
|
{
"resource": ""
}
|
|
q9216
|
train
|
function (fn) {
var container = this;
var program = function () {
var subscriber = new Subscription(fn, null, container);
return subscriber.execute.apply(subscriber, arguments);
};
Utils.extend(program, fn);
return program;
}
|
javascript
|
{
"resource": ""
}
|
|
q9217
|
train
|
function (fn, create) {
return subscribe.call(this, fn, function (value) {
return Utils.trackNode(create(value));
}, function (value) {
this.value.replace(create(value));
}).value.fragment;
}
|
javascript
|
{
"resource": ""
}
|
|
q9218
|
train
|
function (fn, cb) {
return subscribe.call(this, fn, function (value) {
return VM.createElement(value);
}, function (value) {
cb(this.value = VM.setTagName(this.value, value));
}).value;
}
|
javascript
|
{
"resource": ""
}
|
|
q9219
|
train
|
function (currentEl, nameFn, valueFn) {
var attrName = subscribe.call(this, nameFn, null, function (value) {
VM.removeAttribute(currentEl(), this.value);
VM.setAttribute(currentEl(), this.value = value, attrValue.value);
});
var attrValue = subscribe.call(this, valueFn, null, function (value) {
VM.setAttribute(currentEl(), attrName.value, this.value = value);
});
return VM.setAttribute(currentEl(), attrName.value, attrValue.value);
}
|
javascript
|
{
"resource": ""
}
|
|
q9220
|
train
|
function (fn) {
return subscribe.call(this, fn, function (value) {
return VM.createComment(value);
}, function (value) {
this.value.textContent = value;
}).value;
}
|
javascript
|
{
"resource": ""
}
|
|
q9221
|
train
|
function(objectName)
{
var app = this;
var objectName = objectName.split(".");
var obj = {};
try
{
switch(objectName.length){
case 1:
for(var module in app.modules)
{
if(app.modules[module].models.hasOwnProperty(objectName[0]))
{
objectName[1]=objectName[0];
objectName[0]=module;
break;
}
}
break;
}
if(app.modules[objectName[0]].models.hasOwnProperty(objectName[1])){
obj = app.modules[objectName[0]].models[objectName[1]];
}else{
throw "not found";
}
}
catch(e)
{
switch(objectName.length){
case 1:
var modulePath = path.join(app._path,"modules");
fs.readdirSync(modulePath).forEach(function(moduleName){
var objFilePath = path.join(app._path,"modules",moduleName,"models",objectName[0]);
if(fs.existsSync(objFilePath+".js"))
{
if( app.modules.hasOwnProperty(moduleName) &&
app.modules[moduleName].hasOwnProperty('models') &&
app.modules[moduleName].models.hasOwnProperty(objectName[0])){
var obj = app.modules[moduleName].models[objectName[0]];
return obj;
}else{
var obj = require(objFilePath)(app);
if(typeof app.modules[moduleName] != "object") app.modules[moduleName]={};
if(typeof app.modules[moduleName].models != "object") app.modules[moduleName].models={};
}
app.modules[moduleName].models[objectName[0]] = obj;
}
});
break;
case 2:
var objFilePath = path.join(app._path,"modules",objectName[0],"models",objectName[1]);
if(fs.existsSync(objFilePath+".js"))
{
var obj = require(objFilePath)(app);
if(typeof app.modules[objectName[0]] != "object") app.modules[objectName[0]]={};
if(typeof app.modules[objectName[0]].models != "object") app.modules[objectName[0]].models={};
app.modules[objectName[0]].models[objectName[1]] = obj;
}
break;
}
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q9222
|
train
|
function(policyName)
{
var app = this;
var objectName = policyName;
var obj = {};
try
{
if(app.policies.hasOwnProperty(policyName)){
obj = app.policies[policyName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"policies",policyName);
if(fs.existsSync(objFilePath+".js"))
{
obj = require(objFilePath);
if(typeof app.policies != "object") app.policies={};
app.policies[policyName] = obj;
}
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q9223
|
train
|
function(roleName)
{
var app = this;
var role = {permissions:[]};
try
{
if(app.roles.hasOwnProperty(roleName)){
role = app.roles[roleName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"roles",roleName);
if(fs.existsSync(objFilePath+".js"))
{
var roleConfig = require(objFilePath);
if(typeof app.roles != "object") app.roles={};
app.roles[roleName]= roleConfig.permissions;
if(roleConfig.hasOwnProperty('isDefault') && roleConfig.isDefault == true){
app.defaultRoles.push(roleName);
}
role = roleConfig.permissions;
}
}
return role;
}
|
javascript
|
{
"resource": ""
}
|
|
q9224
|
train
|
function(exceptionName)
{
var app = this;
var exception = {};
try
{
if(app.exceptions.hasOwnProperty(exceptionName)){
exception = app.exceptions[exceptionName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"exceptions",exceptionName);
if(fs.existsSync(objFilePath+".js"))
{
var exceptionConfig = require(objFilePath);
if(typeof app.exceptions != "object") app.exceptions={};
app.exceptions[exceptionName]= exceptionConfig;
exception = exceptionConfig;
}
}
return exception;
}
|
javascript
|
{
"resource": ""
}
|
|
q9225
|
loadModule
|
train
|
function loadModule (actorPath) {
try {
let key = path.resolve(actorPath)
delete require.cache[ key ]
return require(actorPath)
} catch (err) {
log.error(`Error loading actor module at ${actorPath} with ${err.stack}`)
return undefined
}
}
|
javascript
|
{
"resource": ""
}
|
q9226
|
loadActors
|
train
|
function loadActors (fount, actors) {
let result
function addActor (acc, instance) {
let factory = isFunction(instance.state)
? instance.state : () => clone(instance.state)
processHandles(instance)
acc[ instance.actor.type ] = {
factory: factory,
metadata: instance
}
return acc
}
function onActors (list) {
function onInstances (instances) {
return instances.reduce(addActor, {})
}
let modules = filter(list)
let promises = modules.map((modulePath) => {
let actorFn = loadModule(modulePath)
return fount.inject(actorFn)
})
return Promise
.all(promises)
.then(onInstances)
}
if (isString(actors)) {
let filePath = actors
if (!fs.existsSync(filePath)) {
filePath = path.resolve(process.cwd(), filePath)
}
return getActors(filePath)
.then(onActors)
} else if (Array.isArray(actors)) {
result = actors.reduce((acc, instance) => {
addActor(acc, instance)
return acc
}, {})
return Promise.resolve(result)
} else if (isObject(actors)) {
let keys = Object.keys(actors)
result = keys.reduce((acc, key) => {
let instance = actors[ key ]
addActor(acc, instance)
return acc
}, {})
return Promise.resolve(result)
} else if (isFunction(actors)) {
result = actors()
if (!result.then) {
result = Promise.resolve(result)
}
return result.then(function (list) {
return list.reduce((acc, instance) => {
addActor(acc, instance)
return Promise.resolve(acc)
}, {})
})
}
}
|
javascript
|
{
"resource": ""
}
|
q9227
|
setContent
|
train
|
function setContent( content, options ) {
options = getOptions( options );
return vscode.workspace.openTextDocument( {
language: options.language
} )
.then( doc => vscode.window.showTextDocument( doc ) )
.then( editor => {
let editBuilder = textEdit => {
textEdit.insert( new vscode.Position( 0, 0 ), String( content ) );
};
return editor.edit( editBuilder, {
undoStopBefore: true,
undoStopAfter: false
} )
.then( () => editor );
} );
}
|
javascript
|
{
"resource": ""
}
|
q9228
|
init
|
train
|
function init(config) {
Object.keys(config).forEach(function (property) {
this[property] = config[property];
}, this);
}
|
javascript
|
{
"resource": ""
}
|
q9229
|
toDot
|
train
|
function toDot() {
var dotGraph = [];
dotGraph.push("digraph " + this.name + " {");
this.children.forEach(function (step) {
dotGraph.push(step.name);
step.dependencies.forEach(function (dependencyName) {
dotGraph.push(dependencyName + " -> " + step.name);
});
});
dotGraph.push("}");
console.debug("Put this in a file and run this in a terminal: dot -Tsvg yourDotFile > graph.svg");
return dotGraph.join("\n");
}
|
javascript
|
{
"resource": ""
}
|
q9230
|
train
|
function (nodeLikeObject) {
var node = this;
if (nodeLikeObject.hasOwnProperty('data') === true) {
setTimeout(function runFlowNode() {
node.code(nodeLikeObject);
}, 0);
}
else if (typeof this.errorCode !== 'undefined') {
setTimeout(function runFlowNodeError() {
node.errorCode(nodeLikeObject);
}, 0);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9231
|
train
|
function (data) {
this.data = data;
this.isFulfilled = true;
if (this.parent === null) {
return;
}
this.parent.dispatch(this.name);
}
|
javascript
|
{
"resource": ""
}
|
|
q9232
|
train
|
function (error) {
this.error = error;
this.isRejected = true;
if (this.parent === null) {
return;
}
this.parent.dispatch(this.name);
this.parent.dispatch('reject', {
data : { node : this, error: error }
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9233
|
tryVerify
|
train
|
function tryVerify (rawBytes) {
const {
tbsCertificate,
tbsCertificate: {
validity: {
notBefore: { value: notBefore },
notAfter: { value: notAfter }
}
},
signatureAlgorithm: { algorithm },
signature: { data: signature }
} = Certificate.decode(rawBytes, 'der')
// Require sha512WithRSAEncryption.
if (algorithm.join('.') !== '1.2.840.113549.1.1.13') {
return false
}
// Check if certificate is still valid.–
const now = Date.now()
if (now < notBefore || now > notAfter) {
return false
}
// Make sure the certificate was signed by CloudFlare's origin pull
// certificate authority.
const verifier = createVerify('RSA-SHA512')
verifier.update(TBSCertificate.encode(tbsCertificate, 'der'))
return verifier.verify(originPullCa, signature)
}
|
javascript
|
{
"resource": ""
}
|
q9234
|
parse
|
train
|
function parse(source) {
var moduleDefinitions = {},
moduleReferences = [];
estraverse.traverse(esprima.parse(source), {
leave: function (node, parent) {
if(!isAngular(node)) {
return;
}
//console.log('node:', JSON.stringify(node, null, 3));
//console.log('parent:', JSON.stringify(parent, null, 3));
var moduleName = parent.arguments[0].value;
// if a second argument exists
// this is a module definition
if(parent.arguments[1]) {
if(parent.arguments[1].type === 'ArrayExpression') {
moduleDefinitions[moduleName] = parent.arguments[1].elements.map(function(item){
return item['value'];
});
} else {
throw 'Argument must be an ArrayExpression, not a variable';
}
} else {
// is a module reference
pushDistinct(moduleReferences, moduleName);
}
}
});
return {
modules: moduleDefinitions,
references: moduleReferences
}
}
|
javascript
|
{
"resource": ""
}
|
q9235
|
View
|
train
|
function View() {
Object.defineProperty(this, '__private', { writable: true, value: {}, });
this.__private.isRenderRequested = false;
var delegates = this.__private.eventDelegates = {};
this.__private.onDelegatedEvent = function onDelegatedEvent(ev) {
var delegatesForEvent = delegates[ev.type];
var el = ev.target;
for (var selectorStr in delegatesForEvent) {
if (!elMatchesSelector(el, selectorStr)) { continue; }
var delegatesForEventAndSelector = delegatesForEvent[selectorStr];
for (var i = 0, n = delegatesForEventAndSelector.length; i < n; ++i) {
delegatesForEventAndSelector[i](ev);
}
}
};
/**
* The root DOM element of the view. The default implementation of {@link module:bff/view#render} assigns to and updates this element. Delegated event listeners, created by calling {@link module:bff/view#listenTo} are attached to this element.
* Replacing the current element with another will clear all currently delegated event listeners - it is usually a better approach update the element (using e.g. {@link module:bff/patch-dom}) instead of replacing it.
* @instance
* @member {HTMLElement|undefined} el
*/
Object.defineProperty(this, 'el', {
enumerable: true,
get: function () { return this.__private.el; },
set: function (el) {
this.stopListening('*');
this.__private.el = el;
}
});
this.__private.childViews = new List();
this.listenTo(this.__private.childViews, 'item:destroyed', function (childView) {
this.__private.childViews.remove(childView);
});
/**
* A list of this view's child views. Initially empty.
* @instance
* @member {module:bff/list} children
*/
Object.defineProperty(this, 'children', {
enumerable: true,
get: function () { return this.__private.childViews; },
});
}
|
javascript
|
{
"resource": ""
}
|
q9236
|
train
|
function (htmlString, returnAll) {
if (RUNTIME_CHECKS) {
if (typeof htmlString !== 'string') {
throw '"htmlString" argument must be a string';
}
if (arguments.length > 1 && typeof returnAll !== 'boolean') {
throw '"returnAll" argument must be a boolean value';
}
}
HTML_PARSER_EL.innerHTML = htmlString;
if (RUNTIME_CHECKS && !returnAll && HTML_PARSER_EL.children.length > 1) {
throw 'The parsed HTML contains more than one root element.' +
'Specify returnAll = true to return all of them';
}
var ret = returnAll ? HTML_PARSER_EL.children : HTML_PARSER_EL.firstChild;
while (HTML_PARSER_EL.firstChild) {
HTML_PARSER_EL.removeChild(HTML_PARSER_EL.firstChild);
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q9237
|
train
|
function (childView, el) {
if (RUNTIME_CHECKS) {
if (!(childView instanceof View)) {
throw '"childView" argument must be a BFF View';
}
if (arguments.length > 1 && !(el === false || el instanceof HTMLElement)) {
throw '"el" argument must be an HTMLElement or the boolean value false';
}
}
this.__private.childViews.push(childView);
el !== false && (el || this.el).appendChild(childView.el);
return childView;
}
|
javascript
|
{
"resource": ""
}
|
|
q9238
|
train
|
function () {
// Iterate backwards because the list might shrink while being iterated
for (var i = this.__private.childViews.length - 1; i >= 0; --i) {
this.__private.childViews[i].destroy();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9239
|
createCache
|
train
|
function createCache(array) {
var index = -1,
length = array.length;
var cache = getObject();
cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;
var result = getObject();
result.array = array;
result.cache = cache;
result.push = cachePush;
while (++index < length) {
result.push(array[index]);
}
return cache.object === false
? (releaseObject(result), null)
: result;
}
|
javascript
|
{
"resource": ""
}
|
q9240
|
getIndexOf
|
train
|
function getIndexOf(array, value, fromIndex) {
var result = (result = lodash.indexOf) === indexOf ? basicIndexOf : result;
return result;
}
|
javascript
|
{
"resource": ""
}
|
q9241
|
train
|
function () {
return new Promise(function (resolve, reject) {
var rotations = [];
for (var i = 0; i < spotlightRotations.length; i++) {
var now = new Date();
var daysToAdd = 3 * i;
now.setDate(now.getDate() + daysToAdd);
var currentSpotlight = Math.floor((((Math.floor((now / 1000) / (24 * 60 * 60))) - 49) % (3 * spotlightRotations.length)) / 3);
var daysUntilNext = (3 - ((Math.floor((now / 1000) / (24 * 60 * 60))) - 49) % (3 * spotlightRotations.length) % 3) + daysToAdd;
var start = new Date();
start.setDate(start.getDate() + (daysUntilNext - 3));
var obj = {
rotation: spotlightRotations[currentSpotlight],
daysUntilNext: daysUntilNext,
startDate: start
};
rotations.push(obj);
}
resolve(rotations);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9242
|
prune
|
train
|
function prune(code) {
var ast = esprima.parse(code);
estraverse.replace(ast, {
leave: function leave(node, parent) {
var ret;
if ('IfStatement' === node.type) {
if ('BinaryExpression' !== node.test.type) return;
if ('self' === node.test.left.argument.name) {
node.alternate = null;
} else if ('global' === node.test.left.argument.name) {
ret = node.alternate;
}
return ret;
}
if (
'BlockStatement' === node.type
&& 'FunctionExpression' === parent.type
) {
return node.body[0].alternate.alternate;
}
}
});
return escodegen.generate(ast, {
format: {
indent: { style: ' ' },
semicolons: false,
compact: true
}
});
}
|
javascript
|
{
"resource": ""
}
|
q9243
|
createStream
|
train
|
function createStream() {
var firstChunk = true;
var stream = through(function transform(chunk, encoding, next) {
if (!firstChunk) return next(null, chunk);
firstChunk = false;
var regex = /^(.+?)(\(function\(\)\{)/
, pattern;
chunk = chunk.toString().replace(regex, function replacer(match, p1, p2) {
pattern = p1;
return p2;
});
this.push(prune(pattern) + chunk);
next();
});
stream.label = 'prune-umd';
return stream;
}
|
javascript
|
{
"resource": ""
}
|
q9244
|
deumdify
|
train
|
function deumdify(browserify) {
//
// Bail out if there is no UMD wrapper.
//
if (!browserify._options.standalone) return;
browserify.pipeline.push(createStream());
browserify.on('reset', function reset() {
browserify.pipeline.push(createStream());
});
}
|
javascript
|
{
"resource": ""
}
|
q9245
|
Raven
|
train
|
function Raven() {
/**
* Pull from the rs forums...this can easily break if they stop using the version 4 of the thread
* http://services.runescape.com/m=forum/forums.ws?75,76,387,65763383
* @returns {Promise} current viswax
* @example
* rsapi.rs.distraction.viswax.getCurrent().then(function(vis) {
* console.log(vis);
* }).catch(console.error);
*/
this.getCurrent = function() {
return new Promise(function (resolve, reject) {
let spawned = false;
let daysUntilNext = 0;
let found = (((Math.floor((Date.now() / 1000) / (24 * 60 * 60))) + 7) % 13);
if (found < 1) {
daysUntilNext = 1 - found;
spawned = true;
}
else {
daysUntilNext = 13 - found;
spawned = false;
}
resolve({
isSpawned: spawned,
daysUntilNext: daysUntilNext
});
});
}
}
|
javascript
|
{
"resource": ""
}
|
q9246
|
handleFailure
|
train
|
function handleFailure (handler) {
return (state, action) => isFailureAction(action) ? handler(state, action, getDataFromAction(action)) : state
}
|
javascript
|
{
"resource": ""
}
|
q9247
|
hash
|
train
|
function hash(password, options) {
options = options || {};
const blocksize = options.blocksize || defaults.blocksize;
const cost = options.cost || defaults.cost;
const parallelism = options.parallelism || defaults.parallelism;
const saltSize = options.saltSize || defaults.saltSize;
// Blocksize Validation
if (typeof blocksize !== 'number' || !Number.isInteger(blocksize)) {
return Promise.reject(
new TypeError("The 'blocksize' option must be an integer")
);
}
if (blocksize < 1 || blocksize > MAX_UINT32) {
return Promise.reject(
new TypeError(
`The 'blocksize' option must be in the range (1 <= blocksize <= ${MAX_UINT32})`
)
);
}
// Cost Validation
if (typeof cost !== 'number' || !Number.isInteger(cost)) {
return Promise.reject(
new TypeError("The 'cost' option must be an integer")
);
}
const maxcost = (128 * blocksize) / 8 - 1;
if (cost < 2 || cost > maxcost) {
return Promise.reject(
new TypeError(
`The 'cost' option must be in the range (1 <= cost <= ${maxcost})`
)
);
}
// Parallelism Validation
if (typeof parallelism !== 'number' || !Number.isInteger(parallelism)) {
return Promise.reject(
new TypeError("The 'parallelism' option must be an integer")
);
}
const maxpar = Math.floor(((Math.pow(2, 32) - 1) * 32) / (128 * blocksize));
if (parallelism < 1 || parallelism > maxpar) {
return Promise.reject(
new TypeError(
`The 'parallelism' option must be in the range (1 <= parallelism <= ${maxpar})`
)
);
}
// Salt Size Validation
if (saltSize < 8 || saltSize > 1024) {
return Promise.reject(
new TypeError(
"The 'saltSize' option must be in the range (8 <= saltSize <= 1023)"
)
);
}
const params = {
N: Math.pow(2, cost),
r: blocksize,
p: parallelism
};
const keylen = 32;
return gensalt(saltSize).then(salt => {
return scrypt.hash(password, params, keylen, salt).then(hash => {
const phcstr = phc.serialize({
id: 'scrypt',
params: {
ln: cost,
r: blocksize,
p: parallelism
},
salt,
hash
});
return phcstr;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9248
|
getName
|
train
|
function getName(candidate) {
var proto = getProto(candidate),
isValid = !!proto && !isPlainObject(candidate) && !Array.isArray(candidate);
if (isValid) {
for (var key in require.cache) {
var exports = require.cache[key].exports,
result = isPlainObject(exports) ? Object.keys(exports).reduce(test.bind(null, key), null) : test(key);
if (result) {
return result;
}
}
}
return null;
function test(filename, result, field) {
if (result) {
return result;
} else {
var candidate = field ? exports[field] : exports,
qualified = [filename, field].filter(Boolean).join('::'),
isDefinition = (typeof candidate === 'function') && !!candidate.prototype &&
(typeof candidate.prototype === 'object') && (candidate.prototype === proto);
return isDefinition && qualified || null;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9249
|
getDefinition
|
train
|
function getDefinition(name) {
var split = name.split('::'),
path = split[0],
field = split[1],
exported = (path in require.cache) && require.cache[path].exports,
definition = !!exported && (field ? exported[field] : exported);
return !!definition && !!getProto(definition) && definition || null;
}
|
javascript
|
{
"resource": ""
}
|
q9250
|
Player
|
train
|
function Player(config) {
/**
* Gets a users hiscores and activities (available for `rs` / `osrs`)
* @param username {String} Display name of the user
* @param type {String} [Optional] normal, ironman, hardcore/ultimate
* @returns {Promise} Object of the users hiscores and activities
* @example
* // returns Sync's RS stats and activities
* rsapi.rs.player.hiscores('sync').then(function(stats) {
* console.log(stats);
* }).catch(console.error);
*
* // returns Sausage's RS stats and activities from the ironman game type
* api.rs.hiscores.player('sausage', 'ironman').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns Sausage's RS stats and activities from the hardcore ironman game type
* api.rs.hiscores.player('sausage', 'hardcore').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns hey jase's Old School RS stats and activities
* api.osrs.hiscores.player('hey jase').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns lezley's Old School RS stats and activities from the ironman game type
* api.osrs.hiscores.player('lezley', 'ironman').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns perm iron's Old School RS stats and activities from the ultimate ironman game type
* api.osrs.hiscores.player('perm iron', 'ultimate').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*/
this.hiscores = function (username, type) {
return new Hiscores(username, config.hiscores).lookup(type);
};
/**
* Gets a users events log (aka adventure log) (available for `rs`)
* @param username {String} Display name of the user
* @returns {Promise} Object of the users events log
* @example
* // returns Sync's events / adventure log
* rsapi.rs.player.events('sync').then(function(stats) {
* console.log(stats);
* }).catch(console.error);
*/
this.events = function (username) {
return new Events(username, config.events).lookup();
}
/**
* Returns the input user(s) clan, title, if the clan is recruiting, if the title is a suffix, as well as online status
* if process.env.username and process.env.password are configured to a valid RS sign-in
* @param usernames {string|array} String of a single username or array of multiple to lookup
* @returns {Promise} Object of the users player details
* @example
* rsapi.rs.player.details(['sync','xredfoxx']).then(function(details) {
* console.log(details);
* }).catch(console.error);
*/
this.details = function (usernames) {
return new Promise(function (resolve, reject) {
var names = [];
if (typeof usernames === 'string') {
names.push(usernames);
}
else if (typeof usernames === 'object') {
names = usernames;
}
else {
var jsonError = new Error('Unrecognized input for usernames. Should be a string or array.');
reject(jsonError);
}
request.createSession().then( function(session) {
request.jsonp(config.urls.playerDetails + JSON.stringify(names), session).then(resolve).catch(reject);
}
).catch(console.error);
});
}
/**
* Return RuneMetrics profile for user
* @param usernames
* @returns {Promise} Object of the users player profile
* @example
* rsapi.rs.player.profile('sync').then(function(profile) {
* console.log(profile);
* }).catch(console.error);
*/
this.profile = function(usernames) {
return new Profile(usernames, config).lookup();
}
}
|
javascript
|
{
"resource": ""
}
|
q9251
|
toAbsolute
|
train
|
function toAbsolute(id) {
return id.startsWith("./") ? path.resolve(id) : require.resolve(id)
}
|
javascript
|
{
"resource": ""
}
|
q9252
|
stripNamespace
|
train
|
function stripNamespace (requestKey) {
return requestKey.startsWith(LP_API_ACTION_NAMESPACE)
? requestKey.slice(LP_API_ACTION_NAMESPACE.length)
: requestKey
}
|
javascript
|
{
"resource": ""
}
|
q9253
|
deepBind
|
train
|
function deepBind(target, thisArg, options) {
if (!isObject(target)) {
throw new TypeError('expected an object');
}
options = options || {};
for (var key in target) {
var fn = target[key];
if (typeof fn === 'object') {
target[key] = deepBind(fn, thisArg);
} else if (typeof fn === 'function') {
target[key] = bind(thisArg, key, fn, options);
// copy function keys
for (var k in fn) {
target[key][k] = fn[k];
}
} else {
target[key] = fn;
}
}
return target;
}
|
javascript
|
{
"resource": ""
}
|
q9254
|
handleResponse
|
train
|
function handleResponse (successHandler, failureHandler) {
if (!(successHandler && failureHandler)) throw new Error('handleResponse requires both a success handler and failure handler.')
return (state, action) => {
if (isSuccessAction(action)) return successHandler(state, action, getDataFromAction(action))
if (isFailureAction(action)) return failureHandler(state, action, getDataFromAction(action))
return state
}
}
|
javascript
|
{
"resource": ""
}
|
q9255
|
buildTable
|
train
|
function buildTable(search) {
// Based on https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm#Description_of_pseudocode_for_the_table-building_algorithm
var table = Array(search.length), pos = 2, cnd = 0, searchLen = search.length;
table[0] = -1;
table[1] = 0;
while (pos < searchLen) {
if (search[pos-1] === search[cnd]) {
// the substring continues
cnd++;
table[pos] = cnd;
pos++;
} else if (cnd > 0) {
// it doesn't, but we can fall back
cnd = table[cnd];
} else {
// we have run part of candidates. Note cnd = 0
table[pos] = 0;
pos++;
}
}
return table;
}
|
javascript
|
{
"resource": ""
}
|
q9256
|
actionCreator
|
train
|
function actionCreator(modelName, actionName) {
return data => (
dispatch({
type: getFullTypeName(modelName, actionName),
data
})
)
}
|
javascript
|
{
"resource": ""
}
|
q9257
|
train
|
function (eventEmitters, eventNames, callback, context, useCapture) {
if (RUNTIME_CHECKS) {
if (!eventEmitters || !(eventEmitters.addEventListener || eventEmitters instanceof Array)) {
throw '"eventEmitters" argument must be an event emitter or an array of event emitters';
}
if (typeof eventNames !== 'string' && !(eventNames instanceof Array)) {
throw '"eventNames" argument must be a string or an array of strings';
}
if (typeof callback !== 'function') {
throw '"callback" argument must be a function';
}
if (arguments.length > 4 && typeof useCapture !== 'boolean') {
throw '"useCapture" argument must be a boolean value';
}
}
// Convenience functionality that allows you to listen to all items in an Array or NodeList
// BFF Lists have this kind of functionality built it, so don't handle that case here
eventEmitters = eventEmitters instanceof Array ||
(typeof NodeList !== 'undefined' && eventEmitters instanceof NodeList) ? eventEmitters : [ eventEmitters ];
eventNames = eventNames instanceof Array ? eventNames : [ eventNames ];
for (var i = 0; i < eventEmitters.length; ++i) {
for (var j = 0; j < eventNames.length; ++j) {
setupListeners(this, eventEmitters[i], eventNames[j], callback, context, !!useCapture);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9258
|
train
|
function (eventEmitter, eventName) {
if (RUNTIME_CHECKS) {
if (!!eventEmitter && !eventEmitter.addEventListener) {
throw '"eventEmitter" argument must be an event emitter';
}
if (arguments.length > 1 && typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
}
if (!this.__private || !this.__private.listeningTo) { return; } // Not listening to anything? We are done.
var eventNames = eventName ? {} : this.__private.listeningTo;
eventName && (eventNames[eventName] = true);
for (eventName in eventNames) {
var listeningToList = this.__private.listeningTo[eventName];
if (!listeningToList) { continue; }
filterList(listeningToList, eventName, eventEmitter);
listeningToList.length || (delete this.__private.listeningTo[eventName]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9259
|
train
|
function (data) {
var items = [];
data.forEach(function (d, i) {
if (d.includes('ITEM:') && d.length > 3) {
var iid = data[i + 1];
var item = {
item: {
id: Number(iid[1].trim()),
name: d[2].replace(/_/g, ' '),
price: d[3],
change: d[4]
}
};
items.push(item);
}
});
return items;
}
|
javascript
|
{
"resource": ""
}
|
|
q9260
|
train
|
function(pagedef, pagedir){
var filenameBase = pagedir + pagedef.uniqueId;
var xmlDef = {ext: '.xml', contents: pd.xml(pagedef.body)};
var metaDef = {
ext: '.json',
contents: JSON.stringify(_.omit(pagedef, 'body'), null, 3)
};
_.each([xmlDef, metaDef], function(item){
var filename = filenameBase + item.ext;
grunt.file.write(filenameBase + item.ext, item.contents);
if(grunt.option('verbose')){
grunt.log.ok(filename + ' written to ' + pagedir);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9261
|
parseAlternateMappingsCall
|
train
|
function parseAlternateMappingsCall(node, output) {
var firstArgument = node.expression.arguments[0];
if (firstArgument && firstArgument.type === 'ObjectExpression') {
firstArgument.properties.forEach(function(prop) {
var aliasClassNames = getPropertyValue(prop); // Could be a string or an array of strings
if (aliasClassNames && aliasClassNames.length > 0) {
var className = prop.key.value;
if (! output.aliasNames) {
output.aliasNames = {};
}
if (typeof aliasClassNames === 'string') {
aliasClassNames = [ aliasClassNames ];
}
var existingAliasClassNames = output.aliasNames[className];
if (existingAliasClassNames) {
aliasClassNames = existingAliasClassNames.concat(aliasClassNames);
}
output.aliasNames[className] = unique(aliasClassNames);
}
});
if (options.optimizeSource) {
// Remove `uses` from parsed file
node.update('/* call to Ext.ClassManager.addNameAlternateMappings removed */');
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9262
|
parseLoaderSetPathCall
|
train
|
function parseLoaderSetPathCall(node, output) {
// Example: `Ext.Loader.setPath('Ext.ux', 'lib/extjs-ux/src');`
var classPrefixArg = node.expression.arguments[0];
var pathArg = node.expression.arguments[1];
if (classPrefixArg && pathArg) {
addResolvePath(classPrefixArg.value, pathArg.value, output);
}
}
|
javascript
|
{
"resource": ""
}
|
q9263
|
fontsmith
|
train
|
function fontsmith(params, cb) {
// Collect paths
var files = params.src,
retObj = {};
// TODO: Allow specification of engine when we have more
// TODO: By default, use an `auto` engine which falls back through engines until it finds one.
// Load in our engine and assert it exists
var engine = engines['icomoon-phantomjs'];
assert(engine, 'fontsmith engine "icomoon-phantomjs" could not be loaded. Please verify its dependencies are satisfied.');
// In series
var palette;
async.waterfall([
// Create an engine to work with
function createEngine (cb) {
// TODO; Figure out what the options will be / where they come from
engine.create({}, cb);
},
// Save the palette for external reference
function savePalette (_palette, cb) {
palette = _palette;
cb();
},
// TODO: Each SVG might have a specified character
// TODO: This is the equivalent of a custom `layout` as defined in spritesmith
// Add in our svgs
function addSvgs (cb) {
// DEV: If we ever run into perf issue regarding this, we should make this a batch function as in spritesmith
async.forEach(files, palette.addSvg.bind(palette), cb);
},
// Export the resulting fonts/map
function exportFn (cb) {
// Format should be {map:{'absolute/path':'\unicode'}, fonts: {svg:'binary', ttf:'binary'}}
palette['export'](params.exportOptions || {}, cb);
}
], cb);
}
|
javascript
|
{
"resource": ""
}
|
q9264
|
train
|
function () {
/**
* Return the current timestamp integer.
*/
var now = Date.now || function () {
return new Date().getTime();
};
// Keep track of the previous "animation frame" manually.
var prev = now();
return function (fn) {
var curr = now();
var ms = Math.max(0, 16 - (curr - prev));
var req = setTimeout(fn, ms);
prev = curr;
return req;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q9265
|
Question
|
train
|
function Question(name, message, options) {
debug('initializing from <%s>', __filename);
if (arguments.length === 0) {
throw new TypeError('expected a string or object');
}
if (Question.isQuestion(name)) {
return name;
}
this.type = 'input';
this.options = {};
this.getDefault();
if (Array.isArray(message)) {
options = { choices: message };
message = name;
}
if (Array.isArray(options)) {
options = { choices: options };
}
define(this, 'Choices', Choices);
define(this, 'isQuestion', true);
utils.assign(this, {
name: name,
message: message,
options: options
});
}
|
javascript
|
{
"resource": ""
}
|
q9266
|
addLineHints
|
train
|
function addLineHints(name, content) {
var
i = -1,
lines = content.split('\n'),
len = lines.length,
out = []
;
while (++i < len) {
out.push(lines[i] +
((i % 10 === 9) ? ' //' + name + ':' + (i + 1) + '//' : ''));
}
return out.join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q9267
|
joinBuffers
|
train
|
function joinBuffers(buffers) {
var
i = -1, j = -1,
num = buffers.length,
totalBytes = 0,
bytesWritten = 0,
buff,
superBuff
;
while (++i < num) {
totalBytes += buffers[i].length;
}
superBuff = new Buffer(totalBytes);
while (++j < num) {
buff = buffers[j];
buff.copy(superBuff, bytesWritten, 0);
bytesWritten += buff.length;
}
return superBuff;
}
|
javascript
|
{
"resource": ""
}
|
q9268
|
wget
|
train
|
function wget(fileURL, callback) {
var
chunks = [],
isHTTPS = fileURL.indexOf('https') === 0,
client = isHTTPS ? https : http,
options = fileURL
;
if (isHTTPS) {
options = url.parse(fileURL);
options.rejectUnauthorized = false;
options.agent = new https.Agent(options);
}
client.get(options, function (res) {
res.on('data', function (chunk) {
chunks.push(chunk);
}).on('end', function () {
callback(null, joinBuffers(chunks));
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9269
|
reduce
|
train
|
function reduce(map, path) {
var mapNode, prefix, split, splits = getResourcePathSplits(path),
subValue, suffix;
while (splits.length) {
split = splits.shift();
suffix = split[1];
prefix = suffix ? split[0] + '/' : split[0];
mapNode = map[prefix];
if (mapNode) {
if (!suffix || typeof mapNode === 'string') {
return { map: mapNode, prefix: prefix, suffix: suffix };
}
if (typeof mapNode === 'object') {
subValue = reduce(mapNode, suffix);
if (subValue) {
subValue.prefix = prefix + '/' + subValue.prefix;
return subValue;
}
}
}
}
return { map: map, prefix: '', suffix: path };
}
|
javascript
|
{
"resource": ""
}
|
q9270
|
getResource
|
train
|
function getResource(map, base, internal, path, callback, addLineHints) {
var
reduced = reduce(map, path),
reducedMap = reduced.map,
reducedMapType = nodeType(reducedMap),
reducedPrefix = reduced.prefix,
reducedSuffix = reduced.suffix,
firstChar = path.charAt(0),
temporary = firstChar === '~',
literal = firstChar === '='
;
if (isURL(path)) {
wget(path, callback);
} else if (literal) {
callback(null, new Buffer(path.substr(1) + '\n'));
} else if (temporary && !internal) {
// External request for a temporary resource.
callback({ code: 403, message: 'Forbidden' });
} else if (reducedSuffix) {
// We did NOT find an exact match in the map.
if (!reducedPrefix && internal) {
getFile(base, path, callback, addLineHints);
} else if (reducedMapType === 'string') {
getFile(base, reducedMap + '/' + reducedSuffix, callback, addLineHints);
} else {
callback({ code: 404, message: 'Not Found' });
}
} else {
// We found an exact match in the map.
if (reducedMap === reducedPrefix) {
// This is just a local file/dir to expose.
getFile(base, reducedPrefix, callback, addLineHints);
} else if (reducedMapType === 'string') {
// A string value may be a web URL.
if (isURL(reducedMap)) {
wget(reducedMap, callback);
} else {
// Otherwise, it's another resource path.
getResource(map, base, true, reducedMap, callback, addLineHints);
}
} else if (reducedMapType === 'array') {
// An array is a list of resources to get packed together.
packResources(map, base, reducedMap, callback);
//} else if (reducedMapType === 'object') {
// An object is a directory. We could return a listing...
// TODO: Do we really want to support listings?
} else {
callback({ code: 500, message: 'Unable to read gravity.map.' });
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9271
|
synchronize
|
train
|
function synchronize (items, cb) {
return items.reduce(function (promise, item) {
return promise.then(function () {
return cb.call(this, item)
})
}, RSVP.resolve())
}
|
javascript
|
{
"resource": ""
}
|
q9272
|
train
|
function () {
var promptRemove = this._promptRemove.bind(this)
var removeFile = this._removeFile.bind(this)
var ui = this.ui
return this._findConfigFiles()
.then(function (files) {
if (files.length === 0) {
ui.writeLine('No JSHint or ESLint config files found.')
return RSVP.resolve({
result: {
deleteFiles: 'none'
}
})
}
ui.writeLine('\nI found the following JSHint and ESLint config files:')
files.forEach(function (file) {
ui.writeLine(' ' + file)
})
var promptPromise = ui.prompt({
type: 'list',
name: 'deleteFiles',
message: 'What would you like to do?',
choices: [
{ name: 'Remove them all', value: 'all' },
{ name: 'Remove individually', value: 'each' },
{ name: 'Nothing', value: 'none' }
]
})
return RSVP.hash({
result: promptPromise,
files: files
})
}).then(function (data) {
var value = data.result.deleteFiles
var files = data.files
// Noop if we're not deleting any files
if (value === 'none') {
return RSVP.resolve()
}
if (value === 'all') {
return RSVP.all(files.map(function (fileName) {
return removeFile(fileName)
}))
}
if (value === 'each') {
return synchronize(files, function (fileName) {
return promptRemove(fileName)
})
}
})
}
|
javascript
|
{
"resource": ""
}
|
|
q9273
|
train
|
function () {
var projectRoot = this.project.root
var ui = this.ui
ui.startProgress('Searching for JSHint and ESLint config files')
return new RSVP.Promise(function (resolve) {
var files = walkSync(projectRoot, {
globs: ['**/.jshintrc', '**/.eslintrc.js'],
ignore: [
'**/bower_components',
'**/dist',
'**/node_modules',
'**/tmp'
]
})
ui.stopProgress()
resolve(files)
})
}
|
javascript
|
{
"resource": ""
}
|
|
q9274
|
train
|
function (filePath) {
var removeFile = this._removeFile.bind(this)
var message = 'Should I remove `' + filePath + '`?'
var promptPromise = this.ui.prompt({
type: 'confirm',
name: 'answer',
message: message,
choices: [
{ key: 'y', name: 'Yes, remove it', value: 'yes' },
{ key: 'n', name: 'No, leave it there', value: 'no' }
]
})
return promptPromise.then(function (response) {
if (response.answer) {
return removeFile(filePath)
} else {
return RSVP.resolve()
}
})
}
|
javascript
|
{
"resource": ""
}
|
|
q9275
|
train
|
function (filePath) {
var projectRoot = this.project.root
var fullPath = resolve(projectRoot, filePath)
return RSVP.denodeify(unlink)(fullPath)
}
|
javascript
|
{
"resource": ""
}
|
|
q9276
|
parseOptions
|
train
|
function parseOptions ({
type,
onUnauthorized,
actions,
types,
requestAction,
successAction,
failureAction,
isStub,
stubData,
adapter,
...requestOptions
}) {
return {
configOptions: omitUndefined({
type,
onUnauthorized,
actions,
types,
requestAction,
successAction,
failureAction,
isStub,
stubData,
adapter,
}),
requestOptions,
}
}
|
javascript
|
{
"resource": ""
}
|
q9277
|
dive
|
train
|
function dive(name) {
// check if this module has already been
// processed in case of circular dependency
if (dive[name]) {
return;
}
dive[name] = true;
dive.required.push(name);
var deps = allModules[name] || [];
deps.forEach(function (item) {
dive(item);
});
}
|
javascript
|
{
"resource": ""
}
|
q9278
|
getClient
|
train
|
function getClient(callback) {
if (!connectionOptions) {
callback('Connection options missing. Please call db.connect before any other database functions to configure the database configuration');
}
if (activeBackend === 'mysql') {
if (activeDb) {
return callback(null, activeDb);
}
else {
connect(connectionOptions);
return callback(null, activeDb);
}
}
else if (activeBackend === 'pgsql') {
return pg.connect(connectionOptions, callback);
}
}
|
javascript
|
{
"resource": ""
}
|
q9279
|
runQuery
|
train
|
function runQuery(client, queryString, args, callback) {
if (activeBackend === 'mysql') {
queryString = queryString.replace(/\$\d+/, '?');
}
client.query(queryString, args, function (err, result) {
if (err) {
callback(err, null);
return;
}
if (activeBackend === 'mysql') {
callback(err, result);
}
else if (activeBackend === 'pgsql') {
var rows = [];
if (result.rows) {
rows = result.rows;
}
callback(err, rows);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q9280
|
errorJSON
|
train
|
function errorJSON (err) {
var res = {}
Object.getOwnPropertyNames(err).forEach(function (key) {
res[key] = err[key]
}, err)
return res
}
|
javascript
|
{
"resource": ""
}
|
q9281
|
getCLFOffset
|
train
|
function getCLFOffset(date) {
const offset = date.getTimezoneOffset().toString();
const op = offset[0] === '-' ? '-' : '+';
let number = offset.replace(op, '');
while (number.length < 4) {
number = `0${number}`;
}
return `${op}${number}`;
}
|
javascript
|
{
"resource": ""
}
|
q9282
|
traverseBreadthFirst
|
train
|
function traverseBreadthFirst(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, callback, userdata) { callback(); },
onComplete: function(rootNode) {},
userdata: null
}, options);
var queue = [];
queue.push([rootNode, options.userdata]);
(function next() {
if (queue.length == 0) {
options.onComplete(rootNode);
return;
}
var front = queue.shift();
var node = front[0];
var data = front[1];
options.onNode(node, function() {
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
async.eachSeries(subnodes,
function(subnode, nextNode) {
queue.push([subnode, subnodeData]);
async.setImmediate(nextNode);
},
function() {
async.setImmediate(next);
}
);
},
data);
})();
}
|
javascript
|
{
"resource": ""
}
|
q9283
|
traverseBreadthFirstSync
|
train
|
function traverseBreadthFirstSync(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, userdata) {},
userdata: null
}, options);
var queue = [];
queue.push([rootNode, options.userdata]);
while (queue.length>0) {
var front = queue.shift();
var node = front[0];
var data = front[1];
options.onNode(node, data);
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
for (var i=0; i<subnodes.length; i++) {
queue.push([subnodes[i], subnodeData]);
}
}
return rootNode;
}
|
javascript
|
{
"resource": ""
}
|
q9284
|
traverseDepthFirst
|
train
|
function traverseDepthFirst(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, callback, userdata) { callback(); },
onComplete: function(rootNode) {},
userdata: null
}, options);
var stack = [];
stack.push([rootNode, options.userdata]);
(function next() {
if (stack.length == 0) {
options.onComplete(rootNode);
return;
}
var top = stack.pop();
var node = top[0];
var data = top[1];
options.onNode(node, function() {
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
async.eachSeries(subnodes,
function(subnode, nextNode) {
stack.push([subnode, subnodeData]);
async.setImmediate(nextNode);
},
function() {
async.setImmediate(next);
}
);
}, data);
})();
}
|
javascript
|
{
"resource": ""
}
|
q9285
|
traverseDepthFirstSync
|
train
|
function traverseDepthFirstSync(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, userdata) {},
userdata: null
}, options);
var stack = [];
stack.push([rootNode, options.userdata]);
while (stack.length>0) {
var top = stack.pop();
var node = top[0];
var data = top[1];
options.onNode(node, data);
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
for (var i=0; i<subnodes.length; i++)
stack.push([subnodes[i], subnodeData]);
}
return rootNode;
}
|
javascript
|
{
"resource": ""
}
|
q9286
|
traverseRecursive
|
train
|
function traverseRecursive(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
onNode: function(node, callback, userdata) {},
onComplete: function(rootNode) {},
userdata: null
}, options);
(function visitNode(node, callback) {
var subnodes = options.subnodesAccessor(node);
async.eachSeries(subnodes, function(subnode, next) {
visitNode(subnode, function() {
async.setImmediate(next);
});
},
function() {
options.onNode(node, function() {
async.setImmediate(callback);
}, options.userdata);
});
})(rootNode, function() {
options.onComplete(rootNode);
});
}
|
javascript
|
{
"resource": ""
}
|
q9287
|
traverseRecursiveSync
|
train
|
function traverseRecursiveSync(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
onNode: function(node, userdata) {},
userdata: null
}, options);
(function visitNode(node) {
var subnodes = options.subnodesAccessor(node);
for (var i=0; i<subnodes.length; i++) {
visitNode(subnodes[i]);
}
options.onNode(node, options.userdata);
})(rootNode);
return rootNode;
}
|
javascript
|
{
"resource": ""
}
|
q9288
|
Reporter
|
train
|
function Reporter (opts) {
this.events = opts.events;
this.config = opts.config;
this.testCount = 0;
this.testIdx = -1;
this.variationCount = -1;
this.data = {};
this.data.tests = [];
this.browser = null;
var defaultReportFolder = 'report';
this.dest = this.config.get('junit-reporter') && this.config.get('junit-reporter').dest ? this.config.get('junit-reporter').dest : defaultReportFolder;
// prepare base xml
this.xml = [
{
name: 'resource',
attrs: {
name:'DalekJSTest'
},
children: []
}
];
this.startListening();
}
|
javascript
|
{
"resource": ""
}
|
q9289
|
train
|
function (name) {
this.testCount = 0;
this.testIdx++;
this.xml[0].children.push({
name: 'testsuite',
children: [],
attrs: {
name: name + ' [' + this.browser + ']',
}
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9290
|
train
|
function (data) {
if (! data.success) {
//var timestamp = Math.round(new Date().getTime() / 1000);
this.xml[0].children[this.testIdx].children[this.testCount].children.push({
name: 'failure',
attrs: {
name: data.type,
message: (data.message ? data.message : 'Expected: ' + data.expected + 'Actual: ' + data.value)
}
});
//if (this.variationCount > -1 && this.xml[0].children[this.testIdx].children[this.testCount].children[this.variationCount]) {
//this.xml[0].children[this.testIdx].children[this.testCount].children[this.variationCount].attrs.end = timestamp;
//}
this.variationCount++;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9291
|
train
|
function (data) {
this.variationCount = -1;
this.xml[0].children[this.testIdx].children.push({
name: 'testcase',
children: [],
attrs: {
classname: this.xml[0].children[this.testIdx].attrs.name,
name: data.name
}
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9292
|
train
|
function () {
//var timestamp = Math.round(new Date().getTime() / 1000);
if (this._checkNodeAttributes(this.testIdx, this.testCount)) {
this.xml[0].children[this.testIdx].children[this.testCount].attrs = {};
}
//this.xml[0].children[this.testIdx].children[this.testCount].attrs.end = timestamp;
//this.xml[0].children[this.testIdx].children[this.testCount].attrs.result = data.status ? 'Passed' : 'Failed';
if (this.variationCount > -1) {
if (this._checkNodeAttributes(this.testIdx, this.testCount, this.variationCount)) {
this.xml[0].children[this.testIdx].children[this.testCount].children[this.variationCount].attrs = {};
}
//this.xml[0].children[this.testIdx].children[this.testCount].children[this.variationCount].attrs.end = timestamp;
}
this.testCount++;
this.variationCount = -1;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9293
|
train
|
function (data) {
this.data.elapsedTime = data.elapsedTime;
this.data.status = data.status;
this.data.assertions = data.assertions;
this.data.assertionsFailed = data.assertionsFailed;
this.data.assertionsPassed = data.assertionsPassed;
var contents = jsonxml(this.xml, {escape: true, removeIllegalNameCharacters: true, prettyPrint: true, xmlHeader: 'version="1.0" encoding="UTF-8"'});
if (path.extname(this.dest) !== '.xml') {
this.dest = this.dest + '/dalek.xml';
}
this.events.emit('report:written', {type: 'junit', dest: this.dest});
this._recursiveMakeDirSync(path.dirname(this.dest.replace(path.basename(this.dest, ''))));
fs.writeFileSync(this.dest, contents, 'utf8');
}
|
javascript
|
{
"resource": ""
}
|
|
q9294
|
train
|
function (path) {
var pathSep = require('path').sep;
var dirs = path.split(pathSep);
var root = '';
while (dirs.length > 0) {
var dir = dirs.shift();
if (dir === '') {
root = pathSep;
}
if (!fs.existsSync(root + dir)) {
fs.mkdirSync(root + dir);
}
root += dir + pathSep;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9295
|
train
|
function (testIdx, testCount, variationCount) {
if (variationCount === undefined) {
return typeof this.xml[0].children[testIdx].children[testCount].attrs === 'undefined';
}
return typeof this.xml[0].children[testIdx].children[testCount].children[variationCount].attrs === 'undefined';
}
|
javascript
|
{
"resource": ""
}
|
|
q9296
|
resolveFuture
|
train
|
function resolveFuture(reject, resolve) {
state = STARTED
return future.fork( function(error) { state = REJECTED
value = error
invokePending('rejected', error)
return reject(error) }
, function(data) { state = RESOLVED
value = data
invokePending('resolved', data)
return resolve(data) })}
|
javascript
|
{
"resource": ""
}
|
q9297
|
invokePending
|
train
|
function invokePending(kind, data) {
var xs = pending
pending.length = 0
for (var i = 0; i < xs.length; ++i) xs[i][kind](value) }
|
javascript
|
{
"resource": ""
}
|
q9298
|
train
|
function (val) {
return (!behavior.enableUndefined || typeof val !== 'undefined')
&& (!behavior.enableNull || val !== null)
&& (!behavior.enableFalse || val !== false)
&& (!behavior.enableNaN || !Number.isNaN(val));
}
|
javascript
|
{
"resource": ""
}
|
|
q9299
|
train
|
function (node) {
// Does this node have a body? If so we can replace its contents.
if (node.body && node.body.length) {
node.body =
[].slice.call(node.body, 0)
.reduce(function(body, node) {
if (!~allowedPrepend.indexOf(node.type))
return body.concat(node);
id++;
sourceMapAdd(id, node, true);
return body.concat(
expressionStatement(
callExpression(filetag, id)
),
node
);
}, []);
}
if (node.noReplace)
return;
// If we're allowed to replace the node,
// replace it with a Call Expression.
if (~allowedReplacements.indexOf(node.type))
return (
id ++,
sourceMapAdd(id, node, false),
callExpression(filetag, id, node)
);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.