_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q38400
checkID
train
function checkID(expectedIdAndVersion, pinfo) { if (!expectedIdAndVersion) return; var parsedSpec = pluginSpec.parse(expectedIdAndVersion); if (parsedSpec.id != pinfo.id) { var alias = parsedSpec.scope ? null : pluginMappernto[parsedSpec.id] || pluginMapperotn[parsedSpec.id]; if (alias !== p...
javascript
{ "resource": "" }
q38401
train
function() { return through.obj(function(file, encode, done){ addBefore(file.path); this.push(file); done(); }); }
javascript
{ "resource": "" }
q38402
train
function() { return through.obj(function(file, encode, done){ addAfter(file.path); this.push(file); done(); }); }
javascript
{ "resource": "" }
q38403
connect
train
function connect(uri, callback) { console.log('connecting to database (' + uri + ')'); mongo.MongoClient.connect(uri, {safe: true}, function (err, client) { if (err) return callback(err); db = client; db.addListener("error", function (error) { console.log("mongo client error: " + error); }); ...
javascript
{ "resource": "" }
q38404
findStoresInZip
train
function findStoresInZip(zip, callback) { var zip5 = typeof(zip) == 'string' ? parseInt(zip, 10) : zip; db.collection(stores, function(err, collection) { if (err) return callback(err); collection.find({zip5:zip5}).toArray(function(err, docs) { if (err) return callback(err); callback(null, docs...
javascript
{ "resource": "" }
q38405
ComponentHint
train
function ComponentHint(options) { // Make this an event emitter EventEmitter.call(this); // List of all components that have been checked, we keep this list so that the same components // are not checked twice. this.lintedComponents = []; // Object holding all external dependencies and their versions this.depe...
javascript
{ "resource": "" }
q38406
isScopeAllowed
train
function isScopeAllowed(allowedScopes, tokenScopes) { allowedScopes = normalizeScope(allowedScopes); tokenScopes = normalizeScope(tokenScopes); if (allowedScopes.length === 0) { return true; } for (var i = 0, n = allowedScopes.length; i < n; i++) { if (tokenScopes.indexOf(allowedScop...
javascript
{ "resource": "" }
q38407
isScopeAuthorized
train
function isScopeAuthorized(requestedScopes, authorizedScopes) { requestedScopes = normalizeScope(requestedScopes); authorizedScopes = normalizeScope(authorizedScopes); if (requestedScopes.length === 0) { return true; } for (var i = 0, n = requestedScopes.length; i < n; i++) { if (aut...
javascript
{ "resource": "" }
q38408
Behalter
train
function Behalter(parent, options) { // normalize arguments for the case of `new Behalter(options)` if (arguments.length === 1 && !(parent instanceof Behalter) && _.isPlainObject(parent)) { options = parent; parent = void 0; } // for hierarchical search, validate type of parent if (parent && !(paren...
javascript
{ "resource": "" }
q38409
reserved
train
function reserved(name) { if (!_.isString(name)) { return false; } return _.contains(RESERVED, name); }
javascript
{ "resource": "" }
q38410
annotate
train
function annotate(fn) { var matched = /function +[^\(]*\(([^\)]*)\).*/.exec(fn.toString()); var names = _.reject(matched[1].split(',') || [], _.isEmpty); return _.map(names, function(name) { return name.replace(/\s+/g, ''); }); }
javascript
{ "resource": "" }
q38411
ko
train
function ko(fn, isParamHandler) { // handlers and middlewares may have safeguard properties to be skipped if ('$$koified' in fn) { return fn; } let handler = function (req, res, next) { let argsLength = arguments.length; let args = new Array(argsLength); for (let i = 0; i < argsLength; i++) { ...
javascript
{ "resource": "" }
q38412
koifyHandler
train
function koifyHandler(fn, args, isErrHandler) { let fnResult; if (isGeneratorFunction(fn)) { fnResult = co(function* () { return yield* fn(...args); }); } else { fnResult = fn(...args); } if (!isPromise(fnResult)) { return fnResult; } let req, res, next; if (isErrHandler) { re...
javascript
{ "resource": "" }
q38413
koify
train
function koify() { let args = slice.call(arguments); let Router; let Route; if ((args.length === 1) && ('Router' in args[0]) && ('Route' in args[0])) { let express = args[0]; Router = express.Router; Route = express.Route; } else { Router = args[0]; Route = args[1]; } if (Router) ...
javascript
{ "resource": "" }
q38414
koifyRouter
train
function koifyRouter(Router) { // router factory function is the prototype let routerPrototype = Router; // original router methods let routerPrototype_ = {}; // router duck testing let routerMethods = Object.keys(routerPrototype).sort(); function isRouter(someRouter) { let someRouterPrototype = ...
javascript
{ "resource": "" }
q38415
koifyRoute
train
function koifyRoute(Route) { let routePrototype = Route.prototype; let routePrototype_ = {}; for (let method of [...methods, 'all']) { routePrototype_[method] = routePrototype[method]; routePrototype[method] = function () { let args = slice.call(arguments); for (let i = 0; i < args.length; i++) ...
javascript
{ "resource": "" }
q38416
matchesCriteria
train
function matchesCriteria(data, criteria) { data = data || {}; criteria = criteria || {}; var match = true; _.each(criteria, function (val, key) { var hasNotOperand = false; if (_.isObject(val) && val['$ne'] ) { hasNotOperand = true; ...
javascript
{ "resource": "" }
q38417
train
function (element, type, handler, context) { var own = this; //非Dom元素不处理 if (!(1 == element.nodeType || element.nodeType == 9 || element === window)|| !vQ.isFunction(handler)) { return; } //获取传入参数 var args = slice.call(arguments); ...
javascript
{ "resource": "" }
q38418
makeError
train
function makeError(e) { return { fatal: true, severity: 2, message: (e.message || '').split('\n', 1)[0], line: parser.line, column: parser.column }; }
javascript
{ "resource": "" }
q38419
train
function (eventNames) { var events = this._events; for (var i = 0; i < arguments.length; i++) { var eventName = arguments[i]; this._validateName(eventName); if (typeof events[eventName] === 'undefi...
javascript
{ "resource": "" }
q38420
train
function (eventName, fn) { if (typeof eventName === 'object') { if (eventName === null) { throw "IllegalArgumentException: eventName must be a String, or an Object."; } for (var name in eventName) { if (eventName...
javascript
{ "resource": "" }
q38421
train
function (eventName, fn) { if (typeof fn !== 'function') { throw "IllegalArgumentException: fn must be a Function."; } var fns = this._events[eventName]; if (fns instanceof Array) { var len = fns.length; ...
javascript
{ "resource": "" }
q38422
train
function (eventName) { var fns = this._events[eventName]; if (typeof fns === 'undefined') { throw "IllegalArgumentException: unsupported eventName (" + eventName + ")"; } if (fns.length > 0) { var args = []...
javascript
{ "resource": "" }
q38423
Bitmap
train
function Bitmap(width, height, bytesPerPixel, endianness) { if (!(this instanceof Bitmap)) { return new Bitmap(width, height, bytesPerPixel, endianness); } // Validate bytes per pixel if (bytesPerPixel === undefined) { bytesPerPixel = 1; } if (bytesPerPixel !== 1 && bytesPerPixel !== 2 && bytesPerP...
javascript
{ "resource": "" }
q38424
normalize
train
function normalize(repo) { const regex = /^((github|gitlab|bitbucket|oschina):)?((.+):)?([^/]+)\/([^#]+)(#(.+))?$/; const match = regex.exec(repo); const type = match[2] || 'github'; let host = match[4] || null; const owner = match[5]; const name = match[6]; const checkout = match[8] || 'master'; if (host === ...
javascript
{ "resource": "" }
q38425
getUrl
train
function getUrl(repo, clone) { let url; if (repo.type === 'github') { url = github(repo, clone); } else if (repo.type === 'gitlab') { url = gitlab(repo, clone); } else if (repo.type === 'bitbucket') { url = bitbucket(repo, clone); } else if (repo.type === 'oschina') { url = oschina(repo, clone); } else {...
javascript
{ "resource": "" }
q38426
github
train
function github(repo, clone) { let url; if (clone) url = 'git@' + repo.host + ':' + repo.owner + '/' + repo.name + '.git'; else url = addProtocol(repo.host) + '/' + repo.owner + '/' + repo.name + '/archive/' + repo.checkout + '.zip'; return url; }
javascript
{ "resource": "" }
q38427
oschina
train
function oschina(repo, clone) { let url; // oschina canceled download directly clone = true; if (clone) url = addProtocol(repo.host) + '/' + repo.owner + '/' + repo.name; // url = 'git@' + repo.host + ':' + repo.owner + '/' + repo.name + '.git'; else url = addProtocol(repo.host) + '/' + repo.owner + '/' + ...
javascript
{ "resource": "" }
q38428
train
function () { var str, i, len; // TODO void tags str = '' + '<' + this.descriptor.e; len = this.attributes.length; for ( i=0; i<len; i+=1 ) { str += ' ' + this.attributes[i].toString(); } str += '>'; if ( this.html ) { str += this.html; } else if ( this.fragment ) { str += this.fragmen...
javascript
{ "resource": "" }
q38429
userStored
train
function userStored(model, error) { if (typeof error != 'undefined') { callback(error); return; } if (user1.get('id') && user2.get('id')) { // users added to store now log them both in and also generate 2 errors self.goodCount = 0; ...
javascript
{ "resource": "" }
q38430
usersStarted
train
function usersStarted(err, session) { if (err) self.badCount++; else self.goodCount++; if (self.badCount == 2 && self.goodCount == 2) { // Resume session1 correctly new Session().resumeSession(store, ip1, session1.get('passCode'), sessionRes...
javascript
{ "resource": "" }
q38431
train
function(debug, milliseconds) { if(debug == null) { this_debug = false; } else { this._debug = debug; } if(milliseconds == null) { this._milliseconds = false; } else { this._milliseconds = true; } }
javascript
{ "resource": "" }
q38432
parseCreateAlertRequest
train
function parseCreateAlertRequest(req){ var reqObj = {}; reqObj.originalUrl = req.originalUrl; reqObj.alertName = req.body.alertName; reqObj.emails = req.body.emails; reqObj.eventCategories = req.body.eventCategories.split(','); reqObj.eventNames = req.body.eventNames.split(','); reqObj.eventSeverities = ...
javascript
{ "resource": "" }
q38433
parseUpdateAlertRequest
train
function parseUpdateAlertRequest(req){ var reqObj = {}; reqObj.originalUrl = req.originalUrl; reqObj.alertName = req.body.alertName; reqObj.emails = req.body.emails.split(','); reqObj.eventCategories = req.body.eventCategories.split(','); reqObj.eventNames = req.body.eventNames.split(','); reqObj.eventSev...
javascript
{ "resource": "" }
q38434
parseListRequest
train
function parseListRequest(req){ var reqObj = {}; reqObj.originalUrl = req.originalUrl; reqObj.uid = req.params.guid; reqObj.env = req.params.environment; reqObj.domain = req.params.domain; return reqObj; }
javascript
{ "resource": "" }
q38435
parseDeleteRequest
train
function parseDeleteRequest(req){ var reqObj = {}; reqObj.originalUrl = req.originalUrl; reqObj.uid = req.params.guid; reqObj.env =req.params.environment; reqObj.domain = req.params.domain; reqObj._id = req.params.id; return reqObj; }
javascript
{ "resource": "" }
q38436
parseAuth
train
function parseAuth(auth) { var parts = auth.split(':'); if (parts[0] && !parts[1]) return ['wait1|t' + parts[0]]; if (!parts[0] && parts[1]) return ['wait1|t' + parts[1]]; if (!parts[0] && !parts[1]) return []; return ['wait1|b' + (new Buffer(auth)).toString('base64')]; }
javascript
{ "resource": "" }
q38437
zipSVG
train
function zipSVG(libs, svgContent, src) { svgContent = svgContent // Remove space between two tags. .replace(/>[ \t\n\r]+</g, '><') // Replace double quotes with single quotes. .replace(/"/g, "'") // Replace many spaces by one single space. .replace(/[ \t\n\r]+/g, ' '); var s...
javascript
{ "resource": "" }
q38438
startsWith
train
function startsWith(text) { var i, arg; for (i = 1 ; i < arguments.length ; i++) { arg = arguments[i]; if (text.substr(0, arg.length) == arg) return true; } return false; }
javascript
{ "resource": "" }
q38439
createSubset
train
function createSubset(keywords, doc) { if (!keywords || Object.prototype.toString.call(keywords) !== '[object Array]') { return doc; } var lookup = createLookUp(keywords); return traverseThroughObject(lookup, doc); }
javascript
{ "resource": "" }
q38440
createLookUp
train
function createLookUp(keywords) { return keywords.reduce(function(p, c) { c.split('.').reduce(function(pr, cu) { if (pr.hasOwnProperty(cu)) { return pr[cu]; } else { pr[cu] = {}; return pr[cu]; } }, p); return p; }, {}); }
javascript
{ "resource": "" }
q38441
traverseThroughObject
train
function traverseThroughObject(lookup, doc, output) { if (!output) { output = {}; } for (var key in lookup) { if (doc.hasOwnProperty(key)) { if(Object.keys(lookup[key]).length === 0) { output[key] = doc[key]; } else { if (!output.hasOwnProperty(key)) { ...
javascript
{ "resource": "" }
q38442
setUntab
train
function setUntab(depth, trim){ started = true; /** Disable untab */ if(!depth){ _depth = null; _trim = false; } else{ _depth = depth; _trim = trim; } }
javascript
{ "resource": "" }
q38443
doUntab
train
function doUntab(input, depth = undefined, trim = undefined){ /** Not a string? Leave it. */ if("[object String]" !== Object.prototype.toString.call(input)) return input; if(trim === undefined) trim = _trim; if(depth === undefined) depth = _depth; /** Strip leading and trailing lines if told to */ if(tr...
javascript
{ "resource": "" }
q38444
hookIntoChai
train
function hookIntoChai(){ if(hooked) return; hooked = true; for(const method of ["equal", "string"]){ Chai.Assertion.overwriteMethod(method, function(__super){ return function(input, ...rest){ __super.apply(this, [ doUntab(input), ...rest ]); } }); } }
javascript
{ "resource": "" }
q38445
objectToString
train
function objectToString(object, tabs) { var result = []; var keys = Object.keys(object); keys.forEach(function (key, keyIndex) { var line; var formatedKey; if (-1 < key.indexOf('@')) { formatedKey = '\'' + key + '\...
javascript
{ "resource": "" }
q38446
stateRefSearch
train
function stateRefSearch(pages, stateName) { for (var i = 0; i < pages.length; i++) { if (pages[i].name === stateName) { return pages[i]; } } return null; }
javascript
{ "resource": "" }
q38447
isEmpty
train
function isEmpty(str) { if (null === str || typeof str === 'undefined') { return true; } if (typeof str === 'string') { return (0 === str.length); } if (typeof str === 'object' && Array.isArray(str)) { return (...
javascript
{ "resource": "" }
q38448
Provider
train
function Provider(id, secret) { if (!(this instanceof Provider)) { return new Provider(id, secret); } this.client = new AWS.SQS({ accessKeyId: id, secretAccessKey: secret, region: 'us-east-1' }); this.queues = {}; }
javascript
{ "resource": "" }
q38449
checkAdd
train
function checkAdd(list, key, func) { list.push({key: key, func: func}); }
javascript
{ "resource": "" }
q38450
checksDo
train
function checksDo(listChecks, cb) { if (listChecks.length === 0) { return cb(); } var check = listChecks.shift(); check.func(check.key, function () { // schedule the next check setImmediate(checksDo, listChecks, cb); }); }
javascript
{ "resource": "" }
q38451
checkRequired
train
function checkRequired(k, cb) { if (k in args) return cb(null); else return cb(buildError(k, 'argument missing')); }
javascript
{ "resource": "" }
q38452
buildError
train
function buildError(k, message) { if (!Array.isArray(errors[k])) errors[k] = []; errors[k].push(message); }
javascript
{ "resource": "" }
q38453
train
function(options, opt_fileList, opt_dirList) { var cmd = ''; // Detect if the tool file is a python script. If so we need to // prefix the exec command with 'python'. if (stringEndsWith(options.toolFile, '.py')) { cmd += 'python '; } // Normalize the folder path and join the tool file. cmd += path....
javascript
{ "resource": "" }
q38454
train
function(results, filePath) { var destDir = path.dirname(filePath); if (!grunt.file.exists(destDir)) { grunt.file.mkdir(destDir); } grunt.file.write(filePath, results); grunt.log.ok('File "' + filePath + '" created.'); }
javascript
{ "resource": "" }
q38455
setLanguage
train
function setLanguage(req) { var host = req.info.host; // hack fix for m.reviews, m.fr, m.es, etc. if (host.substring(0, 2) === 'm.') { req.app.isLegacyMobile = true; host = host.substring(2); } var subdomain = host.substring(0, 2); // either at ...
javascript
{ "resource": "" }
q38456
setAppInfo
train
function setAppInfo(req, domainMap) { var host = req.info.hostname; var domain; // hack fix for m.reviews, m.fr, m.es, etc. if (host.substring(0, 2) === 'm.') { req.app.isLegacyMobile = true; host = host.substring(2); } // if the host starts with...
javascript
{ "resource": "" }
q38457
setContext
train
function setContext(req) { var session = cls.getNamespace('appSession'); var appName = req.app.name; if (session && session.active) { session.set('app', appName); session.set('lang', req.app.lang); session.set('url', routeHelper.getBaseUrl(appName) + req.url....
javascript
{ "resource": "" }
q38458
getDomainMap
train
function getDomainMap() { var domainMap = { 'www': 'www' }; // temp hack for mobile redirect stuff (remove later) _.each(appConfigs, function (appConfig, appName) { var domain = appConfig.domain || appName; // by default domain is the app name domainMap[domain] = appName; ...
javascript
{ "resource": "" }
q38459
init
train
function init(ctx) { var domainMap = getDomainMap(); // for each request we need to set the proper context ctx.server.ext('onRequest', function (req, reply) { setLanguage(req); setAppInfo(req, domainMap); var appName = req.app.name; var lang = re...
javascript
{ "resource": "" }
q38460
train
function (directoryNames) { var i, directoryName; for (i = 0; i < directoryNames.length; i++) { directoryName = directoryNames[i]; mkdirp.sync(directoryName); // make output similar to yeoman's console.log(' ' + chalk.green('create') + ' ' + directoryN...
javascript
{ "resource": "" }
q38461
f_teklif_tumu
train
function f_teklif_tumu(_tahta_id, _ihale_id, _arama) { return f_teklif_idleri(_tahta_id, _ihale_id, _arama.Sayfalama) .then( /** * * @param {string[]} _teklif_idler * @returns {*} */ functio...
javascript
{ "resource": "" }
q38462
Encoder
train
function Encoder(options) { Transform.call(this); this._writableState.objectMode = true; this._readableState.objectMode = false; this.eol = options.eol; }
javascript
{ "resource": "" }
q38463
isComparable
train
function isComparable(object) { let type = typeof object; if (type === 'number' || type === 'string' || type == 'boolean') return true; if (type === 'object' && object instanceof Date) return true; return false; }
javascript
{ "resource": "" }
q38464
dashCase
train
function dashCase(str) { var newStr = ''; for (var i = 0, len = str.length; i < len; i++) { if (str[i] === str[i].toUpperCase()) { newStr += '-'; } newStr += str[i].toLowerCase(); } return newStr; }
javascript
{ "resource": "" }
q38465
defaultComparator
train
function defaultComparator(key, a, b) { if (key(a) < key(b)) return -1; if (key(a) > key(b)) return 1; return 0; }
javascript
{ "resource": "" }
q38466
train
function(mode, targetHost, system, containerDef, container, out, cb) { if (container.specific && container.specific.dockerContainerId) { var stopCmd = commands.kill.replace('__TARGETID__', container.specific.dockerContainerId); executor.exec(mode, stopCmd, config.imageCachePath, out, function(err) { ...
javascript
{ "resource": "" }
q38467
train
function(mode, targetHost, system, containerDef, container, out, newConfig, cb) { if (container.specific && container.specific.dockerContainerId && container.specific.configPath && container.specific.hup) { tmp.file(function(err, path) { if (err) { return cb(err); } fs.writeFile(path, newCon...
javascript
{ "resource": "" }
q38468
addInsert
train
function addInsert(agent) { /* `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `userAgent` VARCHAR(255) NOT NULL, `agentGroup_id` INT UNSIGNED NOT NULL DEFAULT '1', `agentSource_id` INT UNSIGNED NOT NULL DEFAULT '1', `timesReported` INT UNSIGNED NOT NULL DEFAULT '1', `status` TINYINT UNSI...
javascript
{ "resource": "" }
q38469
updateAgent
train
function updateAgent(id, group, source, status) { var groupId = groups.indexOf(group); if (groupId <= 0) { console.error("ERROR: group='" + group + "' was not found."); return; } var sourceId = sources.indexOf(source); if (sourceId <= 0) { console.error("ERROR: source='" + so...
javascript
{ "resource": "" }
q38470
main
train
function main() { agents.forEach(function (agent) { var r = agentdb.lookupPattern(agent.agent); if (r !== null) { if (agent.groupId == 1) { // Unknown group -> update agent updateAgent(agent.id, r.group, r.source, 2); } else if (agent.status != 1) { ...
javascript
{ "resource": "" }
q38471
onStreamEnd
train
function onStreamEnd(done) { Promise .all(lintPromiseList) .then(passLintResultsThroughReporters) .then(lintResults => { process.nextTick(() => { const errorCount = lintResults.reduce((sum, res) => { const errors = res.results[0].warnings.filter(isErrorSeverity); ...
javascript
{ "resource": "" }
q38472
train
function (userOptions) { Axis.prototype.setOptions.call(this, userOptions); this.options.crosshair = this.options.marker; this.coll = 'colorAxis'; }
javascript
{ "resource": "" }
q38473
train
function (value, point) { var pos, stops = this.stops, from, to, color, dataClasses = this.dataClasses, dataClass, i; if (dataClasses) { i = dataClasses.length; while (i--) { dataClass = dataClasses[i]; from = dataClass.from; to = dataClass.to; if ((from === UNDEFINED || ...
javascript
{ "resource": "" }
q38474
train
function () { var grad, horiz = this.horiz, options = this.options, reversed = this.reversed; grad = horiz ? [+reversed, 0, +!reversed, 0] : [0, +!reversed, 0, +reversed]; // #3190 this.legendColor = { linearGradient: { x1: grad[0], y1: grad[1], x2: grad[2], y2: grad[3] }, stops: options.stops || ...
javascript
{ "resource": "" }
q38475
train
function (legend, item) { var padding = legend.padding, legendOptions = legend.options, horiz = this.horiz, box, width = pick(legendOptions.symbolWidth, horiz ? 200 : 12), height = pick(legendOptions.symbolHeight, horiz ? 12 : 200), labelPadding = pick(legendOptions.labelPadding, horiz ? 16 : 30), ...
javascript
{ "resource": "" }
q38476
train
function () { var axis = this, chart = this.chart, legendItems = this.legendItems, legendOptions = chart.options.legend, valueDecimals = legendOptions.valueDecimals, valueSuffix = legendOptions.valueSuffix || '', name; if (!legendItems.length) { each(this.dataClasses, function (dataClass, i) {...
javascript
{ "resource": "" }
q38477
train
function () { var options; seriesTypes.scatter.prototype.init.apply(this, arguments); options = this.options; this.pointRange = options.pointRange = pick(options.pointRange, options.colsize || 1); // #3758, prevent resetting in setData this.yAxis.axisPointRange = options.rowsize || 1; // general point range ...
javascript
{ "resource": "" }
q38478
taskFontmin
train
function taskFontmin() { // prase options let opts = this.options() let data = this.data let destdir = opts.dest || './' let basedir = opts.basedir || './' let src = grunt.file.expand(data.src) let fonts = grunt.file.expand(join(basedir, this.target)) let getText = opts.ge...
javascript
{ "resource": "" }
q38479
extract
train
function extract(arr, obj) { return arr.filter(item => Object.keys(obj).every(key => item[key] === obj[key])); }
javascript
{ "resource": "" }
q38480
once
train
function once(event, listener) { function g() { this.removeListener(event, g); listener.apply(this, arguments); }; this.on(event, g); return this; }
javascript
{ "resource": "" }
q38481
removeListener
train
function removeListener(event, listener) { this._events = this._events || {}; if(event in this._events) { this._events[event].splice(this._events[event].indexOf(listener), 1); } return this; }
javascript
{ "resource": "" }
q38482
emit
train
function emit(event /* , args... */) { this._events = this._events || {}; // NOTE: copy array so that removing listeners in listeners (once etc) // NOTE: does not affect the iteration var list = (this._events[event] || []).slice(0); for(var i = 0; i < list.length; i++) { list[i].apply(this, Array.prototyp...
javascript
{ "resource": "" }
q38483
promiseWriteFile
train
function promiseWriteFile(targetPath, content, tabs = 2) { const fileName = targetPath.split('/').pop(); let contentHolder = content; if (targetPath.endsWith('.json')) { contentHolder = JSON.stringify(contentHolder, null, tabs); } return new Promise((resolve, reject) => { fs.writeFile(targetPath, co...
javascript
{ "resource": "" }
q38484
getGesture
train
function getGesture( element_ ) { const element = ensureDom( element_ ); if ( !element[ SYMBOL ] ) element[ SYMBOL ] = new Gesture( element ); return element[ SYMBOL ]; }
javascript
{ "resource": "" }
q38485
handlerWithChainOfResponsability
train
function handlerWithChainOfResponsability( eventName, evt ) { const chain = this._events[ eventName ].chain; for ( let i = 0; i < chain.length; i++ ) { const responsible = chain[ i ]; if ( responsible( evt ) === true ) return; } }
javascript
{ "resource": "" }
q38486
doRegister
train
function doRegister( event, responsible ) { var hammerEvent = getEventNameForPrefix( event, "hammer." ); if ( hammerEvent && !this._hammer ) { this._hammer = new Hammer( this.$, { domEvents: true } ); // To get domEvents.stopPropagation() available. this._hammer.domEvents = true; } ...
javascript
{ "resource": "" }
q38487
onDrag
train
function onDrag( register, slot, args ) { const that = this; register( 'hammer.pan', function ( evt ) { if ( evt.isFinal ) return false; setHammerXY( that.$, evt ); if ( typeof that._dragX === 'undefined' ) { that._dragX = evt.x; that._dragY = evt.y; ...
javascript
{ "resource": "" }
q38488
froms
train
function froms(froms) { var args = Array.prototype.splice.call(arguments, 0); if (isUndefined(froms)) { froms = []; } if (!isArray(froms)) { throw { name: 'Error', message: 'Argument is not an array', arguments: args }; } var f = froms .filter(function (from) { retu...
javascript
{ "resource": "" }
q38489
createThingme
train
function createThingme (opts) { opts = defaultOptions(opts); validateThings(opts.things); return createWebservice(opts); }
javascript
{ "resource": "" }
q38490
createWebservice
train
function createWebservice (opts) { var server = new Hapi.Server(opts.host, opts.port, { cors: { methods: ['GET'] } }); defineRoutes(server, opts); return { address: 'http://' + opts.host + ':' + opts.port + '/', hapi: server, options: opts, sta...
javascript
{ "resource": "" }
q38491
defineRoutes
train
function defineRoutes (server, opts) { require('../route')(server, opts); require('../route/things')(server, opts); require('../route/random')(server, opts); require('../route/bomb')(server, opts); require('../route/count')(server, opts); }
javascript
{ "resource": "" }
q38492
write
train
function write (database) { var deferred = q.defer(); // Write database to file under database name fs.writeFile(globalConfig.db.location + database + '.db.json', JSON.stringify(databases[database]), function (err) { if(err) return deferred.reject(err); deferred.resolve(); }); return deferred.promi...
javascript
{ "resource": "" }
q38493
verifyConfig
train
function verifyConfig (config) { config = config || {}; config.db = config.db || {}; config.db.location = config.db.location || __dirname + 'databases/'; // /cwd/databases/ default config.db.timeout = config.db.timeout || 1000 * 60 * 5; // 5 minute default config.db.fileTimeout = config.db.fileTimeout || -1; ...
javascript
{ "resource": "" }
q38494
createLocation
train
function createLocation () { var deferred = q.defer(); // Make the directory, and report status mkdirp(globalConfig.db.location, function (err, made) { if(err) return deferred.reject(err); deferred.resolve(made); }); return deferred.promise; }
javascript
{ "resource": "" }
q38495
createDatabase
train
function createDatabase (name) { var deferred = q.defer(); // Make sure the database location exists ready.then(function () { // Check if database exists fs.exists(globalConfig.db.location + name + '.db.json', function (exists) { if(exists) return deferred.resolve(); // If database is non-ex...
javascript
{ "resource": "" }
q38496
closeDatabase
train
function closeDatabase (name) { var deferred = q.defer(); // We need to be sure the database location exists ready.then(function () { clearTimeout(timeouts[name]); // Write to file write(name).then(function () { // Remove database from memory delete databases[name]; deferred.resol...
javascript
{ "resource": "" }
q38497
actionOn
train
function actionOn (name) { // Clear a possibly existing timeout clearTimeout(timeouts[name]); // Make sure user hasn't declined auto-close if(globalConfig.db.timeout < 0) return; // Set up auto-close timeouts[name] = setTimeout(function () { closeDatabase(name); }, globalConfig.db.timeout); }
javascript
{ "resource": "" }
q38498
train
function(file, options, callback) { // If the file is a string, we assume it's a path on disk if (_.isString(file)) { try { file = fs.createReadStream(file); } catch (err) { return callback({'message': 'A stream could not be...
javascript
{ "resource": "" }
q38499
train
function(link, options, callback) { var data = {'link': link}; addSizes(data, options, 'thumbnailSizes'); addSizes(data, options, 'imageSizes'); return processr._request('POST', '/resources', data, callback); }
javascript
{ "resource": "" }