_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q32700 | priorityFill | train | function priorityFill( callback ) {
var queue, prioritizedQueue;
queue = config.queue.slice( priorityFill.pos );
prioritizedQueue = config.queue.slice( 0, -config.queue.length + priorityFill.pos );
queue.unshift( callback );
queue.unshift.apply( queue, prioritizedQueue );
config.queue = queue;
priorityFill.pos += 1;
} | javascript | {
"resource": ""
} |
q32701 | train | function( count ) {
var test = this.test,
popped = false,
acceptCallCount = count;
if ( typeof acceptCallCount === "undefined" ) {
acceptCallCount = 1;
}
test.semaphore += 1;
test.usedAsync = true;
pauseProcessing();
return function done() {
if ( popped ) {
test.pushFailure( "Too many calls to the `assert.async` callback",
sourceFromStacktrace( 2 ) );
return;
}
acceptCallCount -= 1;
if ( acceptCallCount > 0 ) {
return;
}
test.semaphore -= 1;
popped = true;
resumeProcessing();
};
} | javascript | {
"resource": ""
} | |
q32702 | find | train | function find(dirname, args, cb) {
var spawned = execFile(
'/usr/bin/find',
['./'].concat(args),
{
maxBuffer: 4000*1024,
cwd: dirname,
},
execHandler(cb)
);
// Handle error
spawned.once('error', cb);
} | javascript | {
"resource": ""
} |
q32703 | modifiedSince | train | function modifiedSince(dirname, time, shouldPrune, cb) {
// Make sure time is in seconds
var timestr = Math.ceil(time + 1).toString();
var args = [
'-type', 'f',
// Modified less than time seconds ago
'-newermt',
timestr+' seconds ago',
];
if(shouldPrune) {
args = EXCLUDED_ARGS.concat(args);
}
// Run the command
find(dirname, args, cb);
} | javascript | {
"resource": ""
} |
q32704 | dumpTree | train | function dumpTree(dirname, shouldPrune, cb) {
var args = ['-type', 'f'];
if(shouldPrune) {
args = EXCLUDED_ARGS.concat(args);
}
find(dirname, args, cb);
} | javascript | {
"resource": ""
} |
q32705 | validateTokenIndent | train | function validateTokenIndent(token, desiredIndentLevel) {
const indentation = tokenInfo.getTokenIndent(token);
const expectedChar = indentType === "space" ? " " : "\t";
return indentation === expectedChar.repeat(desiredIndentLevel * indentSize) ||
// To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs.
indentation.includes(" ") && indentation.includes("\t");
} | javascript | {
"resource": ""
} |
q32706 | getFirstToken | train | function getFirstToken(element) {
let token = sourceCode.getTokenBefore(element);
while (astUtils.isOpeningParenToken(token) && token !== startToken) {
token = sourceCode.getTokenBefore(token);
}
return sourceCode.getTokenAfter(token);
} | javascript | {
"resource": ""
} |
q32707 | addBlocklessNodeIndent | train | function addBlocklessNodeIndent(node) {
if (node.type !== "BlockStatement") {
const lastParentToken = sourceCode.getTokenBefore(node, astUtils.isNotOpeningParenToken);
let firstBodyToken = sourceCode.getFirstToken(node);
let lastBodyToken = sourceCode.getLastToken(node);
while (
astUtils.isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)) &&
astUtils.isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken))
) {
firstBodyToken = sourceCode.getTokenBefore(firstBodyToken);
lastBodyToken = sourceCode.getTokenAfter(lastBodyToken);
}
offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1);
/*
* For blockless nodes with semicolon-first style, don't indent the semicolon.
* e.g.
* if (foo) bar()
* ; [1, 2, 3].map(foo)
*/
const lastToken = sourceCode.getLastToken(node);
if (node.type !== "EmptyStatement" && astUtils.isSemicolonToken(lastToken)) {
offsets.setDesiredOffset(lastToken, lastParentToken, 0);
}
}
} | javascript | {
"resource": ""
} |
q32708 | addParensIndent | train | function addParensIndent(tokens) {
const parenStack = [];
const parenPairs = [];
tokens.forEach(nextToken => {
// Accumulate a list of parenthesis pairs
if (astUtils.isOpeningParenToken(nextToken)) {
parenStack.push(nextToken);
} else if (astUtils.isClosingParenToken(nextToken)) {
parenPairs.unshift({ left: parenStack.pop(), right: nextToken });
}
});
parenPairs.forEach(pair => {
const leftParen = pair.left;
const rightParen = pair.right;
// We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments.
if (!parameterParens.has(leftParen) && !parameterParens.has(rightParen)) {
const parenthesizedTokens = new Set(sourceCode.getTokensBetween(leftParen, rightParen));
parenthesizedTokens.forEach(token => {
if (!parenthesizedTokens.has(offsets.getFirstDependency(token))) {
offsets.setDesiredOffset(token, leftParen, 1);
}
});
}
offsets.setDesiredOffset(rightParen, leftParen, 0);
});
} | javascript | {
"resource": ""
} |
q32709 | ignoreNode | train | function ignoreNode(node) {
const unknownNodeTokens = new Set(sourceCode.getTokens(node, { includeComments: true }));
unknownNodeTokens.forEach(token => {
if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) {
const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token);
if (token === firstTokenOfLine) {
offsets.ignoreToken(token);
} else {
offsets.setDesiredOffset(token, firstTokenOfLine, 0);
}
}
});
} | javascript | {
"resource": ""
} |
q32710 | isFirstTokenOfStatement | train | function isFirstTokenOfStatement(token, leafNode) {
let node = leafNode;
while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) {
node = node.parent;
}
node = node.parent;
return !node || node.range[0] === token.range[0];
} | javascript | {
"resource": ""
} |
q32711 | prototypeString | train | function prototypeString(method) {
for(var func in funcs) {
if (method !== undefined && func != method) {
continue;
}
var mod = funcs[func];
var pcount = mods[mod].funcs[func];
if (!String.prototype.hasOwnProperty(func)) {
var proto = "Object.defineProperty(String.prototype, "
+"'"+func+"',"
+"{value: function(params){ return mods['"+mod+"']."+func+"(this.toString(), params);},"
+"enumerable: false})";
eval(proto);
}
}
} | javascript | {
"resource": ""
} |
q32712 | Options | train | function Options(options) {
if (!(this instanceof Options)) {
return new Options(options);
}
this.defaults = this.defaults || {};
this.options = this.options || {};
if (options) {
this.option(options);
}
} | javascript | {
"resource": ""
} |
q32713 | train | function(key, value) {
switch (utils.typeOf(key)) {
case 'object':
this.visit('default', key);
break;
case 'string':
if (typeof value === 'undefined') {
return utils.get(this.defaults, key);
}
utils.set(this.defaults, key, value);
break;
default: {
throw new TypeError('expected a string or object');
}
}
return this;
} | javascript | {
"resource": ""
} | |
q32714 | train | function(key, value, type) {
var val = utils.get(this.options, key);
if (typeof val === 'undefined' || (type && utils.typeOf(val) !== type)) {
return value;
}
return val;
} | javascript | {
"resource": ""
} | |
q32715 | getPackageSet | train | function getPackageSet(index, callback) {
var page = {
limit : 100,
offset : index*100
}
ckan.exec('current_package_list_with_resources', page, function(err, resp){
checkError(err, resp);
for( var i = 0; i < resp.result.length; i++ ) {
data.packages[resp.result[i].id] = resp.result[i];
}
if( resp.result.length == 0 ) {
if( callback ) callback();
} else {
if( options.debug ) console.log("CKAN EXPORT: Package data loaded ("+(index*100)+" to "+((index+1)*100)+")");
index++;
getPackageSet(index, callback);
}
});
} | javascript | {
"resource": ""
} |
q32716 | train | function (message, important) {
/** @type {string} */
const prefix = 'VarGate SG1 Log:';
/** @type {Array} */
let args = [];
if (window['DEBUG_MODE']) {
if (typeof message !== 'string' && message.length) {
args = message;
} else {
args.push(message);
}
args.unshift(prefix);
try {
switch (window['DEBUG_MODE']) {
case 'verbose':
console['warn'].apply(console, args);
break;
case 'static':
console['warn'].apply(console, JSON.parse(JSON.stringify(args)));
break;
case 'minimal':
if (important) console['warn'].apply(console, args);
break;
default:
// do nothing
}
} catch (e) {
// Looks like we can't log anything
}
}
} | javascript | {
"resource": ""
} | |
q32717 | popsicleServer | train | function popsicleServer (app) {
var server = serverAddress(app)
return function (req, next) {
server.listen()
req.url = server.url(req.url)
return promiseFinally(next(), function () {
server.close()
})
}
} | javascript | {
"resource": ""
} |
q32718 | train | function () {
// get client's current date
var date = new Date();
// turn date to utc
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
// set new Date object
var new_date = new Date(utc + (3600000*settings.offset))
return new_date;
} | javascript | {
"resource": ""
} | |
q32719 | countdown | train | function countdown () {
var target_date = new Date(settings.date), // set target date
current_date = currentDate(); // get fixed current date
// difference of dates
var difference = target_date - current_date;
// if difference is negative than it's pass the target date
if (difference < 0) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// based on the date change the refrence wording
var ref_days = (days === 1) ? 'day' : 'days',
ref_hours = (hours === 1) ? 'hour' : 'hours',
ref_minutes = (minutes === 1) ? 'minute' : 'minutes',
ref_seconds = (seconds === 1) ? 'second' : 'seconds';
// set to DOM
container.find('.days').text(days);
container.find('.hours').text(hours);
container.find('.minutes').text(minutes);
container.find('.seconds').text(seconds);
container.find('.days_ref').text(ref_days);
container.find('.hours_ref').text(ref_hours);
container.find('.minutes_ref').text(ref_minutes);
container.find('.seconds_ref').text(ref_seconds);
} | javascript | {
"resource": ""
} |
q32720 | ftpCwd | train | function ftpCwd(inPath, cb) {
ftp.raw.cwd(inPath, function(err) {
if (err) {
ftp.raw.mkd(inPath, function(err) {
if (err) {
log.error('Error creating new remote folder ' + inPath + ' --> ' + err);
cb(err);
} else {
log.ok('New remote folder created ' + inPath.yellow);
ftpCwd(inPath, cb);
}
});
} else {
cb(null);
}
});
} | javascript | {
"resource": ""
} |
q32721 | streamToGenerator | train | async function* streamToGenerator(stream) {
let promise;
stream.on('data', data => promise.resolve(data));
stream.once('end', () => promise.resolve(null));
stream.on('error', error => {
stream.removeAllListeners();
promise.reject(error);
});
while (true) {
promise = defer();
yield promise;
}
} | javascript | {
"resource": ""
} |
q32722 | train | function(filePath){
var parts = filePath.split('/');
if(parts.length > 0){
var id = parts.pop();
return {
id: id,
path: parts.join('/')
}
} else {
return false;
}
} | javascript | {
"resource": ""
} | |
q32723 | getQueuedLink | train | function getQueuedLink(callback, seconds) {
var dateField = 'queued.lastAttempt';
seconds = seconds || DELAY_SECONDS;
// function to process the link
var process = function(err, res) {
var queuedLink = null;
if (res && res.hits && res.hits.hits.length) {
var hit = res.hits.hits[0]._source;
var queued = hit.queued;
queuedLink = { uri: hit.uri, queued: queued, total: res.hits.total };
queued.lastAttempt = new Date().toISOString();
queued.attempts = queued.attempts + 1;
hit.queued = queued;
// update accesses
contentLib.indexContentItem(hit, {state: 'queued', member: queued.member}, function(err, res) {
// process the link
if (!err) {
callback(null, queuedLink);
} else {
utils.passingError(err);
}
});
} else {
callback(err, null);
}
};
// call query with the function
GLOBAL.svc.indexer.formQuery({query: {
terms: dateField + ':<now-' + seconds + 's AND state:queued AND queued.attempts:<' + MAX_ATTEMPTS
}, sort: dateField, sourceFields : ['uri', 'title', 'queued.*'], size : 1 }, process);
} | javascript | {
"resource": ""
} |
q32724 | train | function(err, res) {
var queuedLink = null;
if (res && res.hits && res.hits.hits.length) {
var hit = res.hits.hits[0]._source;
var queued = hit.queued;
queuedLink = { uri: hit.uri, queued: queued, total: res.hits.total };
queued.lastAttempt = new Date().toISOString();
queued.attempts = queued.attempts + 1;
hit.queued = queued;
// update accesses
contentLib.indexContentItem(hit, {state: 'queued', member: queued.member}, function(err, res) {
// process the link
if (!err) {
callback(null, queuedLink);
} else {
utils.passingError(err);
}
});
} else {
callback(err, null);
}
} | javascript | {
"resource": ""
} | |
q32725 | getLinkContents | train | function getLinkContents(err, queuedLink) {
// no link found
if (!queuedLink) {
return;
}
// retrieve https directly
var method = (queuedLink.uri.toString().indexOf('https') === 0) ? utils.retrieveHTTPS : utils.retrieve;
method(queuedLink.uri, function(err, data) {
contentLib.indexContentItem({ uri: ''+queuedLink.uri, content: data}, {isHTML: true, member: queuedLink.queued.member}, function(err, res, cItem) {
if (err || !cItem) {
GLOBAL.error('getLinkContents failed', err, res);
return;
}
// if it recently gained content queue links
if (cItem.state !== utils.states.content.queued && cItem.previousState === utils.states.content.queued) {
GLOBAL.info('queueing links', cItem.uri, 'relevance', cItem.queued.relevance);
queueLinks(cItem);
}
GLOBAL.debug('scraped', err, data ? data.length : 'no content');
});
});
} | javascript | {
"resource": ""
} |
q32726 | queueLinks | train | function queueLinks(cItem) {
if (!cItem.queued || !cItem.queued.categories) {
GLOBAL.error('missing queued || queued.categories', cItem.uri, cItem.queued);
return;
}
var relevance = cItem.queued.relevance;
if (relevance > 0) {
relevance--;
var links = contentLib.getRecognizedLinks(cItem);
var categories = cItem.queued.categories;
// FIXME: add callback
for (var type in links) {
var typeLinks = links[type], referers = [cItem.uri], state = utils.states.annotations.validated;
// FIXME add referers
typeLinks.forEach(function(uri) {
queueLink(uri, { relevance: relevance, categories: categories, referers: referers, member: cItem.queued.member, state: state});
});
}
return links;
}
} | javascript | {
"resource": ""
} |
q32727 | queueLink | train | function queueLink(uri, context) {
var queuedDetails = { queueOnly: true, member: context.member, categories: context.categories, relevance: context.relevance, attempts: 0, lastAttempt: new Date().toISOString(), team: context.team };
var toQueue = { title: 'Queued ' + context.categories, uri: uri, state: utils.states.content.queued, queued: queuedDetails};
contentLib.indexContentItem(toQueue, context, utils.passingError);
} | javascript | {
"resource": ""
} |
q32728 | queueSearcher | train | function queueSearcher(data, cb) {
// validate
if (data.team && data.team.length > 0 && data.input && data.member && data.categories && data.categories.length > 0) {
// log the search
GLOBAL.svc.indexer.saveSearchLog({searchID: GLOBAL.svc.indexer.searchID(data), searchDate: new Date()}, utils.passingError);
// process it by each member
data.team.forEach(function(m) {
var user = auth.getUserByUsername(m), context = { member: user.username, input: data.input, relevance: data.relevance, team: data.team, categories: data.categories};
// user not found
if (!user) {
console.log('queueSearch: user not found', m);
} else {
console.log('execing', data, 'user', user);
// it's a searcher, add links
if (user.type === 'Searcher') {
if (user.api) {
// use query template or just the term
context.query = (user.template || '$SBQUERY').replace('$SBQUERY', data.input);
context.targetResults = data.targetResults || 10;
// one callback per uri
searchAPIs.exec(user.api, context, function(err, uri, resultContext) {
console.log('got a link', uri);
var status;
if (err) {
utils.passingError(err);
} else {
status = { uri: uri, source: resultContext.referers };
queueLink(uri, resultContext);
}
if (cb) {
cb(err, status);
}
});
// scrape style location
} else if (user.locations) {
user.locations.split('\n').forEach(function(l) {
l = l.replace('$SBQUERY', data.input);
GLOBAL.info(' /queueSearch', l);
queueLink(l, context);
});
} else {
GLOBAL.error('unknown searcher type', user);
}
// an annotator or individual
} else {
GLOBAL.info(' /queueSearch', data.uri);
queueLink(data.uri, context);
}
}
});
} else {
console.log('missing data', data);
}
} | javascript | {
"resource": ""
} |
q32729 | train | function(o) {
this._id++;
o.__id = this._id;
// FIXME collusion with tree state
o._state = o.state;
this.mapped[this._id] = o;
return this._id;
} | javascript | {
"resource": ""
} | |
q32730 | checkDefined | train | function checkDefined(key) {
//noinspection JSPotentiallyInvalidUsageOfThis
if (! data[`${this.moduleName}.${key}`] && typeof parent.get(key) !== 'undefined' && ! util.squelch()) {
// Not allowing sub-modules to name variables already defined in the parent (unless using override).
// Things get weird when expecting a variable defined in two places.
//noinspection JSPotentiallyInvalidUsageOfThis
util.throw(`In "${this.moduleName}" variable "${key}" defined in module "${parent.moduleName}". Choose a different name.`);
}
} | javascript | {
"resource": ""
} |
q32731 | assignNestedPropertyListener | train | function assignNestedPropertyListener(object, key, fullKey, context) {
/** @type {Array} */
const pathArray = key.split('.');
if (pathArray.length === 1 && typeof key === 'string') {
// Sanitize `key`
key = key.replace(/[^\w$]/g, '');
if (object[key] === undefined) {
// Create a watch on the property, and run once it's been set
Object.defineProperty(object, key, {
/** @type {boolean} */
'configurable': true,
/** @param {*} val */
'set': function(val) {
delete object[key];
object[key] = val;
context.set(fullKey, object);
}
});
} else {
// The property's already been defined. Trigger it.
context.set(fullKey, object);
}
} else {
assignNestedPropertyListener(object[pathArray[0]], pathArray.splice(1).join('.'), fullKey, context);
}
} | javascript | {
"resource": ""
} |
q32732 | arrAssoc | train | function arrAssoc(x, k, v) {
var y;
if (k < 0 || k > x.length) {
throw new Error('Index ' + k + ' out of bounds [0,' + x.length + ']');
}
y = [].concat(x);
y[k] = v;
return y;
} | javascript | {
"resource": ""
} |
q32733 | WebTreeStore | train | function WebTreeStore(storageObject, storageId, dataChanged) {
this.storage = storageObject;
this.id = storageId;
this._setItem(this.id + "-tree", true);
this.dataChanged = dataChanged;
} | javascript | {
"resource": ""
} |
q32734 | train | function(service, credentials, accounts, keywords) {
Stream.call(this, service, credentials, accounts, keywords);
this._twit = new Twit(credentials);
this.responder = new Responder();
this._changes = [];
this._interval = setInterval(this.intervalMethod.bind(this), QUEUE_PERIOD_DEFAULT);
} | javascript | {
"resource": ""
} | |
q32735 | train | function(ferret, fn) {
if (ferret._ready) {
return fn(null)
} else if (ferret._error) {
return fn(new Error('Not connected to the database'))
} else {
ferret._readyQueue.push(fn)
}
} | javascript | {
"resource": ""
} | |
q32736 | train | function(ferret, collection_name, callback) {
_ready(ferret, function(err) {
if (err) {
process.nextTick(function() {
callback(err)
})
} else {
if (ferret._collections[collection_name]) {
process.nextTick(function() {
callback(null, ferret._collections[collection_name])
})
} else {
ferret._db.collection(collection_name, function(err, collection){
if (!err) { ferret._collections[collection_name] = collection }
callback(err, collection)
})
}
}
})
} | javascript | {
"resource": ""
} | |
q32737 | train | function() {
var pairs = _self.querystring().split('&');
var params = {};
for(var i=0; i<pairs.length; i++) {
if(pairs[i] === '') continue;
var nameValue = pairs[i].split('=');
params[nameValue[0]] = (typeof nameValue[1] === 'undefined' || nameValue[1] === '') ? true : decodeURIComponent(nameValue[1]);
}
return params;
} | javascript | {
"resource": ""
} | |
q32738 | train | function(subdomain, username, passwordOrAPIToken, methodURL, requestMethod, callback, data, attachments) {
var baseUrl = subdomain + '.mydonedone.com'
, path = '/issuetracker/api/v2/' + methodURL
, auth = new Buffer(username + ':' + passwordOrAPIToken).toString('base64')
, options = {
hostname: baseUrl,
path: path,
method: requestMethod,
headers: {
Authorization: 'Basic ' + auth
}
}
, respData = '';
if(data) {
data = querystring.stringify(data);
options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
options.headers['Content-Length'] = Buffer.byteLength(data);
}
var req = https.request(options, function(res) {
res.setEncoding('utf8');
// Collect response chunks
res.on('data', function(chunk) {
respData += chunk;
});
// Process the response once all data has come in
res.on('end', function() {
var respJson = JSON.parse(respData);
// Non-200 responses are API errors. Execute the callback with the error message.
if(200 !== res.statusCode) {
var errMsg = 'HTTP Error ' + res.statusCode + ', Message: ' + respJson.Message;
if(callback) {
callback(errMsg);
}
}
else {
if(callback) {
callback(null, respJson);
}
}
});
});
// Write the POST data
if(data) {
req.write(data);
}
req.end();
req.on('error', function(e) {
callback(e);
});
} | javascript | {
"resource": ""
} | |
q32739 | train | function(cb) {
exports.getReleaseBuildInfo(subdomain, username, passwordOrAPIToken, id, function(err, respData) {
cb(err, respData);
});
} | javascript | {
"resource": ""
} | |
q32740 | train | function(releaseBuildInfo, cb) {
orderNumbers = releaseBuildInfo.order_numbers_ready_for_next_release.join(',');
// Trigger an error when there are no issues that are ready to release
if('' === orderNumbers) {
cb('Cannot create release build, there are no issues marked as "Ready for Next Release".');
}
else {
exports.getPeopleInProject(subdomain, username, passwordOrAPIToken, id, function(err, respData) {
cb(err, respData);
});
}
} | javascript | {
"resource": ""
} | |
q32741 | train | function(peopleInProject, cb) {
userIdsToCc = _.pluck(peopleInProject, 'id').join(',');
exports.getProject(subdomain, username, passwordOrAPIToken, id, function(err, respData) {
cb(err, respData);
});
} | javascript | {
"resource": ""
} | |
q32742 | train | function(projectInfo, cb) {
projectTitle = projectInfo.title;
if(projectTitle) {
emailBody = emailBody.replace('{{Project Name}}', projectTitle);
}
exports.createReleaseBuildForProject(subdomain, username, passwordOrAPIToken, id, orderNumbers, title, description, emailBody, userIdsToCc, function(err, respData) {
cb(err, respData);
});
} | javascript | {
"resource": ""
} | |
q32743 | op1 | train | function op1(value, priority) {
if (value === MINUS) {
priority += 2;
}
return new Token(OP1, value, priority);
} | javascript | {
"resource": ""
} |
q32744 | op2 | train | function op2(value, priority) {
if (value === MULTIPLY) {
priority += 1;
} else if (value === DIVIDE || value === INT_DIVIDE) {
priority += 2;
}
return new Token(OP2, value, priority);
} | javascript | {
"resource": ""
} |
q32745 | formatDeckAsShortCards | train | function formatDeckAsShortCards(deck) {
var newDeck = {
_id: deck._id,
name: deck.name,
username: deck.username,
lastUpdated: deck.lastUpdated,
faction: { name: deck.faction.name, value: deck.faction.value }
};
if (deck.agenda) {
newDeck.agenda = { code: deck.agenda.code };
}
newDeck.bannerCards = (deck.bannerCards || []).map(function (card) {
return { code: card.code };
});
newDeck.drawCards = formatCards(deck.drawCards || []);
newDeck.plotCards = formatCards(deck.plotCards || []);
newDeck.rookeryCards = formatCards(deck.rookeryCards || []);
return newDeck;
} | javascript | {
"resource": ""
} |
q32746 | poweredBy | train | function poweredBy(app, config) {
config = extend({}, defaults, config);
if(config.disablePoweredBy) {
return app.disable('x-powered-by');
}
if(config.poweredBy === false) {
return;
}
app.use(function xPoweredBy(req, res, next) {
res.header('x-powered-by', config.poweredBy);
next();
});
} | javascript | {
"resource": ""
} |
q32747 | train | function(namespace)
{
if (!namespace || !conbo.isString(namespace))
{
conbo.warn('First parameter must be the namespace string, received', namespace);
return;
}
if (!__namespaces[namespace])
{
__namespaces[namespace] = new conbo.Namespace();
}
var ns = __namespaces[namespace],
params = conbo.rest(arguments),
func = params.pop()
;
if (conbo.isFunction(func))
{
var obj = func.apply(ns, params);
if (conbo.isObject(obj) && !conbo.isArray(obj))
{
ns.import(obj);
}
}
return ns;
} | javascript | {
"resource": ""
} | |
q32748 | train | function(obj, propName, value)
{
if (conbo.isAccessor(obj, propName)) return;
if (arguments.length < 3) value = obj[propName];
var enumerable = propName.indexOf('_') != 0;
var internalName = '__'+propName;
__definePrivateProperty(obj, internalName, value);
var getter = function()
{
return this[internalName];
};
var setter = function(newValue)
{
if (!conbo.isEqual(newValue, this[internalName]))
{
this[internalName] = newValue;
__dispatchChange(this, propName);
}
};
Object.defineProperty(obj, propName, {enumerable:enumerable, configurable:true, get:getter, set:setter});
} | javascript | {
"resource": ""
} | |
q32749 | train | function(obj)
{
var regExp = arguments[1];
var keys = regExp instanceof RegExp
? conbo.filter(conbo.keys(obj), function(key) { return regExp.test(key); })
: (arguments.length > 1 ? conbo.rest(arguments) : conbo.keys(obj));
keys.forEach(function(key)
{
var descriptor = Object.getOwnPropertyDescriptor(obj, key)
|| {value:obj[key], configurable:true, writable:true};
descriptor.enumerable = false;
Object.defineProperty(obj, key, descriptor);
});
} | javascript | {
"resource": ""
} | |
q32750 | train | function(value)
{
if (value == undefined) return conbo.identity;
if (conbo.isFunction(value)) return value;
return conbo.property(value);
} | javascript | {
"resource": ""
} | |
q32751 | train | function(type, handler, scope)
{
if (!this.__queue || !(type in this.__queue) || !this.__queue[type].length)
{
return false;
}
var filtered = this.__queue[type].filter(function(queued)
{
return (!handler || queued.handler == handler) && (!scope || queued.scope == scope);
});
return !!filtered.length;
} | javascript | {
"resource": ""
} | |
q32752 | train | function(event)
{
if (!(event instanceof conbo.Event))
{
throw new Error('event parameter is not an instance of conbo.Event');
}
if (!this.__queue || (!(event.type in this.__queue) && !this.__queue.all)) return this;
if (!event.target) event.target = this;
event.currentTarget = this;
var queue = conbo.union(this.__queue[event.type] || [], this.__queue.all || []);
if (!queue || !queue.length) return this;
for (var i=0, length=queue.length; i<length; ++i)
{
var value = queue[i];
var returnValue = value.handler.call(value.scope || this, event);
if (value.once) EventDispatcher__removeEventListener.call(this, event.type, value.handler, value.scope);
if (event.immediatePropagationStopped) break;
}
return this;
} | javascript | {
"resource": ""
} | |
q32753 | train | function(contextClass, cloneSingletons, cloneCommands)
{
contextClass || (contextClass = conbo.Context);
return new contextClass
({
context: this,
app: this.app,
namespace: this.namespace,
commands: cloneCommands ? conbo.clone(this.__commands) : undefined,
singletons: cloneSingletons ? conbo.clone(this.__singletons) : undefined
});
} | javascript | {
"resource": ""
} | |
q32754 | train | function(eventType, commandClass)
{
if (!eventType) throw new Error('eventType cannot be undefined');
if (!commandClass) throw new Error('commandClass for '+eventType+' cannot be undefined');
if (this.__commands[eventType] && this.__commands[eventType].indexOf(commandClass) != -1)
{
return this;
}
this.__commands[eventType] = this.__commands[eventType] || [];
this.__commands[eventType].push(commandClass);
return this;
} | javascript | {
"resource": ""
} | |
q32755 | train | function(eventType, commandClass)
{
if (!eventType) throw new Error('eventType cannot be undefined');
if (commandClass === undefined)
{
delete this.__commands[eventType];
return this;
}
if (!this.__commands[eventType]) return;
var index = this.__commands[eventType].indexOf(commandClass);
if (index == -1) return;
this.__commands[eventType].splice(index, 1);
return this;
} | javascript | {
"resource": ""
} | |
q32756 | train | function(propertyName, singletonClass)
{
if (!propertyName) throw new Error('propertyName cannot be undefined');
if (singletonClass === undefined)
{
conbo.warn('singletonClass for '+propertyName+' is undefined');
}
if (conbo.isClass(singletonClass))
{
var args = conbo.rest(arguments);
if (args.length == 1 && singletonClass.prototype instanceof conbo.ConboClass)
{
args.push(this);
}
this.__singletons[propertyName] = new (Function.prototype.bind.apply(singletonClass, args))
}
else
{
this.__singletons[propertyName] = singletonClass;
}
return this;
} | javascript | {
"resource": ""
} | |
q32757 | train | function(obj)
{
var scope = this;
for (var a in scope.__singletons)
{
if (a in obj)
{
(function(value)
{
Object.defineProperty(obj, a,
{
configurable: true,
get: function() { return value; }
});
})(scope.__singletons[a]);
}
}
return this;
} | javascript | {
"resource": ""
} | |
q32758 | train | function(obj)
{
for (var a in this.__singletons)
{
if (a in obj)
{
Object.defineProperty(obj, a,
{
configurable: true,
value: undefined
});
}
}
return this;
} | javascript | {
"resource": ""
} | |
q32759 | train | function()
{
conbo.assign(this,
{
__commands: undefined,
__singletons: undefined,
__app: undefined,
__namespace: undefined,
__parentContext: undefined
});
this.removeEventListener();
return this;
} | javascript | {
"resource": ""
} | |
q32760 | train | function(item)
{
var items = conbo.toArray(arguments);
if (items.length)
{
this.source.push.apply(this.source, this.__applyItemClass(items));
this.__updateBindings(items);
this.dispatchEvent(new conbo.ConboEvent(conbo.ConboEvent.ADD));
this.dispatchChange('length');
}
return this.length;
} | javascript | {
"resource": ""
} | |
q32761 | train | function()
{
if (!this.length) return;
var item = this.source.pop();
this.__updateBindings(item, false);
this.dispatchEvent(new conbo.ConboEvent(conbo.ConboEvent.REMOVE));
this.dispatchChange('length');
return item;
} | javascript | {
"resource": ""
} | |
q32762 | train | function(begin, length)
{
begin || (begin = 0);
if (conbo.isUndefined(length)) length = this.length;
return new conbo.List({source:this.source.slice(begin, length)});
} | javascript | {
"resource": ""
} | |
q32763 | train | function(begin, length)
{
begin || (begin = 0);
if (conbo.isUndefined(length)) length = this.length;
var inserts = conbo.rest(arguments,2);
var items = this.source.splice.apply(this.source, [begin, length].concat(inserts));
if (items.length) this.dispatchEvent(new conbo.ConboEvent(conbo.ConboEvent.REMOVE));
if (inserts.length) this.dispatchEvent(new conbo.ConboEvent(conbo.ConboEvent.ADD));
if (items.length || inserts.length)
{
this.dispatchChange('length');
}
return new conbo.List({source:items});
} | javascript | {
"resource": ""
} | |
q32764 | train | function(compareFunction)
{
this.source.sort(compareFunction);
this.dispatchEvent(new conbo.ConboEvent(conbo.ConboEvent.CHANGE));
return this;
} | javascript | {
"resource": ""
} | |
q32765 | train | function(items, enabled)
{
var method = enabled === false ? 'removeEventListener' : 'addEventListener';
items = (conbo.isArray(items) ? items : [items]).slice();
while (items.length)
{
var item = items.pop();
if (item instanceof conbo.EventDispatcher)
{
item[method](conbo.ConboEvent.CHANGE, this.dispatchEvent, this);
}
}
} | javascript | {
"resource": ""
} | |
q32766 | train | function()
{
var el = this.__obj;
var a = {};
if (el)
{
conbo.forEach(el.attributes, function(p)
{
a[conbo.toCamelCase(p.name)] = p.value;
});
}
return a;
} | javascript | {
"resource": ""
} | |
q32767 | train | function(obj)
{
var el = this.__obj;
if (el && obj)
{
conbo.forEach(obj, function(value, name)
{
el.setAttribute(conbo.toKebabCase(name), value);
});
}
return this;
} | javascript | {
"resource": ""
} | |
q32768 | train | function(className)
{
var el = this.__obj;
return el instanceof Element && className
? el.classList.contains(className)
: false;
} | javascript | {
"resource": ""
} | |
q32769 | train | function(selector)
{
var el = this.__obj;
if (el)
{
var matchesFn;
['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn)
{
if (typeof document.body[fn] == 'function')
{
matchesFn = fn;
return true;
}
return false;
});
var parent;
// traverse parents
while (el)
{
parent = el.parentElement;
if (parent && parent[matchesFn](selector))
{
return parent;
}
el = parent;
}
}
} | javascript | {
"resource": ""
} | |
q32770 | train | function(el)
{
var attrs = conbo.assign({}, this.attributes);
if (this.id && !el.id)
{
attrs.id = this.id;
}
el.classList.add('cb-glimpse');
el.cbGlimpse = this;
for (var attr in attrs)
{
el.setAttribute(conbo.toKebabCase(attr), attrs[attr]);
}
if (this.style)
{
el.style = conbo.assign(el.style, this.style);
}
__definePrivateProperty(this, '__el', el);
return this;
} | javascript | {
"resource": ""
} | |
q32771 | train | function(selector, deep)
{
if (this.el)
{
var results = conbo.toArray(this.el.querySelectorAll(selector));
if (!deep)
{
var views = this.el.querySelectorAll('.cb-view, [cb-view], [cb-app]');
// Remove elements in child Views
conbo.forEach(views, function(el)
{
var els = conbo.toArray(el.querySelectorAll(selector));
results = conbo.difference(results, els.concat(el));
});
}
return results;
}
return [];
} | javascript | {
"resource": ""
} | |
q32772 | train | function()
{
try
{
var el = this.el;
if (el.parentNode)
{
el.parentNode.removeChild(el);
this.dispatchEvent(new conbo.ConboEvent(conbo.ConboEvent.DETACH));
}
}
catch(e) {}
return this;
} | javascript | {
"resource": ""
} | |
q32773 | train | function()
{
this.dispatchEvent(new conbo.ConboEvent(conbo.ConboEvent.REMOVE));
if (this.data)
{
this.data = undefined;
}
if (this.subcontext && this.subcontext != this.context)
{
this.subcontext.destroy();
this.subcontext = undefined;
}
if (this.context)
{
this.context
.uninjectSingletons(this)
.removeEventListener(undefined, undefined, this)
;
this.context = undefined;
}
var children = this.querySelectorAll('.cb-view', true);
while (children.length)
{
var child = children.pop();
try { child.cbView.remove(); }
catch (e) {}
}
this.unbindView()
.detach()
.removeEventListener()
.destroy()
;
return this;
} | javascript | {
"resource": ""
} | |
q32774 | train | function(view)
{
if (arguments.length > 1)
{
conbo.forEach(arguments, function(view, index, list)
{
this.appendView(view);
},
this);
return this;
}
if (typeof view === 'function')
{
view = new view(this.context);
}
if (!(view instanceof conbo.View))
{
throw new Error('Parameter must be conbo.View class or instance of it');
}
this.body.appendChild(view.el);
return this;
} | javascript | {
"resource": ""
} | |
q32775 | train | function(view)
{
if (arguments.length > 1)
{
conbo.forEach(arguments, function(view, index, list)
{
this.prependView(view);
},
this);
return this;
}
if (typeof view === 'function')
{
view = new view(this.context);
}
if (!(view instanceof conbo.View))
{
throw new Error('Parameter must be conbo.View class or instance of it');
}
var firstChild = this.body.firstChild;
firstChild
? this.body.insertBefore(view.el, firstChild)
: this.appendView(view);
return this;
} | javascript | {
"resource": ""
} | |
q32776 | train | function()
{
var template = this.template;
if (!!this.templateUrl)
{
this.loadTemplate();
}
else
{
if (conbo.isFunction(template))
{
template = template(this);
}
var el = this.el;
if (conbo.isString(template))
{
el.innerHTML = this.__parseTemplate(template);
}
else if (/{{(.+?)}}/.test(el.textContent))
{
el.innerHTML = this.__parseTemplate(el.innerHTML);
}
this.__initView();
}
return this;
} | javascript | {
"resource": ""
} | |
q32777 | train | function(url)
{
url || (url = this.templateUrl);
var el = this.body;
this.unbindView();
if (this.templateCacheEnabled !== false && View__templateCache[url])
{
el.innerHTML = View__templateCache[url];
this.__initView();
return this;
}
var resultHandler = function(event)
{
var result = this.__parseTemplate(event.result);
if (this.templateCacheEnabled !== false)
{
View__templateCache[url] = result;
}
el.innerHTML = result;
this.__initView();
};
var faultHandler = function(event)
{
el.innerHTML = '';
this.dispatchEvent(new conbo.ConboEvent(conbo.ConboEvent.TEMPLATE_ERROR));
this.__initView();
};
conbo
.httpRequest({url:url, dataType:'text'})
.then(resultHandler.bind(this), faultHandler.bind(this))
;
return this;
} | javascript | {
"resource": ""
} | |
q32778 | train | function(command, data, method, resultClass)
{
var scope = this;
data = conbo.clone(data || {});
command = this.parseUrl(command, data);
data = this.encodeFunction(data, method);
return new Promise(function(resolve, reject)
{
conbo.httpRequest
({
data: data,
type: method || 'GET',
headers: scope.headers,
url: (scope.rootUrl+command).replace(/\/$/, ''),
contentType: scope.contentType || conbo.CONTENT_TYPE_JSON,
dataType: scope.dataType,
dataFilter: scope.decodeFunction,
resultClass: resultClass || scope.resultClass,
makeObjectsBindable: scope.makeObjectsBindable
})
.then(function(event)
{
scope.dispatchEvent(event);
resolve(event);
})
.catch(function(event)
{
scope.dispatchEvent(event);
reject(event);
});
});
} | javascript | {
"resource": ""
} | |
q32779 | train | function(command, method, resultClass)
{
if (conbo.isObject(command))
{
method = command.method;
resultClass = command.resultClass;
command = command.command;
}
this[conbo.toCamelCase(command)] = function(data)
{
return this.call(command, data, method, resultClass);
};
return this;
} | javascript | {
"resource": ""
} | |
q32780 | train | function(url, data)
{
var parsedUrl = url,
matches = parsedUrl.match(/:\b\w+\b/g);
if (!!matches)
{
matches.forEach(function(key)
{
key = key.substr(1);
if (!(key in data))
{
throw new Error('Property "'+key+'" required but not found in data');
}
});
}
conbo.keys(data).forEach(function(key)
{
var regExp = new RegExp(':\\b'+key+'\\b', 'g');
if (regExp.test(parsedUrl))
{
parsedUrl = parsedUrl.replace(regExp, data[key]);
delete data[key];
}
});
return parsedUrl;
} | javascript | {
"resource": ""
} | |
q32781 | train | function(fragment, options)
{
options || (options = {});
fragment = this.__getFragment(fragment);
if (this.fragment === fragment)
{
return;
}
var location = this.location;
this.fragment = fragment;
if (options.replace)
{
var href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#!/' + fragment);
}
else
{
location.hash = '#!/' + fragment;
}
if (options.trigger)
{
this.__loadUrl(fragment);
}
return this;
} | javascript | {
"resource": ""
} | |
q32782 | train | function(fragmentOverride)
{
var fragment = this.fragment = this.__getFragment(fragmentOverride);
var matched = conbo.some(this.handlers, function(handler)
{
if (handler.route.test(fragment))
{
handler.callback(fragment);
return true;
}
});
if (!matched)
{
this.dispatchEvent(new conbo.ConboEvent(conbo.ConboEvent.FAULT));
}
return matched;
} | javascript | {
"resource": ""
} | |
q32783 | _postHandlers | train | function _postHandlers() {
// any authentication checks first
if(config.authentication.enabled) {
logger.info(pkgname + " authentication to API's enabled");
app.all(config.api.path, function(req, res, next) {
if(config.authentication.ignores && req.params) {
// check if the params is in ignores list
var matches = _.filter(req.params, function(param) {
return _.find(config.authentication.ignores, function(ignore) {
return param.indexOf(ignore)==0;
});
});
if(matches && matches.length>0) {
logger.debug(pkgname+"ignored auth for param:" + matches);
return next();
}
}
if(req.loggedIn) {
return next(); // auth success go to next
} else {
return next(error(401, 'unauthorized access'));
}
});
}
// install api checks
if(config.api.keycheck) {
logger.info(pkgname + " keycheck to API's enabled");
// here we validate the API key
app.all(config.api.path, function(req, res, next){
var key = req.query[config.api.KEYNAME] || req.body[config.api.KEYNAME];
// key isnt present
if (!key) return next(error(400, 'api key required'));
// key is invalid
if (!~config.api.keys.indexOf(key)) return next(error(401, 'invalid api key'));
// all good, store req.key for route access
req.key = key;
next();
});
}
// jsonp support for delete, put & post (partial post)
if(config.server.jsonp) {
logger.info(pkgname + " jsonp support on api's enabled");
// check if callback is there along with method
app.all(config.api.path, function(req, res, next) {
if(req.query && req.query['callback'] && req.query['_method']) {
// lets rewrite the method, especially PUT/DELETE/POST
req.method=req.query['_method'];
logger.debug(pkgname + "jsonp request converted:"+req.query);
}
next();
});
}
var api = {
index: function(req,res) {
res.json({app:config.app.title, version:config.app.version});
}
};
global.apiresource = app.resource('api', api);
logger.info(pkgname + " api handler added");
logger.debug(pkgname + "init complete");
} | javascript | {
"resource": ""
} |
q32784 | _errorHandlers | train | function _errorHandlers() {
// middleware with an arity of 4 are considered
// error handling middleware. When you next(err)
// it will be passed through the defined middleware
// in order, but ONLY those with an arity of 4, ignoring
// regular middleware.
app.use(function(err, req, res, next){
logger.error(err);
console.trace();
if(req.accepts('html') || req.is('html')) {
res.status(err.status || 500);
res.render('500', { error: err });
return;
}
res.send(err.status || 500, { error: err.message });
});
// our custom JSON 404 middleware. Since it's placed last
// it will be the last middleware called, if all others
// invoke next() and do not respond.
app.use(function(req, res) {
logger.error('Failed to locate:'+req.url);
console.trace();
if(req.accepts('html') || req.is('html')) {
res.status(404);
res.render('404', { url: req.url });
return;
}
res.send(404, { error: "can't find the resource" });
});
} | javascript | {
"resource": ""
} |
q32785 | getCode | train | function getCode(code, language) {
if (prism.languages.hasOwnProperty(language)) {
code = prism.highlight(code, prism.languages[language]);
return `<pre class="language-${language}"><code>${code}</code></pre>`;
} else {
return `<pre class="language-unknown"><code>${code}</code></pre>`;
}
} | javascript | {
"resource": ""
} |
q32786 | children | train | function children(selector) {
var arr = [], slice = this.slice, nodes, matches;
this.each(function(el) {
nodes = slice.call(el.childNodes);
// only include elements
nodes = nodes.filter(function(n) {
if(n instanceof Element) { return n;}
})
// filter direct descendants by selector
if(selector) {
matches = slice.call(el.querySelectorAll(selector));
for(var i = 0;i < nodes.length;i++) {
if(~matches.indexOf(nodes[i])) {
arr.push(nodes[i]);
}
}
// get all direct descendants
}else{
arr = arr.concat(nodes);
}
});
return this.air(arr);
} | javascript | {
"resource": ""
} |
q32787 | getSibling | train | function getSibling(node, relativeIndex) {
var parent = node.parentNode;
if (parent === null) {
return null;
}
var currentIndex = parent.childNodes.indexOf(node);
var siblingIndex = currentIndex + relativeIndex;
if (siblingIndex < 0 || siblingIndex > parent.childNodes.length - 1) {
return null;
}
return parent.childNodes[siblingIndex];
} | javascript | {
"resource": ""
} |
q32788 | train | function (rawHtml) {
var matchKeys = Object.keys(options.unescape);
if (matchKeys.length === 0) {
return rawHtml;
}
var pattern = new RegExp('(' + matchKeys.join('|') + ')', 'g');
return rawHtml.replace(pattern, function (match) {
return options.unescape[match];
});
} | javascript | {
"resource": ""
} | |
q32789 | readFile | train | function readFile(file) {
try {
file = require(path.relative(__dirname, file));
} catch (err) {
return err;
}
return file;
} | javascript | {
"resource": ""
} |
q32790 | writeFile | train | function writeFile(input, output, type) {
var json = readFile(input),
content = getContent(json, type);
fs.writeFile(output, content, function (err) {
if (err) {
throw err;
}
console.log('The file "' + output + '" was written successfully!');
});
} | javascript | {
"resource": ""
} |
q32791 | _extractActions | train | function _extractActions( opts )
{
// main properties
const data = opts.data,
configState = opts.stateData,
stateView = opts.stateView,
stateName = opts.stateName;
// new defined properties
let stateTransitions = [],
viewData = opts.viewData,
appDataView,
action,
statePrefix;
forein( configState.actions, ( prop, actionName ) => {
statePrefix = (stateName+ '->' +actionName);
appDataView = data[ prop.target ].view;
// Return action data for FSM
action = {
action : actionName,
target : prop.target,
_id : statePrefix
};
// return ViewData for View manager and append all views
viewData[ statePrefix ] = {
currentView : stateView,
nextView : appDataView,
linkedVTransModules : _extractTransitions( prop, stateView, appDataView ),
name : actionName
};
// // assign fsm action to state
stateTransitions[ stateTransitions.length ] = action;
});
return { stateTransitions : stateTransitions, viewData : viewData };
} | javascript | {
"resource": ""
} |
q32792 | _extractTransitions | train | function _extractTransitions( prop, stateView, nextView )
{
var groupedTransitions = [];
if( prop.transitions ) { // if more transitions exist, add them
groupedTransitions = prop.transitions.map( ( transitionObject ) => {
return transitionObject;
});
}
prop.views = unique( prop.views, [ stateView, nextView ] );
groupedTransitions.unshift( { transitionType : prop.transitionType, views : prop.views } );
return groupedTransitions;
} | javascript | {
"resource": ""
} |
q32793 | ReMix | train | function ReMix(name) {
var args = _.flatten(_.toArray(arguments));
if (_.isString(name) || _.isNull(name) || _.isUndefined(name))
args = args.slice(1);
else
name = undefined;
/**
* Unique id used for storing data in RegExp objects
* @private
*/
this._id = genguid();
/**
* Current instance options
* @private
*/
this._opt = {};
/**
* Stores current unresolved specification
* @private
*/
this._specs = [];
/**
* Tracking data for relating namespace to match index
* @private
*/
this._matches = [];
/**
* This ReMix's name
* @private
*/
this._name = name;
/**
* Used when composing ReMix objects or named RegExp objects. {@link module:lib/remix#scope}
* @private
*/
this._namestack = [];
/**
* Used to track position when executing regular expression
* @private
*/
this._lastIndex = 0;
if (name)
this._namestack.push(name);
this.options(ReMix.defaultOptions);
if (args.length)
this.add(args);
} | javascript | {
"resource": ""
} |
q32794 | shouldFilter | train | function shouldFilter(filters, anno) {
for (var i = filters.length - 1; i > -1; i--) {
var filter = filters[i];
if (filter.type === anno.type) {
if (_.isEqual(filter.position, anno.position)) {
if (anno.isA && anno.isA === 'Date') {
var filterDate = new Date(filter.value), fieldDate = new Date(anno.typed.Date);
if (filter.operator === '<') {
return fieldDate < filterDate;
} else if (filter.operator === '>') {
return fieldDate > filterDate;
} else {
return filterDate === fieldDate;
}
}
} else {
return filter.value == anno.value;
}
}
}
return false;
} | javascript | {
"resource": ""
} |
q32795 | train | function(name) {
var match = null;
list.forEach(function(file) {
if(_.indexOf(file.modules, name) >= 0) {
match = file;
return false;
}
});
return match;
} | javascript | {
"resource": ""
} | |
q32796 | train | function(module) {
if (!module) {
return;
}
var file = fileByModules(module);
Array.prototype.push.apply(seen, file.modules);
file.requires.forEach(function(module) {
// Ignore resoled modules and dependencies in own file
if((_.indexOf(resolved, module) < 0) &&
(_.indexOf(file.modules, module) < 0)) {
// Catch circular dependencies
if(_.indexOf(seen, module) < 0) {
resolve(module);
}
else {
grunt.fail.fatal('Circular dependency detected:\n\t' +
file.modules.join(', ') + ' depend on ' +
module, 1);
}
}
});
Array.prototype.push.apply(resolved, file.modules);
} | javascript | {
"resource": ""
} | |
q32797 | WarehouseModels | train | function WarehouseModels(datastar) {
this.Build = require('./build')(datastar, this);
this.BuildFile = require('./build-file')(datastar, this);
this.BuildHead = require('./build-head')(datastar, this);
this.Package = require('./package')(datastar, this);
this.PackageCache = require('./package-cache')(datastar, this);
this.Version = require('./version')(datastar, this);
this.Dependent = require('./dependent')(datastar, this);
this.DependentOf = require('./dependent-of')(datastar, this);
this.ReleaseLine = require('./release-line')(datastar, this);
this.ReleaseLineHead = require('./release-line-head')(datastar, this);
this.ReleaseLineDep = require('./release-line-dep')(datastar, this);
} | javascript | {
"resource": ""
} |
q32798 | _delete | train | function _delete() {
// Remove string token
cookiesUtil.deleteCookie(_config2.default.tokenName);
// Remove user data
envStorage.removeItem(_config2.default.tokenDataName);
_logger2.default.log({
description: 'Token was removed.',
func: 'delete', obj: 'token'
});
} | javascript | {
"resource": ""
} |
q32799 | initVadRAnalytics | train | function initVadRAnalytics(params){
timeManager.init();
dataCollector.init();
dataManager.init();
deviceData.init();
user.init();
initState = true;
// set initial params if provided
_setParams(params);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.