_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q31200
assertThresholds
train
function assertThresholds(thresholds) { if (!elv(thresholds)) return null; if (typeof thresholds !== 'object') { throw new TypeError(msg.argThresholds); } const avg = elv.coalesce(thresholds.avg, false); const max = elv.coalesce(thresholds.max, false); const min = elv.coalesce(thresholds.min, false); ...
javascript
{ "resource": "" }
q31201
assertThreshold
train
function assertThreshold(value, other, threshold) { if (!threshold && value > other) throw new ThresholdError(); const ratio = 1 - (value / other); if (ratio < threshold) throw new ThresholdError(); }
javascript
{ "resource": "" }
q31202
checkThresholds
train
function checkThresholds(metrics, thresholds) { if (!elv(thresholds)) return; const target = metrics[thresholds.target]; for (let i = 0; i < metrics.length; i++) { if (i === thresholds.target) continue; const other = metrics[i]; assertThreshold(target.avg, other.avg, thresholds.avg); assertThre...
javascript
{ "resource": "" }
q31203
bench
train
function bench(functions, options) { const funcs = assertFunctions(functions); const opts = assertOptions(options); const metrics = []; const totalRuns = funcs.length * opts.runs; let runCount = 0; for (let i = 0; i < funcs.length; i++) { const func = funcs[i]; const totals = [0, 0]; let max = ...
javascript
{ "resource": "" }
q31204
train
function (accountIdOrSlug, params) { var path; if (accountIdOrSlug) { path = this.constructPath(constants.ACCOUNTS, accountIdOrSlug); return this.Core.GET(path, params); } else { return this.rejectRequest('Bad Request: An account id or slug must be supplied for this operation'); } }
javascript
{ "resource": "" }
q31205
updateContainers
train
function updateContainers(next) { monitor.docker.listContainers(function(err, list) { if (err) { console.log('Error listing running containers: %s', err.message, err); return next(err); } if (!monitor.started) { if (handler.onMonitorStarted) { handler.onMonitorSt...
javascript
{ "resource": "" }
q31206
processDockerEvent
train
function processDockerEvent(event, stop) { if (trackedEvents.indexOf(event.status) !== -1) { var container = containerById.get(event.id); if (container) { if (positiveEvents.indexOf(event.status) !== -1) { updateContainer(container); } else { removeContainer(container...
javascript
{ "resource": "" }
q31207
train
function (attr) { this.debug("STREAM: opened."); this._setStatus(xmpp.Status.AUTHENTICATING); var handshake = sha1.hex(attr.id + this.password); this.debug("Calculated authentication token " + handshake + " from stream id '" + attr.id + "' and password '" + this.password + "'"); this.debug("Sending auth...
javascript
{ "resource": "" }
q31208
addConditionalEventListener
train
function addConditionalEventListener(emitter, type, listener) { function conditionalListener() { var done = listener.apply(emitter, arguments); if (done === true) { removeEventListener(emitter, type, conditionalListener); } } // TODO Check be...
javascript
{ "resource": "" }
q31209
listenMany
train
function listenMany(handler, isFunction, emitter, args) { var errors = []; if (isFunction) { try { handler.apply(emitter, args); } catch (error) { errors.push(error); } } else { var length = handler.length, ...
javascript
{ "resource": "" }
q31210
spliceList
train
function spliceList(list, index) { for (var i = index, j = i + 1, length = list.length; j < length; i += 1, j += 1) { list[i] = list[j]; } list.pop(); }
javascript
{ "resource": "" }
q31211
train
function(){ this.randX=65535; while(this.joints!==null){ this.removeJoint(this.joints); } while(this.contacts!==null){ this.removeContact(this.contacts); } while(this.rigidBodies!==null){ this.removeRigidBody(this.rigidBodies); ...
javascript
{ "resource": "" }
q31212
train
function(rigidBody){ if(rigidBody.parent){ throw new Error("It is not possible to be added to more than one world one of the rigid body"); } rigidBody.parent=this; rigidBody.awake(); for(var shape=rigidBody.shapes; shape!==null; shape=shape.next){ this.add...
javascript
{ "resource": "" }
q31213
train
function(rigidBody){ var remove=rigidBody; if(remove.parent!==this)return; remove.awake(); var js=remove.jointLink; while(js!=null){ var joint=js.joint; js=js.next; this.removeJoint(joint); } for(var shape=rigidBody.shapes; shape!==null;...
javascript
{ "resource": "" }
q31214
train
function(shape){ if(!shape.parent || !shape.parent.parent){ throw new Error("It is not possible to be added alone to shape world"); } shape.proxy = this.broadPhase.createProxy(shape); shape.updateProxy(); this.broadPhase.addProxy(shape.proxy); }
javascript
{ "resource": "" }
q31215
train
function(joint){ if(joint.parent){ throw new Error("It is not possible to be added to more than one world one of the joint"); } if(this.joints!=null)(this.joints.prev=joint).next=this.joints; this.joints=joint; joint.parent=this; this.numJoints++; join...
javascript
{ "resource": "" }
q31216
train
function(joint){ var remove=joint; var prev=remove.prev; var next=remove.next; if(prev!==null)prev.next=next; if(next!==null)next.prev=prev; if(this.joints==remove)this.joints=next; remove.prev=null; remove.next=null; this.numJoints--; remo...
javascript
{ "resource": "" }
q31217
train
function(shape){ if(shape.parent){ throw new Error("It is not possible that you add to the multi-rigid body the shape of one"); } if(this.shapes!=null)(this.shapes.prev=shape).next=this.shapes; this.shapes=shape; shape.parent=this; if(this.parent)this.parent.a...
javascript
{ "resource": "" }
q31218
train
function(shape){ var remove=shape; if(remove.parent!=this)return; var prev=remove.prev; var next=remove.next; if(prev!=null)prev.next=next; if(next!=null)next.prev=prev; if(this.shapes==remove)this.shapes=next; remove.prev=null; remove.next=null; ...
javascript
{ "resource": "" }
q31219
train
function(){ if(!this.allowSleep||!this.sleeping)return; this.sleeping=false; this.sleepTime=0; // awake connected constraints var cs=this.contactLink; while(cs!=null){ cs.body.sleepTime=0; cs.body.sleeping=false; cs=cs.next; } ...
javascript
{ "resource": "" }
q31220
train
function(){ if(!this.allowSleep||this.sleeping)return; this.linearVelocity.init(); this.angularVelocity.init(); this.sleepPosition.copy(this.position); this.sleepOrientation.copy(this.orientation); /*this.linearVelocity.x=0; this.linearVelocity.y=0; this.l...
javascript
{ "resource": "" }
q31221
train
function(timeStep){ switch(this.type){ case this.BODY_STATIC: this.linearVelocity.init(); this.angularVelocity.init(); // ONLY FOR TEST if(this.controlPos){ this.position.copy(this.newPosition); t...
javascript
{ "resource": "" }
q31222
train
function(){ var prev=this.s1Link.prev; var next=this.s1Link.next; if(prev!==null)prev.next=next; if(next!==null)next.prev=prev; if(this.shape1.contactLink==this.s1Link)this.shape1.contactLink=next; this.s1Link.prev=null; this.s1Link.next=null; this.s1Link....
javascript
{ "resource": "" }
q31223
train
function(x,y,z,normalX,normalY,normalZ,penetration,flip){ var p=this.points[this.numPoints++]; p.position.x=x; p.position.y=y; p.position.z=z; var r=this.body1.rotation; var rx=x-this.body1.position.x; var ry=y-this.body1.position.y; var rz=z-this.body1.po...
javascript
{ "resource": "" }
q31224
train
function(aabb1,aabb2){ this.minX = (aabb1.minX<aabb2.minX) ? aabb1.minX : aabb2.minX; this.maxX = (aabb1.maxX>aabb2.maxX) ? aabb1.maxX : aabb2.maxX; this.minY = (aabb1.minY<aabb2.minY) ? aabb1.minY : aabb2.minY; this.maxY = (aabb1.maxY>aabb2.maxY) ? aabb1.maxY : aabb2.maxY; this....
javascript
{ "resource": "" }
q31225
train
function(){ var h=this.maxY-this.minY; var d=this.maxZ-this.minZ; return 2*((this.maxX-this.minX)*(h+d)+h*d); }
javascript
{ "resource": "" }
q31226
train
function(x,y,z){ return x>=this.minX&&x<=this.maxX&&y>=this.minY&&y<=this.maxY&&z>=this.minZ&&z<=this.maxZ; }
javascript
{ "resource": "" }
q31227
train
function(s1,s2){ var b1=s1.parent; var b2=s2.parent; if( b1==b2 || // same parents (!b1.isDynamic&&!b2.isDynamic) || // static or kinematic object (s1.belongsTo&s2.collidesWith)==0 || (s2.belongsTo&s1.collidesWith)==0 // collision filtering ){ return ...
javascript
{ "resource": "" }
q31228
train
function(){ while(this.numPairs>0){ var pair=this.pairs[--this.numPairs]; pair.shape1=null; pair.shape2=null; } this.numPairChecks=0; this.collectPairs(); }
javascript
{ "resource": "" }
q31229
train
function(leaf){ if(this.root==null){ this.root=leaf; return; } var lb=leaf.aabb; var sibling=this.root; var oldArea; var newArea; while(sibling.proxy==null){ // descend the node to search the best pair var c1=sibling.child1; ...
javascript
{ "resource": "" }
q31230
train
function(leaf){ if(leaf==this.root){ this.root=null; return; } var parent=leaf.parent; var sibling; if(parent.child1==leaf){ sibling=parent.child2; }else{ sibling=parent.child1; } if(parent==this.root){ ...
javascript
{ "resource": "" }
q31231
train
function (timeString) { if (!timeString) { return null } var timeArr = timeString.split(':') return parseInt(timeArr[0], 10) * 3600 + parseInt(timeArr[1], 10) * 60 + parseInt(timeArr[2]) }
javascript
{ "resource": "" }
q31232
train
function () { insertCfg.model.sync({force: true}).then(function () { var streamInserterCfg = util.makeStreamerConfig(insertCfg.model) var inserter = dbStreamer.getInserter(streamInserterCfg) inserter.connect(function (err) { if (err) return callback(err) csv() .fromFile(...
javascript
{ "resource": "" }
q31233
done
train
function done( error, data, info ) { error = error || null; data = data || null; info = info || null; clbk( error, data, info ); }
javascript
{ "resource": "" }
q31234
train
function (identifierUrn, params) { var path = this.constructPath(constants.IDENTIFIERS, identifierUrn); return this.Core.GET(path, params); }
javascript
{ "resource": "" }
q31235
train
function (identifierUrn) { if (identifierUrn) { var path = this.constructPath(constants.IDENTIFIERS, identifierUrn); return this.Core.DELETE(path); } else { return this.rejectRequest('Bad request: An identifier URN is required.'); } }
javascript
{ "resource": "" }
q31236
findOne
train
function findOne(repository, options) { const entityPrimaryKeyColumn = lodash_1.find(repository.metadata.columns, (columnMetadata) => columnMetadata.isPrimary).propertyName; const entityColumns = repository.metadata.columns.map((columnMetadata) => columnMetadata.propertyName); const entityManyToOneOrOneToOn...
javascript
{ "resource": "" }
q31237
updateStatus
train
function updateStatus(runCount, totalRuns, stream) { if (runCount % 10 !== 0) return; const percent = Math.floor((runCount / totalRuns) * 100); const blocks = Math.floor(percent / 2); const empty = 50 - blocks; const value = '|' + '\u2588'.repeat(blocks) + '\u2591'.repeat(empty) + '| ' + ...
javascript
{ "resource": "" }
q31238
train
function (identifier, params) { var path = this.constructPath(constants.LOCATIONS, identifier); return this.Core.GET(path, params); }
javascript
{ "resource": "" }
q31239
train
function (identifier) { var path; if (identifier) { path = this.constructPath(constants.LOCATIONS, identifier); return this.Core.DELETE(path); } else { return this.rejectRequest('Bad Request: A location identifier is required.'); } }
javascript
{ "resource": "" }
q31240
train
function (locationIdentifier, spaceIdentifier, params) { var path; if (locationIdentifier) { path = this.constructPath(constants.LOCATIONS, locationIdentifier, constants.SPACES, spaceIdentifier); return this.Core.GET(path, params); } else { return this.rejectRequest('Bad Reques...
javascript
{ "resource": "" }
q31241
train
function (locationIdentifier, data) { var path; if (locationIdentifier) { path = this.constructPath(constants.LOCATIONS, locationIdentifier, constants.SPACES); return this.Core.POST(path, data); } else { return this.rejectRequest('Bad Request: A location identifier is required....
javascript
{ "resource": "" }
q31242
train
function (locationIdentifier, params) { var path; if (locationIdentifier) { path = this.constructPath(constants.LOCATIONS, locationIdentifier, constants.PRESENCE); return this.Core.GET(path, params); } else { return this.rejectRequest('Bad Request: A location identifier is requ...
javascript
{ "resource": "" }
q31243
updateInterpolatedTimes
train
function updateInterpolatedTimes (cfg, callback) { const db = cfg.db const lastTimepoint = cfg.lastTimepoint const nextTimepoint = cfg.nextTimepoint const timeDiff = nextTimepoint.arrival_time - lastTimepoint.departure_time let literal // sqlite null is a string if (nextTimepoint.shape_dist_traveled && ne...
javascript
{ "resource": "" }
q31244
interpolateStopTimes
train
function interpolateStopTimes (db, callback) { console.log('interpolating stop times') const streamerConfig = util.makeStreamerConfig(db.trip) const querier = dbStreamer.getQuerier(streamerConfig) const maxUpdateConcurrency = db.trip.sequelize.getDialect() === 'sqlite' ? 1 : 100 const updateQueue = async.queu...
javascript
{ "resource": "" }
q31245
onComplete
train
function onComplete (err) { if (err) { console.log('interpolation encountered an error: ', err) return callback(err) } // set is complete and create a queue drain function // however, a feed may not have any interpolated times, so // `isComplete` is set in case nothing is pushed to the q...
javascript
{ "resource": "" }
q31246
onRowComplete
train
function onRowComplete () { if (rowTimeout) { clearTimeout(rowTimeout) } if (isComplete && numUpdates === 0) { rowTimeout = setTimeout(() => { // check yet again, because interpolated times could've appeared since setting timeout if (numUpdates === 0) { console.log('int...
javascript
{ "resource": "" }
q31247
requestId
train
function requestId (ctx, next) { let requestId = uuid.v4() ctx.id = requestId ctx.request.id = requestId ctx.state.requestId = requestId ctx.set('X-Request-Id', requestId) return next() }
javascript
{ "resource": "" }
q31248
rdelete
train
function rdelete(m, key) { if (m.parent && m.parent.filename === require.resolve(key)) { delete m.parent; } for (var i = m.children.length - 1; i >= 0; i--) { if (m.children[i].filename === require.resolve(key)) { m.children.splice(i, 1); } else { rdel...
javascript
{ "resource": "" }
q31249
getNewVersions
train
function getNewVersions() { return getTags() .then(tags => { var newVersions = [] for(tag of tags) { if (semver.gt(tag.name, update.latest) || ( semver.eq(tag.name, update.latest) && (semver(tag.name).build[0] || 0) > (semver(update.latest).build[0] || 0) )) { n...
javascript
{ "resource": "" }
q31250
cloneRepo
train
function cloneRepo() { return new Promise((resolve, reject) => { git.clone(`https://${GH_TOKEN}@github.com/dbtek/bootswatch-dist.git`, '.tmp/repo', (err, result) => { if (err) { return reject(err) } resolve(result) }) }) }
javascript
{ "resource": "" }
q31251
copyRepo
train
function copyRepo(dest) { return new Promise((resolve, reject) => { ncp('.tmp/repo', dest, (err) => { if (err) { reject(err) return } resolve() }) }) }
javascript
{ "resource": "" }
q31252
downloadBootstrapAssets
train
function downloadBootstrapAssets(version, path) { console.log(chalk.blue((`Downloading Bootstrap assets to ${path}`))) version = semver.clean(version) const url = 'https://maxcdn.bootstrapcdn.com/bootstrap' var proms = [ 'fonts/glyphicons-halflings-regular.eot', 'fonts/glyphicons-halflings-regular.woff'...
javascript
{ "resource": "" }
q31253
updatePackageInfo
train
function updatePackageInfo(theme, version) { const cwd = `.tmp/${version}/${theme}/publish` bower.version = `${version}-${theme}` pkg.version = `${version}-${theme}` return Promise.all([ fs.writeFile(`${cwd}/bower.json`, JSON.stringify(bower, null, 4)), fs.writeFile(`${cwd}/package.json`, JSON.stringify...
javascript
{ "resource": "" }
q31254
releaseTheme
train
function releaseTheme(theme, version) { const repoPath = `.tmp/${version}/${theme}/publish` return setupThemeRepo(theme, version) .then(() => { console.log(chalk.blue('Committing changes...')) return new Promise((resolve, reject) => { // commit changes git.add(['css', 'js', 'fonts', ...
javascript
{ "resource": "" }
q31255
train
function(callback) { fs.stat(outputFile,function(err,stat) { if (err) { return callback(null) } console.log('Found old ' + outputFile + ' so now removing') fs.unlinkSync(outputFile) return callback(null) }) }
javascript
{ "resource": "" }
q31256
train
function(callback) { fs.appendFileSync(outputFile,";(function(root,factory){\r\n") fs.appendFileSync(outputFile," if (typeof define === 'function' && define.amd) {\r\n") fs.appendFileSync(outputFile," define([], factory);\r\n") fs.appendFileSync(outputFile," } else if (typeof exports === 'objec...
javascript
{ "resource": "" }
q31257
train
function(callback) { var fileLoop = function(currentDir,templateDirectories,cb) { var callback_has_been_called = false fs.readdir(currentDir,function(err,files) { if (err) { return console.log('Unable to find files in path',currentDir) } var num = files.length var finishFile = fun...
javascript
{ "resource": "" }
q31258
train
function(callback) { fs.appendFileSync(outputFile,"\r\n") fs.appendFileSync(outputFile," return puglatizer;\r\n") fs.appendFileSync(outputFile,"}));\r\n") return callback() }
javascript
{ "resource": "" }
q31259
resolveHandler
train
function resolveHandler(_ref4) { var action = _ref4.action; var type = _ref4.type; var payload = _ref4.payload; var error = _ref4.error; return _extends({}, action, { type: type, payload: payload, error: error }); }
javascript
{ "resource": "" }
q31260
createFetchMiddleware
train
function createFetchMiddleware() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var config = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var finalConfig = _extends({}, config); // Be compatible with previous API if (typeof config === 'boo...
javascript
{ "resource": "" }
q31261
getUrlParams
train
function getUrlParams(path) { if (!path) { return {}; } var bits = path.split('?'); var querystring = bits.length > 1 ? bits[1] : ''; return toObject(querystring); }
javascript
{ "resource": "" }
q31262
_defaults
train
function _defaults (config) { let values = require('./defaults/default') try { values = merge(values, require(`./defaults/${process.env.NODE_ENV}`)) } catch (e) { } return defaultsDeep(config, values) }
javascript
{ "resource": "" }
q31263
extractDataFromIntelHexLine
train
function extractDataFromIntelHexLine(intelHexLine) { if (!intelHexLine.startsWith(':')) { throw new Error(`Intel hex lines need to start with ':'`) } let asciiHex = intelHexLine.slice(1, intelHexLine.length) if (asciiHex.length === 0) { throw new Error(`Length of ascii hex string needs to be greater t...
javascript
{ "resource": "" }
q31264
train
function() { var i = 0 var part = null for( var i = 0; i < this.partitions.length; i++ ) { part = this.partitions[i] if( part.type === 0xEE || part.type === 0xEF ) { return part } } return null }
javascript
{ "resource": "" }
q31265
replaceCodeBlocks
train
function replaceCodeBlocks(contents) { function processCode() { return ast => { visit(ast, 'code', node => { const start = node.position.start.line; const end = node.position.end.line; for (let line = start; line < end - 1; line++) { lines[line] = ''; } }); }; } const lines = splitLin...
javascript
{ "resource": "" }
q31266
controllerMethod
train
function controllerMethod (controller, method) { if (controller && controller[method]) { return controller[method] } // Handle hello-based Controller classes if (isClass(controller) && controller.action) { return controller.action(method) } return notImplemented }
javascript
{ "resource": "" }
q31267
applyFetchMiddleware
train
function applyFetchMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } var middlewaresWithOnResolve = middlewares.filter(function (m) { return typeof m.onResolve === 'function'; }); if (middlewaresWithOnRe...
javascript
{ "resource": "" }
q31268
run
train
function run (action, command, name, flags) { switch (action) { case 'new': case 'generate': case 'g': generate(command, name, flags) break case 'migrate': migrate(command || 'up') break case 'up': migrate('up') break case 'down': case 'rollback': ...
javascript
{ "resource": "" }
q31269
generate
train
function generate (generatorName, name, flags) { let generator switch (generatorName) { case 'app': generator = new generators.App(name) break case 'controller': generator = new generators.Controller(name, flags) break case 'model': generator = new generators.Model(name, f...
javascript
{ "resource": "" }
q31270
migrate
train
async function migrate (direction) { let config = require(path.join(process.cwd(), '.', 'config')) let db = require(path.join(process.cwd(), '.', 'db')) if (direction === 'up') { await db.migrate.latest(config.db) } else if (direction === 'down') { await db.migrate.rollback(config.db) } else { cl...
javascript
{ "resource": "" }
q31271
train
function (options) { return options.mount && options.target && options.component && type(options.component) === TYPES.STRING && type(options.target) === TYPES.STRING && type(options.mount) === TYPES.STRING; }
javascript
{ "resource": "" }
q31272
train
function (options) { return ( options.paths && options.baseUrl && type(options.paths) === TYPES.OBJECT && type(options.baseUrl) === TYPES.STRING ) || ( options.buildProfile && type(options.buildProfile) === TYPES.STRING ); }
javascript
{ "resource": "" }
q31273
train
function (options) { return options.moduleRoot && options.remapModule && options.ignorePatterns && type(options.moduleRoot) === TYPES.STRING && type(options.remapModule) === TYPES.STRING && ( (type(options.ignorePatterns) === TYPES.STRING || type(options.ignorePatterns) === TYPES.REGEXP) ...
javascript
{ "resource": "" }
q31274
train
function (path) { var profile; try { profile = eval(fs.readFileSync(path, 'utf-8')); } catch (err) { // set profile to empty, check in prerender will throw an error // if no path or baseUrl is present profile = {}; } return profile; }
javascript
{ "resource": "" }
q31275
train
function (moduleRoot, remapModule, ignores) { var tree = madge(moduleRoot, { format: 'amd' }).tree, paths = [], map = {}; /** * Filter function to test module paths, ignores can be array[string|regexp]|string|regexp * @param {string} path - module path */ var matches = function ...
javascript
{ "resource": "" }
q31276
train
function (component, props) { var Component = React.createFactory(component); return ReactDomServer.renderToString(Component(props)); }
javascript
{ "resource": "" }
q31277
train
function (target, mount, component) { var file = fs.readFileSync(target, 'utf-8'); var $ = cheerio.load(file); //- returns true if any of the elements match mount, so throw if false if (!$(mount).is(mount)) { throw messages.errors.domNodeNotFound(mount); } //- write to html $(mount).append(compo...
javascript
{ "resource": "" }
q31278
collectTargetObservablesAndContext
train
function collectTargetObservablesAndContext(templateObject) { var targets = []; var contexts = []; /** * * ``` * // context index sample (`x` == Observable) * { * foo: x, // => ['foo'] * bar: { * foo: x, // => ['bar', 'foo'] * bar: [_, _, x] // => ['bar', 'bar', 2...
javascript
{ "resource": "" }
q31279
Code
train
function Code( buffer, start, end ) { if( !(this instanceof Code) ) return new Code( buffer, start, end ) this.offset = start || 0x00 if( Buffer.isBuffer( buffer ) ) { this.data = buffer.slice( start, end ) } else { this.data = Buffer.alloc( 446 ) } }
javascript
{ "resource": "" }
q31280
train
function(options) { var that = this this.name = options.name // Record the url and protocol, ignore SSL certs this.url = url.parse(options.url) if (this.url.protocol.indexOf('https') === 0) { this.protocol = https this.url.rejectUnauthorized = false } else this.proto...
javascript
{ "resource": "" }
q31281
train
function(element) { var c={}; try { var rect = element.getBoundingClientRect(); c.x = Math.floor((rect.left + rect.right) / 2); c.y = Math.floor((rect.top + rect.bottom) / 2); } catch(e) { c.x = 1; c.y = 1; } return c; }
javascript
{ "resource": "" }
q31282
train
function(event, property, value) { try { Object.defineProperty(event, property, { get : function() { return value; } }); } catch(e) { event[property] = value; } }
javascript
{ "resource": "" }
q31283
train
function(element, content) { var nodeName = element.nodeName.toLowerCase(), type = element.hasAttribute('type') ? element.getAttribute('type') : null; if (nodeName === 'textarea') { return true; } if (nodeName === 'input' && ['text', 'password', 'number', 'date'].indexOf(type) !== ...
javascript
{ "resource": "" }
q31284
train
function(element) { if('TEXTAREA'===element.nodeName ||('INPUT'===element.nodeName&&element.hasAttribute('type') &&('text'===element.getAttribute('type') ||'number'===element.getAttribute('type')) ) ) { return true; } return false; }
javascript
{ "resource": "" }
q31285
train
function(element) { if('TEXTAREA'===element.nodeName || 'SELECT'===element.nodeName || ('INPUT'===element.nodeName&&element.hasAttribute('type') &&('text'===element.getAttribute('type') || 'number'===element.getAttribute('type') || 'password'===element.getAttribute('type') ...
javascript
{ "resource": "" }
q31286
removeElement
train
function removeElement(elem) { var parent = elem.parentNode; if (parent && parent.nodeType !== 11) { parent.removeChild(elem); } }
javascript
{ "resource": "" }
q31287
parseUrl
train
function parseUrl(url, params) { var paramsStr = ''; if (typeof params === 'string') { paramsStr = params; } else if ((typeof params === 'undefined' ? 'undefined' : _typeof(params)) === 'object') { Object.keys(params).forEach(function (key) { if (url.indexOf(key + '=') < 0) { paramsStr += '...
javascript
{ "resource": "" }
q31288
createMap
train
function createMap(mapConfig) { app.debug('MapActions >>> createMap'); var basemap = (0, _jsUtilsParams.getUrlParams)(location.href)[_jsConstantsAppConstants.MAP.basemap]; if (basemap) { mapConfig.options.basemap = basemap; } var deferred = new Promise(function (resolve) { ...
javascript
{ "resource": "" }
q31289
setBasemap
train
function setBasemap(basemap) { app.debug('MapActions >>> setBasemap'); app.map.setBasemap(basemap); _jsDispatcher.Dispatcher.dispatch({ actionType: _jsConstantsAppConstants.MAP.basemap, data: basemap }); }
javascript
{ "resource": "" }
q31290
_charIsPrintable
train
function _charIsPrintable(charCode) { // C0 control characters if((charCode >=0 && charCode <= 0x1F) || 0x7F === charCode) { return false; } // C1 control characters if(charCode >= 0x80 && charCode <= 0x9F) { return false; } if(-1 !== _downKeys.indexOf(this.CTRL)) { return ...
javascript
{ "resource": "" }
q31291
_inputChar
train
function _inputChar(char) { if(_charIsPrintable(char.charCodeAt(0)) &&utils.isSelectable(document.activeElement)) { // add the char // FIXME: put at caretPosition/replace selected content document.activeElement.value += char; // fire an input event utils.dispatch(document.activeE...
javascript
{ "resource": "" }
q31292
_getModifiers
train
function _getModifiers() { var modifiers = ''; if(_downKeys.length) { for(var i=_downKeys.length-1; i>=0; i--) { if(-1 !== _that.MODIFIERS.indexOf(_downKeys[i])) { modifiers += (modifiers ? ' ' : '') + _downKeys[i]; } } } return modifiers; }
javascript
{ "resource": "" }
q31293
getInputAsStream
train
function getInputAsStream(input) { return new Promise(function(resolve, reject) { if (input.write) { // already a stream resolve(input); } else { // read from file fs.readFileAsync(input, 'utf-8').then(function(data) { // c...
javascript
{ "resource": "" }
q31294
buildJsonSchema
train
function buildJsonSchema(comments) { // skeleton schema object var schema = { properties: { } }; // go through each comment block (comments || []).forEach(function(block) { // we're only interested in customTags (none standard jsDoc comments i.e. @schema.) (block.c...
javascript
{ "resource": "" }
q31295
train
function(arg) { var args = Array.isArray(arg) ? arg : Array.apply(null, arguments); lastMsgDate = new Date(); fs.write(tempFile, JSON.stringify(args) + '\n', 'a'); }
javascript
{ "resource": "" }
q31296
train
function(option) { var opt = { name: option.name || Date.now().toString(), path: option.path ? option.path + '/' : '', rect: option.rect || webpage.viewportSize }; // use clipRect to capture only the area of the specified position webpage.clipRect = opt.rect; webpage.render([options.screenshotPa...
javascript
{ "resource": "" }
q31297
defaultExtractor
train
function defaultExtractor(response) { // 204 NO CONTENT if (response.status === 204) { return undefined; } const contentTypeHeader = response.headers.get('Content-Type'); if (!contentTypeHeader) { // This is the correct thing to do based on my interpretation of the HTTP specification: // https:/...
javascript
{ "resource": "" }
q31298
handleErrors
train
function handleErrors(errorFormatter, response) { if (!response.ok) { if (errorFormatter) { return errorFormatter(response); } return defaultErrorFormatter(response); } return response; }
javascript
{ "resource": "" }
q31299
getOffset
train
function getOffset(selector) { var rect, doc, docElem; var elem = document.querySelector(selector); if(!elem) { return false; } if(!elem.getClientRects().length) { return { top: 0, left: 0, width: 0, height: 0}; } rect = elem.getBoundingClientRect(); if(rect.width ||...
javascript
{ "resource": "" }