_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q45100
expand
train
function expand( v1, v2, pixels ) { var x = v2.x - v1.x, y = v2.y - v1.y, det = x * x + y * y, idet; if ( det === 0 ) return; idet = pixels / Math.sqrt( det ); x *= idet; y *= idet; v2.x += x; v2.y += y; v1.x -= x; v1.y -= y; }
javascript
{ "resource": "" }
q45101
binarySearchIndices
train
function binarySearchIndices( value ) { function binarySearch( start, end ) { // return closest larger index // if exact number is not found if ( end < start ) return start; var mid = start + Math.floor( ( end - start ) / 2 ); if ( cumulativeAreas[ mid ] > value ) { return binarySearch( start, mid - 1 ); } else if ( cumulativeAreas[ mid ] < value ) { return binarySearch( mid + 1, end ); } else { return mid; } } var result = binarySearch( 0, cumulativeAreas.length - 1 ) return result; }
javascript
{ "resource": "" }
q45102
train
function ( geometry ) { geometry.computeBoundingBox(); var bb = geometry.boundingBox; var offset = new THREE.Vector3(); offset.addVectors( bb.min, bb.max ); offset.multiplyScalar( -0.5 ); geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) ); geometry.computeBoundingBox(); return offset; }
javascript
{ "resource": "" }
q45103
train
function ( points, scale ) { var c = [], v3 = [], point, intPoint, weight, w2, w3, pa, pb, pc, pd; point = ( points.length - 1 ) * scale; intPoint = Math.floor( point ); weight = point - intPoint; c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1; c[ 1 ] = intPoint; c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1; c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2; pa = points[ c[ 0 ] ]; pb = points[ c[ 1 ] ]; pc = points[ c[ 2 ] ]; pd = points[ c[ 3 ] ]; w2 = weight * weight; w3 = weight * w2; v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 ); v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 ); v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 ); return v3; }
javascript
{ "resource": "" }
q45104
updateVirtualLight
train
function updateVirtualLight( light, cascade ) { var virtualLight = light.shadowCascadeArray[ cascade ]; virtualLight.position.copy( light.position ); virtualLight.target.position.copy( light.target.position ); virtualLight.lookAt( virtualLight.target ); virtualLight.shadowCameraVisible = light.shadowCameraVisible; virtualLight.shadowDarkness = light.shadowDarkness; virtualLight.shadowBias = light.shadowCascadeBias[ cascade ]; var nearZ = light.shadowCascadeNearZ[ cascade ]; var farZ = light.shadowCascadeFarZ[ cascade ]; var pointsFrustum = virtualLight.pointsFrustum; pointsFrustum[ 0 ].z = nearZ; pointsFrustum[ 1 ].z = nearZ; pointsFrustum[ 2 ].z = nearZ; pointsFrustum[ 3 ].z = nearZ; pointsFrustum[ 4 ].z = farZ; pointsFrustum[ 5 ].z = farZ; pointsFrustum[ 6 ].z = farZ; pointsFrustum[ 7 ].z = farZ; }
javascript
{ "resource": "" }
q45105
updateShadowCamera
train
function updateShadowCamera( camera, light ) { var shadowCamera = light.shadowCamera, pointsFrustum = light.pointsFrustum, pointsWorld = light.pointsWorld; _min.set( Infinity, Infinity, Infinity ); _max.set( -Infinity, -Infinity, -Infinity ); for ( var i = 0; i < 8; i ++ ) { var p = pointsWorld[ i ]; p.copy( pointsFrustum[ i ] ); THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera ); p.applyMatrix4( shadowCamera.matrixWorldInverse ); if ( p.x < _min.x ) _min.x = p.x; if ( p.x > _max.x ) _max.x = p.x; if ( p.y < _min.y ) _min.y = p.y; if ( p.y > _max.y ) _max.y = p.y; if ( p.z < _min.z ) _min.z = p.z; if ( p.z > _max.z ) _max.z = p.z; } shadowCamera.left = _min.x; shadowCamera.right = _max.x; shadowCamera.top = _max.y; shadowCamera.bottom = _min.y; // can't really fit near/far //shadowCamera.near = _min.z; //shadowCamera.far = _max.z; shadowCamera.updateProjectionMatrix(); }
javascript
{ "resource": "" }
q45106
getObjectMaterial
train
function getObjectMaterial( object ) { return object.material instanceof THREE.MeshFaceMaterial ? object.material.materials[ 0 ] : object.material; }
javascript
{ "resource": "" }
q45107
train
function(){ this.frameIndex++; if (this.frameIndex >= this.rightCropPosition) { this.frameIndex = this.frameIndex % (this.rightCropPosition || 1); if ((this.frameIndex < this.leftCropPosition)) { this.frameIndex = this.leftCropPosition; } }else{ this.frameIndex--; } }
javascript
{ "resource": "" }
q45108
train
function (factor) { console.log('cull frames', factor); factor || (factor = 1); for (var i = 0; i < this.frameData.length; i++) { this.frameData.splice(i, factor); } this.setMetaData(); }
javascript
{ "resource": "" }
q45109
train
function () { if (this.frameData.length == 0) { return 0 } return this.frameData.length / (this.frameData[this.frameData.length - 1].timestamp - this.frameData[0].timestamp) * 1000000; }
javascript
{ "resource": "" }
q45110
train
function(){ var frameData = this.croppedFrameData(), packedFrames = [], frameDatum; packedFrames.push(this.packingStructure); for (var i = 0, len = frameData.length; i < len; i++){ frameDatum = frameData[i]; packedFrames.push( this.packArray( this.packingStructure, frameDatum ) ); } return packedFrames; }
javascript
{ "resource": "" }
q45111
train
function(packedFrames){ var packingStructure = packedFrames[0]; var frameData = [], frameDatum; for (var i = 1, len = packedFrames.length; i < len; i++) { frameDatum = packedFrames[i]; frameData.push( this.unPackArray( packingStructure, frameDatum ) ); } return frameData; }
javascript
{ "resource": "" }
q45112
train
function (callback) { var xhr = new XMLHttpRequest(), url = this.url, recording = this, contentLength = 0; xhr.onreadystatechange = function () { if (xhr.readyState === xhr.DONE) { if (xhr.status === 200 || xhr.status === 0) { if (xhr.responseText) { recording.finishLoad(xhr.responseText, callback); } else { console.error('Leap Playback: "' + url + '" seems to be unreachable or the file is empty.'); } } else { console.error('Leap Playback: Couldn\'t load "' + url + '" (' + xhr.status + ')'); } } }; xhr.addEventListener('progress', function(oEvent){ if ( recording.options.loadProgress ) { if (oEvent.lengthComputable) { var percentComplete = oEvent.loaded / oEvent.total; recording.options.loadProgress( recording, percentComplete, oEvent ); } } }); this.loading = true; xhr.open("GET", url, true); xhr.send(null); }
javascript
{ "resource": "" }
q45113
train
function () { this.idle(); delete this.recording; this.recording = new Recording({ timeBetweenLoops: this.options.timeBetweenLoops, loop: this.options.loop, requestProtocolVersion: this.controller.connection.opts.requestProtocolVersion, serviceVersion: this.controller.connection.protocol.serviceVersion }); this.controller.emit('playback.stop', this); }
javascript
{ "resource": "" }
q45114
train
function () { if (!this.recording || this.recording.blank()) return; var finalFrame = this.recording.cloneCurrentFrame(); finalFrame.hands = []; finalFrame.fingers = []; finalFrame.pointables = []; finalFrame.tools = []; this.sendImmediateFrame(finalFrame); }
javascript
{ "resource": "" }
q45115
train
function (frameData) { // Would be better to check controller.streaming() in showOverlay, but that method doesn't exist, yet. this.setGraphic('wave'); if (frameData.hands.length > 0) { this.recording.addFrame(frameData); this.hideOverlay(); } else if ( !this.recording.blank() ) { this.finishRecording(); } }
javascript
{ "resource": "" }
q45116
train
function (frames) { this.setFrames(frames); if (player.recording != this){ console.log('recordings changed during load'); return } // it would be better to use streamingCount here, but that won't be in until 0.5.0+ // For now, it just flashes for a moment until the first frame comes through with a hand on it. // if (autoPlay && (controller.streamingCount == 0 || pauseOnHand)) { if (player.autoPlay) { player.play(); if (player.pauseOnHand) { player.setGraphic('connect'); } } player.controller.emit('playback.recordingSet', this); }
javascript
{ "resource": "" }
q45117
train
function (graphicName) { if (!this.overlay) return; if (this.graphicName == graphicName) return; this.graphicName = graphicName; switch (graphicName) { case 'connect': this.overlay.style.display = 'block'; this.overlay.innerHTML = CONNECT_LEAP_ICON; break; case 'wave': this.overlay.style.display = 'block'; this.overlay.innerHTML = MOVE_HAND_OVER_LEAP_ICON; break; case undefined: this.overlay.innerHTML = ''; break; } }
javascript
{ "resource": "" }
q45118
hasNestedProperty
train
function hasNestedProperty(obj, propertyPath, returnVal = false) { if (!propertyPath) return false; // strip the leading dot propertyPath = propertyPath.replace(/^\./, ''); const properties = propertyPath.split('.'); for (var i = 0; i < properties.length; i++) { var prop = properties[i]; if (!obj || !obj.hasOwnProperty(prop)) { return returnVal ? null : false; } else { obj = obj[prop]; } } return returnVal ? obj : true; }
javascript
{ "resource": "" }
q45119
DumperGetArgs
train
function DumperGetArgs(a,index) { var args = new Array(); // This is kind of ugly, but I don't want to use js1.2 functions, just in case... for (var i=index; i<a.length; i++) { args[args.length] = a[i]; } return args; }
javascript
{ "resource": "" }
q45120
train
function(onReady) { var self = this; if (APPID === 'change me') { console.log('Error -- edit weatherman.js and provide the APPID for Open Weathermap.'.bold.yellow); } // Load the replies and process them. rs.loadFile("weatherman.rive").then(function() { rs.sortReplies(); onReady(); }).catch(function(err) { console.error(err); }); // This is a function for delivering the message to a user. Its actual // implementation could vary; for example if you were writing an IRC chatbot // this message could deliver a private message to a target username. self.sendMessage = function(username, message) { // This just logs it to the console like "[Bot] @username: message" console.log( ["[Brick Tamland]", message].join(": ").underline.green ); }; // This is a function for a user requesting a reply. It just proxies through // to RiveScript. self.getReply = function(username, message, callback) { return rs.reply(username, message, self); } }
javascript
{ "resource": "" }
q45121
train
function(rs, args) { // This function is invoked by messages such as: // what is 5 subtracted by 2 // add 6 to 7 if (args[0].match(/^\d+$/)) { // They used the first form, with a number. return Controllers.doMath(args[1], args[0], args[2]); } else { // The second form, first word being the operation. return Controllers.doMath(args[0], args[1], args[2]); } }
javascript
{ "resource": "" }
q45122
DocusignAPIError
train
function DocusignAPIError(message, type, code, subcode, traceID) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'DocusignAPIError'; this.message = message; this.type = type; this.code = code; this.subcode = subcode; this.traceID = traceID; this.status = 500; }
javascript
{ "resource": "" }
q45123
checkMethods
train
function checkMethods(spec) { assert(spec.method, 'missing route methods'); if (typeof spec.method === 'string') { spec.method = spec.method.split(' '); } if (!Array.isArray(spec.method)) { throw new TypeError('route methods must be an array or string'); } if (spec.method.length === 0) { throw new Error('missing route method'); } spec.method.forEach((method, i) => { assert(typeof method === 'string', 'route method must be a string'); spec.method[i] = method.toLowerCase(); }); }
javascript
{ "resource": "" }
q45124
checkValidators
train
function checkValidators(spec) { if (!spec.validate) return; let text; if (spec.validate.body) { text = 'validate.type must be declared when using validate.body'; assert(/json|form/.test(spec.validate.type), text); } if (spec.validate.type) { text = 'validate.type must be either json, form, multipart or stream'; assert(/json|form|multipart|stream/i.test(spec.validate.type), text); } if (spec.validate.output) { spec.validate._outputValidator = new OutputValidator(spec.validate.output); } // default HTTP status code for failures if (!spec.validate.failure) { spec.validate.failure = 400; } }
javascript
{ "resource": "" }
q45125
wrapError
train
function wrapError(spec, parsePayload) { return async function errorHandler(ctx, next) { try { await parsePayload(ctx, next); } catch (err) { captureError(ctx, 'type', err); if (spec.validate.continueOnError) { return await next(); } else { return ctx.throw(err); } } }; }
javascript
{ "resource": "" }
q45126
makeJSONBodyParser
train
function makeJSONBodyParser(spec) { const opts = spec.validate.jsonOptions || {}; if (typeof opts.limit === 'undefined') { opts.limit = spec.validate.maxBody; } return async function parseJSONPayload(ctx, next) { if (!ctx.request.is('json')) { return ctx.throw(400, 'expected json'); } ctx.request.body = ctx.request.body || await parse.json(ctx, opts); await next(); }; }
javascript
{ "resource": "" }
q45127
makeFormBodyParser
train
function makeFormBodyParser(spec) { const opts = spec.validate.formOptions || {}; if (typeof opts.limit === 'undefined') { opts.limit = spec.validate.maxBody; } return async function parseFormBody(ctx, next) { if (!ctx.request.is('urlencoded')) { return ctx.throw(400, 'expected x-www-form-urlencoded'); } ctx.request.body = ctx.request.body || await parse.form(ctx, opts); await next(); }; }
javascript
{ "resource": "" }
q45128
makeBodyParser
train
function makeBodyParser(spec) { if (!(spec.validate && spec.validate.type)) return noopMiddleware; switch (spec.validate.type) { case 'json': return wrapError(spec, makeJSONBodyParser(spec)); case 'form': return wrapError(spec, makeFormBodyParser(spec)); case 'stream': case 'multipart': return wrapError(spec, makeMultipartParser(spec)); default: throw new Error(`unsupported body type: ${spec.validate.type}`); } }
javascript
{ "resource": "" }
q45129
makeValidator
train
function makeValidator(spec) { const props = 'header query params body'.split(' '); return async function validator(ctx, next) { if (!spec.validate) return await next(); let err; for (let i = 0; i < props.length; ++i) { const prop = props[i]; if (spec.validate[prop]) { err = validateInput(prop, ctx, spec.validate); if (err) { captureError(ctx, prop, err); if (!spec.validate.continueOnError) return ctx.throw(err); } } } await next(); if (spec.validate._outputValidator) { debug('validating output'); err = spec.validate._outputValidator.validate(ctx); if (err) { err.status = 500; return ctx.throw(err); } } }; }
javascript
{ "resource": "" }
q45130
makeSpecExposer
train
function makeSpecExposer(spec) { const defn = clone(spec); return async function specExposer(ctx, next) { ctx.state.route = defn; await next(); }; }
javascript
{ "resource": "" }
q45131
prepareRequest
train
async function prepareRequest(ctx, next) { ctx.request.params = ctx.params; await next(); }
javascript
{ "resource": "" }
q45132
addConfig
train
function addConfig(configObj, platformObj) { for (const n in configObj) { if (n != PLATFORM && configObj.hasOwnProperty(n)) { if (angular.isObject(configObj[n])) { if (angular.isUndefined(platformObj[n])) { platformObj[n] = {}; } addConfig(configObj[n], platformObj[n]); } else if (angular.isUndefined(platformObj[n])) { platformObj[n] = null; } } } }
javascript
{ "resource": "" }
q45133
removeImplementedInterfaces
train
function removeImplementedInterfaces(context, node, ast) { if (node.implements && node.implements.length > 0) { var first = node.implements[0]; var last = node.implements[node.implements.length - 1]; var idx = findTokenIndex(ast.tokens, first.start); do { idx--; } while (ast.tokens[idx].value !== 'implements'); var lastIdx = findTokenIndex(ast.tokens, last.start); do { if (!isComment(ast.tokens[idx])) { removeNode(context, ast.tokens[idx]); } } while (idx++ !== lastIdx); } }
javascript
{ "resource": "" }
q45134
regexpPattern
train
function regexpPattern(pattern) { if (!pattern) { return pattern; } // A very simplified glob transform which allows passing legible strings like // "myPath/*.js" instead of a harder to read RegExp like /\/myPath\/.*\.js/. if (typeof pattern === 'string') { pattern = pattern.replace(/\./g, '\\.').replace(/\*/g, '.*'); if (pattern[0] !== '/') { pattern = '/' + pattern; } return new RegExp(pattern); } if (typeof pattern.test === 'function') { return pattern; } throw new Error( 'flow-remove-types: includes and excludes must be RegExp or path strings. Got: ' + pattern ); }
javascript
{ "resource": "" }
q45135
train
function(e) { var current = _this._getCurrentTab(); // Fetch current tab var activatedTab = e.data.tab; e.preventDefault(); // Trigger click event for whenever a tab is clicked/touched even if the tab is disabled activatedTab.tab.trigger('tabs-click', activatedTab); // Make sure this tab isn't disabled if(!activatedTab.disabled) { // Check if hash has to be set in the URL location if(_this.options.setHash) { // Set the hash using the history api if available to tackle Chromes repaint bug on hash change if(history.pushState) { // Fix for missing window.location.origin in IE if (!window.location.origin) { window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: ''); } history.pushState(null, null, window.location.origin + window.location.pathname + window.location.search + activatedTab.selector); } else { // Otherwise fallback to the hash update for sites that don't support the history api window.location.hash = activatedTab.selector; } } e.data.tab._ignoreHashChange = true; // Check if the activated tab isnt the current one or if its collapsible. If not, do nothing if(current !== activatedTab || _this._isCollapisble()) { // The activated tab is either another tab of the current one. If it's the current tab it is collapsible // Either way, the current tab can be closed _this._closeTab(e, current); // Check if the activated tab isnt the current one or if it isnt collapsible if(current !== activatedTab || !_this._isCollapisble()) { _this._openTab(e, activatedTab, false, true); } } } }
javascript
{ "resource": "" }
q45136
after
train
function after(count, callback) { var countdown = count; return function shim(err) { if (typeof callback !== 'function') return; if (err) { callback(err); callback = null; return; } if (--countdown === 0) { callback(); callback = null; } }; }
javascript
{ "resource": "" }
q45137
createJsonFileDiscoverProvider
train
function createJsonFileDiscoverProvider(hostsFile) { var fs = require('fs'); return function jsonFileProvider(callback) { fs.readFile(hostsFile, function onFileRead(err, data) { if (err) { callback(err); return; } var hosts; try { hosts = JSON.parse(data.toString()); } catch (e) { callback(e); return; } callback(null, hosts); return; }); }; }
javascript
{ "resource": "" }
q45138
retryDiscoverProvider
train
function retryDiscoverProvider(opts, innerDiscoverProvider) { if (!opts) { return innerDiscoverProvider; } return function retryingDiscoverProvider(callback) { var policy; var defaultPolicy = { minDelay: 500, maxDelay: 15000, timeout: 60000 }; if (opts === true) { policy = defaultPolicy; } else { policy = _.defaults({}, opts, defaultPolicy); } var backoff = opts.backoff || new Backoff(policy); var lastError = null; attempt(null); function attempt(fail) { if (fail) { fail.lastError = lastError; return setImmediate(callback, fail); } innerDiscoverProvider(function onTry(err, hosts) { // We got results! if (!err && hosts !== null && hosts.length > 0) { return setImmediate(callback, null, hosts); } lastError = err; backoff.retry(attempt); }); } }; }
javascript
{ "resource": "" }
q45139
createFromOpts
train
function createFromOpts(opts) { opts = opts || {}; if (typeof opts === 'function') { return opts; } if (typeof opts === 'string') { return createJsonFileDiscoverProvider(opts); } if (Array.isArray(opts)) { return createStaticHostsProvider(opts); } var discoverProvider; if (opts.discoverProvider) { discoverProvider = opts.discoverProvider; } else if (opts.hosts) { discoverProvider = createStaticHostsProvider(opts.hosts); } else if (opts.bootstrapFile && typeof opts.bootstrapFile === 'string') { discoverProvider = createJsonFileDiscoverProvider(opts.bootstrapFile); } else if (opts.bootstrapFile && Array.isArray(opts.bootstrapFile)) { /* This weird case is added for backwards compatibility :( */ discoverProvider = createStaticHostsProvider(opts.bootstrapFile); } else { return null; } if (opts.retry) { discoverProvider = retryDiscoverProvider(opts.retry, discoverProvider); } return discoverProvider; }
javascript
{ "resource": "" }
q45140
resolveEventConfig
train
function resolveEventConfig(ringpop, traceEvent) { var tracerConfig = tracerConfigMap[traceEvent]; if (!tracerConfig) { return null; } var sourcePath = tracerConfig.sourcePath; // subtle but important -- if we resolve here, then the underlying object // can never change. if we do latent resolution, there may be a resource // leak when we try to remove listener from something that is out of our // reachable scope. var emitter = getIn(ringpop, sourcePath.slice(0, -1)); var event = _.last(sourcePath); return emitter && _.defaults( {}, { sourceEmitter: emitter, sourceEvent: event, traceEvent: traceEvent }, tracerConfig ); }
javascript
{ "resource": "" }
q45141
Config
train
function Config(ringpop, seedConfig) { seedConfig = seedConfig || {}; this.ringpop = ringpop; this.store = {}; this._seed(seedConfig); }
javascript
{ "resource": "" }
q45142
Update
train
function Update(subject, source) { if (!(this instanceof Update)) { return new Update(subject, source); } this.id = uuid.v4(); this.timestamp = Date.now(); // Populate subject subject = subject || {}; this.address = subject.address; this.incarnationNumber = subject.incarnationNumber; this.status = subject.status; // Populate source source = source || {}; this.source = source.address; this.sourceIncarnationNumber = source.incarnationNumber; }
javascript
{ "resource": "" }
q45143
takeNode
train
function takeNode(hosts) { var index = Math.floor(Math.random() * hosts.length); var host = hosts[index]; hosts.splice(index, 1); return host; }
javascript
{ "resource": "" }
q45144
DampingReusableEvent
train
function DampingReusableEvent(member, oldDampScore) { this.name = this.constructor.name; this.member = member; this.oldDampScore = oldDampScore; }
javascript
{ "resource": "" }
q45145
createDampReqHandler
train
function createDampReqHandler(addr) { var start = self.Date.now(); return function onDampReq(err, res) { var timing = self.Date.now() - start; self.ringpop.stat('timing', 'protocol.damp-req', timing); // Prevents double-callback if (typeof callback !== 'function') { return; } numPendingReqs--; if (err) { errors.push(err); } else { // Enrich the result with the addr of the damp // req member for reporting purposes. res.dampReqAddr = addr; res.timing = timing; results.push(res); } // The first rVal requests will be reported. if (results.length >= rVal) { callback(null, results); callback = null; return; } if (numPendingReqs < rVal - results.length) { callback(UnattainableRValError({ flappers: flapperAddrs, rVal: rVal, errors: errors })); callback = null; return; } }; }
javascript
{ "resource": "" }
q45146
callRequestMiddleware
train
function callRequestMiddleware(arg2, arg3) { i += 1; if (i < self.middlewares.length) { var next = self.middlewares[i].request; if (typeof next === 'function') { next(req, arg2, arg3, callRequestMiddleware); } else { // skip this middleware if it doesn't implement request callRequestMiddleware(arg2, arg3); } } else { handler(req, arg2, arg3, callResponseMiddleware); } }
javascript
{ "resource": "" }
q45147
callResponseMiddleware
train
function callResponseMiddleware(err, res1, res2) { i -= 1; if (i >= 0) { var next = self.middlewares[i].response; if (typeof next === 'function') { next(req, err, res1, res2, callResponseMiddleware); } else { // skip this middleware if it doesn't implement response callResponseMiddleware(err, res1, res2); } } else { callback(req, err, res1, res2); } }
javascript
{ "resource": "" }
q45148
dedupeNonExistent
train
function dedupeNonExistent(nonExistent) { const deduped = new Set(nonExistent); nonExistent.length = deduped.size; let i = 0; for (const elem of deduped) { nonExistent[i] = elem; i++; } }
javascript
{ "resource": "" }
q45149
setLocale
train
async function setLocale (sim, opts, localeConfig = {}, safari = false) { if (!opts.language && !opts.locale && !opts.calendarFormat) { logger.debug('No reason to set locale'); return { _updated: false, }; } // we need the simulator to have its directories in place if (await sim.isFresh()) { await launchAndQuitSimulator(sim, safari); } logger.debug('Setting locale information'); localeConfig = { language: opts.language || localeConfig.language, locale: opts.locale || localeConfig.locale, calendarFormat: opts.calendarFormat || localeConfig.calendarFormat, _updated: false, }; try { let updated = await sim.updateLocale(opts.language, opts.locale, opts.calendarFormat); if (updated) { localeConfig._updated = true; } } catch (e) { logger.errorAndThrow(`Appium was unable to set locale info: ${e}`); } return localeConfig; }
javascript
{ "resource": "" }
q45150
train
function (strategy, selector, mult, context) { let ext = mult ? 's' : ''; let command = ''; context = !context ? context : `, '${context}'` ; switch (strategy) { case 'name': command = `au.getElement${ext}ByName('${selector}'${context})`; break; case 'accessibility id': command = `au.getElement${ext}ByAccessibilityId('${selector}'${context})`; break; case 'id': command = `au.getElement${ext}ById('${selector}')`; break; case '-ios uiautomation': command = `au.getElement${ext}ByUIAutomation('${selector}'${context})`; break; default: command = `au.getElement${ext}ByType('${selector}'${context})`; } return command; }
javascript
{ "resource": "" }
q45151
train
function () { var alert = getAlert(); if (alert.isNil()) { throw new ERROR.NoAlertOpenError(); } var texts = this.getElementsByType('text', alert); // If an alert does not have a title, alert.name() is null, use empty string var text = alert.name() || ""; if (texts.length > 1) { // Safari alerts have the URL as a title if (text.indexOf('http') === 0 || text === "") { text = texts.last().name(); } else { // go through all the text elements and concatenate text = null; for (var i = 0; i < texts.length; i++) { var subtext = texts[i].name(); if (subtext) { // if there is text, append it, otherwise use sub text text = text ? text + ' ' + subtext : subtext; } } } } else if (parseFloat($.systemVersion) >= 9.3) { // iOS 9.3 Safari alerts only have one UIATextView texts = this.getElementsByType('UIATextView', alert); text = texts[0].name(); } return text; }
javascript
{ "resource": "" }
q45152
quickLaunch
train
async function quickLaunch (udid, appPath = path.resolve(__dirname, '..', '..', 'assets', 'TestApp.app')) { let traceTemplatePath = await xcode.getAutomationTraceTemplatePath(); let scriptPath = path.resolve(__dirname, '..', '..', 'assets', 'blank_instruments_test.js'); let traceDocument = path.resolve('/', 'tmp', 'testTrace.trace'); let resultsPath = path.resolve('/', 'tmp'); // the trace document can be in a weird state // but we never do anything with it, so delete await fs.rimraf(traceDocument); let args = [ 'instruments', '-D', traceDocument, '-t', traceTemplatePath, '-w', udid, appPath, '-e', 'UIASCRIPT', scriptPath, '-e', 'UIARESULTSPATH', resultsPath]; log.debug(`Running command: 'xcrun ${args.join(' ')}'`); await exec('xcrun', args); }
javascript
{ "resource": "" }
q45153
convertCookie
train
function convertCookie (value, converter) { if (value.indexOf('"') === 0) { // this is a quoted cookied according to RFC2068 // remove enclosing quotes and internal quotes and backslashes value = value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\'); } let parsedValue; try { parsedValue = decodeURIComponent(value.replace(/\+/g, ' ')); } catch (e) { // no need to fail if we can't decode log.warn(e); } return converter ? converter(parsedValue) : parsedValue; }
javascript
{ "resource": "" }
q45154
createJSCookie
train
function createJSCookie (key, value, options = {}) { return [ encodeURIComponent(key), '=', value, options.expires ? `; expires=${options.expires}` : '', options.path ? `; path=${options.path}` : '', options.domain ? `; domain=${options.domain}` : '', options.secure ? '; secure' : '' ].join(''); }
javascript
{ "resource": "" }
q45155
createJWPCookie
train
function createJWPCookie (key, cookieString, converter = null) { let result = {}; let cookies = cookieString ? cookieString.split('; ') : []; for (let cookie of cookies) { let parts = cookie.split('='); // get the first and second element as name and value let name = decodeURIComponent(parts.shift()); let val = parts[0]; // if name is key, this is the central element of the cookie, so add as `name` // otherwise it is an optional element if (key && key === name) { result.name = key; result.value = convertCookie(val, converter); } else { result[name] = convertCookie(val, converter); } } return result; }
javascript
{ "resource": "" }
q45156
getValue
train
function getValue (key, cookieString, converter = null) { let result = createJWPCookie(key, cookieString, converter); // if `key` is undefined we want the entire cookie return _.isUndefined(key) ? result : result.value; }
javascript
{ "resource": "" }
q45157
train
function (selector, ctx) { if (typeof selector !== 'string') { return null; } var _ctx = $.mainApp() , elems = []; if (typeof ctx === 'string') { _ctx = this.cache[ctx]; } else if (typeof ctx !== 'undefined') { _ctx = ctx; } $.target().pushTimeout(0); if (selector === 'alert') { var alert = $.mainApp().alert(); if (alert) { elems = $(alert); } } else { elems = $(selector, _ctx); } $.target().popTimeout(); return elems; }
javascript
{ "resource": "" }
q45158
train
function () { var orientation = $.orientation() , value = null; switch (orientation) { case UIA_DEVICE_ORIENTATION_UNKNOWN: case UIA_DEVICE_ORIENTATION_FACEUP: case UIA_DEVICE_ORIENTATION_FACEDOWN: value = "UNKNOWN"; break; case UIA_DEVICE_ORIENTATION_PORTRAIT: case UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN: value = "PORTRAIT"; break; case UIA_DEVICE_ORIENTATION_LANDSCAPELEFT: case UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT: value = "LANDSCAPE"; break; } if (value !== null) { return value; } else { throw new ERROR.UnknownError('Unsupported Orientation: ' + orientation); } }
javascript
{ "resource": "" }
q45159
Request
train
function Request(options) { return new Promise(function(resolve, reject) { client(options, function(err, res) { if (err) { reject(err); } else { resolve(res); } }); }); }
javascript
{ "resource": "" }
q45160
BlameRangeList
train
function BlameRangeList(blame) { var ranges = blame.ranges; return ranges .filter(function(range) { return ( range && range.commit && range.commit.author && range.commit.author.user && range.commit.author.user.login ); }) .map(function(range) { return BlameRange({ age: range.age, count: range.endingLine - range.startingLine + 1, login: range.commit.author.user.login }); }) .filter(Boolean); }
javascript
{ "resource": "" }
q45161
parseGithubURL
train
function parseGithubURL(url) { var githubUrlRe = /github\.com\/([^/]+)\/([^/]+)\/pull\/([0-9]+)/; var match = url.match(githubUrlRe); if (!match) { return null; } return { owner: match[1], repo: match[2], number: match[3] }; }
javascript
{ "resource": "" }
q45162
main
train
async function main() { event.$emit('before-client-render') if (globalState.initialData) { dataStore.replaceState(globalState.initialData) } await routerReady(router) if (router.getMatchedComponents().length === 0) { throw new ReamError(pageNotFound(router.currentRoute.path)) } }
javascript
{ "resource": "" }
q45163
SendStream
train
function SendStream (req, path, options) { Stream.call(this) var opts = options || {} this.options = opts this.path = path this.req = req this._acceptRanges = opts.acceptRanges !== undefined ? Boolean(opts.acceptRanges) : true this._cacheControl = opts.cacheControl !== undefined ? Boolean(opts.cacheControl) : true this._etag = opts.etag !== undefined ? Boolean(opts.etag) : true this._dotfiles = opts.dotfiles !== undefined ? opts.dotfiles : 'ignore' if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') { throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') } this._hidden = Boolean(opts.hidden) if (opts.hidden !== undefined) { deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead') } // legacy support if (opts.dotfiles === undefined) { this._dotfiles = undefined } this._extensions = opts.extensions !== undefined ? normalizeList(opts.extensions, 'extensions option') : [] this._immutable = opts.immutable !== undefined ? Boolean(opts.immutable) : false this._index = opts.index !== undefined ? normalizeList(opts.index, 'index option') : ['index.html'] this._lastModified = opts.lastModified !== undefined ? Boolean(opts.lastModified) : true this._maxage = opts.maxAge || opts.maxage this._maxage = typeof this._maxage === 'string' ? ms(this._maxage) : Number(this._maxage) this._maxage = !isNaN(this._maxage) ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) : 0 this._root = opts.root ? resolve(opts.root) : null if (!this._root && opts.from) { this.from(opts.from) } }
javascript
{ "resource": "" }
q45164
clearHeaders
train
function clearHeaders (res) { var headers = getHeaderNames(res) for (var i = 0; i < headers.length; i++) { res.removeHeader(headers[i]) } }
javascript
{ "resource": "" }
q45165
containsDotFile
train
function containsDotFile (parts) { for (var i = 0; i < parts.length; i++) { var part = parts[i] if (part.length > 1 && part[0] === '.') { return true } } return false }
javascript
{ "resource": "" }
q45166
contentRange
train
function contentRange (type, size, range) { return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size }
javascript
{ "resource": "" }
q45167
getHeaderNames
train
function getHeaderNames (res) { return typeof res.getHeaderNames !== 'function' ? Object.keys(res._headers || {}) : res.getHeaderNames() }
javascript
{ "resource": "" }
q45168
hasListeners
train
function hasListeners (emitter, type) { var count = typeof emitter.listenerCount !== 'function' ? emitter.listeners(type).length : emitter.listenerCount(type) return count > 0 }
javascript
{ "resource": "" }
q45169
normalizeList
train
function normalizeList (val, name) { var list = [].concat(val || []) for (var i = 0; i < list.length; i++) { if (typeof list[i] !== 'string') { throw new TypeError(name + ' must be array of strings or false') } } return list }
javascript
{ "resource": "" }
q45170
parseTokenList
train
function parseTokenList (str) { var end = 0 var list = [] var start = 0 // gather tokens for (var i = 0, len = str.length; i < len; i++) { switch (str.charCodeAt(i)) { case 0x20: /* */ if (start === end) { start = end = i + 1 } break case 0x2c: /* , */ list.push(str.substring(start, end)) start = end = i + 1 break default: end = i + 1 break } } // final token list.push(str.substring(start, end)) return list }
javascript
{ "resource": "" }
q45171
tarballedProps
train
function tarballedProps (pkg, spec, opts) { const needsShrinkwrap = (!pkg || ( pkg._hasShrinkwrap !== false && !pkg._shrinkwrap )) const needsBin = !!(!pkg || ( !pkg.bin && pkg.directories && pkg.directories.bin )) const needsIntegrity = !pkg || (!pkg._integrity && pkg._integrity !== false) const needsShasum = !pkg || (!pkg._shasum && pkg._shasum !== false) const needsHash = needsIntegrity || needsShasum const needsManifest = !pkg || !pkg.name const needsExtract = needsShrinkwrap || needsBin || needsManifest if (!needsShrinkwrap && !needsBin && !needsHash && !needsManifest) { return BB.resolve({}) } else { opts = optCheck(opts) const tarStream = fetchFromManifest(pkg, spec, opts) const extracted = needsExtract && new tar.Parse() return BB.join( needsShrinkwrap && jsonFromStream('npm-shrinkwrap.json', extracted), needsManifest && jsonFromStream('package.json', extracted), needsBin && getPaths(extracted), needsHash && ssri.fromStream(tarStream, { algorithms: ['sha1', 'sha512'] }), needsExtract && pipe(tarStream, extracted), (sr, mani, paths, hash) => { if (needsManifest && !mani) { const err = new Error(`Non-registry package missing package.json: ${spec}.`) err.code = 'ENOPACKAGEJSON' throw err } const extraProps = mani || {} delete extraProps._resolved // drain out the rest of the tarball tarStream.resume() // if we have directories.bin, we need to collect any matching files // to add to bin if (paths && paths.length) { const dirBin = mani ? (mani && mani.directories && mani.directories.bin) : (pkg && pkg.directories && pkg.directories.bin) if (dirBin) { extraProps.bin = {} paths.forEach(filePath => { if (minimatch(filePath, dirBin + '/**')) { const relative = path.relative(dirBin, filePath) if (relative && relative[0] !== '.') { extraProps.bin[path.basename(relative)] = path.join(dirBin, relative) } } }) } } return Object.assign(extraProps, { _shrinkwrap: sr, _resolved: (mani && mani._resolved) || (pkg && pkg._resolved) || spec.fetchSpec, _integrity: needsIntegrity && hash && hash.sha512 && hash.sha512[0].toString(), _shasum: needsShasum && hash && hash.sha1 && hash.sha1[0].hexDigest() }) } ) } }
javascript
{ "resource": "" }
q45172
stripBOM
train
function stripBOM (content) { content = content.toString() // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) // because the buffer-to-string conversion in `fs.readFileSync()` // translates it to FEFF, the UTF-16 BOM. if (content.charCodeAt(0) === 0xFEFF) return content.slice(1) return content }
javascript
{ "resource": "" }
q45173
genPoints
train
function genPoints (inArr, ref, ref$1) { var minX = ref.minX; var minY = ref.minY; var maxX = ref.maxX; var maxY = ref.maxY; var max = ref$1.max; var min = ref$1.min; var arr = inArr.map(function (item) { return (typeof item === 'number' ? item : item.value); }); var minValue = Math.min.apply(Math, arr.concat( [min] )) - 0.001; var gridX = (maxX - minX) / (arr.length - 1); var gridY = (maxY - minY) / (Math.max.apply(Math, arr.concat( [max] )) + 0.001 - minValue); return arr.map(function (value, index) { var title = typeof inArr[index] === 'number' ? inArr[index] : inArr[index].title; return { x: index * gridX + minX, y: maxY - (value - minValue) * gridY + +(index === arr.length - 1) * 0.00001 - +(index === 0) * 0.00001, v: title } }) }
javascript
{ "resource": "" }
q45174
ignorePlugins
train
function ignorePlugins(plugins, currentPlugin) { return plugins.reduce(function (acc, plugin) { if (currentPlugin && currentPlugin.indexOf(plugin) > -1) { return true; } return acc; }, false); }
javascript
{ "resource": "" }
q45175
generateGCMPayload
train
function generateGCMPayload(requestData, pushId, timeStamp, expirationTime) { let payload = { priority: 'high' }; payload.data = { data: requestData.data, push_id: pushId, time: new Date(timeStamp).toISOString() } const optionalKeys = ['content_available', 'notification']; optionalKeys.forEach((key, index, array) => { if (requestData.hasOwnProperty(key)) { payload[key] = requestData[key]; } }); if (expirationTime) { // The timeStamp and expiration is in milliseconds but gcm requires second let timeToLive = Math.floor((expirationTime - timeStamp) / 1000); if (timeToLive < 0) { timeToLive = 0; } if (timeToLive >= GCMTimeToLiveMax) { timeToLive = GCMTimeToLiveMax; } payload.timeToLive = timeToLive; } return payload; }
javascript
{ "resource": "" }
q45176
sliceDevices
train
function sliceDevices(devices, chunkSize) { let chunkDevices = []; while (devices.length > 0) { chunkDevices.push(devices.splice(0, chunkSize)); } return chunkDevices; }
javascript
{ "resource": "" }
q45177
runMicroBenchmarks
train
function runMicroBenchmarks(lists, resources) { console.log('Run micro bench...'); // Create adb engine to use in benchmark const { engine, serialized } = createEngine(lists, resources, { loadCosmeticFilters: true, loadNetworkFilters: true, }, true /* Also serialize engine */); const filters = getFiltersFromLists(lists); const combinedLists = filters.join('\n'); const { networkFilters, cosmeticFilters } = parseFilters(combinedLists); const results = {}; // Arguments shared among benchmarks const args = { lists, resources, engine, filters, serialized, networkFilters, cosmeticFilters, combinedLists, }; [ benchCosmeticsFiltersParsing, benchEngineCreation, benchEngineDeserialization, benchEngineSerialization, benchGetCosmeticTokens, benchGetNetworkTokens, benchNetworkFiltersParsing, benchStringHashing, benchStringTokenize, benchGetCosmeticsFilters, ].forEach((bench) => { if (bench.name.toLowerCase().includes(GREP)) { const suite = new Benchmark.Suite(); suite.add(bench.name, () => bench(args)).on('cycle', (event) => { results[bench.name] = { opsPerSecond: event.target.hz, relativeMarginOfError: event.target.stats.rme, numberOfSamples: event.target.stats.sample.length, }; }).run({ async: false }); } }); return { engineStats: { numFilters: engine.size, numCosmeticFilters: engine.cosmetics.size, numExceptionFilters: engine.exceptions.size, numImportantFilters: engine.importants.size, numRedirectFilters: engine.redirects.size, }, microBenchmarks: results, }; }
javascript
{ "resource": "" }
q45178
train
function() { let docDomain = this.getDocDomain(); if ( docDomain === '' ) { docDomain = this.docHostname; } if ( this.domain !== undefined && this.domain !== '' ) { return this.domain !== docDomain; } const hostname = this.getHostname(); if ( hostname.endsWith(docDomain) === false ) { return true; } const i = hostname.length - docDomain.length; if ( i === 0 ) { return false; } return hostname.charCodeAt(i - 1) !== 0x2E /* '.' */; }
javascript
{ "resource": "" }
q45179
train
function() { let tabDomain = this.getTabDomain(); if ( tabDomain === '' ) { tabDomain = this.tabHostname; } if ( this.domain !== undefined && this.domain !== '' ) { return this.domain !== tabDomain; } const hostname = this.getHostname(); if ( hostname.endsWith(tabDomain) === false ) { return true; } const i = hostname.length - tabDomain.length; if ( i === 0 ) { return false; } return hostname.charCodeAt(i - 1) !== 0x2E /* '.' */; }
javascript
{ "resource": "" }
q45180
train
function() { const buf8 = pslBuffer8; const buf32 = pslBuffer32; const iCharData = buf32[CHARDATA_PTR_SLOT]; let iNode = pslBuffer32[RULES_PTR_SLOT]; let cursorPos = -1; let iLabel = LABEL_INDICES_SLOT; // Label-lookup loop for (;;) { // Extract label indices const labelBeg = buf8[iLabel+1]; const labelLen = buf8[iLabel+0] - labelBeg; // Match-lookup loop: binary search let r = buf32[iNode+0] >>> 16; if ( r === 0 ) { break; } const iCandidates = buf32[iNode+2]; let l = 0; let iFound = 0; while ( l < r ) { const iCandidate = l + r >>> 1; const iCandidateNode = iCandidates + iCandidate + (iCandidate << 1); const candidateLen = buf32[iCandidateNode+0] & 0x000000FF; let d = labelLen - candidateLen; if ( d === 0 ) { const iCandidateChar = candidateLen <= 4 ? iCandidateNode + 1 << 2 : iCharData + buf32[iCandidateNode+1]; for ( let i = 0; i < labelLen; i++ ) { d = buf8[labelBeg+i] - buf8[iCandidateChar+i]; if ( d !== 0 ) { break; } } } if ( d < 0 ) { r = iCandidate; } else if ( d > 0 ) { l = iCandidate + 1; } else /* if ( d === 0 ) */ { iFound = iCandidateNode; break; } } // 2. If no rules match, the prevailing rule is "*". if ( iFound === 0 ) { if ( buf8[iCandidates + 1 << 2] !== 0x2A /* '*' */ ) { break; } iFound = iCandidates; } iNode = iFound; // 5. If the prevailing rule is a exception rule, modify it by // removing the leftmost label. if ( (buf32[iNode+0] & 0x00000200) !== 0 ) { if ( iLabel > LABEL_INDICES_SLOT ) { return iLabel - 2; } break; } if ( (buf32[iNode+0] & 0x00000100) !== 0 ) { cursorPos = iLabel; } if ( labelBeg === 0 ) { break; } iLabel += 2; } return cursorPos; }
javascript
{ "resource": "" }
q45181
train
function(tabId, url) { var entry = tabContexts.get(tabId); if ( entry === undefined ) { entry = new TabContext(tabId); entry.autodestroy(); } entry.push(url); mostRecentRootDocURL = url; mostRecentRootDocURLTimestamp = Date.now(); return entry; }
javascript
{ "resource": "" }
q45182
train
function(tabId) { var entry = tabContexts.get(tabId); if ( entry !== undefined ) { return entry; } // https://github.com/chrisaljoudi/uBlock/issues/1025 // Google Hangout popup opens without a root frame. So for now we will // just discard that best-guess root frame if it is too far in the // future, at which point it ceases to be a "best guess". if ( mostRecentRootDocURL !== '' && mostRecentRootDocURLTimestamp + 500 < Date.now() ) { mostRecentRootDocURL = ''; } // https://github.com/chrisaljoudi/uBlock/issues/1001 // Not a behind-the-scene request, yet no page store found for the // tab id: we will thus bind the last-seen root document to the // unbound tab. It's a guess, but better than ending up filtering // nothing at all. if ( mostRecentRootDocURL !== '' ) { return push(tabId, mostRecentRootDocURL); } // If all else fail at finding a page store, re-categorize the // request as behind-the-scene. At least this ensures that ultimately // the user can still inspect/filter those net requests which were // about to fall through the cracks. // Example: Chromium + case #12 at // http://raymondhill.net/ublock/popup.html return tabContexts.get(vAPI.noTabId); }
javascript
{ "resource": "" }
q45183
train
function(s) { const match = reParseRegexLiteral.exec(s); let regexDetails; if ( match !== null ) { regexDetails = match[1]; if ( isBadRegex(regexDetails) ) { return; } if ( match[2] ) { regexDetails = [ regexDetails, match[2] ]; } } else { regexDetails = s.replace(reEatBackslashes, '$1') .replace(reEscapeRegex, '\\$&'); regexToRawValue.set(regexDetails, s); } return regexDetails; }
javascript
{ "resource": "" }
q45184
train
function(server, port, options, cb) { return this.client.connect.call(this.client, server, port, options, cb); }
javascript
{ "resource": "" }
q45185
train
function(middleware, options) { if (this.server && this.server.auth) { this.server.auth(middleware, options); } else { throw new Error("vantage.auth is only available in Vantage.IO. Please use this (npm install vantage-io --save)"); } return this; }
javascript
{ "resource": "" }
q45186
train
function(args, cb) { var ssn = this.getSessionById(args.sessionId); if (!this._authFn) { var nodeEnv = process.env.NODE_ENV || "development"; if (nodeEnv !== "development") { var msg = "The Node server you are connecting to appears " + "to be a production server, and yet its Vantage.js " + "instance does not support any means of authentication. \n" + "To connect to this server without authentication, " + "ensure its 'NODE_ENV' environmental variable is set " + "to 'development' (it is currently '" + nodeEnv + "')."; ssn.log(chalk.yellow(msg)); ssn.authenticating = false; ssn.authenticated = false; cb(msg, false); } else { ssn.authenticating = false; ssn.authenticated = true; cb(void 0, true); } } else { this._authFn.call(ssn, args, function(message, authenticated) { ssn.authenticating = false; ssn.authenticated = authenticated; if (authenticated === true) { cb(void 0, true); } else { cb(message); } }); } }
javascript
{ "resource": "" }
q45187
on
train
function on(str, opts, cbk) { cbk = (_.isFunction(opts)) ? opts : cbk; cbk = cbk || function() {}; opts = opts || {}; ssn.server.on(str, function() { if (!ssn.server || (!ssn.authenticating && !ssn.authenticated)) { //console.log("Not Authenticated. Closing Session.", ssn.authenticating, ssn.authenticated); self.parent._send("vantage-close-downstream", "downstream", { sessionId: ssn.id }); return; } cbk.apply(self, arguments); }); }
javascript
{ "resource": "" }
q45188
matrMult
train
function matrMult(m, v) { return [ new Fraction(m[0]).mul(v[0]).add(new Fraction(m[1]).mul(v[1])), new Fraction(m[2]).mul(v[0]).add(new Fraction(m[3]).mul(v[1])) ]; }
javascript
{ "resource": "" }
q45189
vecSub
train
function vecSub(a, b) { return [ new Fraction(a[0]).sub(b[0]), new Fraction(a[1]).sub(b[1]) ]; }
javascript
{ "resource": "" }
q45190
run
train
function run(V, j) { var t = H(V); //console.log("H(X)"); for (var i in t) { // console.log(t[i].toFraction()); } var s = grad(V); //console.log("vf(X)"); for (var i in s) { // console.log(s[i].toFraction()); } //console.log("multiplikation"); var r = matrMult(t, s); for (var i in r) { // console.log(r[i].toFraction()); } var R = (vecSub(V, r)); console.log("X"+j); console.log(R[0].toFraction(), "= "+R[0].valueOf()); console.log(R[1].toFraction(), "= "+R[1].valueOf()); console.log("\n"); return R; }
javascript
{ "resource": "" }
q45191
train
function(a, b) { parse(a, b); return new Fraction( this["s"] * this["n"] * P["d"] + P["s"] * this["d"] * P["n"], this["d"] * P["d"] ); }
javascript
{ "resource": "" }
q45192
train
function(a, b) { if (isNaN(this['n']) || isNaN(this['d'])) { return new Fraction(NaN); } if (a === undefined) { return new Fraction(this["s"] * this["n"] % this["d"], 1); } parse(a, b); if (0 === P["n"] && 0 === this["d"]) { Fraction(0, 0); // Throw DivisionByZero } /* * First silly attempt, kinda slow * return that["sub"]({ "n": num["n"] * Math.floor((this.n / this.d) / (num.n / num.d)), "d": num["d"], "s": this["s"] });*/ /* * New attempt: a1 / b1 = a2 / b2 * q + r * => b2 * a1 = a2 * b1 * q + b1 * b2 * r * => (b2 * a1 % a2 * b1) / (b1 * b2) */ return new Fraction( this["s"] * (P["d"] * this["n"]) % (P["n"] * this["d"]), P["d"] * this["d"] ); }
javascript
{ "resource": "" }
q45193
train
function(a, b) { parse(a, b); var t = (this["s"] * this["n"] * P["d"] - P["s"] * P["n"] * this["d"]); return (0 < t) - (t < 0); }
javascript
{ "resource": "" }
q45194
regularizeNone
train
function regularizeNone(weights, gradientCount) { const [gradient, count] = gradientCount; for (let i = 0; i < gradient.length; i++) { let grad = (gradient[i] || 0) / count; weights[i] = (weights[i] || 0) - grad; } }
javascript
{ "resource": "" }
q45195
regularizeL1
train
function regularizeL1(weights, gradientCount, stepSize) { const [gradient, count] = gradientCount; for (let i = 0; i < gradient.length; i++) { let grad = (gradient[i] || 0) / count; weights[i] = weights[i] || 0; weights[i] -= stepSize * grad + (weights[i] > 0 ? 1 : -1); } }
javascript
{ "resource": "" }
q45196
regularizeL2
train
function regularizeL2(weights, gradientCount, stepSize, regParam) { const [gradient, count] = gradientCount; for (let i = 0; i < gradient.length; i++) { let grad = (gradient[i] || 0) / count; weights[i] = weights[i] || 0; weights[i] -= stepSize * (grad + regParam * weights[i]); } }
javascript
{ "resource": "" }
q45197
randomizeArray
train
function randomizeArray(array) { let i = array.length; while (i) { let j = Math.floor(Math.random() * i--); [array[i], array[j]] = [array[j], array[i]]; } return array; }
javascript
{ "resource": "" }
q45198
sampleSizeFraction
train
function sampleSizeFraction(num, total, withReplacement) { const minSamplingRate = 1e-10; // Limited by RNG's resolution const delta = 1e-4; // To have 0.9999 success rate const fraction = num / total; let upperBound; if (withReplacement) { // Poisson upper bound for Pr(num successful poisson trials) > (1-delta) let numStd = num < 6 ? 12 : num < 16 ? 9 : 6; upperBound = Math.max(num + numStd * Math.sqrt(num), minSamplingRate) / total; } else { // Binomial upper bound for Pr(num successful bernoulli trials) > (1-delta) let gamma = - Math.log(delta) / total; upperBound = Math.min(1, Math.max(minSamplingRate, fraction + gamma + Math.sqrt(gamma * gamma + 2 * gamma * fraction))); } return upperBound; }
javascript
{ "resource": "" }
q45199
iterateDone
train
function iterateDone() { dlog(start, 'iterate'); blocksToRegister.map(function(block) {mm.register(block);}); if (action) { if (action.opt._postIterate) { action.opt._postIterate(action.init, action.opt, self, tmpPart.partitionIndex, function () { done({data: {host: self.grid.host.uuid, path: self.exportFile}}); }); } else done({data: action.init}); } else { const start1 = Date.now(); self.nodes[self.datasetId].spillToDisk(self, function() { done({pid: self.pid, files: self.files}); dlog(start1, 'spillToDisk'); }); } }
javascript
{ "resource": "" }