_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, 'app.js'),
stylesUrl: path.join(relativeAssetsDir, 'app.css')
};
// If using inline assets, load files and strings
if (inlineAssets) {
assets.inlineScripts = loadFile(path.join(distDir, 'app.js'));
assets.inlineStyles = loadFile(path.join(distDir, 'app.inline.css'));
}
// If using CDN, return remote urls
if (cdn) {
assets.scriptsUrl = `https://unpkg.com/mochawesome-report-generator@${pkg.version}/dist/app.js`;
assets.stylesUrl = `https://unpkg.com/mochawesome-report-generator@${pkg.version}/dist/app.css`;
}
// In DEV mode, return local urls
if (dev) {
assets.scriptsUrl = 'http://localhost:8080/app.js';
assets.stylesUrl = 'http://localhost:8080/app.css';
}
// Copy the assets if needed
if (!dev && !cdn && !inlineAssets) {
copyAssets(reportOptions);
}
return assets;
}
|
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.saveHtml) {
return { reportOptions };
}
// Get the assets
const assets = getAssets(reportOptions);
// Render basic template to string
// const { styles, scripts } = assets;
const renderedHtml = render(React.createElement(MainHTML, {
data,
options: reportOptions,
title: reportOptions.reportPageTitle,
useInlineAssets: reportOptions.inlineAssets && !reportOptions.cdn,
...assets
}));
const html = `<!doctype html>\n${renderedHtml}`;
return { html, reportOptions };
}
|
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)
.then(savedHtml => (autoOpen && openFile(savedHtml)) || savedHtml)
: null);
savePromises.push(saveJson
? saveFile(jsonFile, JSON.stringify(data, null, 2), overwrite)
: null);
return Promise.all(savePromises);
}
|
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 ]);
} else {
err = ERRORS.GENERIC;
}
}
// If the file was loaded successfully,
// validate the json against the TestReport schema
if (data) {
const validationResult = t.validate(data, types.TestReport, { strict: true });
if (!validationResult.isValid()) {
err = ERRORS.INVALID_JSON(validationResult.errors);
} else {
validFiles += 1;
}
}
return {
filename: file,
data,
err
};
}
|
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.readdirSync(arg).map(file => path.join(arg, file)),
files
);
}
// If `statSync` failed, validating will handle the error
// If the argument is a file, check if its a JSON file before validating
if (!stats || JsonFileRegex.test(arg)) {
acc.push(validateFile(arg));
}
return acc;
}, files);
}
|
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 ignore else */
if (validFiles > 1 || args.timestamp !== false) {
args.overwrite = false;
}
const promises = files.map(file => {
// Files with errors we just resolve
if (file.err) {
return Promise.resolve(file);
}
// Valid files get created but first we need to pass correct filename option
// Default value is name of file
// If a filename option was provided, all files get that name
const reportFilename = getReportFilename(file, args);
return report.create(file.data, Object.assign({}, args, { reportFilename }));
});
return Promise.all(promises)
.then(handleResolved)
.catch(handleError);
}
|
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];
paramsStr.push((noEncode? key : encodeURIComponent(key)) +
'=' + (noEncode? this.escapeSpecials(value) : encodeURIComponent(value)));
}
}
// Build string from the array.
return paramsStr.join('&');
} else {
return params;
}
}
|
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);
return new Promise(function (resolve, reject) {
window.navigator.geolocation.getCurrentPosition(function (position) {
resolve(position);
}, function (err) {
var errorMessage = 'Geolocation: ';
if(err.code === 1) {
errorMessage = 'You didn\'t share your location.';
} else if(err.code === 2) {
errorMessage = 'Couldn\'t detect your current location.';
} else if(err.code === 3) {
errorMessage = 'Retrieving position timed out.';
} else {
errorMessage = 'Unknown error.';
}
reject(errorMessage);
}, geolocationOptions);
});
}else{
return new Promise(function (resolve, reject) {
reject('Your browser\/environment doesn\'t support geolocation.');
});
}
}
|
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 (dependency) {
installArgs.push(require(dependency));
});
}
plugin.install.apply(plugin, installArgs);
return this;
} else {
throw new TypeError('Plugin must implement \'install()\' method.');
}
}
|
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();
}
}
}
return parsed;
}
|
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, options.headers[header]);
}
}
// Set timeout.
if (options.timeout > 0) {
xhr.timeout = options.timeout;
}
return xhr;
}
|
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 && this.status < 300) {
if (successCallback) {
Logger.warnCallbackDeprecation();
successCallback(response);
}
resolve(response);
} else {
errorHandler(response);
}
}
} catch (exception) {
// Do nothing, will be handled by ontimeout.
}
}
|
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 = options.params || {};
params.callback = uniqueName;
params.access_token = options.authorization;
params.method = options.method || 'get';
params.data = JSON.stringify(options.data);
options.params = params;
options.apiUrl = options.apiUrl && options.apiUrl.replace('//api', '//js-api');
// Evrythng REST API default endpoint does not provide JSON-P
// support, which '//js-api.evrythng.com' does.
var url = Utils.buildUrl(options);
// Return a promise and resolve/reject it in the callback function.
return new Promise(function(resolve, reject) {
// Attach callback as a global method. Evrythng's REST API error
// responses always have a status and array of errors.
window[uniqueName] = function(response){
if (response.errors && response.status) {
var errorData = _buildError(url, response.status, params.method, response);
Logger.error(errorData);
if(errorCallback) {
Logger.warnCallbackDeprecation();
errorCallback(errorData);
}
reject(errorData);
}else {
if(successCallback) {
Logger.warnCallbackDeprecation();
successCallback(response);
}
try {
response = JSON.parse(response);
} catch(e){}
resolve(response);
}
// Remove callback from window.
try {
delete window[uniqueName];
} catch (e) {}
window[uniqueName] = null;
};
_load(url, reject);
});
}
|
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(entity, singleAction, actionType);
});
} else {
ret.type = actionType !== 'all' && actionType || actionObj.type || '';
_addEntityIdentifier(entity, ret);
}
return ret;
}
|
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 Scope
return new EVT.User({
id: access.evrythngUser,
apiKey: access.evrythngApiKey,
type: 'anonymous'
}, $this.scope);
});
}
|
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) {
/*userResponse = authResponse + status + user*/
resolve(userResponse);
} else {
// Reject login promise if the user canceled the FB login.
reject(userResponse);
}
});
}, options);
});
}
|
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
// user info in the `user` property.
FB.api('/me', {
fields: [
'id',
'first_name',
'last_name' ,
'gender',
'link',
'picture',
'locale',
'name',
'timezone',
'updated_time',
'verified'
].toString()
}, function (userInfo) {
resolve(Utils.extend(response, { user: userInfo }));
});
});
}else{
// Return an already resolved promise.
return new Promise(function (resolve) {
resolve(response);
});
}
}
|
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 Scope with the user information and Api Key returned
// from the REST API.
var user = new EVT.User({
id: access.evrythngUser,
apiKey: access.evrythngApiKey
}, $this);
// Fetch user dto from the platform and then
// return initial response
// TODO: Introduce proper read when DEV-190 merged
return EVT.api({
url: '/users/' + user.id,
authorization: user.apiKey
}).then(function(userDetails) {
// Prepare resolve object. Move Facebook user data to
// 'user.facebook' object
Utils.extend(user, { facebook: response.user }, true);
// Merge user data from the platform to User Scope
Utils.extend(user, userDetails, true);
response.user = user;
return response;
});
});
}
|
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({
url: '/users/' + access.evrythngUser,
authorization: access.evrythngApiKey
}).then(function (userInfo) {
// Keep nested success handler because we also need the *access*
// object returned form the previous call to create the User Scope.
var userObj = Utils.extend(userInfo, {
id: access.evrythngUser,
apiKey: access.evrythngApiKey
});
// Create User Scope
var user = new EVT.User(userObj, $this);
return { user: user };
});
});
}
|
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
var url = this.path.split('/');
args[0].url = '/' + url[1];
args[0].params = Utils.extend(args[0].params, {
filter: {
name: decodeURIComponent(url[2])
}
});
return args;
}
|
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(this.resource.scope, id);
}
|
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);
if (browserRegExpResult != null && browserRegExpResult[1]) {
pgwBrowser.browser.name = browserData[i].name;
pgwBrowser.browser.group = browserData[i].group;
// Check version
if (browserData[i].versionIdentifier) {
var versionRegExp = new RegExp(browserData[i].versionIdentifier.toLowerCase());
var versionRegExpResult = versionRegExp.exec(userAgent);
if (versionRegExpResult != null && versionRegExpResult[1]) {
setBrowserVersion(versionRegExpResult[1]);
}
} else {
setBrowserVersion(browserRegExpResult[1]);
}
break;
}
}
return true;
}
|
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
if (splitVersion[1]) {
pgwBrowser.browser.minorVersion = parseInt(splitVersion[1]);
}
return true;
}
|
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 (osRegExpResult != null) {
pgwBrowser.os.name = osData[i].name;
pgwBrowser.os.group = osData[i].group;
// Version defined
if (osData[i].version) {
setOsVersion(osData[i].version, (osData[i].versionSeparator) ? osData[i].versionSeparator : '.');
// Version detected
} else if (osRegExpResult[1]) {
setOsVersion(osRegExpResult[1], (osData[i].versionSeparator) ? osData[i].versionSeparator : '.');
// Version identifier
} else if (osData[i].versionIdentifier) {
var versionRegExp = new RegExp(osData[i].versionIdentifier.toLowerCase());
var versionRegExpResult = versionRegExp.exec(userAgent);
if (versionRegExpResult != null && versionRegExpResult[1]) {
setOsVersion(versionRegExpResult[1], (osData[i].versionSeparator) ? osData[i].versionSeparator : '.');
}
}
break;
}
}
return true;
}
|
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 = version.replace(new RegExp(separator, 'g'), '.');
}
pgwBrowser.os.fullVersion = version;
// Major version
if (splitVersion[0]) {
pgwBrowser.os.majorVersion = parseInt(splitVersion[0]);
}
// Minor version
if (splitVersion[1]) {
pgwBrowser.os.minorVersion = parseInt(splitVersion[1]);
}
return true;
}
|
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::StartResizing');
} else {
clearTimeout(resizeEvent);
}
resizeEvent = setTimeout(function() {
$(window).trigger('PgwBrowser::StopResizing');
clearTimeout(resizeEvent);
resizeEvent = null;
}, 300);
}
return true;
}
|
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';
}
} else {
switch(window.orientation) {
case -90:
case 90:
pgwBrowser.viewport.orientation = 'landscape';
break;
default:
pgwBrowser.viewport.orientation = 'portrait';
break;
}
}
// Orientation trigger
$(window).trigger('PgwBrowser::OrientationChange');
return true;
}
|
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 record.dependency_a[0];
} else if (!_.isEmpty(record.dependency)) {
return record.dependency[0];
}
return record.country_a[0];
}
|
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 the user reloads the site.
cache.flush(filePath)
const styleExtensions = [
'.css',
'.scss',
'.sass',
'.less'
]
// Reload stylesheets when the file extension is a known style extension
if (styleExtensions.includes(fileExtension) === true) return bs.reload('*.css')
const imageExtensions = [
'.png',
'.jpg',
'.jpeg',
'.svg',
'.gif',
'.webp'
]
// Reload images when the file extension is a known image extension supported by Browsersync
if (imageExtensions.includes(fileExtension) === true) return bs.reload(`*${ fileExtension }`)
bs.reload()
}
|
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
return [
...ignoredFiles,
...ignoredRoutes,
...customFiles
]
}
|
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 'object':
if (value === null) {
return 'null'
}
for (i = 0; i < stack.length; i++) {
if (stack[i] === value) {
return '"[Circular]"'
}
}
if (Array.isArray(value)) {
if (value.length === 0) {
return '[]'
}
stack.push(value)
res = '['
// Use null as placeholder for non-JSON values.
for (i = 0; i < value.length - 1; i++) {
const tmp = stringifyReplacerArr(i, value[i], stack, replacer)
res += tmp !== undefined ? tmp : 'null'
res += ','
}
const tmp = stringifyReplacerArr(i, value[i], stack, replacer)
res += tmp !== undefined ? tmp : 'null'
res += ']'
stack.pop()
return res
}
if (replacer.length === 0) {
return '{}'
}
stack.push(value)
res = '{'
var separator = ''
for (i = 0; i < replacer.length; i++) {
if (typeof replacer[i] === 'string' || typeof replacer[i] === 'number') {
key = replacer[i]
const tmp = stringifyReplacerArr(key, value[key], stack, replacer)
if (tmp !== undefined) {
res += `${separator}"${strEscape(key)}":${tmp}`
separator = ','
}
}
}
res += '}'
stack.pop()
return res
case 'string':
return `"${strEscape(value)}"`
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null'
case 'boolean':
return value === true ? 'true' : 'false'
}
}
|
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 !== 'object') {
return stringifySimple(key, value, stack)
}
if (value === null) {
return 'null'
}
}
for (i = 0; i < stack.length; i++) {
if (stack[i] === value) {
return '"[Circular]"'
}
}
if (Array.isArray(value)) {
if (value.length === 0) {
return '[]'
}
stack.push(value)
res = '['
// Use null as placeholder for non-JSON values.
for (i = 0; i < value.length - 1; i++) {
const tmp = stringifySimple(i, value[i], stack)
res += tmp !== undefined ? tmp : 'null'
res += ','
}
const tmp = stringifySimple(i, value[i], stack)
res += tmp !== undefined ? tmp : 'null'
res += ']'
stack.pop()
return res
}
const keys = insertSort(Object.keys(value))
if (keys.length === 0) {
return '{}'
}
stack.push(value)
var separator = ''
res = '{'
for (i = 0; i < keys.length; i++) {
key = keys[i]
const tmp = stringifySimple(key, value[key], stack)
if (tmp !== undefined) {
res += `${separator}"${strEscape(key)}":${tmp}`
separator = ','
}
}
res += '}'
stack.pop()
return res
case 'string':
return `"${strEscape(value)}"`
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
// Convert the numbers implicit to a string instead of explicit.
return isFinite(value) ? String(value) : 'null'
case 'boolean':
return value === true ? 'true' : 'false'
}
}
|
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 ${JSON.stringify(unitMap, null, 2)}`);
}
return new BN(unitValue, 10);
}
|
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%)' : 'polygon(0% 200%, 0% 0%, 200% 0%)'),
visibility: !on || clipPathSupported() ? 'visible' : 'hidden'
}
})}
{React.cloneElement(onIcon, {
className: classes.onIcon,
style: {
...clipPath(on ? 'polygon(100% -100%, 100% 100%, -100% 100%)' : 'polygon(100% 100%, 100% 100%, 100% 100%)'),
visibility: on || clipPathSupported() ? 'visible' : 'hidden'
}
})}
</div>
)
}
|
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[buffer.length - 2] === 0xFF && buffer[buffer.length - 1] === 0xD9) {
return 'jpg';
} else if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46 &&
buffer[3] === 0x38 && (buffer[4] === 0x39 || buffer[4] === 0x37) &&
buffer[5] === 0x61) {
return 'gif';
} else if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46 &&
buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50) {
return 'webp';
// deflate: recklessly assumes contents are PBF.
} else if (buffer[0] === 0x78 && buffer[1] === 0x9C) {
return 'pbf';
// gzip: recklessly assumes contents are PBF.
} else if (buffer[0] === 0x1F && buffer[1] === 0x8B) {
return 'pbf';
}
return false;
}
|
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] === 0xFF && buffer[1] === 0xD8 &&
buffer[buffer.length - 2] === 0xFF && buffer[buffer.length - 1] === 0xD9) {
head['Content-Type'] = 'image/jpeg';
} else if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46 &&
buffer[3] === 0x38 && (buffer[4] === 0x39 || buffer[4] === 0x37) &&
buffer[5] === 0x61) {
head['Content-Type'] = 'image/gif';
} else if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46 &&
buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50) {
head['Content-Type'] = 'image/webp';
// deflate: recklessly assumes contents are PBF.
} else if (buffer[0] === 0x78 && buffer[1] === 0x9C) {
head['Content-Type'] = 'application/x-protobuf';
head['Content-Encoding'] = 'deflate';
// gzip: recklessly assumes contents are PBF.
} else if (buffer[0] === 0x1F && buffer[1] === 0x8B) {
head['Content-Type'] = 'application/x-protobuf';
head['Content-Encoding'] = 'gzip';
}
return head;
}
|
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) {
return f(err);
}
if (resp.statusCode < 200 || resp.statusCode >= 300) {
return f(new Error('Invalid HTTP Status code "' + resp.statusCode + '" for "' + fileUrl + '"'));
}
fs.writeFileSync(path.resolve(process.cwd(), filename), body);
f();
});
}
|
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
*/
function defaultsDeep(config, defaults) {
if (_.isPlainObject(config)) {
return _.mapValues(_.defaults(config, defaults), function(val, index) {
return defaultsDeep(_.get(config, index), _.get(defaults, index));
});
}
return config || defaults;
}
cb(err, defaultsDeep(res, conf));
});
}, f);
} else {
f(null, conf);
}
}
|
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 config || defaults;
}
|
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) {
return '0' + value;
}
return value;
}
|
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.requeue = configuration.amqpRequeue;
}
if (configuration.amqpTimeout) {
configuration.timeout = configuration.amqpTimeout;
}
return 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 (process.env.AMQP_DEBUG && !configuration.transport) {
configuration.transport = console;
}
return configuration;
}
|
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: {},
getItem: function(itemKey) {return this.data[itemKey]; },
setItem: function(itemKey, val) {
this.data[itemKey] = val;
clearTimeout(this.storeEvent);
this.storeEvent = setTimeout(store, 1);
}
};
Environment.call(this);
}
|
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.parse(queryString);
}
for (var i = 0, len = routes.length; i < len; i++) {
var current = routes[i];
// Simply skip null or undefined to allow ternaries in route definitions
if (!current) continue;
invariant(
current.props.handler !== undefined && current.props.path !== undefined,
"Router should contain either Route or NotFound components as routes");
if (current.props.path) {
// Allow passing compiler options to url-pattern, see
// https://github.com/snd/url-pattern#customize-the-pattern-syntax
// Note that this blows up if you provide an empty object on a regex path
urlPatternOptions = null;
if (Array.isArray(current.props.urlPatternOptions) || current.props.path instanceof RegExp) {
// If an array is passed, it takes precedence - assumed these are regexp keys
urlPatternOptions = current.props.urlPatternOptions;
} else if (routerURLPatternOptions || current.props.urlPatternOptions) {
urlPatternOptions = assign({}, routerURLPatternOptions, current.props.urlPatternOptions);
}
// matchKeys is deprecated
// FIXME remove this block in next minor version
if(current.props.matchKeys) {
urlPatternOptions = current.props.matchKeys;
warning(false,
'`matchKeys` is deprecated; please use the prop `urlPatternOptions` instead. See the CHANGELOG for details.');
}
var cacheKey = current.props.path + (urlPatternOptions ? JSON.stringify(urlPatternOptions) : '');
var pattern = patternCache[cacheKey];
if (!pattern) {
pattern = patternCache[cacheKey] = new URLPattern(current.props.path, urlPatternOptions);
}
if (!page) {
match = pattern.match(pathToMatch);
if (match) {
page = current;
}
// Backcompat fix in 0.27: regexes in url-pattern no longer return {_: matches}
if (match && current.props.path instanceof RegExp && !match._ && Array.isArray(match)) {
match = {_: match};
}
// Backcompat fix; url-pattern removed the array wrapper on wildcards
if (match && match._ != null && !Array.isArray(match._)) {
match._ = [match._];
}
}
}
if (!notFound && current.props.path === null) {
notFound = current;
}
}
return new Match(
pathToMatch,
page ? page : notFound ? notFound : null,
match,
queryObj,
(urlPatternOptions || {}).namedSegmentValueDecoders
);
}
|
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(props) {
return props.children;
},
getDefaultProps: function() {
return {
component: component
};
},
render: function() {
// Render the Route's handler.
var handler = this.renderRouteHandler();
if (!this.props.component) {
return handler;
} else {
// Pass all props except this component to the Router (containing div/body) and the children,
// which are swapped out by the route handler.
var props = assign({}, this.props);
props = omit(props, PROP_KEYS);
return React.createElement(this.props.component, props, handler);
}
}
});
}
|
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 ) return;
this._applyQueryParam( key, val );
}, this);
}
|
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);
}
target[method].call(target, nextRequest);
}
}
|
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 " + method + ' on target for uri ' + request.uri);
}
this._emitters.push(emitter);
target[method].call(target, request, options, emitter);
}
}
|
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.index;
}
if (match.index == pos) {
if (match[1]) {
// sss
tokens.push(angular.extend({
value: match[1]
}, definedTokens.string));
tokens.push(definedTokens.sss);
} else if (match[2]) {
// escaped string
tokens.push(angular.extend({
value: match[2].replace("''", "'")
}, definedTokens.string));
} else if (definedTokens[match[0]].name == "timezone") {
// static timezone
var tz = SYS_TIMEZONE;
if (definedTokens[match[0]].colon) {
tz = insertColon(tz);
}
tokens.push(angular.extend({
value: tz
}, definedTokens[match[0]]));
} else {
// other tokens
tokens.push(definedTokens[match[0]]);
}
pos = tokenRE.lastIndex;
}
}
if (pos < format.length) {
tokens.push(angular.extend({
value: format.substring(pos)
}, definedTokens.string));
}
return tokens;
}
|
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() - 7);
} else {
date.setDate(date.getDate() + 7);
}
}
}
|
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 new CormoTypesString();
case 'number':
return new CormoTypesNumber();
case 'boolean':
return new CormoTypesBoolean();
case 'integer':
return new CormoTypesInteger();
case 'geopoint':
return new CormoTypesGeoPoint();
case 'date':
return new CormoTypesDate();
case 'object':
return new CormoTypesObject();
case 'recordid':
return new CormoTypesRecordID();
case 'text':
return new CormoTypesText();
}
throw new Error(`unknown type: ${type}`);
}
else if (type === String) {
return new CormoTypesString();
}
else if (type === Number) {
return new CormoTypesNumber();
}
else if (type === Boolean) {
return new CormoTypesBoolean();
}
else if (type === Date) {
return new CormoTypesDate();
}
else if (type === Object) {
return new CormoTypesObject();
}
if (typeof type === 'function') {
return new type();
}
return type;
}
|
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] = {});
}
}
else {
for (const part of parts) {
obj = obj[part];
if (!obj) {
return [undefined, undefined];
}
}
}
}
return [obj, last];
}
|
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.arrayify(patterns);
if (!utils.hasGlob(patterns)) {
copyEach(patterns, dir, opts, cb);
return;
}
opts.patterns = patterns;
if (!opts.srcBase) {
opts.srcBase = path.resolve(opts.cwd, utils.parent(patterns));
}
utils.glob(patterns, opts, function(err, files) {
if (err) {
cb(err);
return;
}
copyEach(files, dir, opts, cb);
});
}
|
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();
}
if (!opts.srcBase && opts.patterns) {
opts.srcBase = path.resolve(opts.cwd, utils.parent(opts.patterns));
}
utils.each(files, function(filename, next) {
var filepath = path.resolve(opts.cwd, filename);
if (utils.isDirectory(filepath)) {
next()
return;
}
copyOne(filepath, dir, opts, next);
}, function(err, arr) {
if (err) {
cb(err);
return;
}
cb(null, arr.filter(Boolean));
});
}
|
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 (typeof file === 'string') {
file = path.resolve(opts.cwd, file);
}
if (!opts.srcBase && opts.patterns) {
opts.srcBase = path.resolve(opts.cwd, utils.parent(opts.patterns));
}
toDest(dir, file, opts, function(err, out) {
if (err) {
cb(err);
return;
}
base(file, out.path, opts, function(err) {
if (err) {
cb(err);
return;
}
cb(null, out);
});
});
}
|
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);
var cb = once(callback);
var listener = once(ws);
src = path.resolve(src);
var rs = fs.createReadStream(src)
.on('error', handleError('read', src, opts, cb))
.once('readable', listener)
.on('end', listener);
function ws() {
mkdir(dest, function(err) {
if (err) return cb(err);
rs.pipe(fs.createWriteStream(dest, writeOpts(opts))
.on('error', handleError('write', dest, opts, cb))
.on('close', handleClose(src, dest, cb)));
});
}
}
|
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);
}
break;
case 'write':
if (!opts.overwrite && err.code === 'EEXIST') {
return cb();
}
err.message = formatError('cannot write to', filepath, err);
break;
}
cb(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');
}
if (typeof src !== 'string') {
return cb(new TypeError('expected "src" to be a string'));
}
if (typeof dest !== 'string') {
return cb(new TypeError('expected "dest" to be a string'));
}
}
|
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(413, {'Content-Type': 'text/plain'});
res.end('req body too large');
return cb(new Error('body overflow'));
}
});
res.on('end', function () {
cb(null, body);
});
}
|
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');
}
if (typeOf(file.contents) !== 'buffer') {
throw new TypeError('expected file.contents to be a buffer');
}
if (typeof options === 'function') {
transformFn = options;
options = null;
}
const opts = Object.assign({ tagname: 'body' }, options, file.options);
const regex = createDelimiterRegex(opts);
let name = getLayoutName(file, opts);
let layout;
let n = 0;
if (!name) return file;
define(file, 'layoutStack', file.layoutStack || []);
// recursively resolve layouts
while ((layout = getLayout(layoutCollection, name))) {
if (inHistory(file, layout, opts)) break;
// if a function is passed, call it on the file before resolving the next layout
if (typeof transformFn === 'function') {
transformFn(file, layout);
}
file.layoutStack.push(layout);
name = resolveLayout(file, layout, opts, regex, name);
n++;
}
if (n === 0) {
let filename = file.relative || file.path;
throw new Error(`layout "${name}" is defined on "${filename}" but cannot be found`);
}
return file;
}
|
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(layoutString)) {
throw new Error(`cannot find tag "${regex.source}" in layout "${name}"`);
}
const fileString = toString(file, options);
let str;
if (options.preserveWhitespace === true) {
const re = new RegExp('(?:^(\\s+))?' + regex.source, 'gm');
let lines;
str = layoutString.replace(re, function(m, whitespace) {
if (whitespace) {
lines = lines || fileString.split('\n'); // only split once, JIT
return lines.map(line => whitespace + line).join('\n');
}
return fileString;
});
} else {
str = Buffer.from(layoutString.replace(regex, () => fileString));
}
file.contents = Buffer.from(str);
return getLayoutName(layout, options);
}
|
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', 'undefined'].includes(name.toLowerCase())) {
return false;
}
return name;
}
|
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.hasPath(name)) {
return view;
}
}
return;
}
for (const key of Object.keys(collection)) {
const view = collection[key];
if (name === key) {
return view;
}
if (!view.path) continue;
if (!view.hasPath) {
return getView(collection, name);
}
if (view.hasPath(name)) {
return view;
}
}
}
|
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 layouts.memo.get(key);
}
if (layoutDelims instanceof RegExp) {
layouts.memo.set(key, layoutDelims);
return layoutDelims;
}
if (Array.isArray(layoutDelims)) {
layoutDelims = `${opts.layoutDelims[0]} (${tagname}) ${opts.layoutDelims[1]}`;
}
if (typeof layoutDelims !== 'string') {
throw new TypeError('expected options.layoutDelims to be a string, array or regex');
}
const regex = new RegExp(layoutDelims, 'g');
layouts.memo.set(key, regex);
return regex;
}
|
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('dropping packet, since %s handle is not allowed', handle)
}
|
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(function (line) {
return line[0] !== '#';
}).join(';')
var envs = {};
eval(expr);
return envs;
} else {
throw Error(result.stderr)
}
}
|
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': this._onRemoteConnect,
'2': this._onMessage,
'3': this._onRemoteDisconnect,
'4': this._onEnd
}
}
|
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) ? resp[0] : resp;
}
if (--dones === 0) {
_this.online = true;
_this.logger.isDebug() && _this.logger.debug("bus is online");
_this.emit('online');
}
}
|
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.driver = bus.driver;
this._logger = bus.logger.withTag(this.id);
this.connected = false;
this.ready = 0;
this.pendingCommands = [];
this.subscribers = {};
}
|
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 _this = this;
this.on('open', function() {
_this.onopen && _this.onopen.apply(_this, arguments);
});
this.on('close', function() {
_this.onclose && _this.onclose.apply(_this, arguments);
});
this.on('error', function() {
_this.onerror && _this.onerror.apply(_this, arguments);
});
this.on('message', function() {
arguments[0] = {data: arguments[0]}
_this.onmessage && _this.onmessage.apply(_this, arguments);
});
}
|
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 || 'notsosecret';
if (!this.options.poolSize || this.options.poolSize <= 0) {
this.options.poolSize = 10;
}
this.options.replaceDelay = this.options.replaceDelay || 5000;
this.options.urls = this.options.urls || [];
this._setupPool();
}
|
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.requesters = {};
this.inflight = 0;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.