_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q39900
getTopImages
train
function getTopImages(params, config, conn) { // defaults config = config || require('../config/config.js') var limit = 10 if (!isNaN(params.limit)) { limit = params.limit } // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } var sql if (params.reviewer) { sql = 'SELECT * from Rating where reviewer = :reviewer order by rating DESC LIMIT :limit ' } else { sql = 'SELECT uri, avg(rating) rating from Rating group by uri order by rating DESC LIMIT :limit ' } conn.query(sql, { replacements: { "reviewer" : params.reviewer, "limit" : params.limit } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
javascript
{ "resource": "" }
q39901
getTags
train
function getTags(params, config, conn) { // defaults config = config || require('../config/config.js') params.limit = 100 // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } if (params.uri) { var sql = 'SELECT t.tag from Media m left join MediaTag mt on m.id = mt.media_id left join Tag t on mt.tag_id = t.id where m.uri = :uri order by t.tag LIMIT :limit ' } else { var sql = 'SELECT * from Tag order by id LIMIT :limit ' } debug(sql) conn.query(sql, { replacements: { "limit" : params.limit, "uri" : params.uri } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
javascript
{ "resource": "" }
q39902
getRandomUnseenImage
train
function getRandomUnseenImage(params, config, conn) { // defaults config = config || require('../config/config.js') params = params || {} var max = config.db.max || 0 var optimization = config.optimization || 0 var offset = Math.floor(Math.random() * max) params.optimization = optimization params.offset = offset // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } var safeClause = '' if (params.safe !== undefined && params.safe !== null) { if (parseInt(params.safe) === 0) { safeClause = '' } else { safeClause = ' and a.safe = :safe ' } } else { safeClause = ' and a.safe = 1 ' } if (params.reviewer) { var sql = "SELECT * from Media m where m.uri not in (select r.uri from Rating r join User u on u.id = r.reviewer_id) and contentType = 'image' and lastSeen is NULL " + safeClause + " and FLOOR( m.id / :optimization ) = FLOOR( RAND() * :optimization ) and m.id >= :offset LIMIT 1;" } else { var sql = "SELECT * from Media m where contentType = 'image' and lastSeen is NULL order by RAND() LIMIT 1;" } debug('getRandomUnseenImage', sql, params) conn.query(sql, { replacements: { "optimization" : params.optimization, "offset" : params.offset } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
javascript
{ "resource": "" }
q39903
getLastSeen
train
function getLastSeen(params, config, conn) { // defaults config = config || require('../config/config.js') params = params || {} params.webid = params.webid || 'http://melvincarvalho.com/#me' // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } var sql = "select f.* from Fragment f join User u on f.user_id = u.id where u.uri = :webid order by lastSeen desc LIMIT 1;" var fragLastSeen var mediaLastSeen var val debug('getLastSeen', sql, params) conn.query(sql, { replacements: { "webid" : params.webid } }).then(function(frag){ var sql = "select r.* from Rating r join User u on u.id = r.reviewer_id and u.uri = :webid order by datePublished desc LIMIT 1;" debug('getLastSeen', sql, params) debug(frag) val = frag fragLastSeen = frag[0][0].lastSeen debug(fragLastSeen) return conn.query(sql, { replacements: { "webid" : params.webid } }) }).then(function(media) { debug(media) mediaLastSeen = media[0][0].datePublished debug(mediaLastSeen) if (mediaLastSeen > fragLastSeen) { debug('media is latest : ' + media.lastSeen) return resolve({"ret" : media, "conn" : conn}) } else { debug('frag is latest : ' + media.lastSeen) return resolve({"ret" : val, "conn" : conn}) } }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
javascript
{ "resource": "" }
q39904
astroViewer
train
function astroViewer (options, cb) { request({ url: 'http://astroviewer-sat2c.appspot.com/predictor', qs: { var: 'passesData', lat: options.lat, lon: options.lon, name: options.name }, headers: { 'User-Agent': 'request' } }, function (error, response, body) { if (error) { cb(error) } // Trim the javascript response var raw = body.slice(17).slice(0, -2) // make sure the keys have quotes around them raw = raw.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2":') // turn the result into valid JSON (hopefully) var info = JSON.parse(raw) cb(false, info) }) }
javascript
{ "resource": "" }
q39905
listPasses
train
function listPasses (data, cb) { var index = 0 var passes = data.passes var newpasses = '' if (passes.length === 0) { newpasses += ':( No results found for **' + data.location.name + '**' } else { passes.map(function (obj) { if (index === 0) { newpasses += '**' + data.location.name + '** (' + obj.timezone + ')\n' } var dateFormat = 'YYYYMMDDHHmmss' var newDateFormat = 'ddd MMM Do, hh:mma' var begin = moment(obj.begin, dateFormat).format(newDateFormat) var duration = moment.utc(moment(obj.end, dateFormat).diff(moment(obj.begin, dateFormat))).format('m\\m s\\s') newpasses += begin + ' (' + duration + ')\n' index++ }) } newpasses += ':satellite:' cb(false, newpasses) }
javascript
{ "resource": "" }
q39906
closeConnection
train
function closeConnection(errMsg) { if (ftp) { ftp.raw.quit(function(err, res) { if (err) { grunt.log.error(err); done(false); } ftp.destroy(); grunt.log.ok("FTP connection closed!"); done(); }); } else if (errMsg) { grunt.log.warn(errMsg); done(false); } else { done(); } }
javascript
{ "resource": "" }
q39907
getNextClar
train
function getNextClar(params, string, files) { if (params === 'all') { files.push(string); return true; } if (Array.isArray(params)){ params.forEach(function(item, i, array) { files.push(string + '.' + item + '$'); return true; }); }else if (typeof params === 'object'){ var param; for (param in params) { var buffer = string; var regular; if (param === 'all'){ regular = '\\w+'; }else{ regular = param; } string += !string ? regular : '-' + regular; getNextClar(params[param], string, files); string = buffer; } }else{ files.push(string + '.' + params + '$'); } return true; }
javascript
{ "resource": "" }
q39908
createDownloadList
train
function createDownloadList() { uploadFiles = []; files.forEach(function(item, i, arr) { var preg = new RegExp(item); var check = false; serverFonts.forEach(function(item, i, arr) { if (preg.test(item)) { uploadFiles.push(item); check = true; // serverFonts.remove(item); } }); if (!check){ grunt.log.warn('You have no suitable fonts at pattern ' + item); } }); downloadFiles(); }
javascript
{ "resource": "" }
q39909
removeFonts
train
function removeFonts(files){ var dest = normalizeDir(options.dest); files.forEach(function(item, i, arr){ grunt.file.delete(dest + item); grunt.log.warn('File ' + item + ' remove.'); }); }
javascript
{ "resource": "" }
q39910
getFilesList
train
function getFilesList(pattern) { //If pattern empty return all avaliable fonts if (pattern === undefined || pattern === '') { formatingFontsArray(serverFonts); closeConnection(); return; // We are completed, close connection and end the program } var serverFiles = [], preg = new RegExp('[\\w\\-\\.]*' + pattern + '[\\w\\-\\.]*'); function regular() { if (serverFonts.length < 1) { if (serverFiles.length !== 0){ formatingFontsArray(serverFiles); }else{ grunt.log.warn('We haven\'t any suitable fonts'); } closeConnection(); return; // We are completed, close connection and end the program } var file = serverFonts.pop(); if (preg.test(file)) { serverFiles.push(file); } regular(); } regular(); }
javascript
{ "resource": "" }
q39911
formatingFontsArray
train
function formatingFontsArray(array) { var fileContent = '', file = [], buffer = array[0].split('.')[0], exp = []; function writeResult() { var str = buffer + ' [' + exp.join(', ') + ']'; fileContent += str + '\n'; grunt.log.ok(str); } array.forEach(function(item, i, arr) { file = item.split('.'); if (buffer === file[0]) { exp.push(file[1]); } else { writeResult(); buffer = file[0]; exp = []; exp.push(file[1]); } }); writeResult(); //Put last search result into file grunt.file.mkdir(options.dest); grunt.file.write(normalizeDir(options.dest) + '.fonts', fileContent); }
javascript
{ "resource": "" }
q39912
sourceReplacer
train
function sourceReplacer(source, replacements) { // shared var getBefore = getField('before'); var getAfter = getField('after'); // split source code into lines, include the delimiter var lines = source.split(/(\r?\n)/g); // split each line further by the replacements for (var i = 0; i < lines.length; i += 2) { var split = lines[i] = [].concat(lines[i]); // initialise each line text into an array for (var before in replacements) { var after = replacements[before]; split.forEach(splitByReplacement(before, after)); } } // utility methods return { toStringBefore: toStringBefore, toStringAfter : toStringAfter, getColumnAfter: getColumnAfter }; /** * String representation of text before replacement * @returns {string} */ function toStringBefore() { return lines.map(getBefore).join(''); } /** * String representation of text after replacement * @returns {string} */ function toStringAfter() { return lines.map(getAfter).join(''); } /** * Get a column position delta as at the given line and column that has occured as a result of replacement. * @param {number} lineIndex The line in the original source at which to evaluate the offset * @param {number} columnIndex The column in the original source at which to evaluate the offset * @returns {number} A column offset in characters */ function getColumnAfter(lineIndex, columnIndex) { if (lineIndex in lines) { var line = lines[lineIndex]; var count = 0; var offset = 0; for (var i = 0; i < line.length; i++) { var widthBefore = getBefore(line[i]).length; var widthAfter = getAfter(line[i]).length; var nextCount = count + widthBefore; if (nextCount > columnIndex) { break; } else { count = nextCount; offset += widthAfter - widthBefore; } } return columnIndex + offset; } else { throw new Error('Line index is out of range'); } } }
javascript
{ "resource": "" }
q39913
getColumnAfter
train
function getColumnAfter(lineIndex, columnIndex) { if (lineIndex in lines) { var line = lines[lineIndex]; var count = 0; var offset = 0; for (var i = 0; i < line.length; i++) { var widthBefore = getBefore(line[i]).length; var widthAfter = getAfter(line[i]).length; var nextCount = count + widthBefore; if (nextCount > columnIndex) { break; } else { count = nextCount; offset += widthAfter - widthBefore; } } return columnIndex + offset; } else { throw new Error('Line index is out of range'); } }
javascript
{ "resource": "" }
q39914
train
function(args) { if (!args) { return []; } if (args[0] instanceof Array) { return args[0]; } return Array.prototype.slice.call(args, 0); }
javascript
{ "resource": "" }
q39915
Reporter
train
function Reporter (opts) { this.events = opts.events; this.config = opts.config; this.data = {}; this.actionQueue = []; this.data.tests = []; this.browser = null; var defaultReportFolder = 'report'; this.dest = this.config.get('json-reporter') && this.config.get('json-reporter').dest ? this.config.get('json-reporter').dest : defaultReportFolder; this.startListening(); }
javascript
{ "resource": "" }
q39916
train
function (data) { this.data.tests.push({ id: data.id, name: data.name, browser: this.browser, status: data.status, passedAssertions: data.passedAssertions, failedAssertions: data.failedAssertions, actions: this.actionQueue }); return this; }
javascript
{ "resource": "" }
q39917
train
function (data) { this.data.elapsedTime = data.elapsedTime; this.data.status = data.status; this.data.assertions = data.assertions; this.data.assertionsFailed = data.assertionsFailed; this.data.assertionsPassed = data.assertionsPassed; var contents = JSON.stringify(this.data, false, 4); if (path.extname(this.dest) !== '.json') { this.dest = this.dest + '/dalek.json'; } this.events.emit('report:written', {type: 'json', dest: this.dest}); this._recursiveMakeDirSync(path.dirname(this.dest.replace(path.basename(this.dest, '')))); fs.writeFileSync(this.dest, contents, 'utf8'); return this; }
javascript
{ "resource": "" }
q39918
cloneArray
train
function cloneArray(a) { var b = [], i = a.length while (i--) b[ i ] = a[ i ] return b }
javascript
{ "resource": "" }
q39919
installPlugin
train
function installPlugin(nameOrPlugin, options) { assert(nameOrPlugin, 'name or plugin is required') var plugin, ctor, self = this, parent = module.parent if (typeof nameOrPlugin === 'string') try { // local plugin if (nameOrPlugin.substring(0, 2) === './') ctor = parent.require(nameOrPlugin) // installed plugin with prefixed name 'hand-over-' else ctor = parent.require('hand-over-' + nameOrPlugin) } catch (ex) { // installed plugin without prefix ctor = parent.require(nameOrPlugin) } else ctor = nameOrPlugin // maybe we've got an already instantiated plugin if (ctor instanceof Plugin) plugin = ctor else { assert.equal(typeof ctor, 'function', 'plugin must provide a constructor') plugin = new ctor(options || {}) assert(plugin instanceof Plugin, 'plugin must be a descendant of Handover.Plugin') } assert(plugin.name, 'plugin must expose a channel name') assert(!(plugin.name in this._plugins), 'plugin is already installed') assert.equal(typeof plugin.send, 'function', "'" + plugin.name + '" does not implements `send()`') assert(plugin.send.length >= 3, "'" + plugin.name + "' plugin's `send()` method must take at least three arguments") assert.equal(typeof plugin.destroy, 'function', "'" + plugin.name + '" does not implements `destroy()`') this._plugins[ plugin.name ] = plugin // delegate plugin errors for convenience plugin.on('error', function (err) { // decorate error object with channel name if (err && typeof err === 'object') err.channel = plugin.name self.emit('error', err) }) // make it chainable return this }
javascript
{ "resource": "" }
q39920
failed
train
function failed(err, userId, channel, target) { if (err && typeof err === 'object') { err.userId = userId err.channel = channel err.target = target } errors.push(err) done() }
javascript
{ "resource": "" }
q39921
done
train
function done() { var arg = errors.length ? errors : null --pending || process.nextTick(callback, arg) }
javascript
{ "resource": "" }
q39922
registerTarget
train
function registerTarget(userId, channel, target, callback) { this.save(userId, channel, target, function (err) { // ensure that we're firing the callback asynchronously process.nextTick(callback, err) }) // make it chainable return this }
javascript
{ "resource": "" }
q39923
unregisterTargets
train
function unregisterTargets(userId, channel, targets, callback) { var self = this // no target list specified, so we need to load all the targets // of the supplied channel if (arguments.length < 4) { // probably we've got the callback as the third arg callback = targets this.load(userId, channel, function (err, targets) { // cannot load targets of the given channel // call back with the error if (err) { if (typeof err === 'object') { err.userId = userId err.channel = channel } process.nextTick(callback, [ err ]) } // we've got that list! else { // ...or maybe that's not really a list? if (!Array.isArray(targets)) targets = [ targets ] removeTargets(self, userId, channel, targets, callback) } }) } // we've got an explicit target list, go remove them else { // ...or maybe that's not really a list? if (!Array.isArray(targets)) targets = [ targets ] removeTargets(self, userId, channel, targets, callback) } // make it chainable return this }
javascript
{ "resource": "" }
q39924
removeTargets
train
function removeTargets(self, userId, channel, targets, callback) { // dereference the original array, // because that may not be trustworthy targets = cloneArray(targets) var pending = targets.length, errors = [] if (pending) targets.forEach(function (target) { self.remove(userId, channel, target, function (err) { // something went wrong if (err) { // decorate errors with debug info if (typeof err === 'object') { err.userId = userId err.channel = channel err.target = target } // collect errors to pass back later to the caller errors.push(err) } // count pending operations and then pass back the control to the caller --pending || process.nextTick(callback, errors.length ? errors : null) }) }) else { // no targets found, so // there is nothing to do here process.nextTick(callback, null) } }
javascript
{ "resource": "" }
q39925
unreference
train
function unreference() { var plugins = this._plugins Object.keys(plugins).forEach(function (name) { var plugin = plugins[ name ] // `unref()` is preferred if (typeof plugin.unref === 'function') plugin.unref() // if we cannot stop gracefully then destroy open // connections immediately else { // `destroy()` is required by `Plugin` base class, // so it's guaranteed that it exists plugin.destroy() } }) // make it chainable return this }
javascript
{ "resource": "" }
q39926
train
function (path, callback) { fs.stat(path, function (err, stats) { failOn(err, "Error while reading the resolver path:", err); if (stats.isFile()) { TomahawkJS.loadAxe(path, _.partial(statResolver, callback)); } else if (stats.isDirectory()) { // Load the resolver from a directory. TomahawkJS.loadDirectory(path, _.partial(startResolver, callback)); } else { // Will be interesting what kind of fs type people will access here console.error("Unsupported FS item for a resolver bundle."); process.exit(1); } }); }
javascript
{ "resource": "" }
q39927
concat
train
function concat (target, data) { target = target || [] if(Object.prototype.toString.call(data)!=='[object Array]') { data = [data] } Array.prototype.push.apply(target, data) return target }
javascript
{ "resource": "" }
q39928
train
function(doc, nodes, selector, after) { var parent = module.exports.resolveParent(doc, selector); if (!parent) { //Try to create the parent recursively if necessary try { var parentToCreate = et.XML('<' + path.basename(selector) + '>'), parentSelector = path.dirname(selector); this.graftXML(doc, [parentToCreate], parentSelector); } catch (e) { return false; } parent = module.exports.resolveParent(doc, selector); if (!parent) return false; } nodes.forEach(function (node) { // check if child is unique first if (uniqueChild(node, parent)) { var children = parent.getchildren(); var insertIdx = after ? findInsertIdx(children, after) : children.length; //TODO: replace with parent.insert after the bug in ElementTree is fixed parent.getchildren().splice(insertIdx, 0, node); } }); return true; }
javascript
{ "resource": "" }
q39929
train
function(doc, nodes, selector) { var parent = module.exports.resolveParent(doc, selector); if (!parent) return false; nodes.forEach(function (node) { var matchingKid = null; if ((matchingKid = findChild(node, parent)) !== null) { // stupid elementtree takes an index argument it doesn't use // and does not conform to the python lib parent.remove(matchingKid); } }); return true; }
javascript
{ "resource": "" }
q39930
train
function(doc, selector, xml) { var target = module.exports.resolveParent(doc, selector); if (!target) return false; if (xml.oldAttrib) { target.attrib = _.extend({}, xml.oldAttrib); } return true; }
javascript
{ "resource": "" }
q39931
findInsertIdx
train
function findInsertIdx(children, after) { var childrenTags = children.map(function(child) { return child.tag; }); var afters = after.split(';'); var afterIndexes = afters.map(function(current) { return childrenTags.lastIndexOf(current); }); var foundIndex = _.find(afterIndexes, function(index) { return index != -1; }); //add to the beginning if no matching nodes are found return typeof foundIndex === 'undefined' ? 0 : foundIndex+1; }
javascript
{ "resource": "" }
q39932
attachToScope
train
function attachToScope(model, itemsToAttach) { var me = this; _.each(itemsToAttach, function (item) { if (me.pancakes.exists(item, null)) { model[item] = me.pancakes.cook(item, null); } }); }
javascript
{ "resource": "" }
q39933
getAppFileNames
train
function getAppFileNames(appName, dir) { var partialsDir = this.pancakes.getRootDir() + delim + 'app' + delim + appName + delim + dir; return fs.existsSync(partialsDir) ? fs.readdirSync(partialsDir) : []; }
javascript
{ "resource": "" }
q39934
dotToCamelCase
train
function dotToCamelCase(name) { if (!name) { return name; } if (name.substring(name.length - 3) === '.js') { name = name.substring(0, name.length - 3); } name = name.toLowerCase(); var parts = name.split('.'); name = parts[0]; for (var i = 1; i < parts.length; i++) { name += parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1); } return name; }
javascript
{ "resource": "" }
q39935
registerJytPlugins
train
function registerJytPlugins() { var rootDir = this.pancakes.getRootDir(); var pluginDir = path.normalize(rootDir + '/app/common/jyt.plugins'); var me = this; // if plugin dir doesn't exist, just return if (!fs.existsSync(pluginDir)) { return; } // else get all plugin files from the jyt.plugins dir var pluginFiles = fs.readdirSync(pluginDir); var deps = { dependencies: me.getJangularDeps() }; _.each(pluginFiles, function (pluginFile) { var name = me.dotToCamelCase(pluginFile); var pluginFlapjack = me.pancakes.requireModule(pluginDir + delim + pluginFile); var plugin = me.pancakes.cook(pluginFlapjack, deps); jangular.registerPlugin(name, plugin); me.jangularDeps[name] = plugin; }); }
javascript
{ "resource": "" }
q39936
isMobileApp
train
function isMobileApp() { var isMobile = false; var appConfigs = this.pancakes.cook('appConfigs', null); _.each(appConfigs, function (appConfig) { if (appConfig.isMobile) { isMobile = true; } }); return isMobile; }
javascript
{ "resource": "" }
q39937
doesFileExist
train
function doesFileExist(filePath) { if (!fileExistsCache.hasOwnProperty(filePath)) { fileExistsCache[filePath] = fs.existsSync(filePath); } return fileExistsCache[filePath]; }
javascript
{ "resource": "" }
q39938
isCyclic
train
function isCyclic(obj) { let seenObjects = []; const detect = obj => { if (obj && typeof obj === "object") { if (seenObjects.includes(obj)) { return true; } seenObjects.push(obj); for (const key in obj) { if (obj.hasOwnProperty(key) && detect(obj[key])) { return true; } } } return false; }; return detect(obj); }
javascript
{ "resource": "" }
q39939
train
function (req, res, next) { if (options.forceAuthorize) { return next(); } var userId = req.oauth2.user.id; var clientId = req.oauth2.client.id; var scope = req.oauth2.req.scope; models.Permissions.isAuthorized(clientId, userId, scope, function (err, authorized) { if (err) { return next(err); } else if (authorized) { req.oauth2.res = {}; req.oauth2.res.allow = true; server._respond(req.oauth2, res, function (err) { if (err) { return next(err); } return next(new AuthorizationError('Unsupported response type: ' + req.oauth2.req.type, 'unsupported_response_type')); }); } else { next(); } }); }
javascript
{ "resource": "" }
q39940
train
function (req, res, next) { if (options.decisionPage) { var urlObj = { pathname: options.decisionPage, query: { transactionId: req.oauth2.transactionID, userId: req.oauth2.user.id, clientId: req.oauth2.client.id, scope: req.oauth2.req.scope, redirectURI: req.oauth2.redirectURI } }; return res.redirect(url.format(urlObj)); } res.render(options.decisionView || 'dialog', { transactionId: req.oauth2.transactionID, user: req.user, client: req.oauth2.client, scopes: req.oauth2.req.scope, redirectURI: req.oauth2.redirectURI }); }
javascript
{ "resource": "" }
q39941
clientLogin
train
function clientLogin(clientId, clientSecret, done) { debug('clientLogin: %s', clientId); clientId = parseInt(clientId); if (!clientId && clientId !== 0) { return done(null, false); } models.Clients.findByClientId(clientId, function (err, client) { if (err) { return done(err); } if (!client) { return done(null, false); } var secret = client.clientSecret || client.restApiKey; if (secret !== clientSecret) { return done(null, false); } return done(null, client); }); }
javascript
{ "resource": "" }
q39942
train
function (namespaces) { _.forEach(namespaces, function (level, namespace) { cache.add(namespace, level); }); return this; }
javascript
{ "resource": "" }
q39943
train
function(level, title, format, filters, needstack, args) { var msg = utils.format.apply(this, args) var data = { timestamp : dateFormat(new Date(), _config.dateformat), message : msg, title : title, level : level, args : args } data.method = data.path = data.line = data.pos = data.file = '' if (needstack) { // get call stack, and analyze it // get all file,method and line number data.stack = (new Error()).stack.split('\n').slice(3) // Stack trace format : // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi var s = data.stack[0], sp = /at\s+(.*)\s+\((.*):(\d*):(\d*)\)/gi .exec(s) || /at\s+()(.*):(\d*):(\d*)/gi.exec(s) if (sp && sp.length === 5) { data.method = sp[1] data.path = sp[2] data.line = sp[3] data.pos = sp[4] var paths = data.path.split('/') data.file = paths[paths.length - 1] } } _config.preprocess(data) // call micro-template to ouput data.output = tinytim.tim(format, data) // process every filter method var len = filters.length for ( var i = 0; i < len; i += 1) { data.output = filters[i](data.output, data) if (!data.output) return data // cancel next process if return a false(include null, undefined) } // trans the final result return _config.transport(data) }
javascript
{ "resource": "" }
q39944
withFilePath
train
function withFilePath (file, msg) { if (file && file.path) { msg += `\n ${file.path}`; } return msg; }
javascript
{ "resource": "" }
q39945
_createRequestParams
train
function _createRequestParams(params){ var resourcePath = params.resourcePath; resourcePath = resourcePath.replace(":domain", params.domain) .replace(":projectid", params.projectid) .replace(":guid", params.appid); log.logger.debug("Creating Request Params For Core ", params); var coreHost = params.appMbaasModel.coreHost; if(coreHost.indexOf("http") !== 0){ // We do not know protocol so using https as default one. coreHost = "https://" + coreHost; } return { url: url.format(coreHost + resourcePath), method: params.method, headers: { 'x-fh-auth-app' : params.apiKey }, json: true, body: params.data || {} }; }
javascript
{ "resource": "" }
q39946
_createResponseHandler
train
function _createResponseHandler(req, next, skipDataResult){ return function(err, httpResponse, responseBody){ log.logger.debug("Performing Core Action ", req.url, err, httpResponse.statusCode, responseBody); if(err || (httpResponse.statusCode !== 200 && httpResponse.statusCode !== 204)){ return next(err || responseBody); } //Not interested in the response from the core. if(!skipDataResult){ req.appformsResultPayload = { data: responseBody || [] }; } next(); }; }
javascript
{ "resource": "" }
q39947
checkFormAssociation
train
function checkFormAssociation(req, res, next){ var requestedFormId = req.params.id; req.appformsResultPayload = req.appformsResultPayload || {}; var formsAssociatedWithProject = req.appformsResultPayload.data || []; var foundForm = _.find(formsAssociatedWithProject, function(formId){ return requestedFormId === formId; }); //Form Associated, can get the form if(foundForm){ return next(); } else{ return next(new Error("Invalid Form Request. Form Not Associated With The Project")); } }
javascript
{ "resource": "" }
q39948
notifySubmissionComplete
train
function notifySubmissionComplete(req, res, next){ req.appformsResultPayload = req.appformsResultPayload || {}; var completeStatus = req.appformsResultPayload.data; var submission = completeStatus.formSubmission; //The Submission Is Not Complete, No need to send a notification. if("complete" !== completeStatus.status){ return next(); } var resourcePath = "/api/v2/appforms/domain/:domain/projects/:projectid/apps/:guid/forms/" + submission.formId + "/submissions/" + req.params.id + "/complete"; var params = _createRequestParams(_.extend({ resourcePath: resourcePath, method: "POST", apiKey: req.get('x-fh-auth-app'), appMbaasModel: req.appMbaasModel, data: completeStatus }, req.params)); log.logger.debug("notifySubmissionComplete ", {params: params}); request(params, _createResponseHandler(req, next, true)); }
javascript
{ "resource": "" }
q39949
replaceMacro
train
function replaceMacro(code) { if (!re) return getKeys(code); var match = code.match(re); if (!match) return getKeys(code); var includeFile = match[1]; includeFile = path.relative(self.config.root, path.join(path.dirname(fileName), includeFile)); self._parse(includeFile, function (err, includeCode) { if (err) return callback(err); includeCode = '\n\r-- ' + macro + ' ' + match[1] + ':\n' + includeCode + '\n\r-- End of ' + match[1]; code = code.replace(match[0], includeCode); replaceMacro(code); }); }
javascript
{ "resource": "" }
q39950
done
train
function done(code) { // calculate shasum and cache info var shasum = crypto.createHash('sha1'); shasum.update(code); self._shasums[scriptName] = shasum.digest('hex'); self._scripts[scriptName] = code; self._files[fileName] = code; // make dublicate entries for both script and script.lua if (path.extname(scriptName) === ext) { var alt = scriptName.substr(0, scriptName.length - ext.length); self._shasums[alt] = self._shasums[scriptName] self._scripts[alt] = self._scripts[scriptName] self._keys[alt] = self._keys[scriptName] } delete self._resolving[fileName]; callback(null, code); }
javascript
{ "resource": "" }
q39951
exec
train
function exec(cmd, args, options) { // If true user wants stdout to output value // instead of using inherit outputting // to process.stdout stream. if (options === true) options = { stdio: 'pipe' }; options = chek_1.extend({}, spawnDefaults, options); if (chek_1.isString(args)) args = argv_1.splitArgs(args); // Ensure command and arguments. if (!cmd) logger_1.log.error('Cannot execute process with command of undefined.'); args = args.map(function (s) { if (/\s/g.test(s)) return '"' + s + '"'; return s; }); // Spawn child. var child = child_process_1.spawnSync(cmd, args, options); if (child.stdout) return child.stdout.toString(); }
javascript
{ "resource": "" }
q39952
processArguments
train
function processArguments(props, args, defaults) { debug('processArguments',props,args,defaults); values = Object.assign({}, defaults); let properties = Object.getOwnPropertyNames(values); // First execute any single-arg functions to create dynamic defaults for (property of properties) { let value = values[property]; if (typeof value === 'function' && value.length === 0) values[property] = value(); } // Then expand a single argument that is an object into a set of values if (args.length === 1 && typeof args[0] === 'object') { Object.assign(values, args[0]); } else { // Or assign arguments to properties in order for (i = 0; i < Math.min(args.length, props.length); i++) values[props[i]] = args[i]; } debug('processArguments returns',values); return values; }
javascript
{ "resource": "" }
q39953
create
train
function create(defaults) { let props = Object.getOwnPropertyNames(defaults); /** Immutable class created from defaults. * */ const immutableClass = class { /** Constructor. * * Can take a single object argument, in which case the properties of the object are copied over into * any matching default propertis that were defined in 'create'. Can also take normal arguments, in which * case the arguments are matched to the default properties in the order in which they were originally * defined in the defaults object. */ constructor() { debug('constructor', props, defaults, arguments); values = processArguments(props,arguments,defaults); // Otherwise assign arguments to properties in order for (let prop of props) { let value = values[prop] Object.defineProperty(this, prop, { value, enumerable: true, writable: false }); } } /** Merge a set of properties with the immutable object, returning a new immutable object * * @param props Properties to merge. * @returns a new immutable object of the same type as 'this'. */ merge(props) { return new this.constructor(Object.assign({}, this, props)); } /** Get the immutable property names * * An immutable object may legitimately have transient proprerties that are not part of the public * interface of the object. We therefore create a getImmutablePropertyNames static method that gets * the list of immutable properties names that is defined for this class. */ static getImmutablePropertyNames() { return props; } /** Extends an immutable object, making a new immutable object. * * @param new_defaults additional properties for the extended object, plus default values for them. */ static extend(new_defaults) { return extend(immutableClass, new_defaults)} }; for (let prop of props) { let setterName = 'set' + prop.slice(0,1).toUpperCase() + prop.slice(1); immutableClass.prototype[setterName] = function(val) { debug(setterName, prop, val); return this.merge({ [prop] : val }); }; } return immutableClass; }
javascript
{ "resource": "" }
q39954
extend
train
function extend(to_extend, new_defaults = {}) { let new_default_props = Object.getOwnPropertyNames(new_defaults); let old_props = to_extend.getImmutablePropertyNames(); let new_props = new_default_props.filter(e => old_props.indexOf(e) < 0); //let overriden_props = new_default_props.filter(e => old_props.indexOf(e) >= 0); let props = old_props.concat(new_props); debug('merged props', props); /** Immutable class created from new_defaults and the extended class * */ let immutableClass = class extends to_extend { /** Constructor. * * Can take a single object argument, in which case the properties of the object are copied over into * any matching default propertis that were defined in 'create'. Can also take normal arguments, in which * case the arguments are matched to the default properties in the base class, and then to additional * properties defined in the new_defaults object . */ constructor() { // Handle case where we have one argument that's an object: assume it's properties to pass in let values = processArguments(props, arguments, new_defaults); // Handle values for base class super(values); // assign values to properties in order for (let prop of new_props) { let value = values[prop]; debug('value', value); Object.defineProperty(this, prop, { value, enumerable: true, writable: false }); } } /** Get the immutable property names * * An immutable object may legitimately have transient proprerties that are not part of the public * interface of the object. We therefore create a getImmutablePropertyNames static method that gets * the list of immutable properties names that is defined for this class. */ static getImmutablePropertyNames() { return props; } /** Extends an immutable object, making a new immutable object. * * @param new_defaults additional properties for the extended object, plus default values for them. */ static extend(new_defaults) { return extend(immutableClass, new_defaults)} }; for (let prop of new_props) { let setterName = 'set' + prop.slice(0,1).toUpperCase() + prop.slice(1); immutableClass.prototype[setterName] = function(val) { debug(setterName, prop, val); return this.merge({ [prop] : val }); }; } return immutableClass; }
javascript
{ "resource": "" }
q39955
withSharo
train
function withSharo(nextConfig = {}) { // https://github.com/zeit/next-plugins/issues/320 const withMdx = require('@zeit/next-mdx')({ // Allow regular markdown files (*.md) to be imported. extension: /\.mdx?$/ }) return ( withSass(withMdx( Object.assign( // ===================================================================== // Default configurations (can be overridden by nextConfig) // ===================================================================== { // Currently empty }, // ===================================================================== // Override default configurations with nextConfig // ===================================================================== nextConfig, // ===================================================================== // Override nextConfig configurations // (note to self: follow Next.js rules on this section) // ===================================================================== { webpack(config, options) { // Allow autoresolving of MDX (*.md, *.mdx) and SCSS (*.scss, *.sass) config.resolve.extensions.push('.md', '.mdx', '.scss', '.sass') if (typeof nextConfig.webpack === 'function') { return nextConfig.webpack(config, options) } return config } } ) )) ) }
javascript
{ "resource": "" }
q39956
insert
train
function insert(node, parent, tight) { var children = parent.children; var length = children.length; var last = children[length - 1]; var isLoose = false; var index; var item; if (node.depth === 1) { item = listItem(); item.children.push({ type: PARAGRAPH, children: [ { type: LINK, title: null, url: '#' + node.id, children: [ { type: TEXT, value: node.value } ] } ] }); children.push(item); } else if (last && last.type === LIST_ITEM) { insert(node, last, tight); } else if (last && last.type === LIST) { node.depth--; insert(node, last, tight); } else if (parent.type === LIST) { item = listItem(); insert(node, item, tight); children.push(item); } else { item = list(); node.depth--; insert(node, item, tight); children.push(item); } /* * Properly style list-items with new lines. */ parent.spread = !tight; if (parent.type === LIST && parent.spread) { parent.spread = false; index = -1; while (++index < length) { if (children[index].children.length > 1) { parent.spread = true; break; } } } // To do: remove `loose` in next major release. if (parent.type === LIST_ITEM) { parent.loose = tight ? false : children.length > 1; } else { if (tight) { isLoose = false; } else { index = -1; while (++index < length) { if (children[index].loose) { isLoose = true; break; } } } index = -1; while (++index < length) { children[index].loose = isLoose; } } }
javascript
{ "resource": "" }
q39957
GFSupload
train
function GFSupload(mongoinst, prefix) { this.mongo = mongoinst; this.db = this.mongo.db; this.Grid = this.mongo.Grid; this.GridStore = this.mongo.GridStore; this.ObjectID = this.mongo.ObjectID; this.prefix = prefix || this.GridStore.DEFAULT_ROOT_COLLECTION; return this; }
javascript
{ "resource": "" }
q39958
train
function (name, guild) { let emoji = guild.emojis.find('name', name); if (emoji === undefined || emoji === null) return name; return `<:${name}:${emoji.id}>`; }
javascript
{ "resource": "" }
q39959
train
function (name, guild) { return guild.members.filter((item) => item.user.username.toLowerCase() === this.name.toLowerCase()).join(); }
javascript
{ "resource": "" }
q39960
train
function (name, guild) { return guild.channels.filter((item) => item.type === "text").filter((item) => item.name === this.name).join(); }
javascript
{ "resource": "" }
q39961
validate
train
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); var withscores; if(args.length > 3) { withscores = ('' + args[3]).toLowerCase(); if(withscores !== Constants.ZSET.WITHSCORES) { throw CommandSyntax; } args[3] = withscores; } }
javascript
{ "resource": "" }
q39962
_printItem
train
function _printItem (item) { switch(item.type) { case 'option': console.log(item.index + ': ' + item.label); break; case 'break': for (var breakString = ''; breakString.length < item.charCount;) { breakString += item.character; } console.log(breakString); break; case 'text': console.log(item.text); break; default: console.error('Invalid item type: ' + item.type); process.exit(); } }
javascript
{ "resource": "" }
q39963
buildImages
train
function buildImages(conf, undertaker) { const imageMinConfig = { progressive: true, svgoPlugins: [{ removeViewBox: false }, { cleanupIDs: true }, { cleanupAttrs: true }] }; const imageSrc = path.join(conf.themeConfig.root, conf.themeConfig.images.src, '**', '*'); const imageDest = path.join(conf.themeConfig.root, conf.themeConfig.images.dest); return undertaker.src(imageSrc) .pipe(imagemin(imageMinConfig)) .pipe(undertaker.dest(imageDest)); }
javascript
{ "resource": "" }
q39964
render
train
function render(element, opts) { opts = opts || {}; var prepend = opts.prepend; var model = opts.model || {}; var indentLevel = opts.indentLevel || 0; var isPretty = opts.isPretty; var jtPrintIndent = isPretty ? '\t' : ''; var jtPrintNewline = isPretty ? '\n' : ''; var indent = '', i, len, prop; var p = []; // p is going to be our concatenator for the HTML string // if no element, then no HTML so return empty string if (!element) { return ''; } // if already a string, just return it if (utils.isString(element)) { return element; } // if an array, wrap it if (utils.isArray(element)) { element = naked(element, null); } // set the indentation level to the current indent if (isPretty && indentLevel) { for (i = 0; i < indentLevel; i++) { indent += jtPrintIndent; } } // if we are prepending some string, add it first if (prepend) { p.push(indent, prepend, jtPrintNewline); } // starting tag open if (element.tag) { p.push(indent, '<', element.tag); } // all tag attributes if (element.attributes) { for (prop in element.attributes) { if (element.attributes.hasOwnProperty(prop)) { if (element.attributes[prop] === null) { p.push(' ', prop); } else { p.push(' ', prop, '="', element.attributes[prop], '"'); } } } } // if no children or text, then close the tag if (element.tag && !element.children && (element.text === undefined || element.text === null)) { // for self closing we just close it, else we add the end tag if (selfClosing.indexOf(element.tag) > -1) { p.push('/>', jtPrintNewline); } else { p.push('></', element.tag, '>', jtPrintNewline); } } // else we need to add children or the inner text else { // if a tag (i.e. not just a string literal) put end bracket if (element.tag) { p.push('>'); } // if children, we will need to recurse if (element.children) { if (element.tag) { p.push(jtPrintNewline); } // recurse down for each child for (i = 0, len = element.children.length; i < len; ++i) { p.push(render(element.children[i], { indentLevel: element.tag ? indentLevel + 1 : indentLevel, isPretty: isPretty, model: model })); } if (element.tag) { p.push(indent); } } // if text, simply add it if (element.text !== null && element.text !== undefined) { p.push(element.text); } // finally if a tag, add close tag if (element.tag) { p.push('</', element.tag, '>', jtPrintNewline); } } return p.join(''); }
javascript
{ "resource": "" }
q39965
addElemsToScope
train
function addElemsToScope(scope) { var prop; for (prop in elems) { if (elems.hasOwnProperty(prop)) { scope[prop] = elems[prop]; } } scope.elem = elem; }
javascript
{ "resource": "" }
q39966
registerComponents
train
function registerComponents(elemNames) { if (!elemNames) { return; } var elemNameDashCase, elemNameCamelCase; for (var i = 0; i < elemNames.length; i++) { elemNameDashCase = elemNames[i]; elemNameCamelCase = utils.dashToCamelCase(elemNameDashCase); elems[elemNameCamelCase] = makeElem(elemNameDashCase); } }
javascript
{ "resource": "" }
q39967
init
train
function init() { var tagName; for (var i = 0; i < allTags.length; i++) { tagName = allTags[i]; elems[tagName] = makeElem(tagName); } }
javascript
{ "resource": "" }
q39968
getBundleMinIf
train
function getBundleMinIf(bundle, build, min) { // Disable minification? if (bundle.noMin) return false; // Glob filter paths to exlude and include files for minification. // Start by excluding absolute paths of pre-minified files. var minGlobs = lodash.map(min, function minAbsPath(relPath) { return build.notPath(path.resolve(relPath)); }); if (minGlobs.length === 0) { // Nothing to exclude, so include all files. return true; } // Append a catch-all inclusion after all exclusions. minGlobs.push('**/*'); return minGlobs; }
javascript
{ "resource": "" }
q39969
Sprite
train
function Sprite(texture) { Container.call(this); /** * The anchor sets the origin point of the texture. * The default is 0,0 this means the texture's origin is the top left * Setting the anchor to 0.5,0.5 means the texture's origin is centered * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner * * @member {Point} */ this.anchor = new math.Point(); /** * The texture that the sprite is using * * @member {Texture} * @private */ this._texture = null; /** * The width of the sprite (this is initially set by the texture) * * @member {number} * @private */ this._width = 0; /** * The height of the sprite (this is initially set by the texture) * * @member {number} * @private */ this._height = 0; /** * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. * * @member {number} * @default [0xFFFFFF] */ this.tint = 0xFFFFFF; /** * The blend mode to be applied to the sprite. Apply a value of blendModes.NORMAL to reset the blend mode. * * @member {number} * @default CONST.BLEND_MODES.NORMAL; */ this.blendMode = CONST.BLEND_MODES.NORMAL; /** * The shader that will be used to render the sprite. Set to null to remove a current shader. * * @member {AbstractFilter} */ this.shader = null; /** * An internal cached value of the tint. * * @member {number} * @default [0xFFFFFF] */ this.cachedTint = 0xFFFFFF; // call texture setter this.texture = texture || Texture.EMPTY; }
javascript
{ "resource": "" }
q39970
processSync
train
function processSync(filename, content, updater, format) { var text = String(content); // parse code to AST using esprima var ast = esprima.parse(text, { loc : true, comment: true, source : filename }); // sort nodes before changing the source-map var sorted = orderNodes(ast); // associate comments with nodes they annotate before changing the sort map associateComments(ast, sorted); // make sure the AST has the data from the original source map var converter = convert.fromSource(text); var originalMap = converter && converter.toObject(); var sourceContent = text; if (originalMap) { sourcemapToAst(ast, originalMap); sourceContent = originalMap.sourcesContent[0]; } // update the AST var updated = ((typeof updater === 'function') && updater(filename, ast)) || ast; // generate compressed code from the AST var pair = codegen.generate(updated, { sourceMap : true, sourceMapWithCode: true, format : format || {} }); // ensure that the source-map has sourcesContent or browserify will not work // source-map source files are posix so we have to slash them var posixPath = filename.replace(/\\/g, '/'); pair.map.setSourceContent(posixPath, sourceContent); // convert the map to base64 embedded comment var mapComment = convert.fromJSON(pair.map.toString()).toComment(); // complete return pair.code + mapComment; }
javascript
{ "resource": "" }
q39971
depthFirst
train
function depthFirst(node, parent) { var results = []; if (node && (typeof node === 'object')) { // valid node so push it to the list and set new parent // don't overwrite parent if one was not given if ('type' in node) { if (parent !== undefined) { node.parent = parent; } parent = node; results.push(node); } // recurse object members using nested function call for (var key in node) { if (WHITE_LIST.test(key)) { var value = node[key]; if (value && (typeof value === 'object')) { results.push.apply(results, depthFirst(value, parent)); } } } } return results; }
javascript
{ "resource": "" }
q39972
breadthFirst
train
function breadthFirst(node, parent) { var results = []; if (node && (typeof node === 'object')) { // begin the queue with the given node var queue = [{node:node, parent:parent}]; while (queue.length) { // pull the next item from the front of the queue var item = queue.shift(); node = item.node; parent = item.parent; // valid node so push it to the list and set new parent // don't overwrite parent if one was not given if ('type' in node) { if (parent !== undefined) { node.parent = parent; } parent = node; results.push(node); } // recurse object members using the queue for (var key in node) { if (WHITE_LIST.test(key)) { var value = node[key]; if (value && (typeof value === 'object')) { queue.push({ node : value, parent: parent }); } } } } } return results; }
javascript
{ "resource": "" }
q39973
nodeSplicer
train
function nodeSplicer(candidate, offset) { offset = offset || 0; return function setter(value) { var found = findReferrer(candidate); if (found) { var key = found.key; var obj = found.object; var array = Array.isArray(obj) && obj; if (!array) { obj[key] = value; } else if (typeof key !== 'number') { throw new Error('A numerical key is required to splice an array'); } else { if (typeof offset === 'function') { offset = offset(array, candidate, value); } var index = Math.max(0, Math.min(array.length, key + offset + Number(offset < 0))); var remove = Number(offset === 0); array.splice(index, remove, value); } } }; }
javascript
{ "resource": "" }
q39974
compareLocation
train
function compareLocation(nodeA, nodeB) { var locA = nodeA && nodeA.loc; var locB = nodeB && nodeB.loc; if (!locA && !locB) { return 0; } else if (Boolean(locA) !== Boolean(locB)) { return locA ? +1 : locB ? -1 : 0; } else { var result = isOrdered(locB.end, locA.start) ? +1 : isOrdered(locA.end, locB.start) ? -1 : // non-overlapping isOrdered(locB.start, locA.start) ? +1 : isOrdered(locA.start, locB.start) ? -1 : // overlapping isOrdered(locA.end, locB.end ) ? +1 : isOrdered(locB.end, locA.end ) ? -1 : // enclosed 0; return result; } }
javascript
{ "resource": "" }
q39975
isOrdered
train
function isOrdered(tupleA, tupleB) { return (tupleA.line < tupleB.line) || ((tupleA.line === tupleB.line) && (tupleA.column < tupleB.column)); }
javascript
{ "resource": "" }
q39976
compareIndex
train
function compareIndex(nodeA, nodeB) { var indexA = nodeA && nodeA.sortIndex; var indexB = nodeB && nodeB.sortIndex; if (!indexA && !indexB) { return 0; } else if (Boolean(indexA) !== Boolean(indexB)) { return indexA ? +1 : indexB ? -1 : 0; } else { return indexA - indexB; } }
javascript
{ "resource": "" }
q39977
findReferrer
train
function findReferrer(candidate, container) { var result; if (candidate) { // initially for the parent of the candidate node container = container || candidate.parent; // consider keys in the node until we have a result var keys = getKeys(container); for (var i = 0; !result && (i < keys.length); i++) { var key = keys[i]; if (WHITE_LIST.test(key)) { var value = container[key]; // found if (value === candidate) { result = { object: container, key : key }; } // recurse else if (value && (typeof value === 'object')) { result = findReferrer(candidate, value); } } } } // complete return result; }
javascript
{ "resource": "" }
q39978
getKeys
train
function getKeys(container) { function arrayIndex(value, i) { return i; } if (typeof container === 'object') { return Array.isArray(container) ? container.map(arrayIndex) : Object.keys(container); } else { return []; } }
javascript
{ "resource": "" }
q39979
tagResultFunction
train
function tagResultFunction(fn, tokenDescription, replacement) { const description = tag(fn); if (description) { tokenDescription = description.replace(tokenDescription, replacement); } tag(fn, tokenDescription); fn.toString = tokenToString; return fn; }
javascript
{ "resource": "" }
q39980
findRoot
train
function findRoot() { let rootPath; try { rootPath = glob.sync('../**/Drupal.php', {ignore: ['../vendor/**', '../node_modules/**']}); } catch (err) { throw new Error('No Drupal root found.'); } // If we found no results for Drupal.php..then bomb out. if (rootPath.length === 0) { throw new Error('No Drupal root found.'); } // Glob returns an array, even though we've only got one item. rootPath = rootPath[0]; const filePathParts = rootPath.split(path.sep); const coreDirPosition = filePathParts.indexOf('core'); // If we found a Drupal.php file, but no core directory..then bomb out. if (coreDirPosition === -1) { throw new Error('No Drupal root found.'); } return filePathParts.slice(0, coreDirPosition).join(path.sep); }
javascript
{ "resource": "" }
q39981
train
function(name) { var i; if (this.$editables.length) { //activate by name if (angular.isString(name)) { for(i=0; i<this.$editables.length; i++) { if (this.$editables[i].name === name) { this.$editables[i].activate(); return; } } } //try activate error field for(i=0; i<this.$editables.length; i++) { if (this.$editables[i].error) { this.$editables[i].activate(); return; } } //by default activate first field this.$editables[0].activate(); } }
javascript
{ "resource": "" }
q39982
getUserForToken
train
function getUserForToken(decodedToken) { var userId = decodedToken._id; var authToken = decodedToken.authToken; var cacheKey = userId + authToken; var conditions = { caller: userService.admin, where: { _id: userId, authToken: authToken, status: 'created' }, findOne: true }; var cachedUser; // if no user id or authToken, then no user if (!userId || !authToken) { return null; } // try to get user from cache, then DB return userCacheService.get({ key: cacheKey }) .then(function (user) { cachedUser = user; return user ? user : userService.find(conditions); }) .then(function (user) { // if user found in database, but not in cache, save in cache if (user && !cachedUser) { userCacheService.set({ key: cacheKey, value: user }); } // return the user return user; }); }
javascript
{ "resource": "" }
q39983
validateToken
train
function validateToken(req, reply) { var authorization = req.headers.authorization; if (!authorization) { return reply.continue(); } // this is hack fix so that localStorage and cookies can either have Bearer or not // if in local storate, it is serialized, so need to replace %20 with space // need to fix this in the future at the source (i.e. on the client side) authorization = authorization.replace('Bearer%20', 'Bearer '); if (!authorization.match(/^Bearer /)) { authorization = 'Bearer ' + authorization; } var parts = authorization.split(/\s+/); if (parts.length !== 2) { log.debug('Authorization header invalid: ' + authorization); return reply.continue(); } if (parts[0].toLowerCase() !== 'bearer') { log.debug('Authorization no bearer'); return reply.continue(); } if (parts[1].split('.').length !== 3) { log.debug('Authorization bearer value invalid'); return reply.continue(); } var token = parts[1]; return jwt.verify(token, privateKey) .then(function (decodedToken) { return getUserForToken(decodedToken); }) .then(function (user) { req.user = user; return reply.continue(); }) // if error continue on as anonymous .catch(function () { //log.debug('Problem verifying token: ' + token); return reply.continue(); }); }
javascript
{ "resource": "" }
q39984
init
train
function init(ctx) { var server = ctx.server; if (!privateKey) { throw new Error('Please set config.security.token.privateKey'); } server.ext('onPreAuth', validateToken); return new Q(ctx); }
javascript
{ "resource": "" }
q39985
execute
train
function execute(req, res) { req.conn.unwatch(req.db); res.send(null, Constants.OK); }
javascript
{ "resource": "" }
q39986
getLibStateAccessor
train
function getLibStateAccessor(libState) { /** The current state name */ return { get actionName() { return libState.actionName; } /** Is in idle state (no more states to progress to) */ , get isIdle() { return libState.isIdle; } /** State can be paused manually or via action dispatch or returning null/undefined from timeoutMS function */ , get isPaused() { return libState.isPaused; } /** The epoch MS that the user was last active */ , get lastActive() { return useFastStore ? fastState.lastActive : libState.lastActive; } /** Event information captured on the last recorded user action */ , get lastEvent() { return useFastStore ? fastState.lastEvent : libState.lastEvent; } /** The timeoutID for the current scheduled next event if it exists */ , get timeoutID() { return useFastStore ? fastState.timeoutID : libState.timeoutID; } }; }
javascript
{ "resource": "" }
q39987
_shouldActivityUpdate
train
function _shouldActivityUpdate(_ref5) { var type = _ref5.type; var pageX = _ref5.pageX; var pageY = _ref5.pageY; if (type !== 'mousemove') return true; var _stores$fast = stores.fast; var lastActive = _stores$fast.lastActive; var _stores$fast$lastEven = _stores$fast.lastEvent; var x = _stores$fast$lastEven.x; var y = _stores$fast$lastEven.y; if (typeof pageX === 'undefined' || typeof pageY === 'undefined') return false; if (Math.abs(pageX - x) < thresholds.mouse && Math.abs(pageY - y) < thresholds.mouse) return false; // SKIP UPDATE IF ITS UNDER THE THRESHOLD MS FROM THE LAST UPDATE var elapsedMS = +new Date() - lastActive; if (elapsedMS < thresholds.elapsedMS) return false; if (process.env.NODE_ENV !== 'production') log.trace('_shouldActivityUpdate: elapsed vs threshold => E[' + elapsedMS + '] >= T[' + thresholds.elapsedMS + '], lastActive => ' + lastActive); return true; }
javascript
{ "resource": "" }
q39988
onActivity
train
function onActivity(e) { if (!_shouldActivityUpdate(e)) return; if (_shouldRestart()) return dispatch(context.actions.start()); /** THIS WILL BE ROUTED TO FAST OR LOCAL STATE IF ENABLED */ setState(_constants.IDLEMONITOR_ACTIVITY, { lastActive: +new Date(), lastEvent: { x: e.pageX, y: e.pageY } }); }
javascript
{ "resource": "" }
q39989
schedule
train
function schedule(actionName) { timeout.clear(); var timeoutMS = timeout.timeoutMS(actionName); log.debug({ actionName: actionName, timeoutMS: timeoutMS }, 'schedule'); var args = { actionName: actionName, isPaused: _isPauseTriggered(timeoutMS) }; if (timeoutMS > 0) return setTimeout(function () { return execute(args); }, timeoutMS); execute(args); }
javascript
{ "resource": "" }
q39990
execute
train
function execute(_ref7) { var actionName = _ref7.actionName; var isPaused = _ref7.isPaused; var nextActionName = getNextActionName(actionName); var wasPaused = stores.redux.isPaused; /** TODO: CHECK LOCAL STATE HERE AND IF ITS BEEN ACTIVE, POSTPONE THE ACTION ABOUT TO BE EXECUTED */ /** SCHEDULE THE NEXT ACTION IF IT EXISTS */ var timeoutID = nextActionName && !isPaused ? schedule(nextActionName) : null; if (isPaused && !wasPaused) { log.info('pausing activity detection'); detection.stop(); } if (!isPaused && wasPaused) { log.info('unpausing activity detection'); detection.start(); } /** UPDATE THE STATE OF THE APP */ setState(actionName, { actionName: actionName, isIdle: typeof nextActionName === 'undefined', isPaused: isPaused, timeoutID: timeoutID }); /** EXECUTE THE USER DEFINED ACTION WITH REDUX THUNK ARGS + CONTEXT (LOG, START/STOP/RESET DISPATCHABLE ACTIONS) */ getAction(actionName)(dispatch, getState, _getChildContext(context)); }
javascript
{ "resource": "" }
q39991
train
function (e) { var elem = e.target; if (this.scrollIfAnchor(elem.getAttribute('href'), true)) { e.preventDefault(); } }
javascript
{ "resource": "" }
q39992
train
function(key, defaultValue){ var value = this.get(key, defaultValue); if($ExpressSESSION.session.store[key]){ delete $ExpressSESSION.session.store[key]; } return value; }
javascript
{ "resource": "" }
q39993
merge
train
function merge(target) { for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { sources[_key - 1] = arguments[_key]; } if (!sources.length) return target; var source = sources.shift(); if ((0, _isObject2.default)(target) && (0, _isObject2.default)(source)) { for (var key in source) { if ((0, _isObject2.default)(source[key])) { if (!target[key]) Object.assign(target, _defineProperty({}, key, {})); merge(target[key], source[key]); } else { Object.assign(target, _defineProperty({}, key, source[key])); } } } return merge.apply(undefined, [target].concat(sources)); }
javascript
{ "resource": "" }
q39994
readQueue
train
function readQueue() { disq.getJob({queue: queueName, count: self.jobCount, withcounters: self.withCounters}, function(err, jobs) { if(err) { self.emit('error', err); } else { jobs.forEach(function(job) { pendingMessages++; self.emit('job', job, function() { pendingMessages--; if(!self.paused && concurrencyPaused && pendingMessages < self.concurrency) { concurrencyPaused = false; setImmediate(readQueue); } }); }); if(!self.paused && pendingMessages<self.concurrency) { setImmediate(readQueue); } else { concurrencyPaused = true; } } }); }
javascript
{ "resource": "" }
q39995
dst
train
function dst(lat1, lon1, lat2, lon2) { // generally used geo measurement function var dLat = lat2 * Math.PI / 180 - lat1 * Math.PI / 180; var dLon = lon2 * Math.PI / 180 - lon1 * Math.PI / 180; var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return d * 1000; // meters }
javascript
{ "resource": "" }
q39996
renderLayout
train
function renderLayout(appName, layoutName, isAmp, dependencies) { var layout = this.pancakes.cook('app/' + appName + '/layouts/' + layoutName + '.layout'); var layoutView = this.pancakes.cook(layout.view, { dependencies: dependencies }); return jangular.render(layoutView, dependencies.model, { strip: false, isAmp: isAmp }); }
javascript
{ "resource": "" }
q39997
checkOnScopeChangeVals
train
function checkOnScopeChangeVals(partial, partialName) { var remodelOnScopeChange = partial.remodelOnScopeChange || (partial.remodel && partial.remodel.onScopeChange); var rerenderOnScopeChange = partial.rerenderOnScopeChange || (partial.rerender && partial.rerender.onScopeChange); var scope = partial.scope || {}; _.each(remodelOnScopeChange, function (scopeVal) { var idx = scopeVal.indexOf('.'); var val = idx > 0 ? scopeVal.substring(0, idx) : scopeVal; if (!scope[val]) { throw new Error(partialName + ' remodelOnScope value \'' + scopeVal + '\' is not defined in the scope definition.'); } }); _.each(rerenderOnScopeChange, function (scopeVal) { var idx = scopeVal.indexOf('.'); var val = idx > 0 ? scopeVal.substring(0, idx) : scopeVal; if (!scope[val]) { throw new Error(partialName + ' rerenderOnScopeChange value \'' + scopeVal + '\' is not defined in the scope definition.'); } }); }
javascript
{ "resource": "" }
q39998
getSubviews
train
function getSubviews(subviewFlapjacks) { var renderedSubviews = {}; var jangularDeps = this.getJangularDeps(); var me = this; _.each(subviewFlapjacks, function (subview, subviewName) { renderedSubviews[subviewName] = me.pancakes.cook(subview, { dependencies: jangularDeps }); }); return renderedSubviews; }
javascript
{ "resource": "" }
q39999
getPartialRenderFn
train
function getPartialRenderFn(partial, partialName) { var jangularDeps = this.getJangularDeps(); var me = this; return function renderPartial(model, elem, attrs) { me.isolateScope(model, partial.scope, attrs); // throw error if onScopeChange values not in the scope {} definition me.checkOnScopeChangeVals(partial, partialName); // set defaults before the modify model me.setDefaults(model, partial.defaults, partial.scope); // set the presets if they exist me.applyPresets(model, partial.defaults, partial.presets); // if model is injection function, just use that me.evalModel(model, partial.scope, partial.model, partialName); // this is similar to both jng.pages renderPage() // as well as ng.uipart.template (for client side pages and partials) me.attachToScope(model, partial.attachToScope); // generate the partial view var dependencies = _.extend({ subviews: me.getSubviews(partial.subviews) }, jangularDeps); return me.pancakes.cook(partial.view, { dependencies: dependencies }); }; }
javascript
{ "resource": "" }