_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q55000
|
oauthErrorResponder
|
train
|
function oauthErrorResponder(req, res, err) {
var accepts = req.accepts(['html', 'json']);
var config = req.app.get('stormpathConfig');
if (accepts === 'json') {
return writeJsonError(res, err);
}
return renderLoginFormWithError(req, res, config, err);
}
|
javascript
|
{
"resource": ""
}
|
q55001
|
defaultUnverifiedHtmlResponse
|
train
|
function defaultUnverifiedHtmlResponse(req, res) {
var config = req.app.get('stormpathConfig');
res.redirect(302, config.web.login.uri + '?status=unverified');
}
|
javascript
|
{
"resource": ""
}
|
q55002
|
defaultAutoAuthorizeHtmlResponse
|
train
|
function defaultAutoAuthorizeHtmlResponse(req, res) {
var config = req.app.get('stormpathConfig');
res.redirect(302, url.parse(req.query.next || '').path || config.web.register.nextUri);
}
|
javascript
|
{
"resource": ""
}
|
q55003
|
defaultJsonResponse
|
train
|
function defaultJsonResponse(req, res) {
res.json({
account: helpers.strippedAccount(req.user)
});
}
|
javascript
|
{
"resource": ""
}
|
q55004
|
applyDefaultAccountFields
|
train
|
function applyDefaultAccountFields(stormpathConfig, req) {
var registerFields = stormpathConfig.web.register.form.fields;
if ((!registerFields.givenName || !registerFields.givenName.required || !registerFields.givenName.enabled) && !req.body.givenName) {
req.body.givenName = 'UNKNOWN';
}
if ((!registerFields.surname || !registerFields.surname.required || !registerFields.surname.enabled) && !req.body.surname) {
req.body.surname = 'UNKNOWN';
}
}
|
javascript
|
{
"resource": ""
}
|
q55005
|
train
|
function (req, config, callback) {
var baseUrl = config.web.baseUrl || req.protocol + '://' + getHost(req);
var linkedInAuthUrl = 'https://www.linkedin.com/uas/oauth2/accessToken';
var linkedInProvider = config.web.social.linkedin;
var options = {
form: {
grant_type: 'authorization_code',
code: req.query.code,
redirect_uri: baseUrl + linkedInProvider.uri,
client_id: linkedInProvider.clientId,
client_secret: linkedInProvider.clientSecret
}
};
request.post(linkedInAuthUrl, options, function (err, result, body) {
var parsedBody;
try {
parsedBody = JSON.parse(body);
} catch (err) {
return callback(err);
}
if (parsedBody.error) {
var errorMessage;
switch (parsedBody.error) {
case 'unauthorized_client':
errorMessage = 'Unable to authenticate with LinkedIn. Please verify that your configuration is correct.';
break;
default:
errorMessage = 'LinkedIn error when exchanging auth code for access token: ' + parsedBody.error_description + ' (' + parsedBody.error + ')';
}
return callback(new Error(errorMessage));
}
callback(err, parsedBody.access_token);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q55006
|
oktaErrorTransformer
|
train
|
function oktaErrorTransformer(err) {
if (err && err.errorCauses) {
err.errorCauses.forEach(function (cause) {
if (cause.errorSummary === 'login: An object with this field already exists in the current organization') {
err.userMessage = 'An account with that email address already exists.';
} else if (!err.userMessage) {
// This clause allows the first error cause to be returned to the user
err.userMessage = cause.errorSummary;
}
});
}
// For OAuth errors
if (err && err.error_description) {
err.message = err.error_description;
}
if (err && err.error === 'invalid_grant') {
err.status = 400;
err.code = 7104;
err.message = 'Invalid username or password.';
}
return err;
}
|
javascript
|
{
"resource": ""
}
|
q55007
|
train
|
function (form) {
var data = {
email: form.data.email
};
if (req.organization) {
data.accountStore = {
href: req.organization.href
};
}
application.sendPasswordResetEmail(data, function (err) {
if (err) {
logger.info('A user tried to reset their password, but supplied an invalid email address: ' + form.data.email + '.');
}
res.redirect(config.web.forgotPassword.nextUri);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q55008
|
train
|
function (form) {
if (config.web.multiTenancy.enabled && req.organization) {
setAccountStoreByHref(form.data, req.organization);
} else {
/**
* Delete this form field, it's automatically added by the
* forms library. If we don't delete it, we submit a null
* name key to the REST API and we get an error.
*/
delete form.data.organizationNameKey;
}
helpers.authenticate(form.data, req, res, function (err) {
if (err) {
if (err.code === 2014) {
err.message = err.userMessage = 'Invalid Username, Password, or Organization';
}
err = oktaErrorTransformer(err);
return renderForm(form, { error: err.userMessage || err.message });
}
helpers.loginResponder(req, res);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q55009
|
getFormFields
|
train
|
function getFormFields(form) {
// Grab all fields that are enabled, and return them as an array.
// If enabled, remove that property and apply the field name.
var fields = Object.keys(form.fields).reduce(function (result, fieldKey) {
var field = _.clone(form.fields[fieldKey]);
if (!field.enabled) {
return result;
}
// Append the field to field order in case it's not present.
if (form.fieldOrder.indexOf(fieldKey) === -1) {
form.fieldOrder.push(fieldKey);
}
field.name = fieldKey;
delete field.enabled;
result.push(field);
return result;
}, []);
// Sort fields by the defined fieldOrder.
// Fields that are not in fieldOrder will be placed at the end of the array.
fields.sort(function (a, b) {
var indexA = form.fieldOrder.indexOf(a.name);
var indexB = form.fieldOrder.indexOf(b.name);
if (indexA === -1) {
return 0;
}
if (indexB === -1) {
return -1;
}
if (indexA > indexB) {
return 1;
}
if (indexA < indexB) {
return -1;
}
return 0;
});
return fields;
}
|
javascript
|
{
"resource": ""
}
|
q55010
|
getAccountStores
|
train
|
function getAccountStores(application, callback) {
var options = { expand: 'accountStore' };
// Get account store mappings.
application.getAccountStoreMappings(options, function (err, accountStoreMappings) {
if (err) {
return callback(err);
}
// Iterate over all account stores, and filter out the ones that
// don't have a provider (Organizations dont have providers)
accountStoreMappings.filter(function (accountStoreMapping, next) {
next(!!accountStoreMapping.accountStore.provider);
}, function (accountStoreMappings) {
if (err) {
return callback(err);
}
// Get the account store, and expand the provider so that we can
// inspect the provider ID
async.map(accountStoreMappings, function (accountStoreMapping, next) {
accountStoreMapping.getAccountStore({ expand: 'provider' }, next);
}, callback);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q55011
|
getAccountStoreModel
|
train
|
function getAccountStoreModel(accountStore) {
var provider = accountStore.provider;
return {
href: accountStore.href,
name: accountStore.name,
provider: {
href: provider.href,
providerId: provider.providerId,
callbackUri: provider.callbackUri,
clientId: provider.clientId
}
};
}
|
javascript
|
{
"resource": ""
}
|
q55012
|
handleAcceptRequest
|
train
|
function handleAcceptRequest(req, res, handlers, fallbackHandler) {
var config = req.app.get('stormpathConfig');
// Accepted is an ordered list of preferred types, as specified by the request.
var accepted = req.accepts();
var produces = config.web.produces;
// Our default response is HTML, if the client does not specify something more
// specific. As such, map the wildcard type to html.
accepted = accepted.map(function (contentType) {
return contentType === '*/*' ? 'text/html' : contentType;
});
// Of the accepted types, find the ones that are allowed by the configuration.
var allowedResponseTypes = _.intersection(produces, accepted);
// Of the allowed response types, find the first handler that matches. But
// always override with the SPA handler if SPA is enabled.
var handler;
allowedResponseTypes.some(function (contentType) {
if (config.web.spa.enabled && contentType === 'text/html') {
handler = spaResponseHandler(config);
return true;
}
if (contentType in handlers) {
handler = handlers[contentType];
return true;
}
});
if (!handler) {
return fallbackHandler();
}
handler(req, res);
}
|
javascript
|
{
"resource": ""
}
|
q55013
|
train
|
function (form) {
var options = {
login: form.data.email
};
if (req.organization) {
options.accountStore = {
href: req.organization.href
};
}
application.resendVerificationEmail(options, function (err, account) {
// Code 2016 means that an account does not exist for the given email
// address. We don't want to leak information about the account
// list, so allow this continue without error.
if (err && err.code !== 2016) {
logger.info('A user tried to resend their account verification email, but failed: ' + err.message);
return helpers.render(req, res, view, { error: err.message, form: form });
}
if (account) {
emailVerificationHandler(new Account(account));
}
res.redirect(config.web.login.uri + '?status=unverified');
});
}
|
javascript
|
{
"resource": ""
}
|
|
q55014
|
writeJsonError
|
train
|
function writeJsonError(res, err, statusCode) {
var status = err.status || err.statusCode || statusCode || 400;
var message = 'Unknown error. Please contact support.';
if (err) {
message = err.userMessage || err.message;
}
res.status(status);
res.json({
status: status,
message: message
});
res.end();
}
|
javascript
|
{
"resource": ""
}
|
q55015
|
strippedAccount
|
train
|
function strippedAccount(account, expansionMap) {
expansionMap = typeof expansionMap === 'object' ? expansionMap : {};
var strippedAccount = _.clone(account);
var hiddenProperties = ['stormpathMigrationRecoveryAnswer', 'emailVerificationToken'];
// Profile data is copied onto custom data, so we don't need to expose profile
if (strippedAccount.profile) {
delete strippedAccount.profile;
}
delete strippedAccount.credentials;
delete strippedAccount._links;
Object.keys(strippedAccount).forEach(function (property) {
var expandable = !!expansionMap[property];
if (strippedAccount[property] && (strippedAccount[property].href || strippedAccount[property].items) && expandable === false) {
delete strippedAccount[property];
}
if (property === 'customData') {
if (expandable) {
Object.keys(strippedAccount[property]).forEach(function (subProperty) {
if (hiddenProperties.indexOf(subProperty) > -1) {
delete strippedAccount[property][subProperty];
}
if (subProperty.match('stormpathApiKey')) {
delete strippedAccount[property][subProperty];
}
});
} else {
delete strippedAccount.customData;
}
}
});
return strippedAccount;
}
|
javascript
|
{
"resource": ""
}
|
q55016
|
MarkerLabel_
|
train
|
function MarkerLabel_(marker, crossURL, handCursorURL) {
this.marker_ = marker;
this.handCursorURL_ = marker.handCursorURL;
this.labelDiv_ = document.createElement("div");
this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;";
// Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil
// in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that
// events can be captured even if the label is in the shadow of a google.maps.InfoWindow.
// Code is included here to ensure the veil is always exactly the same size as the label.
this.eventDiv_ = document.createElement("div");
this.eventDiv_.style.cssText = this.labelDiv_.style.cssText;
// This is needed for proper behavior on MSIE:
this.eventDiv_.addEventListener('selectstart', function() { return false; });
this.eventDiv_.addEventListener('dragstart', function() { return false; });
// Get the DIV for the "X" to be displayed when the marker is raised.
this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL);
}
|
javascript
|
{
"resource": ""
}
|
q55017
|
train
|
function(filePath, options) {
var clientOptions = {};
if (options && options !== null) {
if (typeof options.headers === "object") {
clientOptions.headers = options.headers;
}
}
return client.createWriteStream(filePath, clientOptions);
}
|
javascript
|
{
"resource": ""
}
|
|
q55018
|
train
|
function(dirPath, callback) {
client
.createDirectory(dirPath)
.then(function() {
__executeCallbackAsync(callback, [null]);
})
.catch(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q55019
|
train
|
function(/* dirPath[, mode], callback */) {
var args = Array.prototype.slice.call(arguments),
argc = args.length;
if (argc <= 1) {
throw new Error("Invalid number of arguments");
}
var dirPath = args[0],
mode = (typeof args[1] === "string") ? args[1] : "node",
callback = function() {};
if (typeof args[1] === "function") {
callback = args[1];
} else if (argc >= 3 && typeof args[2] === "function") {
callback = args[2];
}
client
.getDirectoryContents(dirPath)
.then(function(contents) {
var results;
if (mode === "node") {
results = contents.map(function(statItem) {
return statItem.basename;
});
} else if (mode === "stat") {
results = contents.map(__convertStat);
} else {
throw new Error("Unknown mode: " + mode);
}
__executeCallbackAsync(callback, [null, results]);
})
.catch(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q55020
|
train
|
function(filePath, targetPath, callback) {
client
.moveFile(filePath, targetPath)
.then(function() {
__executeCallbackAsync(callback, [null]);
})
.catch(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q55021
|
train
|
function(targetPath, callback) {
client
.deleteFile(targetPath)
.then(function() {
__executeCallbackAsync(callback, [null]);
})
.catch(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q55022
|
train
|
function(remotePath, callback) {
client
.stat(remotePath)
.then(function(stat) {
__executeCallbackAsync(callback, [null, __convertStat(stat)]);
})
.catch(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q55023
|
train
|
function(/* filename, data[, encoding], callback */) {
var args = Array.prototype.slice.call(arguments),
argc = args.length;
if (argc <= 2) {
throw new Error("Invalid number of arguments");
}
var filePath = args[0],
data = args[1],
encoding = (argc >= 3 && typeof args[2] === "string") ? args[2] : "text",
callback = function() {};
if (typeof args[2] === "function") {
callback = args[2];
} else if (argc >= 4 && typeof args[3] === "function") {
callback = args[3];
}
encoding = (encoding === "utf8") ? "text" : encoding;
client
.putFileContents(filePath, data, { format: encoding })
.then(function() {
__executeCallbackAsync(callback, [null]);
})
.catch(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q55024
|
loadMockData
|
train
|
function loadMockData(server, next) {
// Create REST resources for each employee
var resources = data.employees.map(function(employee) {
return new swagger.Resource('/employees', employee.username, employee);
});
// Save the resources to the mock data store
server.dataStore.save(resources, next);
}
|
javascript
|
{
"resource": ""
}
|
q55025
|
verifyUsernameDoesNotExist
|
train
|
function verifyUsernameDoesNotExist(req, res, next) {
var username = req.body.username;
var dataStore = req.app.dataStore;
// Check for an existing employee REST resource - /employees/{username}
var resource = new swagger.Resource('/employees', username, null);
dataStore.get(resource, function(err, resource) {
if (resource) {
// The username already exists, so send an HTTP 409 (Conflict)
res.sendStatus(409);
}
else {
next();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q55026
|
SwaggerServer
|
train
|
function SwaggerServer(app) {
app = app || express();
// Event Emitter
_.extend(this, EventEmitter.prototype);
EventEmitter.call(this);
/**
* @type {Middleware}
* @protected
*/
this.__middleware = new SwaggerMiddleware(app);
/**
* @type {SwaggerParser}
* @protected
*/
this.__parser = new SwaggerParser(this);
/**
*
* @type {Handlers|exports|module.exports}
* @private
*/
this.__handlers = new Handlers(this);
/**
* @type {SwaggerWatcher}
* @protected
*/
this.__watcher = new SwaggerWatcher(this);
/**
* The Express Application.
* @type {e.application}
*/
this.app = app;
/**
* The {@link DataStore} object that's used by the mock middleware.
* See https://github.com/BigstickCarpet/swagger-express-middleware/blob/master/docs/exports/DataStore.md
*
* @type {DataStore}
*/
Object.defineProperty(this, 'dataStore', {
configurable: true,
enumerable: true,
get: function() {
return app.get('mock data store');
},
set: function(value) {
app.set('mock data store', value);
}
});
/**
* Parses the given Swagger API.
*
* @param {string|object} swagger
* The file path or URL of a Swagger 2.0 API spec, in YAML or JSON format.
* Or a valid Swagger API object (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object).
*
* @param {function} [callback]
* function(err, api, parser)
*/
this.parse = function(swagger, callback) {
this.__parser.parse(swagger);
if (_.isFunction(callback)) {
this.__parser.whenParsed(callback);
}
};
/**
* Adds the Swaggerize Express handlers to the Express Instance
* (see https://github.com/krakenjs/swaggerize-express for info and acceptable formats)
*/
this.addHandlers = function() {
this.__handlers.setupHandlers();
};
// Patch the Express app to support Swagger
application.patch(this);
// For convenience, expose many of the Express app's methods directly on the Swagger Server object
var server = this;
swaggerMethods.concat(['enable', 'disable', 'set', 'listen', 'use', 'route', 'all'])
.forEach(function(method) {
server[method] = app[method].bind(app);
});
}
|
javascript
|
{
"resource": ""
}
|
q55027
|
createRouter
|
train
|
function createRouter() {
var rtr = express.Router.apply(express, arguments);
router.patch(rtr);
return rtr;
}
|
javascript
|
{
"resource": ""
}
|
q55028
|
Route
|
train
|
function Route(path) {
// Convert Swagger-style path to Express-style path
path = path.replace(util.swaggerParamRegExp, ':$1');
express.Route.call(this, path);
}
|
javascript
|
{
"resource": ""
}
|
q55029
|
train
|
function(router, target) {
// By default, just patch the router's own methods.
// If a target is given, then patch the router to call the target's methods
target = target || router;
// get(setting), which is different than get(path, fn)
var get = router.get;
// Wrap all of these methods to convert Swagger-style paths to Express-style paths
var fns = {};
['use', 'route', 'all'].concat(swaggerMethods).forEach(function(method) {
fns[method] = target[method];
router[method] = function(path) {
var args = _.drop(arguments, 0);
// Special-case for `app.get(setting)`
if (args.length === 1 && method === 'get') {
return get.call(router, path);
}
// Convert Swagger-style path to Express-style path
if (_.isString(path)) {
args[0] = path.replace(util.swaggerParamRegExp, ':$1');
}
// Pass-through to the corresponding Express method
var ret = fns[method].apply(target, args);
if (router.__sortMiddleWare) {
router.__sortMiddleWare();
}
return ret;
};
});
}
|
javascript
|
{
"resource": ""
}
|
|
q55030
|
Handlers
|
train
|
function Handlers(server) {
var self = this;
this.server = server;
//Store the most recently parsed swagger data for when only the handlers get re-attached.
this.server.on('parsed', function(err, api, parser, basePath) {
self.api = api;
self.parser = parser;
self.basePath = basePath;
self.setupHandlers();
});
}
|
javascript
|
{
"resource": ""
}
|
q55031
|
addPathToExpress
|
train
|
function addPathToExpress(handlerObj, handlePath) {
var self = handlerObj;
//Check to make sure that the module exists and will load properly to what node expects
if (moduleExists.call(self, handlePath)) {
//retrieve the http verbs defined in the handler files and then add to the swagger server
var handleVerbs = require(handlePath);
//Get the route path by removing the ./handlers and the .js file extension
//TODO: Use path names to get these
var routePath = handlePath.replace(/.*\/handlers/, '');
routePath = routePath.replace(/\.js/, '');
swaggerMethods.forEach(function(method) {
if (handleVerbs[method] && validSwaggerize(self, handleVerbs[method])) {
self.server[method](routePath, handleVerbs[method]);
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q55032
|
moduleExists
|
train
|
function moduleExists(name) {
//TODO: Check that the file exists before trying to require it.
try {
require.resolve(name);
}
catch (err) {
this.server.emit('error', err);
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q55033
|
loadMockData
|
train
|
function loadMockData(server, next) {
// Create REST resources for each employee photo
var resources = [];
data.employees.forEach(function(employee) {
var collectionPath = '/employees/' + employee.username + '/photos';
resources.push(new swagger.Resource(collectionPath, 'portrait', {path: employee.portrait}));
resources.push(new swagger.Resource(collectionPath, 'thumbnail', {path: employee.thumbnail}));
});
// Save the resources to the mock data store
server.dataStore.save(resources, next);
}
|
javascript
|
{
"resource": ""
}
|
q55034
|
SwaggerWatcher
|
train
|
function SwaggerWatcher(server) {
var self = this;
self.server = server;
/**
* The Swagger API files that are being watched.
* @type {FSWatcher[]}
*/
self.watchedSwaggerFiles = [];
/**
* The Handler files that are being watched.
* @type {FSWatcher[]}
*/
self.watchedHandlerFiles = [];
// Watch Swagger API files
server.on('parsed', function(err, api, parser) {
// Watch all the files that were parsed
self.unwatchSwaggerFiles();
self.watchSwaggerFiles(parser.$refs.paths('fs'));
});
// Watch Handler Files
server.on('handled', function(err, filePaths) {
self.unwatchHandlerFiles(filePaths);
self.watchHandlerFiles(filePaths);
});
}
|
javascript
|
{
"resource": ""
}
|
q55035
|
watchFile
|
train
|
function watchFile(path, onChange) {
try {
var oldStats = fs.statSync(path);
var watcher = fs.watch(path, {persistent: false});
watcher.on('error', watchError);
watcher.on('change', function(event) {
fs.stat(path, function(err, stats) {
if (err) {
/* istanbul ignore next: not easy to repro this error in tests */
watchError(err);
}
else if (stats.mtime > oldStats.mtime) {
oldStats = stats;
onChange(event, path);
}
else {
util.debug('Ignoring %s event for "%s" because %j <= %j', event, path, stats.mtime, oldStats.mtime);
}
});
});
return watcher;
}
catch (e) {
watchError(e);
}
function watchError(e) {
util.warn('Error watching file "%s": %s', path, e.stack);
}
}
|
javascript
|
{
"resource": ""
}
|
q55036
|
authenticate
|
train
|
function authenticate(req, res, next) {
var username = req.body.username,
password = req.body.password;
if (req.session && req.session.user.username === username) {
// This user is already logged in
next();
return;
}
// Get the employee REST resource - /employees/{username}
var dataStore = req.app.dataStore;
var resource = new swagger.Resource('/employees', username, null);
dataStore.get(resource, function(err, resource) {
// Check the login credentials
if (resource && resource.data.password === password) {
// Login is valid, so create a new session object
var sessionId = Math.random().toString(36).substr(2);
req.session = {
id: sessionId,
created: new Date(),
user: resource.data
};
// Save the session REST resource
resource = new swagger.Resource('/sessions', req.session.id, req.session);
dataStore.save(resource, next);
}
else {
// Login failed
res.sendStatus(401);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q55037
|
sendSessionResponse
|
train
|
function sendSessionResponse(req, res, next) {
// Set the session cookie
res.cookie('session', req.session.id);
// Set the Location HTTP header
res.location('/sessions/' + req.session.id);
// Send the response
res.status(201).json(req.session);
}
|
javascript
|
{
"resource": ""
}
|
q55038
|
identifyUser
|
train
|
function identifyUser(req, res, next) {
// Get the session ID from the session cookie
var sessionId = req.cookies.session;
req.session = null;
if (sessionId) {
// Get the session REST resource
var resource = new swagger.Resource('/sessions', sessionId, null);
req.app.dataStore.get(resource, function(err, resource) {
if (resource) {
// Add the session to the request, so other middleware can use it
req.session = resource.data;
console.log('Current User: %s', req.session.user.username);
}
else {
console.warn('INVALID SESSION ID: ' + sessionId);
}
next();
});
}
else {
console.log('Current User: ANONYMOUS');
next();
}
}
|
javascript
|
{
"resource": ""
}
|
q55039
|
mustBeLoggedIn
|
train
|
function mustBeLoggedIn(req, res, next) {
if (req.session && req.session.user) {
next();
}
else {
res.status(401).send('You must be logged-in to access this resource');
}
}
|
javascript
|
{
"resource": ""
}
|
q55040
|
adminsOnly
|
train
|
function adminsOnly(req, res, next) {
if (req.session && _.contains(req.session.user.roles, 'admin')) {
next();
}
else {
res.status(401).send('Only administrators can access this resource');
}
}
|
javascript
|
{
"resource": ""
}
|
q55041
|
yourselfOnly
|
train
|
function yourselfOnly(req, res, next) {
// Get the username or sessionId from the URL
var username = req.params.username;
var sessionId = req.params.sessionId;
if (!req.session) {
res.status(401).send('You must be logged-in to access this resource');
}
else if (_.contains(req.session.user.roles, 'admin') ||
(username && req.session.user.username === username) ||
(sessionId && req.session.id === sessionId)) {
next();
}
else {
res.status(401).send('You can only perform this operation on your own account');
}
}
|
javascript
|
{
"resource": ""
}
|
q55042
|
loadMockData
|
train
|
function loadMockData(server, next) {
// Create REST resources for each project
var resources = data.projects.map(function(project) {
return new swagger.Resource('/projects', project.id, project);
});
// Save the resources to the mock data store
server.dataStore.save(resources, next);
}
|
javascript
|
{
"resource": ""
}
|
q55043
|
verifyProjectIdDoesNotExist
|
train
|
function verifyProjectIdDoesNotExist(req, res, next) {
var projectId = req.body.id;
var dataStore = req.app.dataStore;
// Check for an existing project REST resource - /projects/{projectId}
var resource = new swagger.Resource('/projects', projectId, null);
dataStore.get(resource, function(err, resource) {
if (resource) {
// The ID already exists, so send an HTTP 409 (Conflict)
res.sendStatus(409);
}
else {
next();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q55044
|
verifyProjectNameDoesNotExist
|
train
|
function verifyProjectNameDoesNotExist(req, res, next) {
var projectName = req.body.name.toLowerCase();
var dataStore = req.app.dataStore;
// Get all project REST resources
dataStore.getCollection('/projects', function(err, resources) {
var alreadyExists = resources.some(function(resource) {
return resource.data.name.toLowerCase() === projectName;
});
if (alreadyExists) {
// The ID already exists, so send an HTTP 409 (Conflict)
res.sendStatus(409);
}
else {
next();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q55045
|
find
|
train
|
function find (client) {
return function find (realmName, userId) {
return new Promise((resolve, reject) => {
const req = {
auth: {
bearer: privates.get(client).accessToken
},
json: true
};
req.url = `${client.baseUrl}/admin/realms/${realmName}/users/${userId}/role-mappings`;
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
if (resp.statusCode !== 200) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
javascript
|
{
"resource": ""
}
|
q55046
|
find
|
train
|
function find (client) {
return function find (realm, options) {
return new Promise((resolve, reject) => {
options = options || {};
const req = {
auth: {
bearer: privates.get(client).accessToken
},
json: true
};
if (options.userId) {
req.url = `${client.baseUrl}/admin/realms/${realm}/users/${options.userId}`;
} else {
req.url = `${client.baseUrl}/admin/realms/${realm}/users`;
req.qs = options;
}
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
if (resp.statusCode !== 200) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
javascript
|
{
"resource": ""
}
|
q55047
|
create
|
train
|
function create (client) {
return function create (realm, user) {
return new Promise((resolve, reject) => {
const req = {
url: `${client.baseUrl}/admin/realms/${realm}/users`,
auth: {
bearer: privates.get(client).accessToken
},
body: user,
method: 'POST',
json: true
};
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
if (resp.statusCode !== 201) {
return reject(body);
}
// eg "location":"https://<url>/auth/admin/realms/<realm>/users/499b7073-fe1f-4b7a-a8ab-f401d9b6b8ec"
const uid = resp.headers.location.replace(/.*\/(.*)$/, '$1');
// Since the create Endpoint returns an empty body, go get what we just imported.
// *** Body is empty but location header contains user id ***
// We need to search based on the userid, since it will be unique
return resolve(client.users.find(realm, {
userId: uid
}));
});
});
};
}
|
javascript
|
{
"resource": ""
}
|
q55048
|
update
|
train
|
function update (client) {
return function update (realmName, user) {
return new Promise((resolve, reject) => {
user = user || {};
const req = {
url: `${client.baseUrl}/admin/realms/${realmName}/users/${user.id}`,
auth: {
bearer: privates.get(client).accessToken
},
json: true,
method: 'PUT',
body: user
};
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
// Check that the status cod
if (resp.statusCode !== 204) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
javascript
|
{
"resource": ""
}
|
q55049
|
resetPassword
|
train
|
function resetPassword (c) {
return function resetPassword (realmName, userId, payload) {
return new Promise((resolve, reject) => {
payload = payload || {};
payload.type = 'password';
if (!userId) {
return reject(new Error('userId is missing'));
}
if (!payload.value) {
return reject(new Error('value for the new password is missing'));
}
const req = {
url: `${c.baseUrl}/admin/realms/${realmName}/users/${userId}/reset-password`,
auth: {
bearer: privates.get(c).accessToken
},
json: true,
method: 'PUT',
body: payload
};
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
// Check that the status cod
if (resp.statusCode !== 204) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
javascript
|
{
"resource": ""
}
|
q55050
|
count
|
train
|
function count (client) {
return function count (realm) {
return new Promise((resolve, reject) => {
const req = {
auth: {
bearer: privates.get(client).accessToken
},
json: true,
url: `${client.baseUrl}/admin/realms/${realm}/users/count`
};
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
if (resp.statusCode !== 200) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
javascript
|
{
"resource": ""
}
|
q55051
|
copyFromValueBuilder
|
train
|
function copyFromValueBuilder(otherValueBuilder) {
var tb = new ValueBuilder();
// TODO: share with QueryBuilder
if (otherValueBuilder != null) {
var clauseKeys = [
'fromIndexesClause', 'whereClause', 'aggregatesClause',
'sliceClause', 'withOptionsClause'
];
var isString = (typeof otherValueBuilder === 'string' || otherValueBuilder instanceof String);
var other = isString ?
JSON.parse(otherValueBuilder) : otherValueBuilder;
for (var i=0; i < clauseKeys.length; i++){
var key = clauseKeys[i];
var value = other[key];
if (value != null) {
// deepcopy instead of clone to avoid preserving prototype
tb[key] = isString ? value : deepcopy(value);
}
}
}
return tb;
}
|
javascript
|
{
"resource": ""
}
|
q55052
|
checkQueryArray
|
train
|
function checkQueryArray(queryArray) {
if (queryArray == null) {
return queryArray;
}
var max = queryArray.length;
if (max === 0) {
return queryArray;
}
var i = 0;
for (; i < max; i++) {
checkQuery(queryArray[i]);
}
return queryArray;
}
|
javascript
|
{
"resource": ""
}
|
q55053
|
and
|
train
|
function and() {
var args = mlutil.asArray.apply(null, arguments);
var queries = [];
var ordered = null;
var arg = null;
for (var i=0; i < args.length; i++) {
arg = args[i];
if (ordered === null) {
if (arg instanceof OrderedDef) {
ordered = arg.ordered;
continue;
} else if (typeof arg === 'boolean') {
ordered = arg;
continue;
}
}
if (arg instanceof Array){
Array.prototype.push.apply(queries, arg);
} else {
queries.push(arg);
}
}
return new AndDef(new QueryListDef(queries, ordered, null, null));
}
|
javascript
|
{
"resource": ""
}
|
q55054
|
andNot
|
train
|
function andNot() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing positive and negative queries');
case 1:
throw new Error('has positive but missing negative query: '+mlutil.identify(args[0], true));
case 2:
return new AndNotDef(new PositiveNegativeDef(args[0], args[1]));
default:
throw new Error('more than two arguments for andNot(): '+args.length);
}
}
|
javascript
|
{
"resource": ""
}
|
q55055
|
boost
|
train
|
function boost() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing matching and boosting queries');
case 1:
throw new Error('has matching but missing boosting query: '+mlutil.identify(args[0], true));
case 2:
return new BoostDef(new MatchingBoostingDef(args[0], args[1]));
default:
throw new Error('too many arguments for boost(): '+args.length);
}
}
|
javascript
|
{
"resource": ""
}
|
q55056
|
directory
|
train
|
function directory() {
var args = mlutil.asArray.apply(null, arguments);
var uris = [];
var infinite = null;
var arg = null;
for (var i=0; i < args.length; i++) {
arg = args[i];
if (infinite === null && (typeof arg === 'boolean')) {
infinite = arg;
} else if (arg instanceof Array){
Array.prototype.push.apply(uris, arg);
} else {
uris.push(arg);
}
}
return new DirectoryQueryDef(
new UrisDef(uris, infinite)
);
}
|
javascript
|
{
"resource": ""
}
|
q55057
|
field
|
train
|
function field() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing field name');
case 1:
return new FieldDef(new FieldNameDef(args[0]));
case 2:
return new FieldDef(new FieldNameDef(args[0], args[1]));
default:
throw new Error('too many arguments for field identifier: '+args.length);
}
}
|
javascript
|
{
"resource": ""
}
|
q55058
|
heatmap
|
train
|
function heatmap() {
var args = mlutil.asArray.apply(null, arguments);
var argLen = args.length;
if (argLen < 1) {
throw new Error('no region or divisions for heat map');
}
var hmap = {};
switch(argLen) {
case 3:
var first = args[0];
var second = args[1];
var third = args[2];
var region = null;
if (typeof first === 'object' && first !== null) {
region = first;
hmap.latdivs = second;
hmap.londivs = third;
} else if (typeof third === 'object' && third !== null) {
region = third;
hmap.latdivs = first;
hmap.londivs = second;
} else {
throw new Error('no first or last region for heat map');
}
var keys = ['s', 'w', 'n', 'e'];
for (var i=0; i < keys.length; i++) {
var key = keys[i];
var value = region[key];
if (value != null) {
hmap[key] = value;
continue;
} else {
var altKey = null;
switch(key) {
case 's':
altKey = 'south';
break;
case 'w':
altKey = 'west';
break;
case 'n':
altKey = 'north';
break;
case 'e':
altKey = 'east';
break;
}
value = (altKey !== null) ? region[altKey] : null;
if (value != null) {
hmap[key] = value;
continue;
}
}
throw new Error('heat map does not have '+key+' key');
}
break;
case 6:
hmap.latdivs = args[0];
hmap.londivs = args[1];
hmap.s = args[2];
hmap.w = args[3];
hmap.n = args[4];
hmap.e = args[5];
break;
default:
throw new Error('could not assign parameters to heat map');
}
return {'heatmap': hmap};
}
|
javascript
|
{
"resource": ""
}
|
q55059
|
latlon
|
train
|
function latlon() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing latitude and longitude for latlon coordinate');
case 1:
throw new Error('missing longitude for latlon coordinate');
case 2:
return new LatLongDef(args[0], args[1]);
default:
throw new Error('too many arguments for latlon coordinate: '+args.length);
}
}
|
javascript
|
{
"resource": ""
}
|
q55060
|
notIn
|
train
|
function notIn() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing positive and negative queries');
case 1:
throw new Error('has positive query but missing negative query: '+mlutil.identify(args[0], true));
case 2:
return new NotInDef(new PositiveNegativeDef(args[0], args[1]));
default:
throw new Error('too many arguments for notIn() query: '+args.length);
}
}
|
javascript
|
{
"resource": ""
}
|
q55061
|
pathIndex
|
train
|
function pathIndex() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing path for path index identifier');
case 1:
return new PathIndexDef(new PathDef(args[0]));
case 2:
return new PathIndexDef(new PathDef(args[0], args[1]));
default:
throw new Error('too many arguments for path index identifier: '+args.length);
}
}
|
javascript
|
{
"resource": ""
}
|
q55062
|
coordSystem
|
train
|
function coordSystem() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing identifier for coordinate system');
case 1:
return new CoordSystemDef(args[0]);
default:
throw new Error('too many arguments for coordinate system identifier: '+args.length);
}
}
|
javascript
|
{
"resource": ""
}
|
q55063
|
property
|
train
|
function property() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing JSON property name');
case 1:
return new JSONPropertyDef(args[0]);
default:
throw new Error('too many arguments for JSON property identifier: '+args.length);
}
}
|
javascript
|
{
"resource": ""
}
|
q55064
|
term
|
train
|
function term() {
var args = mlutil.asArray.apply(null, arguments);
var text = [];
var weight = null;
var termOptions = null;
var arg = null;
for (var i=0; i < args.length; i++) {
arg = args[i];
if (weight === null && arg instanceof WeightDef) {
weight = arg.weight;
continue;
}
if (termOptions === null && arg instanceof TermOptionsDef) {
termOptions = arg['term-option'];
continue;
}
if (arg instanceof Array){
Array.prototype.push.apply(text, arg);
} else {
text.push(arg);
}
}
return new TermDef(new TextDef(null, null, text, weight, termOptions, null));
}
|
javascript
|
{
"resource": ""
}
|
q55065
|
calculate
|
train
|
function calculate() {
/*jshint validthis:true */
var self = (this instanceof QueryBuilder) ? this : new QueryBuilder();
var args = mlutil.asArray.apply(null, arguments);
// TODO: distinguish facets and values
var calculateClause = {
constraint: args
};
self.calculateClause = calculateClause;
return self;
}
|
javascript
|
{
"resource": ""
}
|
q55066
|
extract
|
train
|
function extract() {
var args = mlutil.asArray.apply(null, arguments);
var argLen = args.length;
if (argLen < 1) {
throw new Error('must specify paths to extract');
}
var extractdef = {};
var arg = args[0];
if (typeof arg === 'string' || arg instanceof String) {
extractdef['extract-path'] = args;
} else {
var paths = arg.paths;
if (typeof paths === 'string' || paths instanceof String) {
extractdef['extract-path'] = [paths];
} else if (Array.isArray(paths)) {
extractdef['extract-path'] = paths;
} else if (paths === void 0) {
throw new Error('first argument does not have key for paths to extract');
}
var namespaces = arg.namespaces;
if (namespaces !== void 0) {
extractdef.namespaces = namespaces;
}
var selected = arg.selected;
if (selected !== void 0) {
extractdef.selected = selected;
}
}
return {'extract-document-data': extractdef};
}
|
javascript
|
{
"resource": ""
}
|
q55067
|
withOptions
|
train
|
function withOptions() {
/*jshint validthis:true */
var self = (this instanceof QueryBuilder) ? this : new QueryBuilder();
// TODO: share with documents.js
var optionKeyMapping = {
search:'search-option', weight:'quality-weight',
forestNames:'forest', similarDocs:'return-similar',
metrics:'return-metrics', queryPlan:'return-plan',
debug:'debug', concurrencyLevel:'concurrency-level',
categories:true, txid:true
};
var withOptionsClause = {};
if (0 < arguments.length) {
var arg = arguments[0];
var argKeys = Object.keys(arg);
for (var i=0; i < argKeys.length; i++) {
var key = argKeys[i];
if (optionKeyMapping[key] !== void 0) {
var value = arg[key];
if (value !== void 0) {
withOptionsClause[key] = value;
} else {
throw new Error('empty options value for '+key);
}
} else {
throw new Error('unknown option '+key);
}
}
}
self.withOptionsClause = withOptionsClause;
return self;
}
|
javascript
|
{
"resource": ""
}
|
q55068
|
remove
|
train
|
function remove() {
var select = null;
var cardinality = null;
var argLen = arguments.length;
for (var i=0; i < argLen; i++) {
var arg = arguments[i];
if (i === 0) {
select = arg;
continue;
}
if (cardinality === null && /^[?.*+]$/.test(arg)) {
cardinality = arg;
continue;
}
break;
}
if (select === null) {
throw new Error('remove takes select and optional cardinality');
}
var operation = {
select: select
};
if (cardinality !== null) {
operation.cardinality = cardinality;
}
return {'delete': operation};
}
|
javascript
|
{
"resource": ""
}
|
q55069
|
insert
|
train
|
function insert() {
var context = null;
var position = null;
var content = void 0;
var cardinality = null;
var argLen = arguments.length;
for (var i=0; i < argLen; i++) {
var arg = arguments[i];
if (i === 0) {
context = arg;
continue;
}
if (arg === null && content === void 0) {
content = arg;
continue;
}
var isString = (typeof arg === 'string' || arg instanceof String);
if (isString) {
if (position === null && /^(before|after|last-child)$/.test(arg)) {
position = arg;
continue;
}
if (cardinality === null && /^[?.*+]$/.test(arg)) {
cardinality = arg;
continue;
}
}
if (content === void 0) {
content = arg;
continue;
}
break;
}
if (context === null || position === null || content === void 0) {
throw new Error(
'insert takes context, position, content, and optional cardinality'
);
}
var operation = {
context: context,
position: position,
content: content
};
if (cardinality !== null) {
operation.cardinality = cardinality;
}
return {insert: operation};
}
|
javascript
|
{
"resource": ""
}
|
q55070
|
replace
|
train
|
function replace() {
var select = null;
var content = void 0;
var cardinality = null;
var apply = null;
var argLen = arguments.length;
for (var i=0; i < argLen; i++) {
var arg = arguments[i];
if (i === 0) {
select = arg;
continue;
}
if (arg === null && content === void 0) {
content = arg;
continue;
}
var isString = (typeof arg === 'string' || arg instanceof String);
if (isString && cardinality === null && /^[?.*+]$/.test(arg)) {
cardinality = arg;
continue;
}
if (apply === null || apply === undefined) {
apply = arg.apply;
if (apply != null) {
content = arg.content;
continue;
}
}
if (content === void 0) {
content = arg;
continue;
}
break;
}
if (select === null) {
throw new Error(
'replace takes a select path, content or an apply function, and optional cardinality'
);
}
var operation = {
select: select,
content: content
};
if (cardinality != null) {
operation.cardinality = cardinality;
}
if (apply != null) {
operation.apply = apply;
}
return {replace: operation};
}
|
javascript
|
{
"resource": ""
}
|
q55071
|
addPermission
|
train
|
function addPermission() {
var permission = getPermission(
mlutil.asArray.apply(null, arguments)
);
if (permission === null) {
throw new Error('permissions.add() takes the role name and one or more insert|update|read|execute capabilities');
}
return insert('/array-node("permissions")', 'last-child', permission);
}
|
javascript
|
{
"resource": ""
}
|
q55072
|
replacePermission
|
train
|
function replacePermission() {
var permission = getPermission(
mlutil.asArray.apply(null, arguments)
);
if (permission === null) {
throw new Error('permissions.replace() takes the role name and one or more insert|update|read|execute capabilities');
}
return replace(
'/permissions[node("role-name") eq "'+permission['role-name']+'"]',
permission
);
}
|
javascript
|
{
"resource": ""
}
|
q55073
|
addProperty
|
train
|
function addProperty(name, value) {
if (typeof name !== 'string' || value == null) {
throw new Error('properties.add() takes a string name and a value');
}
var prop = {};
prop[name] = value;
return insert('/object-node("properties")', 'last-child', prop);
}
|
javascript
|
{
"resource": ""
}
|
q55074
|
replaceProperty
|
train
|
function replaceProperty(name, value) {
if (typeof name !== 'string' || value == null) {
throw new Error('properties.replace() takes a string name and a value');
}
return replace('/properties/node("'+name+'")', value);
}
|
javascript
|
{
"resource": ""
}
|
q55075
|
addMetadataValue
|
train
|
function addMetadataValue(name, value) {
if (typeof name !== 'string' || typeof value !== 'string' ) {
throw new Error('metadataValues.add() takes a string name and string value');
}
var metaVal = {};
metaVal[name] = value;
return insert('/object-node("metadataValues")', 'last-child', metaVal);
}
|
javascript
|
{
"resource": ""
}
|
q55076
|
asArray
|
train
|
function asArray() {
var argLen = arguments.length;
switch(argLen) {
// No arguments returns an empty array
case 0:
return [];
// Single array argument returns that array
case 1:
var arg = arguments[0];
if (Array.isArray(arg)) {
return arg;
}
// Single object argument returns an array with object as only element
return [arg];
// List of arguments returns an array with arguments as elements
default:
var args = new Array(argLen);
for(var i=0; i < argLen; ++i) {
args[i] = arguments[i];
}
return args;
}
}
|
javascript
|
{
"resource": ""
}
|
q55077
|
openOutputTransform
|
train
|
function openOutputTransform(headers/*, data*/) {
/*jshint validthis:true */
var operation = this;
var txid = headers.location.substring('/v1/transactions/'.length);
if (operation.withState === true) {
return new mlutil.Transaction(txid, operation.rawHeaders['set-cookie']);
}
return {txid: txid};
}
|
javascript
|
{
"resource": ""
}
|
q55078
|
probeOutputTransform
|
train
|
function probeOutputTransform(/*headers, data*/) {
/*jshint validthis:true */
var operation = this;
var statusCode = operation.responseStatusCode;
var exists = (statusCode === 200) ? true : false;
if (operation.contentOnly === true) {
return exists;
}
var output = exists ? operation.responseHeaders : {};
output.uri = operation.uri;
output.exists = exists;
return output;
}
|
javascript
|
{
"resource": ""
}
|
q55079
|
ExtlibsWrapper
|
train
|
function ExtlibsWrapper(extlibs, name, dir) {
if (!(this instanceof ExtlibsWrapper)) {
return new ExtlibsWrapper(extlibs, name, dir);
}
this.extlibs = extlibs;
this.name = name;
this.dir = dir;
}
|
javascript
|
{
"resource": ""
}
|
q55080
|
concatBanner
|
train
|
function concatBanner() {
if (typeof argv.banner !== 'undefined') {
if (argv.banner) {
return Promise.resolve().then(() => {
concat.add(null, require(path.join(process.cwd(), argv.banner)));
return log('banner', argv.banner);
});
}
return readPkg().then(pkg => {
concat.add(null, getDefaultBanner(pkg.pkg));
return log('dbanner', pkg.path);
});
}
return Promise.resolve();
}
|
javascript
|
{
"resource": ""
}
|
q55081
|
concatFooter
|
train
|
function concatFooter() {
if (argv.footer) {
return Promise.resolve().then(() => {
concat.add(null, require(path.join(process.cwd(), argv.footer)));
return log('footer', `Concat footer from ${argv.footer}`);
});
}
return Promise.resolve();
}
|
javascript
|
{
"resource": ""
}
|
q55082
|
concatFiles
|
train
|
function concatFiles() {
return Promise.all(argv._.map(handleGlob)).then(globs => {
const files = globs.reduce((acc, cur) => acc.concat(cur), []);
if (
(files.length < 2 && typeof argv.banner === 'undefined' && !argv.footer) ||
(files.length === 0 && (typeof argv.banner === 'undefined' || !argv.footer))
) {
throw new Error(
chalk.bold.red('Require at least 2 file, banner or footer to concatenate. ("ncat --help" for help)\n')
);
}
return files.forEach(file => {
concat.add(file.file, file.content, file.map);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q55083
|
handleGlob
|
train
|
function handleGlob(glob) {
if (glob === '-') {
return stdinCache.then(stdin => [{content: stdin}]);
}
return globby(glob.split(' '), {nodir: true}).then(files => Promise.all(files.map(handleFile)));
}
|
javascript
|
{
"resource": ""
}
|
q55084
|
getSourceMappingURL
|
train
|
function getSourceMappingURL() {
if (path.extname(argv.output) === '.css') {
return `\n/*# sourceMappingURL=${path.basename(argv.output)}.map */`;
}
return `\n//# sourceMappingURL=${path.basename(argv.output)}.map`;
}
|
javascript
|
{
"resource": ""
}
|
q55085
|
resolvePaths
|
train
|
function resolvePaths(paths) {
var exec = {};
var originalWd = process.cwd();
for (var name in paths) {
process.chdir(originalWd);
exec[name] = resolveLink(paths[name]);
process.chdir(originalWd);
}
process.chdir(originalWd);
return exec;
}
|
javascript
|
{
"resource": ""
}
|
q55086
|
resolveLink
|
train
|
function resolveLink(path) {
var links = readLinkRecursive(path);
var resolved = p.resolve.apply(null, links);
trace('links', links, 'resolves to', resolved);
return resolved;
}
|
javascript
|
{
"resource": ""
}
|
q55087
|
readLinkRecursive
|
train
|
function readLinkRecursive(path, seen) {
seen = seen || [];
seen.push(p.dirname(path));
var next = readLink(path);
trace('recur', seen, next);
if (!next) {
seen.push(p.basename(path));
return seen;
}
return readLinkRecursive(next, seen);
}
|
javascript
|
{
"resource": ""
}
|
q55088
|
SMTPTransport
|
train
|
function SMTPTransport(options) {
EventEmitter.call(this);
options = options || {};
if (typeof options === 'string') {
options = {
url: options
};
}
var urlData;
var service = options.service;
if (typeof options.getSocket === 'function') {
this.getSocket = options.getSocket;
}
if (options.url) {
urlData = shared.parseConnectionUrl(options.url);
service = service || urlData.service;
}
this.options = assign(
false, // create new object
options, // regular options
urlData, // url options
service && wellknown(service) // wellknown options
);
this.logger = shared.getLogger(this.options);
// temporary object
var connection = new SMTPConnection(this.options);
this.name = 'SMTP';
this.version = packageData.version + '[client:' + connection.version + ']';
}
|
javascript
|
{
"resource": ""
}
|
q55089
|
assign
|
train
|
function assign( /* target, ... sources */ ) {
var args = Array.prototype.slice.call(arguments);
var target = args.shift() || {};
args.forEach(function (source) {
Object.keys(source || {}).forEach(function (key) {
if (['tls', 'auth'].indexOf(key) >= 0 && source[key] && typeof source[key] === 'object') {
// tls and auth are special keys that need to be enumerated separately
// other objects are passed as is
if (!target[key]) {
// esnure that target has this key
target[key] = {};
}
Object.keys(source[key]).forEach(function (subKey) {
target[key][subKey] = source[key][subKey];
});
} else {
target[key] = source[key];
}
});
});
return target;
}
|
javascript
|
{
"resource": ""
}
|
q55090
|
collectComments
|
train
|
function collectComments(content, comments) {
const table = []
let from = 0
let end
while (true) {
let start = content.indexOf('/*', from)
if (start > -1) {
end = content.indexOf('*/', start + 2)
if (end > -1) {
comments.push(content.slice(start + 2, end))
table.push(content.slice(from, start))
table.push('/*___PRESERVE_CANDIDATE_COMMENT_' + (comments.length - 1) + '___*/')
from = end + 2
} else {
// unterminated comment
end = -2
break
}
} else {
break
}
}
table.push(content.slice(end + 2))
return table.join('')
}
|
javascript
|
{
"resource": ""
}
|
q55091
|
processFiles
|
train
|
function processFiles(filenames = [], options = defaultOptions) {
if (options.convertUrls) {
options.target = resolve(process.cwd(), options.convertUrls).split(PATH_SEP)
}
const uglies = []
// process files
filenames.forEach(filename => {
try {
const content = readFileSync(filename, 'utf8')
if (content.length) {
if (options.convertUrls) {
options.source = resolve(process.cwd(), filename).split(PATH_SEP)
options.source.pop()
}
uglies.push(processString(content, options))
}
} catch (e) {
if (options.debug) {
console.error(`uglifycss: unable to process "${filename}"\n${e.stack}`)
} else {
console.error(`uglifycss: unable to process "${filename}"\n\t${e}`)
}
process.exit(1)
}
})
// return concat'd results
return uglies.join('')
}
|
javascript
|
{
"resource": ""
}
|
q55092
|
getSpecsRegex
|
train
|
function getSpecsRegex() {
const argv = minimist(process.argv.slice(2));
/**
* The command line argument `--ieBatch` is a string representing
* the current batch to run, of total batches.
* For example, `npm run test:unit:ci:ie -- --ieBatch 1of3`
*/
const [
currentRun,
totalRuns
] = argv.ieBatch.split('of');
if (!currentRun || !totalRuns) {
throw 'Invalid IE 11 batch request! Please provide a command line argument in the format of `--ieBatch 1of3`.';
}
const moduleDirectories = getDirectories(path.resolve('src/modules'));
const totalModules = moduleDirectories.length;
const modulesPerRun = Math.ceil(moduleDirectories.length / totalRuns);
const startAtIndex = modulesPerRun * (currentRun - 1);
const modules = moduleDirectories.splice(startAtIndex, modulesPerRun);
if (modules.length === 0) {
return;
}
console.log(`[Batch ${currentRun} of ${totalRuns}]`);
console.log(`--> Running specs for ${modules.length} modules...`);
console.log(`--> Starting at module ${startAtIndex}, ending at module ${startAtIndex + modules.length}, of ${totalModules} total modules\n`);
console.log(modules.join(',\n'));
return [
String.raw`\\/`,
'\(',
...modules.join('|'),
')\\/'
].join('').replace(/\-/g, '\\-');
}
|
javascript
|
{
"resource": ""
}
|
q55093
|
setup
|
train
|
function setup() {
return browser.getProcessedConfig()
.then((configuration) => {
let cucumberFormat = configuration.cucumberOpts.format;
IS_JSON_FORMAT = cucumberFormat && cucumberFormat.includes('json');
if (Array.isArray(cucumberFormat)) {
IS_JSON_FORMAT = cucumberFormat.find((format) => {
cucumberFormat = format;
return format.includes('json')
});
}
if (IS_JSON_FORMAT) {
/**
* If options are provided override the values to the PLUGIN_CONFIG object
*/
if (this.config.options) {
Object.assign(PLUGIN_CONFIG, this.config.options);
}
/**
* Get the JSON folder path and file name if they are still empty
*/
const formatPathMatch = cucumberFormat.match(/(.+):(.+)/);
const filePathMatch = formatPathMatch[2].match(/(.*)\/(.*)\.json/);
// Get the cucumber results path
PLUGIN_CONFIG.cucumberResultsPath = filePathMatch[1];
// Get the cucumber report name
PLUGIN_CONFIG.cucumberReportName = filePathMatch[2];
/**
* If the json output folder is still default, then create a new one
*/
if (PLUGIN_CONFIG.jsonOutputPath === JSON_OUTPUT_FOLDER) {
PLUGIN_CONFIG.jsonOutputPath = path.join(PLUGIN_CONFIG.cucumberResultsPath, JSON_OUTPUT_FOLDER);
}
/**
* Check whether the file name need to be unique
*/
PLUGIN_CONFIG.uniqueReportFileName = (Array.isArray(configuration.multiCapabilities)
&& configuration.multiCapabilities.length > 0)
|| typeof configuration.getMultiCapabilities === 'function'
|| configuration.capabilities.shardTestFiles;
/**
* Prepare the PID_INSTANCE_DATA
*/
const metadata = {
browser: {
name: '',
version: ''
},
device: '',
platform: {
name: '',
version: ''
}
};
PID_INSTANCE_DATA = {
pid: process.pid,
metadata: Object.assign(metadata, configuration.capabilities[PLUGIN_CONFIG.metadataKey] || {})
};
/**
* Create the needed folders if they are not present
*/
fs.ensureDirSync(PLUGIN_CONFIG.cucumberResultsPath);
fs.ensureDirSync(PLUGIN_CONFIG.jsonOutputPath);
} else {
console.warn('\n### NO `JSON` FORMAT IS SPECIFIED IN THE PROTRACTOR CONF FILE UNDER `cucumberOpts.format ###`\n');
}
});
}
|
javascript
|
{
"resource": ""
}
|
q55094
|
onPrepare
|
train
|
function onPrepare() {
if (IS_JSON_FORMAT) {
return browser.getCapabilities()
.then((capabilities) => {
PID_INSTANCE_DATA.metadata.browser.name = PID_INSTANCE_DATA.metadata.browser.name === ''
? capabilities.get('browserName').toLowerCase()
: PID_INSTANCE_DATA.metadata.browser.name;
PID_INSTANCE_DATA.metadata.browser.version = (capabilities.get('version') || capabilities.get('browserVersion'))
|| PID_INSTANCE_DATA.metadata.browser.version;
});
}
}
|
javascript
|
{
"resource": ""
}
|
q55095
|
passLintResultsThroughReporters
|
train
|
function passLintResultsThroughReporters(lintResults) {
const warnings = lintResults
.reduce((accumulated, res) => accumulated.concat(res.results), []);
return Promise
.all(reporters.map(reporter => reporter(warnings)))
.then(() => lintResults);
}
|
javascript
|
{
"resource": ""
}
|
q55096
|
download
|
train
|
function download(source, { verbose, output, onStart, onProgress } = {}) {
return new Promise(function(y, n) {
if (typeof output === 'undefined') {
output = path.basename(url.parse(source).pathname) || 'unknown';
}
/**
* Parse the source url into parts
*/
const sourceUrl = url.parse(source);
/**
* Determine to use https or http request depends on source url
*/
let request = null;
if (sourceUrl.protocol === 'https:') {
request = https.request;
} else if (sourceUrl.protocol === 'http:') {
request = http.request;
} else {
throw new Error('protocol should be http or https');
}
/**
* Issue the request
*/
const req = request(
{
method: 'GET',
protocol: sourceUrl.protocol,
host: sourceUrl.hostname,
port: sourceUrl.port,
path: sourceUrl.pathname + (sourceUrl.search || '')
},
function(res) {
if (res.statusCode === 200) {
const fileSize = Number.isInteger(res.headers['content-length'] - 0)
? parseInt(res.headers['content-length'])
: 0;
let downloadedSize = 0;
/**
* Create write stream
*/
var writeStream = fs.createWriteStream(output, {
flags: 'w+',
encoding: 'binary'
});
res.pipe(writeStream);
/**
* Invoke `onStartCallback` function
*/
if (onStart) {
onStart(res.headers);
}
res.on('data', function(chunk) {
downloadedSize += chunk.length;
if (onProgress) {
onProgress({
fileSize,
downloadedSize,
percentage: fileSize > 0 ? downloadedSize / fileSize : 0
});
}
});
res.on('error', function(err) {
writeStream.end();
n(err);
});
writeStream.on('finish', function() {
writeStream.end();
req.end('finished');
y({ headers: res.headers, fileSize });
});
} else if (
res.statusCode === 301 ||
res.statusCode === 302 ||
res.statusCode === 307
) {
const redirectLocation = res.headers.location;
if (verbose) {
console.log('node-wget-promise: Redirected to:', redirectLocation);
}
/**
* Call download function recursively
*/
download(redirectLocation, {
output,
onStart,
onProgress
})
.then(y)
.catch(n);
} else {
n('Server responded with unhandled status: ' + res.statusCode);
}
}
);
req.end('done');
req.on('error', err => n(err));
});
}
|
javascript
|
{
"resource": ""
}
|
q55097
|
Strategy
|
train
|
function Strategy(options, verify) {
if (typeof options == 'function') {
verify = options;
options = {};
}
if (!verify) throw new Error('OAuth 2.0 client password strategy requires a verify function');
passport.Strategy.call(this);
this.name = 'oauth2-client-password';
this._verify = verify;
this._passReqToCallback = options.passReqToCallback;
}
|
javascript
|
{
"resource": ""
}
|
q55098
|
bundleJsFiles
|
train
|
function bundleJsFiles () {
return concat(jsFiles)
.then((output) => {
const uglified = UglifyJS.minify(output)
if (uglified.error) {
throw new Error(uglified.error)
}
return uglified.code
})
}
|
javascript
|
{
"resource": ""
}
|
q55099
|
addMember
|
train
|
function addMember(path, memberPath, setId, msg) {
// FIXME: This will have to break due to switched arguments
var node = _getNode(path),
memberNode = _getNode(memberPath);
if (node && memberNode) {
state.core.addMember(node, setId, memberNode);
saveRoot(typeof msg === 'string' ? msg : 'addMember(' + path + ',' + memberPath + ',' + setId + ')');
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.