_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q36100
handleError
train
function handleError(promise) { if (canHandleError) { return promise.catch(function(err) { if (ctx) { ctx.error = err; if (ctx.emit) ctx.emit('error', ctx); } else { ctx = { error: err }; } return onError(ctx, next).catch(function(err) { // Log catched error in onError logError(`[${new Date()}] ${err.name || err.message} \n ${err.stack}`); }); }); } else { return promise; } }
javascript
{ "resource": "" }
q36101
aegean
train
function aegean(path) { if (path === null || path === undefined || path.constructor !== String) { throw new Error("aegean expects parameter 1 to be a string"); } if (fs_1.existsSync(path) === false) { throw new Error("file \"" + path + "\" does not exist"); } var stat = fs_1.lstatSync(path); if (stat.isFile() === false) { throw new Error("path \"" + path + "\" should target a file"); } var content = fs_1.readFileSync(path).toString(); var result = inline(content, path); return result; }
javascript
{ "resource": "" }
q36102
inline
train
function inline(content, path) { var result = content; var ast = babylon.parse(content, { allowImportExportEverywhere: true }); var statements = ast.program.body; var gap = 0; for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { var statement = statements_1[_i]; if (statement.type === "ImportDeclaration") { if (statement.specifiers.length === 0) { var regexpLocalFile = /^\.\//; var subPath = ""; if (regexpLocalFile.test(statement.source.value)) { subPath = path_1.dirname(path) + "/" + statement.source.value + (statement.source.value.endsWith(".js") ? "" : ".js"); } else { subPath = require.resolve(statement.source.value); } if (fs_1.existsSync(subPath) === false) { throw new Error("file \"" + path_1.resolve(__dirname, subPath) + "\" does not exist"); } var stat = fs_1.lstatSync(subPath); if (stat.isFile() === false) { throw new Error("path \"" + subPath + "\" should target a file"); } var subContent = fs_1.readFileSync(subPath).toString(); var subResult = inline(subContent, subPath); result = result.substring(0, statement.start + gap) + subResult + result.substring(statement.end + gap); gap += subResult.length - (statement.end - statement.start); } } } return result; }
javascript
{ "resource": "" }
q36103
spawnObservable
train
function spawnObservable(command, args) { return Observable.create(observer => { const cmd = spawn(command, args); observer.next(''); // hack to kick things off, not every command will have a stdout cmd.stdout.on('data', (data) => { observer.next(data.toString('utf8')); }); cmd.stderr.on('data', (data) => { observer.error(data.toString('utf8')); }); cmd.on('close', (data) => { observer.complete(); }); }); }
javascript
{ "resource": "" }
q36104
createUmd
train
function createUmd(name, globals) { // core module is ngd3 the rest are ngd3.feature const MODULE_NAMES = { ngd3: 'ngd3', }; const ENTRIES = { ngd3: `${process.cwd()}/dist/index.js`, }; const moduleName = MODULE_NAMES[name]; const entry = ENTRIES[name]; return generateBundle(entry, { dest: `${process.cwd()}/dist/bundles/${name}.umd.js`, globals, moduleName }); }
javascript
{ "resource": "" }
q36105
replaceVersionsObservable
train
function replaceVersionsObservable(name, versions) { return Observable.create((observer) => { const package = getSrcPackageFile(name); let pkg = readFileSync(package, 'utf8'); const regexs = Object.keys(versions).map(key => ({ expr: new RegExp(key, 'g'), key, val: versions[key] })); regexs.forEach(reg => { pkg = pkg.replace(reg.expr, reg.val); }); const outPath = getDestPackageFile(name); writeFile(outPath, pkg, err => { if (err) { observer.error(err); } else { observer.next(pkg); observer.complete(); } }); }); }
javascript
{ "resource": "" }
q36106
getVersions
train
function getVersions() { const paths = [ getDestPackageFile('ngd3'), ]; return paths .map(path => require(path)) .map(pkgs => pkgs.version); }
javascript
{ "resource": "" }
q36107
fixUnicode
train
function fixUnicode(txt) { txt = txt.replace(/\003/g, ' '); txt = txt.replace(/\004/g, ' '); txt = txt.replace(/(\r|\n)/g, ' '); txt = txt.replace(/[\u007f-\uffff]/g, function (c) { return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4); }); return txt; }
javascript
{ "resource": "" }
q36108
__fetchTicketInfo
train
function __fetchTicketInfo(server, ticketid, callback) { assert(server.cache_folder); var filename = server._ticket_cache_file(ticketid); //xx console.log("filename " , filename.red); assert(_.isFunction(callback)); var command = 'issues/' + ticketid.toString() + '.json?include=relations,journals'; perform_http_get_transaction(server,command, function (err, txt) { txt = fixUnicode(txt); var ticket = null; try { var o = JSON.parse(txt); fs.writeFileSync(filename, JSON.stringify(o, null, " ")); console.warn(" writing ", filename); ticket= o.issue; } catch (err) { console.log("error !".red, err.message); fs.writeFileSync("toto.txt", txt); callback(err); return; // the ticket may have been deleted } callback(null,ticket); }); }
javascript
{ "resource": "" }
q36109
RelativePoint
train
function RelativePoint(relativePointDict){ if(!(this instanceof RelativePoint)) return new RelativePoint(relativePointDict) relativePointDict = relativePointDict || {} // Check relativePointDict has the required fields // // checkType('float', 'relativePointDict.x', relativePointDict.x, {required: true}); // // checkType('float', 'relativePointDict.y', relativePointDict.y, {required: true}); // // Init parent class RelativePoint.super_.call(this, relativePointDict) // Set object properties Object.defineProperties(this, { x: { writable: true, enumerable: true, value: relativePointDict.x }, y: { writable: true, enumerable: true, value: relativePointDict.y } }) }
javascript
{ "resource": "" }
q36110
initializeStates
train
function initializeStates() { // Set all states to NOT_READY var numVertices = graph.vertexCount(); var vertexIds = graph.getVertexIds(); for(var i = 0; i < numVertices; i++) { graph.getVertex(vertexIds[i]).setState("NOT_READY"); } }
javascript
{ "resource": "" }
q36111
startReadyProcesses
train
function startReadyProcesses() { // Start as many processes as we can! //writeToLog("INFO", "***** maxNumberOfRunningProcesses = " + maxNumberOfRunningProcesses + "; numberOfRunningProcesses = " + numberOfRunningProcesses); var numVertices = graph.vertexCount(); var vertexIds = graph.getVertexIds(); for(var i = 0; i < numVertices; i++) { if(graph.getVertex(vertexIds[i]).state == "READY") { if(maxNumberOfRunningProcesses > 0 && numberOfRunningProcesses < maxNumberOfRunningProcesses) { numberOfRunningProcesses++; graph.getVertex(vertexIds[i]).setState("IN_PROGRESS"); } else if(maxNumberOfRunningProcesses <= 0) { numberOfRunningProcesses++; graph.getVertex(vertexIds[i]).setState("IN_PROGRESS"); } } } }
javascript
{ "resource": "" }
q36112
vertexIdsFromArray
train
function vertexIdsFromArray(arr) { var numVertices = arr.length; var vertexIds = []; for(var i = 0; i < numVertices; i++) { vertexIds.push(arr[i].id); } return vertexIds; }
javascript
{ "resource": "" }
q36113
writeToLog
train
function writeToLog(level, msg) { var displayPrefix = "PK-" + pkGuid + ": "; if(loggingMechanism && logUserObject) { loggingMechanism.addLog(level, displayPrefix + msg, logUserObject); } else { console.log(displayPrefix + msg); } }
javascript
{ "resource": "" }
q36114
zoomCondition
train
function zoomCondition(zoom) { var zooms = []; for (var i = 0; i <= _carto2['default'].tree.Zoom.maxZoom; i++) { if (zoom & 1 << i) { zooms.push(i); } } var zoomRanges = detectZoomRanges(zooms), value, operator; if (zoomRanges.length > 1) { operator = 'IN'; value = zooms; } else { var range = zoomRanges[0]; if (range[0] === 0) { operator = '<='; value = range[1]; } else if (range[1] === _carto2['default'].tree.Zoom.maxZoom) { operator = '>='; value = range[0]; } else { // We're only handling >=, <= and IN right now operator = 'IN'; value = zooms; } } if (value.length === 0) { return null; } return [{ operator: operator, type: 'zoom', value: value }]; }
javascript
{ "resource": "" }
q36115
detectZoomRanges
train
function detectZoomRanges(zooms) { var ranges = []; var currentRange = []; for (var i = 0, z = zooms[0]; i <= zooms.length; i++, z = zooms[i]) { if (currentRange.length < 2) { currentRange.push(z); continue; } if (currentRange.length === 2) { if (z === currentRange[1] + 1) { currentRange[1] = z; } else { ranges.push(currentRange); currentRange = []; } } } if (currentRange.length > 0) { ranges.push(currentRange); } return ranges; }
javascript
{ "resource": "" }
q36116
onchange
train
function onchange(evt) { // called in context var ctrl = evt.target; if (ctrl.parentElement === this.el) { if (ctrl.value === 'subexp') { this.children.push(new FilterTree({ parent: this })); } else { this.add({ state: { editor: ctrl.value }, focus: true }); } ctrl.selectedIndex = 0; } }
javascript
{ "resource": "" }
q36117
move
train
function move (leftPort, rightPort) { leftPort = leftPort || 'b' rightPort = rightPort || 'c' var write = writeAction('motors_write', [leftPort, rightPort]) /** * Run motors forever * @param {Number} speed speed of motor * @param {Object} opts object of optional params */ function * forever (speed, turn, opts) { speed = speed || motorDefaults.speed var speeds = turnToSpeeds(turn, speed) yield write('run-forever', { left: { 'speed_sp': speeds.left.toString() }, right: { 'speed_sp': speeds.right.toString() } }) } /** * Run drive motors for a number of degrees * @param {Number} degrees degrees to turn motor * @param {Number} speed speed at which to turn motors * @param {Number} turn turn direction */ function * degrees (deg, speed, turn) { speed = speed || motorDefaults.speed var opts = turnToDegrees(turn, speed, deg) yield * writeAndWait('run-to-rel-pos', { left: { 'position_sp': opts.left.degrees.toString(), 'speed_sp': opts.left.speed.toString() }, right: { 'position_sp': opts.right.degrees.toString(), 'speed_sp': opts.right.speed.toString() } }) } /** * Run drive motors for a number of rotations * @param {Number} rotations number of rotations to turn the motor * @param {Number} speed speed at which to turn motors * @param {Number} turn turn direction */ function * rotations (rots, speed, turn) { speed = speed || motorDefaults.speed yield * this.degrees(Math.round(rots * 360), speed, turn) } /** * Run drive motors for a specified amount of time * @param {Number} time time to run the motors for (in milliseconds) * @param {Number} speed speed at which to turn motors * @param {Number} turn turn direction */ function * timed (time, speed, turn) { speed = speed || motorDefaults.speed var speeds = turnToSpeeds(turn, speed) yield * writeAndWait('run-timed', { left: { 'time_sp': time.toString(), 'speed_sp': speeds.left.toString() }, right: { 'time_sp': time.toString(), 'speed_sp': speeds.right.toString() } }) } /** * Stops motors */ function * stop () { yield write('stop', {left: {}, right: {}}) } /** * Write and hold execution until the motors are done moving * @param {string} command move command * @param {object} opts move options */ function * writeAndWait (command, opts) { var ran = false yield write(command, opts) while (true) { var devices = yield * read() if (devices.motor(leftPort) === 'running' || devices.motor(rightPort) === 'running') { ran = true } if (devices.motor(leftPort) === '' && devices.motor(rightPort) === '' && ran) { break } } } return { forever: forever, degrees: degrees, rotations: rotations, timed: timed, stop: stop } }
javascript
{ "resource": "" }
q36118
turnToSpeeds
train
function turnToSpeeds (turn, speed) { turn = Math.max(Math.min(turn, 100), -100) var reducedSpeed = otherSpeed(turn, speed) reducedSpeed = percentToSpeed(reducedSpeed) speed = percentToSpeed(speed) return { left: turn < 0 ? reducedSpeed : speed, right: turn > 0 ? reducedSpeed : speed } }
javascript
{ "resource": "" }
q36119
turnToDegrees
train
function turnToDegrees (turn, speed, degrees) { turn = Math.max(Math.min(turn, 100), -100) var opts = turnToSpeeds(turn, speed) opts.left = { speed: opts.left } opts.right = { speed: opts.right } var reducedSpeed = otherSpeed(turn, speed) var reducedDegrees = Math.round((reducedSpeed / speed) * degrees) opts.left.degrees = turn < 0 ? reducedDegrees : degrees opts.right.degrees = turn > 0 ? reducedDegrees : degrees return opts }
javascript
{ "resource": "" }
q36120
joinQueue
train
function joinQueue(fn, ctx, exclusive) { // Promisify `fn` fn = promisify(fn, 0); // Add into queue var deferred = defer(); this.queue.push({fn: fn, ctx: ctx, deferred: deferred, exclusive: exclusive}); // Run queue runQueue.call(this); // Return deferred promise return deferred.promise; }
javascript
{ "resource": "" }
q36121
runNext
train
function runNext() { if (this.locked) return false; var item = this.queue[0]; if (!item) return false; if (item.exclusive) { if (this.running) return false; this.locked = true; } this.queue.shift(); this.running++; var self = this; item.fn.call(item.ctx).then(function(res) { runDone.call(self, item, true, res); }, function(err) { runDone.call(self, item, false, err); }); return true; }
javascript
{ "resource": "" }
q36122
runDone
train
function runDone(item, resolved, res) { // Adjust state of lock this.running--; if (this.locked) this.locked = false; // Resolve/reject promise item.deferred[resolved ? 'resolve' : 'reject'](res); // Run queue again runQueue.call(this); }
javascript
{ "resource": "" }
q36123
encloseN
train
function encloseN(L, B) { var circle, l0 = null, l1 = L.head, l2, p1; switch (B.length) { case 1: circle = enclose1(B[0]); break; case 2: circle = enclose2(B[0], B[1]); break; case 3: circle = enclose3(B[0], B[1], B[2]); break; } while (l1) { p1 = l1._, l2 = l1.next; if (!circle || !encloses(circle, p1)) { // Temporarily truncate L before l1. if (l0) L.tail = l0, l0.next = null; else L.head = L.tail = null; B.push(p1); circle = encloseN(L, B); // Note: reorders L! B.pop(); // Move l1 to the front of L and reconnect the truncated list L. if (L.head) l1.next = L.head, L.head = l1; else l1.next = null, L.head = L.tail = l1; l0 = L.tail, l0.next = l2; } else { l0 = l1; } l1 = l2; } L.tail = l0; return circle; }
javascript
{ "resource": "" }
q36124
kw
train
function kw(bundler) { assert.equal(typeof bundler, 'object') const handler = thenify(wreq(bundler)) // Koa middleware. // @param {Function} next // @return {Promise} return function *watchifyRequest(next) { const ctx = this return yield handler(this.req, this.res) .then(success) .catch(failure) function success(res) { ctx.response.body = res } function failure(err) { ctx.throw(err) } } }
javascript
{ "resource": "" }
q36125
serialize
train
function serialize(type, source, options) { var codec = type.codec if (!codec) return postEncode(new Buffer([ type.byte ]), options) var buffer = codec.encode(source, bytewise) if (options && options.nested && codec.escape) buffer = codec.escape(buffer) var hint = typeof codec.length === 'number' ? (codec.length + 1) : void 0 var buffers = [ new Buffer([ type.byte ]), buffer ] return postEncode(Buffer.concat(buffers, hint), options) }
javascript
{ "resource": "" }
q36126
postEncode
train
function postEncode(encoded, options) { if (options === null) return encoded return bytewise.postEncode(encoded, options) }
javascript
{ "resource": "" }
q36127
cleanUpAndMoveOn
train
function cleanUpAndMoveOn(evt) { var el = evt.target; // remove `error` CSS class, which may have been added by `FilterLeaf.prototype.invalid` el.classList.remove('filter-tree-error'); // set or remove 'warning' CSS class, as per el.value FilterNode.setWarningClass(el); if (el === this.view.column) { // rebuild operator list according to selected column name or type, restoring selected item makeOpMenu.call(this, el.value); } if (el.value) { // find next sibling control, if any if (!el.multiple) { while ((el = el.nextElementSibling) && (!('name' in el) || el.value.trim() !== '')); // eslint-disable-line curly } // and click in it (opens select list) if (el && el.value.trim() === '') { el.value = ''; // rid of any white space FilterNode.clickIn(el); } } // forward the event to the application's event handler if (this.eventHandler) { this.eventHandler(evt); } }
javascript
{ "resource": "" }
q36128
RegionOfInterest
train
function RegionOfInterest(regionOfInterestDict){ if(!(this instanceof RegionOfInterest)) return new RegionOfInterest(regionOfInterestDict) regionOfInterestDict = regionOfInterestDict || {} // Check regionOfInterestDict has the required fields // // checkType('RelativePoint', 'regionOfInterestDict.points', regionOfInterestDict.points, {isArray: true, required: true}); // // checkType('RegionOfInterestConfig', 'regionOfInterestDict.regionOfInterestConfig', regionOfInterestDict.regionOfInterestConfig, {required: true}); // // checkType('String', 'regionOfInterestDict.id', regionOfInterestDict.id, {required: true}); // // Init parent class RegionOfInterest.super_.call(this, regionOfInterestDict) // Set object properties Object.defineProperties(this, { points: { writable: true, enumerable: true, value: regionOfInterestDict.points }, regionOfInterestConfig: { writable: true, enumerable: true, value: regionOfInterestDict.regionOfInterestConfig }, id: { writable: true, enumerable: true, value: regionOfInterestDict.id } }) }
javascript
{ "resource": "" }
q36129
brackets2dots
train
function brackets2dots(string) { return ({}).toString.call(string) == '[object String]' ? string.replace(REPLACE_BRACKETS, '.$1').replace(LFT_RT_TRIM_DOTS, '') : '' }
javascript
{ "resource": "" }
q36130
metriclcs
train
function metriclcs(s1, s2) { if (typeof s1 !== "string" || typeof s1 !== "string") return NaN; if (s1 === s2) return 1; const mlen = Math.max(s1.length, s2.length); if (mlen === 0) return 1; return lcsLength(s1, s2) / mlen; }
javascript
{ "resource": "" }
q36131
plugin
train
function plugin (config) { /** * Init */ // Throw an error if non-object supplied as `options` if (config && (typeof(config) !== 'object' || config instanceof Array)) { throw new Error('metalsmith-nested error: options argument must be an object'); } config = config || {}; // Set options or defaults let opts = { directory: config.directory || 'nested', generated: config.generated || 'layouts', pattern: config.pattern, // match to apply default layout default: config.default, // default layout }; // Throw an error if `nested` directory cannot be found if (!fs.existsSync(opts.directory)) { throw new Error(`metalsmith-nested error: could not find source directory (${opts.directory}) at location (${path.resolve(opts.directory)})`); } /** * Test if file has layout front-matter or matches pattern with default layout * * Code source: * https://github.com/superwolff/metalsmith-layouts/blob/master/lib/helpers/check.js * * @param {Object} files * @param {String} file * @param {String} pattern * @param {String} default * @return {Boolean} */ function check(files, file, pattern, def) { let data = files[file]; // Only process utf8 encoded files (so no binary) if (!utf8(data.contents)) { return false; } // Only process files that match the pattern (if there is a pattern) if (pattern && !match(file, pattern)[0]) { return false; } // Only process files with a specified layout or default template. // Allow the default template to be cancelled by layout: false. return 'layout' in data ? data.layout : def; } /** * Recursively look up specified `layout` in front-matter and combine * contents with previous results on `temp` via `injectContent` method * * @param {Object} tfiles * @param {String} tfile * @param {Object} resolved * @param {String} temp * @return {String} */ function resolveTemplate (tfiles, tfile, resolved, temp = '') { // If parent layout was called by a page directly (vs. through a child layout) // inject already resolved content with child `temp` if (resolved[tfile]) { return injectContent(resolved[tfile], temp); } // Process layout as prescribed else if (tfiles[tfile]) { // Lookup layout in tfiles tree let tdata = tfiles[tfile]; // Combine parent-child on `temp` via `injectContent` temp = injectContent(tdata.contents.toString(), temp); // If this layout has a parent `layout` in front-matter, "lather, rinse, repeat" return tdata.layout ? resolveTemplate(tfiles, tdata.layout, resolved, temp) : temp; } else { return temp; } } /** * Combine parent-child content on `{{{contents}}}` expression * This could be set as an options @property for `plugin` if wanted * * @param {String} parentContent * @param {String} childContent * @return {String} */ function injectContent (parentContent, childContent) { // If no `childContent` return `parentContent` as-is return childContent ? parentContent.replace(/\{\{\{\s*contents\s*\}\}\}/gim, childContent) : parentContent; } // Storage for resolved layouts let resolved = {}; /** * Main plugin function */ return function (files, metalsmith, done) { /** * Create build tree for layout files */ Metal(process.cwd()) .source(opts.directory) .destination(opts.generated) // Access layout build tree `tfiles` from `nested` directory .use(function(tfiles, metal, next) { setImmediate(next); // Process each page file (not layout) for `layout` front-matter or default layout Object.keys(files).forEach(file => { // Test if we use a layout on this page file or skip if (!check(files, file, opts.pattern, opts.default)) { return; // next page } let layout = files[file].layout || opts.default, combined; // Check if already resolved layout before processing if (resolved[layout]) { combined = resolved[layout]; } else { // Process-combine layout files recursively for this page combined = resolveTemplate(tfiles, layout, resolved); // Store combined results for future pages using same layout resolved[layout] = combined; } // Write combined layouts result to layout build tree // *** It's worth noting that until now we are always passing {String} values // converted from layout `tfile.contents` and not a file {Object} or {Buffer} tfiles[layout].contents = new Buffer(combined); }); }) // Write layout build tree to `generated` directory .build(function(err) { if (err) throw err; }); // We must allow time to disc write combined layout files // before processing `metalsmith-layout` plugin setTimeout(done, 100); }; }
javascript
{ "resource": "" }
q36132
check
train
function check(files, file, pattern, def) { let data = files[file]; // Only process utf8 encoded files (so no binary) if (!utf8(data.contents)) { return false; } // Only process files that match the pattern (if there is a pattern) if (pattern && !match(file, pattern)[0]) { return false; } // Only process files with a specified layout or default template. // Allow the default template to be cancelled by layout: false. return 'layout' in data ? data.layout : def; }
javascript
{ "resource": "" }
q36133
resolveTemplate
train
function resolveTemplate (tfiles, tfile, resolved, temp = '') { // If parent layout was called by a page directly (vs. through a child layout) // inject already resolved content with child `temp` if (resolved[tfile]) { return injectContent(resolved[tfile], temp); } // Process layout as prescribed else if (tfiles[tfile]) { // Lookup layout in tfiles tree let tdata = tfiles[tfile]; // Combine parent-child on `temp` via `injectContent` temp = injectContent(tdata.contents.toString(), temp); // If this layout has a parent `layout` in front-matter, "lather, rinse, repeat" return tdata.layout ? resolveTemplate(tfiles, tdata.layout, resolved, temp) : temp; } else { return temp; } }
javascript
{ "resource": "" }
q36134
dasherize
train
function dasherize(str) { return str.replace( /([a-z])([A-Z])/g, (_, let1, let2) => `${let1}-${let2.toLowerCase()}` ); }
javascript
{ "resource": "" }
q36135
write
train
function write (type, port) { return createAction(WRITE, writeCommand) /** * function that returns a write actions * @private * @param {string} command * @param {object} opts move object * @return {object} write action object */ function writeCommand (command, opts) { return { type: type, command: command, opts: opts, port: port } } }
javascript
{ "resource": "" }
q36136
writeCommand
train
function writeCommand (command, opts) { return { type: type, command: command, opts: opts, port: port } }
javascript
{ "resource": "" }
q36137
train
function(filepath) { // Construct the destination file path. var dest = path.join( grunt.config('copy.coverage.dest'), path.relative(process.cwd(), filepath) ); // Return false if the file exists. return !(grunt.file.exists(dest)); }
javascript
{ "resource": "" }
q36138
getPackageVersion
train
function getPackageVersion() { var packageJson = path.join(process.cwd(), 'package.json'), version; try { version = require(packageJson).version; } catch (unused) { throw new Error('Could not load package.json, please make sure it exists'); } if (!semver.valid(version)) { throw new Error('Invalid version number found in package.json, please make sure it is valid'); } return [ semver.major(version), semver.minor(version), semver.patch(version) ].join('.'); }
javascript
{ "resource": "" }
q36139
writePackageVersion
train
function writePackageVersion(newVersion) { var packageJson = path.join(process.cwd(), 'package.json'), raw = require(packageJson); raw.version = newVersion; fs.writeFileSync(packageJson, JSON.stringify(raw, null, 2)); }
javascript
{ "resource": "" }
q36140
train
function (obj) { var ret = {}; if( Object.prototype.toString.call(obj) === '[object Object]' ) { for (var key in obj) { ret[key] = arrayClean(obj[key]); } } else if( Object.prototype.toString.call(obj) === '[object Array]' ) { if (obj.length === 1) { ret = arrayClean(obj[0]); } else { ret = new Array; for(var i=0;i<obj.length;i++) { ret.push(arrayClean(obj[i])); } } } else { ret = obj; } return ret; }
javascript
{ "resource": "" }
q36141
queryImport
train
function queryImport(styles) { if (styles.indexOf('@import') < 0) return [] const arr = [] const ast = csstree.parse(styles); csstree.walk(ast, { enter: function (node) { if (node.type === 'Atrule' && node.name === 'import') { const pat = node.prelude.children.head.data.value arr.push(pat.substring(1, pat.length - 1)) } } }) return arr }
javascript
{ "resource": "" }
q36142
handleImportStyle
train
function handleImportStyle(styles, initPath, mayRM) { if (!!mayRM) { styles = styles.replace(mayRM, '') } if (styles.indexOf('@import') < 0) return styles const ast = csstree.parse(styles); csstree.walk(ast, { enter: function (node) { if (node.type === 'Atrule') { if (node.name === 'import') { const pat = node.prelude.children.head.data.value if (initPath && typeof pat === 'string') { const realP = pat.substring(1, pat.length - 1) const newPath = path.dirname(initPath) const resPath = path.resolve(newPath, realP) const text = fs.readFileSync(resPath).toString() const re = new RegExp("[\\s]*@import[\\s]+\"" + realP + "\";", "g"); //handle with loop import styles = styles.replace(re, handleImportStyle(text, resPath, re)) } } } } }) return styles }
javascript
{ "resource": "" }
q36143
createStylefromCode
train
function createStylefromCode(styles, abspath) { //may import other file const arr = queryImport(styles) const baseRes = handleImportStyle(styles, abspath) const obj = {} const ast = csstree.parse(baseRes); csstree.walk(ast, { enter: function (node) { if (node.type === 'Rule' && node.prelude && node.prelude.type === 'SelectorList') { const clzName = [] node.prelude.children.forEach(e => { //we may handle each class selector here let ans = selectorBlockHandler(e) if (ans) { //to save before value obj[ans] = obj[ans] || {} //save ans to log which to give value clzName.push(ans) } }) const styleArray = [] node.block.children.forEach(e => { //handle with unit or function case const styleItem = styleBlockHandler(e) styleItem.length > 0 && styleArray.push(styleItem) }) clzName.forEach(e => { try { const styleObject = transform(styleArray) if (styleObject.fontWeight) { //fontWeight must be string styleObject.fontWeight = styleObject.fontWeight + "" } Object.assign(obj[e], styleObject) } catch (e) { console.error("convert ", abspath, " error:", e.message) } }) } }, }) return {styles: obj, imports: arr} }
javascript
{ "resource": "" }
q36144
createStyleDictionary
train
function createStyleDictionary(styles) { let total = {} for (let k in styles) { const val = styles[k] //sort clz name to judge arbitrary order in multi-className k = sortSeq(k) //merge style chain from last condition const lastEle = getLastEle(k) //no sharing data. create new chain if (!total.hasOwnProperty(lastEle)) { total[lastEle] = createItem(k, val)[lastEle] } else { //merge chain data merge(createItem(k, styles[k]), total) } } return total }
javascript
{ "resource": "" }
q36145
selectorBlockHandler
train
function selectorBlockHandler(element) { if (element.type === 'Selector') { const name = [] let discard = false element.children.forEach(e => { switch (e.type) { case "ClassSelector": name.push("." + e.name); break; //not support for now case "Combinator": name.push(e.name); discard = true return null case "TypeSelector": name.push(e.name); break; case "IdSelector": //not support for now name.push("#" + e.name); discard = true return null case "WhiteSpace": name.push(" "); break default: { // console.warn('unknown selector type:', e) discard = true return null } } }) if (!discard) return name.join("") else return null } }
javascript
{ "resource": "" }
q36146
paddingElementForTransform
train
function paddingElementForTransform(proper, arr) { //RN not support multi font-family keywords if (proper === 'font-family') { return [proper, arr.pop()] } //not support such shorthand if (proper === 'background') { return ['background-color', arr.join(" ")] } //not support such shorthand if (proper === 'border-bottom' || proper === 'border-top' || proper === 'border-right' || proper === 'border-left') { // console.warn("not support property",proper) return [] } //content property should take just single value if (proper === 'content' && arr.length === 1) return [proper, arr[0]] return [proper, arr.join(" ")] }
javascript
{ "resource": "" }
q36147
styleBlockHandler
train
function styleBlockHandler(element) { const {property, value} = element let result = [] const styleContent = value && value.children ? value.children : [] const defaultUnit = "px" styleContent.forEach(e => { switch (e.type) { case "Identifier": result.push(e.name); break case "Dimension": result.push(e.value + defaultUnit); break case 'Function': { //function case need '()' container,such as rgb(255,0,0) let name = e.name + "(" e.children.forEach(e => name += e.value + queryUnit(e.unit)) result.push(name + ")") break } case "HexColor": { result.push("#" + e.value) break } case "String": { const str = e.value result.push(str) break } case "Number": { result.push(e.value) break } case "Percentage": { result.push(e.value + "%") break } case "WhiteSpace": { break } case "Operator": { break } case "Url": { break } default: // console.log("unknown,", property, e) break } }) //padding modification if (result.length > 0) return paddingElementForTransform(property, result) return [] }
javascript
{ "resource": "" }
q36148
train
function (uuid) { uuid = ref.reinterpret(uuid, 16).toString('hex'); return [ uuid.slice(0, 8), uuid.slice(8, 12), uuid.slice(12, 16), uuid.slice(16, 20), uuid.slice(20, 32) ].join('-'); }
javascript
{ "resource": "" }
q36149
train
function (trail, options) { this.trail = trail; this.options = options || {}; this.cursor = lib.tdb_cursor_new(this.trail.tdb._db); /*\ |*| Filter logic \*/ if (typeof this.options.filter != 'undefined') { const err = lib.tdb_cursor_set_event_filter(this.cursor, this.options.filter); if (err) { throw new TrailDBError('Unable to set event filter: ' + this.trail.id); } } const r = lib.tdb_get_trail(this.cursor, this.trail.id); if (r) { throw new TrailDBError('Failed to open trail cursor: ' + this.trail.id); } return this; }
javascript
{ "resource": "" }
q36150
train
function (options) { if (!options.path) { throw new TrailDBError('Path is required'); } if (!options.fieldNames || !options.fieldNames.length) { throw new TrailDBError('Field names are required'); } if (options.path.slice(-4) === '.tdb') { options.path = options.path.slice(0, -4); } this._cons = lib.tdb_cons_init(); this.numFields = options.fieldNames.length; const fieldNamesLength = ref.alloc(ref.types.uint64, this.numFields); const fieldNamesArray = new T_STRING_ARRAY(this.numFields); options.fieldNames.forEach(function (field, i) { fieldNamesArray[i] = ref.allocCString(field); }); const r = lib.tdb_cons_open( this._cons, ref.allocCString(options.path), fieldNamesArray, ref.deref(fieldNamesLength) ); if (r !== 0) { throw new TrailDBError('Cannot open constructor: ' + r); } this.path = options.path; this.fieldNames = options.fieldNames; return this; }
javascript
{ "resource": "" }
q36151
train
function (options) { this._db = lib.tdb_init(); const r = lib.tdb_open(this._db, ref.allocCString(options.path)); if (r !== 0) { throw new TrailDBError('Could not open TrailDB: ' + r); } this.numTrails = lib.tdb_num_trails(this._db); this.numEvents = lib.tdb_num_events(this._db); this.numFields = lib.tdb_num_fields(this._db); this.fieldNames = []; this.fieldNameToId = {}; for (let i = 0; i < this.numFields; i++) { this.fieldNames[i] = lib.tdb_get_field_name(this._db, i); this.fieldNameToId[this.fieldNames[i]] = i; } return this; }
javascript
{ "resource": "" }
q36152
encodeBound
train
function encodeBound(data, base) { var prefix = data.prefix var buffer = prefix ? base.encode(prefix, null) : new Buffer([ data.byte ]) if (data.upper) buffer = Buffer.concat([ buffer, new Buffer([ 0xff ]) ]) return util.encodedBound(data, buffer) }
javascript
{ "resource": "" }
q36153
train
function(required, cb) { var chain = new Chain(config); chain.on(required, cb); return chain; }
javascript
{ "resource": "" }
q36154
commandFactory
train
function commandFactory(combos, cmd) { var command; // if no combos provided // consider it as a single command run if (!cmd) { cmd = combos; combos = [{}]; } command = partial(iterate, combos, cmd); command.commandDescription = partial(commandDescription, cmd); return command; }
javascript
{ "resource": "" }
q36155
forEachFactory
train
function forEachFactory(properties) { // expand object's combinations into an array of objects if (typeOf(properties) == 'object') { properties = cartesian(clone(properties)); } return {command: partial(commandFactory, properties)}; }
javascript
{ "resource": "" }
q36156
valueFactory
train
function valueFactory(value) { function command(cb) { cb(null, value); } command.commandDescription = partial(commandDescription, 'VALUE SETTER'); return command; }
javascript
{ "resource": "" }
q36157
commandDescription
train
function commandDescription(desc, state) { desc = state[desc] || desc; return desc.join ? '[' + desc.join(', ') + ']' : desc.toString(); }
javascript
{ "resource": "" }
q36158
iterate
train
function iterate(accumulator, combos, cmd, callback) { var params; // initial call might not have accumulator if (arguments.length == 3) { callback = cmd; cmd = combos; combos = accumulator; accumulator = []; } // resolve params from combo reference if (typeof combos == 'string') { // only work with arrays and object this way params = null; // get elements one by one from the array // consider number of elements in `accumulator` // as number of processed from referenced array if (Array.isArray(this[combos]) && this[combos][accumulator.length]) { params = {}; params[combos] = this[combos][accumulator.length]; } // if object gets referenced // create list of combinations out of it // and use array logic to resolve // current iteration params else if (typeOf(this[combos]) == 'object') { params = cartesian(clone(this[combos]))[accumulator.length]; } } else { // get another combination params = combos.shift(); } // when done with the combos // invoke callback if (!params) { // if it's a single element, return it as is callback(null, (accumulator && accumulator.length == 1) ? accumulator[0] : accumulator); return; } // if command name doesn't as state property // consider it as standalone command runCommand.call(this, params, this[cmd] || cmd, function(err, output) { accumulator.push(output); if (err) { callback(err, accumulator); return; } // rinse, repeat iterate.call(this, accumulator, combos, cmd, callback); }.bind(this)); }
javascript
{ "resource": "" }
q36159
keepAssigned
train
function keepAssigned(...objs) { var ka = create(keepAssignedPrototype); defineProperty(ka, 'objs', { value: [] }); // first-come first-served [...objs].forEach(o => _keepAssigned(ka, o)); return ka; }
javascript
{ "resource": "" }
q36160
findFirstProp
train
function findFirstProp(objs, p) { for (let obj of objs) { if (obj && obj.hasOwnProperty(p)) { return valueize(obj[p]); } } }
javascript
{ "resource": "" }
q36161
calcProp
train
function calcProp(ka, p) { var val = ka[p]; if (isKeepAssigned(val)) { recalc(val); } else { val.val = findFirstProp(ka.objs, p); } }
javascript
{ "resource": "" }
q36162
placeKey
train
function placeKey(ka, v, k, pusher) { if (isObject(v)) { if (k in ka) { _keepAssigned(ka[k], v, pusher); } else { ka[k] = subKeepAssigned(ka.objs, k, pusher); } } else { if (k in ka) { ka[k].val = calcProp(ka, k); } else { defineProperty(ka, k, { get() { return U(findFirstProp(ka.objs, k)); }, enumerable: true }); //upward(v, ka[k]); } } }
javascript
{ "resource": "" }
q36163
recalc
train
function recalc(ka) { for (let [key, val] of objectPairs(ka)) { if (isKeepAssigned(val)) { recalc(val); } else { val.val = getter(key); } } }
javascript
{ "resource": "" }
q36164
subKeepAssigned
train
function subKeepAssigned(objs, k, pusher) { var ka = keepAssigned(); objs .map(propGetter(k)) .filter(Boolean) .forEach(o => _keepAssigned(ka, o, pusher)); return ka; }
javascript
{ "resource": "" }
q36165
_keepAssigned
train
function _keepAssigned(ka, o, pusher = unshift) { // Handle an upwardable object changing, in case of `O(model.obj)`. function objectChanged(_o) { replace(ka.objs, o, _o); recalc(ka); } // @TODO: figure out how to handle this. // upward(o, objectChanged); function key(v, k) { placeKey(ka, v, k); } function update(k, v) { processKey(k, v); } function _delete(k) { recalc(ka); } var handlers = { add: argify(placeKey, ka), update: argify(placeKey, ka), delete: _delete }; observeObject(o, makeObserver(handlers)); pusher.call(ka.objs, o); mapObject(o, (v, k) => placeKey(ka, v, k, pusher)); return ka; }
javascript
{ "resource": "" }
q36166
train
function(source, dimension) { // create the matrix var mat = {} // if dimension is an integer, the matrix is square if (_.isFunction(source) && _.isInteger(dimension) && dimension >= 0) { dimension = { x:dimension, y:dimension } } // source can be a 2-var predicate function or a line based matrix if (_.isFunction(source) && dimension && _.isInteger(dimension.x) && dimension.x >= 0 && _.isInteger(dimension.y) && dimension.y >= 0) { // creating the matrix mat.x = dimension.x mat.y = dimension.y mat.data = [] // populate for (var i = 0; i < mat.x; i++) { mat.data.push([]) for (var j = 0; j < mat.y; j++) { if (source(i, j)) { mat.data[i].push(j) } } } } else if (_.isArray(source) && source[0] && _.isArray(source[0])) { // creating the matrix mat.x = source.length mat.y = source[0].length mat.data = [] // populate for (var i = 0; i < mat.x; i++) { mat.data.push([]) for (var j = 0; j < mat.y; j++) { if (source[i][j]) { mat.data[i].push(j) } } } } // return the matrix return mat }
javascript
{ "resource": "" }
q36167
train
function(sbm) { // creating matrix var mat = [] // populate for (var i = 0; i < sbm.x; i++) { mat.push([]) for (var j = 0; j < sbm.y; j++) { mat[i][j] = _.includes(sbm.data[i], j) ? 1 : 0 } } // return the matrix return mat }
javascript
{ "resource": "" }
q36168
train
function(n) { n = _.isInteger(n) ? n : 0 return { x: n, y: n, data: _.map(_.range(n), function (num) { return [num] }) } }
javascript
{ "resource": "" }
q36169
train
function(matrix) { // if not square if (matrix.x != matrix.y) { return } // return trace return _.filter(matrix.data, function (line, number) { return _.includes(line, number) }).length }
javascript
{ "resource": "" }
q36170
train
function(sbm) { // create the matrix var mat = {} mat.x = sbm.y mat.y = sbm.x mat.data = [] // populate for (var i = 0; i < mat.x; i++) { mat.data.push([]) for (var j = 0; j < mat.y; j++) { if (_.includes(sbm.data[j], i)) { mat.data[i].push(j) } } } return mat }
javascript
{ "resource": "" }
q36171
train
function(sbmA, sbmB) { // check size if (sbmA.x !== sbmB.x || sbmA.y !== sbmB.y) { return false } // check return _.every(sbmA.data, function (line, idx) { return _.isEqual(line.sort(), sbmB.data[idx].sort()) }) }
javascript
{ "resource": "" }
q36172
train
function(sbm) { // create the matrix var mat = {} mat.x = sbm.x mat.y = sbm.y mat.data = [] // populate for (var i = 0; i < mat.x; i++) { mat.data[i] = _.difference(_.range(mat.y), sbm.data[i]) } // return matrix return mat }
javascript
{ "resource": "" }
q36173
train
function(sbmA, sbmB) { // if not the same sizes if (sbmA.x != sbmB.x || sbmA.y != sbmB.y) { return } // create the matrix var mat = {} mat.x = sbmA.x mat.y = sbmA.y mat.data = [] // populate for (var i = 0; i < mat.x; i++) { mat.data[i] = _.intersection(sbmA.data[i], sbmB.data[i]) } // return matrix return mat }
javascript
{ "resource": "" }
q36174
train
function(sbmA, sbmB) { // if not the same sizes if (sbmA.x != sbmB.x || sbmA.y != sbmB.y) { return } // create the matrix var mat = {} mat.x = sbmA.x mat.y = sbmA.y mat.data = [] // populate for (var i = 0; i < mat.x; i++) { mat.data[i] = _.union(sbmA.data[i], sbmB.data[i]).sort() } // return matrix return mat }
javascript
{ "resource": "" }
q36175
train
function(sbmA, sbmB) { // check if size compatible if (sbmA.y !== sbmB.x) { return } // create a new matrix return this.make((function (i, j) { return _.reduce(_.map(_.range(sbmA.y), (function(id) { return this.check(sbmA, i, id) && this.check(sbmB, id, j) }).bind(this)), function (sum, a) { return sum ^ a }) == 1 }).bind(this), { x: sbmA.x, y: sbmB.y }) }
javascript
{ "resource": "" }
q36176
train
function(sbm, n) { if (n == 0) { return this.identity(n) } else if (n == 1) { return sbm } else if (n % 2 == 0) { return this.pow(this.multiply(sbm, sbm), n/2) } else { return this.multiply(sbm, this.pow(this.multiply(sbm, sbm), (n-1)/2)) } }
javascript
{ "resource": "" }
q36177
train
function(sbm) { // if the matrix ain't square, symmetry is off if (sbm.x !== sbm.y) { return false } // symmetry status var symmetry = true // iterate for (var i = 0; i < sbm.x; i++) { for (var j = 0; j <= i; j++) { symmetry = symmetry && ((_.includes(sbm.data[i], j) ^ _.includes(sbm.data[j], i)) === 0) } } // return return symmetry }
javascript
{ "resource": "" }
q36178
train
function(sbm) { return _.sum(_.map(sbm.data, function (ar) { return ar.length })) }
javascript
{ "resource": "" }
q36179
train
function() { if (!(this instanceof EventParser)) { return new EventParser(); } /** * Parses Mandrill Events request. Sets mandrillEvents property on req. Expects body to contain decoded post body mandrill_events parameter. Please see Madrills article {@link https://mandrill.zendesk.com/hc/en-us/articles/205583207-What-is-the-format-of-inbound-email-webhooks- | What is the format of inbound email webhook } * @param { Request } req - Express request * @param { object } req.body - request body * @param { string } req.body.mandrill_events - JSON String of Mandrill events * @param { Response } res - Express response */ var parser = function(req, res, next) { if (req.body && req.body.mandrill_events) { try { req.mandrillEvents = JSON.parse(req.body.mandrill_events); next(); } catch (err) { next(err); } } else { next(new Error('No body or body is missing [mandrill_events] property')); } }; return parser; }
javascript
{ "resource": "" }
q36180
retrieveAssociations
train
function retrieveAssociations(req, res) { switch(req.accepts(['json', 'html'])) { // TODO: support HTML in future //case 'html': // res.sendFile(path.resolve(__dirname + '/../../web/association.html')); // break; default: var rootUrl = req.protocol + '://' + req.get('host'); var queryPath = req.originalUrl; req.chickadee.getAssociations(req, rootUrl, queryPath, function(response, status) { res.status(status).json(response); }); break; } }
javascript
{ "resource": "" }
q36181
retrieveAssociation
train
function retrieveAssociation(req, res) { if(redirect(req.params.id, '', '', res)) { return; } switch(req.accepts(['json', 'html'])) { // TODO: support HTML in future //case 'html': // res.sendFile(path.resolve(__dirname + '/../../web/association.html')); // break; default: var id = req.params.id; var rootUrl = req.protocol + '://' + req.get('host'); var queryPath = req.originalUrl; req.chickadee.getAssociation(req, id, null, rootUrl, queryPath, function(response, status) { res.status(status).json(response); }); break; } }
javascript
{ "resource": "" }
q36182
replaceAssociation
train
function replaceAssociation(req, res) { if(redirect(req.params.id, '', '', res)) { return; } var id = req.params.id; var url = req.body.url; var directory = req.body.directory; var tags = req.body.tags; var position = req.body.position; var rootUrl = req.protocol + '://' + req.get('host'); var queryPath = req.originalUrl; req.chickadee.setAssociation(req, id, url, directory, tags, position, rootUrl, queryPath, function(response, status) { res.status(status).json(response); }); }
javascript
{ "resource": "" }
q36183
replaceAssociationPosition
train
function replaceAssociationPosition(req, res) { if(redirect(req.params.id, '../', '/tags', res)) { return; } var id = req.params.id; var position = req.body.position; var rootUrl = req.protocol + '://' + req.get('host'); var queryPath = req.originalUrl; req.chickadee.setAssociation(req, id, null, null, null, position, rootUrl, queryPath, function(response, status) { res.status(status).json(response); }); }
javascript
{ "resource": "" }
q36184
deleteAssociationPosition
train
function deleteAssociationPosition(req, res) { if(redirect(req.params.id, '../', '/tags', res)) { return; } var id = req.params.id; var rootUrl = req.protocol + '://' + req.get('host'); var queryPath = req.originalUrl; req.chickadee.removeAssociation(req, id, 'position', rootUrl, queryPath, function(response, status) { res.status(status).json(response); }); }
javascript
{ "resource": "" }
q36185
p_nor
train
function p_nor(z) { var e, z2, prev = 0.0, t, p, i = 3; if (z < -12) { return 0.0; } if (z > 12) { return 1.0; } if (z === 0.0) { return 0.5; } if (z > 0) { e = true; } else { e = false; z = -z; } z2 = z * z; p = z * Math.exp(-0.5 * z2) / SQ2PI; t = p; for (i; i < 200; i = i + 2) { prev = p; t = t * (z2 / i); p = p + t; if (p <= prev) { return (e ? 0.5 + p : 0.5 - p); } } return (e ? 1.0 : 0.0); }
javascript
{ "resource": "" }
q36186
pf
train
function pf(q, n1, n2) { var eps, fw, s, qe, w1, w2, w3, w4, u, u2, a, b, c, d; if (q < 0.0 || q > 1.0 || n1 < 1 || n2 < 1) { console.error('Error : Illegal parameter in pf()!'); return 0.0; } if (n1 <= 240 || n2 <= 240) { eps = 1.0e-5; } if (n2 === 1) { eps = 1.0e-4; } fw = 0.0; s = 1000.0; while (true) { fw = fw + s; if (s <= eps) { return fw; } if ((qe = q_f(n1, n2, fw) - q) === 0.0) { return fw; } if (qe < 0.0) { fw = fw - s; s = s / 10.0; } } eps = 1.0e-6; qn = q; if (q < 0.5) { qn = 1.0 - q; } u = pnorm(qn); w1 = 2.0 / n1 / 9.0; w2 = 2.0 / n2 / 9.0; w3 = 1.0 - w1; w4 = 1.0 - w2; u2 = u * u; a = w4 * w4 - u2 * w2; b = -2.0 * w3 * w4; c = w3 * w3 - u2 * w1; d = b * b - 4 * a * c; if (d < 0.0) { fw = pfsub(a, b, 0.0); } else { if (a.abs > eps) { fw = pfsub(a, b, d); } else { if (abs(b) > eps) { return -c / b; } fw = pfsub(a, b, 0.0); } } return fw * fw * fw; }
javascript
{ "resource": "" }
q36187
puts
train
function puts(error, stdout, stderr) { if (error || stderr) { let err = null; if (error) { err = `${error}`; } else if (stderr) { err = `${stderr}`; } returnObj.code = 1; returnObj.error = err; } else if (stdout) { returnObj.code = 0; returnObj.result = `${stdout}`; } else { returnObj.code = null; returnObj.result = "Unknown stdout"; } }
javascript
{ "resource": "" }
q36188
createProxy
train
function createProxy(instance, symbols, enumerable) { return new Proxy(instance, { set: (target, propertyName, value) => { let { symbol, isNew } = getSymbol(symbols, propertyName) instance[symbol] = value if (!enumerable && isNew) { Object.defineProperty(instance, symbol, { enumerable: false }) } return true }, get: (target, propertyName) => { if (!symbols.has(propertyName)) { return undefined // the property has not been defined (set) yet } let { symbol } = getSymbol(symbols, propertyName) return instance[symbol] } }) }
javascript
{ "resource": "" }
q36189
getSymbol
train
function getSymbol(symbols, propertyName) { if (symbols.has(propertyName)) { return { symbol: symbols.get(propertyName), isNew: false } } let symbol = Symbol(propertyName) symbols.set(propertyName, symbol) return { symbol, isNew: true } }
javascript
{ "resource": "" }
q36190
parse
train
function parse(size) { var matches = size.match(regexp); if (!matches) return null; var multiplicator = matches[3] ? +matches[3].replace(/x$/, '') : 1; return { width: +matches[1] * multiplicator, height: +matches[2] * multiplicator }; }
javascript
{ "resource": "" }
q36191
train
function() { var streams = this.sourceStreams = toArray(arguments); if(streams.length > 1) { this.resultStream = Bacon.mergeAll(streams); } else { this.resultStream = streams[0]; } this.streamsHash = this._computeStreamsHash('any', streams); // invalidate 'all' return this; }
javascript
{ "resource": "" }
q36192
train
function() { var streams = this.sourceStreams = toArray(arguments); if(streams.length === 1) { this.any.apply(this, streams); return this; } this.resultStream = Bacon.zipAsArray(streams); this.streamsHash = this._computeStreamsHash('all', streams); // invalidate 'any' return this; }
javascript
{ "resource": "" }
q36193
train
function(autocrat, governor, origHandler, context) { var streamsHash = this.streamsHash, handlerSequence, isFirstHandler, deferred, handler; context || (context = this.governor); if(isFunction(origHandler)) { origHandler = bind(origHandler, context); } else if(isString(origHandler)){ origHandler = bind(this.governor[origHandler], context); } if(autocrat.awaiting[this.streamsHash]) { handlerSequence = autocrat.awaiting[this.streamsHash]; } else { handlerSequence = autocrat.awaiting[this.streamsHash] = []; isFirstHandler = true; } deferred = new HandlerDeferred(handlerSequence); handler = this._buildAsyncHandler(origHandler, deferred); if(isFirstHandler) { deferred.handlerIndex = 0; handlerSequence.push(handler); this.resultStream.subscribe(handler); } else { deferred.handlerIndex = handlerSequence.length; handlerSequence.push(handler); } // terminate chain return this; }
javascript
{ "resource": "" }
q36194
train
function(propName, updater) { var updaterName, handler; if(!isFunction(updater)) { updaterName = 'update' + propName[0].toUpperCase() + propName.slice(1); updater = this.governor[updaterName]; } if(updater) { this.then(function(advisorEvent, deferred, consequenceActions, streamEvent) { var currVal = this.props[propName].value; var updaterArgs = [currVal].concat(advisorEvent, streamEvent); var retVal = updater.apply(this, updaterArgs); // Only trigger a reactive change if the value has actually changed; // if(!isEqual(retVal, currVal)) this.props[propName] = retVal; this.props[propName] = retVal deferred.resolve(retVal); }); } else { throw new Error('An updater function was not specified and governor.' + updaterName + ' is not defined'); } return this; }
javascript
{ "resource": "" }
q36195
train
function() { var props = arguments.length ? toArray(arguments) : keys(this.governor.props); forEach(props, this.updateProp, this); return this; }
javascript
{ "resource": "" }
q36196
removeElements
train
function removeElements(collection, newCollection, index) { if (index === void 0) { index = 'id'; } var oldLength = collection.length; _.remove(collection, function (item) { return !_.some(newCollection, function (c) { return c[index] === item[index]; }); }); return collection.length !== oldLength; }
javascript
{ "resource": "" }
q36197
sync
train
function sync(collection, newCollection, index) { if (index === void 0) { index = 'id'; } var answer = removeElements(collection, newCollection, index); if (newCollection) { newCollection.forEach(function (item) { var oldItem = _.find(collection, function (c) { return c[index] === item[index]; }); if (!oldItem) { answer = true; collection.push(item); } else { if (item !== oldItem) { angular.copy(item, oldItem); answer = true; } } }); } return answer; }
javascript
{ "resource": "" }
q36198
escapeColons
train
function escapeColons(url) { var answer = url; if (_.startsWith(url, 'proxy')) { answer = url.replace(/:/g, '\\:'); } else { answer = url.replace(/:([^\/])/, '\\:$1'); } return answer; }
javascript
{ "resource": "" }
q36199
url
train
function url(path) { if (path) { if (_.startsWith(path, "/")) { if (!_urlPrefix) { // lets discover the base url via the base html element _urlPrefix = $('base').attr('href') || ""; if (_.endsWith(_urlPrefix, '/')) { _urlPrefix = _urlPrefix.substring(0, _urlPrefix.length - 1); } } if (_urlPrefix) { return _urlPrefix + path; } } } return path; }
javascript
{ "resource": "" }