_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q28900
train
function (callback) { var self = this; function initDispatcher() { debug('init event dispatcher'); self.dispatcher = new EventDispatcher(self.publisher, self); self.dispatcher.start(callback); } this.store.on('connect', function () { self.emit('connect'); }); this.stor...
javascript
{ "resource": "" }
q28901
train
function (query, skip, limit) { if (!this.store.streamEvents) { throw new Error('Streaming API is not suppoted by '+(this.options.type || 'inmemory') +' db implementation.'); } if (typeof query === 'number') { limit = skip; skip = query; query = {}; }; if (typeof quer...
javascript
{ "resource": "" }
q28902
train
function (commitStamp, skip, limit) { if (!this.store.streamEvents) { throw new Error('Streaming API is not suppoted by '+(this.options.type || 'inmemory') +' db implementation.'); } if (!commitStamp) { var err = new Error('Please pass in a date object!'); debug(err); throw err; ...
javascript
{ "resource": "" }
q28903
train
function (query, revMin, revMax) { if (typeof query === 'string') { query = { aggregateId: query }; } if (!query.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err); if (callback) callback(err); return; } return this.store.streamEventsBy...
javascript
{ "resource": "" }
q28904
train
function (commitStamp, skip, limit, callback) { if (!commitStamp) { var err = new Error('Please pass in a date object!'); debug(err); throw err; } if (typeof skip === 'function') { callback = skip; skip = 0; limit = -1; } else if (typeof limit === 'function') { ...
javascript
{ "resource": "" }
q28905
train
function (query, revMin, revMax, callback) { if (typeof revMin === 'function') { callback = revMin; revMin = 0; revMax = -1; } else if (typeof revMax === 'function') { callback = revMax; revMax = -1; } if (typeof query === 'string') { query = { aggregateId: query }; ...
javascript
{ "resource": "" }
q28906
train
function (query, revMax, callback) { if (typeof revMax === 'function') { callback = revMax; revMax = -1; } if (typeof query === 'string') { query = { aggregateId: query }; } if (!query.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err);...
javascript
{ "resource": "" }
q28907
train
function(obj, callback) { if (obj.streamId && !obj.aggregateId) { obj.aggregateId = obj.streamId; } if (!obj.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err); if (callback) callback(err); return; } obj.streamId = obj.aggregateId; ...
javascript
{ "resource": "" }
q28908
train
function(eventstream, callback) { var self = this; async.waterfall([ function getNewCommitId(callback) { self.getNewId(callback); }, function commitEvents(id, callback) { // start committing. var event, currentRevision = eventstream.currentRevision(), ...
javascript
{ "resource": "" }
q28909
train
function (query, callback) { if (!callback) { callback = query; query = null; } if (typeof query === 'string') { query = { aggregateId: query }; } this.store.getUndispatchedEvents(query, callback); }
javascript
{ "resource": "" }
q28910
train
function (query, callback) { if (!callback) { callback = query; query = null; } if (typeof query === 'string') { query = { aggregateId: query }; } this.store.getLastEvent(query, callback); }
javascript
{ "resource": "" }
q28911
train
function (query, callback) { if (!callback) { callback = query; query = null; } if (typeof query === 'string') { query = { aggregateId: query }; } var self = this; this.store.getLastEvent(query, function (err, evt) { if (err) return callback(err); callback(null,...
javascript
{ "resource": "" }
q28912
train
function (evtOrId, callback) { if (typeof evtOrId === 'object') { evtOrId = evtOrId.id; } this.store.setEventToDispatched(evtOrId, callback); }
javascript
{ "resource": "" }
q28913
getSections
train
function getSections($, root, relative) { var items = []; var sections = root.children("section[data-type], div[data-type='part']"); sections.each(function(index, el) { var jel = $(el); var header = jel.find("> header"); // create section item var item = { id: jel.attr("id"), type...
javascript
{ "resource": "" }
q28914
train
function(config, stream, extras, callback) { var tocFiles = this.tocFiles = []; // First run through every file and get a tree of the section // navigation within that file. Save to our nav object. stream = stream.pipe(through.obj(function(file, enc, cb) { // create cheerio element for file if ...
javascript
{ "resource": "" }
q28915
relativeTOC
train
function relativeTOC(file, parent) { _.each(parent.children, function(child) { if(child.relative) { var href = ""; if(config.format != "pdf") { var relativeFolder = path.relative(path.dirname(file.relative), path.dirname(child.relative)); href = path...
javascript
{ "resource": "" }
q28916
loadConfig
train
function loadConfig(path) { try { var configJSON = JSON.parse(fs.readFileSync(process.cwd() + "/" + path)); console.log("Config file detected: " + path) return configJSON; } catch(e) { console.log("Config file: " + e.toString()) } }
javascript
{ "resource": "" }
q28917
triggerBuild
train
function triggerBuild() { // Pick command lines options that take precedence var cmdConfig = _.pick(argv, ['files', 'verbose']);; // load config file and merge into config var jsonConfig = loadConfig(argv.config || 'magicbook.json'); _.defaults(cmdConfig, jsonConfig); // trigger the build with the new co...
javascript
{ "resource": "" }
q28918
train
function(config, extras, callback) { // load all files in the source folder vfs.src(config.fonts.files) // vinyl-fs dest automatically determines whether a file // should be updated or not, based on the mtime timestamp. // so we don't need to do that manually. .pipe(vfs.dest(path.join(...
javascript
{ "resource": "" }
q28919
train
function(config, stream, extras, callback) { // Finish the stream so we get a full array of files, that // we can use to figure out whether add prev/next placeholders. streamHelpers.finishWithFiles(stream, function(files) { // loop through each file and get the title of the heading // as well ...
javascript
{ "resource": "" }
q28920
train
function(config, stream, extras, callback) { stream = stream.pipe(through.obj(function(file, enc, cb) { var contents = file.contents.toString(); var changed = false; if(file.prev) { changed = true; file.prev.$el = file.prev.$el || cheerio.load(file.prev.contents.toString()); ...
javascript
{ "resource": "" }
q28921
mapImages
train
function mapImages(imageMap, srcFolder, destFolder) { return through.obj(function(file, enc, cb) { // find the relative path to image. If any pipe has changed the filename, // it's the original is set in orgRelative, so we look at that first. var relativeFrom = file.orgRelative || file.relative; var r...
javascript
{ "resource": "" }
q28922
replaceSrc
train
function replaceSrc(imageMap) { return through.obj(function(file, enc, cb) { file.$el = file.$el || cheerio.load(file.contents.toString()); var changed = false; // loop over each image file.$el("img").each(function(i, el) { // convert el to cheerio el var jel = file.$el(this); var ...
javascript
{ "resource": "" }
q28923
serializeParams
train
function serializeParams(params) { for (var key in params) { var param = params[key]; if (param instanceof MediaObject || (param && (params.object !== undefined || params.hub !== undefined || params.sink !== undefined))) { if (param && param.id != null) { params[key] = param.id; ...
javascript
{ "resource": "" }
q28924
encodeRpc
train
function encodeRpc(transaction, method, params, callback) { if (transaction) return transactionOperation.call(transaction, method, params, callback); var object = params.object; if (object && object.transactions && object.transactions.length) { var error = new TransactionNotCommitedExce...
javascript
{ "resource": "" }
q28925
disguise
train
function disguise(target, source, unthenable) { if (source == null || target === source) return target for (var key in source) { if (target[key] !== undefined) continue if (unthenable && (key === 'then' || key === 'catch')) continue if (typeof source[key] === 'function') var descriptor = { ...
javascript
{ "resource": "" }
q28926
disguiseThenable
train
function disguiseThenable(target, source) { if (target === source) return target if (target.then instanceof Function) { var target_then = target.then function then(onFulfilled, onRejected) { if (onFulfilled != null) onFulfilled = onFulfilled.bind(target) if (onRejected != null) onRejected = on...
javascript
{ "resource": "" }
q28927
getConstructor
train
function getConstructor(type, strict) { var result = register.classes[type.qualifiedType] || register.abstracts[type .qualifiedType] || register.classes[type.type] || register.abstracts[type.type] || register.classes[type] || register.abstracts[type]; if (result) return result; if (type.hierarchy !...
javascript
{ "resource": "" }
q28928
createMediaObject
train
function createMediaObject(item, callback) { var transaction = item.transaction; delete item.transaction; var constructor = createConstructor(item, strict); item = constructor.item; delete constructor.item; var params = item.params || {}; delete item.params; if (params.mediaPipeline ...
javascript
{ "resource": "" }
q28929
exec
train
function exec(command, args) { execa.sync(command, args, { stdio: 'inherit', preferLocal: true, }); }
javascript
{ "resource": "" }
q28930
codePointAt
train
function codePointAt(str, idx){ if(idx === undefined){ idx = 0; } var code = str.charCodeAt(idx); // if a high surrogate if (0xD800 <= code && code <= 0xDBFF && idx < str.length - 1){ var hi = code; var low = str.charCodeAt(idx + 1); if (0xDC00 <= low && low <= 0xDFFF){ return ((hi - 0xD8...
javascript
{ "resource": "" }
q28931
expandFiles
train
function expandFiles(files, workingDirectory) { const promises = []; files.forEach((file) => { if ( file.path !== './package.json' && file.path !== './npm-shrinkwrap.json' ) { promises.push(Promise.resolve(file)); return; } findPackageDependencies(workingDirectory, true).forEach((d...
javascript
{ "resource": "" }
q28932
findAliasesForExports
train
function findAliasesForExports(nodes) { const result = new Set(['exports']); nodes.forEach((node) => { if (node.type !== 'VariableDeclaration') { return; } node.declarations.forEach(({ id, init }) => { if (!init) { return; } if (init.type !== 'Identifier') { retur...
javascript
{ "resource": "" }
q28933
stringify
train
function stringify (gj) { if (gj.type === 'Feature') { gj = gj.geometry; } function pairWKT (c) { return c.join(' '); } function ringWKT (r) { return r.map(pairWKT).join(', '); } function ringsWKT (r) { return r.map(ringWKT).map(wrapParens).join(', '); } function multiRingsWKT (r) ...
javascript
{ "resource": "" }
q28934
sendVerificationEmail
train
function sendVerificationEmail (req, res, next) { // skip if we don't need to send the email if (!req.sendVerificationEmail) { next() // send the email } else { var user = req.user var ttl = (settings.emailVerification && settings.emailVerification.tokenTTL) || (3600 * 24 * 7) One...
javascript
{ "resource": "" }
q28935
determineProvider
train
function determineProvider (req, res, next) { var providerID = req.params.provider || req.body.provider if (providerID && settings.providers[providerID]) { req.provider = providers[providerID] } next() }
javascript
{ "resource": "" }
q28936
setUserOnRequest
train
function setUserOnRequest (req, res, next) { if (!req.session || !req.session.user) { return next() } User.get(req.session.user, function (err, user) { if (err) { return next(err) } if (!user) { delete req.session.user return next() } req.user = user next() }) }
javascript
{ "resource": "" }
q28937
hashPassword
train
function hashPassword (data) { var password = data.password var hash = data.hash if (password) { var salt = bcrypt.genSaltSync(10) hash = bcrypt.hashSync(password, salt) } this.hash = hash }
javascript
{ "resource": "" }
q28938
train
function (req, callback) { var params = req.body var clientId = params.client_id var clientSecret = params.client_secret // missing credentials if (!clientId || !clientSecret) { return callback(new AuthorizationError({ error: 'unauthorized_client', error_description: 'Missing ...
javascript
{ "resource": "" }
q28939
dnToDomain
train
function dnToDomain (dn) { if (!dn || typeof dn !== 'string') { return null } var matches = domainDnRegex.exec(dn) if (matches) { return matches[1].replace(dnPartRegex, '$1.').toLowerCase() } else { return null } }
javascript
{ "resource": "" }
q28940
normalizeDN
train
function normalizeDN (dn) { if (!dn || typeof dn !== 'string') { return null } var normalizedDN = '' // Take advantage of replace() to grab the matched segments of the DN. If what // is left over contains unexpected characters, we assume the original DN was // malformed. var extra = dn.replace(dnPartRegex, ...
javascript
{ "resource": "" }
q28941
authorizationCodeGrant
train
function authorizationCodeGrant (code, done) { var endpoint = this.endpoints.token var provider = this.provider var client = this.client var url = endpoint.url var method = endpoint.method && endpoint.method.toLowerCase() var auth = endpoint.auth var parser = endpoint.parser var accept = endpoint.accept...
javascript
{ "resource": "" }
q28942
train
function (done) { Client.listByTrusted('true', { select: [ '_id', 'client_name', 'client_uri', 'application_type', 'logo_uri', 'trusted', 'scopes', 'created', 'modified' ] }, function (err, clients) { ...
javascript
{ "resource": "" }
q28943
train
function (done) { user.authorizedScope(function (err, scopes) { if (err) { return done(err) } done(null, scopes) }) }
javascript
{ "resource": "" }
q28944
train
function (done) { var index = 'users:' + user._id + ':clients' Client.__client.zrevrange(index, 0, -1, function (err, ids) { if (err) { return done(err) } done(null, ids) }) }
javascript
{ "resource": "" }
q28945
setOPBrowserState
train
function setOPBrowserState (event) { var key = 'anvil.connect.op.state' var current = localStorage[key] var update = event.data if (current !== update) { document.cookie = 'anvil.connect.op.state=' + update localStorage['anvil.connect.op.state'] = update } }
javascript
{ "resource": "" }
q28946
pushToRP
train
function pushToRP (event) { if (source) { console.log('updating RP: changed') source.postMessage('changed', origin) } else { console.log('updateRP called but source undefined') } }
javascript
{ "resource": "" }
q28947
respondToRPMessage
train
function respondToRPMessage (event) { var parser, messenger, clientId, rpss, salt, opbs, input, opss, comparison // Parse message origin origin = event.origin parser = document.createElement('a') parser.href = document.referrer messenger = parser.protocol + '//' + parser.host // Igno...
javascript
{ "resource": "" }
q28948
getBearerToken
train
function getBearerToken (req, res, next) { // check for access token in the authorization header if (req.authorization.scheme && req.authorization.scheme.match(/Bearer/i)) { req.bearer = req.authorization.credentials } // check for access token in the query params if (req.query && req.query.access_token)...
javascript
{ "resource": "" }
q28949
selectConnectParams
train
function selectConnectParams (req, res, next) { req.connectParams = req[lookupField[req.method]] || {} next() }
javascript
{ "resource": "" }
q28950
train
function (done) { // the token is random if (token.indexOf('.') === -1) { AccessToken.get(token, function (err, instance) { if (err) { return done(err) } if (!instance) { return done(new UnauthorizedError({ realm: 'user', ...
javascript
{ "resource": "" }
q28951
determineClientScope
train
function determineClientScope (req, res, next) { var params = req.connectParams var subject = req.client var scope = params.scope || subject.default_client_scope if (params.grant_type === 'client_credentials') { Scope.determine(scope, subject, function (err, scope, scopes) { if (err) { return next(er...
javascript
{ "resource": "" }
q28952
unstashParams
train
function unstashParams (req, res, next) { // OAuth 2.0 callbacks should have a state param // OAuth 1.0 must use the session to store the state value var id = req.query.state || req.session.state var key = 'authorization:' + id if (!id) { // && request is OAuth 2.0 return next(new MissingStateError()) ...
javascript
{ "resource": "" }
q28953
verifyAuthorizationCode
train
function verifyAuthorizationCode (req, res, next) { var params = req.connectParams if (params.grant_type === 'authorization_code') { AuthorizationCode.getByCode(params.code, function (err, ac) { if (err) { return next(err) } // Can't find authorization code if (!ac) { return next(new...
javascript
{ "resource": "" }
q28954
parseAuthorizationHeader
train
function parseAuthorizationHeader (req, res, next) { // parse the header if it's present in the request if (req.headers && req.headers.authorization) { var components = req.headers.authorization.split(' ') var scheme = components[0] var credentials = components[1] // ensure the correct number of co...
javascript
{ "resource": "" }
q28955
createUser
train
function createUser (req, res, next) { User.insert(req.body, { private: true }, function (err, user) { if (err) { res.render('signup', { params: qs.stringify(req.body), request: req.body, providers: settings.providers, error: err.message }) } else ...
javascript
{ "resource": "" }
q28956
verifyClientToken
train
function verifyClientToken (req, res, next) { var header = req.headers['authorization'] // missing header if (!header) { return next(new UnauthorizedError({ realm: 'client', error: 'unauthorized_client', error_description: 'Missing authorization header', statusCode: 403 })) // ...
javascript
{ "resource": "" }
q28957
render
train
function render (template, locals, callback) { var engineExt = engineName.charAt(0) === '.' ? engineName : ('.' + engineName) var tmplPath = path.join(templatesDir, template + engineExt) var origTmplPath = path.join(origTemplatesDir, template + engineExt) function renderToText (html) { var text = htmlToT...
javascript
{ "resource": "" }
q28958
sendMail
train
function sendMail (template, locals, options, callback) { var self = this this.render(template, locals, function (err, html, text) { if (err) { return callback(err) } self.transport.sendMail({ from: options.from || defaultFrom, to: options.to, subject: options.subject, html: html, ...
javascript
{ "resource": "" }
q28959
setSessionAmr
train
function setSessionAmr (session, amr) { if (amr) { if (!Array.isArray(amr)) { session.amr = [amr] } else if (session.amr.indexOf(amr) === -1) { session.amr.push(amr) } } }
javascript
{ "resource": "" }
q28960
isOOB
train
function isOOB (cb) { User.listByRoles('authority', function (err, users) { if (err) { return cb(err) } // return true if there are no authority users return cb(null, !users || !users.length) }) }
javascript
{ "resource": "" }
q28961
readSetupToken
train
function readSetupToken (cb) { var token var write = false try { // try to read setup token from filesystem token = keygen.loadSetupToken() // if token is blank, try to generate a new token and save it if (!token.trim()) { write = true } } catch (err) { // if unable to read, try t...
javascript
{ "resource": "" }
q28962
verifyClientIdentifiers
train
function verifyClientIdentifiers (req, res, next) { // mismatching client identifiers if (req.token.payload.sub !== req.params.clientId) { return next(new AuthorizationError({ error: 'unauthorized_client', error_description: 'Mismatching client id', statusCode: 403 })) // all's well }...
javascript
{ "resource": "" }
q28963
verifyRedirectURI
train
function verifyRedirectURI (req, res, next) { var params = req.connectParams Client.get(params.client_id, { private: true }, function (err, client) { if (err) { return next(err) } // The client must be registered. if (!client || client.redirect_uris.indexOf(params.redirect_uri) === -1) { d...
javascript
{ "resource": "" }
q28964
determineUserScope
train
function determineUserScope (req, res, next) { var params = req.connectParams var scope = params.scope var subject = req.user Scope.determine(scope, subject, function (err, scope, scopes) { if (err) { return next(err) } req.scope = scope req.scopes = scopes next() }) }
javascript
{ "resource": "" }
q28965
promptToAuthorize
train
function promptToAuthorize (req, res, next) { var params = req.connectParams var client = req.client var user = req.user var scopes = req.scopes // The client is not trusted and the user has yet to decide on consent if (client.trusted !== true && typeof params.authorize === 'undefined') { // check for ...
javascript
{ "resource": "" }
q28966
verifyClientRegistration
train
function verifyClientRegistration (req, res, next) { // check if we have a token and a token is required var registration = req.body var claims = req.claims var clientRegType = settings.client_registration var required = (registration.trusted || clientRegType !== 'dynamic') var trustedRegScope = settings.tr...
javascript
{ "resource": "" }
q28967
validateTokenParams
train
function validateTokenParams (req, res, next) { var params = req.body // missing grant type if (!params.grant_type) { return next(new AuthorizationError({ error: 'invalid_request', error_description: 'Missing grant type', statusCode: 400 })) } // unsupported grant type if (grantT...
javascript
{ "resource": "" }
q28968
stashParams
train
function stashParams (req, res, next) { var id = crypto.randomBytes(10).toString('hex') var key = 'authorization:' + id var ttl = 1200 // 20 minutes var params = JSON.stringify(req.connectParams) var multi = client.multi() req.session.state = id req.authorizationId = id multi.set(key, params) multi....
javascript
{ "resource": "" }
q28969
getAuthorizedScopes
train
function getAuthorizedScopes (req, res, next) { // Get the scopes authorized for the verified and decoded token var scopeNames = req.claims.scope && req.claims.scope.split(' ') Scope.get(scopeNames, function (err, scopes) { if (err) { return next(err) } req.scopes = scopes next() }) }
javascript
{ "resource": "" }
q28970
writev
train
function writev (chunks, cb) { var buffers = new Array(chunks.length) for (var i = 0; i < chunks.length; i++) { if (typeof chunks[i].chunk === 'string') { buffers[i] = Buffer.from(chunks[i], 'utf8') } else { buffers[i] = chunks[i].chunk } } this._write(Buffer.concat(bu...
javascript
{ "resource": "" }
q28971
onTriggerClick
train
function onTriggerClick(e, noFocus) { toggleSubmenu(elements.trigger, (_, done) => { Classlist(elements.trigger).toggle(ACTIVE_CLASS); const wasActive = Classlist(elements.menu).contains(ACTIVE_CLASS); const first = wasActive ? ACTIVE_CLASS : 'dqpl-show'; const second = first === ACTIVE_CLAS...
javascript
{ "resource": "" }
q28972
toggleSubmenu
train
function toggleSubmenu(trigger, toggleFn) { const droplet = document.getElementById(trigger.getAttribute('aria-controls')); if (!droplet) { return; } toggleFn(droplet, (noFocus, focusTarget) => { const prevExpanded = droplet.getAttribute('aria-expanded'); const wasCollapsed = !prevExpanded || ...
javascript
{ "resource": "" }
q28973
rndid
train
function rndid(len) { len = len || 8; const id = rndm(len); if (document.getElementById(id)) { return rndid(len); } return id; }
javascript
{ "resource": "" }
q28974
init
train
function init (options) { if (typeof options === 'string') { options = { base: options } } options = options || {} // There is probably 99% chance that the project root directory in located // above the node_modules directory var base = nodePath.resolve( options.base || nodePath.join(__dirname, '....
javascript
{ "resource": "" }
q28975
train
function() { console.log('start : init test : ' + bench.initFcts.length); for (let i = 0; i < bench.initFcts.length; i++) { console.log( 'initializing test data ' + (i + 1) + '/' + bench.initFcts.length ); if (bench.initFcts[i]) { bench.initFcts[i].call(this, benc...
javascript
{ "resource": "" }
q28976
train
function(event) { this.currentNb++; if (this.currentNb < this.length) pingAll(connList); //to avoid mysql2 taking all the server memory if (promiseMysql2 && promiseMysql2.clearParserCache) promiseMysql2.clearParserCache(); if (mysql2 && mysql2.clearParserCache) mysql2.clearParserCa...
javascript
{ "resource": "" }
q28977
train
function(pool, iteration, timeoutEnd) { return new Promise(function(resolve, reject) { const creationTryout = function(resolve, reject) { if (closed) { reject( Errors.createError( 'Cannot create new connection to pool, pool closed', true, ...
javascript
{ "resource": "" }
q28978
train
function(pool) { if ( !connectionInCreation && pool.idleConnections() < opts.minimumIdle && pool.totalConnections() < opts.connectionLimit && !closed ) { connectionInCreation = true; process.nextTick(() => { const timeoutEnd = Date.now() + opts.initializationTimeout; ...
javascript
{ "resource": "" }
q28979
train
function(pool) { let toRemove = Math.max(1, pool.idleConnections() - opts.minimumIdle); while (toRemove > 0) { const conn = idleConnections.peek(); --toRemove; if (conn && conn.lastUse + opts.idleTimeout * 1000 < Date.now()) { idleConnections.shift(); conn.forceEnd().catch(err ...
javascript
{ "resource": "" }
q28980
train
function() { firstTaskTimeout = clearTimeout(firstTaskTimeout); const task = taskQueue.shift(); if (task) { const conn = idleConnections.shift(); if (conn) { activeConnections[conn.threadId] = conn; resetTimeoutToNextTask(); processTask(conn, task.sql, task.values, task....
javascript
{ "resource": "" }
q28981
train
function(authFailHandler) { _timeout = null; const handshake = _receiveQueue.peekFront(); authFailHandler( Errors.createError( 'Connection timeout', true, info, '08S01', Errors.ER_CONNECTION_TIMEOUT, handshake ? handshake.stack : null ) ); }
javascript
{ "resource": "" }
q28982
train
function() { const err = Errors.createError( 'socket timeout', true, info, '08S01', Errors.ER_SOCKET_TIMEOUT ); const packetMsgs = info.getLastPackets(); if (packetMsgs !== '') { err.message = err.message + '\nlast received packets:\n' + packetMsgs; } _fatalEr...
javascript
{ "resource": "" }
q28983
train
function(authFailHandler, err) { if (_status === Status.CLOSING || _status === Status.CLOSED) return; _socket.writeBuf = () => {}; _socket.flush = () => {}; //socket has been ended without error if (!err) { err = Errors.createError( 'socket has unexpectedly been closed', true...
javascript
{ "resource": "" }
q28984
FilteredPoolCluster
train
function FilteredPoolCluster(poolCluster, patternArg, selectorArg) { const cluster = poolCluster; const pattern = patternArg; const selector = selectorArg; /** * Get a connection according to previously indicated pattern and selector. * * @return {Promise} */ this.getConnection = () => { retu...
javascript
{ "resource": "" }
q28985
train
function(pool) { const conn = new Connection(options.connOptions); return conn .connect() .then(() => { if (pool.closed) { conn .end() .then(() => {}) .catch(() => {}); return Promise.reject( Errors.createError( ...
javascript
{ "resource": "" }
q28986
checkAllowableRegions
train
function checkAllowableRegions(touchCoordinates, x, y) { for (var i = 0; i < touchCoordinates.length; i += 2) { if (hit(touchCoordinates[i], touchCoordinates[i+1], x, y)) { touchCoordinates.splice(i, i + 2); return true; // allowable region } } return false; // No allowable regio...
javascript
{ "resource": "" }
q28987
preventGhostClick
train
function preventGhostClick(x, y) { if (!touchCoordinates) { $rootElement[0].addEventListener('click', onClick, true); $rootElement[0].addEventListener('touchstart', onTouchStart, true); touchCoordinates = []; } lastPreventedTime = Date.now(); checkAllowableRegions(touchCoordinates, x...
javascript
{ "resource": "" }
q28988
Tweenable
train
function Tweenable (opt_initialState, opt_config) { this._currentState = opt_initialState || {}; this._configured = false; this._scheduleFunction = DEFAULT_SCHEDULE_FUNCTION; // To prevent unnecessary calls to setConfig do not set default configuration here. // Only set default configurat...
javascript
{ "resource": "" }
q28989
aggregate
train
function aggregate (weights, values) { const max = 10 * R.sum(weights); const min = 1 * R.sum(weights); const sum = R.sum(R.zipWith(R.multiply, weights, values)); return score(min, max, sum); }
javascript
{ "resource": "" }
q28990
findNodes
train
function findNodes(body, nodeName) { let nodesArray = []; if (body) { nodesArray = body.filter(node => node.type === nodeName); } return nodesArray; }
javascript
{ "resource": "" }
q28991
isGlobalCallExpression
train
function isGlobalCallExpression(node, destructuredName, aliases) { const isDestructured = node && node.callee && node.callee.name === destructuredName; const isGlobalCall = node.callee && aliases.indexOf(node.callee.name) > -1; return !isDestructured && isGlobalCall; }
javascript
{ "resource": "" }
q28992
getSize
train
function getSize(node) { return (node.loc.end.line - node.loc.start.line) + 1; }
javascript
{ "resource": "" }
q28993
parseCallee
train
function parseCallee(node) { const parsedCallee = []; let callee; if (isCallExpression(node) || isNewExpression(node)) { callee = node.callee; while (isMemberExpression(callee)) { if (isIdentifier(callee.property)) { parsedCallee.push(callee.property.name); } callee = callee.ob...
javascript
{ "resource": "" }
q28994
parseArgs
train
function parseArgs(node) { let parsedArgs = []; if (isCallExpression(node)) { parsedArgs = node.arguments .filter(argument => isLiteral(argument) && argument.value) .map(argument => argument.value); } return parsedArgs; }
javascript
{ "resource": "" }
q28995
findUnorderedProperty
train
function findUnorderedProperty(arr) { for (let i = 0; i < arr.length - 1; i++) { if (arr[i].order > arr[i + 1].order) { return arr[i]; } } return null; }
javascript
{ "resource": "" }
q28996
getPropertyValue
train
function getPropertyValue(node, path) { const parts = typeof path === 'string' ? path.split('.') : path; if (parts.length === 1) { return node[path]; } const property = node[parts[0]]; if (property && parts.length > 1) { parts.shift(); return getPropertyValue(property, parts); } return pro...
javascript
{ "resource": "" }
q28997
collectObjectPatternBindings
train
function collectObjectPatternBindings(node, initialObjToBinding) { if (!isObjectPattern(node.id)) return []; const identifiers = Object.keys(initialObjToBinding); const objBindingName = node.init.name; const bindingIndex = identifiers.indexOf(objBindingName); if (bindingIndex === -1) return []; const bind...
javascript
{ "resource": "" }
q28998
isEmptyMethod
train
function isEmptyMethod(node) { return node.value.body && node.value.body.body && node.value.body.body.length <= 0; }
javascript
{ "resource": "" }
q28999
getParent
train
function getParent(node, predicate) { let currentNode = node; while (currentNode) { if (predicate(currentNode)) { return currentNode; } currentNode = currentNode.parent; } return null; }
javascript
{ "resource": "" }