_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 !== pinfo.id) { throw new Error('Expected plugin to have ID "' + parsedSpec.id + '" but got "' + pinfo.id + '".'); } } if (parsedSpec.version && !semver.satisfies(pinfo.version, parsedSpec.version)) { throw new Error('Expected plugin ' + pinfo.id + ' to satisfy version "' + parsedSpec.version + '" but got "' + pinfo.version + '".'); } }
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); }); callback(null, db); }); }
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.dependencyVersions = {}; // Set linting options from given options or defaults options = options || {}; this.depPaths = options.depPaths || []; this.lookupPaths = options.lookupPaths || []; this.recursive = options.recursive || false; this.verbose = options.verbose || false; this.quiet = options.quiet || false; this.silent = options.silent || false; this.ignorePaths = options.ignorePaths || []; this.warnPaths = options.warnPaths || []; // Inject default dep path if it exists if (!this.depPaths.length && fs.existsSync('./components')) { this.depPaths.push('./components'); } // Keep a count of total errors and warnings this.totalErrors = 0; this.on('lint.error', function () { this.totalErrors += 1; }); this.totalWarnings = 0; this.on('lint.warning', function () { this.totalWarnings += 1; }); }
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(allowedScopes[i]) !== -1) { return true; } } return false; }
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 (authorizedScopes.indexOf(requestedScopes[i]) === -1) { return false; } } return true; }
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 && !(parent instanceof Behalter)) { throw new TypeError('parent must be an instance of Behalter'); } // construct this with super constructor EventEmitter2.call(this, options); // configure default properties this.__parent = parent; this.__values = {}; this.__factories = {}; // configure options: to INHERIT options, configure only for root if (!parent) { this.__options = { useGetter: true, useSetter: false }; } else { this.__options = {}; } }
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++) { args[i] = arguments[i]; } return ko.ifyHandler(fn, args); }; let errHandler = function (err, req, res, next) { let argsLength = arguments.length; let args = new Array(argsLength); for (let i = 0; i < argsLength; i++) { args[i] = arguments[i]; } return ko.ifyHandler(fn, args, true); }; let paramHandler = function (req, res, next, val) { let argsLength = arguments.length; let args = new Array(argsLength); for (let i = 0; i < argsLength; i++) { args[i] = arguments[i]; } return ko.ifyHandler(fn, args); }; let wrapper; // the way Express distinguishes error handlers from regular ones if (fn.length === 4) { wrapper = isParamHandler ? paramHandler : errHandler; } else { wrapper = handler; } // safeguard Object.defineProperty(wrapper, '$$koified', { configurable: true, writable: true, value: true }); return wrapper; }
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) { req = args[1]; res = args[2]; next = args[3]; } else { req = args[0]; res = args[1]; next = args[2]; } return fnResult.then((result) => { // implicit 'next' if ((result === req) || (result === res)) { next(); // explicit 'next' } else if ((isFunction(next) && (result === next)) || (result === ko.NEXT)) { next(); } else if (result === ko.NEXT_ROUTE) { next('route'); } else if (isError(result)) { next(result); } else if (result !== undefined) { if (isNumber(result)) { res.sendStatus(result); } else { res.send(result); } } // exposed for testing return result; }, (err) => { next(err); return err; }); }
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) { ko.ifyRouter(Router); } if (Route) { ko.ifyRoute(Route); } return 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 = Object.getPrototypeOf(someRouter); let someRouterMethods = Object.keys(someRouterPrototype).sort(); return arrayEqual(someRouterMethods, routerMethods) && (typeof someRouterPrototype === 'function'); } routerPrototype_.use = routerPrototype.use; routerPrototype.use = function () { let args = slice.call(arguments); for (let i = 0; i < args.length; i++) { let handler = args[i]; // don't wrap router instances if (isFunction(handler) && !isRouter(handler)) { args[i] = ko.ko(handler); } } return routerPrototype_.use.apply(this, args); }; routerPrototype_.param = routerPrototype.param; routerPrototype.param = function () { let args = slice.call(arguments); let handler = args[1]; if (isFunction(handler)) { // additional argument to indicate param handler args[1] = ko.ko(handler, true); } return routerPrototype_.param.apply(this, args); }; // safeguard Object.defineProperty(routerPrototype, '$$koified', { configurable: true, writable: true, value: false }); return Router; }
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++) { let handler = args[i]; if (isFunction(handler)) { args[i] = ko.ko(handler); } } return routePrototype_[method].apply(this, args); }; } return Route; }
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; val = val['$ne']; } var dataValue = getNestedValue(data, key); if (_.isString(val) && _.isArray(dataValue)) { // allows you to check if an array contains a value match = (dataValue.indexOf(val) > -1); } else { var vals = _.isArray(val) ? val : [val]; if (vals.indexOf(dataValue) < 0) { match = false; } if ( hasNotOperand ) { match = !match; } } }); return match; }
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); //批量绑定事件处理 if (vQ.isArray(type)) { return own._handleMultipleEvents.apply(own, [own.one].concat(args)); //return own._handleMultipleEvents(own.one, element, type, handler); } var func = function () { own.unbind(element, type, func); handler.apply(context || element, arguments); }; // copy the guid to the new function so it can removed using the original function's ID func.$$guid = handler.$$guid = handler.$$guid || own._guid++; own.bind(element, type, func); //var func = function(){ // own.unbind.apply(own,args); // handler.apply(context || element, arguments); //}; ////args = [type, func].concat(args.slice(2));//更换fun 这样支持不定个数的参数 // //// copy the guid to the new function so it can removed using the original function's ID //func.$$guid = handler.$$guid = handler.$$guid || own._guid++; ////own.observe(element, type, func); //own.bind.apply(own,args); }
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] === 'undefined') { events[eventName] = []; } } return this; }
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.hasOwnProperty(name)) { this.bind(name, eventName[name]); } } return this; } if (!this.isSupported(eventName)) { throw "IllegalArgumentException: unrecognized event name (" + eventName + ")."; } if (typeof fn !== 'function') { throw "IllegalArgumentException: fn must be a Function."; } this._events[eventName].push(fn); if (this.numListeners(eventName) === 1) { this._sendActivation('_activate', eventName); } return this; }
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; for (var i = len - 1; i >= 0; i--) { if (fns[i] === fn) { fns.splice(i, 1); } } if ( fns.length !== len && fns.length === 0 ) { this._sendActivation('_deactivate', eventName); } } return this; }
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 = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); } var hasFoundFalse = false; for ( var i = 0; i < fns.length && !hasFoundFalse; i++ ) { if (fns[i].apply(this, args) === false) { hasFoundFalse = true; } } if (hasFoundFalse) { return false; } } return true; }
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 && bytesPerPixel !== 4) { throw new Error("Invalid number of bytes per pixel: " + bytesPerPixel); } this._width = width; this._height = height; this._bytesPerPixel = bytesPerPixel; this._endianness = endianness === undefined ? Endianness.BIG : endianness; this._palette = bytesPerPixel === 1 ? [].concat(DEFAULT_PALETTE) : []; this._data = new Buffer(width * height * bytesPerPixel); saveReadAndWriteFunction.call(this); // Initialize to white this.clear(0xFF); }
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 === null) { if (type === 'github') { host = 'github.com'; } else if (type === 'gitlab') { host = 'gitlab.com'; } else if (type === 'bitbucket') { host = 'bitbucket.com'; } else if (type === 'oschina') { host = 'git.oschina.net'; } } return { type, host, owner, name, checkout }; }
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 { url = github(repo, clone); } return url; }
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 + '/' + repo.name + '/repository/archive/' + repo.checkout; return {url, clone}; }
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.fragment.toString(); } str += '</' + this.descriptor.e + '>'; return str; }
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; self.badCount = 0; session1.startSession(store, name1, 'badpassword', ip1, usersStarted); session1.startSession(store, name1, pass1, ip1, usersStarted); session2.startSession(store, 'john', pass2, ip2, usersStarted); session2.startSession(store, name2, pass2, ip2, usersStarted); } }
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'), sessionResumed_Test1); } }
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 = req.body.eventSeverities.split(','); reqObj.uid = req.body.uid; reqObj.env = req.body.env; reqObj.alertEnabled = req.body.enabled; reqObj._id = new Mongoose.Types.ObjectId(); reqObj.domain = req.params.domain; return reqObj; }
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.eventSeverities = req.body.eventSeverities.split(','); reqObj.uid = req.body.uid; reqObj.env = req.body.env; reqObj.alertEnabled = req.body.enabled; reqObj._id = req.params.id; reqObj.domain = req.params.domain; return reqObj; }
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 svgTree = libs.parseHTML(svgContent); // We want to remove unused `id`attributes. // Such an attribute is used as long as there is a `xlink:href` attribute referencing it. var idsToKeep = {}; // Remove Inkscape tags and <image>. libs.Tree.walk(svgTree, function(node) { if (node.type !== libs.Tree.TAG) return; var name = node.name.toLowerCase(); if (name == 'flowroot') { libs.warning( "Please don't use <flowRoot> nor <flowRegion> in your SVG (\"" + src + "\")!\n" + "If it was created with Inkscape, convert it in SVG 1.1 by opening the `Text` menu\n" + "and selecting \"Convert to Text\".", src, svgContent, node.pos ); } var nodeToDelete = startsWith( name, "metadata", "inkscape:", "sodipodi:", "image", "dc:", "cc:", "rdf:", "flowroot", "flowregion" ); if (nodeToDelete) { node.type = libs.Tree.VOID; delete node.children; } else if (node.attribs) { var attribsToDelete = []; var attribName, attribValue; for (attribName in node.attribs) { if ( startsWith( attribName, 'inkscape:', 'sodipodi:', 'xmlns:inkscape', 'xmlns:sodipodi', 'xmlns:dc', 'xmlns:cc', 'xmlns:rdf' ) ) { // This is an attribute to delete. attribsToDelete.push(attribName); } else { // Look for references (`xlink:href`). attribValue = node.attribs[attribName].trim(); if (attribName.toLowerCase() == 'xlink:href') { if (attribValue.charAt(0) == '#') { // Remember that this ID must not be deleted. idsToKeep[attribValue.substr(1)] = 1; } } else { // Look for local URLs: `url(#idToKeep)`. var match; while ((match = RX_LOCAL_URL.exec(attribValue))) { idsToKeep[match[1]] = 1; } } } } attribsToDelete.forEach(function (attribName) { delete node.attribs[attribName]; }); } }); // Removing emtpy <g> and <defs>. libs.Tree.walk(svgTree, function(node) { if (node.type != libs.Tree.TAG) return; var name = node.name.toLowerCase(); if (node.attribs && node.attribs.id) { // Try to remove unused ID. if (!idsToKeep[node.attribs.id]) { delete node.attribs.id; } } if (['g', 'defs'].indexOf(name) > -1) { // If this tag has no child, we must delete it. var childrenCount = 0; (node.children || []).forEach(function (child) { if (child.type == libs.Tree.TEXT || child.type == libs.Tree.TAG) { childrenCount++; } }); if (childrenCount == 0) { // This tag is empty, remove it. delete node.children; node.type = libs.Tree.VOID; } } }); var svg = libs.Tree.toString(svgTree); return svg; // The following code was used when we embeded the SVG in Data URI form. /* console.log(svg); console.log(); console.log("Base64: " + (new Buffer(svg)).toString('base64').length); console.log("UTF-8: " + encodeURIComponent(svg).length); console.log(); var encodedSVG_base64 = (new Buffer(svg)).toString('base64'); var encodedSVG_utf8 = encodeURIComponent(svg); if (encodedSVG_base64 < encodedSVG_utf8) { return '"data:image/svg+xml;base64,' + encodedSVG_base64 + '"'; } else { return '"data:image/svg+xml;utf8,' + encodedSVG_utf8 + '"'; } */ }
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)) { if (Object.prototype.toString.call(doc[key]) === '[object Array]') { output[key] = []; for (var i = 0, _len = doc[key].length; i < _len; i++) { var field = {}; output[key].push(field); traverseThroughObject(lookup[key], doc[key][i], field); } } else { output[key] = {}; traverseThroughObject(lookup[key], doc[key], output[key]); } } } } } return output; }
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(trim) input = input.replace(/^(?:[\x20\t]*\n)*|(?:\n[\x20\t]*)*$/gi, ""); const untabPatt = new RegExp("^(?:" + untabChar + "){0," + depth + "}", "gm"); return input.replace(untabPatt, ""); }
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 + '\''; } else { formatedKey = key; } if (typeof object[key] === 'object') { if (Array.isArray(object[key])) { var newTabs = (tabs + 1); line = getTabs(tabs) + '' + formatedKey + ': ['; object[key].forEach(function (item, itemIndex) { if (typeof item === 'object') { line += "\n" + getTabs(newTabs) + '{'; line += "\n" + objectToString(item, (newTabs + 1)); line += "\n" + getTabs(newTabs) + '}'; } else if (typeof item === 'string') { line += "\n" + getTabs(newTabs) + '\'' + addslashes(item) + '\''; } else if (typeof item === 'boolean') { line += "\n" + getTabs(newTabs) + '' + item; } else if (typeof item === 'number') { line += "\n" + getTabs(newTabs) + '' + item; } if (itemIndex < (object[key].length - 1)) { line += ','; } }); line += "\n" + getTabs(tabs) + ']'; } else { line = getTabs(tabs) + '' + formatedKey + ': {' + "\n"; line += objectToString(object[key], (tabs + 1)); line += "\n" + getTabs(tabs) + '}'; } } else if (typeof object[key] === 'string') { line = getTabs(tabs) + '' + formatedKey + ': \'' + addslashes(object[key]) + '\''; } else if (typeof object[key] === 'boolean') { line = getTabs(tabs) + '' + formatedKey + ': ' + object[key]; } else if (typeof object[key] === 'number') { line = getTabs(tabs) + '' + formatedKey + ': ' + object[key]; } if (keyIndex < (keys.length - 1)) { line += ','; } result.push(line); }); return result.join("\n"); }
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 (0 === str.length); } return false; }
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.join(path.resolve(options.closureLinterPath), options.toolFile) + ' '; // Set command flags cmd += (options.strict) ? '--strict ' : ''; cmd += (options.maxLineLength) ? '--max_line_length ' + options.maxLineLength + ' ' : ''; // Finally add files to be linted if (opt_dirList && opt_dirList.length > 0) { cmd += opt_dirList.map(function(value) {return '-r ' + value;}).join(' ') + ' '; } if (opt_fileList && opt_fileList.length > 0) { cmd += opt_fileList.join(' '); } return cmd; }
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 language-based subdomain or we use english req.app.lang = (host.charAt(2) === '.' && langSubdomains.indexOf(subdomain) >= 0) ? subdomain : 'en'; }
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 the lang, then remove it if (host.indexOf(req.app.lang + '.') === 0) { host = host.substring(3); } // if the host name equals the base host then we are dealing with the default domain (ex. gethuman.com) if (host === config.baseHost) { domain = ''; } // else we need to extract the domain from the host else { var dotIdx = host.indexOf('.'); var dashIdx = host.indexOf('-'); var idx = (dashIdx > 0 && dashIdx < dotIdx) ? dashIdx : dotIdx; domain = host.substring(0, idx); } // get the app name var appName = domainMap[domain]; // if no app name found, try to use the default (else if no default, throw error) if (!appName) { if (config.webserver && config.webserver.defaultApp) { appName = config.webserver.defaultApp; } else { throw AppError.invalidRequestError('No valid domain in requested host: ' + req.info.host); } } // at this point we should have the domain and the app name so set it in the request req.app.domain = domain; req.app.name = appName; }
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.path); } }
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; }); return domainMap; }
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 = req.app.lang; if (req.app.isLegacyMobile || appName === 'www' || req.app.domain === 'contact') { appName = appName === 'www' ? 'contact' : appName; reply.redirect(routeHelper.getBaseUrl(appName, lang) + req.url.path).permanent(true); return; } setContext(req); reply.continue(); }); return new Q(ctx); }
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') + ' ' + directoryName.replace('/', '\\') + '\\'); } }
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 {*} */ function (_teklif_idler) { var sonucAnahtari = result.kp.temp.ssetTahtaIhaleTeklifleri(_tahta_id, _ihale_id), /** @type {LazyLoadingResponse} */ sonuc = schema.f_create_default_object(schema.SCHEMA.LAZY_LOADING_RESPONSE); if (_teklif_idler && _teklif_idler.length > 0) { return result.dbQ.scard(sonucAnahtari) .then(function (_toplamKayitSayisi) { sonuc.ToplamKayitSayisi = parseInt(_toplamKayitSayisi); var db_teklif = require('./db_teklif'); var opts = db_teklif.OptionsTeklif({ bArrUrunler: true, bKalemBilgisi: true, bIhaleBilgisi: true, bKurumBilgisi: true, optUrun: {} }); return db_teklif.f_db_teklif_id(_teklif_idler, _tahta_id, opts) .then(function (_dbTeklifler) { //göndermeden önce sıralıyoruz var teklifler = _.sortBy(_dbTeklifler, ['Kalem_Id', 'TeklifDurumu_Id']); sonuc.Data = teklifler; return sonuc; }); }); } else { //teklif yok sonuc.ToplamKayitSayisi = 0; sonuc.Data = []; return sonuc; } }); }
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) { out.preview({cmd: stopCmd, host: 'localhost'}); if (err && err.code !== 2) { cb(err); } else { cb(); } }); } else { cb(); } }
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, newConfig, 'utf8', function(err) { if (err) { return cb(err); } var copyCmd = commands.generateCopyCommand(container.specific.dockerContainerId, container.specific.configPath, path); var hupCmd = commands.generateHupCommand(container); executor.exec(mode, copyCmd, config.imageCachePath, out, function(err) { if (err) { return cb(err); } executor.exec(mode, hupCmd, config.imageCachePath, out, function(err) { cb(err); }); }); }); }); } else { cb(); } }
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 UNSIGNED NOT NULL DEFAULT '0', `description` TEXT, `created` DATETIME NULL, `modified` DATETIME NULL, */ console.log("INSERT INTO `Agents` VALUES (NULL, '" + quote(agent.agent) + "', '" + agent.groupId + "', '" + agent.sourceId + "', '0', '0', '', NOW(), NOW());"); }
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='" + source + "' was not found."); return; } console.log("UPDATE `Agents` SET `status`='" + status + "', " + "`agentGroup_id`='" + groupId + "', " + "`agentSource_id`='" + sourceId + "' WHERE " + "`id`='" + id + "';"); }
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) { if (r.group == agent.group) { if ((agent.source == 'Unknown') && (r.source != 'Unknown')) { // Unknown source -> update agent updateAgent(agent.id, r.group, r.source, 2); } else if ((agent.source == r.source) && (agent.status != 2)) { // 2 is good updateStatus(agent.id, 2); } else if ((agent.source != r.source) && (agent.status != 3)) { // must include exact. updateStatus(agent.id, 1); } } else if (agent.status != 3) { // need to include exact. updateStatus(agent.id, 1); } } else if ((r.group == agent.group) && (r.source == agent.source)) { // can use pattern updateStatus(agent.id, 2); } } else { r = agentdb.lookupHash(agent.agent); if (r !== null) { if ((r.group != agent.group) || (r.source != agent.source)) { if (debug) { console.error("ERROR: lookup did not match: " + agent.agent); } if (debug) { console.error(" lookup.group=" + r.group+", expected="+agent.group+", lookup.source=" + r.source + ", expected="+agent.source); } } else if ((agent.status != 1) && (agent.status != 3)) { updateStatus(agent.id, 1); } } else { if ((agent.status < 3) && ((agent.group != "Unknown") || (agent.source != "Unknown"))) { if (debug) { console.error("ERROR: missing:" + agent.agent); } notfound.push(agent); } } } }); if (notfound.length > 0) { console.error("Warning: user-agents were not found: " + notfound.length); if (createMissing) { notfound.forEach(function (agent) { addInsert(agent); }); } } }
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); return sum + errors.length; }, 0); if (pluginOptions.failAfterError && errorCount > 0) { const errorMessage = `Failed with ${errorCount} ${errorCount === 1 ? 'error' : 'errors'}`; this.emit('error', new PluginError(pluginName, errorMessage)); } done(); }); }) .catch(error => { process.nextTick(() => { this.emit('error', new PluginError(pluginName, error, { showStack: Boolean(pluginOptions.debug) })); done(); }); }); }
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 || value >= from) && (to === UNDEFINED || value <= to)) { color = dataClass.color; if (point) { point.dataClass = i; } break; } } } else { if (this.isLog) { value = this.val2lin(value); } pos = 1 - ((this.max - value) / ((this.max - this.min) || 1)); i = stops.length; while (i--) { if (pos > stops[i][0]) { break; } } from = stops[i] || stops[i + 1]; to = stops[i + 1] || from; // The position within the gradient pos = 1 - (to[0] - pos) / ((to[0] - from[0]) || 1); color = this.tweenColors( from.color, to.color, pos ); } return color; }
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 || [ [0, options.minColor], [1, options.maxColor] ] }; }
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), itemDistance = pick(legendOptions.itemDistance, 10); this.setLegendColor(); // Create the gradient item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 11, width, height ).attr({ zIndex: 1 }).add(item.legendGroup); box = item.legendSymbol.getBBox(); // Set how much space this legend item takes up this.legendItemWidth = width + padding + (horiz ? itemDistance : labelPadding); this.legendItemHeight = height + padding + (horiz ? labelPadding : 0); }
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) { var vis = true, from = dataClass.from, to = dataClass.to; // Assemble the default name. This can be overridden by legend.options.labelFormatter name = ''; if (from === UNDEFINED) { name = '< '; } else if (to === UNDEFINED) { name = '> '; } if (from !== UNDEFINED) { name += Highcharts.numberFormat(from, valueDecimals) + valueSuffix; } if (from !== UNDEFINED && to !== UNDEFINED) { name += ' - '; } if (to !== UNDEFINED) { name += Highcharts.numberFormat(to, valueDecimals) + valueSuffix; } // Add a mock object to the legend items legendItems.push(extend({ chart: chart, name: name, options: {}, drawLegendSymbol: LegendSymbolMixin.drawRectangle, visible: true, setState: noop, setVisible: function () { vis = this.visible = !vis; each(axis.series, function (series) { each(series.points, function (point) { if (point.dataClass === i) { point.setVisible(vis); } }); }); chart.legend.colorizeItem(this, vis); } }, dataClass)); }); } return legendItems; }
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.getText!==undefined ? opts.getText : (content)=>html2text.fromString(content) let type='woff', typeOpts=true // check if more than one output option is specified if ( !atMostDefined(data, 1, 'woff', 'css') ) throw new Error('Multiple output type defined!') // set type, typeOpts if (data.woff!==undefined) { type='woff' } if (data.css!==undefined) { type='css'; typeOpts=data.css } // string of unique characters(glyphs) to be included in minimized font let uniqGlyphs = src.map( path => grunt.file.read(path) ) .map( getText ) .join() .split('') .sort().reduce( nodup(), [] ) // remove duplicate characters .join('') fonts.forEach( path => { // create output ArrayBuffer let ttf = readToTTF(path) let stripped = glyphStrip(ttf, uniqGlyphs) let output = ttfToOutput(stripped, type, typeOpts) // solve dest path, write output let destPath = join(destdir, getOutputFilename(path,type)) grunt.file.write(destPath, toBuffer(output)) // output information grunt.log.writeln(basename(path)+' => '+type+' ' +chalk.green(stripped.glyf.length)+' glyphs, ' +chalk.green(output.byteLength)+' bytes') } ) }
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.prototype.slice.call(arguments, 1)) } return list.length > 0; }
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, contentHolder, err => { if (err) reject(err); resolve({ path: targetPath, fileName, content: contentHolder }); }); }); }
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; } var eventDef = this._events[ event ]; if ( !eventDef ) { var handler = handlerWithChainOfResponsability.bind( this, event ); eventDef = { chain: [], handler: handler }; if ( hammerEvent ) this._hammer.on( hammerEvent, handler ); else this.$.addEventListener( event, handler ); this._events[ event ] = eventDef; } eventDef.chain.push( responsible ); }
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; that._dragStart = true; } setHammerVxVy.call( that, that.$, evt ); const domEvt = evt.srcEvent; slot( { x: evt.x, y: evt.y, x0: evt.x0, y0: evt.y0, vx: evt.vx, vy: evt.vy, sx: evt.velocityX, sy: evt.velocityY, event: evt, target: evt.target, buttons: getButtons( evt ), preventDefault: domEvt.preventDefault.bind( domEvt ), stopPropagation: domEvt.stopImmediatePropagation.bind( domEvt ) }, args ); return true; } ); }
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) { return !isUndefined(from); }) .map(function (from) { if (isObject(from)) { if (isUndefined(from.target) && isUndefined(from.default)) { throw { name: 'Error', message: 'from.target and from.default are both undefined', arguments: args }; } if (isUndefined(from.default) && !isString(from.target)) { throw { name: 'Error', message: 'from.target is not a string', arguments: args }; } return from; } else { return { target: from }; }; }); return f; }
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, start: server.start.bind(server) }; }
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.promise; }
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; // No limit default return config; }
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-existent, simply write an empty object as placeholder fs.writeFile(globalConfig.db.location + name + '.db.json', '{}', function (err) { if(err) return deferred.reject('Database couldn\'t create table'); return deferred.resolve(); }); }); }, function () { deferred.reject('Database couldn\'t instantiate'); }); return deferred.promise; }
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.resolve(); }, function (err) { deferred.reject(err); }); }, function () { deferred.reject('Database couldn\'t instantiate'); }); return deferred.promise; }
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 opened for the provided path', 'err': err}); } } // Attach an error listener to the stream file.on('error', function(err) { return callback({'message': 'An error occurred when reading from the stream', 'err': err}); }); // Upload the file var data = {'file': file}; addSizes(data, options, 'thumbnailSizes'); addSizes(data, options, 'imageSizes'); return processr._request('POST', '/resources', data, callback); }
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": "" }