_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q10500
setLab
train
function setLab(color, l, a, b) { var white = [ 95.047, 100.000, 108.883 ]; //for X, Y, Z var y = (l + 16) / 116; var x = a / 500 + y; var z = y - b / 200; x = fromLabValueToXYZValue(x, white[0]); y = fromLabValueToXYZValue(y, white[1]); z = fromLabValueToXYZValue(z, white[2]); return setXYZ(color, x, y, z); }
javascript
{ "resource": "" }
q10501
getLab
train
function getLab(color) { var xyz = getXYZ(color); var white = [ 95.047, 100.000, 108.883 ]; //for X, Y, Z var x = fromXYZValueToLabValue(xyz[0], white[0]); var y = fromXYZValueToLabValue(xyz[1], white[1]); var z = fromXYZValueToLabValue(xyz[2], white[2]); return [ 116 * y - 16, 500 * (x - y), 200 * (y - z) ] }
javascript
{ "resource": "" }
q10502
DatabaseDbModel
train
function DatabaseDbModel(name, tableName) { this.__name = name; this.hasRelationships = false; this.hasValidations = false; this.hasMethods = false; this.hasStatics = false; this.hasFields = false; this.fields = {}; this.__hasMany = {}; this.__hasOne = {}; this.__belongsTo = {}; this.__errors = {}; this.__jsonFields = []; this.hasJsonFields = false; this.methods = {}; this.statics = {}; this.validations = {}; this.options = { timestamps: true, createdAt: 'created_at', updatedAt: 'updated_at', deletedAt: false }; if (typeof tableName === 'string') { this.options['tableName'] = tableName; } else { this.options['tableName'] = tableName; } this.instanceMethods(); }
javascript
{ "resource": "" }
q10503
Enum
train
function Enum(name, values) { /** The generic Enum instance * @constructor */ function EnumInstance(x) {return _.includes(EnumInstance, x)} Object.defineProperties(EnumInstance, { __jsmf__: {value: {uuid: generateId(), conformsTo: Enum}} , __name: {value: name} , getName: {value: getName} , conformsTo: {value: () => conformsTo(EnumInstance)} }) if (_.isArray(values)) { _.forEach(values, (v, k) => EnumInstance[v] = k) } else { _.forEach(values, (v, k) => EnumInstance[k] = v) } return EnumInstance }
javascript
{ "resource": "" }
q10504
createElementModule
train
function createElementModule() { return gulp .src(`./${config.src.path}/${config.src.entrypoint}`) .pipe( modifyFile(content => { return content.replace( new RegExp(`../node_modules/${config.element.scope}/`, 'g'), '../' ); }) ) .pipe( rename({ basename: config.element.tag }) ) .pipe(gulp.dest(`./${config.temp.path}`)); }
javascript
{ "resource": "" }
q10505
injectTemplate
train
function injectTemplate(forModule) { return ( gulp .src( forModule ? `./${config.temp.path}/${config.element.tag}.js` : `./${config.temp.path}/${config.element.tag}.script.js` ) // Inject the template html. .pipe( inject(gulp.src(`./${config.temp.path}/${config.src.template.html}`), { starttag: '[[inject:template]]', endtag: '[[endinject]]', removeTags: true, transform: util.transforms.getFileContents }) ) // Inject the style css. .pipe( inject(gulp.src(`./${config.temp.path}/${config.src.template.css}`), { starttag: '[[inject:style]]', endtag: '[[endinject]]', removeTags: true, transform: util.transforms.getFileContents }) ) .pipe(gulp.dest(`./${config.temp.path}`)) ); }
javascript
{ "resource": "" }
q10506
train
function(index, value) { if (index && value) { if (this.cache[index] === undefined) { this.cache[index] = false; } this.cache[index] = value; }else{ if (!index) { return this.cache; } else if (this.cache[index]) { return this.cache[index]; } } return this; }
javascript
{ "resource": "" }
q10507
train
function(component) { var cid, foundCmp; if (typeof component === 'object') { cid = component.id(); } foundCmp = false; $.each(jsCow.componentsObjectList, function(i, c) { if (c.id() === component) { foundCmp = c; } }); return foundCmp; }
javascript
{ "resource": "" }
q10508
train
function(childs) { var list = []; if ( childs instanceof Array ) { list = childs; } else { list.push(childs); } $.each(list, (function(self) { return function(i, child) { if (typeof child === 'object' && !child.__cfg__.__execInit__) { var content = self.view().content(); if ( content ) { content.append( child.placeholder() ); } else { content = self.placeholder(); } child.parent(self); child.target(content); self.__children__.push(child); } }; })(this)); return this; }
javascript
{ "resource": "" }
q10509
train
function(child) { window.setTimeout((function(self, child) { return function() { if (!child.config.__execInit__ && typeof child === 'object') { self.add(child); child.__init(); } }; }(this, child)), 0); return this; }
javascript
{ "resource": "" }
q10510
train
function(cmp) { // Remove the component reference from parent children list if (typeof cmp !== 'undefined' && typeof cmp === 'object') { $(this.children()).each((function(self, cmp) { return function(i,c) { if (c.id() === cmp.id()) { self.__children__.splice(i,1); } }; })(this, cmp)); } else { // Call to remove the component reference from parent children list if (typeof this.parent() !== 'undefined' && this.parent()) { this.parent().del(this); } // Remove the component domelemeents and delete the component instance from global jscow instance list $(jsCow.componentsObjectList).each((function(self) { return function(i, c) { if (c !== 'undefined' && c.id() === self.id()) { c.view().removeAll(); jsCow.componentsObjectList.splice(i,1); } }; })(this)); // Delete children components of the component to be delete var list = this.__children__; if (list.length > 0) { $(list).each(function(i,c) { c.del(); }); } } return this; }
javascript
{ "resource": "" }
q10511
train
function(method, root) { var methodList; if (root === true) { $.extend(true, this, method); } else { var _this = this; if (!this.extension) { var ext = function() {}; methodList = {}; $.each(method, function(i, m) { methodList[i] = (function( _super, m, i ) { m._super = typeof _super[i] === 'function' ? _super[i] : function(){}; return function() { m.apply( _super, arguments); }; })( _this, m, i ); }); $.extend(true, ext.prototype, methodList); this.extension = new ext(); } else { methodList = {}; $.each(method, function(i, m) { methodList[i] = (function( _super, m, i ) { m._super = typeof _super[i] === 'function' ? _super[i] : function(){}; return function() { m.apply( _super, arguments); }; })( _this, m, i ); }); $.extend(true, this.extension, methodList); } } return this; }
javascript
{ "resource": "" }
q10512
train
function(config) { var cfg = config; var self = this; var viewList = this.list(); $(viewList).each(function(i, view) { if (!view.isInit) { if (view.dom !== 'undefined' && view.dom.main !== 'undefined') { if (i === 0 && self.cmp().placeholder()) { self.cmp().placeholder().replaceWith( view.dom.main ); } if (i > 0) { viewList[ i - 1 ].dom.main.after( view.dom.main ); } } view.isInit = true; } }).promise().done(function() { self.cmp().trigger('view.ready'); }); }
javascript
{ "resource": "" }
q10513
train
function() { var self = this; var viewList = this.list(); $.each(viewList, function(i, view) { self.cmp().trigger("view.update"); }); return this; }
javascript
{ "resource": "" }
q10514
train
function(target) { var self = this; var viewList = this.list(); $.each(viewList, function(i, view) { view.main().appendTo(target); self.cmp().target(target); }); return this; }
javascript
{ "resource": "" }
q10515
train
function (event, d, l) { var config = this.cmp().config(); var data = d; var local = l; if (typeof d === 'undefined' || !d) { data = config; }else if (typeof d === 'object') { data = d; }else{ data = {}; } if (data) { var self = this; if (typeof local === 'undefined' || !local) { local = this.cmp(); } else { local = false; } if (jsCow.events[event] !== undefined) { $.each(jsCow.events[event], (function(self, event, data, local) { return function (i, e) { if (typeof local === "object" && local.id() === e.sender.id() && e.local) { setTimeout( function() { if (jsCow.debug.events) { console.log("local :: trigger event ", "'"+e.event+"'", "from", "'"+self.cmp().id()+"' for '"+e.that.id()+"'."); } e.handler.apply(e.that, [{ data: data, sender: self.cmp(), date: new Date() }]); }, 0 ); } else if (self.isNot(local) === e.local) { setTimeout( function() { if (jsCow.debug.events) { console.log("global :: trigger even", "'"+e.event+"'", "from", "'"+self.cmp().id()+"' for '"+e.that.id()+"'."); } e.handler.apply(e.that, [{ data: data, sender: self.cmp(), date: new Date() }]); }, 0 ); } }; })(self, event, data, local)); } } return this; }
javascript
{ "resource": "" }
q10516
train
function (event, data, local) { // trigger event in current component var bubble = this.bubbleTrigger(event, data, local); if (bubble) { // Next Event bubbling - up this.bubbleOut(event, data, local); // Next Event bubbling - down this.bubbleIn(event, data, local); } }
javascript
{ "resource": "" }
q10517
train
function (event, data, local) { var bubble = true; this.trigger(event, data, local); return bubble; }
javascript
{ "resource": "" }
q10518
solveAngle
train
function solveAngle(a, b, c) { var temp = (a * a + b * b - c * c) / (2 * a * b); if (temp >= -1 && temp <= 1) { return radToDeg(Math.acos(temp)); } else { throw new Error("No angle solution for points " + a + " " + b + " " + c); } }
javascript
{ "resource": "" }
q10519
area
train
function area(poly) { var i = -1, n = poly.length, a, b = poly[n - 1], area = 0; while (++i < n) { a = b; b = poly[i]; area += a.y * b.x - a.x * b.y; } return Math.abs(area * 0.5); }
javascript
{ "resource": "" }
q10520
_loop
train
function _loop(i, storesLen) { var store = stores[i]; var getState = store.getState, name = store.anew.name, _store$dispatch = store.dispatch, reducers = _store$dispatch.reducers, effects = _store$dispatch.effects, actions = _store$dispatch.actions, _store$dispatch$batch = _store$dispatch.batch, done = _store$dispatch$batch.done, batches = _objectWithoutProperties(_store$dispatch$batch, ['done']); var getStoreState = function getStoreState() { return reduxStore.getState()[name]; }; /** * Merge into combined store */ reduxStore.dispatch.reducers[name] = reducers; reduxStore.dispatch.effects[name] = effects; reduxStore.dispatch.actions[name] = actions; reduxStore.dispatch.batch[name] = batches; reduxStore.getState[name] = getStoreState; /** * Update each store references */ store.subscribe = reduxStore.subscribe; store.anew.getBatches = function () { return reduxStore.anew.getBatches(); }; store.dispatch = function (action) { return reduxStore.dispatch(action); }; store.getState = getStoreState; /** * Redefine replace reducer */ store.replaceReducer = function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } anewStore.reducers[name] = nextReducer; reduxReducer = (0, _combineReducers2.default)(anewStore.reducers); reduxStore.dispatch({ type: '@@anew:RESET' }); }; /** * Reassign reducers, effects, and batch to maintain dispatch * object's shape per store. */ store.dispatch.persistor = reduxStore.persistor; store.dispatch.reducers = reducers; store.dispatch.effects = effects; store.dispatch.actions = actions; store.dispatch.batch = batches; store.dispatch.batch.done = done; /** * Reassign selectors to maintian getState * object's shape per store */ reduxStore.getState[name] = Object.assign(reduxStore.getState[name], getState); store.getState = Object.assign(store.getState, getState); /** * Assign Core */ store.anew.core = reduxStore; }
javascript
{ "resource": "" }
q10521
_slice
train
function _slice(args, from, to) { switch (arguments.length) { case 1: return _slice(args, 0, args.length); case 2: return _slice(args, from, args.length); default: var list = []; var idx = 0; var len = Math.max(0, Math.min(args.length, to) - from); while (idx < len) { list[idx] = args[from + idx]; idx += 1; } return list; } }
javascript
{ "resource": "" }
q10522
from
train
function from(arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) }
javascript
{ "resource": "" }
q10523
train
function(browser, data) { // Some browsers are platform specific so exit out if not available if(data[browser][process.platform]) { if(browser.indexOf("firefox") !== -1) { // Handles firefox, firefox aurora and firefox nightly cleanLaunchFirefox(browser, data); } else if(browser.indexOf("chrome") !== -1) { // Handles chrome and chrome canary cleanLaunchChrome(browser, data); } else if(browser.indexOf("opera") !== -1) { // Handles opera and opera next cleanLaunchOpera(browser, data); } else if(browser.indexOf("phantomjs") !== -1) { // Handles opera and opera next cleanLaunchPhantomjs(browser, data); } else { // Safari don't require special treatment data[browser].process = exec(data[browser][process.platform] + " " + url); } } }
javascript
{ "resource": "" }
q10524
canInitialize
train
function canInitialize(dependencies, initialized) { return !dependencies || dependencies.length === 0 || dependencies.every(function (name) { return !!initialized[name]; }); }
javascript
{ "resource": "" }
q10525
done
train
function done(error) { if (error) { errors.push(error); } if (--initializing <= 0) { if (errors && errors.length) { var errorResult = new Error('Errors occurred during initialization.'); errorResult.initializationErrors = errors; callback(errorResult); } else { processPostInitializeQueue(postInitializeQueue, callback); } } }
javascript
{ "resource": "" }
q10526
createPersistStore
train
function createPersistStore(reduxStore) { var persistor = (0, _reduxPersist.persistStore)(reduxStore); var dispatch = persistor.dispatch, getState = persistor.getState; reduxStore.persistor = persistor; reduxStore.getState.persistor = getState; reduxStore.dispatch.persistor = dispatch; reduxStore.dispatch.persistor = Object.assign(reduxStore.dispatch.persistor, { flush: persistor.flush, pause: persistor.pause, persist: persistor.flush, purge: persistor.purge }); return reduxStore; }
javascript
{ "resource": "" }
q10527
train
function(paths) { var appends = []; if (grunt.option("quiet") || config.quiet) { appends.push("--quiet"); } if (grunt.option("verbose") || config.verbose) { appends.push("--verbose"); } if (grunt.option("rules") || config.rules) { var rules = _.isString(config.rules) ? config.rules.split(",") : config.rules; appends.push("--rules=" + rules.join(",")); } if (grunt.option("dryRun") || config.dryRun) { appends.push("--dry-run"); } if (grunt.option("diff") || config.diff) { appends.push("--diff"); } if (grunt.option("allowRisky") || config.allowRisky) { appends.push("--allow-risky yes"); } if (grunt.option("usingCache") || config.usingCache) { appends.push("--using-cache " + config.usingCache); } if (grunt.option("configfile") || config.configfile) { appends.push("--config=" + config.configfile); } var bin = path.normalize(config.bin), append = appends.join(" "), cmds = []; if (paths.length) { cmds = _.map(paths, function(thePath) { return bin + " fix " + thePath + " " + append; }); } if (grunt.option("configfile") || config.configfile) { cmds.push(bin + " fix " + append); } return cmds; }
javascript
{ "resource": "" }
q10528
createPointObjects
train
function createPointObjects(array) { if (!array) { array = []; } var acc = array.reduce(function(accumulator, current) { if (current.x && current.y) { // Point accumulator.push(current); } else if (current.start && current.end && current.height) { // Arc // Consider an arc "flat enough" if its height is < the value times its length if (!current.interpolatedPoints) { current = new Arc(current.start, current.end, current.height); } var newPoints = current.interpolatedPoints({relative: 0.1}); accumulator = accumulator.concat(newPoints); } else if (current[0] && current[1]) { // x, y pair var pt = new Point(current[0], current[1]); accumulator.push(pt); } else { debug("don't know how to accommodate", current); } return accumulator; }, []); return acc; }
javascript
{ "resource": "" }
q10529
esc
train
function esc(str) { if(typeof(str) !== "string") str = "" + str; str = str.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(res) { switch(res) { case "\0": return "\\0"; case "\n": return "\\n"; case "\r": return "\\r"; case "\b": return "\\b"; case "\t": return "\\t"; case "\x1a": return "\\Z"; default: return "\\"+res; } }); return "'"+str+"'"; }
javascript
{ "resource": "" }
q10530
readComponents
train
function readComponents( componentPath, referenceFile, localeFile, layoutSegment, contentSegment, filingCabinet, renderer ) { logger.showInfo( '*** Reading components...' ); // Initialize the store. getComponents( componentPath, 0, '', referenceFile, localeFile, layoutSegment, contentSegment, filingCabinet.references, filingCabinet.documents, filingCabinet.layouts, filingCabinet.segments, filingCabinet.locales, renderer, '' ); }
javascript
{ "resource": "" }
q10531
makeFixer
train
function makeFixer(options) { if (typeof options === 'undefined') { return true; } if (typeof options === 'boolean') { return options; } const rulesToFix = options.rules; const fixWarnings = options.warnings; function ruleFixer(eslintMessage) { if (!rulesToFix) return true; if (rulesToFix.indexOf(eslintMessage.ruleId) !== -1) { return true; } return false; } function warningFixer(eslintMessage) { if (fixWarnings === false) { return eslintMessage.severity === 2; } return true; } return function (eslintMessage) { return ruleFixer(eslintMessage) && warningFixer(eslintMessage); }; }
javascript
{ "resource": "" }
q10532
createFunction
train
function createFunction() { // Lazy define. createFunction = function(args, body) { var result, anchor = freeDefine ? freeDefine.amd : Benchmark, prop = uid + 'createFunction'; runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=function(' + args + '){' + body + '}'); result = anchor[prop]; delete anchor[prop]; return result; }; // Fix JaegerMonkey bug. // For more information see http://bugzil.la/639720. createFunction = support.browser && (createFunction('', 'return"' + uid + '"') || _.noop)() == uid ? createFunction : Function; return createFunction.apply(null, arguments); }
javascript
{ "resource": "" }
q10533
delay
train
function delay(bench, fn) { bench._timerId = _.delay(fn, bench.delay * 1e3); }
javascript
{ "resource": "" }
q10534
getMean
train
function getMean(sample) { return (_.reduce(sample, function(sum, x) { return sum + x; }) / sample.length) || 0; }
javascript
{ "resource": "" }
q10535
isStringable
train
function isStringable(value) { return _.isString(value) || (_.has(value, 'toString') && _.isFunction(value.toString)); }
javascript
{ "resource": "" }
q10536
execute
train
function execute() { var listeners, async = isAsync(bench); if (async) { // Use `getNext` as the first listener. bench.on('complete', getNext); listeners = bench.events.complete; listeners.splice(0, 0, listeners.pop()); } // Execute method. result[index] = _.isFunction(bench && bench[name]) ? bench[name].apply(bench, args) : undefined; // If synchronous return `true` until finished. return !async && getNext(); }
javascript
{ "resource": "" }
q10537
getNext
train
function getNext(event) { var cycleEvent, last = bench, async = isAsync(last); if (async) { last.off('complete', getNext); last.emit('complete'); } // Emit "cycle" event. eventProps.type = 'cycle'; eventProps.target = last; cycleEvent = Event(eventProps); options.onCycle.call(benches, cycleEvent); // Choose next benchmark if not exiting early. if (!cycleEvent.aborted && raiseIndex() !== false) { bench = queued ? benches[0] : result[index]; if (isAsync(bench)) { delay(bench, execute); } else if (async) { // Resume execution if previously asynchronous but now synchronous. while (execute()) {} } else { // Continue synchronous execution. return true; } } else { // Emit "complete" event. eventProps.type = 'complete'; options.onComplete.call(benches, Event(eventProps)); } // When used as a listener `event.aborted = true` will cancel the rest of // the "complete" listeners because they were already called above and when // used as part of `getNext` the `return false` will exit the execution while-loop. if (event) { event.aborted = true; } else { return false; } }
javascript
{ "resource": "" }
q10538
compare
train
function compare(other) { var bench = this; // Exit early if comparing the same benchmark. if (bench == other) { return 0; } var critical, zStat, sample1 = bench.stats.sample, sample2 = other.stats.sample, size1 = sample1.length, size2 = sample2.length, maxSize = max(size1, size2), minSize = min(size1, size2), u1 = getU(sample1, sample2), u2 = getU(sample2, sample1), u = min(u1, u2); function getScore(xA, sampleB) { return _.reduce(sampleB, function(total, xB) { return total + (xB > xA ? 0 : xB < xA ? 1 : 0.5); }, 0); } function getU(sampleA, sampleB) { return _.reduce(sampleA, function(total, xA) { return total + getScore(xA, sampleB); }, 0); } function getZ(u) { return (u - ((size1 * size2) / 2)) / sqrt((size1 * size2 * (size1 + size2 + 1)) / 12); } // Reject the null hypothesis the two samples come from the // same population (i.e. have the same median) if... if (size1 + size2 > 30) { // ...the z-stat is greater than 1.96 or less than -1.96 // http://www.statisticslectures.com/topics/mannwhitneyu/ zStat = getZ(u); return abs(zStat) > 1.96 ? (u == u1 ? 1 : -1) : 0; } // ...the U value is less than or equal the critical U value. critical = maxSize < 5 || minSize < 3 ? 0 : uTable[maxSize][minSize - 3]; return u <= critical ? (u == u1 ? 1 : -1) : 0; }
javascript
{ "resource": "" }
q10539
interpolate
train
function interpolate(string) { // Replaces all occurrences of `#` with a unique number and template tokens with content. return _.template(string.replace(/\#/g, /\d+/.exec(templateData.uid)))(templateData); }
javascript
{ "resource": "" }
q10540
findItem
train
function findItem( path, items ) { var result = null; items.forEach( function ( item ) { if (!result && item instanceof MenuItem && item.paths.filter( function( value ) { return value === path; } ).length > 0) result = item; if (!result && item instanceof MenuNode) { var child = findItem( path, item.children ); if (child) result = child; } } ); return result; }
javascript
{ "resource": "" }
q10541
getAggregationFields
train
function getAggregationFields(query, aggParam, supplimentalBanList) { let retVal = []; const _aggParam = aggParam || 'aggregations'; if (!query[_aggParam]) { return retVal; } const _supplimentalBanList = supplimentalBanList || {}; _.each(query[_aggParam].split(','), (agg) => { assertAggNameIsAllowed(agg, _supplimentalBanList); _supplimentalBanList[agg] = true; let _type = query[`${agg}.type`]; !_type && (_type = 'terms'); const aggOptions = permittedAggOptions[_type]; _.each(aggOptions, (aggOption) => { const expectedOptionName = `${agg}.${aggOption}`; retVal.push(expectedOptionName); }); if (query[`${agg}.aggregations`]) { const nestedAggFields = getAggregationFields(query, `${agg}.aggregations`, _supplimentalBanList); retVal = retVal.concat(nestedAggFields); } }); return retVal; }
javascript
{ "resource": "" }
q10542
getTopHitsResult
train
function getTopHitsResult(aggResponse, aggName, esResponse, aggregationObjects) { const aggLookup = {}; const linked = {}; // keeps track of all linked objects. type->id->true const typeLookup = {}; function getAggLookup(_aggLookup, _aggregationObjects) { _.each(_aggregationObjects, (aggObj) => { _aggLookup[aggObj.name] = aggObj; aggObj.aggregations && getAggLookup(_aggLookup, aggObj.aggregations); }); } getAggLookup(aggLookup, aggregationObjects); // dedupes already-linked entities. if (aggLookup[aggName] && aggLookup[aggName].include) { _.each(aggLookup[aggName].include.split(','), (linkProperty) => { if (_this.collectionLookup[linkProperty]) { const _type = inflect.pluralize(_this.collectionLookup[linkProperty]); typeLookup[linkProperty] = _type; esResponse.linked && _.each(esResponse.linked[_type] || [], (resource) => { linked[_type] = linked[_type] || {}; linked[_type][resource.id] = true; }); } }); } return _.map(aggResponse.hits.hits, (esReponseObj) => { if (aggLookup[aggName] && aggLookup[aggName].include) { _.each(aggLookup[aggName].include.split(','), (linkProperty) => { if (typeLookup[linkProperty]) { const _type = typeLookup[linkProperty]; // if this isn't already linked, link it. // TODO: links may be an array of objects, so treat it that way at all times. const hasLinks = !!(esReponseObj._source.links) && !!(esReponseObj._source.links[linkProperty]); if (hasLinks) { const entitiesToInclude = [].concat(unexpandSubentity(esReponseObj._source.links[linkProperty])); _.each(entitiesToInclude, (entityToInclude) => { const entityIsAlreadyIncluded = !!(linked[_type]) && !!(linked[_type][entityToInclude.id]); if (!entityIsAlreadyIncluded) { esResponse.linked = esResponse.linked || {}; esResponse.linked[_type] = esResponse.linked[_type] || []; esResponse.linked[_type] = esResponse.linked[_type].concat(entityToInclude); linked[_type] = linked[_type] || {}; linked[_type][entityToInclude.id] = true; } }); } } else { console.warn(`[Elastic-Harvest] ${linkProperty} is not in collectionLookup. ${linkProperty} was either ` + 'incorrectly specified by the end-user, or dev failed to include the relevant key in the lookup ' + 'provided to initialize elastic-harvest.'); } }); } return unexpandEntity(esReponseObj._source); }); }
javascript
{ "resource": "" }
q10543
createBuckets
train
function createBuckets(terms) { return _.map(terms, (term) => { // 1. see if there are other terms & if they have buckets. const retVal = { key: term.key, count: term.doc_count }; _.each(term, (aggResponse, responseKey) => { if (responseKey === 'key' || responseKey === 'doc_count') { return null; } else if (aggResponse.buckets) { retVal[responseKey] = createBuckets(aggResponse.buckets); } else if (aggResponse.hits && aggResponse.hits.hits) { // top_hits aggs result from nested query w/o reverse nesting. retVal[responseKey] = getTopHitsResult(aggResponse, responseKey, _esResponse, aggregationObjects); // to combine nested aggs w others, you have to un-nest them, & this takes up an aggregation-space. } else if (responseKey !== 'reverse_nesting' && aggResponse) { // stats & extended_stats aggs // This means it's the result of a nested stats or extended stats query. if (aggResponse[responseKey]) { retVal[responseKey] = aggResponse[responseKey]; } else { retVal[responseKey] = aggResponse; } } else if (responseKey === 'reverse_nesting') { _.each(aggResponse, (reverseNestedResponseProperty, reverseNestedResponseKey) => { if (reverseNestedResponseKey === 'doc_count') { return null; } else if (reverseNestedResponseProperty.buckets) { retVal[reverseNestedResponseKey] = createBuckets(reverseNestedResponseProperty.buckets); // this gets a little complicated because reverse-nested then renested subdocuments are .. // complicated (because the extra aggs for nesting throws things off). } else if (reverseNestedResponseProperty[reverseNestedResponseKey] && reverseNestedResponseProperty[reverseNestedResponseKey].buckets) { retVal[reverseNestedResponseKey] = createBuckets( reverseNestedResponseProperty[reverseNestedResponseKey].buckets); // this gets a little MORE complicated because of reverse-nested then renested top_hits aggs } else if (reverseNestedResponseProperty.hits && reverseNestedResponseProperty.hits.hits) { retVal[reverseNestedResponseKey] = getTopHitsResult(reverseNestedResponseProperty, reverseNestedResponseKey, _esResponse, aggregationObjects); // stats & extended_stats aggs } else if (reverseNestedResponseProperty) { // This means it's the result of a nested stats or extended stats query. if (reverseNestedResponseProperty[reverseNestedResponseKey]) { retVal[reverseNestedResponseKey] = reverseNestedResponseProperty[reverseNestedResponseKey]; } else { retVal[reverseNestedResponseKey] = reverseNestedResponseProperty; } } return null; }); } return null; }); return retVal; }); }
javascript
{ "resource": "" }
q10544
createCustomRoutingQueryString
train
function createCustomRoutingQueryString(pathToCustomRoutingKey, query) { const invalidRegexList = [/^ge=/, /^gt=/, /^ge=/, /^lt=/, /\*$/]; // array of invalid regex let customRoutingValue; if (!pathToCustomRoutingKey) return ''; // customRouting is not enabled for this type customRoutingValue = query[pathToCustomRoutingKey]; // fetch the value // filters like [ 'gt: '10', lt: '20' ] are not valid customRouting values but may show up if (typeof customRoutingValue !== 'string') return ''; // check for range and wildcard filters _.forEach(invalidRegexList, (invalidRegex) => { // if our value matches one of these regex, it's probably not the value we should be hashing for customRouting if (invalidRegex.test(customRoutingValue)) { customRoutingValue = ''; return false; } return true; }); return customRoutingValue ? `routing=${customRoutingValue}` : ''; }
javascript
{ "resource": "" }
q10545
unexpandEntity
train
function unexpandEntity(sourceObject, includeFields) { _.each(sourceObject.links || [], (val, key) => { if (!_.isArray(sourceObject.links[key])) { // I know the extra .toString seems unnecessary, but sometimes val.id is already an objectId, and other times its // a string. sourceObject.links[key] = val.id && val.id.toString() || val && val.toString && val.toString(); } else { _.each(sourceObject.links[key], (innerVal, innerKey) => { sourceObject.links[key][innerKey] = innerVal.id.toString(); }); } }); return (includeFields && includeFields.length) ? Util.includeFields(sourceObject, includeFields) : sourceObject; }
javascript
{ "resource": "" }
q10546
unexpandSubentity
train
function unexpandSubentity(subEntity) { if (_.isArray(subEntity)) { _.each(subEntity, (entity, index) => { subEntity[index] = unexpandSubentity(entity); }); } else { _.each(subEntity, (val, propertyName) => { if (_.isObject(val) && val.id) { subEntity.links = subEntity.links || {}; subEntity.links[propertyName] = val.id; delete subEntity[propertyName]; } }); } return subEntity; }
javascript
{ "resource": "" }
q10547
groupNestedPredicates
train
function groupNestedPredicates(_nestedPredicates) { let maxDepth = 0; const nestedPredicateObj = {}; const nestedPredicateParts = _.map(_nestedPredicates, (predicateArr) => { const predicate = predicateArr[0]; const retVal = predicate.split('.'); nestedPredicateObj[predicate] = predicateArr[1]; retVal.length > maxDepth && (maxDepth = retVal.length); return retVal; }); const groups = {}; for (let i = 0; i < maxDepth; i++) { groups[i] = _.groupBy(nestedPredicateParts, (predicateParts) => { let retval = ''; for (let j = 0; j < i + 1; j++) { retval += (predicateParts[j] ? `${predicateParts[j]}.` : ''); } return retval.substr(0, retval.length - 1); }); } const completed = {}; const levels = {}; const paths = {}; // Simplifies the grouping for (let i = maxDepth - 1; i >= 0; i--) { _.each(groups[i], (values, key) => { _.each(values, (value) => { const strKey = value.join('.'); if (!completed[strKey] && values.length > 1) { (!levels[i] && (levels[i] = [])); levels[i].push(strKey); (completed[strKey] = true); paths[i] = key; } if (!completed[strKey] && i < 1) { (!levels[i] && (levels[i] = [])); levels[i].push(strKey); (completed[strKey] = true); paths[i] = key; } }); }); } return { groups: levels, paths, nestedPredicateObj }; }
javascript
{ "resource": "" }
q10548
train
function(indexOrItem) { this._assertNotDestroyed('$save'); var self = this; var item = self._resolveItem(indexOrItem); var key = self.$keyAt(item); if( key !== null ) { var ref = self.$ref().ref().child(key); var data = $wilddogUtils.toJSON(item); return $wilddogUtils.doSet(ref, data).then(function() { self.$$notify('child_changed', key); return ref; }); } else { return $wilddogUtils.reject('Invalid record; could determine key for '+indexOrItem); } }
javascript
{ "resource": "" }
q10549
train
function(indexOrItem) { this._assertNotDestroyed('$remove'); var key = this.$keyAt(indexOrItem); if( key !== null ) { var ref = this.$ref().ref().child(key); return $wilddogUtils.doRemove(ref).then(function() { return ref; }); } else { return $wilddogUtils.reject('Invalid record; could not determine key for '+indexOrItem); } }
javascript
{ "resource": "" }
q10550
train
function(profile) { var user = this.getUser(); if (user) { return this._q.when(user.updateProfile(profile)); } else { return this._q.reject("Cannot update profile since there is no logged in user."); } }
javascript
{ "resource": "" }
q10551
WilddogObject
train
function WilddogObject(ref) { if( !(this instanceof WilddogObject) ) { return new WilddogObject(ref); } // These are private config props and functions used internally // they are collected here to reduce clutter in console.log and forEach this.$$conf = { // synchronizes data to Wilddog sync: new ObjectSyncManager(this, ref), // stores the Wilddog ref ref: ref, // synchronizes $scope variables with this object binding: new ThreeWayBinding(this), // stores observers registered with $watch listeners: [] }; // this bit of magic makes $$conf non-enumerable and non-configurable // and non-writable (its properties are still writable but the ref cannot be replaced) // we redundantly assign it above so the IDE can relax Object.defineProperty(this, '$$conf', { value: this.$$conf }); this.$id = $wilddogUtils.getKey(ref.ref()); this.$priority = null; $wilddogUtils.applyDefaults(this, this.$$defaults); // start synchronizing data with Wilddog this.$$conf.sync.init(); }
javascript
{ "resource": "" }
q10552
train
function () { var self = this; var ref = self.$ref(); var data = $wilddogUtils.toJSON(self); return $wilddogUtils.doSet(ref, data).then(function() { self.$$notify(); return self.$ref(); }); }
javascript
{ "resource": "" }
q10553
train
function(fn, ctx, wait, maxWait) { var start, cancelTimer, args, runScheduledForNextTick; if( typeof(ctx) === 'number' ) { maxWait = wait; wait = ctx; ctx = null; } if( typeof wait !== 'number' ) { throw new Error('Must provide a valid integer for wait. Try 0 for a default'); } if( typeof(fn) !== 'function' ) { throw new Error('Must provide a valid function to debounce'); } if( !maxWait ) { maxWait = wait*10 || 100; } // clears the current wait timer and creates a new one // however, if maxWait is exceeded, calls runNow() on the next tick. function resetTimer() { if( cancelTimer ) { cancelTimer(); cancelTimer = null; } if( start && Date.now() - start > maxWait ) { if(!runScheduledForNextTick){ runScheduledForNextTick = true; utils.compile(runNow); } } else { if( !start ) { start = Date.now(); } cancelTimer = utils.wait(runNow, wait); } } // Clears the queue and invokes the debounced function with the most recent arguments function runNow() { cancelTimer = null; start = null; runScheduledForNextTick = false; fn.apply(ctx, args); } function debounced() { args = Array.prototype.slice.call(arguments, 0); resetTimer(); } debounced.running = function() { return start > 0; }; return debounced; }
javascript
{ "resource": "" }
q10554
runNow
train
function runNow() { cancelTimer = null; start = null; runScheduledForNextTick = false; fn.apply(ctx, args); }
javascript
{ "resource": "" }
q10555
otuMapArray
train
function otuMapArray(data) { this.data = data; this.len = this.data.length; this.data[this.len] = []; for (var i = 0; i < this.len; i++) { this.data[this.len].push(i); } this.reset = function () { var _this = this; if (!this.data[this.len]) { this.data[this.len] = []; } for (var i = 0; i < this.len; i++) { this.data[this.len].push(i); } }; this.pop = function () { var _this = this; var index = this.rng(this.data[this.len].length); return this.data[this.data[this.len].splice(index, 1)]; }; this.rng = function (range) { var _this = this; if (range === 0) this.reset(); return randy.randInt(range); }; }
javascript
{ "resource": "" }
q10556
prepareStack
train
function prepareStack(stack) { let lines = stack.split('\n').slice(1) if (lines.length > 500) { // Stack too big, probably this is caused by stack overflow // Remove middle values let skipped = lines.length - 500, top = lines.slice(0, 250), bottom = lines.slice(-250) lines = top.concat('--- skipped ' + skipped + ' frames ---', bottom) } return lines.map(line => line.trim().replace(/^at /, '').replace(basePath, '.')) }
javascript
{ "resource": "" }
q10557
getReference
train
function getReference( referenceFile ) { var text = ''; // Read references file. var referencePath = path.join( process.cwd(), referenceFile ); var stats = fs.statSync( referencePath ); if (stats && stats.isFile()) { text = fs.readFileSync( referencePath, { encoding: 'utf8' } ); // Find common root definitions (tilde references). var tildes = { }; var re = /^\s*\[(~\d*)]\s*:/g; var source = text.split( '\n' ); var target = [ ]; for (var i = 0; i < source.length; i++) { var line = source[ i ].trim(); // Search common root pattern. var result = re.exec( line ); if (result) // Save common root value. tildes[ result[ 1 ] ] = line.substring( line.indexOf( ':' ) + 1 ).trim(); else if (line[ 0 ] === '[') // Store reference link. target.push( line ); } text = target.join( '\n' ); // Replace tilde+number pairs with common roots. var noIndex = false; for (var attr in tildes) { if (tildes.hasOwnProperty( attr )) { if (attr === '~') noIndex = true; else { var re_n = new RegExp( ' ' + attr, 'g' ); var re_value = ' ' + tildes[ attr ]; text = text.replace( re_n, re_value ); } } } // Finally replace tildes with its common root. if (noIndex) text = text.replace( / ~/g, ' ' + tildes[ '~' ] ); } return text; }
javascript
{ "resource": "" }
q10558
createPersistConfig
train
function createPersistConfig(persist, name) { switch (typeof persist === 'undefined' ? 'undefined' : _typeof(persist)) { case 'boolean': if (persist) { persist = { key: name, storage: _storage2.default }; } break; case 'object': persist = _extends({ storage: _storage2.default }, persist, { key: name }); break; } return persist; }
javascript
{ "resource": "" }
q10559
getListener
train
function getListener(event, id) { if (hasListeners(event)) { var listeners = getListeners(event); if (_.has(listeners, id)) { return listeners[id]; } } return false; }
javascript
{ "resource": "" }
q10560
addListener
train
function addListener(id, event, listener) { if (!hasListeners(event)) { context._events[event] = {}; } context._events[event][id] = listener; return id; }
javascript
{ "resource": "" }
q10561
wipeCache
train
function wipeCache(stubs, resolver, waveCallback, removeFromCache = removeFromCache_nodejs) { waveCallback = waveCallback || waveCallback_default; const cache = require.cache; wipeMap( cache, (cache, callback) => cache.forEach( moduleName => resolver(stubs, moduleName) && callback(moduleName) ), waveCallback, removeFromCache ); }
javascript
{ "resource": "" }
q10562
train
function(){ scheduler.sequence(function(){ console.log("running"); motors.set({"A,B": 20, "C,D": 0}); //move left wheels }).wait(function(){ //wait until we moved off the line return colorSensor.value == ColorSensor.colors.WHITE; }).do(function(){ motors.set({"A,B": 0, "C,D": 20}); //move right wheels }).wait(function(){ //wait until we're back on the line if(colorSensor.value == ColorSensor.colors.BLUE) console.log("blue now"); return colorSensor.value == ColorSensor.colors.BLUE; }).wait(function(){ //now wait until we're off the line if(colorSensor.value == ColorSensor.colors.WHITE) console.log("now white"); return colorSensor.value == ColorSensor.colors.WHITE; }).do(function(){ motors.set({"A,B": 20, "C,D": 0}); //move left wheels }).wait(function(){ //wait until we're back on the line return colorSensor.value == ColorSensor.colors.BLUE; }).do(function(){ console.log("rescheduling"); this.schedule(); //reschedule the sequence now that we're back at the starting conditions }).schedule(); //schedule the sequence to be run }
javascript
{ "resource": "" }
q10563
train
async function(fileName, fileExt, resolve, parse, cwd) { // Get an array of paths to tell the location of potential files const locations = resolve(fileName, fileExt) // Look for the data in the same directory as filePath const relativePath = await locatePath(locations, { cwd }) // Only continue with files if (relativePath == null) return null // Path to data must be absolute to read it const absolutePath = path.resolve(cwd, relativePath) // Load the file const contents = util.promisify(fs.readFile)(absolutePath, 'utf8') // Parse file contents with the given parser if (parse != null) { try { return parse(contents, absolutePath) } catch (err) { throw new Error(`Failed to parse '${ relativePath }'`) } } return contents }
javascript
{ "resource": "" }
q10564
train
async function(filePath, index, resolvers, opts) { // Use the filePath to generate a unique id const id = crypto.createHash('sha1').update(filePath).digest('hex') // File name and extension const { name: fileName, ext: fileExt } = path.parse(filePath) // Absolute directory path to the component const fileCwd = path.resolve(opts.cwd, path.dirname(filePath)) // Absolute preview URL const rawURL = '/' + rename(filePath, '.html') const processedURL = opts.url(rawURL) // Reuse data from resolver and add additional information const data = await pMap(resolvers, async (resolver, index) => { return Object.assign({}, resolver, { index, data: await getFile(fileName, fileExt, resolver.resolve, resolver.parse, fileCwd) }) }) return { index, id, name: fileName, src: filePath, url: processedURL, data } }
javascript
{ "resource": "" }
q10565
caseInsensitiveLookup
train
function caseInsensitiveLookup (object, lookup) { lookup = lookup.toLowerCase(); for (var property in object) { if (object.hasOwnProperty(property) && lookup == property.toLowerCase()) { return object[property]; } } return undefined; }
javascript
{ "resource": "" }
q10566
tryPackErrorKeys
train
function tryPackErrorKeys(object, results) { if (object instanceof Error) { results.push(packValue("message"), packValue("stack")); return true; } }
javascript
{ "resource": "" }
q10567
packValue
train
function packValue(value) { const result = memoizedMap.get(value); if (result == null) { if (value >= MIN_DICT_INDEX && value <= MAX_VERBATIM_INTEGER && Number.isInteger(value)) return -value; memoize(value); if (typeof value === "number") return String(value); if (/^[0-9\.]|^~/.test(value)) return `~${value}`; return value; } return result; }
javascript
{ "resource": "" }
q10568
memoize
train
function memoize(value, objectKey) { const oldValue = memoized[memoizedIndex]; if (oldValue !== undefined) { memoizedMap.delete(oldValue); memoizedObjectMap.delete(oldValue); } if (objectKey) memoizedObjectMap.set(objectKey, memoizedIndex); else memoizedMap.set(value, memoizedIndex); memoized[memoizedIndex] = value; memoizedIndex++; if (memoizedIndex >= maxDictSize + MIN_DICT_INDEX) memoizedIndex = MIN_DICT_INDEX; }
javascript
{ "resource": "" }
q10569
daisy_chain
train
function daisy_chain(head, tail) { var result = head; for (var i = 0; i < tail.length; i++) { result = new node({ type: "binary", operator: tail[i][1], left: result, right: tail[i][3] }); } return result; }
javascript
{ "resource": "" }
q10570
preprocessor_branch
train
function preprocessor_branch(if_directive, elif_directives, else_directive) { var elseList = elif_directives; if (else_directive) { elseList = elseList.concat([else_directive]); } var result = if_directive[0]; result.guarded_statements = if_directive[1].statements; var current_branch = result; for (var i = 0; i < elseList.length; i++) { current_branch.elseBody = elseList[i][0]; current_branch.elseBody.guarded_statements = elseList[i][1].statements; current_branch = current_branch.elseBody; } return result; }
javascript
{ "resource": "" }
q10571
Sounds
train
function Sounds(folder,loadCallback) { if(!folder) throw new Error('No folder given for sounds !') // sound is on by default this.muted=false; // contains sounds elements this.sounds={}; // contains sounds to load this.soundsToLoad=new Array(); // callback executed when each sounds are loaded this.loadedSounds=loadCallback; // detecting supported extensions var sound=document.createElement('audio'); this.exts=[]; if(sound.canPlayType('audio/ogg')) this.exts.push('ogg'); if(sound.canPlayType('audio/mp3')) this.exts.push('mp3'); if(sound.canPlayType('audio/x-midi')) this.exts.push('mid'); // folder containing sounds this.folder=folder; }
javascript
{ "resource": "" }
q10572
bindState
train
function bindState(rows) { // build state from rows and immutable initState //---------------------------------------------------------- this.state = merge( {} , this.props.initState , {rows} ) // fill state arrays with init vals //---------------------------------------------------------- function initVals(map, ct) { while (ct--) map.forEach((v, k) => k.push(v())) } const cols = Math.ceil(this.props.arLen, rows) const colMap = new Map() colMap.set(this.state.widths, () => 0) initVals(colMap, cols) const rowMap = new Map() rowMap.set(this.state.indices, () => []) rowMap.set(this.state.strs, () => '') initVals(rowMap, rows) }
javascript
{ "resource": "" }
q10573
readServerConfig
train
function readServerConfig( server ) { try { const severConfig = getConfig( appSeverConfig ); return Right( Object.assign( server, severConfig )); } catch ( e ) { print( chalk.red( `Failed to read ${SEVER_CONFIG}.` ), e.message ); print(); return Left( null ); } }
javascript
{ "resource": "" }
q10574
readWebpackConfig
train
function readWebpackConfig( server ) { const devConfig = server.webpackConfig && server.webpackConfig.dev; const configFile = paths.resolveApp( devConfig ) || appWebpackDevConfig; try { assert( existsSync( configFile ), `File ${devConfig || WEBPACK_DEV_CONFIG} is not exsit.` ); const wpConfig = getConfig( configFile ); // plugins: function if ( is.Function( wpConfig.plugins )) { wpConfig.plugins = wpConfig.plugins( wpConfig ); } // plugins: not array if ( !is.Array( wpConfig.plugins )) { wpConfig.plugins = [wpConfig.plugins]; } // plugins: array in array wpConfig.plugins = flatten( wpConfig.plugins.map(( plugin ) => { return is.Function( plugin ) ? plugin( wpConfig ) : plugin; })); server.webpackDevConfig = wpConfig; watchFiles.push( configFile ); return Right( server ); } catch ( e ) { print( chalk.red( `Failed to read ${devConfig || WEBPACK_DEV_CONFIG}.` ), e.message ); print(); return Left( null ); } }
javascript
{ "resource": "" }
q10575
Babbler
train
function Babbler (id) { if (!(this instanceof Babbler)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (!id) { throw new Error('id required'); } this.id = id; this.listeners = []; // Array.<Listen> this.conversations = {}; // Array.<Array.<Conversation>> all open conversations this.connect(); // automatically connect to the local message bus }
javascript
{ "resource": "" }
q10576
flattenAll
train
function flattenAll() { var result = []; for (var role in permissions) { result = result.concat(flatten(role)); } return uniq(result); }
javascript
{ "resource": "" }
q10577
flatten
train
function flatten(role) { var children = permissions[role] || []; var result = [role]; for (var i in children) { result = result.concat(flatten(children[i])); } return result; }
javascript
{ "resource": "" }
q10578
getParent
train
function getParent(role) { var result = []; for (var parentRole in permissions) { if (permissions[parentRole].indexOf(role) > -1) { result.push(parentRole); result = result.concat(getParent(parentRole)); } } return result; }
javascript
{ "resource": "" }
q10579
iszero
train
function iszero(x, tolerance) { if (tolerance === void 0) { tolerance = constants_1.EPSILON; } // the 'less-than-equal' comparision is necessary for correct result // when tolerance = 0 return Math.abs(x) <= tolerance; }
javascript
{ "resource": "" }
q10580
isequal
train
function isequal(a, b, tolerance) { if (tolerance === void 0) { tolerance = constants_1.EPSILON; } return iszero(a - b, tolerance); }
javascript
{ "resource": "" }
q10581
range
train
function range(a, b) { if (b === undefined) { b = a; a = 0; } b = Math.max(b, 0); var arr = []; for (var i = a; i < b; i++) { arr.push(i); } return new ndarray_1.NDArray(arr, { datatype: 'i32' }); }
javascript
{ "resource": "" }
q10582
eye
train
function eye(arg0, datatype) { var n, m; if (Array.isArray(arg0)) { n = arg0[0]; if (arg0.length > 1) { m = arg0[1]; } else { m = n; } } else { n = m = arg0; } var A = new ndarray_1.NDArray({ shape: [n, m], datatype: datatype, fill: 0 }); var ndiag = Math.min(n, m); for (var i = 0; i < ndiag; i++) { A.set(i, i, 1); } return A; }
javascript
{ "resource": "" }
q10583
zeros
train
function zeros(arg0, datatype) { var A; if (Array.isArray(arg0)) { A = new ndarray_1.NDArray({ shape: arg0, datatype: datatype }); } else { A = new ndarray_1.NDArray({ shape: [arg0], datatype: datatype }); } A.fill(0); return A; }
javascript
{ "resource": "" }
q10584
empty
train
function empty(arg0, datatype) { var A; if (Array.isArray(arg0)) { A = new ndarray_1.NDArray({ shape: arg0, datatype: datatype }); } else { A = new ndarray_1.NDArray({ shape: [arg0], datatype: datatype }); } return A; }
javascript
{ "resource": "" }
q10585
cross
train
function cross(A, B) { if (A.shape.length !== 1 || B.shape.length !== 1) { throw new Error('A or B is not 1D'); } if (A.length < 3 || B.length < 3) { throw new Error('A or B is less than 3 in length'); } var a1 = A.getN(0); var a2 = A.getN(1); var a3 = A.getN(2); var b1 = B.getN(0); var b2 = B.getN(1); var b3 = B.getN(2); return new ndarray_1.NDArray([ a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1 ]); }
javascript
{ "resource": "" }
q10586
length
train
function length(A) { if (A.shape.length !== 1) { throw new Error('A is not a 1D array'); } return Math.sqrt(dot(A, A)); }
javascript
{ "resource": "" }
q10587
dir
train
function dir(A) { if (A.shape.length !== 1) { throw new Error('A is not a 1D array'); } return div(A, length(A)); }
javascript
{ "resource": "" }
q10588
IIf
train
function IIf (condition, trueBlock, falseBlock) { if (!(this instanceof IIf)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (typeof condition === 'function') { this.condition = condition; } else if (condition instanceof RegExp) { this.condition = function (message, context) { return condition.test(message); } } else { this.condition = function (message, context) { return message == condition; } } if (trueBlock && !trueBlock.isBlock) { throw new TypeError('Parameter trueBlock must be a Block'); } if (falseBlock && !falseBlock.isBlock) { throw new TypeError('Parameter falseBlock must be a Block'); } this.trueBlock = trueBlock || null; this.falseBlock = falseBlock || null; }
javascript
{ "resource": "" }
q10589
train
function () { return Token.destroy({ where: { code: req.get('token') } }).then(function (data) { return data; }).catch(function (err) { res.database(err) }); }
javascript
{ "resource": "" }
q10590
train
function (roles) { roles.map(function (role) { return Role.findOrCreate({ where: { code: role, ownerId: req[options.auth.model].id }, defaults: { code: role, ownerId: req[options.auth.model].id } }).spread(function (role, created) { return role }).catch(function (err) { res.database(err) }); }); return Promise.all(roles); }
javascript
{ "resource": "" }
q10591
train
function (role) { return Role.destroy({ where: { code: role, ownerId: req[options.auth.model].id }, limit: 1 }).catch(function (err) { res.database(err) }); }
javascript
{ "resource": "" }
q10592
train
function (role) { return Role.count({ where: { code: role, ownerId: req[options.auth.model].id }, limit: 1 }).then(function (data) { return data == 1 }).catch(function (err) { res.database(err) }); }
javascript
{ "resource": "" }
q10593
train
function (roles) { return Role.count({ where: { code: { $in: roles }, ownerId: req[options.auth.model].id } }).then(function (data) { return data == roles.length }).catch(function (err) { res.database(err) }); }
javascript
{ "resource": "" }
q10594
create
train
function create(key, value) { if (!Buffer.isBuffer(key)) { throw new TypeError('expected buffer') } return { key, value, left: null, right: null, height: 0 } }
javascript
{ "resource": "" }
q10595
compare
train
function compare(tree_key, key) { let buf if (Buffer.isBuffer(key)) { buf = key } else if (typeof key == 'string') { buf = Buffer.from(key) } else { throw new TypeError('Argument `key` must be a Buffer or a string') } return Buffer.compare(tree_key, buf) }
javascript
{ "resource": "" }
q10596
lookup
train
function lookup(tree, key) { if (!tree) { return null } switch (compare(tree.key, key)) { case 0: return tree case 1: return lookup(tree.right, key) case -1: return lookup(tree.left, key) default: break } }
javascript
{ "resource": "" }
q10597
train
function( definitions, path ) { //region Search engine properties /** * Gets the title of the document. * @type {string} * @readonly */ this.title = ''; /** * Gets the keywords of the document. * @type {string} * @readonly */ this.keywords = ''; /** * Gets the description of the document. * @type {string} * @readonly */ this.description = ''; //endregion //region Menu properties /** * Gets the text of the menu item. * @type {string} * @readonly */ this.text = ''; /** * Gets the order of the menu item. * @type {string} * @readonly */ this.order = 0; /** * Indicates whether the menu item is displayed. * @type {Boolean} * @readonly */ this.hidden = false; /** * Indicates whether the menu item is a leaf with hidden children, * i.e. a truncated menu node. * @type {Boolean} * @readonly */ this.umbel = false; //endregion //region Page properties /** * Gets the identifier of the content, it defaults to the path. * @type {string} * @readonly */ this.id = ''; /** * Gets the path of the content. * @type {string} * @readonly */ this.path = path; /** * Gets the name of a custom document for the content. * @type {string} * @readonly */ this.document = ''; /** * Gets the name of a custom layout for the content. * @type {string} * @readonly */ this.layout = ''; /** * Gets the token collection for the segments found on the content. * @type {object} * @readonly */ this.segments = { }; /** * Indicates whether the content is enabled for search. * @type {Boolean} * @readonly */ this.searchable = true; //endregion // Set the defined properties of the content. Object.assign( this, getMainProperties( definitions ) ); Object.assign( this.segments, getSegmentProperties( definitions ) ); // Set default identity. if (!this.id) this.id = path; // Immutable object. freeze( this ); }
javascript
{ "resource": "" }
q10598
findLeadingComments
train
function findLeadingComments(comments, index, beginIndex, first) { const leadComments = []; if (first && ignoreComment.test(comments[index].raw)) { return leadComments; } let backIndex = index - 1; while (backIndex >= beginIndex && (comments[backIndex].loc.end.line + 1 === comments[backIndex + 1].loc.start.line || comments[backIndex].loc.end.line === comments[backIndex + 1].loc.start.line)) { if (first && ignoreComment.test(comments[backIndex].raw)) { break; } backIndex -= 1; } for (let ind = backIndex + 1; ind <= index; ind += 1) { leadComments.push(comments[ind]); } return leadComments; }
javascript
{ "resource": "" }
q10599
loadTo
train
function loadTo(S) { /** * Takes a non-empty list as its argument and return the first member of the argument. * @param {list} l * @returns {*} * @example * // returns 1 * car([1, 2]); */ S.car = (l) => { if (S.isAtom(l) || S.isNull(l)) { throw new TypeError('The Law of Car: You can only take the car of a non-empty list.'); } let result = l[0]; // Clone there result if it is a list or an object to keep the function pure if (S.isList(result)) { result = result.slice(); } if (S.isObject(result)) { result = Object.assign({}, result); } return result; }; /** * Takes a non-empty list as its argument and returns a new list contaiting the same members * as the argument, except for the car. * @param {list} l * @return {list} * @example * // returns [2] * cdr([1, 2]); */ S.cdr = (l) => { if (S.isAtom(l) || S.isNull(l)) { throw new TypeError('The Law of Cdr: You can only take the cdr of a non-empty list.'); } return l.slice(1); }; /** * Takes two arguments, the second of which must be a list, and returns a new list comtaining * the first argument and the elements of the second argument. * @param {*} exp * @param {list} l * @returns {list} * @example * // returns ['cat', 'dog'] * cons('cat', ['dog']); */ S.cons = (exp, l) => { if (S.isAtom(l)) { throw new TypeError('The Law of Cons: The second argument must be a list.'); } const n = l.slice(0); n.unshift(exp); return n; }; /** * Takes any expression as its argument and returns the expression unevaluated. Should only * be used inside S-Expressions and jS-Expressions. * @param {*} exp * @returns {*} * @example * // returns ['cat', 'dog'] * evaluate(`(cons cat (dog))`); * * // returns ['cons', 'cat', ['dog']] * evaluate(`(quote (cons cat (dog)))`); */ S.quote = exp => exp; /** * Adds 1 to a number. * @param {number} n * @returns {number} * @example * // returns 2 * add1(1); */ S.add1 = (n) => { if (!S.isNumber(n)) { throw new TypeError('Arithmetic operations can only be done on numbers.'); } return n + 1; }; /** * Subtracts 1 from a number. * @param {number} n * @returns {number} * @example * // returns 1 * sub1(2); */ S.sub1 = (n) => { if (!S.isNumber(n)) { throw new TypeError('Arithmetic operations can only be done on numbers.'); } return n - 1; }; /** * The applicative order Y-combinator. * @param {function} le */ S.Y = le => (f => f(f))(f => le(x => (f(f))(x))); }
javascript
{ "resource": "" }