_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q32400 | train | function(zCriticalValue) {
var baselineValue = this.baseline.pEstimate(zCriticalValue).value;
var ratio = this.differenceEstimate(zCriticalValue).value / baselineValue;
var error = this.differenceEstimate(zCriticalValue).error / baselineValue;
return new Abba.ValueWithError(ratio, error)... | javascript | {
"resource": ""
} | |
q32401 | callInstanceMethod | train | function callInstanceMethod(methodName, req, res, next) {
res.__apiMethod = 'instanceMethod';
res.__apiInstanceMethod = methodName;
const self = this;
const id = req.params.id;
const methodOptions = this.apiOptions.expose[methodName];
const wrapper = (methodOptions.exec instanceof Function) ?
met... | javascript | {
"resource": ""
} |
q32402 | fetchView | train | function fetchView( data, id ) {
data.backgroundColor = randomCol();
data.fontColour = data.backgroundImage? '' : getContrastYIQ( data.backgroundColor );
let wrapper = document.createElement('div');
wrapper.className = 'section hidden';
wrapper.innerHTML = SimpleViewTemplate( data );
wrapper.dataset.id =... | javascript | {
"resource": ""
} |
q32403 | disabled | train | function disabled(val) {
// return whether the first element in the set
// is hidden
if(val === undefined) {
return this.hasClass(className);
// hide on truthy
}else if(val) {
this.addClass(className);
// show on falsey
}else{
this.removeClass(className);
}
return this;
} | javascript | {
"resource": ""
} |
q32404 | write | train | function write(ws, source) {
return new Promise(function ($return, $error) {
if (!(ws instanceof Writable)) {
return $error(new Error('Writable stream expected'));
}
if (source instanceof Readable) {
if (!source.readable) {
return $error(new Error('Str... | javascript | {
"resource": ""
} |
q32405 | init | train | function init() { // {{{2
/**
* Class constructor
*
* @method constructor
* @internal
*/
O.inherited(this)();
this.setMaxListeners(Consts.coreListeners);
this.subjectState = this.SUBJECT_STATE.INIT;
this.peers = {};
this.shards = {};
} | javascript | {
"resource": ""
} |
q32406 | newSelector | train | function newSelector($block, multiple, type){
var selector = new jqCronSelector(_self, $block, multiple, type);
selector.$.bind('selector:open', function(){
// we close all opened selectors of all other jqCron
for(var n = jqCronInstances.length; n--; ){
if(jqCronInstances[n] != _self) {
jqCronI... | javascript | {
"resource": ""
} |
q32407 | array_unique | train | function array_unique(l){
var i=0,n=l.length,k={},a=[];
while(i<n) {
k[l[i]] || (k[l[i]] = 1 && a.push(l[i]));
i++;
}
return a;
} | javascript | {
"resource": ""
} |
q32408 | RainyDay | train | function RainyDay(options) {
this.img = document.getElementById(options.element);
this.opacity = options.opacity || 1;
this.blurRadius = options.blur || 10;
this.w = this.img.clientWidth;
this.h = this.img.clientHeight;
this.drops = [];
// prepare canvas elements
this.canvas = this.prep... | javascript | {
"resource": ""
} |
q32409 | Drop | train | function Drop(rainyday, centerX, centerY, min, base) {
this.x = Math.floor(centerX);
this.y = Math.floor(centerY);
this.r = (Math.random() * base) + min;
this.rainyday = rainyday;
this.context = rainyday.context;
this.reflection = rainyday.reflected;
} | javascript | {
"resource": ""
} |
q32410 | CollisionMatrix | train | function CollisionMatrix(x, y, r) {
this.resolution = r;
this.xc = x;
this.yc = y;
this.matrix = new Array(x);
for (var i = 0; i <= (x + 5); i++) {
this.matrix[i] = new Array(y);
for (var j = 0; j <= (y + 5); ++j) {
this.matrix[i][j] = new DropItem(null);
}
}
... | javascript | {
"resource": ""
} |
q32411 | _transitionViews | train | function _transitionViews( transitionObj )
{
if( !transitionObj ){ return TransitionController.error('transition is not defined'); }
const transitionModule = _options.transitions[ transitionObj.transitionType ];
if( transitionModule ) {
const deferred = Deferred(),
views = transitionObj.views,... | javascript | {
"resource": ""
} |
q32412 | template | train | function template(source, target) {
source = source || {};
target = target || {};
for(var z in source) {
target[z] = $.partial(source[z]);
}
return target;
} | javascript | {
"resource": ""
} |
q32413 | swap | train | function swap(source, target) {
// wrap to allow string selectors, arrays etc.
source = $(source);
target = $(target);
source.each(function(el, index) {
var content = target.get(index);
if(el.parentNode && content) {
// deep clone template partial
content = content.cloneNode(true);
// ... | javascript | {
"resource": ""
} |
q32414 | createUploadPromise | train | function createUploadPromise(filepath, destination, options) {
return function () {
// get the name of the file and construct the url for uploading it
var filename = getFilename(filepath),
dropboxPath = destination + (options.version_name ? ("/" + options.version_name + "/") : "/") + filepath,
... | javascript | {
"resource": ""
} |
q32415 | process | train | function process(sources, options) {
sources = explodeall(sources);
if (!grunt.fail.errorcount) {
var content = extract(sources, options);
return enclose(content.join(SPACER));
}
} | javascript | {
"resource": ""
} |
q32416 | extract | train | function extract(sources, options) {
return sources
.map(function(src) {
return [src, grunt.file.read(src)];
})
.filter(function(list) {
return syntax.valid(grunt, list[0], list[1]);
})
.map(function(list) {
return extras(list[0], list[1], options);
});
} | javascript | {
"resource": ""
} |
q32417 | writefile | train | function writefile(filepath, filetext, options) {
var version = '-1.0.0';
var packag = filename('package.json', options);
var banner = filename('BANNER.txt', options);
if (grunt.file.exists(banner)) {
filetext = grunt.file.read(banner) + '\n' + filetext;
}
if (grunt.file.exists(packag)) {
var json = g... | javascript | {
"resource": ""
} |
q32418 | uglyfile | train | function uglyfile(prettyfile, sourcecode, options) {
var mintarget = prettyfile.replace('.js', '.min.js');
var maptarget = prettyfile.replace('.js', '.js.map');
var uglycodes = uglify(options.max ? prettyfile : sourcecode);
writefile(mintarget, uglycodes.code, options);
if (options.map) {
writefile(maptarg... | javascript | {
"resource": ""
} |
q32419 | uglify | train | function uglify(prettyfile, sourcecode) {
console.warn(
'Not quite getting the right path to source in the map :/'
);
return ugli.minify(sourcecode || prettyfile, {
fromString: sourcecode !== undefined,
outSourceMap: path.basename(prettyfile) + '.map',
compress: {
warnings: false
}
});
} | javascript | {
"resource": ""
} |
q32420 | train | function (obj, meta, status = 200, errorCode = -1, devMsg = null, usrMsg = null, moreInfo = null) {
if (res.finished) {
// request ended
return
}
// ref.: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
if (status < 300) {
// OK
// respond client and clos... | javascript | {
"resource": ""
} | |
q32421 | without | train | function without(componentIDs) {
const context = this.readContext(this);
context.pushOp(WITHOUT);
// the preceeding command is used as the first argument
context.pushVal(componentIDs, true);
return context;
} | javascript | {
"resource": ""
} |
q32422 | dualDiff | train | function dualDiff(a1, a2) {
var o1={}, o2={}, diff1=[], diff2=[], i, len, k;
for (i=0, len=a1.length; i<len; i++) { o1[a1[i]] = true; }
for (i=0, len=a2.length; i<len; i++) { o2[a2[i]] = true; }
for (k in o1) { if (!(k in o2)) { diff1.push(k); } }
for (k in o2) { if (!(k in o1)) { diff2.push(k); } }... | javascript | {
"resource": ""
} |
q32423 | generateHmac | train | function generateHmac(data, key, encoding) {
var hmac = crypto.createHmac(HMAC_SHA256_ALGORITHM, key);
hmac.update(data);
return hmac.digest(encoding);
} | javascript | {
"resource": ""
} |
q32424 | css | train | function css(key, val) {
var style, props;
if(!this.length) {
return this;
}
if(key && typeof key === 'object') {
props = key;
}else if(key && val) {
props = {};
props[key] = val;
}
// get style object
if(key === undefined) {
style = window.getComputedStyle(this.dom[0], null);
... | javascript | {
"resource": ""
} |
q32425 | _filesInDirectory | train | async function _filesInDirectory(dirPath, options) {
const basedir = options.basedir || getCallingDir();
const resolvedDirPath = basedir?path.resolve(basedir, dirPath):dirPath;
let xExt = _getExtensionRegEx(options.extension || settings.get('extensions'));
try {
const files = (await readDir(resolvedDirPath... | javascript | {
"resource": ""
} |
q32426 | filesInDirectories | train | async function filesInDirectories(dirPaths, options) {
let files = await Promise.all(makeArray(dirPaths).map(dirPath=>_filesInDirectory(dirPath, options)));
return flattenDeep(files);
} | javascript | {
"resource": ""
} |
q32427 | _getExtensionRegEx | train | function _getExtensionRegEx(ext=settings.get('extensions')) {
let _ext = '(?:' + makeArray(ext).join('|') + ')';
return new RegExp(_ext + '$');
} | javascript | {
"resource": ""
} |
q32428 | _canImport | train | function _canImport(fileName, callingFileName, options) {
if (callingFileName && (fileName === callingFileName)) return false;
let _fileName = _getFileTests(fileName, options);
if (options.includes) return (intersection(options.includes, _fileName).length > 0);
if (options.excludes) return (intersection(options... | javascript | {
"resource": ""
} |
q32429 | _importDirectoryOptionsParser | train | function _importDirectoryOptionsParser(options={}) {
const _options = Object.assign({
imports: {},
onload: options.callback,
extension: makeArray(options.extensions || settings.get('extensions')),
useSyncRequire: settings.get('useSyncRequire'),
merge: settings.get('mergeImports'),
rescursive: ... | javascript | {
"resource": ""
} |
q32430 | importDirectory | train | function importDirectory(dirPath, options, callback) {
if (!callback) return _importDirectory(dirPath, options);
_importDirectory(dirPath, options).then(
imports=>setImmediate(()=>callback(null, imports)),
err=>setImmediate(()=>callback(err, undefined))
);
} | javascript | {
"resource": ""
} |
q32431 | captureStackTrace | train | function captureStackTrace(error, constructor) {
if (Error.captureStackTrace) {
Error.captureStackTrace(error, constructor);
} else {
error.stack = new Error().stack;
}
} | javascript | {
"resource": ""
} |
q32432 | createFile | train | function createFile(tree, name, prop, options) {
var opts = utils.extend({}, options);
var str = create(tree[name], {label: 'cwd'});
var file = new utils.File({path: `${prop}-${name}.txt`, contents: new Buffer(str)});
if (typeof opts.treename === 'function') {
opts.treename(file);
}
file.... | javascript | {
"resource": ""
} |
q32433 | sortObject | train | function sortObject(object) {
var keys = Object.keys(object);
var sorted = {};
var options = {
sensitivity: 'base'
};
function compare(a, b) {
return a.localeCompare(b, options);
}
keys.sort(compare);
for (var index in keys) {
if (keys[index]) {
var key = ke... | javascript | {
"resource": ""
} |
q32434 | isValidES2015VarName | train | function isValidES2015VarName(name) {
// In ES2015-compatible code, these are reserved words.
if (name === 'await') { return false; }
if (name === 'enum') { return false; }
return validateVarName(allowedCharactersES2015, name, exports.strict);
} | javascript | {
"resource": ""
} |
q32435 | validateVarName | train | function validateVarName(regex, name, strict) {
if (strict) {
// These are only an issue in strict mode.
if (name === 'eval') { return false; }
if (name === 'arguments') { return false; }
}
var result = regex.test(name);
result = result && validateCommonReservedWords(name);
return result;
} | javascript | {
"resource": ""
} |
q32436 | train | function(s) {
//TODO: validate array length
//TODO: return unwanted subset as new Px object
var counts = this.valCounts(),
multipliers = [];
_.each(s, function(d, i) {
if (d[0] === '*') {
s[i] = _.range(0, co... | javascript | {
"resource": ""
} | |
q32437 | deploy | train | function deploy(params, cb) {
params.resourcePath = config.addURIParams(constants.SERVICES_BASE_PATH + "/:guid/deploy", params);
params.method = "POST";
params.data = params.service;
mbaasRequest.admin(params, cb);
} | javascript | {
"resource": ""
} |
q32438 | qinu | train | function qinu (options, args) {
const { dict, length, template, args: optArgs, random } =
this instanceof Qinu ? options : normalizeOptions(options)
if (!(args instanceof Array)) {
args = Array.prototype.slice.call(arguments, 1)
}
if (optArgs instanceof Array) {
args = optArgs.concat(args)
}
co... | javascript | {
"resource": ""
} |
q32439 | brequire | train | function brequire(module) {
var basepath = process.env.SRC_base ? path.resolve(process.env.SRC_base)
: path.join(__dirname, '..');
if (module.charAt(0) == '.')
return require(path.join(basepath, module));
else //by calling require() from this location we ensure base's copy of the module will... | javascript | {
"resource": ""
} |
q32440 | returnRankedIntents | train | function returnRankedIntents(input, intents) {
return new Promise((resolve, reject) => {
let lowerCase = input.toLowerCase();
let totalScore = 0;
//loop through all loaded intents
intents.forEach((intent) => {
intent.score = 0;
intent.utterences.forEach((utte... | javascript | {
"resource": ""
} |
q32441 | operate | train | function operate(input, direct, method) {
var node = input[0],
state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked,
active = method == _update ? {
checked: node[_checked],
disabled: node[_disabled],
indeterminate: input.attr(_indeterminate) == 't... | javascript | {
"resource": ""
} |
q32442 | on | train | function on(input, state, keep) {
var node = input[0],
parent = input.parent(),
checked = state == _checked,
indeterminate = state == _indeterminate,
disabled = state == _disabled,
callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
regular = option(input,... | javascript | {
"resource": ""
} |
q32443 | off | train | function off(input, state, keep) {
var node = input[0],
parent = input.parent(),
checked = state == _checked,
indeterminate = state == _indeterminate,
disabled = state == _disabled,
callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
regular = option(input... | javascript | {
"resource": ""
} |
q32444 | tidy | train | function tidy(input, callback) {
if (input.data(_iCheck)) {
// Remove everything except input
input.parent().html(input.attr('style', input.data(_iCheck).s || ''));
// Callback
if (callback) {
input[_callback](callback);
};
// Unbind events
input.off('.i').unwrap... | javascript | {
"resource": ""
} |
q32445 | option | train | function option(input, state, regular) {
if (input.data(_iCheck)) {
return input.data(_iCheck).o[state + (regular ? '' : 'Class')];
};
} | javascript | {
"resource": ""
} |
q32446 | ajaxCallback | train | function ajaxCallback(data, textStatus) {
//responses should be a list of successful responses
//if any request failed it *may or may not* be an http-level error
//depending on server-side implementation
// konsole.log("datarequest", data, textStatus, 'dbdata.'+txnId, comm... | javascript | {
"resource": ""
} |
q32447 | train | function( obj ) {
var accessor = this._getAccessor( obj );
var seen = {};
for( var i = 0; i < this.form.elements.length; i++) {
this.serializeField( this.form.elements[i], accessor, seen);
}
return accessor.target;
} | javascript | {
"resource": ""
} | |
q32448 | train | function( obj ) { //set form html
var accessor = this._getAccessor( obj );
for( var i = 0; i < this.form.elements.length; i++) {
this.deserializeField( this.form.elements[i], accessor );
}
return accessor.target;
} | javascript | {
"resource": ""
} | |
q32449 | train | function( element, obj ) {
var accessor = this._getAccessor( obj );
var value = accessor.get( element.name || '');
value = this._format( element.name, value, element );
if( element.type == "radio" || element.type == "checkbox" ) {
element.checked = this._isSelected( element.value, value );
} ... | javascript | {
"resource": ""
} | |
q32450 | uploadSubmissionFile | train | function uploadSubmissionFile(params, cb) {
var resourcePath = config.addURIParams("/appforms/submissions/:id/fields/:fieldId/files/:fileId", params);
var method = "POST";
var data = params.fileDetails;
params.resourcePath = resourcePath;
params.method = method;
params.data = data;
//Flagging This Reque... | javascript | {
"resource": ""
} |
q32451 | getSubmissionStatus | train | function getSubmissionStatus(params, cb) {
var resourcePath = config.addURIParams("/appforms/submissions/:id/status", params);
var method = "GET";
var data = {};
params.resourcePath = resourcePath;
params.method = method;
params.data = data;
//Flagging This Request As A File Request
params.fileRequest... | javascript | {
"resource": ""
} |
q32452 | exportCSV | train | function exportCSV(params, cb) {
var resourcePath = config.addURIParams("/appforms/submissions/export", params);
var method = "POST";
var data = params.queryParams;
params.resourcePath = resourcePath;
params.method = method;
params.data = data;
params.fileRequest = true;
mbaasRequest.app(params, cb);... | javascript | {
"resource": ""
} |
q32453 | validate | train | function validate(candidate) {
if (candidate.doc_type) {
var schema = schemasDeepCopy()[candidate.doc_type];
validator.validate(candidate, schema);
var errors = validator.getLastErrors();
return errors;
}
return [{
dataModel: 'the object to be validated is missing a `doc_type` property'
}];... | javascript | {
"resource": ""
} |
q32454 | generate | train | function generate(model, count) {
count = count || 1;
var registry = {};
var models = [];
if (model) {
models = typeof model === 'string' ? [model] : model;
} else {
models = Object.keys(schemas);
}
function build(model) {
var instance = jsf(schemas[model]);
var invalid = validate(instan... | javascript | {
"resource": ""
} |
q32455 | serverClose | train | function serverClose (signal, done) {
_logger.info('Process received ' + signal + ', exiting ....')
if (done === undefined) {
done = function () {
process.exit(0)
}
}
if (server) {
server.close(done)
} else {
done()
}
} | javascript | {
"resource": ""
} |
q32456 | scroll | train | function scroll(e) {
var attr = e.element.attributes;
if (!(attr || attr.href)) return;
var target = $(attr.href.value).plain(0);
if (!target) return;
e.preventDefault();
//
// Store the current window top Y and difference.
//
this.y = document.body.scrollTop;
this.target = ta... | javascript | {
"resource": ""
} |
q32457 | animate | train | function animate() {
var diff = this.speed;
//
// If we're getting close to the endpoint stop at 0.
//
if (this.delta < diff) {
clearInterval(this.animated);
diff = this.delta;
}
//
// Keep track of how much is scrolled.
//
this.delta = this.delta - diff;
this.y... | javascript | {
"resource": ""
} |
q32458 | arrayHasAdjacent | train | function arrayHasAdjacent(values, array) {
error_if_not_array_1.errorIfNotArray(values);
if (is_empty_not_empty_1.isEmpty(values))
return false;
var indexes = array_get_indexes_1.getIndexesOf(values[0], array);
var i = -1;
while (++i < indexes.length) {
if (indexes[i] + values.length... | javascript | {
"resource": ""
} |
q32459 | restartAppFromWatching | train | function restartAppFromWatching(err) {
updateWatcherCount()
if (err) self.emit('error', err)
if (dashboard.state !== 'stop') {
log('Restarting ' + conf.name + ' due to file watch trigger')
appLink.afterThat('restart')
} else log('Watcher restart ignored in stop state')
} | javascript | {
"resource": ""
} |
q32460 | renderTemplate | train | function renderTemplate(fragment, templateName) {
if (templateName === 'none') return fragment._txt;
var t = generator.template$[templateName];
if (!t) {
log('Unknown template %s for %s, using default.', templateName, fragment._href);
t = generator.template$.default;
}
var out;
try ... | javascript | {
"resource": ""
} |
q32461 | renderPage | train | function renderPage(page) {
var template = pageTemplate(page);
var html = renderTemplate(page, template);
return '<div data-render-page="' + esc(template) + '">' + html + '</div>';
} | javascript | {
"resource": ""
} |
q32462 | docTemplate | train | function docTemplate(page) {
return page.doclayout ||
(page.notemplate && 'none') ||
(page.nolayout && page.template) ||
(generator.template$['doc-layout'] && 'doc-layout') ||
layoutTemplate(page);
} | javascript | {
"resource": ""
} |
q32463 | rewriteLink | train | function rewriteLink(href, renderOpts) {
var imgRoute = renderOpts.fqImages && (renderOpts.fqImages.route || '/images/');
var imgPrefix = renderOpts.fqImages && renderOpts.fqImages.url;
var linkPrefix = renderOpts.fqLinks || renderOpts.relPath;
if (imgPrefix && u.startsWith(href, imgRoute)) { href = im... | javascript | {
"resource": ""
} |
q32464 | inventory | train | function inventory() {
var images = generator.images = {};
var currentPage;
var baseRenderImage = generator.renderer.image;
generator.renderer.image = function(href, title, text) {
if (!images[href]) { images[href] = []; }
images[href].push(currentPage._href);
return baseRenderImage(... | javascript | {
"resource": ""
} |
q32465 | createSession | train | function createSession(){
// can also check if any ealier session can be used
if (!currentSession){
const createNewSession = _setSessionReferrer();
const currentSessionCookie = utils.getCookie(constants.sessionCookieName);
if (currentSessionCookie && !createNewSession){
... | javascript | {
"resource": ""
} |
q32466 | train | function(subscription_id) {
var params = {
client_id: this._credentials.client_id,
client_secret: this._credentials.client_secret
};
if (subscription_id==='users') {
params.object = 'user';
} else if (subscription_id==='all') {
params.object = 'all';
} else {
params... | javascript | {
"resource": ""
} | |
q32467 | train | function() {
this.subscribe('user', function(error, response) {
if (!error && response) {
logger.info('instagram -', 'users', 'subscription confirmed');
Subscriber.prototype.subscriptions['users'] = response.id;
}
});
} | javascript | {
"resource": ""
} | |
q32468 | createAnnotation | train | function createAnnotation(desc) {
utils.check(['type', 'hasTarget', 'annotatedBy'], desc);
var anno = { type: desc.type, hasTarget: desc.hasTarget, annotatedAt : desc.annotatedAt || new Date().toISOString(), annotatedBy : desc.annotatedBy, state: desc.state || utils.states.annotations.unvalidated};
// used to cr... | javascript | {
"resource": ""
} |
q32469 | createRange | train | function createRange(desc) {
var fields = ['exact', 'offset', 'selector'];
utils.check(fields, desc);
return { exact: desc.exact, offset: desc.offset, selector: desc.selector};
} | javascript | {
"resource": ""
} |
q32470 | createInstance | train | function createInstance(desc) {
var fields = ['exact', 'instance', 'selector'];
utils.check(fields, desc);
return { exact: desc.exact, instance: desc.instance, selector: desc.selector};
} | javascript | {
"resource": ""
} |
q32471 | diffTable | train | function diffTable(results) {
var curRefs = $('.references-list li').text().toString().split('\n').map(function(r) { return r.trim(); });
$('#sbResults').html('<table><thead><tr><th>Title</th><th>Created</th><th>Source</th></tr></thead><tbody></tbody></table>');
console.log('diffResults', results);
if (results ... | javascript | {
"resource": ""
} |
q32472 | findInstanceOffset | train | function findInstanceOffset(anno, text) {
var re = new RegExp('\\b'+anno.exact+'\\b', 'g'), cur = 1, match;
while ((match = re.exec(text)) !== null) {
if (cur === anno.instance) {
return match.index;
}
cur++;
}
} | javascript | {
"resource": ""
} |
q32473 | displayAllAnnos | train | function displayAllAnnos(treeItems) {
var items = [], selector, newHTML, i;
// two passes; first assign offsets and add to array with the same selector
for (i in treeItems.map) {
var anno = treeItems.map[i];
console.log(anno);
if (anno.selector === 'body') {
anno.selector = '#SBEnc... | javascript | {
"resource": ""
} |
q32474 | insertAnno | train | function insertAnno(anno, newHTML) {
var annoID = 'SB-anno-' + anno.__id;
var startTag = '<span id="' + annoID + '" class="sbAnnotation sbAnnotation-b">', endTag = '</span>';
anno.offset = findInstanceOffset(anno, newHTML);
return newHTML.substring(0, anno.offset) + startTag + anno.exact + endTag + new... | javascript | {
"resource": ""
} |
q32475 | _getParent | train | function _getParent(config) {
if (config.hasOwnProperty('parent')) {
if (!isString(config.parent)) return config.parent;
if (cache.has(config.parent)) return cache.get(config.parent);
}
return settings.get('parent').parent || settings.get('parent');
} | javascript | {
"resource": ""
} |
q32476 | _getRequire | train | function _getRequire(config) {
if (!config.syncRequire && !config.resolveModulePath) return requireLike(config.filename);
const _requireResolver = {
basedir:config.basedir||path.dirname(config.filename),
parent:config.filename,
scope:config.scope,
useSandbox:config.useSandbox,
squashErrors:!!((... | javascript | {
"resource": ""
} |
q32477 | createId | train | function createId (coll) {
var _ = this
var idProperty = _.__id()
if (_.isEmpty(coll)) {
return 1
} else {
var id = _.maxBy(coll, function (doc) {
return doc[idProperty]
})[idProperty]
if (_.isFinite(id)) {
// Increment integer id
return ++id
} else {
// Generate str... | javascript | {
"resource": ""
} |
q32478 | hasClass | train | function hasClass(className) {
var i, val;
for(i = 0;i < this.length;i++) {
val = this.get(i).getAttribute(attr);
val = val ? val.split(/\s+/) : [];
if(~val.indexOf(className)) {
return true;
}
}
return false;
} | javascript | {
"resource": ""
} |
q32479 | removeClass | train | function removeClass(className) {
if(!className) {
// remove all classes from all matched elements
this.each(function(el) {
el.removeAttribute(attr);
});
return this;
}
var classes = className.split(/\s+/);
this.each(function(el) {
var val = el.getAttribute(attr);
// no class attri... | javascript | {
"resource": ""
} |
q32480 | toggleClass | train | function toggleClass(className) {
var classes = className.split(/\s+/)
, name
, i;
for(i = 0;i < classes.length;i++) {
name = classes[i];
if(this.hasClass(name)) {
this.removeClass(name)
}else{
this.addClass(name)
}
}
} | javascript | {
"resource": ""
} |
q32481 | delById | train | function delById(req, res, next) {
res.__apiMethod = 'delete';
var self = this;
var id = req.params.id;
var filter = this.option('delete', 'filter');
if (filter instanceof Function) filter = filter.call(this, req);
var query = extend({_id: id}, filter);
this.model.remove(query).exec(function(err, a... | javascript | {
"resource": ""
} |
q32482 | labelFragment | train | function labelFragment(fragment, func, source) {
// use 'in' to handle case where delim is set to ''
var leftDelim = 'leftDelim' in source ? source.leftDelim : '----';
var rightDelim = 'rightDelim' in source ? source.rightDelim : '----';
var headerDelim = 'headerDelim' in source ? source.heade... | javascript | {
"resource": ""
} |
q32483 | clientSave | train | function clientSave() {
u.each(sources, function(source) {
var dirtyFiles = u.filter(source.files, function(file) {
if (file._dirty) { // 1 means unsaved, 2 means saving
file._dirty = 2; // side effect of filter
return true;
}
return false;
});
if (... | javascript | {
"resource": ""
} |
q32484 | reloadSources | train | function reloadSources(names) {
names = u.isArray(names) ? names :
names ? [names] :
u.keys(opts.source$);
var results = [];
u.each(names, function(name) {
var source = opts.source$[name];
if (source) {
source._reloadFromSource = true;
results.push(name);... | javascript | {
"resource": ""
} |
q32485 | Alcatraz | train | function Alcatraz(method, source, domain) {
if (!(this instanceof Alcatraz)) return new Alcatraz(method, source);
this.domain = domain || ('undefined' !== typeof document ? document.domain : '');
this.method = 'if ('+method+') '+ method;
this.source = source;
this.compiled = null;
} | javascript | {
"resource": ""
} |
q32486 | polyconsole | train | function polyconsole(method) {
var attach = { debug: 1, error: 1, log: 1, warn: 1 };
//
// Ensure that this host environment always has working console.
//
global.console[method] = function polyfilled() {
var args = Array.prototype.slice.call(arguments, 0);
//
// ... | javascript | {
"resource": ""
} |
q32487 | getDate | train | function getDate(ymValue) {
checkNumber(ymValue)
var utcFullYear = Math.floor(ymValue / monthsPerYear) + zeroUtcFullYear
var utcMonth = modFix(Math.floor(ymValue), monthsPerYear) + zeroUtcMonth
return new Date(Date.UTC(utcFullYear, utcMonth))
} | javascript | {
"resource": ""
} |
q32488 | encodeDate | train | function encodeDate(date) {
if (!(date instanceof Date)) throw new Error('Value not Date: ' + date)
return (date.getUTCFullYear() * monthsPerYear + date.getUTCMonth()) - yearMonthZero
} | javascript | {
"resource": ""
} |
q32489 | handleIt | train | function handleIt(cb) {
callbacks = cb;
broadcast = callbacks.broadcast;
let msg = {
cmd: MessageType.RockPaperScissors,
handlerId: id
};
broadcast("action", msg);
// Return a promise for the result
deferred = q.defer();
return deferred.promise;
} | javascript | {
"resource": ""
} |
q32490 | beginCountdown | train | function beginCountdown() {
let msg = {
cmd: MessageType.RpsCountdown
};
broadcast("action", msg);
q.delay(COUNTDOWN_DELAY).done(determineWinner);
} | javascript | {
"resource": ""
} |
q32491 | restartGame | train | function restartGame(players) {
// Replace the current instance with a new instance
let newGame = new RockPaperScissors(game, players, winCounter, id);
proxy.swap(newGame);
q.delay(RESULTS_DELAY)
.done(function() {
deferred.resolve(newGame.handleIt(callbacks));
});
} | javascript | {
"resource": ""
} |
q32492 | containsPath | train | function containsPath(self, dirname) {
return self.__paths__.some(function(p) {
return p === dirname.substr(0, p.length);
});
} | javascript | {
"resource": ""
} |
q32493 | sortMatches | train | function sortMatches(self, matches, basename) {
var weights = {};
var ext_name = path.extname(basename);
var aliases = has(self.__aliases__, ext_name) ? self.__aliases__[ext_name] : [];
matches.forEach(function(match) {
// XXX: this doesn't work well with aliases
// i.e. entry=index.php, extna... | javascript | {
"resource": ""
} |
q32494 | match | train | function match(self, dirname, basename, callback) {
var pathname, stats, pattern, matches;
pattern = patternFor(self, basename);
matches = self.entries(dirname).filter(function(m) { return pattern.test(m); });
matches = sortMatches(self, matches, basename);
while (matches.length) {
pathname = path.join... | javascript | {
"resource": ""
} |
q32495 | setPositionCallback | train | function setPositionCallback(positionFunction){
if (typeof(positionFunction) == 'function'){
orientationCollector.setPositionCallback(positionFunction);
callbacks.positionCallback = positionFunction;
}
else
logger.warn('Trying to set a non function object as position callback');
... | javascript | {
"resource": ""
} |
q32496 | configureEventCollection | train | function configureEventCollection(eventType, collectionStatus, timePeriod){
if (eventType in dataConfig){
// check that collection status is present as true or false
collectionStatus = collectionStatus == false ? false : true;
dataConfig[eventType].status = collectionStatus;
if(!i... | javascript | {
"resource": ""
} |
q32497 | tick | train | function tick(){
performanceCollector.tick();
const useMedia = dataManager.getMediaState();
const playTimeSinceStart = timeManager.getPlayTimeSinceStart();
for (let key in dataConfig){
const infoDict = dataConfig[key];
if (infoDict.status &&
playTimeSinceStart - infoDic... | javascript | {
"resource": ""
} |
q32498 | _setEvents | train | function _setEvents(eventsArray){
for (let i = 0; i < eventsArray.length; i++){
let event = eventsArray[i];
dataManager.registerEvent(event[0], event[1], event[2]);
}
} | javascript | {
"resource": ""
} |
q32499 | train | function(propertyName, value)
{
if (this[propertyName] === value)
{
return this;
}
// Ensure numbers are returned as Number not String
if (value && conbo.isString(value) && !isNaN(value))
{
value = parseFloat(value);
if (isNaN(value)) value = '';
}
this[propertyName] = valu... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.