_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q17700 | onSignInConfirmPhoneVerification | train | function onSignInConfirmPhoneVerification() {
var verificationId = $('#signin-phone-verification-id').val();
var verificationCode = $('#signin-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
signInOrLinkCredential(credential);
} | javascript | {
"resource": ""
} |
q17701 | onLinkReauthVerifyPhoneNumber | train | function onLinkReauthVerifyPhoneNumber() {
var phoneNumber = $('#link-reauth-phone-number').val();
var provider = new firebase.auth.PhoneAuthProvider(auth);
// Clear existing reCAPTCHA as an existing reCAPTCHA could be targeted for a
// sign-in operation.
clearApplicationVerifier();
// Initialize a reCAPTCHA application verifier.
makeApplicationVerifier('link-reauth-verify-phone-number');
provider.verifyPhoneNumber(phoneNumber, applicationVerifier)
.then(function(verificationId) {
clearApplicationVerifier();
$('#link-reauth-phone-verification-id').val(verificationId);
alertSuccess('Phone verification sent!');
}, function(error) {
clearApplicationVerifier();
onAuthError(error);
});
} | javascript | {
"resource": ""
} |
q17702 | onUpdateConfirmPhoneVerification | train | function onUpdateConfirmPhoneVerification() {
if (!activeUser()) {
alertError('You need to sign in before linking an account.');
return;
}
var verificationId = $('#link-reauth-phone-verification-id').val();
var verificationCode = $('#link-reauth-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
activeUser().updatePhoneNumber(credential).then(function() {
refreshUserData();
alertSuccess('Phone number updated!');
}, onAuthError);
} | javascript | {
"resource": ""
} |
q17703 | onReauthConfirmPhoneVerification | train | function onReauthConfirmPhoneVerification() {
var verificationId = $('#link-reauth-phone-verification-id').val();
var verificationCode = $('#link-reauth-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
activeUser().reauthenticateWithCredential(credential)
.then(function(result) {
logAdditionalUserInfo(result);
refreshUserData();
alertSuccess('User reauthenticated!');
}, onAuthError);
} | javascript | {
"resource": ""
} |
q17704 | signInOrLinkCredential | train | function signInOrLinkCredential(credential) {
if (currentTab == '#user-section') {
if (!activeUser()) {
alertError('You need to sign in before linking an account.');
return;
}
activeUser().linkWithCredential(credential)
.then(function(result) {
logAdditionalUserInfo(result);
refreshUserData();
alertSuccess('Provider linked!');
}, onAuthError);
} else {
auth.signInWithCredential(credential)
.then(onAuthUserCredentialSuccess, onAuthError);
}
} | javascript | {
"resource": ""
} |
q17705 | onChangeEmail | train | function onChangeEmail() {
var email = $('#changed-email').val();
activeUser().updateEmail(email).then(function() {
refreshUserData();
alertSuccess('Email changed!');
}, onAuthError);
} | javascript | {
"resource": ""
} |
q17706 | onSendSignInLinkToEmail | train | function onSendSignInLinkToEmail() {
var email = $('#sign-in-with-email-link-email').val();
auth.sendSignInLinkToEmail(email, getActionCodeSettings()).then(function() {
alertSuccess('Email sent!');
}, onAuthError);
} | javascript | {
"resource": ""
} |
q17707 | onSendSignInLinkToEmailCurrentUrl | train | function onSendSignInLinkToEmailCurrentUrl() {
var email = $('#sign-in-with-email-link-email').val();
var actionCodeSettings = {
'url': window.location.href,
'handleCodeInApp': true
};
auth.sendSignInLinkToEmail(email, actionCodeSettings).then(function() {
if ('localStorage' in window && window['localStorage'] !== null) {
window.localStorage.setItem(
'emailForSignIn',
// Save the email and the timestamp.
JSON.stringify({
email: email,
timestamp: new Date().getTime()
}));
}
alertSuccess('Email sent!');
}, onAuthError);
} | javascript | {
"resource": ""
} |
q17708 | onSendPasswordResetEmail | train | function onSendPasswordResetEmail() {
var email = $('#password-reset-email').val();
auth.sendPasswordResetEmail(email, getActionCodeSettings()).then(function() {
alertSuccess('Email sent!');
}, onAuthError);
} | javascript | {
"resource": ""
} |
q17709 | onConfirmPasswordReset | train | function onConfirmPasswordReset() {
var code = $('#password-reset-code').val();
var password = $('#password-reset-password').val();
auth.confirmPasswordReset(code, password).then(function() {
alertSuccess('Password has been changed!');
}, onAuthError);
} | javascript | {
"resource": ""
} |
q17710 | onFetchSignInMethodsForEmail | train | function onFetchSignInMethodsForEmail() {
var email = $('#fetch-sign-in-methods-email').val();
auth.fetchSignInMethodsForEmail(email).then(function(signInMethods) {
log('Sign in methods for ' + email + ' :');
log(signInMethods);
if (signInMethods.length == 0) {
alertSuccess('Sign In Methods for ' + email + ': N/A');
} else {
alertSuccess(
'Sign In Methods for ' + email +': ' + signInMethods.join(', '));
}
}, onAuthError);
} | javascript | {
"resource": ""
} |
q17711 | onLinkWithEmailAndPassword | train | function onLinkWithEmailAndPassword() {
var email = $('#link-email').val();
var password = $('#link-password').val();
activeUser().linkWithCredential(
firebase.auth.EmailAuthProvider.credential(email, password))
.then(onAuthUserCredentialSuccess, onAuthError);
} | javascript | {
"resource": ""
} |
q17712 | onLinkWithGenericIdPCredential | train | function onLinkWithGenericIdPCredential() {
var providerId = $('#link-generic-idp-provider-id').val();
var idToken = $('#link-generic-idp-id-token').val();
var accessToken = $('#link-generic-idp-access-token').val();
var provider = new firebase.auth.OAuthProvider(providerId);
activeUser().linkWithCredential(
provider.credential(idToken, accessToken))
.then(onAuthUserCredentialSuccess, onAuthError);
} | javascript | {
"resource": ""
} |
q17713 | onUnlinkProvider | train | function onUnlinkProvider() {
var providerId = $('#unlinked-provider-id').val();
activeUser().unlink(providerId).then(function(user) {
alertSuccess('Provider unlinked from user.');
refreshUserData();
}, onAuthError);
} | javascript | {
"resource": ""
} |
q17714 | onApplyActionCode | train | function onApplyActionCode() {
var code = $('#email-verification-code').val();
auth.applyActionCode(code).then(function() {
alertSuccess('Email successfully verified!');
refreshUserData();
}, onAuthError);
} | javascript | {
"resource": ""
} |
q17715 | getIdToken | train | function getIdToken(forceRefresh) {
if (activeUser() == null) {
alertError('No user logged in.');
return;
}
if (activeUser().getIdToken) {
activeUser().getIdToken(forceRefresh).then(alertSuccess, function() {
log("No token");
});
} else {
activeUser().getToken(forceRefresh).then(alertSuccess, function() {
log("No token");
});
}
} | javascript | {
"resource": ""
} |
q17716 | getIdTokenResult | train | function getIdTokenResult(forceRefresh) {
if (activeUser() == null) {
alertError('No user logged in.');
return;
}
activeUser().getIdTokenResult(forceRefresh).then(function(idTokenResult) {
alertSuccess(JSON.stringify(idTokenResult));
}, onAuthError);
} | javascript | {
"resource": ""
} |
q17717 | onGetRedirectResult | train | function onGetRedirectResult() {
auth.getRedirectResult().then(function(response) {
log('Redirect results:');
if (response.credential) {
log('Credential:');
log(response.credential);
} else {
log('No credential');
}
if (response.user) {
log('User\'s id:');
log(response.user.uid);
} else {
log('No user');
}
logAdditionalUserInfo(response);
console.log(response);
}, onAuthError);
} | javascript | {
"resource": ""
} |
q17718 | logAdditionalUserInfo | train | function logAdditionalUserInfo(response) {
if (response.additionalUserInfo) {
if (response.additionalUserInfo.username) {
log(response.additionalUserInfo['providerId'] + ' username: ' +
response.additionalUserInfo.username);
}
if (response.additionalUserInfo.profile) {
log(response.additionalUserInfo['providerId'] + ' profile information:');
log(JSON.stringify(response.additionalUserInfo.profile, null, 2));
}
if (typeof response.additionalUserInfo.isNewUser !== 'undefined') {
log(response.additionalUserInfo['providerId'] + ' isNewUser: ' +
response.additionalUserInfo.isNewUser);
}
}
} | javascript | {
"resource": ""
} |
q17719 | populateActionCodes | train | function populateActionCodes() {
var emailForSignIn = null;
var signInTime = 0;
if ('localStorage' in window && window['localStorage'] !== null) {
try {
// Try to parse as JSON first using new storage format.
var emailForSignInData =
JSON.parse(window.localStorage.getItem('emailForSignIn'));
emailForSignIn = emailForSignInData['email'] || null;
signInTime = emailForSignInData['timestamp'] || 0;
} catch (e) {
// JSON parsing failed. This means the email is stored in the old string
// format.
emailForSignIn = window.localStorage.getItem('emailForSignIn');
}
if (emailForSignIn) {
// Clear old codes. Old format codes should be cleared immediately.
if (new Date().getTime() - signInTime >= 1 * 24 * 3600 * 1000) {
// Remove email from storage.
window.localStorage.removeItem('emailForSignIn');
}
}
}
var actionCode = getParameterByName('oobCode');
if (actionCode != null) {
var mode = getParameterByName('mode');
if (mode == 'verifyEmail') {
$('#email-verification-code').val(actionCode);
} else if (mode == 'resetPassword') {
$('#password-reset-code').val(actionCode);
} else if (mode == 'signIn') {
if (emailForSignIn) {
$('#sign-in-with-email-link-email').val(emailForSignIn);
$('#sign-in-with-email-link-link').val(window.location.href);
onSignInWithEmailLink();
// Remove email from storage as the code is only usable once.
window.localStorage.removeItem('emailForSignIn');
}
} else {
$('#email-verification-code').val(actionCode);
$('#password-reset-code').val(actionCode);
}
}
} | javascript | {
"resource": ""
} |
q17720 | onCopyActiveUser | train | function onCopyActiveUser() {
tempAuth.updateCurrentUser(activeUser()).then(function() {
alertSuccess('Copied active user to temp Auth');
}, function(error) {
alertError('Error: ' + error.code);
});
} | javascript | {
"resource": ""
} |
q17721 | onCopyLastUser | train | function onCopyLastUser() {
// If last user is null, NULL_USER error will be thrown.
auth.updateCurrentUser(lastUser).then(function() {
alertSuccess('Copied last user to Auth');
}, function(error) {
alertError('Error: ' + error.code);
});
} | javascript | {
"resource": ""
} |
q17722 | onApplyAuthSettingsChange | train | function onApplyAuthSettingsChange() {
try {
auth.settings.appVerificationDisabledForTesting =
$("input[name=enable-app-verification]:checked").val() == 'No';
alertSuccess('Auth settings changed');
} catch (error) {
alertError('Error: ' + error.code);
}
} | javascript | {
"resource": ""
} |
q17723 | train | function() {
if (!self.initialized_) {
self.initialized_ = true;
// Listen to Auth events on iframe.
self.oauthSignInHandler_.addAuthEventListener(self.authEventHandler_);
}
} | javascript | {
"resource": ""
} | |
q17724 | train | function() {
// The developer may have tried to previously run gapi.load and failed.
// Run this to fix that.
fireauth.util.resetUnloadedGapiModules();
var loader = /** @type {function(string, !Object)} */ (
fireauth.util.getObjectRef('gapi.load'));
loader('gapi.iframes', {
'callback': resolve,
'ontimeout': function() {
// The above reset may be sufficient, but having this reset after
// failure ensures that if the developer calls gapi.load after the
// connection is re-established and before another attempt to embed
// the iframe, it would work and would not be broken because of our
// failed attempt.
// Timeout when gapi.iframes.Iframe not loaded.
fireauth.util.resetUnloadedGapiModules();
reject(new Error('Network Error'));
},
'timeout': fireauth.iframeclient.IframeWrapper.NETWORK_TIMEOUT_.get()
});
} | javascript | {
"resource": ""
} | |
q17725 | createBuildTask | train | function createBuildTask(filename, prefix, suffix) {
return () =>
gulp
.src([
`${closureLibRoot}/closure/goog/**/*.js`,
`${closureLibRoot}/third_party/closure/goog/**/*.js`,
'src/**/*.js'
], { base: '.' })
.pipe(sourcemaps.init())
.pipe(
closureCompiler({
js_output_file: filename,
output_wrapper: `${prefix}%output%${suffix}`,
entry_point: 'fireauth.exports',
compilation_level: OPTIMIZATION_LEVEL,
externs: [
'externs/externs.js',
'externs/grecaptcha.js',
'externs/gapi.iframes.js',
path.resolve(
__dirname,
'../firebase/externs/firebase-app-externs.js'
),
path.resolve(
__dirname,
'../firebase/externs/firebase-error-externs.js'
),
path.resolve(
__dirname,
'../firebase/externs/firebase-app-internal-externs.js'
)
],
language_out: 'ES5',
only_closure_dependencies: true
})
)
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'));
} | javascript | {
"resource": ""
} |
q17726 | defaultVersionMatcher | train | function defaultVersionMatcher(raw) {
// sanity check
if (ramda.isNil(raw) || ramda.isEmpty(raw)) return null
try {
// look for something that looks like semver
var rx = /([0-9]+\.[0-9]+\.[0-9]+)/
var match = ramda.match(rx, raw)
if (match.length > 0) {
return match[0]
} else {
return null
}
} catch (err) {
// something tragic happened
return false
}
} | javascript | {
"resource": ""
} |
q17727 | enforce | train | function enforce(opts = {}) {
// opts to pass in
var optional = opts.optional || false
var range = opts.range
var whichExec = opts.which
var packageName = opts.packageName || opts.which
var versionCommand = opts.versionCommand
var installMessage = opts.installMessage
var versionMatcher = opts.versionMatcher || defaultVersionMatcher
/**
* Prints a friendly message that they don't meet the requirement.
*
* @param {string} installedVersion - current version if installed.
*/
function printNotMetMessage(installedVersion) {
console.log('Ignite CLI requires ' + packageName + ' ' + range + ' to be installed.')
if (installedVersion) {
console.log('')
console.log('You currently have ' + installedVersion + ' installed.')
}
console.log('')
console.log(installMessage)
}
/**
* Gets the version from the global dependency.
*
* @return {string} The version number or null.
*/
function getVersion() {
// parse the version number
try {
// find the executable
var resolvedPath = which.sync(whichExec)
// grab the raw output
var result = shell.exec(`"${resolvedPath}" ${versionCommand}`, { silent: true })
var rawOut = ramda.trim(result.stdout || '')
var rawErr = ramda.trim(result.stderr || '') // java -version does this... grr
// assign the "right" one to raw
var raw = rawOut
if (ramda.isEmpty(raw)) {
raw = rawErr
}
if (ramda.isEmpty(raw)) {
raw = null
}
// and run it by the version matcher
return versionMatcher(raw)
} catch (err) {
return null
}
}
// are we installed?
var isInstalled = Boolean(shell.which(whichExec))
if (!isInstalled) {
if (optional) {
return true
} else {
printNotMetMessage()
return false
}
}
// which version is installed?
try {
var installedVersion = getVersion()
var isMet = semver.satisfies(installedVersion, range)
// dependency has minimum met, we're good.
if (isMet) return true
} catch (err) {
// can't parse? just catch and we'll fallback to an error.
}
// o snap, time to upgrade
printNotMetMessage(installedVersion)
return false
} | javascript | {
"resource": ""
} |
q17728 | printNotMetMessage | train | function printNotMetMessage(installedVersion) {
console.log('Ignite CLI requires ' + packageName + ' ' + range + ' to be installed.')
if (installedVersion) {
console.log('')
console.log('You currently have ' + installedVersion + ' installed.')
}
console.log('')
console.log(installMessage)
} | javascript | {
"resource": ""
} |
q17729 | getVersion | train | function getVersion() {
// parse the version number
try {
// find the executable
var resolvedPath = which.sync(whichExec)
// grab the raw output
var result = shell.exec(`"${resolvedPath}" ${versionCommand}`, { silent: true })
var rawOut = ramda.trim(result.stdout || '')
var rawErr = ramda.trim(result.stderr || '') // java -version does this... grr
// assign the "right" one to raw
var raw = rawOut
if (ramda.isEmpty(raw)) {
raw = rawErr
}
if (ramda.isEmpty(raw)) {
raw = null
}
// and run it by the version matcher
return versionMatcher(raw)
} catch (err) {
return null
}
} | javascript | {
"resource": ""
} |
q17730 | triggerCharacter | train | function triggerCharacter({
char = '@',
allowSpaces = false,
startOfLine = false,
}) {
return $position => {
// Matching expressions used for later
const escapedChar = `\\${char}`
const suffix = new RegExp(`\\s${escapedChar}$`)
const prefix = startOfLine ? '^' : ''
const regexp = allowSpaces
? new RegExp(`${prefix}${escapedChar}.*?(?=\\s${escapedChar}|$)`, 'gm')
: new RegExp(`${prefix}(?:^)?${escapedChar}[^\\s${escapedChar}]*`, 'gm')
// Lookup the boundaries of the current node
const textFrom = $position.before()
const textTo = $position.end()
const text = $position.doc.textBetween(textFrom, textTo, '\0', '\0')
let match = regexp.exec(text)
let position
while (match !== null) {
// JavaScript doesn't have lookbehinds; this hacks a check that first character is " "
// or the line beginning
const matchPrefix = match.input.slice(Math.max(0, match.index - 1), match.index)
if (/^[\s\0]?$/.test(matchPrefix)) {
// The absolute position of the match in the document
const from = match.index + $position.start()
let to = from + match[0].length
// Edge case handling; if spaces are allowed and we're directly in between
// two triggers
if (allowSpaces && suffix.test(text.slice(to - 1, to + 1))) {
match[0] += ' '
to += 1
}
// If the $position is located within the matched substring, return that range
if (from < $position.pos && to >= $position.pos) {
position = {
range: {
from,
to,
},
query: match[0].slice(char.length),
text: match[0],
}
}
}
match = regexp.exec(text)
}
return position
}
} | javascript | {
"resource": ""
} |
q17731 | networkIdleCallback | train | function networkIdleCallback(fn, options = {timeout: 0}) {
// Call the function immediately if required features are absent
if (
!('MessageChannel' in window) ||
!('serviceWorker' in navigator) ||
!navigator.serviceWorker.controller
) {
DOMContentLoad.then(() => fn({didTimeout: false}));
return;
}
const messageChannel = new MessageChannel();
navigator.serviceWorker.controller
.postMessage(
'NETWORK_IDLE_ENQUIRY',
[messageChannel.port2],
);
const timeoutId = setTimeout(() => {
const cbToPop = networkIdleCallback.__callbacks__
.find(cb => cb.id === timeoutId);
networkIdleCallback.__popCallback__(cbToPop, true);
}, options.timeout);
networkIdleCallback.__callbacks__.push({
id: timeoutId,
fn,
timeout: options.timeout,
});
messageChannel.port1.addEventListener('message', handleMessage);
messageChannel.port1.start();
} | javascript | {
"resource": ""
} |
q17732 | handleMessage | train | function handleMessage(event) {
if (!event.data) {
return;
}
switch (event.data) {
case 'NETWORK_IDLE_ENQUIRY_RESULT_IDLE':
case 'NETWORK_IDLE_CALLBACK':
networkIdleCallback.__callbacks__.forEach(callback => {
networkIdleCallback.__popCallback__(callback, false);
});
break;
}
} | javascript | {
"resource": ""
} |
q17733 | mapValues | train | function mapValues(obj, iteratee) {
const result = {}
for (const k in obj) {
result[k] = iteratee(obj[k])
}
return result
} | javascript | {
"resource": ""
} |
q17734 | heuristic | train | function heuristic() {
if (this.type === typeEnum.unit) {
// Remove the excess.
return Math.max(0, this.cache.size - this.capacity)
} else if (this.type === typeEnum.heap) {
if (getHeapSize() >= this.capacity) {
console.log('LRU HEURISTIC heap:', getHeapSize())
// Remove half of them.
return this.cache.size >> 1
} else {
return 0
}
} else {
console.error(`Unknown heuristic '${this.type}' for LRU cache.`)
return 1
}
} | javascript | {
"resource": ""
} |
q17735 | parseVersion | train | function parseVersion(versionString) {
versionString = versionString.toLowerCase().replace('-', '.')
const versionList = []
versionString.split('.').forEach(versionPart => {
const parsedPart = /(\d*)([a-z]*)(\d*)/.exec(versionPart)
if (parsedPart[1]) {
versionList.push(parseInt(parsedPart[1]))
}
if (parsedPart[2]) {
let weight
// calculate weight as a negative number
// 'rc' > 'pre' > 'beta' > 'alpha' > any other value
switch (parsedPart[2]) {
case 'alpha':
case 'beta':
case 'pre':
case 'rc':
weight = (parsedPart[2].charCodeAt(0) - 128) * 100
break
default:
weight = -10000
}
// add positive number, i.e. 'beta5' > 'beta2'
weight += parseInt(parsedPart[3]) || 0
versionList.push(weight)
}
})
return versionList
} | javascript | {
"resource": ""
} |
q17736 | sortDjangoVersions | train | function sortDjangoVersions(versions) {
return versions.sort((a, b) => {
if (
parseDjangoVersionString(a).major === parseDjangoVersionString(b).major
) {
return (
parseDjangoVersionString(a).minor - parseDjangoVersionString(b).minor
)
} else {
return (
parseDjangoVersionString(a).major - parseDjangoVersionString(b).major
)
}
})
} | javascript | {
"resource": ""
} |
q17737 | parseClassifiers | train | function parseClassifiers(parsedData, pattern) {
const results = []
for (let i = 0; i < parsedData.info.classifiers.length; i++) {
const matched = pattern.exec(parsedData.info.classifiers[i])
if (matched && matched[1]) {
results.push(matched[1].toLowerCase())
}
}
return results
} | javascript | {
"resource": ""
} |
q17738 | fixLink | train | function fixLink (name, str) {
/* In 6.x some API start with `xpack.` when in master they do not. We
* can safely ignore that for link generation. */
name = name.replace(/^xpack\./, '')
const override = LINK_OVERRIDES[name]
if (override) return override
if (!str) return ''
/* Replace references to the guide with the attribute {ref} because
* the json files in the Elasticsearch repo are a bit of a mess. */
str = str.replace(/^.+guide\/en\/elasticsearch\/reference\/[^/]+\/([^./]*\.html(?:#.+)?)$/, '{ref}/$1')
str = str.replace(/frozen\.html/, 'freeze-index-api.html')
str = str.replace(/ml-file-structure\.html/, 'ml-find-file-structure.html')
str = str.replace(/security-api-get-user-privileges\.html/, 'security-api-get-privileges.html')
return str
} | javascript | {
"resource": ""
} |
q17739 | getLeft | train | function getLeft(node) {
let left = node.left;
while (isConcatenation(left)) {
left = left.right;
}
return left;
} | javascript | {
"resource": ""
} |
q17740 | getRight | train | function getRight(node) {
let right = node.right;
while (isConcatenation(right)) {
right = right.left;
}
return right;
} | javascript | {
"resource": ""
} |
q17741 | createDisableDirectives | train | function createDisableDirectives(type, loc, value) {
const ruleIds = Object.keys(commentParser.parseListConfig(value));
const directiveRules = ruleIds.length ? ruleIds : [null];
return directiveRules.map(ruleId => ({ type, line: loc.line, column: loc.column + 1, ruleId }));
} | javascript | {
"resource": ""
} |
q17742 | normalizeVerifyOptions | train | function normalizeVerifyOptions(providedOptions) {
const isObjectOptions = typeof providedOptions === "object";
const providedFilename = isObjectOptions ? providedOptions.filename : providedOptions;
return {
filename: typeof providedFilename === "string" ? providedFilename : "<input>",
allowInlineConfig: !isObjectOptions || providedOptions.allowInlineConfig !== false,
reportUnusedDisableDirectives: isObjectOptions && !!providedOptions.reportUnusedDisableDirectives
};
} | javascript | {
"resource": ""
} |
q17743 | resolveParserOptions | train | function resolveParserOptions(parserName, providedOptions, enabledEnvironments) {
const parserOptionsFromEnv = enabledEnvironments
.filter(env => env.parserOptions)
.reduce((parserOptions, env) => ConfigOps.merge(parserOptions, env.parserOptions), {});
const mergedParserOptions = ConfigOps.merge(parserOptionsFromEnv, providedOptions || {});
const isModule = mergedParserOptions.sourceType === "module";
if (isModule) {
// can't have global return inside of modules
mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false });
}
mergedParserOptions.ecmaVersion = normalizeEcmaVersion(mergedParserOptions.ecmaVersion, isModule);
return mergedParserOptions;
} | javascript | {
"resource": ""
} |
q17744 | resolveGlobals | train | function resolveGlobals(providedGlobals, enabledEnvironments) {
return Object.assign(
{},
...enabledEnvironments.filter(env => env.globals).map(env => env.globals),
providedGlobals
);
} | javascript | {
"resource": ""
} |
q17745 | analyzeScope | train | function analyzeScope(ast, parserOptions, visitorKeys) {
const ecmaFeatures = parserOptions.ecmaFeatures || {};
const ecmaVersion = parserOptions.ecmaVersion || 5;
return eslintScope.analyze(ast, {
ignoreEval: true,
nodejsScope: ecmaFeatures.globalReturn,
impliedStrict: ecmaFeatures.impliedStrict,
ecmaVersion,
sourceType: parserOptions.sourceType || "script",
childVisitorKeys: visitorKeys || evk.KEYS,
fallback: Traverser.getKeys
});
} | javascript | {
"resource": ""
} |
q17746 | getScope | train | function getScope(scopeManager, currentNode) {
// On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope.
const inner = currentNode.type !== "Program";
for (let node = currentNode; node; node = node.parent) {
const scope = scopeManager.acquire(node, inner);
if (scope) {
if (scope.type === "function-expression-name") {
return scope.childScopes[0];
}
return scope;
}
}
return scopeManager.scopes[0];
} | javascript | {
"resource": ""
} |
q17747 | markVariableAsUsed | train | function markVariableAsUsed(scopeManager, currentNode, parserOptions, name) {
const hasGlobalReturn = parserOptions.ecmaFeatures && parserOptions.ecmaFeatures.globalReturn;
const specialScope = hasGlobalReturn || parserOptions.sourceType === "module";
const currentScope = getScope(scopeManager, currentNode);
// Special Node.js scope means we need to start one level deeper
const initialScope = currentScope.type === "global" && specialScope ? currentScope.childScopes[0] : currentScope;
for (let scope = initialScope; scope; scope = scope.upper) {
const variable = scope.variables.find(scopeVar => scopeVar.name === name);
if (variable) {
variable.eslintUsed = true;
return true;
}
}
return false;
} | javascript | {
"resource": ""
} |
q17748 | createRuleListeners | train | function createRuleListeners(rule, ruleContext) {
try {
return rule.create(ruleContext);
} catch (ex) {
ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`;
throw ex;
}
} | javascript | {
"resource": ""
} |
q17749 | getAncestors | train | function getAncestors(node) {
const ancestorsStartingAtParent = [];
for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
ancestorsStartingAtParent.push(ancestor);
}
return ancestorsStartingAtParent.reverse();
} | javascript | {
"resource": ""
} |
q17750 | isRedundantSemi | train | function isRedundantSemi(semiToken) {
const nextToken = sourceCode.getTokenAfter(semiToken);
return (
!nextToken ||
astUtils.isClosingBraceToken(nextToken) ||
astUtils.isSemicolonToken(nextToken)
);
} | javascript | {
"resource": ""
} |
q17751 | isEndOfArrowBlock | train | function isEndOfArrowBlock(lastToken) {
if (!astUtils.isClosingBraceToken(lastToken)) {
return false;
}
const node = sourceCode.getNodeByRangeIndex(lastToken.range[0]);
return (
node.type === "BlockStatement" &&
node.parent.type === "ArrowFunctionExpression"
);
} | javascript | {
"resource": ""
} |
q17752 | isOnSameLineWithNextToken | train | function isOnSameLineWithNextToken(node) {
const prevToken = sourceCode.getLastToken(node, 1);
const nextToken = sourceCode.getTokenAfter(node);
return !!nextToken && astUtils.isTokenOnSameLine(prevToken, nextToken);
} | javascript | {
"resource": ""
} |
q17753 | maybeAsiHazardAfter | train | function maybeAsiHazardAfter(node) {
const t = node.type;
if (t === "DoWhileStatement" ||
t === "BreakStatement" ||
t === "ContinueStatement" ||
t === "DebuggerStatement" ||
t === "ImportDeclaration" ||
t === "ExportAllDeclaration"
) {
return false;
}
if (t === "ReturnStatement") {
return Boolean(node.argument);
}
if (t === "ExportNamedDeclaration") {
return Boolean(node.declaration);
}
if (isEndOfArrowBlock(sourceCode.getLastToken(node, 1))) {
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q17754 | maybeAsiHazardBefore | train | function maybeAsiHazardBefore(token) {
return (
Boolean(token) &&
OPT_OUT_PATTERN.test(token.value) &&
token.value !== "++" &&
token.value !== "--"
);
} | javascript | {
"resource": ""
} |
q17755 | isOneLinerBlock | train | function isOneLinerBlock(node) {
const parent = node.parent;
const nextToken = sourceCode.getTokenAfter(node);
if (!nextToken || nextToken.value !== "}") {
return false;
}
return (
!!parent &&
parent.type === "BlockStatement" &&
parent.loc.start.line === parent.loc.end.line
);
} | javascript | {
"resource": ""
} |
q17756 | normalizeOptions | train | function normalizeOptions(options = {}) {
const hasGroups = options.groups && options.groups.length > 0;
const groups = hasGroups ? options.groups : DEFAULT_GROUPS;
const allowSamePrecedence = options.allowSamePrecedence !== false;
return {
groups,
allowSamePrecedence
};
} | javascript | {
"resource": ""
} |
q17757 | includesBothInAGroup | train | function includesBothInAGroup(groups, left, right) {
return groups.some(group => group.indexOf(left) !== -1 && group.indexOf(right) !== -1);
} | javascript | {
"resource": ""
} |
q17758 | shouldIgnore | train | function shouldIgnore(node) {
const a = node;
const b = node.parent;
return (
!includesBothInAGroup(options.groups, a.operator, b.operator) ||
(
options.allowSamePrecedence &&
astUtils.getPrecedence(a) === astUtils.getPrecedence(b)
)
);
} | javascript | {
"resource": ""
} |
q17759 | isMixedWithParent | train | function isMixedWithParent(node) {
return (
node.operator !== node.parent.operator &&
!astUtils.isParenthesised(sourceCode, node)
);
} | javascript | {
"resource": ""
} |
q17760 | reportBothOperators | train | function reportBothOperators(node) {
const parent = node.parent;
const left = (parent.left === node) ? node : parent;
const right = (parent.left !== node) ? node : parent;
const message =
"Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'.";
const data = {
leftOperator: left.operator,
rightOperator: right.operator
};
context.report({
node: left,
loc: getOperatorToken(left).loc.start,
message,
data
});
context.report({
node: right,
loc: getOperatorToken(right).loc.start,
message,
data
});
} | javascript | {
"resource": ""
} |
q17761 | check | train | function check(node) {
if (TARGET_NODE_TYPE.test(node.parent.type) &&
isMixedWithParent(node) &&
!shouldIgnore(node)
) {
reportBothOperators(node);
}
} | javascript | {
"resource": ""
} |
q17762 | isLoneBlock | train | function isLoneBlock(node) {
return node.parent.type === "BlockStatement" ||
node.parent.type === "Program" ||
// Don't report blocks in switch cases if the block is the only statement of the case.
node.parent.type === "SwitchCase" && !(node.parent.consequent[0] === node && node.parent.consequent.length === 1);
} | javascript | {
"resource": ""
} |
q17763 | markLoneBlock | train | function markLoneBlock() {
if (loneBlocks.length === 0) {
return;
}
const block = context.getAncestors().pop();
if (loneBlocks[loneBlocks.length - 1] === block) {
loneBlocks.pop();
}
} | javascript | {
"resource": ""
} |
q17764 | getContinueContext | train | function getContinueContext(state, label) {
if (!label) {
return state.loopContext;
}
let context = state.loopContext;
while (context) {
if (context.label === label) {
return context;
}
context = context.upper;
}
/* istanbul ignore next: foolproof (syntax error) */
return null;
} | javascript | {
"resource": ""
} |
q17765 | getBreakContext | train | function getBreakContext(state, label) {
let context = state.breakContext;
while (context) {
if (label ? context.label === label : context.breakable) {
return context;
}
context = context.upper;
}
/* istanbul ignore next: foolproof (syntax error) */
return null;
} | javascript | {
"resource": ""
} |
q17766 | getReturnContext | train | function getReturnContext(state) {
let context = state.tryContext;
while (context) {
if (context.hasFinalizer && context.position !== "finally") {
return context;
}
context = context.upper;
}
return state;
} | javascript | {
"resource": ""
} |
q17767 | getThrowContext | train | function getThrowContext(state) {
let context = state.tryContext;
while (context) {
if (context.position === "try" ||
(context.hasFinalizer && context.position === "catch")
) {
return context;
}
context = context.upper;
}
return state;
} | javascript | {
"resource": ""
} |
q17768 | removeConnection | train | function removeConnection(prevSegments, nextSegments) {
for (let i = 0; i < prevSegments.length; ++i) {
const prevSegment = prevSegments[i];
const nextSegment = nextSegments[i];
remove(prevSegment.nextSegments, nextSegment);
remove(prevSegment.allNextSegments, nextSegment);
remove(nextSegment.prevSegments, prevSegment);
remove(nextSegment.allPrevSegments, prevSegment);
}
} | javascript | {
"resource": ""
} |
q17769 | checkComputedProperty | train | function checkComputedProperty(node, value) {
if (
validIdentifier.test(value) &&
(allowKeywords || keywords.indexOf(String(value)) === -1) &&
!(allowPattern && allowPattern.test(value))
) {
const formattedValue = node.property.type === "Literal" ? JSON.stringify(value) : `\`${value}\``;
context.report({
node: node.property,
messageId: "useDot",
data: {
key: formattedValue
},
fix(fixer) {
const leftBracket = sourceCode.getTokenAfter(node.object, astUtils.isOpeningBracketToken);
const rightBracket = sourceCode.getLastToken(node);
if (sourceCode.getFirstTokenBetween(leftBracket, rightBracket, { includeComments: true, filter: astUtils.isCommentToken })) {
// Don't perform any fixes if there are comments inside the brackets.
return null;
}
const tokenAfterProperty = sourceCode.getTokenAfter(rightBracket);
const needsSpaceAfterProperty = tokenAfterProperty &&
rightBracket.range[1] === tokenAfterProperty.range[0] &&
!astUtils.canTokensBeAdjacent(String(value), tokenAfterProperty);
const textBeforeDot = astUtils.isDecimalInteger(node.object) ? " " : "";
const textAfterProperty = needsSpaceAfterProperty ? " " : "";
return fixer.replaceTextRange(
[leftBracket.range[0], rightBracket.range[1]],
`${textBeforeDot}.${value}${textAfterProperty}`
);
}
});
}
} | javascript | {
"resource": ""
} |
q17770 | validateNode | train | function validateNode(node, leftSide) {
/*
* When the left part of a binary expression is a single expression wrapped in
* parentheses (ex: `(a) + b`), leftToken will be the last token of the expression
* and operatorToken will be the closing parenthesis.
* The leftToken should be the last closing parenthesis, and the operatorToken
* should be the token right after that.
*/
const operatorToken = sourceCode.getTokenAfter(leftSide, astUtils.isNotClosingParenToken);
const leftToken = sourceCode.getTokenBefore(operatorToken);
const rightToken = sourceCode.getTokenAfter(operatorToken);
const operator = operatorToken.value;
const operatorStyleOverride = styleOverrides[operator];
const style = operatorStyleOverride || globalStyle;
const fix = getFixer(operatorToken, style);
// if single line
if (astUtils.isTokenOnSameLine(leftToken, operatorToken) &&
astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
// do nothing.
} else if (operatorStyleOverride !== "ignore" && !astUtils.isTokenOnSameLine(leftToken, operatorToken) &&
!astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
// lone operator
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "Bad line breaking before and after '{{operator}}'.",
data: {
operator
},
fix
});
} else if (style === "before" && astUtils.isTokenOnSameLine(leftToken, operatorToken)) {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "'{{operator}}' should be placed at the beginning of the line.",
data: {
operator
},
fix
});
} else if (style === "after" && astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "'{{operator}}' should be placed at the end of the line.",
data: {
operator
},
fix
});
} else if (style === "none") {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "There should be no line break before or after '{{operator}}'.",
data: {
operator
},
fix
});
}
} | javascript | {
"resource": ""
} |
q17771 | loadJSConfigFile | train | function loadJSConfigFile(filePath) {
debug(`Loading JS config file: ${filePath}`);
try {
return importFresh(filePath);
} catch (e) {
debug(`Error reading JavaScript file: ${filePath}`);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
throw e;
}
} | javascript | {
"resource": ""
} |
q17772 | loadPackageJSONConfigFile | train | function loadPackageJSONConfigFile(filePath) {
debug(`Loading package.json config file: ${filePath}`);
try {
return loadJSONConfigFile(filePath).eslintConfig || null;
} catch (e) {
debug(`Error reading package.json file: ${filePath}`);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
throw e;
}
} | javascript | {
"resource": ""
} |
q17773 | configMissingError | train | function configMissingError(configName) {
const error = new Error(`Failed to load config "${configName}" to extend from.`);
error.messageTemplate = "extend-config-missing";
error.messageData = {
configName
};
return error;
} | javascript | {
"resource": ""
} |
q17774 | writeJSONConfigFile | train | function writeJSONConfigFile(config, filePath) {
debug(`Writing JSON config file: ${filePath}`);
const content = stringify(config, { cmp: sortByKey, space: 4 });
fs.writeFileSync(filePath, content, "utf8");
} | javascript | {
"resource": ""
} |
q17775 | writeYAMLConfigFile | train | function writeYAMLConfigFile(config, filePath) {
debug(`Writing YAML config file: ${filePath}`);
// lazy load YAML to improve performance when not used
const yaml = require("js-yaml");
const content = yaml.safeDump(config, { sortKeys: true });
fs.writeFileSync(filePath, content, "utf8");
} | javascript | {
"resource": ""
} |
q17776 | writeJSConfigFile | train | function writeJSConfigFile(config, filePath) {
debug(`Writing JS config file: ${filePath}`);
let contentToWrite;
const stringifiedContent = `module.exports = ${stringify(config, { cmp: sortByKey, space: 4 })};`;
try {
const CLIEngine = require("../cli-engine");
const linter = new CLIEngine({
baseConfig: config,
fix: true,
useEslintrc: false
});
const report = linter.executeOnText(stringifiedContent);
contentToWrite = report.results[0].output || stringifiedContent;
} catch (e) {
debug("Error linting JavaScript config file, writing unlinted version");
const errorMessage = e.message;
contentToWrite = stringifiedContent;
e.message = "An error occurred while generating your JavaScript config file. ";
e.message += "A config file was still generated, but the config file itself may not follow your linting rules.";
e.message += `\nError: ${errorMessage}`;
throw e;
} finally {
fs.writeFileSync(filePath, contentToWrite, "utf8");
}
} | javascript | {
"resource": ""
} |
q17777 | write | train | function write(config, filePath) {
switch (path.extname(filePath)) {
case ".js":
writeJSConfigFile(config, filePath);
break;
case ".json":
writeJSONConfigFile(config, filePath);
break;
case ".yaml":
case ".yml":
writeYAMLConfigFile(config, filePath);
break;
default:
throw new Error("Can't write to unknown file type.");
}
} | javascript | {
"resource": ""
} |
q17778 | getEslintCoreConfigPath | train | function getEslintCoreConfigPath(name) {
if (name === "eslint:recommended") {
/*
* Add an explicit substitution for eslint:recommended to
* conf/eslint-recommended.js.
*/
return path.resolve(__dirname, "../../conf/eslint-recommended.js");
}
if (name === "eslint:all") {
/*
* Add an explicit substitution for eslint:all to conf/eslint-all.js
*/
return path.resolve(__dirname, "../../conf/eslint-all.js");
}
throw configMissingError(name);
} | javascript | {
"resource": ""
} |
q17779 | applyExtends | train | function applyExtends(config, configContext, filePath) {
const extendsList = Array.isArray(config.extends) ? config.extends : [config.extends];
// Make the last element in an array take the highest precedence
const flattenedConfig = extendsList.reduceRight((previousValue, extendedConfigReference) => {
try {
debug(`Loading ${extendedConfigReference}`);
// eslint-disable-next-line no-use-before-define
return ConfigOps.merge(load(extendedConfigReference, configContext, filePath), previousValue);
} catch (err) {
/*
* If the file referenced by `extends` failed to load, add the path
* to the configuration file that referenced it to the error
* message so the user is able to see where it was referenced from,
* then re-throw.
*/
err.message += `\nReferenced from: ${filePath}`;
if (err.messageTemplate === "plugin-missing") {
err.messageData.configStack.push(filePath);
}
throw err;
}
}, Object.assign({}, config));
delete flattenedConfig.extends;
return flattenedConfig;
} | javascript | {
"resource": ""
} |
q17780 | isExistingFile | train | function isExistingFile(filename) {
try {
return fs.statSync(filename).isFile();
} catch (err) {
if (err.code === "ENOENT") {
return false;
}
throw err;
}
} | javascript | {
"resource": ""
} |
q17781 | checkMetaProperty | train | function checkMetaProperty(node, metaName, propertyName) {
return node.meta.name === metaName && node.property.name === propertyName;
} | javascript | {
"resource": ""
} |
q17782 | getVariableOfArguments | train | function getVariableOfArguments(scope) {
const variables = scope.variables;
for (let i = 0; i < variables.length; ++i) {
const variable = variables[i];
if (variable.name === "arguments") {
/*
* If there was a parameter which is named "arguments", the
* implicit "arguments" is not defined.
* So does fast return with null.
*/
return (variable.identifiers.length === 0) ? variable : null;
}
}
/* istanbul ignore next */
return null;
} | javascript | {
"resource": ""
} |
q17783 | isOneLiner | train | function isOneLiner(node) {
const first = sourceCode.getFirstToken(node),
last = sourceCode.getLastToken(node);
return first.loc.start.line === last.loc.end.line;
} | javascript | {
"resource": ""
} |
q17784 | getElseKeyword | train | function getElseKeyword(node) {
return node.alternate && sourceCode.getFirstTokenBetween(node.consequent, node.alternate, isElseKeywordToken);
} | javascript | {
"resource": ""
} |
q17785 | needsSemicolon | train | function needsSemicolon(closingBracket) {
const tokenBefore = sourceCode.getTokenBefore(closingBracket);
const tokenAfter = sourceCode.getTokenAfter(closingBracket);
const lastBlockNode = sourceCode.getNodeByRangeIndex(tokenBefore.range[0]);
if (astUtils.isSemicolonToken(tokenBefore)) {
// If the last statement already has a semicolon, don't add another one.
return false;
}
if (!tokenAfter) {
// If there are no statements after this block, there is no need to add a semicolon.
return false;
}
if (lastBlockNode.type === "BlockStatement" && lastBlockNode.parent.type !== "FunctionExpression" && lastBlockNode.parent.type !== "ArrowFunctionExpression") {
/*
* If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression),
* don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause
* a SyntaxError if it was followed by `else`.
*/
return false;
}
if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) {
// If the next token is on the same line, insert a semicolon.
return true;
}
if (/^[([/`+-]/u.test(tokenAfter.value)) {
// If the next token starts with a character that would disrupt ASI, insert a semicolon.
return true;
}
if (tokenBefore.type === "Punctuator" && (tokenBefore.value === "++" || tokenBefore.value === "--")) {
// If the last token is ++ or --, insert a semicolon to avoid disrupting ASI.
return true;
}
// Otherwise, do not insert a semicolon.
return false;
} | javascript | {
"resource": ""
} |
q17786 | prepareCheck | train | function prepareCheck(node, body, name, opts) {
const hasBlock = (body.type === "BlockStatement");
let expected = null;
if (node.type === "IfStatement" && node.consequent === body && requiresBraceOfConsequent(node)) {
expected = true;
} else if (multiOnly) {
if (hasBlock && body.body.length === 1) {
expected = false;
}
} else if (multiLine) {
if (!isCollapsedOneLiner(body)) {
expected = true;
}
} else if (multiOrNest) {
if (hasBlock && body.body.length === 1 && isOneLiner(body.body[0])) {
const leadingComments = sourceCode.getCommentsBefore(body.body[0]);
expected = leadingComments.length > 0;
} else if (!isOneLiner(body)) {
expected = true;
}
} else {
expected = true;
}
return {
actual: hasBlock,
expected,
check() {
if (this.expected !== null && this.expected !== this.actual) {
if (this.expected) {
context.report({
node,
loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
messageId: opts && opts.condition ? "missingCurlyAfterCondition" : "missingCurlyAfter",
data: {
name
},
fix: fixer => fixer.replaceText(body, `{${sourceCode.getText(body)}}`)
});
} else {
context.report({
node,
loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
messageId: opts && opts.condition ? "unexpectedCurlyAfterCondition" : "unexpectedCurlyAfter",
data: {
name
},
fix(fixer) {
/*
* `do while` expressions sometimes need a space to be inserted after `do`.
* e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)`
*/
const needsPrecedingSpace = node.type === "DoWhileStatement" &&
sourceCode.getTokenBefore(body).range[1] === body.range[0] &&
!astUtils.canTokensBeAdjacent("do", sourceCode.getFirstToken(body, { skip: 1 }));
const openingBracket = sourceCode.getFirstToken(body);
const closingBracket = sourceCode.getLastToken(body);
const lastTokenInBlock = sourceCode.getTokenBefore(closingBracket);
if (needsSemicolon(closingBracket)) {
/*
* If removing braces would cause a SyntaxError due to multiple statements on the same line (or
* change the semantics of the code due to ASI), don't perform a fix.
*/
return null;
}
const resultingBodyText = sourceCode.getText().slice(openingBracket.range[1], lastTokenInBlock.range[0]) +
sourceCode.getText(lastTokenInBlock) +
sourceCode.getText().slice(lastTokenInBlock.range[1], closingBracket.range[0]);
return fixer.replaceText(body, (needsPrecedingSpace ? " " : "") + resultingBodyText);
}
});
}
}
}
};
} | javascript | {
"resource": ""
} |
q17787 | prepareIfChecks | train | function prepareIfChecks(node) {
const preparedChecks = [];
for (let currentNode = node; currentNode; currentNode = currentNode.alternate) {
preparedChecks.push(prepareCheck(currentNode, currentNode.consequent, "if", { condition: true }));
if (currentNode.alternate && currentNode.alternate.type !== "IfStatement") {
preparedChecks.push(prepareCheck(currentNode, currentNode.alternate, "else"));
break;
}
}
if (consistent) {
/*
* If any node should have or already have braces, make sure they
* all have braces.
* If all nodes shouldn't have braces, make sure they don't.
*/
const expected = preparedChecks.some(preparedCheck => {
if (preparedCheck.expected !== null) {
return preparedCheck.expected;
}
return preparedCheck.actual;
});
preparedChecks.forEach(preparedCheck => {
preparedCheck.expected = expected;
});
}
return preparedChecks;
} | javascript | {
"resource": ""
} |
q17788 | getCommentLineNums | train | function getCommentLineNums(comments) {
const lines = [];
comments.forEach(token => {
const start = token.loc.start.line;
const end = token.loc.end.line;
lines.push(start, end);
});
return lines;
} | javascript | {
"resource": ""
} |
q17789 | codeAroundComment | train | function codeAroundComment(token) {
let currentToken = token;
do {
currentToken = sourceCode.getTokenBefore(currentToken, { includeComments: true });
} while (currentToken && astUtils.isCommentToken(currentToken));
if (currentToken && astUtils.isTokenOnSameLine(currentToken, token)) {
return true;
}
currentToken = token;
do {
currentToken = sourceCode.getTokenAfter(currentToken, { includeComments: true });
} while (currentToken && astUtils.isCommentToken(currentToken));
if (currentToken && astUtils.isTokenOnSameLine(token, currentToken)) {
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q17790 | isParentNodeType | train | function isParentNodeType(parent, nodeType) {
return parent.type === nodeType ||
(parent.body && parent.body.type === nodeType) ||
(parent.consequent && parent.consequent.type === nodeType);
} | javascript | {
"resource": ""
} |
q17791 | isCommentAtParentStart | train | function isCommentAtParentStart(token, nodeType) {
const parent = getParentNodeOfToken(token);
return parent && isParentNodeType(parent, nodeType) &&
token.loc.start.line - parent.loc.start.line === 1;
} | javascript | {
"resource": ""
} |
q17792 | isCommentAtParentEnd | train | function isCommentAtParentEnd(token, nodeType) {
const parent = getParentNodeOfToken(token);
return parent && isParentNodeType(parent, nodeType) &&
parent.loc.end.line - token.loc.end.line === 1;
} | javascript | {
"resource": ""
} |
q17793 | isCommentAtBlockEnd | train | function isCommentAtBlockEnd(token) {
return isCommentAtParentEnd(token, "ClassBody") || isCommentAtParentEnd(token, "BlockStatement") || isCommentAtParentEnd(token, "SwitchCase") || isCommentAtParentEnd(token, "SwitchStatement");
} | javascript | {
"resource": ""
} |
q17794 | report | train | function report(nodeOrToken) {
context.report({
node: nodeOrToken,
messageId: "unexpected",
fix(fixer) {
/*
* Expand the replacement range to include the surrounding
* tokens to avoid conflicting with semi.
* https://github.com/eslint/eslint/issues/7928
*/
return new FixTracker(fixer, context.getSourceCode())
.retainSurroundingTokens(nodeOrToken)
.remove(nodeOrToken);
}
});
} | javascript | {
"resource": ""
} |
q17795 | checkForPartOfClassBody | train | function checkForPartOfClassBody(firstToken) {
for (let token = firstToken;
token.type === "Punctuator" && !astUtils.isClosingBraceToken(token);
token = sourceCode.getTokenAfter(token)
) {
if (astUtils.isSemicolonToken(token)) {
report(token);
}
}
} | javascript | {
"resource": ""
} |
q17796 | usedMemberSyntax | train | function usedMemberSyntax(node) {
if (node.specifiers.length === 0) {
return "none";
}
if (node.specifiers[0].type === "ImportNamespaceSpecifier") {
return "all";
}
if (node.specifiers.length === 1) {
return "single";
}
return "multiple";
} | javascript | {
"resource": ""
} |
q17797 | isLastNode | train | function isLastNode(node) {
const token = sourceCode.getTokenAfter(node);
return !token || (token.type === "Punctuator" && token.value === "}");
} | javascript | {
"resource": ""
} |
q17798 | getLastCommentLineOfBlock | train | function getLastCommentLineOfBlock(commentStartLine) {
const currentCommentEnd = commentEndLine[commentStartLine];
return commentEndLine[currentCommentEnd + 1] ? getLastCommentLineOfBlock(currentCommentEnd + 1) : currentCommentEnd;
} | javascript | {
"resource": ""
} |
q17799 | checkForBlankLine | train | function checkForBlankLine(node) {
/*
* lastToken is the last token on the node's line. It will usually also be the last token of the node, but it will
* sometimes be second-last if there is a semicolon on a different line.
*/
const lastToken = getLastToken(node),
/*
* If lastToken is the last token of the node, nextToken should be the token after the node. Otherwise, nextToken
* is the last token of the node.
*/
nextToken = lastToken === sourceCode.getLastToken(node) ? sourceCode.getTokenAfter(node) : sourceCode.getLastToken(node),
nextLineNum = lastToken.loc.end.line + 1;
// Ignore if there is no following statement
if (!nextToken) {
return;
}
// Ignore if parent of node is a for variant
if (isForTypeSpecifier(node.parent.type)) {
return;
}
// Ignore if parent of node is an export specifier
if (isExportSpecifier(node.parent.type)) {
return;
}
/*
* Some coding styles use multiple `var` statements, so do nothing if
* the next token is a `var` statement.
*/
if (nextToken.type === "Keyword" && isVar(nextToken.value)) {
return;
}
// Ignore if it is last statement in a block
if (isLastNode(node)) {
return;
}
// Next statement is not a `var`...
const noNextLineToken = nextToken.loc.start.line > nextLineNum;
const hasNextLineComment = (typeof commentEndLine[nextLineNum] !== "undefined");
if (mode === "never" && noNextLineToken && !hasNextLineComment) {
context.report({
node,
messageId: "unexpected",
data: { identifier: node.name },
fix(fixer) {
const linesBetween = sourceCode.getText().slice(lastToken.range[1], nextToken.range[0]).split(astUtils.LINEBREAK_MATCHER);
return fixer.replaceTextRange([lastToken.range[1], nextToken.range[0]], `${linesBetween.slice(0, -1).join("")}\n${linesBetween[linesBetween.length - 1]}`);
}
});
}
// Token on the next line, or comment without blank line
if (
mode === "always" && (
!noNextLineToken ||
hasNextLineComment && !hasBlankLineAfterComment(nextToken, nextLineNum)
)
) {
context.report({
node,
messageId: "expected",
data: { identifier: node.name },
fix(fixer) {
if ((noNextLineToken ? getLastCommentLineOfBlock(nextLineNum) : lastToken.loc.end.line) === nextToken.loc.start.line) {
return fixer.insertTextBefore(nextToken, "\n\n");
}
return fixer.insertTextBeforeRange([nextToken.range[0] - nextToken.loc.start.column, nextToken.range[1]], "\n");
}
});
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.