text:
import logging
import sys
import time
import pigpio

from Adafruit_BNO055 import BNO055

#---------------------------------------------------------------------------------------------------------------|
# --- Initialize Orientation Sensor ---
bno = BNO055.BNO055(serial_port='/dev/ttyAMA0', rst=18)

# Enable verbose debug logging if -v is passed as a parameter.
if len(sys.argv) == 2 and sys.argv[1].lower() == '-v':
    logging.basicConfig(level=logging.DEBUG)

# Initialize the BNO055 and stop if something went wrong.
if not bno.begin():
    raise RuntimeError('Failed to initialize BNO055! Is the sensor connected?')

# Print system status and self test result.
status, self_test, error = bno.get_system_status()
print('System status: {0}'.format(status))
print('Self test result (0x0F is normal): 0x{0:02X}'.format(self_test))
# Print out an error if system status is in error mode.
if status == 0x01:
    print('System error: {0}'.format(error))
    print('See datasheet section 4.3.59 for the meaning.')

# Print BNO055 software revision and other diagnostic data.
sw, bl, accel, mag, gyro = bno.get_revision()
print('Software version:   {0}'.format(sw))
print('Bootloader version: {0}'.format(bl))
print('Accelerometer ID:   0x{0:02X}'.format(accel))
print('Magnetometer ID:    0x{0:02X}'.format(mag))
print('Gyroscope ID:       0x{0:02X}\n'.format(gyro))
#---------------------------------------------------------------------------------------------------------------|

pi = pigpio.pi()
systemOn = True
motorOneSpeed = 180
motorTwoSpeed = 180
motorThreeSpeed = 180
motorFourSpeed = 185

min = 180
strength = 200

#---------------------
#------Functions------
#---------------------

def initializeMotors(motorOne, motorTwo, motorThree, motorFour):
    pi.set_PWM_frequency(motorOne, 400)
    pi.set_PWM_range(motorOne, 2500)
    pi.set_PWM_frequency(motorTwo, 400)
    pi.set_PWM_range(motorTwo, 2500)
    pi.set_PWM_frequency(motorThree, 400)
    pi.set_PWM_range(motorThree, 2500)
    pi.set_PWM_frequency(motorFour, 400)
    pi.set_PWM_range(motorFour, 2500)

    pi.set_PWM_dutycycle(motorOne,  motorOneSpeed)
    pi.set_PWM_dutycycle(motorTwo,  motorTwoSpeed)
    pi.set_PWM_dutycycle(motorThree,  motorThreeSpeed)
    pi.set_PWM_dutycycle(motorFour,  motorFourSpeed)

def increaseSpeed(motorSpeed):
    motorSpeed = motorSpeed + 5
    return motorSpeed

def decreaseSpeed(motorSpeed):
    motorSpeed = motorSpeed - 5
    return motorSpeed

def shutdownMotor(motorSpeed):
    while motorSpeed > 0:
        motorSpeed = motorSpeed - 1
        return motorSpeed

#-----------------------------
#------Movement Fucntions-----
#-----------------------------

def strafeLeft():
    motorThreeSpeed = increaseSpeed(motorThreeSpeed)
    motorTwoSpeed = increaseSpeed(motorTwoSpeed)
    sleep(.5)
    motorThreeSpeed = decreaseSpeed(motorThreeSpeed)
    motorTwoSpeed = decreaseSpeed(motorTwoSpeed)

def strafeRight():
    motorOneSpeed = increaseSpeed(motorOneSpeed)
    motorFourSpeed = increaseSpeed(motorFourSpeed)
    sleep(.5)
    motorOneSpeed = decreaseSpeed(motorOneSpeed)
    motorFourSpeed = decreaseSpeed(motorFourSpeed)

def moveForward():
    motorFourSpeed = increaseSpeed(motorFourSpeed)
    motorTwoSpeed = increaseSpeed(motorTwoSpeed)
    sleep(.5)
    motorFourpeed = decreaseSpeed(motorFourSpeed)
    motorTwoSpeed = decreaseSpeed(motorTwoSpeed)

def moveBackwards():
    motorOneSpeed = increaseSpeed(motorOneSpeed)
    motorThreeSpeed = increaseSpeed(motorThreeSpeed)
    sleep(.5)
    motorThreeSpeed = decreaseSpeed(motorThreeSpeed)
    motorOneSpeed = decreaseSpeed(motorTwoSpeed)

#-----------------------------
#------Begin the program------
#-----------------------------

#----------------------------------------
# This will prompt for the pins to modify
# Each entered pin will be initialized and have global values set to default
#----------------------------------------

print('***Connect Battery & Press ENTER to start***')
res = raw_input()

print('***Enter Pins for Each Prompted Motor***')

print('Motor 1')
res = input()
motorOne = res

print('Motor 2')
res = input()
motorTwo = res

print('Motor 3')
res = input()
motorThree = res

print('Motor 4')
res = input()
motorFour = res

#----------------------------------------
# All motors will now be initialized
# The loop-to-follow will receive inputs and then change motorspeeds accordingly
#----------------------------------------

initializeMotors(motorOne, motorTwo, motorThree, motorFour)

res = raw_input()
motorOneSpeed = 195
motorTwoSpeed = 185
motorThreeSpeed = 190
motorFourSpeed = 190

res = raw_input()

print ('System initialized and running.')
print ('Follow your reference key or press 9 to shutdown')
cycling = True
try:
    while cycling:
        pi.set_PWM_dutycycle(motorOne,  motorOneSpeed)
        pi.set_PWM_dutycycle(motorTwo,  motorTwoSpeed)
        pi.set_PWM_dutycycle(motorThree,  motorThreeSpeed)
        pi.set_PWM_dutycycle(motorFour,  motorFourSpeed)

        print ("motorOne: %s" % (motorOneSpeed))
        print ("motorTwo: %s" % (motorTwoSpeed))
        print ("motorThree: %s" % (motorThreeSpeed))
        print ("motorFour: %s" % (motorFourSpeed))

        # Read the Euler angles for heading, roll, pitch (all in degrees).
        heading, roll, pitch = bno.read_euler()
        # Read the calibration status, 0=uncalibrated and 3=fully calibrated.
        sys, gyro, accel, mag = bno.get_calibration_status()
        # Print everything out.
        print('Heading={0:0.2F} Roll={1:0.2F} Pitch={2:0.2F}\tSys_cal={3} Gyro_cal={4} Accel_cal={5} Mag_cal={6}'.format(heading, roll, pitch, sys, gyro, accel, mag))

        range = (strength - min)

        MaxTurn = 10
        change = heading
        if(change > 180):
            change = change * 100
            change = change / float(180)
            change = change - 100
            change = 100 - change
        #end of if

        Tpercent = (change * 100) / float(180)
        RTurn = MaxTurn * Tpercent
        if(heading > 180):
            Rturn *= -1

        RTurn *= -1

        Right = ((roll / float(30)) * range)
        Left = -1 * ((roll / float(30)) * range)

        Front = -1 * ((pitch / float(30)) * range)
        Back = ((pitch / float(30)) * range)

        #=====================================================

        #sets the motors actual values
        motorTwoSpeed = Back + Right + strength + RTurn
        motorFourSpeed = Back + Left + strength - RTurn
        motorThreeSpeed = Front + Right + strength  - RTurn
        motorOneSpeed = Front + Left + strength + RTurn
        """
        if (motorOneSpeed > 220):
            motorOneSpeed = 220
            print("Excess prevented on Motor 1")
        if (motorTwoSpeed > 210):
            motorTwoSpeed = 210
            print("Excess prevented on Motor 2")
        if (motorThreeSpeed > 215):
            motorThreeSpeed = 215
            print("Excess prevented on Motor 3")
        if (motorFourSpeed > 215):
            motorFourSpeed = 215
            print("Excess prevented on Motor 4")

            """
    # End of while
# End of Try

#----------------------------------------
# When the while loop has ended, the code will proceed here
# This will shutdown all motors in increments of one, until the speed value has reached '0'
#----------------------------------------

finally:
    # shut down cleanly
    while (systemOn):
        if motorOneSpeed > 0:
            motorOneSpeed = motorOneSpeed - 1
        if motorTwoSpeed > 0:
            motorTwoSpeed = motorTwoSpeed - 1
        if motorThreeSpeed > 0:
            motorThreeSpeed = motorThreeSpeed - 1
        if motorFourSpeed > 0:
            motorFourSpeed = motorFourSpeed - 1

        pi.set_PWM_dutycycle(motorOne,  motorOneSpeed)
        pi.set_PWM_dutycycle(motorTwo,  motorTwoSpeed)
        pi.set_PWM_dutycycle(motorThree,  motorThreeSpeed)
        pi.set_PWM_dutycycle(motorFour,  motorFourSpeed)

        if (motorOneSpeed == 0) and (motorTwoSpeed == 0) and (motorThreeSpeed == 0) and (motorFourSpeed == 0):
            systemOn = False

monitoring = False

print ("System Shutdown")

# Done


text:
#pragma warning disable CA1024

namespace Dike.Core.Configuration
{
    using Conditions;
    using Dike.Core.Collections.Extensions;
    using Dike.Core.Runtime.Session;
    using System;
    using System.Collections.Generic;
    using System.Collections.Immutable;
    using System.Linq;
    using System.Threading.Tasks;

    /// <summary>
    /// This class implements <see cref="ISettingManager"/> to manage setting values in the database.
    /// </summary>
    public class SettingManager
        : ISettingManager, Dependency.ISingleInstance
    {
        #region Fields

        /// <summary>
        /// The application settings cache key.
        /// </summary>
        public const string ApplicationSettingsCacheKey = "ApplicationSettings";

        private readonly Runtime.Caching.ITypedCache<string, Dictionary<string, SettingInfo>> _applicationSettingCache;
        private readonly ISettingDefinitionManager _settingDefinitionManager;
        private readonly Runtime.Caching.ITypedCache<int, Dictionary<string, SettingInfo>> _tenantSettingCache;
        private readonly Runtime.Caching.ITypedCache<string, Dictionary<string, SettingInfo>> _userSettingCache;

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="SettingManager"/> class.
        /// </summary>
        /// <param name="settingDefinitionManager">The setting definition manager.</param>
        /// <param name="cacheManager">The cache manager.</param>
        public SettingManager(ISettingDefinitionManager settingDefinitionManager, Runtime.Caching.ICacheManager cacheManager)
        {
            _settingDefinitionManager = settingDefinitionManager;
            _applicationSettingCache = cacheManager.GetApplicationSettingsCache();
            _tenantSettingCache = cacheManager.GetTenantSettingsCache();
            _userSettingCache = cacheManager.GetUserSettingsCache();

            Session = EmptySession.Instance;
            SettingStore = DefaultConfigSettingStore.Instance;
        }

        #endregion Constructors

        #region Properties

        /// <summary>
        /// Gets or sets the session.
        /// </summary>
        /// <value>The session.</value>
        public ISession Session
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the setting store.
        /// </summary>
        /// <value>The setting store.</value>
        public ISettingStore SettingStore
        {
            get;
            set;
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Changes the value of an application setting asynchronous.
        /// </summary>
        /// <param name="name">The unique name of the setting.</param>
        /// <param name="value">The new value.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        [Domain.UnitOfWork.UnitOfWork]
        public virtual async Task ChangeSettingForApplicationAsync(string name, string value)
        {
            await InsertOrUpdateOrDeleteSettingValueAsync(name, value, null, null).ConfigureAwait(false);
            await _applicationSettingCache.RemoveAsync(ApplicationSettingsCacheKey).ConfigureAwait(false);
        }

        /// <summary>
        /// Changes the value of a tenant asynchronous.
        /// </summary>
        /// <param name="tenantId">The tenant identifier.</param>
        /// <param name="name">The unique name of the setting.</param>
        /// <param name="value">The new value.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        [Domain.UnitOfWork.UnitOfWork]
        public virtual async Task ChangeSettingForTenantAsync(int tenantId, string name, string value)
        {
            await InsertOrUpdateOrDeleteSettingValueAsync(name, value, tenantId, null).ConfigureAwait(false);
            await _tenantSettingCache.RemoveAsync(tenantId).ConfigureAwait(false);
        }

        /// <summary>
        /// Changes the value of a user asynchronous.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="name">The unique name of the setting.</param>
        /// <param name="value">The new value.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        [Domain.UnitOfWork.UnitOfWork]
        public virtual Task ChangeSettingForUserAsync(long userId, string name, string value)
            => ChangeSettingForUserAsync(new UserIdentifier(Session.TenantId, userId), name, value);

        /// <summary>
        /// Changes the value of a user asynchronous.
        /// </summary>
        /// <param name="user">The user identifier.</param>
        /// <param name="name">The unique name of the setting.</param>
        /// <param name="value">The new value.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        [Domain.UnitOfWork.UnitOfWork]
        public async Task ChangeSettingForUserAsync(UserIdentifier user, string name, string value)
        {
            await InsertOrUpdateOrDeleteSettingValueAsync(name, value, user.TenantId, user.UserId).ConfigureAwait(false);
            await _userSettingCache.RemoveAsync(user.ToUserIdentifierString()).ConfigureAwait(false);
        }

        /// <summary>
        /// Gets the current values for all settings asynchronous. It gets all setting values, overwritten by application, current tenant (if exists) and the current user (if exists).
        /// </summary>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains a read only list with all setting values.</returns>
        public async Task<IReadOnlyList<ISettingValue>> GetAllSettingValuesAsync()
            => await GetAllSettingValuesAsync(SettingScopes.Application | SettingScopes.Tenant | SettingScopes.User).ConfigureAwait(false);

        /// <summary>
        /// Gets all current values for the settings asynchronous. It gets default values of all settings overwritten by given scopes values.
        /// </summary>
        /// <param name="scopes">One or more scopes to get.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains a read only list with all setting values.</returns>
        public async Task<IReadOnlyList<ISettingValue>> GetAllSettingValuesAsync(SettingScopes scopes)
        {
            Dictionary<string, SettingDefinition> settingDefinitions = new Dictionary<string, SettingDefinition>();
            Dictionary<string, ISettingValue> settingValues = new Dictionary<string, ISettingValue>();

            // Fill all setting with default values.
            foreach (SettingDefinition setting in _settingDefinitionManager.GetAllSettingDefinitions())
            {
                settingDefinitions[setting.Name] = setting;
                settingValues[setting.Name] = new SettingValueObject(setting.Name, setting.DefaultValue);
            }

            // Overwrite application settings
            if (scopes.HasFlag(SettingScopes.Application))
            {
                foreach (ISettingValue settingValue in await GetAllSettingValuesForApplicationAsync().ConfigureAwait(false))
                {
                    SettingDefinition setting = settingDefinitions.GetOrDefault(settingValue.Name);

                    // UNDONE aspnetboilderplate : Conditions get complicated, try to simplify it
                    if (setting == null || !setting.Scopes.HasFlag(SettingScopes.Application))
                    {
                        continue;
                    }

                    if (!setting.IsInherited &&
                        ((setting.Scopes.HasFlag(SettingScopes.Tenant) && Session.TenantId.HasValue) || (setting.Scopes.HasFlag(SettingScopes.User) && Session.UserId.HasValue)))
                    {
                        continue;
                    }

                    settingValues[settingValue.Name] = new SettingValueObject(settingValue.Name, settingValue.Value);
                }
            }

            // Overwrite tenant settings
            if (scopes.HasFlag(SettingScopes.Tenant) && Session.TenantId.HasValue)
            {
                foreach (ISettingValue settingValue in await GetAllSettingValuesForTenantAsync(Session.TenantId.Value).ConfigureAwait(false))
                {
                    SettingDefinition setting = settingDefinitions.GetOrDefault(settingValue.Name);

                    // UNDONE aspnetboilderplate : Conditions get complicated, try to simplify it
                    if (setting == null || !setting.Scopes.HasFlag(SettingScopes.Tenant))
                    {
                        continue;
                    }

                    if (!setting.IsInherited &&
                        (setting.Scopes.HasFlag(SettingScopes.User) && Session.UserId.HasValue))
                    {
                        continue;
                    }

                    settingValues[settingValue.Name] = new SettingValueObject(settingValue.Name, settingValue.Value);
                }
            }

            // Overwrite user settings
            if (scopes.HasFlag(SettingScopes.User) && Session.UserId.HasValue)
            {
                foreach (ISettingValue settingValue in await GetAllSettingValuesForUserAsync(Session.ToUserIdentifier()).ConfigureAwait(false))
                {
                    SettingDefinition setting = settingDefinitions.GetOrDefault(settingValue.Name);
                    if (setting != null && setting.Scopes.HasFlag(SettingScopes.User))
                    {
                        settingValues[settingValue.Name] = new SettingValueObject(settingValue.Name, settingValue.Value);
                    }
                }
            }

            return settingValues.Values.ToImmutableList();
        }

        /// <summary>
        /// Gets all current setting values for the application asynchronous. It returns only settings those are explicitly set for the application.
        /// </summary>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains a read only list with all setting values.</returns>
        /// <remarks>If a setting's default value is used, it's not included in the result list.
        /// If you want to get current values of all settings, use the <see cref="GetAllSettingValuesAsync()"/> method.</remarks>
        public async Task<IReadOnlyList<ISettingValue>> GetAllSettingValuesForApplicationAsync()
            => (await GetApplicationSettingsAsync().ConfigureAwait(false)).Values
                    .Select(setting => new SettingValueObject(setting.Name, setting.Value))
                    .ToImmutableList();

        /// <summary>
        /// Gets all current setting values for the given tenant asynchronous. It returns only settings those are explicitly set for the tenant.
        /// </summary>
        /// <param name="tenantId">The tenant identifier.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains a read only list with all setting values.</returns>
        /// <remarks>If a setting's default value is used, it's not included in the result list.
        /// If you want to get current values of all settings, use the <see cref="GetAllSettingValuesAsync()"/> method.</remarks>
        public async Task<IReadOnlyList<ISettingValue>> GetAllSettingValuesForTenantAsync(int tenantId)
            => (await GetReadOnlyTenantSettingsAsync(tenantId).ConfigureAwait(false)).Values
                    .Select(setting => new SettingValueObject(setting.Name, setting.Value))
                    .ToImmutableList();

        /// <summary>
        /// Gets the current setting values for the given user asynchronous. It returns only settings those are explicitly set for the user.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains a read only list with all setting values.</returns>
        /// <remarks>If a setting's value is not set for the user (for example if user uses the default value), it's not included the result list.
        /// If you want to get current values of all settings, use <see cref="GetAllSettingValuesAsync()"/> method.</remarks>
        public Task<IReadOnlyList<ISettingValue>> GetAllSettingValuesForUserAsync(long userId)
            => GetAllSettingValuesForUserAsync(new UserIdentifier(Session.TenantId, userId));

        /// <summary>
        /// Gets the current setting values for the given user asynchronous. It returns only settings those are explicitly set for the user.
        /// </summary>
        /// <param name="user">The user identifier.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains a read only list with all setting values.</returns>
        /// <remarks>If a setting's value is not set for the user (for example if user uses the default value), it's not included the result list.
        /// If you want to get current values of all settings, use <see cref="GetAllSettingValuesAsync()"/> method.</remarks>
        public async Task<IReadOnlyList<ISettingValue>> GetAllSettingValuesForUserAsync(UserIdentifier user)
            => (await GetReadOnlyUserSettingsAsync(user).ConfigureAwait(false)).Values
                        .Select(setting => new SettingValueObject(setting.Name, setting.Value))
                        .ToImmutableList();

        /// <summary>
        /// Gets the current value of a setting asynchronous. It gets the setting value, overwritten by application, current tenant and current user if exists.
        /// </summary>
        /// <param name="name">The unique name of the setting.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains the current value of the setting.</returns>
        public Task<string> GetSettingValueAsync(string name)
            => GetSettingValueInternalAsync(name, Session.TenantId, Session.UserId);

        /// <summary>
        /// Gets the current value of an application setting asynchronous.
        /// </summary>
        /// <param name="name">The unique name of the setting.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains the current value of the application setting.</returns>
        public Task<string> GetSettingValueForApplicationAsync(string name)
            => GetSettingValueInternalAsync(name);

        /// <summary>
        /// Gets the current value of an application setting asynchronous.
        /// </summary>
        /// <param name="name">The unique name of the setting.</param>
        /// <param name="fallbackToDefault">if set to <c>false</c> it just gets the value from the tenant and returns null if the application has not defined a value for the setting.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains the current value of the application setting.</returns>
        public Task<string> GetSettingValueForApplicationAsync(string name, bool fallbackToDefault)
            => GetSettingValueInternalAsync(name, fallbackToDefault: fallbackToDefault);

        /// <summary>
        /// Gets the current value of a tenant setting asynchronous. It gets the setting value, overwritten by given tenant.
        /// </summary>
        /// <param name="name">The unique name of the setting.</param>
        /// <param name="tenantId">The tenant identifier.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains the current value of the tenant setting.</returns>
        public Task<string> GetSettingValueForTenantAsync(string name, int tenantId)
            => GetSettingValueInternalAsync(name, tenantId);

        /// <summary>
        /// Gets the current value of a tenant setting asynchronous.
        /// </summary>
        /// <param name="name">The unique name of the setting.</param>
        /// <param name="tenantId">The tenant identifier.</param>
        /// <param name="fallbackToDefault">if set to <c>false</c> it just gets the value from the tenant and returns null if the tenant has not defined a value for the setting.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains the current value of the tenant setting.</returns>
        public Task<string> GetSettingValueForTenantAsync(string name, int tenantId, bool fallbackToDefault)
            => GetSettingValueInternalAsync(name, tenantId, fallbackToDefault: fallbackToDefault);

        /// <summary>
        /// Gets the current value of a user setting asynchronous. It gets the setting value, overwritten by given tenant and user.
        /// </summary>
        /// <param name="name">The unique name of the setting.</param>
        /// <param name="tenantId">The tenant identifier.</param>
        /// <param name="userId">The user identifier.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains the current value of the user setting.</returns>
        public Task<string> GetSettingValueForUserAsync(string name, int? tenantId, long userId)
            => GetSettingValueInternalAsync(name, tenantId, userId);

        /// <summary>
        /// Gets the current value of a user setting asynchronous.
        /// </summary>
        /// <param name="name">The unique name of the setting.</param>
        /// <param name="tenantId">The tenant identifier.</param>
        /// <param name="userId">The user identifier.</param>
        /// <param name="fallbackToDefault">if set to <c>false</c> it just gets the value from the user and returns null if the user has not defined a value for the setting.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains the current value of the user setting.</returns>
        public Task<string> GetSettingValueForUserAsync(string name, int? tenantId, long userId, bool fallbackToDefault)
            => GetSettingValueInternalAsync(name, tenantId, userId, fallbackToDefault);

        /// <summary>
        /// Gets the current value of a user setting asynchronous. It gets the setting value, overwritten by given tenant and user.
        /// </summary>
        /// <param name="name">The unique name of the setting.</param>
        /// <param name="user">The user identifier.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains the current value of the user setting.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="name"/> can not be <c>null</c>.</exception>
        /// <exception cref="ArgumentException"><paramref name="name"/> can not be empty or contain only whitespace.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="user"/> can not be <c>null</c>.</exception>
        public Task<string> GetSettingValueForUserAsync(string name, UserIdentifier user)
        {
            name.Requires(nameof(name)).IsNotNullOrWhiteSpace();
            user.Requires(nameof(user)).IsNotNull();

            return GetSettingValueForUserAsync(name, user.TenantId, user.UserId);
        }

        /// <summary>
        /// Asynchronously gets a read only list of all application settings.
        /// </summary>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains a read only list of all application settings.</returns>
        private async Task<Dictionary<string, SettingInfo>> GetApplicationSettingsAsync()
            => await _applicationSettingCache.GetItemAsync(
                    ApplicationSettingsCacheKey,
                    async (string dummy) =>
                    {
                        Dictionary<string, SettingInfo> dictionary = new Dictionary<string, SettingInfo>();

                        List<SettingInfo> settingValues = await SettingStore.GetAllListAsync(null, null).ConfigureAwait(false);
                        foreach (SettingInfo settingValue in settingValues)
                        {
                            dictionary[settingValue.Name] = settingValue;
                        }

                        return dictionary;
                    }).ConfigureAwait(false);

        /// <summary>
        /// Asynchronously gets a read only list of all tenant settings.
        /// </summary>
        /// <param name="tenantId">The tenant identifier.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains a read only list of all tenant settings.</returns>
        private async Task<ImmutableDictionary<string, SettingInfo>> GetReadOnlyTenantSettingsAsync(int tenantId)
        {
            Dictionary<string, SettingInfo> cachedDictionary = await GetTenantSettingsFromCacheAsync(tenantId).ConfigureAwait(false);
            lock (cachedDictionary)
            {
                return cachedDictionary.ToImmutableDictionary();
            }
        }

        /// <summary>
        /// Asynchronously gets a read only list of all user settings.
        /// </summary>
        /// <param name="user">The user identifier.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains a read only list of all user settings.</returns>
        private async Task<ImmutableDictionary<string, SettingInfo>> GetReadOnlyUserSettingsAsync(UserIdentifier user)
        {
            Dictionary<string, SettingInfo> cachedDictionary = await GetUserSettingsFromCacheAsync(user).ConfigureAwait(false);
            lock (cachedDictionary)
            {
                return cachedDictionary.ToImmutableDictionary();
            }
        }

        /// <summary>
        /// Asynchronously gets a read only setting value or null for the application.
        /// </summary>
        /// <param name="name">The unique name of the setting.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains the read only setting value or <c>null</c>.</returns>
        private async Task<SettingInfo> GetSettingValueForApplicationOrNullAsync(string name)
            => (await GetApplicationSettingsAsync().ConfigureAwait(false)).GetOrDefault(name);

        /// <summary>
        /// Asynchronously gets a read only setting value or null for a tenant.
        /// </summary>
        /// <param name="tenantId">The tenant identifier.</param>
        /// <param name="name">The unique name of the setting.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains the read only setting value or <c>null</c>.</returns>
        private async Task<SettingInfo> GetSettingValueForTenantOrNullAsync(int tenantId, string name)
            => (await GetReadOnlyTenantSettingsAsync(tenantId).ConfigureAwait(false)).GetOrDefault(name);

        /// <summary>
        /// Asynchronously gets a read only setting value or null for a user.
        /// </summary>
        /// <param name="user">The user identifier.</param>
        /// <param name="name">The unique name of the setting.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains the read only setting value or <c>null</c>.</returns>
        private async Task<SettingInfo> GetSettingValueForUserOrNullAsync(UserIdentifier user, string name)
            => (await GetReadOnlyUserSettingsAsync(user).ConfigureAwait(false)).GetOrDefault(name);

        /// <summary>
        /// Gets a setting value asynchronously.
        /// </summary>
        /// <param name="name">The unique name of the setting.</param>
        /// <param name="tenantId">The tenant identifier.</param>
        /// <param name="userId">The user identifier.</param>
        /// <param name="fallbackToDefault">if set to <c>true</c> the return value falls back to the default value if the setting is not found.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains the current value of the setting.</returns>
        private async Task<string> GetSettingValueInternalAsync(string name, int? tenantId = null, long? userId = null, bool fallbackToDefault = true)
        {
            SettingDefinition settingDefinition = _settingDefinitionManager.GetSettingDefinition(name);

            // Get for user if defined
            if (settingDefinition.Scopes.HasFlag(SettingScopes.User) && userId.HasValue)
            {
                SettingInfo settingValue = await GetSettingValueForUserOrNullAsync(new UserIdentifier(tenantId, userId.Value), name).ConfigureAwait(false);
                if (settingValue != null)
                {
                    return settingValue.Value;
                }

                if (!fallbackToDefault)
                {
                    return null;
                }

                if (!settingDefinition.IsInherited)
                {
                    return settingDefinition.DefaultValue;
                }
            }

            // Get for tenant if defined
            if (settingDefinition.Scopes.HasFlag(SettingScopes.Tenant) && tenantId.HasValue)
            {
                SettingInfo settingValue = await GetSettingValueForTenantOrNullAsync(tenantId.Value, name).ConfigureAwait(false);
                if (settingValue != null)
                {
                    return settingValue.Value;
                }

                if (!fallbackToDefault)
                {
                    return null;
                }

                if (!settingDefinition.IsInherited)
                {
                    return settingDefinition.DefaultValue;
                }
            }

            // Get for application if defined
            if (settingDefinition.Scopes.HasFlag(SettingScopes.Application))
            {
                SettingInfo settingValue = await GetSettingValueForApplicationOrNullAsync(name).ConfigureAwait(false);
                if (settingValue != null)
                {
                    return settingValue.Value;
                }

                if (!fallbackToDefault)
                {
                    return null;
                }
            }

            // Not defined, get default value
            return settingDefinition.DefaultValue;
        }

        /// <summary>
        /// Asynchronously gets a tenant settings from the cache.
        /// </summary>
        /// <param name="tenantId">The tenant identifier.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains a dictionary with the names and setting values.</returns>
        private async Task<Dictionary<string, SettingInfo>> GetTenantSettingsFromCacheAsync(int tenantId)
            => await _tenantSettingCache.GetItemAsync(
                    tenantId,
                    async (int dummy) =>
                    {
                        Dictionary<string, SettingInfo> dictionary = new Dictionary<string, SettingInfo>();

                        List<SettingInfo> settingValues = await SettingStore.GetAllListAsync(tenantId, null).ConfigureAwait(false);
                        foreach (SettingInfo settingValue in settingValues)
                        {
                            dictionary[settingValue.Name] = settingValue;
                        }

                        return dictionary;
                    }).ConfigureAwait(false);

        /// <summary>
        /// Asynchronously gets a user settings from the cache.
        /// </summary>
        /// <param name="user">The user identifier.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains a dictionary with the names and setting values.</returns>
        private async Task<Dictionary<string, SettingInfo>> GetUserSettingsFromCacheAsync(UserIdentifier user)
            => await _userSettingCache.GetItemAsync(
                    user.ToUserIdentifierString(),
                    async (string dummy) =>
                    {
                        Dictionary<string, SettingInfo> dictionary = new Dictionary<string, SettingInfo>();

                        List<SettingInfo> settingValues = await SettingStore.GetAllListAsync(user.TenantId, user.UserId).ConfigureAwait(false);
                        foreach (SettingInfo settingValue in settingValues)
                        {
                            dictionary[settingValue.Name] = settingValue;
                        }

                        return dictionary;
                    }).ConfigureAwait(false);

        /// <summary>
        /// Asynchronously insert, updates or deletes a setting value.
        /// </summary>
        /// <param name="name">The unique name of the setting.</param>
        /// <param name="value">The value.</param>
        /// <param name="tenantId">The tenant identifier.</param>
        /// <param name="userId">The user identifier.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains the setting value.</returns>
        private async Task<SettingInfo> InsertOrUpdateOrDeleteSettingValueAsync(string name, string value, int? tenantId, long? userId)
        {
            SettingDefinition settingDefinition = _settingDefinitionManager.GetSettingDefinition(name);
            SettingInfo settingValue = await SettingStore.GetSettingOrNullAsync(tenantId, userId, name).ConfigureAwait(false);

            // Determine defaultValue
            string defaultValue = settingDefinition.DefaultValue;

            if (settingDefinition.IsInherited)
            {
                // for Tenant and User, Application's value overrides Setting Definition's default value.
                if (tenantId.HasValue || userId.HasValue)
                {
                    SettingInfo applicationValue = await GetSettingValueForApplicationOrNullAsync(name).ConfigureAwait(false);
                    if (applicationValue != null)
                    {
                        defaultValue = applicationValue.Value;
                    }
                }

                // for User, Tenants's value overrides Application's default value.
                if (userId.HasValue && tenantId.HasValue)
                {
                    SettingInfo tenantValue = await GetSettingValueForTenantOrNullAsync(tenantId.Value, name).ConfigureAwait(false);
                    if (tenantValue != null)
                    {
                        defaultValue = tenantValue.Value;
                    }
                }
            }

            // no need to store on database if the value is the default value
            if (value == defaultValue)
            {
                if (settingValue != null)
                {
                    await SettingStore.DeleteAsync(settingValue).ConfigureAwait(false);
                }

                return null;
            }

            // if it's not default value and not stored on database, then insert it
            if (settingValue == null)
            {
                settingValue = new SettingInfo
                {
                    TenantId = tenantId,
                    UserId = userId,
                    Name = name,
                    Value = value,
                };

                await SettingStore.CreateAsync(settingValue).ConfigureAwait(false);
                return settingValue;
            }

            // it's same value in database, no need to update
            if (settingValue.Value == value)
            {
                return settingValue;
            }

            // update the setting on database.
            settingValue.Value = value;
            await SettingStore.UpdateAsync(settingValue).ConfigureAwait(false);

            return settingValue;
        }

        #endregion Methods

        #region Classes

        /// <summary>
        /// Represents a setting value.
        /// </summary>
        private class SettingValueObject
            : ISettingValue
        {
            #region Constructors

            /// <summary>
            /// Initializes a new instance of the <see cref="SettingValueObject"/> class.
            /// </summary>
            /// <param name="name">The unique name of the setting.</param>
            /// <param name="value">The value of the setting.</param>
            public SettingValueObject(string name, string value)
            {
                Value = value;
                Name = name;
            }

            #endregion Constructors

            #region Properties

            /// <summary>
            /// Gets the unique name of the setting.
            /// </summary>
            /// <value>The unique name of the setting.</value>
            public string Name
            {
                get;
            }

            /// <summary>
            /// Gets the value of the setting.
            /// </summary>
            /// <value>The value of the setting.</value>
            public string Value
            {
                get;
            }

            #endregion Properties
        }

        #endregion Classes
    }
}

#pragma warning restore CA1024

redpajama_set_name: RedPajamaGithub


text:
<?php

// autoloading composer first
if (file_exists('../libraries/vendor/autoload.php')) {
	require('../libraries/vendor/autoload.php');
}

// running application
require('../libraries/vendor/Numbers/Framework/Application.php');
Application::run();


text:
import { Mouse, UiFinder, Waiter } from '@ephox/agar';
import { context, describe, it } from '@ephox/bedrock-client';
import { Css, Height, Remove, Scroll, SugarBody, SugarElement, Traverse } from '@ephox/sugar';
import { TinyDom, TinyHooks, TinyUiActions } from '@ephox/wrap-mcagar';
import { assert } from 'chai';

import Editor from 'tinymce/core/api/Editor';
import { Dialog } from 'tinymce/core/api/ui/Ui';

import * as DialogUtils from '../../module/DialogUtils';
import * as PageScroll from '../../module/PageScroll';
import { resizeToPos, scrollRelativeEditor } from '../../module/UiUtils';

describe('browser.tinymce.themes.silver.window.SilverInlineDialogPositionTest', () => {
  const dialogSpec: Dialog.DialogSpec<{}> = {
    title: 'Silver Test Inline (Toolbar) Dialog',
    body: {
      type: 'panel',
      items: []
    },
    buttons: [
      {
        type: 'cancel',
        name: 'cancel',
        text: 'Cancel'
      }
    ],
    initialData: {}
  };

  const pAssertPos = (dialog: SugarElement<HTMLElement>, pos: string, x: number, y: number) =>
    Waiter.pTryUntil('Wait for dialog position to update', () => {
      const diff = 5;
      const position = Css.get(dialog, 'position');
      const top = dialog.dom.offsetTop;
      const left = dialog.dom.offsetLeft;
      assert.equal(position, pos, `Dialog position (${position}) should be ${pos}`);
      assert.approximately(top, y, diff, `Dialog top position (${top}px) should be ~${y}px`);
      assert.approximately(left, x, diff, `Dialog left position (${left}px) should be ~${x}px`);
    });

  const openDialog = (editor: Editor): SugarElement<HTMLElement> => {
    DialogUtils.open(editor, dialogSpec, { inline: 'toolbar' });
    const dialog = UiFinder.findIn(SugarBody.body(), '.tox-dialog-inline').getOrDie();
    return Traverse.parent(dialog).getOr(dialog) as SugarElement<HTMLElement>;
  };

  context('Top toolbar positioning', () => {
    const hook = TinyHooks.bddSetup<Editor>({
      base_url: '/project/tinymce/js/tinymce',
      resize: 'both',
      height: 400,
      width: 650,
      toolbar_sticky: false,
      toolbar_mode: 'wrap'
    }, []);

    it('Test position when resizing', async () => {
      const editor = hook.editor();
      const resizeHandle = UiFinder.findIn(SugarBody.body(), '.tox-statusbar__resize-handle').getOrDie();
      const dialog = openDialog(editor);
      await pAssertPos(dialog, 'absolute', 158, -306);

      // Shrink the editor to 300px
      Mouse.mouseDown(resizeHandle);
      resizeToPos(650, 400, 500, 300);
      await pAssertPos(dialog, 'absolute', 5, -166); // Toolbar wraps so y diff is 100 + toolbar height

      // Enlarge the editor to 500px
      Mouse.mouseDown(resizeHandle);
      resizeToPos(500, 300, 750, 500);
      await pAssertPos(dialog, 'absolute', 258, -406);

      // Resize back to the original size
      Mouse.mouseDown(resizeHandle);
      resizeToPos(750, 500, 650, 400);
      await pAssertPos(dialog, 'absolute', 158, -306);

      DialogUtils.close(editor);
    });

    it('Test position when scrolling', async () => {
      const editor = hook.editor();
      const dialog = openDialog(editor);

      // Enlarge the editor to 2000px
      Height.set(TinyDom.container(editor), 2000);
      editor.dispatch('ResizeEditor');
      await pAssertPos(dialog, 'absolute', 158, -1901);

      // Scroll to 1500px and assert docked
      Scroll.to(0, 1500);
      await pAssertPos(dialog, 'fixed', 158, 0);

      // Scroll back to top and assert not docked
      Scroll.to(0, 0);
      await pAssertPos(dialog, 'absolute', 158, -1906);

      DialogUtils.close(editor);
    });

    it('Test initial position when initially scrolled', async () => {
      const editor = hook.editor();

      // Enlarge the editor to 2000px
      Height.set(TinyDom.container(editor), 2000);
      editor.dispatch('ResizeEditor');

      // Scroll to 1500px, open the dialog and assert docked
      Scroll.to(0, 1500);
      const dialog = openDialog(editor);
      await pAssertPos(dialog, 'fixed', 158, 0);

      // Scroll back to top and assert not docked
      Scroll.to(0, 0);
      await pAssertPos(dialog, 'absolute', 158, -1906);

      DialogUtils.close(editor);
    });
  });

  context('Bottom toolbar positioning', () => {
    const hook = TinyHooks.bddSetup<Editor>({
      base_url: '/project/tinymce/js/tinymce',
      height: 400,
      width: 600,
      toolbar_sticky: true,
      toolbar_location: 'bottom'
    }, []);

    PageScroll.bddSetup(hook.editor, 1000);

    it('Position of dialog should be constant when toolbar bottom docks', async () => {
      const editor = hook.editor();

      // Scroll so that the editor is fully in view
      scrollRelativeEditor(editor, 'top', -100);
      const dialog = openDialog(editor);
      await pAssertPos(dialog, 'absolute', 108, -1387);

      // Scroll so that bottom of window overlaps bottom of editor
      scrollRelativeEditor(editor, 'bottom', -200);
      await pAssertPos(dialog, 'absolute', 108, -1387);

      // Scroll so that top of window overlaps top of editor
      scrollRelativeEditor(editor, 'top', 200);
      await pAssertPos(dialog, 'fixed', 108, 0);

      DialogUtils.close(editor);
    });

    it('Test position when resizing', async () => {
      const editor = hook.editor();
      const resizeHandle = UiFinder.findIn(SugarBody.body(), '.tox-statusbar__resize-handle').getOrDie();

      scrollRelativeEditor(editor, 'top', -100);
      const dialog = openDialog(editor);
      await pAssertPos(dialog, 'absolute', 108, -1387);

      // Shrink the editor to 300px
      Mouse.mouseDown(resizeHandle);
      resizeToPos(600, 400, 600, 300);
      await pAssertPos(dialog, 'absolute', 108, -1287);

      DialogUtils.close(editor);
    });
  });

  context('Bottom toolbar with inline editor positioning', () => {
    const hook = TinyHooks.bddSetupFromElement<Editor>({
      theme: 'silver',
      base_url: '/project/tinymce/js/tinymce',
      inline: true,
      toolbar_location: 'bottom'
    }, () => {
      const div = SugarElement.fromHtml<HTMLDivElement>('

');
      return {
        element: div,
        teardown: () => Remove.remove(div)
      };
    }, []);

    PageScroll.bddSetup(hook.editor, 1000);

    it('Position of dialog should be constant when toolbar bottom docks', async () => {
      const editor = hook.editor();

      // Scroll so that the editor is fully in view
      scrollRelativeEditor(editor, 'top', -100);
      editor.focus();
      await TinyUiActions.pWaitForPopup(editor, '.tox-tinymce-inline');
      const dialog = openDialog(editor);
      await pAssertPos(dialog, 'absolute', 106, -1388);

      // Scroll so that bottom of window overlaps bottom of editor
      scrollRelativeEditor(editor, 'bottom', -200);
      await pAssertPos(dialog, 'absolute', 106, -1388);

      // Scroll so that top of window overlaps top of editor
      scrollRelativeEditor(editor, 'top', 200);
      await pAssertPos(dialog, 'fixed', 106, 0);

      DialogUtils.close(editor);
    });
  });
});


text:
import { ComponentType } from "react"

import { Resolver } from "found-relay"
import { ScrollManager } from "found-scroll"
import createInitialFarceRouter from "found/createInitialFarceRouter"
import createRender from "found/createRender"

import {
  BrowserProtocol,
  HashProtocol,
  MemoryProtocol,
  createQueryMiddleware,
} from "farce"

import qs from "qs"

import createLogger from "Utils/logger"
import { getUser } from "Utils/user"
import { createRouteConfig } from "./Utils/createRouteConfig"
import { queryStringParsing } from "./Utils/queryStringParsing"

import { createRelaySSREnvironment } from "System/Relay/createRelaySSREnvironment"
import { Boot } from "System/Router/Boot"

import { RouterConfig } from "./"

import { trackingMiddleware } from "System/Analytics/trackingMiddleware"
import { RenderError, RenderPending, RenderReady } from "./RenderStatus"
import { shouldUpdateScroll } from "./Utils/shouldUpdateScroll"
import { buildClientAppContext } from "System/Router/buildClientAppContext"

interface Resolve {
  ClientApp: ComponentType<any>
}

const logger = createLogger("Artsy/Router/buildClientApp.tsx")

export function buildClientApp(config: RouterConfig): Promise<Resolve> {
  return new Promise(async (resolve, reject) => {
    try {
      const {
        context = {},
        history = {},
        initialRoute = "/",
        routes = [],
      } = config
      const clientContext = buildClientAppContext(context)

      if (clientContext) {
        const user = getUser(clientContext.user)
        const relayEnvironment = createRelaySSREnvironment({
          cache: JSON.parse(window.__RELAY_BOOTSTRAP__ || "{}"),
          user,
        })

        const getHistoryProtocol = () => {
          switch (history.protocol) {
            case "browser":
              return new BrowserProtocol()
            case "hash":
              return new HashProtocol()
            case "memory":
              return new MemoryProtocol(initialRoute)
            default:
              return new BrowserProtocol()
          }
        }

        const historyMiddlewares = [
          createQueryMiddleware({
            parse: queryStringParsing,
            stringify: qs.stringify,
          }),
          trackingMiddleware({
            excludePaths: [
              // Due to special needs, this page has its own page-view tracking implementation.
              // @see https://github.com/artsy/force/blob/2c0db041fa6cb50e9f747ea95860ad5c38290653/src/Apps/Artwork/ArtworkApp.tsx#L117-L121
              "/artwork(.*)",
            ],
            excludeReferrers: ["/\\?(.*)onboarding=true(.*)"],
          }),
        ]
        const resolver = new Resolver(relayEnvironment)

        const Renderer = createRender({
          renderError: RenderError,
          renderPending: RenderPending,
          renderReady: RenderReady,
        })

        const Router = await createInitialFarceRouter({
          historyMiddlewares,
          historyOptions: history.options,
          historyProtocol: getHistoryProtocol(),
          matchContext: clientContext,
          render: renderArgs => {
            return (
              <ScrollManager
                renderArgs={renderArgs}
                shouldUpdateScroll={shouldUpdateScroll}
              >
                <Renderer {...renderArgs} />
              </ScrollManager>
            )
          },
          resolver,
          routeConfig: createRouteConfig(routes),
        })

        const ClientApp = () => {
          return (
            <Boot
              context={clientContext}
              user={user}
              relayEnvironment={relayEnvironment}
              routes={routes}
            >
              <Router resolver={resolver} />
            </Boot>
          )
        }

        resolve({
          ClientApp,
        })
      }
    } catch (error) {
      logger.error(error)
      reject(error)
    }
  })
}


text:
cask :v1 => 'font-noto-sans-buhid' do
  version :latest
  sha256 :no_check

  url 'https://noto-website.storage.googleapis.com/pkgs/NotoSansBuhid-unhinted.zip'
  homepage 'https://www.google.com/get/noto'
  license :apache

  font 'NotoSansBuhid-Regular.ttf'
end


text:
<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * QuoteRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class QuoteRepository extends EntityRepository
{
    public function getBest()
    {
        return $this->createQueryBuilder('q')
            ->orderBy('q.created', 'DESC')
            ->getQuery()
            ->execute();
    }
}


text:
# Disallow Magic Numbers (no-magic-numbers)

'Magic numbers' are numbers that occur multiple times in code without an explicit meaning.
They should preferably be replaced by named constants.

```js
var now = Date.now(),
    inOneHour = now + (60 * 60 * 1000);
```

## Rule Details

The `no-magic-numbers` rule aims to make code more readable and refactoring easier by ensuring that special numbers
are declared as constants to make their meaning explicit.

Examples of **incorrect** code for this rule:

```js
/*eslint no-magic-numbers: "error"*/

var dutyFreePrice = 100,
    finalPrice = dutyFreePrice + (dutyFreePrice * 0.25);
```

```js
/*eslint no-magic-numbers: "error"*/

var data = ['foo', 'bar', 'baz'];

var dataLast = data[2];
```

```js
/*eslint no-magic-numbers: "error"*/

var SECONDS;

SECONDS = 60;
```

Examples of **correct** code for this rule:

```js
/*eslint no-magic-numbers: "error"*/

var TAX = 0.25;

var dutyFreePrice = 100,
    finalPrice = dutyFreePrice + (dutyFreePrice * TAX);
```

## Options

### ignore

An array of numbers to ignore. It's set to `[]` by default.
If provided, it must be an `Array`.

The array can contain values of `number` and `string` types.
If it's a string, the text must be parsed as `bigint` literal (e.g., `"100n"`).

Examples of **correct** code for the sample `{ "ignore": [1] }` option:

```js
/*eslint no-magic-numbers: ["error", { "ignore": [1] }]*/

var data = ['foo', 'bar', 'baz'];
var dataLast = data.length && data[data.length - 1];
```

Examples of **correct** code for the sample `{ "ignore": ["1n"] }` option:

```js
/*eslint no-magic-numbers: ["error", { "ignore": ["1n"] }]*/

foo(1n);
```

### ignoreArrayIndexes

A boolean to specify if numbers used as array indexes are considered okay. `false` by default.

Examples of **correct** code for the `{ "ignoreArrayIndexes": true }` option:

```js
/*eslint no-magic-numbers: ["error", { "ignoreArrayIndexes": true }]*/

var data = ['foo', 'bar', 'baz'];
var dataLast = data[2];
```

### enforceConst

A boolean to specify if we should check for the const keyword in variable declaration of numbers. `false` by default.

Examples of **incorrect** code for the `{ "enforceConst": true }` option:

```js
/*eslint no-magic-numbers: ["error", { "enforceConst": true }]*/

var TAX = 0.25;

var dutyFreePrice = 100,
    finalPrice = dutyFreePrice + (dutyFreePrice * TAX);
```

### detectObjects

A boolean to specify if we should detect numbers when setting object properties for example. `false` by default.

Examples of **incorrect** code for the `{ "detectObjects": true }` option:

```js
/*eslint no-magic-numbers: ["error", { "detectObjects": true }]*/

var magic = {
  tax: 0.25
};

var dutyFreePrice = 100,
    finalPrice = dutyFreePrice + (dutyFreePrice * magic.tax);
```

Examples of **correct** code for the `{ "detectObjects": true }` option:

```js
/*eslint no-magic-numbers: ["error", { "detectObjects": true }]*/

var TAX = 0.25;

var magic = {
  tax: TAX
};

var dutyFreePrice = 100,
    finalPrice = dutyFreePrice + (dutyFreePrice * magic.tax);
```


text:
<?php

require_once(_PS_MODULE_DIR_ . 'billmategateway/library/abstracts/CallbackController.php');

class BillmategatewayAcceptModuleFrontController extends CallbackController
{
    public $request = 'accept';

    public function __construct()
    {
        parent::__construct();
    }

    public function postProcess()
    {
        if ($this->method == 'checkout') {
            $checkoutOrderId = Common::getCartCheckoutHash();

            if ($checkoutOrderId) {
                return $this->respondWithSuccess(array(
                    'hash' => urlencode($checkoutOrderId),
                ));
            }
        }

        // If payment data is invalid, show default confirm page
        if (!$this->client->verifyPaymentData()) {
            return $this->respondWithSuccess(true);
        }

        // If payment is not payed, show default confirm page
        if (!$this->client->isPayed()) {
            return $this->respondWithSuccess(true);
        }

        // If no order id is set, show default confirm page
        if (!$orderId = $this->client->getOrderId()) {
            return $this->respondWithSuccess(true);
        }

        // If no order is found, show default confirm page
        if (!$order = $this->orderHelper->getOrderByReference($orderId)) {
            return $this->respondWithSuccess(true);
        }

        // Show confirm page with order data
        return $this->respondWithSuccess(array(
            'oid' => $order->id,
        ));
    }

    protected function respondWithError($value)
    {
        if (version_compare(_PS_VERSION_, '1.7.0.0', '>')) {
            $this->errors[] = $this->l('Det uppstod ett problem, var vänlig försök igen eller prova ett annat betalsätt.');
            $this->redirectWithNotifications('index.php?controller=order');
        }

        $this->errors[] = Tools::displayError('Det uppstod ett problem, var vänlig försök igen eller prova ett annat betalsätt.');
        Tools::redirect('index.php?controller=order');
    }

    protected function respondWithSuccess($value)
    {
        $query = (!empty($value) && is_array($value)) ? $value : array();

        Tools::redirect(
            $this->context->link->getModuleLink('billmategateway', 'confirm', $query, true)
        );
    }
}


text:
package io.github.moosbusch.lumpi.action.spi;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.pivot.wtk.Component;
import io.github.moosbusch.lumpi.action.QuitAction;
import io.github.moosbusch.lumpi.action.spi.AbstractApplicationAction;
import io.github.moosbusch.lumpi.application.LumpiApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *
 * @author Gunnar Kappei
 */
public abstract class AbstractQuitAction extends AbstractApplicationAction implements QuitAction {
    @Autowired
    private LumpiApplicationContext appCtx;

    @Override
    public void doPerform(Component source) {
        if (canExit()) {
            try {
                appCtx.getApplication().shutdown(true);
            } catch (Exception ex) {
                Logger.getLogger(QuitAction.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}


text:
package org.burroloco.donkey.scope.included;

public interface InScope {
    String externalize();
}


text:
namespace Logs {

  export const logsModule = angular.module('hawtio-logs-logs', [])
    .config(configureLogsRoutes)
    .run(configureLogsHelp)
    .run(configureLogsMainNav)
    .filter('logDateFilter', logDateFilter)
    .filter('highlight', highlight)
    .component('logs', logsComponent)
    .component('logModal', logModalComponent)
    .service('logsService', LogsService)
    .name;

}


text:
<?php
namespace Roketi\Panel\Controller;

/*                                                                     *
 * This script belongs to the TYPO3 Flow package 'Roketi.Panel'.       *
 *                                                                     *
 *                                                                     */

use TYPO3\Flow\Annotations as Flow;

/**
 * Central log (viewer) controller
 */
class LogController extends BaseController {

	/**
	 * @var \Roketi\Panel\Domain\Repository\LogEntryRepository
	 * @Flow\Inject
	 */
	protected $logEntryRepository;

	/**
	 * Render the last log entries
	 */
	public function indexAction() {
		$this->view->assign(
			'entries',
			$this->logEntryRepository->findLatest()
		);
	}
}


text:
'use strict';

const Banana = require('banana-i18n');
const fs = require('fs');
const P = require('bluebird');
const wikiLanguage = require('../../lib/wikiLanguage');

const messagesByLocale = {};
const localizersByLocale = {};
const localeRegex = /^[a-z-]{2,7}$/i;

/**
 * i18n for PCS
 */
class Localizer {
    /**
     * Returns all of the localization strings relevant for the given locales
     *
     * @param {!Array<string>} locales list of locales
     * @return {!Promise} a promise resolving to a map from locale to a map with
     * messages for that locale by key
     */
    static getMessagesAndFallbacksForLocales(locales) {
        const props = {};
        const allLocales = new Set(locales);
        for (const locale of locales) {
            const fallbackBanana = new Banana(locale);
            const fallbackLocales = fallbackBanana.getFallbackLocales();
            for (const fallbackLocale of fallbackLocales) {
                allLocales.add(fallbackLocale);
            }
        }
        for (const locale of allLocales) {
            props[locale] = this.getMessagesForLocale(locale);
        }
        return P.props(props).then(props2 => {
            const filteredProps = {};
            for (const locale of Object.keys(props2)) {
                const value = props2[locale];
                if (!value || Object.keys(value).length === 0) {
                    continue;
                }
                filteredProps[locale] = value;
            }
            return filteredProps;
        });
    }

    /**
     * Return the localization strings for a given locale
     *
     * @param {!string} locale
     * @return {!Promise} a promise resolving to a map from
     * localization key to value for that locale. This method
     * returns an empty object instead of erroring out to allow
     * for multiple locales to be requested simultaneously without
     * one failure causing the whole request to fail.
     */
    static getMessagesForLocale(locale) {
        return new P((res) => {
            if (!locale) {
                res({});
                return;
            }
            // Check the cache first, returned cached messages if found
            if (messagesByLocale[locale]) {
                res(messagesByLocale[locale]);
                return;
            }
            // Ensure this is a language and not some other path
            if (!localeRegex.test(locale)) {
                // don't cache the empty object so we're not polluting the
                // cache with every bad key we get
                res({});
                return;
            }
            const stringsFolder = `${__dirname}/../../i18n/`;
            const stringsPath = `${stringsFolder + locale}.json`;
            fs.readFile(stringsPath, { encoding: 'utf8' }, (err, data) => {
                const bail = () => {
                    // cache the empty object so we don't keep trying to read
                    // from the filesystem for locales we don't have
                    messagesByLocale[locale] = {};
                    res({});
                };
                if (err || !data) {
                    bail();
                    return;
                }
                try {
                    const messages = JSON.parse(data);
                    messagesByLocale[locale] = messages;
                    res(messages);
                } catch (e) {
                    bail();
                }
            });
        });
    }

    /**
     * @param {!object} req request object
     * @return {!Array<string>} list of preferred locales for the request
     */
    static getLocalesFromReq(req) {
        const languageCode = wikiLanguage.getLanguageCode(req.params.domain);
        return wikiLanguage.getAllLanguageVariantsForLanguageCode(languageCode);
    }

    /**
     * @param {!object} req request object
     * @return {!Promise} promise that resolves to a localizer for that request
     */
    static promise(req) {
        return new P((res, rej) => {
            const languageCode = wikiLanguage.getLanguageCode(req.params.domain);
            let locales = [languageCode];
            if (wikiLanguage.isLanguageCodeWithVariants(languageCode)) {
                const acceptLanguage = req.headers['accept-language'];
                const relevantLocales = wikiLanguage
                    .relevantWikiLanguageCodesFromAcceptLanguageHeader(
                        acceptLanguage,
                        languageCode
                    );
                if (relevantLocales && relevantLocales.length > 0) {
                    locales = relevantLocales;
                }
            }
            const key = locales.join('|');
            if (localizersByLocale[key]) {
                res(localizersByLocale[key]);
                return;
            }
            Localizer.getMessagesAndFallbacksForLocales(locales).then(messages => {
                const banana = new Banana(locales[0], { finalFallback: 'en' });
                banana.load(messages);
                localizersByLocale[key] = banana;
                res(banana);
            }).catch(err => {
                rej(err);
            });
        });
    }
}

module.exports = Localizer;


text:
<?php

namespace Magento\Framework\Cache\Test\Unit\Backend;

class DatabaseTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager
     */
    protected $objectManager;

    public function setUp()
    {
        $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
    }

    /**
     * @param array $options
     *
     * @expectedException \Zend_Cache_Exception
     * @dataProvider initializeWithExceptionDataProvider
     */
    public function testInitializeWithException($options)
    {
        $this->objectManager->getObject(
            'Magento\Framework\Cache\Backend\Database',
            [
                'options' => $options,
            ]
        );
    }

    /**
     * @return array
     */
    public function initializeWithExceptionDataProvider()
    {
        return [
            'empty_adapter' => [
                'options' => [
                    'adapter_callback' => '',
                    'data_table' => 'data_table',
                    'data_table_callback' => 'data_table_callback',
                    'tags_table' => 'tags_table',
                    'tags_table_callback' => 'tags_table_callback',
                    'adapter' => '',
                ],
            ],
            'empty_data_table' => [
                'options' => [
                    'adapter_callback' => '',
                    'data_table' => '',
                    'data_table_callback' => '',
                    'tags_table' => 'tags_table',
                    'tags_table_callback' => 'tags_table_callback',
                    'adapter' => $this->getMock('Magento\Framework\DB\Adapter\Pdo\Mysql', [], [], '', false),
                ],
            ],
            'empty_tags_table' => [
                'options' => [
                    'adapter_callback' => '',
                    'data_table' => 'data_table',
                    'data_table_callback' => 'data_table_callback',
                    'tags_table' => '',
                    'tags_table_callback' => '',
                    'adapter' => $this->getMock('Magento\Framework\DB\Adapter\Pdo\Mysql', [], [], '', false),
                ],
            ],
        ];
    }

    /**
     * @param array $options
     * @param bool|string $expected
     *
     * @dataProvider loadDataProvider
     */
    public function testLoad($options, $expected)
    {
        /** @var \Magento\Framework\Cache\Backend\Database $database */
        $database = $this->objectManager->getObject(
            'Magento\Framework\Cache\Backend\Database',
            ['options' => $options]
        );

        $this->assertEquals($expected, $database->load(5));
        $this->assertEquals($expected, $database->load(5, true));
    }

    /**
     * @return array
     */
    public function loadDataProvider()
    {
        $connectionMock = $this->getMockBuilder('Magento\Framework\DB\Adapter\Pdo\Mysql')
            ->setMethods(['select', 'fetchOne'])
            ->disableOriginalConstructor()
            ->getMock();

        $selectMock = $this->getMock('Magento\Framework\DB\Select', ['where', 'from'], [], '', false);

        $selectMock->expects($this->any())
            ->method('where')
            ->will($this->returnSelf());

        $selectMock->expects($this->any())
            ->method('from')
            ->will($this->returnSelf());

        $connectionMock->expects($this->any())
            ->method('select')
            ->will($this->returnValue($selectMock));

        $connectionMock->expects($this->any())
            ->method('fetchOne')
            ->will($this->returnValue('loaded_value'));

        return [
            'with_store_data' => [
                'options' => $this->getOptionsWithStoreData($connectionMock),
                'expected' => 'loaded_value',

            ],
            'without_store_data' => [
                'options' => $this->getOptionsWithoutStoreData(),
                'expected' => false,
            ],
        ];
    }

    /**
     * @param \Magento\Framework\DB\Adapter\Pdo\Mysql|\PHPUnit_Framework_MockObject_MockObject $connectionMock
     * @return array
     */
    public function getOptionsWithStoreData($connectionMock)
    {
        return [
            'adapter_callback' => '',
            'data_table' => 'data_table',
            'data_table_callback' => 'data_table_callback',
            'tags_table' => 'tags_table',
            'tags_table_callback' => 'tags_table_callback',
            'store_data' => 'store_data',
            'adapter' => $connectionMock,
        ];
    }

    /**
     * @param null|\Magento\Framework\DB\Adapter\Pdo\Mysql|\PHPUnit_Framework_MockObject_MockObject $connectionMock
     * @return array
     */
    public function getOptionsWithoutStoreData($connectionMock = null)
    {
        if (null === $connectionMock) {
            $connectionMock = $this->getMockBuilder('Magento\Framework\DB\Adapter\Pdo\Mysql')
                ->disableOriginalConstructor()
                ->getMock();
        }

        return [
            'adapter_callback' => '',
            'data_table' => 'data_table',
            'data_table_callback' => 'data_table_callback',
            'tags_table' => 'tags_table',
            'tags_table_callback' => 'tags_table_callback',
            'store_data' => '',
            'adapter' => $connectionMock
        ];
    }

    /**
     * @param array $options
     * @param bool|string $expected
     *
     * @dataProvider loadDataProvider
     */
    public function testTest($options, $expected)
    {
        /** @var \Magento\Framework\Cache\Backend\Database $database */
        $database = $this->objectManager->getObject(
            'Magento\Framework\Cache\Backend\Database',
            ['options' => $options]
        );

        $this->assertEquals($expected, $database->load(5));
        $this->assertEquals($expected, $database->load(5, true));
    }

    /**
     * @param array $options
     * @param bool $expected
     *
     * @dataProvider saveDataProvider
     */
    public function testSave($options, $expected)
    {
        /** @var \Magento\Framework\Cache\Backend\Database $database */
        $database = $this->objectManager->getObject(
            'Magento\Framework\Cache\Backend\Database',
            ['options' => $options]
        );

        $this->assertEquals($expected, $database->save('data', 4));
    }

    /**
     * @return array
     */
    public function saveDataProvider()
    {
        return [
            'major_case_with_store_data' => [
                'options' => $this->getOptionsWithStoreData($this->getSaveAdapterMock(true)),
                'expected' => true,
            ],
            'minor_case_with_store_data' => [
                'options' => $this->getOptionsWithStoreData($this->getSaveAdapterMock(false)),
                'expected' => false,
            ],
            'without_store_data' => [
                'options' => $this->getOptionsWithoutStoreData(),
                'expected' => true,
            ],
        ];
    }

    /**
     * @param bool $result
     * @return \Magento\Framework\DB\Adapter\Pdo\Mysql|\PHPUnit_Framework_MockObject_MockObject
     */
    protected function getSaveAdapterMock($result)
    {
        $connectionMock = $this->getMockBuilder('Magento\Framework\DB\Adapter\Pdo\Mysql')
            ->setMethods(['quoteIdentifier', 'query'])
            ->disableOriginalConstructor()
            ->getMock();

        $dbStatementMock = $this->getMockBuilder('Zend_Db_Statement_Interface')
            ->setMethods(['rowCount'])
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();

        $dbStatementMock->expects($this->any())
            ->method('rowCount')
            ->will($this->returnValue($result));

        $connectionMock->expects($this->any())
            ->method('quoteIdentifier')
            ->will($this->returnValue('data'));

        $connectionMock->expects($this->any())
            ->method('query')
            ->will($this->returnValue($dbStatementMock));

        return $connectionMock;
    }

    /**
     * @param array $options
     * @param bool $expected
     *
     * @dataProvider removeDataProvider
     */
    public function testRemove($options, $expected)
    {
        /** @var \Magento\Framework\Cache\Backend\Database $database */
        $database = $this->objectManager->getObject(
            'Magento\Framework\Cache\Backend\Database',
            ['options' => $options]
        );

        $this->assertEquals($expected, $database->remove(3));
    }

    /**
     * @return array
     */
    public function removeDataProvider()
    {
        $connectionMock = $this->getMockBuilder('Magento\Framework\DB\Adapter\Pdo\Mysql')
            ->setMethods(['delete'])
            ->disableOriginalConstructor()
            ->getMock();

        $connectionMock->expects($this->any())
            ->method('delete')
            ->will($this->returnValue(true));

        return [
            'with_store_data' => [
                'options' => $this->getOptionsWithStoreData($connectionMock),
                'expected' => true,

            ],
            'without_store_data' => [
                'options' => $this->getOptionsWithoutStoreData(),
                'expected' => false,
            ],
        ];
    }

    /**
     * @param array $options
     * @param string $mode
     * @param bool $expected
     *
     * @dataProvider cleanDataProvider
     */
    public function testClean($options, $mode, $expected)
    {
        /** @var \Magento\Framework\Cache\Backend\Database $database */
        $database = $this->objectManager->getObject(
            'Magento\Framework\Cache\Backend\Database',
            ['options' => $options]
        );

        $this->assertEquals($expected, $database->clean($mode));
    }

    /**
     * @return array
     */
    public function cleanDataProvider()
    {
        $connectionMock = $this->getMockBuilder('Magento\Framework\DB\Adapter\Pdo\Mysql')
            ->setMethods(['query', 'delete'])
            ->disableOriginalConstructor()
            ->getMock();

        $connectionMock->expects($this->any())
            ->method('query')
            ->will($this->returnValue(false));

        $connectionMock->expects($this->any())
            ->method('delete')
            ->will($this->returnValue(true));

        return [
            'mode_all_with_store_data' => [
                'options' => $this->getOptionsWithStoreData($connectionMock),
                'mode' => \Zend_Cache::CLEANING_MODE_ALL,
                'expected' => false,

            ],
            'mode_all_without_store_data' => [
                'options' => $this->getOptionsWithoutStoreData($connectionMock),
                'mode' => \Zend_Cache::CLEANING_MODE_ALL,
                'expected' => false,
            ],
            'mode_old_with_store_data' => [
                'options' => $this->getOptionsWithStoreData($connectionMock),
                'mode' => \Zend_Cache::CLEANING_MODE_OLD,
                'expected' => true,

            ],
            'mode_old_without_store_data' => [
                'options' => $this->getOptionsWithoutStoreData($connectionMock),
                'mode' => \Zend_Cache::CLEANING_MODE_OLD,
                'expected' => true,
            ],
            'mode_matching_tag_without_store_data' => [
                'options' => $this->getOptionsWithoutStoreData($connectionMock),
                'mode' => \Zend_Cache::CLEANING_MODE_MATCHING_TAG,
                'expected' => true,
            ],
            'mode_not_matching_tag_without_store_data' => [
                'options' => $this->getOptionsWithoutStoreData($connectionMock),
                'mode' => \Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG,
                'expected' => true,
            ],
            'mode_matching_any_tag_without_store_data' => [
                'options' => $this->getOptionsWithoutStoreData($connectionMock),
                'mode' => \Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG,
                'expected' => true,
            ],
        ];
    }

    /**
     * @expectedException \Zend_Cache_Exception
     */
    public function testCleanException()
    {
        /** @var \Magento\Framework\Cache\Backend\Database $database */
        $database = $this->objectManager->getObject(
            'Magento\Framework\Cache\Backend\Database',
            ['options' => $this->getOptionsWithoutStoreData()]
        );

        $database->clean('my_unique_mode');
    }

    /**
     * @param array $options
     * @param array $expected
     *
     * @dataProvider getIdsDataProvider
     */
    public function testGetIds($options, $expected)
    {
        /** @var \Magento\Framework\Cache\Backend\Database $database */
        $database = $this->objectManager->getObject(
            'Magento\Framework\Cache\Backend\Database',
            ['options' => $options]
        );

        $this->assertEquals($expected, $database->getIds());
    }

    /**
     * @return array
     */
    public function getIdsDataProvider()
    {
        $connectionMock = $this->getMockBuilder('Magento\Framework\DB\Adapter\Pdo\Mysql')
            ->setMethods(['select', 'fetchCol'])
            ->disableOriginalConstructor()
            ->getMock();

        $selectMock = $this->getMock('Magento\Framework\DB\Select', ['from'], [], '', false);

        $selectMock->expects($this->any())
            ->method('from')
            ->will($this->returnSelf());

        $connectionMock->expects($this->any())
            ->method('select')
            ->will($this->returnValue($selectMock));

        $connectionMock->expects($this->any())
            ->method('fetchCol')
            ->will($this->returnValue(['value_one', 'value_two']));

        return [
            'with_store_data' => [
                'options' => $this->getOptionsWithStoreData($connectionMock),
                'expected' => ['value_one', 'value_two'],

            ],
            'without_store_data' => [
                'options' => $this->getOptionsWithoutStoreData(),
                'expected' => [],
            ],
        ];
    }

    public function testGetTags()
    {
        $connectionMock = $this->getMockBuilder('Magento\Framework\DB\Adapter\Pdo\Mysql')
            ->setMethods(['select', 'fetchCol'])
            ->disableOriginalConstructor()
            ->getMock();

        $selectMock = $this->getMock('Magento\Framework\DB\Select', ['from', 'distinct'], [], '', false);

        $selectMock->expects($this->any())
            ->method('from')
            ->will($this->returnSelf());

        $selectMock->expects($this->any())
            ->method('distinct')
            ->will($this->returnSelf());

        $connectionMock->expects($this->any())
            ->method('select')
            ->will($this->returnValue($selectMock));

        $connectionMock->expects($this->any())
            ->method('fetchCol')
            ->will($this->returnValue(['value_one', 'value_two']));

        /** @var \Magento\Framework\Cache\Backend\Database $database */
        $database = $this->objectManager->getObject(
            'Magento\Framework\Cache\Backend\Database',
            ['options' => $this->getOptionsWithStoreData($connectionMock)]
        );

        $this->assertEquals(['value_one', 'value_two'], $database->getIds());
    }

    public function testGetIdsMatchingTags()
    {
        $connectionMock = $this->getMockBuilder('Magento\Framework\DB\Adapter\Pdo\Mysql')
            ->setMethods(['select', 'fetchCol'])
            ->disableOriginalConstructor()
            ->getMock();

        $selectMock = $this->getMock(
            'Magento\Framework\DB\Select',
            ['from', 'distinct', 'where', 'group', 'having'],
            [],
            '',
            false
        );

        $selectMock->expects($this->any())
            ->method('from')
            ->will($this->returnSelf());

        $selectMock->expects($this->any())
            ->method('distinct')
            ->will($this->returnSelf());

        $selectMock->expects($this->any())
            ->method('where')
            ->will($this->returnSelf());

        $selectMock->expects($this->any())
            ->method('group')
            ->will($this->returnSelf());

        $selectMock->expects($this->any())
            ->method('having')
            ->will($this->returnSelf());

        $connectionMock->expects($this->any())
            ->method('select')
            ->will($this->returnValue($selectMock));

        $connectionMock->expects($this->any())
            ->method('fetchCol')
            ->will($this->returnValue(['value_one', 'value_two']));

        /** @var \Magento\Framework\Cache\Backend\Database $database */
        $database = $this->objectManager->getObject(
            'Magento\Framework\Cache\Backend\Database',
            ['options' => $this->getOptionsWithStoreData($connectionMock)]
        );

        $this->assertEquals(['value_one', 'value_two'], $database->getIdsMatchingTags());
    }

    public function testGetIdsNotMatchingTags()
    {
        $connectionMock = $this->getMockBuilder('Magento\Framework\DB\Adapter\Pdo\Mysql')
            ->setMethods(['select', 'fetchCol'])
            ->disableOriginalConstructor()
            ->getMock();

        $selectMock = $this->getMock(
            'Magento\Framework\DB\Select',
            ['from', 'distinct', 'where', 'group', 'having'],
            [],
            '',
            false
        );

        $selectMock->expects($this->any())
            ->method('from')
            ->will($this->returnSelf());

        $selectMock->expects($this->any())
            ->method('distinct')
            ->will($this->returnSelf());

        $selectMock->expects($this->any())
            ->method('where')
            ->will($this->returnSelf());

        $selectMock->expects($this->any())
            ->method('group')
            ->will($this->returnSelf());

        $selectMock->expects($this->any())
            ->method('having')
            ->will($this->returnSelf());

        $connectionMock->expects($this->any())
            ->method('select')
            ->will($this->returnValue($selectMock));

        $connectionMock->expects($this->at(1))
            ->method('fetchCol')
            ->will($this->returnValue(['some_value_one']));

        $connectionMock->expects($this->at(3))
            ->method('fetchCol')
            ->will($this->returnValue(['some_value_two']));

        /** @var \Magento\Framework\Cache\Backend\Database $database */
        $database = $this->objectManager->getObject(
            'Magento\Framework\Cache\Backend\Database',
            ['options' => $this->getOptionsWithStoreData($connectionMock)]
        );

        $this->assertEquals(['some_value_one'], $database->getIdsNotMatchingTags());
    }

    public function testGetIdsMatchingAnyTags()
    {
        $connectionMock = $this->getMockBuilder('Magento\Framework\DB\Adapter\Pdo\Mysql')
            ->setMethods(['select', 'fetchCol'])
            ->disableOriginalConstructor()
            ->getMock();

        $selectMock = $this->getMock('Magento\Framework\DB\Select', ['from', 'distinct'], [], '', false);

        $selectMock->expects($this->any())
            ->method('from')
            ->will($this->returnSelf());

        $selectMock->expects($this->any())
            ->method('distinct')
            ->will($this->returnSelf());

        $connectionMock->expects($this->any())
            ->method('select')
            ->will($this->returnValue($selectMock));

        $connectionMock->expects($this->any())
            ->method('fetchCol')
            ->will($this->returnValue(['some_value_one', 'some_value_two']));

        /** @var \Magento\Framework\Cache\Backend\Database $database */
        $database = $this->objectManager->getObject(
            'Magento\Framework\Cache\Backend\Database',
            ['options' => $this->getOptionsWithStoreData($connectionMock)]
        );

        $this->assertEquals(['some_value_one', 'some_value_two'], $database->getIds());
    }

    public function testGetMetadatas()
    {
        $connectionMock = $this->getMockBuilder('Magento\Framework\DB\Adapter\Pdo\Mysql')
            ->setMethods(['select', 'fetchCol', 'fetchRow'])
            ->disableOriginalConstructor()
            ->getMock();

        $selectMock = $this->getMock('Magento\Framework\DB\Select', ['from', 'where'], [], '', false);

        $selectMock->expects($this->any())
            ->method('from')
            ->will($this->returnSelf());

        $selectMock->expects($this->any())
            ->method('where')
            ->will($this->returnSelf());

        $connectionMock->expects($this->any())
            ->method('select')
            ->will($this->returnValue($selectMock));

        $connectionMock->expects($this->any())
            ->method('fetchCol')
            ->will($this->returnValue(['some_value_one', 'some_value_two']));

        $connectionMock->expects($this->any())
            ->method('fetchRow')
            ->will($this->returnValue(['expire_time' => '3', 'update_time' => 2]));

        /** @var \Magento\Framework\Cache\Backend\Database $database */
        $database = $this->objectManager->getObject(
            'Magento\Framework\Cache\Backend\Database',
            ['options' => $this->getOptionsWithStoreData($connectionMock)]
        );

        $this->assertEquals(
            [
               'expire' => 3,
                'mtime' => 2,
                'tags' => ['some_value_one', 'some_value_two'],
            ],
            $database->getMetadatas(5)
        );
    }

    /**
     * @param array $options
     * @param bool $expected
     *
     * @dataProvider touchDataProvider
     */
    public function testTouch($options, $expected)
    {
        /** @var \Magento\Framework\Cache\Backend\Database $database */
        $database = $this->objectManager->getObject(
            'Magento\Framework\Cache\Backend\Database',
            ['options' => $options]
        );

        $this->assertEquals($expected, $database->touch(2, 100));
    }

    /**
     * @return array
     */
    public function touchDataProvider()
    {
        $connectionMock = $this->getMockBuilder('Magento\Framework\DB\Adapter\Pdo\Mysql')
            ->setMethods(['update'])
            ->disableOriginalConstructor()
            ->getMock();

        $connectionMock->expects($this->any())
            ->method('update')
            ->will($this->returnValue(false));

        return [
            'with_store_data' => [
                'options' => $this->getOptionsWithStoreData($connectionMock),
                'expected' => false,

            ],
            'without_store_data' => [
                'options' => $this->getOptionsWithoutStoreData(),
                'expected' => true,
            ],
        ];
    }
}


text:
import {
    API
} from '../../constants/api';

//Utils
import {
    apiFetch
} from '../../../lib/utils/api';

class SearchApi {
    static getPagesOcurrency(query) {
        return apiFetch(API.Search.Sitios, {}, query);
    };

}

export default SearchApi;


text:
/**
 * This fuzz target attempts to decompress the fuzzed data with the simple
 * decompression function to ensure the decompressor never crashes.
 */

#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "fuzz_helpers.h"
#include "lz4.h"

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{

    uint32_t seed = FUZZ_seed(&data, &size);
    size_t const dstCapacity = FUZZ_rand32(&seed, 0, 4 * size);
    size_t const smallDictSize = size + 1;
    size_t const largeDictSize = 64 * 1024 - 1;
    size_t const dictSize = MAX(smallDictSize, largeDictSize);
    char* const dst = (char*)malloc(dstCapacity);
    char* const dict = (char*)malloc(dictSize + size);
    char* const largeDict = dict;
    char* const dataAfterDict = dict + dictSize;
    char* const smallDict = dataAfterDict - smallDictSize;

    FUZZ_ASSERT(dst);
    FUZZ_ASSERT(dict);

    /* Prepare the dictionary. The data doesn't matter for decompression. */
    memset(dict, 0, dictSize);
    memcpy(dataAfterDict, data, size);

    /* Decompress using each possible dictionary configuration. */
    /* No dictionary. */
    LZ4_decompress_safe_usingDict((char const*)data, dst, size,
                                  dstCapacity, NULL, 0);
    /* Small external dictonary. */
    LZ4_decompress_safe_usingDict((char const*)data, dst, size,
                                  dstCapacity, smallDict, smallDictSize);
    /* Large external dictionary. */
    LZ4_decompress_safe_usingDict((char const*)data, dst, size,
                                  dstCapacity, largeDict, largeDictSize);
    /* Small prefix. */
    LZ4_decompress_safe_usingDict((char const*)dataAfterDict, dst, size,
                                  dstCapacity, smallDict, smallDictSize);
    /* Large prefix. */
    LZ4_decompress_safe_usingDict((char const*)data, dst, size,
                                  dstCapacity, largeDict, largeDictSize);
    /* Partial decompression. */
    LZ4_decompress_safe_partial((char const*)data, dst, size,
                                dstCapacity, dstCapacity);
    free(dst);
    free(dict);

    return 0;
}


text:
.customboard {
    overflow-y: hidden;
}