_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q15700
replaceImpureComputedKeys
train
function replaceImpureComputedKeys(path) { const impureComputedPropertyDeclarators = []; for (const propPath of path.get("properties")) { const key = propPath.get("key"); if (propPath.node.computed && !key.isPure()) { const name = path.scope.generateUidBasedOnNode(key.node); const de...
javascript
{ "resource": "" }
q15701
createObjectSpread
train
function createObjectSpread(path, file, objRef) { const props = path.get("properties"); const last = props[props.length - 1]; t.assertRestElement(last.node); const restElement = t.cloneNode(last.node); last.remove(); const impureComputedPropertyDeclarators = replaceImpureComputedKeys(path); ...
javascript
{ "resource": "" }
q15702
buildInitStatement
train
function buildInitStatement(metadata, exportNames, initExpr) { return t.expressionStatement( exportNames.reduce( (acc, exportName) => template.expression`EXPORTS.NAME = VALUE`({ EXPORTS: metadata.exportName, NAME: exportName, VALUE: acc, }), initExpr, ...
javascript
{ "resource": "" }
q15703
getDefs
train
function getDefs(chalk) { return { gutter: chalk.grey, marker: chalk.red.bold, message: chalk.red.bold, }; }
javascript
{ "resource": "" }
q15704
load
train
function load(url, successCallback, errorCallback) { const xhr = new XMLHttpRequest(); // async, however scripts will be executed in the order they are in the // DOM to mirror normal script loading. xhr.open("GET", url, true); if ("overrideMimeType" in xhr) { xhr.overrideMimeType("text/plain"); } xhr...
javascript
{ "resource": "" }
q15705
getPluginsOrPresetsFromScript
train
function getPluginsOrPresetsFromScript(script, attributeName) { const rawValue = script.getAttribute(attributeName); if (rawValue === "") { // Empty string means to not load ANY presets or plugins return []; } if (!rawValue) { // Any other falsy value (null, undefined) means we're not overriding thi...
javascript
{ "resource": "" }
q15706
deopt
train
function deopt(path, state) { if (!state.confident) return; state.deoptPath = path; state.confident = false; }
javascript
{ "resource": "" }
q15707
getPrototypeOfExpression
train
function getPrototypeOfExpression(objectRef, isStatic, file, isPrivateMethod) { objectRef = t.cloneNode(objectRef); const targetRef = isStatic || isPrivateMethod ? objectRef : t.memberExpression(objectRef, t.identifier("prototype")); return t.callExpression(file.addHelper("getPrototypeOf"), [targ...
javascript
{ "resource": "" }
q15708
applyEnsureOrdering
train
function applyEnsureOrdering(path) { // TODO: This should probably also hoist computed properties. const decorators = (path.isClass() ? [path].concat(path.get("body.body")) : path.get("properties") ).reduce((acc, prop) => acc.concat(prop.node.decorators || []), []); const identDecorators = decorators.f...
javascript
{ "resource": "" }
q15709
applyClassDecorators
train
function applyClassDecorators(classPath) { if (!hasClassDecorators(classPath.node)) return; const decorators = classPath.node.decorators || []; classPath.node.decorators = null; const name = classPath.scope.generateDeclaredUidIdentifier("class"); return decorators .map(dec => dec.expression) .rever...
javascript
{ "resource": "" }
q15710
applyMethodDecorators
train
function applyMethodDecorators(path, state) { if (!hasMethodDecorators(path.node.body.body)) return; return applyTargetDecorators(path, state, path.node.body.body); }
javascript
{ "resource": "" }
q15711
applyObjectDecorators
train
function applyObjectDecorators(path, state) { if (!hasMethodDecorators(path.node.properties)) return; return applyTargetDecorators(path, state, path.node.properties); }
javascript
{ "resource": "" }
q15712
getDefs
train
function getDefs(chalk) { return { keyword: chalk.cyan, capitalized: chalk.yellow, jsx_tag: chalk.yellow, punctuator: chalk.yellow, // bracket: intentionally omitted. number: chalk.magenta, string: chalk.green, regex: chalk.magenta, comment: chalk.grey, invalid: chalk.white.bg...
javascript
{ "resource": "" }
q15713
getTokenType
train
function getTokenType(match) { const [offset, text] = match.slice(-2); const token = matchToToken(match); if (token.type === "name") { if (esutils.keyword.isReservedWordES6(token.value)) { return "keyword"; } if ( JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.subst...
javascript
{ "resource": "" }
q15714
exchangePassword
train
function exchangePassword(client, username, password, scope, body, authInfo, done) { if (!client || !client.id) { return done(new common.errors.UnauthorizedError({ message: common.i18n.t('errors.middleware.auth.clientCredentialsNotProvided') }), false); } // Validate the user ...
javascript
{ "resource": "" }
q15715
assertSetupCompleted
train
function assertSetupCompleted(status) { return function checkPermission(__) { return checkSetup().then((isSetup) => { if (isSetup === status) { return __; } const completed = common.i18n.t('errors.api.authentication.setupAlreadyCompleted'), ...
javascript
{ "resource": "" }
q15716
_isCurrentUrl
train
function _isCurrentUrl(href, currentUrl) { if (!currentUrl) { return false; } var strippedHref = href.replace(/\/+$/, ''), strippedCurrentUrl = currentUrl.replace(/\/+$/, ''); return strippedHref === strippedCurrentUrl; }
javascript
{ "resource": "" }
q15717
parseDefaultSettings
train
function parseDefaultSettings() { var defaultSettingsInCategories = require('../data/schema/').defaultSettings, defaultSettingsFlattened = {}, dynamicDefault = { db_hash: uuid.v4(), public_hash: crypto.randomBytes(15).toString('hex'), // @TODO: session_secret woul...
javascript
{ "resource": "" }
q15718
parsePackageJson
train
function parsePackageJson(path) { return fs.readFile(path) .catch(function () { var err = new Error(common.i18n.t('errors.utils.parsepackagejson.couldNotReadPackage')); err.context = path; return Promise.reject(err); }) .then(function (source) { ...
javascript
{ "resource": "" }
q15719
train
function (items) { return '+(' + _.reduce(items, function (memo, ext) { return memo !== '' ? memo + '|' + ext : ext; }, '') + ')'; }
javascript
{ "resource": "" }
q15720
train
function (directory) { // Globs match content in the root or inside a single directory var extMatchesBase = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_OR_SINGLE_DIR), {cwd: directory}), extMatchesAll = glob.sync( this.getExtensionGlob(this.getExtensions(), ALL...
javascript
{ "resource": "" }
q15721
train
function (filePath) { const tmpDir = path.join(os.tmpdir(), uuid.v4()); this.fileToDelete = tmpDir; return Promise.promisify(extract)(filePath, {dir: tmpDir}).then(function () { return tmpDir; }); }
javascript
{ "resource": "" }
q15722
train
function (handler, directory) { var globPattern = this.getExtensionGlob(handler.extensions, ALL_DIRS); return _.map(glob.sync(globPattern, {cwd: directory}), function (file) { return {name: file, path: path.join(directory, file)}; }); }
javascript
{ "resource": "" }
q15723
train
function (directory) { // Globs match root level only var extMatches = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_ONLY), {cwd: directory}), dirMatches = glob.sync(this.getDirectoryGlob(this.getDirectories(), ROOT_ONLY), {cwd: directory}), extMatchesAll; /...
javascript
{ "resource": "" }
q15724
train
function (file, importOptions = {}) { var self = this; // Step 1: Handle converting the file to usable data return this.loadFile(file).then(function (importData) { // Step 2: Let the importers pre-process the data return self.preProcess(importData); }).then(funct...
javascript
{ "resource": "" }
q15725
trimSchema
train
function trimSchema(schema) { var schemaObject = {}; _.each(schema, function (value, key) { if (value !== null && typeof value !== 'undefined') { schemaObject[key] = value; } }); return schemaObject; }
javascript
{ "resource": "" }
q15726
sequence
train
function sequence(tasks /* Any Arguments */) { const args = Array.prototype.slice.call(arguments, 1); return Promise.reduce(tasks, function (results, task) { const response = task.apply(this, args); if (response && response.then) { return response.then(function (result) { ...
javascript
{ "resource": "" }
q15727
characterOccurance
train
function characterOccurance(stringToTest) { var chars = {}, allowedOccurancy, valid = true; stringToTest = _.toString(stringToTest); allowedOccurancy = stringToTest.length / 2; // Loop through string and accumulate character counts _.each(stringToTest, function (char) { if ...
javascript
{ "resource": "" }
q15728
permittedAttributes
train
function permittedAttributes() { let filteredKeys = ghostBookshelf.Model.prototype.permittedAttributes.apply(this, arguments); this.relationships.forEach((key) => { filteredKeys.push(key); }); return filteredKeys; }
javascript
{ "resource": "" }
q15729
train
function (name) { const {app, proxy} = getAppByName(name); // Check for an activate() method on the app. if (!_.isFunction(app.activate)) { return Promise.reject(new Error(common.i18n.t('errors.apps.noActivateMethodLoadingApp.error', {name: name}))); } // Wrapping t...
javascript
{ "resource": "" }
q15730
getPostData
train
function getPostData(req, res, next) { req.body = req.body || {}; const urlWithoutSubdirectoryWithoutAmp = res.locals.relativeUrl.match(/(.*?\/)amp\/?$/)[1]; /** * @NOTE * * We have to figure out the target permalink, otherwise it would be possible to serve a post * which lives in two ...
javascript
{ "resource": "" }
q15731
getImageDimensions
train
function getImageDimensions(metaData) { var fetch = { coverImage: imageLib.imageSizeCache(metaData.coverImage.url), authorImage: imageLib.imageSizeCache(metaData.authorImage.url), ogImage: imageLib.imageSizeCache(metaData.ogImage.url), logo: imageLib.imageSizeCache(metaData.blog.logo...
javascript
{ "resource": "" }
q15732
train
function (perm) { var permObjId; // Look for a matching action type and object type first if (perm.get('action_type') !== actType || perm.get('object_type') !== objType) { return false; } ...
javascript
{ "resource": "" }
q15733
sendMail
train
function sendMail(object) { if (!(mailer instanceof mail.GhostMailer)) { mailer = new mail.GhostMailer(); } return mailer.send(object.mail[0].message).catch((err) => { if (mailer.state.usingDirect) { notificationsAPI.add( { notifications: [{ ...
javascript
{ "resource": "" }
q15734
errorHandler
train
function errorHandler(error, req, res, next) { req.body.email = ''; req.body.subscribed_url = santizeUrl(req.body.subscribed_url); req.body.subscribed_referrer = santizeUrl(req.body.subscribed_referrer); if (error.statusCode !== 404) { res.locals.error = error; return _renderer(req, res...
javascript
{ "resource": "" }
q15735
exportSubscribers
train
function exportSubscribers() { return models.Subscriber.findAll(options).then((data) => { return formatCSV(data.toJSON(options)); }).catch((err) => { return Promise.reject(new common.errors.GhostError({err: err})); }); }
javascript
{ "resource": "" }
q15736
t
train
function t(path, bindings) { let string, isTheme, msg; currentLocale = I18n.locale(); if (bindings !== undefined) { isTheme = bindings.isThemeString; delete bindings.isThemeString; } string = I18n.findString(path, {isThemeString: isTheme}); // If...
javascript
{ "resource": "" }
q15737
findString
train
function findString(msgPath, opts) { const options = merge({log: true}, opts || {}); let candidateString, matchingString, path; // no path? no string if (msgPath.length === 0 || !isString(msgPath)) { chalk.yellow('i18n.t() - received an empty path.'); return ''; ...
javascript
{ "resource": "" }
q15738
onSaved
train
function onSaved(model, response, options) { ghostBookshelf.Model.prototype.onSaved.apply(this, arguments); if (options.method !== 'insert') { return; } var status = model.get('status'); model.emitChange('added', options); if (['published', 'scheduled'].in...
javascript
{ "resource": "" }
q15739
filterData
train
function filterData(data) { var filteredData = ghostBookshelf.Model.filterData.apply(this, arguments), extraData = _.pick(data, this.prototype.relationships); _.merge(filteredData, extraData); return filteredData; }
javascript
{ "resource": "" }
q15740
hideMembersOnlyContent
train
function hideMembersOnlyContent(attrs, frame) { const membersEnabled = labs.isSet('members'); if (!membersEnabled) { return PERMIT_CONTENT; } const postHasMemberTag = attrs.tags && attrs.tags.find((tag) => { return (tag.name === MEMBER_TAG); }); const requestFromMember = frame.o...
javascript
{ "resource": "" }
q15741
getVersionPath
train
function getVersionPath(options) { const apiVersions = config.get('api:versions'); let requestedVersion = options.version || 'v0.1'; let requestedVersionType = options.type || 'content'; let versionData = apiVersions[requestedVersion]; if (typeof versionData === 'string') { versionData = api...
javascript
{ "resource": "" }
q15742
getBlogUrl
train
function getBlogUrl(secure) { var blogUrl; if (secure) { blogUrl = config.get('url').replace('http://', 'https://'); } else { blogUrl = config.get('url'); } if (!blogUrl.match(/\/$/)) { blogUrl += '/'; } return blogUrl; }
javascript
{ "resource": "" }
q15743
getSubdir
train
function getSubdir() { // Parse local path location var localPath = url.parse(config.get('url')).path, subdir; // Remove trailing slash if (localPath !== '/') { localPath = localPath.replace(/\/$/, ''); } subdir = localPath === '/' ? '' : localPath; return subdir; }
javascript
{ "resource": "" }
q15744
replacePermalink
train
function replacePermalink(permalink, resource) { let output = permalink, primaryTagFallback = 'all', publishedAtMoment = moment.tz(resource.published_at || Date.now(), settingsCache.get('active_timezone')), permalinkLookUp = { year: function () { return publishedA...
javascript
{ "resource": "" }
q15745
makeAbsoluteUrls
train
function makeAbsoluteUrls(html, siteUrl, itemUrl, options = {assetsOnly: false}) { html = html || ''; const htmlContent = cheerio.load(html, {decodeEntities: false}); const staticImageUrlPrefixRegex = new RegExp(STATIC_IMAGE_URL_PREFIX); // convert relative resource urls to absolute ['href', 'src']...
javascript
{ "resource": "" }
q15746
initialize
train
function initialize() { var self = this; // NOTE: triggered before `creating`/`updating` this.on('saving', function onSaving(newObj, attrs, options) { if (options.method === 'insert') { // id = 0 is still a valid value for external usage if (_.isUndef...
javascript
{ "resource": "" }
q15747
onUpdating
train
function onUpdating(model, attr, options) { if (this.relationships) { model.changed = _.omit(model.changed, this.relationships); } if (schema.tables[this.tableName].hasOwnProperty('updated_by')) { if (!options.importing && !options.migrating) { this.set('...
javascript
{ "resource": "" }
q15748
fixDates
train
function fixDates(attrs) { var self = this; _.each(attrs, function each(value, key) { if (value !== null && schema.tables[self.tableName].hasOwnProperty(key) && schema.tables[self.tableName][key].type === 'dateTime') { attrs[key] = moment(valu...
javascript
{ "resource": "" }
q15749
fixBools
train
function fixBools(attrs) { var self = this; _.each(attrs, function each(value, key) { if (schema.tables[self.tableName].hasOwnProperty(key) && schema.tables[self.tableName][key].type === 'bool') { attrs[key] = value ? true : false; } }); ...
javascript
{ "resource": "" }
q15750
contextUser
train
function contextUser(options) { options = options || {}; options.context = options.context || {}; if (options.context.user || ghostBookshelf.Model.isExternalUser(options.context.user)) { return options.context.user; } else if (options.context.integration) { /** ...
javascript
{ "resource": "" }
q15751
toJSON
train
function toJSON(unfilteredOptions) { const options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'toJSON'); options.omitPivot = true; // CASE: get JSON of previous attrs if (options.previous) { const clonedModel = _.cloneDeep(this); clonedModel.attribut...
javascript
{ "resource": "" }
q15752
permittedOptions
train
function permittedOptions(methodName) { const baseOptions = ['context', 'withRelated']; const extraOptions = ['transacting', 'importing', 'forUpdate', 'migrating']; switch (methodName) { case 'toJSON': return baseOptions.concat('shallow', 'columns', 'previous'); case...
javascript
{ "resource": "" }
q15753
sanitizeData
train
function sanitizeData(data) { var tableName = _.result(this.prototype, 'tableName'), date; _.each(data, (value, property) => { if (value !== null && schema.tables[tableName].hasOwnProperty(property) && schema.tables[tableName][property].type === 'dateTime' ...
javascript
{ "resource": "" }
q15754
filterByVisibility
train
function filterByVisibility(items, visibility, explicit, fn) { var memo = _.isArray(items) ? [] : {}; if (_.includes(visibility, 'all')) { return fn ? _.map(items, fn) : items; } // We don't want to change the structure of what is returned return _.reduce(items, fun...
javascript
{ "resource": "" }
q15755
handleMessage
train
function handleMessage(message) { var type = message.data.type; var id = message.data.id; var payload = message.data.payload; switch(type) { case 'load-index': makeRequest(SEARCH_TERMS_URL, function(searchInfo) { index = createIndex(loadIndex(searchInfo)); self.postMessage({type: type,...
javascript
{ "resource": "" }
q15756
makeRequest
train
function makeRequest(url, callback) { // The JSON file that is loaded should be an array of PageInfo: var searchDataRequest = new XMLHttpRequest(); searchDataRequest.onload = function() { callback(JSON.parse(this.responseText)); }; searchDataRequest.open('GET', url); searchDataRequest.send(); }
javascript
{ "resource": "" }
q15757
loadIndex
train
function loadIndex(searchInfo /*: SearchInfo */) { return function(index) { // Store the pages data to be used in mapping query results back to pages // Add search terms from each page to the search index searchInfo.forEach(function(page /*: PageInfo */) { index.add(page); pages[page.path] = p...
javascript
{ "resource": "" }
q15758
createImportTargets
train
function createImportTargets(importTargets, targetName, targetDirectory) { const importMap = {}; for (const x in importTargets) { importMap['rxjs/' + x] = ('rxjs-compat/' + targetName + importTargets[x]).replace(/\.js$/, ''); } const outputData = ` "use strict" var path = require('path'); var dir = path.r...
javascript
{ "resource": "" }
q15759
spinner
train
function spinner(promise, text = 'loading', spinnerIcon = 'monkey') { const spinner = ora({ spinner: spinnerIcon, text }).start(); return new Promise((resolve, reject) => { promise .then(resolved => { spinner.stop(); resolve(resolved); }) ...
javascript
{ "resource": "" }
q15760
askTypeOfApplication
train
function askTypeOfApplication() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'list', name: 'applicationType', message: 'Which *type* of application would you like to deploy?', choices: [ { ...
javascript
{ "resource": "" }
q15761
askRegion
train
function askRegion() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'list', name: 'region', message: 'Which region?', choices: regionList, default: this.aws.region ? _.indexOf(regionList, this.aws.region...
javascript
{ "resource": "" }
q15762
askCloudFormation
train
function askCloudFormation() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'input', name: 'cloudFormationName', message: "Please enter your stack's name. (must be unique within a region)", default: this.aws.cloudFo...
javascript
{ "resource": "" }
q15763
askPerformances
train
function askPerformances() { if (this.abort) return null; const done = this.async(); const chainPromises = index => { if (index === this.appConfigs.length) { done(); return null; } const config = this.appConfigs[index]; const awsConfig = this.aws.apps....
javascript
{ "resource": "" }
q15764
askScaling
train
function askScaling() { if (this.abort) return null; const done = this.async(); const chainPromises = index => { if (index === this.appConfigs.length) { done(); return null; } const config = this.appConfigs[index]; const awsConfig = this.aws.apps.find(...
javascript
{ "resource": "" }
q15765
askVPC
train
function askVPC() { if (this.abort) return null; const done = this.async(); const vpcList = this.awsFacts.availableVpcs.map(vpc => { const friendlyName = _getFriendlyNameFromTag(vpc); return { name: `ID: ${vpc.VpcId} (${friendlyName ? `name: '${friendlyName}', ` : ''}default: ${...
javascript
{ "resource": "" }
q15766
askDeployNow
train
function askDeployNow() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'confirm', name: 'deployNow', message: 'Would you like to deploy now?.', default: true } ]; return this.prompt(prompts).then(pr...
javascript
{ "resource": "" }
q15767
_doesEventContainsNestedStackId
train
function _doesEventContainsNestedStackId(stack) { if (stack.ResourceType !== 'AWS::CloudFormation::Stack') { return false; } if (stack.ResourceStatusReason !== 'Resource creation Initiated') { return false; } if (stack.ResourceStatus !== 'CREATE_IN_PROGRESS') { return false; ...
javascript
{ "resource": "" }
q15768
_formatStatus
train
function _formatStatus(status) { let statusColorFn = chalk.grey; if (_.endsWith(status, 'IN_PROGRESS')) { statusColorFn = chalk.yellow; } else if (_.endsWith(status, 'FAILED') || _.startsWith(status, 'DELETE')) { statusColorFn = chalk.red; } else if (_.endsWith(status, 'COMPLETE')) { ...
javascript
{ "resource": "" }
q15769
_getStackLogLine
train
function _getStackLogLine(stack, indentation = 0) { const time = chalk.blue(`${stack.Timestamp.toLocaleTimeString()}`); const spacing = _.repeat('\t', indentation); const status = _formatStatus(stack.ResourceStatus); const stackName = chalk.grey(stack.StackName); const resourceType = chalk.bold(sta...
javascript
{ "resource": "" }
q15770
loginToAws
train
function loginToAws(region, accountId, username, password) { const commandLine = `docker login --username AWS --password ${password} https://${accountId}.dkr.ecr.${region}.amazonaws.com`; return new Promise( (resolve, reject) => command(commandLine, (err, stdout) => { if (err...
javascript
{ "resource": "" }
q15771
pushImage
train
function pushImage(repository) { const commandLine = `docker push ${repository}`; return new Promise((resolve, reject) => command(commandLine, (err, stdout) => { if (err) { reject(err); } resolve(stdout); }) ); }
javascript
{ "resource": "" }
q15772
checkDocker
train
function checkDocker() { if (this.abort || this.skipChecks) return; const done = this.async(); shelljs.exec('docker -v', { silent: true }, (code, stdout, stderr) => { if (stderr) { this.log( chalk.red( 'Docker version 1.10.0 or later is not installed ...
javascript
{ "resource": "" }
q15773
checkImageExist
train
function checkImageExist(opts = { cwd: './', appConfig: null }) { if (this.abort) return; let imagePath = ''; this.warning = false; this.warningMessage = 'To generate the missing Docker image(s), please run:\n'; if (opts.appConfig.buildTool === 'maven') { imagePath = this.destinationPath(`$...
javascript
{ "resource": "" }
q15774
importJDL
train
function importJDL() { logger.info('The JDL is being parsed.'); const jdlImporter = new jhiCore.JDLImporter(this.jdlFiles, { databaseType: this.prodDatabaseType, applicationType: this.applicationType, applicationName: this.baseName, generatorVersion: packagejs.version, fo...
javascript
{ "resource": "" }
q15775
cleanupOldFiles
train
function cleanupOldFiles(generator) { if (generator.isJhipsterVersionLessThan('3.2.0')) { // removeFile and removeFolder methods should be called here for files and folders to cleanup generator.removeFile(`${ANGULAR_DIR}components/form/uib-pager.config.js`); generator.removeFile(`${ANGULAR_D...
javascript
{ "resource": "" }
q15776
rewriteFile
train
function rewriteFile(args, generator) { args.path = args.path || process.cwd(); const fullPath = path.join(args.path, args.file); args.haystack = generator.fs.read(fullPath); const body = rewrite(args); generator.fs.write(fullPath, body); }
javascript
{ "resource": "" }
q15777
rewrite
train
function rewrite(args) { // check if splicable is already in the body text const re = new RegExp(args.splicable.map(line => `\\s*${escapeRegExp(line)}`).join('\n')); if (re.test(args.haystack)) { return args.haystack; } const lines = args.haystack.split('\n'); let otherwiseLineIndex =...
javascript
{ "resource": "" }
q15778
rewriteJSONFile
train
function rewriteJSONFile(filePath, rewriteFile, generator) { const jsonObj = generator.fs.readJSON(filePath); rewriteFile(jsonObj, generator); generator.fs.writeJSON(filePath, jsonObj, null, 2); }
javascript
{ "resource": "" }
q15779
copyWebResource
train
function copyWebResource(source, dest, regex, type, generator, opt = {}, template) { if (generator.enableTranslation) { generator.template(source, dest, generator, opt); } else { renderContent(source, generator, generator, opt, body => { body = body.replace(regex, ''); sw...
javascript
{ "resource": "" }
q15780
getJavadoc
train
function getJavadoc(text, indentSize) { if (!text) { text = ''; } if (text.includes('"')) { text = text.replace(/"/g, '\\"'); } let javadoc = `${_.repeat(' ', indentSize)}/**`; const rows = text.split('\n'); for (let i = 0; i < rows.length; i++) { javadoc = `${javadoc...
javascript
{ "resource": "" }
q15781
buildEnumInfo
train
function buildEnumInfo(field, angularAppName, packageName, clientRootFolder) { const fieldType = field.fieldType; field.enumInstance = _.lowerFirst(fieldType); const enumInfo = { enumName: fieldType, enumValues: field.fieldValues.split(',').join(', '), enumInstance: field.enumInstanc...
javascript
{ "resource": "" }
q15782
getAllJhipsterConfig
train
function getAllJhipsterConfig(generator, force) { let configuration = generator && generator.config ? generator.config.getAll() || {} : {}; if ((force || !configuration.baseName) && jhiCore.FileUtils.doesFileExist('.yo-rc.json')) { const yoRc = JSON.parse(fs.readFileSync('.yo-rc.json', { encoding: 'utf-...
javascript
{ "resource": "" }
q15783
getDBTypeFromDBValue
train
function getDBTypeFromDBValue(db) { if (constants.SQL_DB_OPTIONS.map(db => db.value).includes(db)) { return 'sql'; } return db; }
javascript
{ "resource": "" }
q15784
askForRelationship
train
function askForRelationship(done) { const context = this.context; const name = context.name; this.log(chalk.green('\nGenerating relationships to other entities\n')); const fieldNamesUnderscored = context.fieldNamesUnderscored; const prompts = [ { type: 'confirm', name...
javascript
{ "resource": "" }
q15785
logFieldsAndRelationships
train
function logFieldsAndRelationships() { const context = this.context; if (context.fields.length > 0 || context.relationships.length > 0) { this.log(chalk.red(chalk.white('\n================= ') + context.entityNameCapitalized + chalk.white(' ================='))); } if (context.fields.length > 0)...
javascript
{ "resource": "" }
q15786
loadAWS
train
function loadAWS(generator) { return new Promise((resolve, reject) => { try { AWS = require('aws-sdk'); // eslint-disable-line ProgressBar = require('progress'); // eslint-disable-line ora = require('ora'); // eslint-disable-line } catch (e) { generato...
javascript
{ "resource": "" }
q15787
initAwsStuff
train
function initAwsStuff(region = DEFAULT_REGION) { ec2 = new AWS.EC2({ region }); // ecr = new AWS.ECR({ region }); s3 = new AWS.S3(); sts = new AWS.STS(); SSM = new AwsSSM(region); ECR = new AwsECR(region); CF = new AwsCF(region); }
javascript
{ "resource": "" }
q15788
getDockerLogin
train
function getDockerLogin() { return spinner( new Promise((resolve, reject) => _getAuthorizationToken().then(authToken => sts .getCallerIdentity({}) .promise() .then(data => { const decoded = utils....
javascript
{ "resource": "" }
q15789
_getAuthorizationToken
train
function _getAuthorizationToken() { return spinner( new Promise((resolve, reject) => ECR.sdk .getAuthorizationToken({}) .promise() .then(data => { if (!_.has(data, 'authorizationData.0')) { reject(new Err...
javascript
{ "resource": "" }
q15790
createS3Bucket
train
function createS3Bucket(bucketName, region = DEFAULT_REGION) { const createBuckerParams = { Bucket: bucketName }; return spinner( new Promise((resolve, reject) => s3 .headBucket({ Bucket: bucketName }) .promise()...
javascript
{ "resource": "" }
q15791
uploadTemplate
train
function uploadTemplate(bucketName, filename, path) { return spinner( new Promise((resolve, reject) => fs.stat(path, (error, stats) => { if (!stats) { reject(new Error(`File ${chalk.bold(path)} not found`)); } const upload = s3....
javascript
{ "resource": "" }
q15792
askForApplicationType
train
function askForApplicationType() { if (this.regenerate) return; const done = this.async(); const prompts = [ { type: 'list', name: 'deploymentApplicationType', message: 'Which *type* of application would you like to deploy?', choices: [ ...
javascript
{ "resource": "" }
q15793
askForPath
train
function askForPath() { if (this.regenerate) return; const done = this.async(); const deploymentApplicationType = this.deploymentApplicationType; let messageAskForPath; if (deploymentApplicationType === 'monolith') { messageAskForPath = 'Enter the root directory where your applications are ...
javascript
{ "resource": "" }
q15794
askForApps
train
function askForApps() { if (this.regenerate) return; const done = this.async(); const messageAskForApps = 'Which applications do you want to include in your configuration?'; const prompts = [ { type: 'checkbox', name: 'chosenApps', message: messageAskForApps...
javascript
{ "resource": "" }
q15795
askForClustersMode
train
function askForClustersMode() { if (this.regenerate) return; const clusteredDbApps = []; this.appConfigs.forEach((appConfig, index) => { if (appConfig.prodDatabaseType === 'mongodb' || appConfig.prodDatabaseType === 'couchbase') { clusteredDbApps.push(this.appsFolders[index]); }...
javascript
{ "resource": "" }
q15796
askForMonitoring
train
function askForMonitoring() { if (this.regenerate) return; const done = this.async(); const prompts = [ { type: 'list', name: 'monitoring', message: 'Do you want to setup monitoring for your applications ?', choices: [ { ...
javascript
{ "resource": "" }
q15797
askForConsoleOptions
train
function askForConsoleOptions() { if (this.regenerate) return; if (this.monitoring !== 'elk') return; const done = this.async(); const prompts = [ { type: 'checkbox', name: 'consoleOptions', message: 'You have selected the JHipster Console w...
javascript
{ "resource": "" }
q15798
askForServiceDiscovery
train
function askForServiceDiscovery() { if (this.regenerate) return; const done = this.async(); const serviceDiscoveryEnabledApps = []; this.appConfigs.forEach((appConfig, index) => { if (appConfig.serviceDiscoveryType) { serviceDiscoveryEnabledApps.push({ baseName: app...
javascript
{ "resource": "" }
q15799
askForAdminPassword
train
function askForAdminPassword() { if (this.regenerate || this.serviceDiscoveryType !== 'eureka') return; const done = this.async(); const prompts = [ { type: 'input', name: 'adminPassword', message: 'Enter the admin password used to secure the JHipster Registry',...
javascript
{ "resource": "" }