_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q49600
copyAssets
train
function copyAssets({ assetsDir }) { if (_shouldCopyAssets(assetsDir)) { fs.copySync(distDir, assetsDir, { filter: src => !/inline/.test(src) }); } }
javascript
{ "resource": "" }
q49601
getAssets
train
function getAssets(reportOptions) { const { assetsDir, cdn, dev, inlineAssets, reportDir } = reportOptions; const relativeAssetsDir = path.relative(reportDir, assetsDir); // Default URLs to assets path const assets = { inlineScripts: null, inlineStyles: null, scriptsUrl: path.join(relativeAssetsDir...
javascript
{ "resource": "" }
q49602
prepare
train
function prepare(reportData, opts) { // Stringify the data if needed let data = reportData; if (typeof data === 'object') { data = JSON.stringify(reportData); } // Get the options const reportOptions = getOptions(opts); // Stop here if we're not generating an HTML report if (!reportOptions.saveHtm...
javascript
{ "resource": "" }
q49603
create
train
function create(data, opts) { const { html, reportOptions } = prepare(data, opts); const { saveJson, saveHtml, autoOpen, overwrite, jsonFile, htmlFile } = reportOptions; const savePromises = []; savePromises.push(saveHtml !== false ? saveFile(htmlFile, html, overwrite) .the...
javascript
{ "resource": "" }
q49604
createSync
train
function createSync(data, opts) { const { html, reportOptions } = prepare(data, opts); const { autoOpen, htmlFile } = reportOptions; fs.outputFileSync(htmlFile, html); if (autoOpen) opener(htmlFile); }
javascript
{ "resource": "" }
q49605
validateFile
train
function validateFile(file) { let data; let err = null; // Try to read and parse the file try { data = JSON.parse(fs.readFileSync(file, 'utf-8')); } catch (e) { if (e.code === 'ENOENT') { err = ERRORS.NOT_FOUND; } else if (JsonErrRegex.test(e.message)) { err = ERRORS.INVALID_JSON([ e ...
javascript
{ "resource": "" }
q49606
getReportFilename
train
function getReportFilename({ filename }, { reportFilename }) { return reportFilename || filename.split(path.sep).pop().replace(JsonFileRegex, ''); }
javascript
{ "resource": "" }
q49607
processArgs
train
function processArgs(args, files = []) { return args.reduce((acc, arg) => { let stats; try { stats = fs.statSync(arg); } catch (err) { // Do nothing } // If argument is a directory, process the files inside if (stats && stats.isDirectory()) { return processArgs( fs.r...
javascript
{ "resource": "" }
q49608
marge
train
function marge(args) { // Reset valid files count validFiles = 0; // Get the array of JSON files to process const files = processArgs(args._); // When there are multiple valid files OR the timestamp option is set // we must force `overwrite` to `false` to ensure all reports are created /* istanbul ignor...
javascript
{ "resource": "" }
q49609
numarray
train
function numarray(x) { for (var j = 0, o = []; j < x.length; j++) o[j] = parseFloat(x[j]); return o; }
javascript
{ "resource": "" }
q49610
isThenable
train
function isThenable(o) { var _then, o_type = typeof o; if (o != null && ( o_type == "object" || o_type == "function" ) ) { _then = o.then; } return typeof _then == "function" ? _then : false; }
javascript
{ "resource": "" }
q49611
train
function (params, noEncode) { if(this.isObject(params)){ var paramsStr = []; for (var key in params) { if (params.hasOwnProperty(key) && params[key] !== undefined) { var value = this.isObject(params[key])? this.buildParams(params[key], true) : params[key]; param...
javascript
{ "resource": "" }
q49612
train
function(options){ var url = options.apiUrl + (options.url ? options.url : ''); if(options.params) { url += (url.indexOf('?') === -1 ? '?' : '&') + this.buildParams(options.params); } return url; }
javascript
{ "resource": "" }
q49613
train
function(options){ if (typeof window !== 'undefined' && window.navigator.geolocation) { // Have default options, but allow to extend with custom. var geolocationOptions = this.extend({ maximumAge: 0, timeout: 10000, enableHighAccuracy: true }, options); ...
javascript
{ "resource": "" }
q49614
train
function (customSettings) { if(Utils.isObject(customSettings)){ this.settings = Utils.extend(this.settings, customSettings); }else{ throw new TypeError('Setup should be called with an options object.'); } return this.settings; }
javascript
{ "resource": "" }
q49615
train
function (plugin){ if (Utils.isObject(plugin) && Utils.isFunction(plugin.install)) { var installArgs = []; // Inject plugin dependencies as requested, using the synchronous // require API for Require.js and Almond.js. if(plugin.$inject){ plugin.$inject.forEach(function (...
javascript
{ "resource": "" }
q49616
train
function (headers) { var parsed = {}; if (headers) { headers = headers.trim().split("\n"); for (var h in headers) { if (headers.hasOwnProperty(h)) { var header = headers[h].match(/([^:]+):(.*)/); parsed[header[1].trim().toLowerCase()] = header[2].trim(); ...
javascript
{ "resource": "" }
q49617
_createXhr
train
function _createXhr(method, url, options) { var xhr = new XMLHttpRequest(); xhr.open(method, url); // Setup headers, including the *Authorization* that holds the Api Key. for (var header in options.headers) { if (options.headers.hasOwnProperty(header)) { xhr.setRequestHeader(header, opti...
javascript
{ "resource": "" }
q49618
errorHandler
train
function errorHandler(response) { if (response) { var errorData = _buildError(xhr, url, method, response); Logger.error(errorData); if (errorCallback) { Logger.warnCallbackDeprecation(); errorCallback(errorData); } reject(errorData); ...
javascript
{ "resource": "" }
q49619
handler
train
function handler() { try { if (this.readyState === this.DONE) { var response = _buildResponse(this, options.fullResponse); // Resolve or reject promise given the response status. // HTTP status of 2xx is considered a success. if (this.status >= 200 && ...
javascript
{ "resource": "" }
q49620
_buildError
train
function _buildError(url, status, method, response) { var errorData = response || {}; errorData.status = status; errorData.url = url; errorData.method = method; return errorData; }
javascript
{ "resource": "" }
q49621
jsonp
train
function jsonp(options, successCallback, errorCallback) { /*jshint camelcase:false */ options = options || {}; // Define unique callback name. var uniqueName = 'callback_json' + (++counter); // Send all data (including method, api key and data) via GET // request params. var params = opti...
javascript
{ "resource": "" }
q49622
_fillAction
train
function _fillAction(entity, actionObj, actionType) { if (!(entity instanceof Scope) && !entity.id) { throw new Error('This entity does not have an ID.'); } var ret = actionObj; if (Utils.isArray(actionObj)) { ret = actionObj.map(function (singleAction) { return _fillAction(entit...
javascript
{ "resource": "" }
q49623
_useBrowserGeolocation
train
function _useBrowserGeolocation(options) { return (options && options.geolocation !== undefined)? options.geolocation : EVT.settings.geolocation; }
javascript
{ "resource": "" }
q49624
train
function (objData) { // Rename user object argument's *evrythngUser* property to // entity-standard-*id*. var args = arguments; if(objData.evrythngUser){ objData.id = objData.evrythngUser; delete objData.evrythngUser; } args[0] = objData; Entity.apply(this, args); }
javascript
{ "resource": "" }
q49625
_createAnonymousUser
train
function _createAnonymousUser() { var $this = this; return EVT.api({ url: this.path, method: 'post', params: { anonymous: true // must be set to create anonymous user }, data: {}, authorization: this.scope.apiKey }).then(function (access) { // Create User...
javascript
{ "resource": "" }
q49626
login
train
function login(options) { // Return promise and resolve once user info is retrieved. return new Promise(function (resolve, reject) { FB.login(function (response) { /*response = authResponse + status*/ _getUser(response).then(function (userResponse) { if(userResponse.user) { ...
javascript
{ "resource": "" }
q49627
_getUser
train
function _getUser(response) { if(response.status == 'connected') { // Return a Promise for the response with user details. return new Promise(function (resolve) { // Until here, `response` was FB's auth response. Here // we start to build bigger response by appending the Facebook's ...
javascript
{ "resource": "" }
q49628
authFacebook
train
function authFacebook(response) { var $this = this; return EVT.api({ url: '/auth/facebook', method: 'post', data: { access: { token: response.authResponse.accessToken } }, authorization: this.apiKey }).then(function (access) { // Create User Sc...
javascript
{ "resource": "" }
q49629
_authEvrythng
train
function _authEvrythng(credentials) { var $this = this; return EVT.api({ url: '/auth/evrythng', method: 'post', data: credentials, authorization: this.apiKey }).then(function (access) { // Once it is authenticated, get this user information as well. return EVT.api({ ...
javascript
{ "resource": "" }
q49630
_logoutFacebook
train
function _logoutFacebook(successCallback, errorCallback) { var $this = this; return Facebook.logout().then(function () { // If successful (always), also logout from Evrythng. return _logoutEvrythng.call($this, successCallback, errorCallback); }); }
javascript
{ "resource": "" }
q49631
readProduct
train
function readProduct() { if (!this.product) { throw new Error('Thng does not have a product.'); } if (!this.resource) { throw new Error('Thng does not have a resource.'); } return this.resource.scope.product(this.product).read(); }
javascript
{ "resource": "" }
q49632
_normalizeArguments
train
function _normalizeArguments(obj) { var args = arguments; if (!obj || Utils.isFunction(obj)) { args = Array.prototype.slice.call(arguments, 0); args.unshift({}); } // Split full path (/actions/_custom) - we get three parts: // 1) empty, 2) root path and 3) encoded action type name ...
javascript
{ "resource": "" }
q49633
thng
train
function thng(id) { // To create nested Resources, the collection itself needs // a resource. if(!this.resource) { throw new Error('This Entity does not have a Resource.'); } var path = this.resource.path + '/thngs'; return Resource.constructorFactory(path, EVT.Entity.Thng) .call(...
javascript
{ "resource": "" }
q49634
collection
train
function collection(id) { if(!this.resource) { throw new Error('This Entity does not have a Resource.'); } var path = this.resource.path + '/collections'; return Resource.constructorFactory(path, EVT.Entity.Collection) .call(this.resource.scope, id); }
javascript
{ "resource": "" }
q49635
train
function() { var userAgent = pgwBrowser.userAgent.toLowerCase(); // Check browser type for (i in browserData) { var browserRegExp = new RegExp(browserData[i].identifier.toLowerCase()); var browserRegExpResult = browserRegExp.exec(userAgent); ...
javascript
{ "resource": "" }
q49636
train
function(version) { var splitVersion = version.split('.', 2); pgwBrowser.browser.fullVersion = version; // Major version if (splitVersion[0]) { pgwBrowser.browser.majorVersion = parseInt(splitVersion[0]); } // Minor version ...
javascript
{ "resource": "" }
q49637
train
function() { var userAgent = pgwBrowser.userAgent.toLowerCase(); // Check browser type for (i in osData) { var osRegExp = new RegExp(osData[i].identifier.toLowerCase()); var osRegExpResult = osRegExp.exec(userAgent); if (osRegExpResul...
javascript
{ "resource": "" }
q49638
train
function(version, separator) { if (separator.substr(0, 1) == '[') { var splitVersion = version.split(new RegExp(separator, 'g'), 2); } else { var splitVersion = version.split(separator, 2); } if (separator != '.') { version...
javascript
{ "resource": "" }
q49639
train
function(init) { pgwBrowser.viewport.width = $(window).width(); pgwBrowser.viewport.height = $(window).height(); // Resize triggers if (typeof init == 'undefined') { if (resizeEvent == null) { $(window).trigger('PgwBrowser::StartResizi...
javascript
{ "resource": "" }
q49640
train
function() { if (typeof window.orientation == 'undefined') { if (pgwBrowser.viewport.width >= pgwBrowser.viewport.height) { pgwBrowser.viewport.orientation = 'landscape'; } else { pgwBrowser.viewport.orientation = 'portrait'; ...
javascript
{ "resource": "" }
q49641
getFirstProperty
train
function getFirstProperty(fields) { return function(record) { for (var i = 0; i < fields.length; i++) { var fieldValue = record[fields[i]]; if (!_.isEmpty(fieldValue)) { return fieldValue[0]; } } }; }
javascript
{ "resource": "" }
q49642
getUSADependencyOrCountryValue
train
function getUSADependencyOrCountryValue(record) { if ('dependency' === record.layer && !_.isEmpty(record.dependency)) { return record.dependency[0]; } else if ('country' === record.layer && !_.isEmpty(record.country)) { return record.country[0]; } if (!_.isEmpty(record.dependency_a)) { return recor...
javascript
{ "resource": "" }
q49643
train
function(bs, event, filePath) { const fileName = path.parse(filePath).base const fileExtension = path.extname(filePath) // Ignore change when filePath is junk if (junk.is(fileName) === true) return // Flush the cache no matter what event was send by Chokidar. // This ensures that we serve the latest files when...
javascript
{ "resource": "" }
q49644
train
function(routes, customFiles) { // Always ignore the following files const ignoredFiles = [ '**/CVS', '**/.git', '**/.svn', '**/.hg', '**/.lock-wscript', '**/.wafpickle-N' ] // Extract the path out of the routes const ignoredRoutes = routes.map((route) => route.path) // Return all ignored files re...
javascript
{ "resource": "" }
q49645
stringifyReplacerArr
train
function stringifyReplacerArr (key, value, stack, replacer) { var i, res // If the value has a toJSON method, call it to obtain a replacement value. if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') { value = value.toJSON(key) } switch (typeof value) { case 'objec...
javascript
{ "resource": "" }
q49646
stringifySimple
train
function stringifySimple (key, value, stack) { var i, res switch (typeof value) { case 'object': if (value === null) { return 'null' } if (typeof value.toJSON === 'function') { value = value.toJSON(key) // Prevent calling `toJSON` again if (typeof value !== 'obj...
javascript
{ "resource": "" }
q49647
callUri
train
function callUri(uri) { var iframe = document.createElement('iframe'); iframe.src = uri; iframe.style.display = 'none'; document.documentElement.appendChild(iframe); setTimeout(function () { return document.documentElement.removeChild(iframe); }, 0); }
javascript
{ "resource": "" }
q49648
getValueOfUnit
train
function getValueOfUnit(unitInput) { const unit = unitInput ? unitInput.toLowerCase() : 'ether'; var unitValue = unitMap[unit]; // eslint-disable-line if (typeof unitValue !== 'string') { throw new Error(`[ethjs-unit] the unit provided ${unitInput} doesn't exists, please use the one of the following units ${...
javascript
{ "resource": "" }
q49649
ToggleIcon
train
function ToggleIcon (props) { const { classes, offIcon, onIcon, on, ...other } = props return ( <div className={classes.root} {...other}> {React.cloneElement(offIcon, { className: classes.offIcon, style: { ...clipPath(on ? 'polygon(0% 0%, 0% 0%, 0% 0%)' : '...
javascript
{ "resource": "" }
q49650
type
train
function type(buffer) { if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47 && buffer[4] === 0x0D && buffer[5] === 0x0A && buffer[6] === 0x1A && buffer[7] === 0x0A) { return 'png'; } else if (buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[...
javascript
{ "resource": "" }
q49651
headers
train
function headers(buffer) { var head = {}; if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47 && buffer[4] === 0x0D && buffer[5] === 0x0A && buffer[6] === 0x1A && buffer[7] === 0x0A) { head['Content-Type'] = 'image/png'; } else if (buffer[0] === 0...
javascript
{ "resource": "" }
q49652
isEmpty
train
function isEmpty(files, dir, acc, opts) { var filter = opts.filter || isGarbageFile; for (const file of files) { const fp = path.join(dir, file); if (opts.dryRun && acc.indexOf(fp) !== -1) { continue; } if (filter(fp) === false) { return false; } } return true; }
javascript
{ "resource": "" }
q49653
postCompareFunc
train
function postCompareFunc(a, b) { var sortType = option.get('sorttype'); var diff = new Date(a.meta.pubdate) - new Date(b.meta.pubdate); return sortType === 'asc' ? diff : -diff; }
javascript
{ "resource": "" }
q49654
downloadDistantOrLoad
train
function downloadDistantOrLoad(fileUrl, f) { if (!fileUrl || !_.isString(fileUrl)) { return f(); } var filename = path.basename(url.parse(fileUrl).path); debug('downloading %s -> %s', fileUrl, filename); request({ url: fileUrl }, function (err, resp, body) { if (err) { ...
javascript
{ "resource": "" }
q49655
extendConf
train
function extendConf(conf, f) { if (_.isArray(conf.extends)) { async.reduce(conf.extends, conf, function(res, filePath, cb) { loadCheckbuildConf(filePath, function(err, conf) { /** * Do almost like _.defaultsDeep, but without merging arrays */ fun...
javascript
{ "resource": "" }
q49656
defaultsDeep
train
function defaultsDeep(config, defaults) { if (_.isPlainObject(config)) { return _.mapValues(_.defaults(config, defaults), function(val, index) { return defaultsDeep(_.get(config, index), _.get(defaults, index)); }); } return co...
javascript
{ "resource": "" }
q49657
train
function(key) { var bits = key.split('.'); var value = item; for (var i = 0; i < bits.length; i++) { value = value[bits[i]]; if (!value) return ''; } if (!value) return ''; if (typeof value === 'function') value = value(); if (typeof value === 'number' && value < 10) { retu...
javascript
{ "resource": "" }
q49658
oldConfigNames
train
function oldConfigNames(config) { const configuration = Object.assign({}, config); if (configuration.amqpUrl) { configuration.host = configuration.amqpUrl; } if (configuration.amqpPrefetch) { configuration.prefetch = configuration.amqpPrefetch; } if (configuration.amqpRequeue) { configuration....
javascript
{ "resource": "" }
q49659
envVars
train
function envVars(config) { const configuration = Object.assign({}, config); if (process.env.AMQP_URL && !configuration.host) { configuration.host = process.env.AMQP_URL; } if (process.env.LOCAL_QUEUE && !configuration.consumerSuffix) { configuration.consumerSuffix = process.env.LOCAL_QUEUE; } if (...
javascript
{ "resource": "" }
q49660
PathnameEnvironment
train
function PathnameEnvironment() { this.onPopState = this.onPopState.bind(this); this.useHistoryApi = !!(window.history && window.history.pushState && window.history.replaceState); Environment.call(this); }
javascript
{ "resource": "" }
q49661
LocalStorageKeyEnvironment
train
function LocalStorageKeyEnvironment(key) { this.key = key; var store = this.onStorage = this.onStorage.bind(this); var storage; try { storage = window.localStorage; storage.setItem(key, storage.getItem(key)); } catch (e) { storage = null; } this.storage = storage || { data: {}, getIt...
javascript
{ "resource": "" }
q49662
matchRoutes
train
function matchRoutes(routes, path, query, routerURLPatternOptions) { var match, page, notFound, queryObj = query, urlPatternOptions; if (!Array.isArray(routes)) { routes = [routes]; } path = path.split('?'); var pathToMatch = path[0]; var queryString = path[1]; if (queryString) { queryObj = qs.p...
javascript
{ "resource": "" }
q49663
createRouter
train
function createRouter(name, component) { return CreateReactClass({ mixins: [RouterMixin, RouteRenderingMixin], displayName: name, propTypes: { component: PropTypes.oneOfType([ PropTypes.string, PropTypes.element, PropTypes.func ]) }, getRoutes: function(pro...
javascript
{ "resource": "" }
q49664
train
function () { var parts; if (!this.queryString) return; parts = this.queryString.replace('?','').split('&'); each(parts, function (part) { var key = decodeURIComponent( part.split('=')[0] ), val = decodeURIComponent( part.split('=')[1] ); if ( part.indexOf( '=' ) === -1 ) retur...
javascript
{ "resource": "" }
q49665
train
function (nextRequest) { var exit, target, method; while(this._exits.length) { exit = this._exits.pop(); target = exit.target; method = exit.method; if (!(method in target)) { throw new Error("Can't call exit " + method + ' on target when changing uri to ' + request.uri); ...
javascript
{ "resource": "" }
q49666
train
function (request, options) { var action, target, method, emitter; while (this._actions.length) { action = this._actions.shift(); target = action.target; method = action.method; emitter = new ActionEmitter; if (!(method in target)) { throw new Error("Can't call action " +...
javascript
{ "resource": "" }
q49667
fixDay
train
function fixDay(days) { var s = [], i; for (i = 1; i < days.length; i++) { s.push(days[i]); } s.push(days[0]); return s; }
javascript
{ "resource": "" }
q49668
createTokens
train
function createTokens(format) { var tokens = [], pos = 0, match; while ((match = tokenRE.exec(format))) { if (match.index > pos) { // doesn't match any token, static string tokens.push(angular.extend({ value: format.substring(pos, match.index) }, definedTokens.string)); pos = match...
javascript
{ "resource": "" }
q49669
setDay
train
function setDay(date, day) { // we don't want to change month when changing date var month = date.getMonth(), diff = day - (date.getDay() || 7); // move to correct date date.setDate(date.getDate() + diff); // check month if (date.getMonth() != month) { if (diff > 0) { date.setDate(date.getDate() -...
javascript
{ "resource": "" }
q49670
_toCORMOType
train
function _toCORMOType(type) { if (typeof type === 'string') { const type_string = type.toLowerCase(); if (/^string\((\d+)\)$/.test(type_string)) { return new CormoTypesString(Number(RegExp.$1)); } switch (type_string) { case 'string': return ne...
javascript
{ "resource": "" }
q49671
getLeafOfPath
train
function getLeafOfPath(obj, path, create_object = true) { const parts = Array.isArray(path) ? path.slice(0) : path.split('.'); const last = parts.pop(); if (parts.length > 0) { if (create_object !== false) { for (const part of parts) { obj = obj[part] || (obj[part] = {});...
javascript
{ "resource": "" }
q49672
getPropertyOfPath
train
function getPropertyOfPath(obj, path) { const [child, last] = getLeafOfPath(obj, path, false); return child && last ? child[last] : undefined; }
javascript
{ "resource": "" }
q49673
setPropertyOfPath
train
function setPropertyOfPath(obj, path, value) { const [child, last] = getLeafOfPath(obj, path); if (child && last) { child[last] = value; } }
javascript
{ "resource": "" }
q49674
copy
train
function copy(patterns, dir, options, cb) { if (arguments.length < 3) { return invalid.apply(null, arguments); } if (typeof options === 'function') { cb = options; options = {}; } var opts = utils.extend({cwd: process.cwd()}, options); opts.cwd = path.resolve(opts.cwd); patterns = utils.arra...
javascript
{ "resource": "" }
q49675
copyEach
train
function copyEach(files, dir, options, cb) { if (arguments.length < 3) { return invalid.apply(null, arguments); } if (typeof options === 'function') { cb = options; options = {}; } var opts = utils.extend({}, options); if (typeof opts.cwd === 'undefined') { opts.cwd = process.cwd(); } ...
javascript
{ "resource": "" }
q49676
copyOne
train
function copyOne(file, dir, options, cb) { if (arguments.length < 3) { return invalid.apply(null, arguments); } if (typeof options === 'function') { cb = options; options = {}; } var opts = utils.extend({}, options); if (typeof opts.cwd === 'undefined') { opts.cwd = process.cwd(); } if...
javascript
{ "resource": "" }
q49677
copyBase
train
function copyBase(src, dest, options, callback) { if (typeof options !== 'object') { callback = options; options = {}; } if (arguments.length < 3) { return invalid.apply(null, arguments); } var fs = utils.fs; // graceful-fs (lazyily required) var opts = utils.extend({overwrite: true}, options)...
javascript
{ "resource": "" }
q49678
writeOpts
train
function writeOpts(opts) { return utils.extend({ flags: opts.flags || (opts.overwrite ? 'w' : 'wx') }, opts); }
javascript
{ "resource": "" }
q49679
mkdir
train
function mkdir(dest, cb) { var dir = path.dirname(path.resolve(dest)); utils.mkdirp(dir, function(err) { if (err && err.code !== 'EEXIST') { err.message = formatError('mkdirp cannot create directory', dir, err); return cb(new Error(err)); } cb(); }); }
javascript
{ "resource": "" }
q49680
handleError
train
function handleError(type, filepath, opts, cb) { return function(err) { switch (type) { case 'read': if (err.code === 'ENOENT') { err.message = formatError('file does not exist', filepath, err); } else { err.message = formatError('cannot read file', filepath, err); ...
javascript
{ "resource": "" }
q49681
invalidArgs
train
function invalidArgs(src, dest, options, cb) { // get the callback so we can give the correct errors // when src or dest is missing if (typeof dest === 'function') cb = dest; if (typeof src === 'function') cb = src; if (typeof cb !== 'function') { throw new TypeError('expected callback to be a function');...
javascript
{ "resource": "" }
q49682
parseRes
train
function parseRes (res, cb) { var body = ''; if ('setEncoding' in res) res.setEncoding('utf-8'); res.on('data', function (data) { body += data; if (body.length > 1e10) { // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQ res.connection.destroy(); res.writeHead(41...
javascript
{ "resource": "" }
q49683
layouts
train
function layouts(file, layoutCollection, options, transformFn) { if (typeOf(file) !== 'object') { throw new TypeError('expected file to be an object'); } if (typeOf(layoutCollection) !== 'object' && !(layoutCollection instanceof Map)) { throw new TypeError('expected layouts collection to be an object'); ...
javascript
{ "resource": "" }
q49684
resolveLayout
train
function resolveLayout(file, layout, options, regex, name) { if (typeOf(layout.contents) !== 'buffer') { throw new Error('expected layout.contents to be a buffer'); } // reset lastIndex, since regex is cached regex.lastIndex = 0; const layoutString = toString(layout, options); if (!regex.test(layoutSt...
javascript
{ "resource": "" }
q49685
getLayoutName
train
function getLayoutName(file, options) { const defaultLayout = options.defaultLayout; const prop = options.layoutProp || 'layout'; const name = file[prop]; if (typeof name === 'undefined' || name === true || name === defaultLayout) { return defaultLayout; } if (!name || ['false', 'null', 'nil', 'none', '...
javascript
{ "resource": "" }
q49686
inHistory
train
function inHistory(file, layout, options) { return !options.disableHistory && file.layoutStack.indexOf(layout) !== -1; }
javascript
{ "resource": "" }
q49687
getLayout
train
function getLayout(collection, name) { if (!name) return; if (collection instanceof Map) { for (const [key, view] of collection) { if (name === key) { return view; } if (!view.path) continue; if (!view.hasPath) { return getView(collection, name); } if (view.ha...
javascript
{ "resource": "" }
q49688
createDelimiterRegex
train
function createDelimiterRegex(options) { const opts = Object.assign({}, options); let tagname = options.tagname; let layoutDelims = options.delims || options.layoutDelims || `{% (${tagname}) %}`; let key = tagname; if (layoutDelims) key += layoutDelims.toString(); if (layouts.memo.has(key)) { return la...
javascript
{ "resource": "" }
q49689
define
train
function define(obj, key, val) { Reflect.defineProperty(obj, key, { configurable: true, enumerable: false, writeable: true, value: val }); }
javascript
{ "resource": "" }
q49690
workerIterator
train
function workerIterator (callback) { Object.keys(cluster.workers).forEach((index) => callback(cluster.workers[index])) }
javascript
{ "resource": "" }
q49691
deliverMessage
train
function deliverMessage (message) { workerIterator((worker) => { if (this.process.pid === worker.process.pid) { return } debug('delivering message to %s', worker.process.pid) worker.send(message) }) }
javascript
{ "resource": "" }
q49692
deliverMessage
train
function deliverMessage (handle, topic, payload) { if (handle === 'broadcast') { const channel = ChannelsManager.resolve(topic) if (!channel) { return debug('broadcast topic %s cannot be handled by any channel', topic) } channel.clusterBroadcast(topic, payload) return } debug('droppin...
javascript
{ "resource": "" }
q49693
getMachineEnv
train
function getMachineEnv(machine) { var child = require('child_process'); var result = child.spawnSync('docker-machine', ['env', machine]); if (result.status === 0) { var str = result.stdout.toString(); var expr = str .replace(new RegExp('export ', 'g'), 'envs.') .split('\n') .filter(func...
javascript
{ "resource": "" }
q49694
Channel
train
function Channel(bus, name, local, remote) { events.EventEmitter.call(this); this.bus = bus; this.name = name; this.type = 'channel'; this.id = 'bus:channel:' + name; this.logger = bus.logger.withTag(name); this.local = local || 'local'; this.remote = remote || 'remote'; this.handlers = { '1': th...
javascript
{ "resource": "" }
q49695
train
function(err, resp) { if (err) { _this.emit('error', 'failed to upload script ' + script.name + ' to redis: ' + err); return; } else { // cluster will send back the hash as many times as there are nodes script.hash = Array.isArray(resp) ? res...
javascript
{ "resource": "" }
q49696
Connection
train
function Connection(index, bus) { events.EventEmitter.call(this); this.setMaxListeners(0); // remove limit on listeners this.index = index; this.id = bus.id + ":connection:" + index; this.urls = bus.options.redis; this.redisOptions = bus.options.redisOptions || {}; this.layout = bus.options.layout; this...
javascript
{ "resource": "" }
q49697
WSMuxChannel
train
function WSMuxChannel(id, mux) { EventEmitter.call(this); this.id = id; this.mux = mux; this.closed = false; this.url = this.mux.url; // websocket-stream relies on this method this.__defineGetter__('readyState', function() { return this.mux._readyState(); }); // hooks for websocket-stream var ...
javascript
{ "resource": "" }
q49698
WSPool
train
function WSPool(bus, options) { events.EventEmitter.call(this); this.setMaxListeners(0); this.bus = bus; this.logger = bus.logger.withTag(bus.id+':wspool'); this.closed = false; this.pool = {}; this.notificationChannels = {}; this.options = options || {}; this.options.secret = this.options.secret || ...
javascript
{ "resource": "" }
q49699
Service
train
function Service(bus, name) { events.EventEmitter.call(this); this.bus = bus; this.name = name; this.logger = bus.logger.withTag(name); this.type = "service"; this.id = "service:" + name; this.replyTo = this.id + ":replyTo:" + crypto.randomBytes(8).toString("hex"); this.pendingReplies = {}; this.reque...
javascript
{ "resource": "" }